diff --git a/software/.gitignore b/software/.gitignore
index 35578c5..58b1042 100644
--- a/software/.gitignore
+++ b/software/.gitignore
@@ -2,3 +2,4 @@ ENV
*.pyc
__pycache__
.pytest_cache
+OpenBookScannerApp_
diff --git a/software/OpenBookScannerApp/.gitignore b/software/OpenBookScannerApp/.gitignore
new file mode 100644
index 0000000..4201aac
--- /dev/null
+++ b/software/OpenBookScannerApp/.gitignore
@@ -0,0 +1,78 @@
+*.iml
+.gradle
+/local.properties
+/.idea/workspace.xml
+/.idea/libraries
+/.idea/caches
+.DS_Store
+/build
+/captures
+.externalNativeBuild
+
+# from https://github.com/github/gitignore/blob/master/Android.gitignore
+
+# Built application files
+*.apk
+*.ap_
+
+# Files for the ART/Dalvik VM
+*.dex
+
+# Java class files
+*.class
+
+# Generated files
+bin/
+gen/
+out/
+
+# Gradle files
+.gradle/
+build/
+
+# Local configuration file (sdk path, etc)
+local.properties
+
+# Proguard folder generated by Eclipse
+proguard/
+
+# Log Files
+*.log
+
+# Android Studio Navigation editor temp files
+.navigation/
+
+# Android Studio captures folder
+captures/
+
+# IntelliJ
+*.iml
+.idea/workspace.xml
+.idea/tasks.xml
+.idea/gradle.xml
+.idea/assetWizardSettings.xml
+.idea/dictionaries
+.idea/libraries
+.idea/caches
+
+# Keystore files
+# Uncomment the following line if you do not want to check your keystore files in.
+#*.jks
+
+# External native build folder generated in Android Studio 2.2 and later
+.externalNativeBuild
+
+# Google Services (e.g. APIs or Firebase)
+google-services.json
+
+# Freeline
+freeline.py
+freeline/
+freeline_project_description.json
+
+# fastlane
+fastlane/report.xml
+fastlane/Preview.html
+fastlane/screenshots
+fastlane/test_output
+fastlane/readme.md
diff --git a/software/OpenBookScannerApp/.idea/codeStyles/Project.xml b/software/OpenBookScannerApp/.idea/codeStyles/Project.xml
new file mode 100644
index 0000000..30aa626
--- /dev/null
+++ b/software/OpenBookScannerApp/.idea/codeStyles/Project.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/.idea/gradle.xml b/software/OpenBookScannerApp/.idea/gradle.xml
new file mode 100644
index 0000000..7ac24c7
--- /dev/null
+++ b/software/OpenBookScannerApp/.idea/gradle.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/.idea/misc.xml b/software/OpenBookScannerApp/.idea/misc.xml
new file mode 100644
index 0000000..99202cc
--- /dev/null
+++ b/software/OpenBookScannerApp/.idea/misc.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/.idea/modules.xml b/software/OpenBookScannerApp/.idea/modules.xml
new file mode 100644
index 0000000..f852883
--- /dev/null
+++ b/software/OpenBookScannerApp/.idea/modules.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/.idea/runConfigurations.xml b/software/OpenBookScannerApp/.idea/runConfigurations.xml
new file mode 100644
index 0000000..7f68460
--- /dev/null
+++ b/software/OpenBookScannerApp/.idea/runConfigurations.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/.idea/vcs.xml b/software/OpenBookScannerApp/.idea/vcs.xml
new file mode 100644
index 0000000..b2bdec2
--- /dev/null
+++ b/software/OpenBookScannerApp/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/README.md b/software/OpenBookScannerApp/README.md
new file mode 100644
index 0000000..cc79dbb
--- /dev/null
+++ b/software/OpenBookScannerApp/README.md
@@ -0,0 +1,55 @@
+# OpenBookScannerApp
+
+This Android App takes the pictures and registers as a scanner.
+You can develop this app with Android Studio 3.1.3.
+This app is compatible with old phones until Android 2.3.
+
+## API
+
+The OpenBookScannerApp requires this API endpoint:
+
+- `POST /scanner` with data
+ Headers:
+ - `Content-Type: application/json`
+ ```
+ {
+ "type": "scanner",
+ "name": "",
+ "id": "random id for this run of the app"
+ }
+ ```
+ The attributes have the following meaning:
+ - `type` is `"scanner"` because this is what the app is going to do.
+ - `name` is the name of the device which should be displayed.
+ - `id` is the id of the scanner as there might be multiple devices of the same name.
+ This results in `200`.
+ Headers:
+ - `Content-Type: application/json`
+ - if no picture shall be taken:
+ ```
+ {
+ "status": "ok",
+ "refresh": 0.5
+ }
+ ```
+ - if a picture shall be taken:
+ ```
+ {
+ "status": "ok",
+ "refresh": SECONDS,
+ "picture": ""
+ ```
+ These are the values explained:
+ - `status` should be `"ok"`. Otherwise, there was an error.
+ - `refresh` is the seconds as float
+ when to re-post to keep the scanner active.
+ - `picture` is the full url including `http://hostname:port/path` where
+ to post the picture once taken.
+ Method: `POST`
+ Headers:
+ - `Content-Type: image/jpeg`
+
+## Thanks
+
+- Big thanks to [isnotmenow](https://github.com/isnotmenow/AndroidProjectForAPI9)
+ for the [APIv9 app](https://github.com/isnotmenow/AndroidProjectForAPI9).
diff --git a/software/OpenBookScannerApp/app/.gitignore b/software/OpenBookScannerApp/app/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/software/OpenBookScannerApp/app/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/software/OpenBookScannerApp/app/build.gradle b/software/OpenBookScannerApp/app/build.gradle
new file mode 100644
index 0000000..f61d4bb
--- /dev/null
+++ b/software/OpenBookScannerApp/app/build.gradle
@@ -0,0 +1,33 @@
+apply plugin: 'com.android.application'
+
+android {
+ compileSdkVersion 25
+ defaultConfig {
+ applicationId "com.github.fablabcb.openbookscannerapp"
+ minSdkVersion 9
+ targetSdkVersion 25
+ versionCode 1
+ versionName "1.0"
+ testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+}
+
+dependencies {
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
+ implementation 'com.android.support:support-v4:25.4.0'
+ implementation 'com.android.support:appcompat-v7:25.4.0'
+ implementation 'com.android.support.constraint:constraint-layout:1.0.2'
+ // implementation 'com.parse:parse-android:1.17.3' // http://docs.parseplatform.org/android/guide/ needs version 14+
+ testImplementation 'junit:junit:4.12'
+
+ // this is the last support test for api >= 9
+ androidTestImplementation 'com.android.support.test:runner:1.0.0'
+ androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.0'
+ implementation 'com.android.support:design:25.4.0'
+}
diff --git a/software/OpenBookScannerApp/app/proguard-rules.pro b/software/OpenBookScannerApp/app/proguard-rules.pro
new file mode 100644
index 0000000..f1b4245
--- /dev/null
+++ b/software/OpenBookScannerApp/app/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile
diff --git a/software/OpenBookScannerApp/app/src/androidTest/java/com/github/fablabcb/openbookscannerapp/ExampleInstrumentedTest.java b/software/OpenBookScannerApp/app/src/androidTest/java/com/github/fablabcb/openbookscannerapp/ExampleInstrumentedTest.java
new file mode 100644
index 0000000..81f399a
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/androidTest/java/com/github/fablabcb/openbookscannerapp/ExampleInstrumentedTest.java
@@ -0,0 +1,26 @@
+package com.github.fablabcb.openbookscannerapp;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+
+/**
+ * Instrumented test, which will execute on an Android device.
+ *
+ * @see Testing documentation
+ */
+@RunWith(AndroidJUnit4.class)
+public class ExampleInstrumentedTest {
+ @Test
+ public void useAppContext() {
+ // Context of the app under test.
+ Context appContext = InstrumentationRegistry.getTargetContext();
+
+ assertEquals("com.github.fablabcb.openbookscannerapp", appContext.getPackageName());
+ }
+}
diff --git a/software/OpenBookScannerApp/app/src/main/AndroidManifest.xml b/software/OpenBookScannerApp/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..3351fa1
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/AndroidManifest.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/app/src/main/java/com/github/fablabcb/openbookscannerapp/MainActivity.java b/software/OpenBookScannerApp/app/src/main/java/com/github/fablabcb/openbookscannerapp/MainActivity.java
new file mode 100644
index 0000000..647a2e1
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/java/com/github/fablabcb/openbookscannerapp/MainActivity.java
@@ -0,0 +1,287 @@
+package com.github.fablabcb.openbookscannerapp;
+
+import android.Manifest;
+import android.content.pm.PackageManager;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.hardware.Camera;
+import android.hardware.Camera.CameraInfo;
+import android.os.Build;
+import android.os.Bundle;
+import android.support.v4.app.ActivityCompat;
+import android.support.v7.app.AppCompatActivity;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.ProtocolException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.UUID;
+
+
+public class MainActivity extends AppCompatActivity {
+
+ private final static String DEBUG_TAG = "MainActivity";
+ private final static int DEFAULT_PORT = 8001;
+
+ private ImageView imageView;
+ private TextView statusText;
+ private Button button;
+ private boolean cameraIsAvailable;
+ private boolean hasCameraFeature;
+ private boolean cameraIsDisabled;
+ private Camera camera;
+ private EditText addressIP;
+ private EditText addressPort;
+ private TextView serverStatus;
+ private UUID app_id;
+
+
+
+ protected void setAttributesOnCreate() {
+ setContentView(R.layout.activity_main);
+ imageView = (ImageView) findViewById(R.id.imageView);
+ statusText = (TextView) findViewById(R.id.statusText);
+ button = (Button) findViewById(R.id.takePictureButton);
+ PackageManager pm = getApplicationContext().getPackageManager();
+ addressIP = (EditText) findViewById(R.id.addressIP);
+ addressPort = (EditText) findViewById(R.id.addressPort);
+ serverStatus = (TextView) findViewById(R.id.serverStatus);
+ hasCameraFeature = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
+ // from https://stackoverflow.com/questions/2982748/create-a-guid-in-java#2982751
+ app_id = java.util.UUID.randomUUID();;
+ }
+
+ private int findFrontFacingCamera() {
+ // Search for the front facing camera
+ // from http://www.vogella.com/tutorials/AndroidCamera/article.html
+ int numberOfCameras = Camera.getNumberOfCameras();
+ for (int cameraId = 0; cameraId < numberOfCameras; cameraId++) {
+ CameraInfo info = new CameraInfo();
+ Camera.getCameraInfo(cameraId, info);
+ if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
+ Log.d(DEBUG_TAG, "Camera found");
+ return cameraId;
+ }
+ }
+ return -1;
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ Log.d(DEBUG_TAG, "onCreate");
+ setAttributesOnCreate();
+
+
+
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ tryToTakeAPicture();
+ }
+ });
+ }
+
+ private void tryToTakeAPicture() {
+ if (cameraIsAvailable) {
+ setCameraParameters();
+ camera.startPreview();
+ camera.takePicture(null, null,
+ new Camera.PictureCallback() {
+ @Override
+ public void onPictureTaken(byte[] data, Camera camera) {
+ Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
+ imageView.setImageBitmap(bm);
+ camera.stopPreview();
+ }
+ });
+ }
+ notifyServer();
+ }
+
+ protected void setCameraParameters() {
+ // https://developer.android.com/reference/android/hardware/Camera.Parameters
+ // setJpegQuality(int quality)
+ // setPictureSize(int width, int height)
+ // getSupportedPictureSizes()
+ Camera.Parameters params = camera.getParameters();
+ Camera.Size maxSize = params.getSupportedPictureSizes().get(0);
+ for (Camera.Size size : params.getSupportedPictureSizes()) {
+ if (size.width >= maxSize.width && size.height > maxSize.height) {
+ maxSize = size;
+ }
+ }
+ params.setPictureSize(maxSize.width, maxSize.height);
+ Log.d(DEBUG_TAG, "Camera resolution: " + maxSize.width + "x" + maxSize.height + "px");
+ params.setJpegQuality(100); // no compression
+ camera.setParameters(params);
+ }
+
+ @Override
+ protected void onPause() {
+ // from http://www.vogella.com/tutorials/AndroidCamera/article.html
+ // see also https://developer.android.com/reference/android/hardware/Camera (10)
+ if (cameraIsAvailable) {
+ camera.release();
+ camera = null;
+ }
+ super.onPause();
+ }
+
+ @Override
+ protected void onResume() {
+ // from https://developer.android.com/reference/android/hardware/Camera (10)
+
+ openCamera();
+ statusText.setText(cameraIsAvailable ? R.string.camera_status_available :
+ cameraIsDisabled ? R.string.camera_status_disabled :
+ !hasCameraFeature ? R.string.camera_status_no_feature : R.string.TODO);
+ super.onResume();
+ }
+
+ private void openCamera() {
+ if (hasCameraFeature) {
+ int cameraId = findFrontFacingCamera();
+ try {
+ camera = Camera.open(cameraId);
+ cameraIsDisabled = false;
+ } catch (RuntimeException e) {
+ // this occurs if no permissions are given, see thedocumentation of Camera.open.
+ cameraIsDisabled = true;
+ }
+ }
+ cameraIsAvailable = hasCameraFeature && !cameraIsDisabled;
+ if (cameraIsDisabled) {
+ // from https://androidkennel.org/android-camera-access-tutorial/
+ // imageView.setImageResource(); // TODO: change picture
+ ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 0);
+ }
+ }
+
+ public int getPort() {
+ // from https://stackoverflow.com/a/25804635/1320237
+ try {
+ return Integer.parseInt(addressPort.getText().toString());
+ } catch (NumberFormatException e) {
+ return DEFAULT_PORT;
+ }
+ }
+
+ public String getHostname() {
+ return addressIP.getText().toString();
+ }
+
+ public URL getServerUrl() throws MalformedURLException {
+ return new URL("http", getHostname(), getPort(), "/scanner");
+ }
+
+ protected void notifyServer() {
+ URL url;
+ setServerStatus(R.string.server_status_starting_request);
+ try {
+ url = getServerUrl();
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ setServerStatus(R.string.server_status_malformed_url);
+ return;
+ }
+ Log.d(DEBUG_TAG, "URL: " + url.toString());
+ // see https://www.wikihow.com/Execute-HTTP-POST-Requests-in-Android
+ HttpURLConnection client;
+ try {
+ client = (HttpURLConnection) url.openConnection();
+ } catch (IOException e) {
+ setServerStatus(R.string.server_status_connection_error);
+ e.printStackTrace();
+ return;
+ }
+ try {
+ client.setRequestMethod("POST");
+ } catch (ProtocolException e) {
+ setServerStatus(R.string.server_status_protocol_exception);
+ e.printStackTrace();
+ return;
+ }
+ // from https://stackoverflow.com/a/34555324/1320237
+ client.addRequestProperty("Accept", "application/json");
+ client.addRequestProperty("Content-Type", "application/json");
+ client.setDoOutput(true);
+ client.setChunkedStreamingMode(0);
+ // write data to the server
+ DataOutputStream os;
+ // from https://stackoverflow.com/q/42767249/1320237
+ JSONObject notification = new JSONObject();
+ try {
+ notification.put("type", "scanner");
+ notification.put("name", getDeviceName());
+ notification.put("id", app_id.toString());
+ } catch (JSONException e) {
+ setServerStatus(R.string.server_status_create_notification_exception);
+ e.printStackTrace();
+ return;
+ }
+ try {
+ os = new DataOutputStream(client.getOutputStream());
+ os.writeBytes(notification.toString());
+ os.flush();
+ os.close();
+ } catch (IOException e) {
+ setServerStatus(R.string.server_status_send_notification_exception);
+ e.printStackTrace();
+ return;
+ }
+ Log.d(DEBUG_TAG, "POST request sent.");
+ try {
+ Log.i("STATUS", String.valueOf(client.getResponseCode()));
+ Log.i("MSG" , client.getResponseMessage());
+ } catch (IOException e) {
+ setServerStatus(R.string.server_status_get_server_response_error);
+ e.printStackTrace();
+ return;
+ }
+ setServerStatus(R.string.server_status_get_server_response);
+
+ }
+
+ private void setServerStatus(int resourceId) {
+ serverStatus.setText(resourceId);
+ }
+
+ public String getDeviceName() {
+ // from https://stackoverflow.com/a/12707479/1320237
+ String manufacturer = Build.MANUFACTURER;
+ String model = Build.MODEL;
+ if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) {
+ return capitalize(model);
+ } else {
+ return capitalize(manufacturer) + " " + model;
+ }
+ }
+
+
+ private String capitalize(String s) {
+ // form https://stackoverflow.com/a/12707479/1320237
+ if (s == null || s.length() == 0) {
+ return "";
+ }
+ char first = s.charAt(0);
+ if (Character.isUpperCase(first)) {
+ return s;
+ } else {
+ return Character.toUpperCase(first) + s.substring(1);
+ }
+ }
+
+}
diff --git a/software/OpenBookScannerApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/software/OpenBookScannerApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
new file mode 100644
index 0000000..7daee77
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/res/drawable-v24/ic_launcher_foreground.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/software/OpenBookScannerApp/app/src/main/res/drawable/ic_launcher_background.xml b/software/OpenBookScannerApp/app/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..4ea54ca
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,171 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/software/OpenBookScannerApp/app/src/main/res/layout/activity_main.xml b/software/OpenBookScannerApp/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 0000000..2925aab
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,109 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-hdpi/ic_launcher.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..a2f5908
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..1b52399
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-mdpi/ic_launcher.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..ff10afd
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..115a4c7
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..dcd3cd8
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..459ca60
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..8ca12fe
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..8e19b41
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..b824ebd
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..4c19a13
Binary files /dev/null and b/software/OpenBookScannerApp/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/software/OpenBookScannerApp/app/src/main/res/values/colors.xml b/software/OpenBookScannerApp/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..5a077b3
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+
+
+ #3F51B5
+ #303F9F
+ #FF4081
+
diff --git a/software/OpenBookScannerApp/app/src/main/res/values/strings.xml b/software/OpenBookScannerApp/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..9e94796
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/res/values/strings.xml
@@ -0,0 +1,23 @@
+
+ OpenBookScanner
+ Loading ...
+ Connect to Server
+ 192.168.0.109
+ port
+ IP Address
+ Connected
+ No Server
+ Snap!
+ Cannot connect: Invalid URL
+ Cannot connect: no address for server
+ Cannot Connect: Protocol Exception: POST not supported
+ Connection Error: Could not notify the server avout this app.
+ Connection Error: Cannot create the notification.
+ Connection Error: Could not read a response from the server.
+ A camera is available.
+ Camera use is disabled for this app: no permission.
+ This app has no camera feature.
+ TODO
+ Notifying the server.
+ The server returned a valid response.
+
diff --git a/software/OpenBookScannerApp/app/src/main/res/values/styles.xml b/software/OpenBookScannerApp/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..705be27
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/main/res/values/styles.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
diff --git a/software/OpenBookScannerApp/app/src/test/java/com/github/fablabcb/openbookscannerapp/ExampleUnitTest.java b/software/OpenBookScannerApp/app/src/test/java/com/github/fablabcb/openbookscannerapp/ExampleUnitTest.java
new file mode 100644
index 0000000..e495365
--- /dev/null
+++ b/software/OpenBookScannerApp/app/src/test/java/com/github/fablabcb/openbookscannerapp/ExampleUnitTest.java
@@ -0,0 +1,17 @@
+package com.github.fablabcb.openbookscannerapp;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * @see Testing documentation
+ */
+public class ExampleUnitTest {
+ @Test
+ public void addition_isCorrect() {
+ assertEquals(4, 2 + 2);
+ }
+}
\ No newline at end of file
diff --git a/software/OpenBookScannerApp/build.gradle b/software/OpenBookScannerApp/build.gradle
new file mode 100644
index 0000000..43c0708
--- /dev/null
+++ b/software/OpenBookScannerApp/build.gradle
@@ -0,0 +1,27 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+
+ repositories {
+ google()
+ jcenter()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:3.1.3'
+
+
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ jcenter()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
diff --git a/software/OpenBookScannerApp/gradle.properties b/software/OpenBookScannerApp/gradle.properties
new file mode 100644
index 0000000..aac7c9b
--- /dev/null
+++ b/software/OpenBookScannerApp/gradle.properties
@@ -0,0 +1,17 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx1536m
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
diff --git a/software/OpenBookScannerApp/gradle/wrapper/gradle-wrapper.jar b/software/OpenBookScannerApp/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..13372ae
Binary files /dev/null and b/software/OpenBookScannerApp/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/software/OpenBookScannerApp/gradle/wrapper/gradle-wrapper.properties b/software/OpenBookScannerApp/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..18db810
--- /dev/null
+++ b/software/OpenBookScannerApp/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Fri Jun 22 02:55:36 CEST 2018
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
diff --git a/software/OpenBookScannerApp/gradlew b/software/OpenBookScannerApp/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/software/OpenBookScannerApp/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/software/OpenBookScannerApp/gradlew.bat b/software/OpenBookScannerApp/gradlew.bat
new file mode 100644
index 0000000..aec9973
--- /dev/null
+++ b/software/OpenBookScannerApp/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/software/OpenBookScannerApp/settings.gradle b/software/OpenBookScannerApp/settings.gradle
new file mode 100644
index 0000000..e7b4def
--- /dev/null
+++ b/software/OpenBookScannerApp/settings.gradle
@@ -0,0 +1 @@
+include ':app'
diff --git a/software/openbookscanner/file_server.py b/software/openbookscanner/file_server.py
index c521ec7..65f542f 100644
--- a/software/openbookscanner/file_server.py
+++ b/software/openbookscanner/file_server.py
@@ -1,6 +1,6 @@
"""Serve the files over the web server."""
from .message import MessageDispatcher
-from flask import Flask, abort
+from flask import abort
from weakref import WeakValueDictionary
import threading
@@ -30,12 +30,12 @@ class FileServer(MessageDispatcher):
FILE_CONTENT = "/file/"
- def __init__(self, port=8001):
+ def __init__(self, flask_server):
"""Create a new file server."""
- self.app = Flask(self.__class__.__name__)
+ super().__init__()
self.files = WeakValueDictionary()
- self.app.route(self.FILE_CONTENT + "")(self.serve_file_content_by_id)
- self.port = port
+ self.flask_server = flask_server
+ self.flask_server.route(self.FILE_CONTENT + "")(self.serve_file_content_by_id)
def serve_file_content_by_id(self, id):
"""Serve a file by an id."""
@@ -57,16 +57,7 @@ def get_file_content_path(self, file):
return self.FILE_CONTENT + str(file.get_id())
def get_port(self):
- """Return the port used to serve the files."""
- return self.port
-
- def run(self):
- """Run the server."""
- self.app.run(host="0.0.0.0", port=self.port)
-
- def run_in_parallel(self):
- """Run the server in parellel."""
- thread = threading.Thread(target=self.run, daemon=True)
- thread.start()
+ """Return the server port."""
+ return self.flask_server.get_port()
diff --git a/software/openbookscanner/flask_server.py b/software/openbookscanner/flask_server.py
new file mode 100644
index 0000000..09e590a
--- /dev/null
+++ b/software/openbookscanner/flask_server.py
@@ -0,0 +1,76 @@
+"""A server to run and configure flask.
+
+"""
+from flask import Flask, request
+from urllib.request import urlopen
+from functools import wraps
+import traceback
+
+class FlaskServer:
+ """A flask server."""
+
+ def __init__(self, port=8001):
+ """Create a new file server."""
+ self.port = port
+ self._app = Flask(self.__class__.__name__)
+
+ def route(self, *args, **kw):
+ """Create a route on the flask app."""
+ add_to_route = self._app.route(*args, **kw)
+ @wraps(add_to_route)
+ def wrap(func):
+ @wraps(func)
+ def error_printing_func(*args, **kw):
+ """Let us know if there is an error even if we are not in production."""
+ try:
+ return func(*args, **kw)
+ except:
+ traceback.print_exc()
+ raise
+ return add_to_route(error_printing_func)
+ return wrap
+
+ def run(self, **kw):
+ """Run the server."""
+ self._app.run(host="0.0.0.0", port=self.port, **kw)
+
+ def is_running(self):
+ """Return whether the server is running."""
+ return True # TODO: use a more robust algorithm
+
+ def get_port(self):
+ """Return the port used to serve the files."""
+ return self.port
+
+ def shutdown(self):
+ """Shutdown the server."""
+ self.route("/shutdown")(self._route_shutdown_server)
+ urlopen(self.get_url("/shutdown"))
+
+ def get_url(self, path="/"):
+ return "http://localhost:{}{}".format(self.get_port(), path)
+
+ def _route_shutdown_server(self):
+ """Perform the shutdown."""
+ # from https://stackoverflow.com/a/23575591
+ func = request.environ.get('werkzeug.server.shutdown')
+ if func is None:
+ raise RuntimeError('Not running with the Werkzeug Server')
+ func()
+ return "Server is shutting down ..."
+
+
+
+
+if __name__ == "__main__":
+ server = FlaskServer()
+ from threading import Thread
+ import time
+ def shutdown_after():
+ time.sleep(2)
+ server.shutdown()
+ thread = Thread(target=shutdown_after)
+ thread.start()
+ print("Closing the server after some time...")
+ server.run()
+
diff --git a/software/openbookscanner/model.py b/software/openbookscanner/model.py
index 79961fc..57ec969 100644
--- a/software/openbookscanner/model.py
+++ b/software/openbookscanner/model.py
@@ -10,6 +10,9 @@
from .message import message
from .storage import UserDefinedStorageLocation
from .conversion import Converter
+from .flask_server import FlaskServer
+from threading import Thread
+from urllib.error import URLError
PUBLIC_MODEL_CLASS_NAME = "OpenBookScanner"
@@ -28,7 +31,10 @@ def __init__(self):
status(StatusStateMachine) --message--> public_message_buffer(BufferingBroker) --message---
---> public_message_broker(ParseBroker) --"""
- self.create_communication_channels()
+ try:
+ self.create_communication_channels()
+ except URLError as e:
+ raise URLError("Please make sure that the parse server is started.")
self.create_model()
def create_communication_channels(self):
@@ -59,14 +65,15 @@ def create_model(self):
self.converter = Converter()
self.internal_messages.subscribe(self.converter)
self.converter.subscribe(self.internal_messages)
+ # server
+ self.flask_server = FlaskServer()
# storage
- self.storage_location = UserDefinedStorageLocation()
+ self.storage_location = UserDefinedStorageLocation(self.flask_server)
self.parse_storage_location = ParseUpdater(self.storage_location, self.update_strategy)
self.storage_location.register_state_observer(self.parse_storage_location)
self.incoming_messages.subscribe(self.storage_location)
self.internal_messages.subscribe(self.storage_location)
self.storage_location.subscribe(self.internal_messages)
- self.storage_location.run_in_parallel()
self.relate_to("storage", self.parse_storage_location)
def relate_to(self, relation, updater):
@@ -103,11 +110,24 @@ def public_state_machine(self, relation, state_machine):
self.relate_to(relation, updater)
return state_machine
+ def run_server(self):
+ """Run the server"""
+ self.flask_server.run()
+
+ def run_update_loop(self):
+ """Run the update in a loop."""
+ try:
+ while 1:
+ self.update()
+ time.sleep(0.5)
+ finally:
+ self.flask_server.shutdown()
+
def run(self):
- """Run the update in a loop."""
- while 1:
- self.update()
- time.sleep(0.5)
+ """"Run all components."""
+ thread = Thread(target=self.run_update_loop, daemon=True)
+ thread.start()
+ self.run_server()
def update(self):
"""Update the book scanner, send and receive messages."""
diff --git a/software/openbookscanner/states/hardware_listener.py b/software/openbookscanner/states/hardware_listener.py
index f444d3c..ab51306 100644
--- a/software/openbookscanner/states/hardware_listener.py
+++ b/software/openbookscanner/states/hardware_listener.py
@@ -3,6 +3,7 @@
"""
from .state import StateMachine, PollingState, State, TransitionOnReceivedMessage
+import time
class Checks:
@@ -161,3 +162,12 @@ def update_hardware(self):
for hardware in self.get_hardware():
hardware.update()
+ def run_update_loop(self, seconds_between_updates=0.5):
+ """Run the update messages in a loop.
+
+ Also update all the detected hardware state machines.
+ """
+ while 1:
+ self.update()
+ self.update_hardware()
+ time.sleep(seconds_between_updates)
diff --git a/software/openbookscanner/states/scanner_app.py b/software/openbookscanner/states/scanner_app.py
new file mode 100644
index 0000000..6f2888f
--- /dev/null
+++ b/software/openbookscanner/states/scanner_app.py
@@ -0,0 +1,175 @@
+"""This module waits for scanner apps to appear.
+
+"""
+
+
+from .hardware_listener import HardwareListener
+from .state import StateMachine, State
+from flask import request
+import json
+import time
+from urllib.parse import quote
+
+
+class ScannerAppStateMixin:
+ """Functionality for all scanner app states."""
+
+ def can_scan(self):
+ """Whether the app is able to scan right now."""
+ return False
+
+ def is_connected(self):
+ """Whether the app is connected."""
+ return True
+
+ def wants_to_scan(self):
+ """Whether a scan is requested."""
+ return False
+
+ def toJSON(self):
+ """Return a JSON representation of the state."""
+ data = super().toJSON()
+ data["can_scan"] = self.can_scan()
+ data["is_connected"] = self.is_connected()
+ data["wants_to_scan"] = self.wants_to_scan()
+ return data
+
+ @property
+ def app(self):
+ """Same as self.state_machine."""
+ return self.state_machine
+
+ def check_timing(self):
+ if self.app.seconds_until_app_should_refresh > 0:
+ next = ReadyToScan
+ elif self.app.seconds_until_app_is_timed_out > 0:
+ next = NotRefreshing
+ else:
+ next = Gone
+ if self.__class__ != next: # avoid changes to same state
+ self.transition_into(next())
+
+
+class ReadyToScan(State, ScannerAppStateMixin):
+ """The app is ready to scan and waiting for the app to reach out again."""
+
+ def receive_update(self, message):
+ """The state is updated."""
+ self.check_timing()
+
+ def can_scan(self):
+ """Whether the app is able to scan right now."""
+ return True
+
+
+class NotRefreshing(ReadyToScan):
+ """The app is not responding when it is expected to."""
+
+
+class Gone(State, ScannerAppStateMixin):
+ """The app seems to be gone and is not responding."""
+
+ def receive_update(self, message):
+ """The state is updated."""
+ self.check_timing()
+
+ def is_connected(self):
+ """Whether the app is connected."""
+ return False
+
+
+class Scanning(State):
+ """The app is scanning a picure."""
+
+ def wants_to_scan(self):
+ """Whether a scan is requested."""
+ return True
+
+class ScannerApp(StateMachine):
+ """A state machine for the scanner app."""
+
+ REFRESH_APP_AFTER_SECONDS = 0.5
+ APP_TIMES_OUT_IF_NOT_RESPONDING_AFTER_SECONDS = 5
+
+ first_state = ReadyToScan
+
+ def __init__(self, id, name, server):
+ super().__init__()
+ self.id = id
+ self.name = name
+ self.server = server
+ self.create_notification_response()
+
+ @property
+ def seconds_until_app_should_refresh(self):
+ """Seconds until the app should notify again."""
+ # TODO: change the refresh interval depending on when the next scan is expected
+ delta = self.last_notification + self.REFRESH_APP_AFTER_SECONDS - time.time()
+ delta = min(self.seconds_until_app_is_timed_out, delta)
+ return (delta if delta > 0 else 0)
+
+ @property
+ def seconds_until_app_is_timed_out(self):
+ """Seconds after which we assume the app to be gone."""
+ delta = self.last_notification + self.APP_TIMES_OUT_IF_NOT_RESPONDING_AFTER_SECONDS - time.time()
+ return (delta if delta > 0 else 0)
+
+ def create_notification_response(self):
+ """Respond to the app."""
+ self.last_notification = time.time()
+ data = {"status": "ok",
+ "refresh": self.seconds_until_app_should_refresh,
+ "timeout": self.seconds_until_app_is_timed_out}
+ if self.state.wants_to_scan():
+ data["picture"] = self.state.get_picture_url()
+ return data
+
+
+class ScannerAppListener(HardwareListener):
+ """A listener for scanner apps.
+
+ Please see the API description in the OpenBookScannerApp folder.
+ """
+
+ def __init__(self, flask_server):
+ """Start a scanner app listener on a FlaskServer."""
+ self._server = flask_server
+ self._server.route("/scanner", methods=["POST"])(self._post_scanner)
+ self._apps = {} # id : app
+ self._new_apps = []
+ super().__init__()
+
+ def _post_scanner(self):
+ """Get a notification from a scanner app."""
+ data = request.json
+ print(__name__, "_post_scanner:", data)
+ assert data.get("type") == "scanner", "The type attribute must be set to scanner to indicate the willingness to scan."
+ name = data.get("name")
+ assert isinstance(name, str), "The name MUST be a string so we can display it to the user."
+ id = data.get("id")
+ assert isinstance(id, str), "The id must be a string so we can compare it to other ids."
+ app = self._apps.get(id, None)
+ if not app:
+ self._apps[id] = app = ScannerApp(id, name, self._server)
+ self.found_new_hardware(app)
+ app.print_state_changes()
+ return json.dumps(app.create_notification_response(), indent=4)
+
+ def has_driver_support(self):
+ """The apps are only supported when the server runs."""
+ return self._server.is_running()
+
+ def listen_for_hardware(self):
+ pass
+
+
+def main():
+ """Try out this server."""
+ from ..flask_server import FlaskServer
+ server = FlaskServer()
+ listener = ScannerAppListener(server)
+ listener.print_state_changes()
+ listener.run_update_loop_in_parallel()
+ server.run()
+
+
diff --git a/software/openbookscanner/states/scanner_app_test.py b/software/openbookscanner/states/scanner_app_test.py
new file mode 100644
index 0000000..79c7cc0
--- /dev/null
+++ b/software/openbookscanner/states/scanner_app_test.py
@@ -0,0 +1,5 @@
+import sys, os
+print("sys.path", sys.path)
+sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
+from openbookscanner.states.scanner_app import main
+main()
diff --git a/software/openbookscanner/states/state.py b/software/openbookscanner/states/state.py
index 03b6a56..4042a66 100644
--- a/software/openbookscanner/states/state.py
+++ b/software/openbookscanner/states/state.py
@@ -9,6 +9,8 @@
from openbookscanner.broker import LocalSubscriber
import atexit
from openbookscanner.message import MessageDispatcher
+from threading import Thread, RLock
+import traceback
class State(MessageDispatcher):
@@ -31,6 +33,7 @@ def on_leave(self):
def transition_into(self, new_state):
"""Use this to transition into another state."""
+ assert self.state_machine.state is self, "Can only transition from self."
self.state_machine.transition_into(new_state)
def toJSON(self):
@@ -67,14 +70,14 @@ def __repr__(self):
"""Return the string representation."""
return "<{} at {}>".format(self.__class__.__name__, hex(id(self)))
- def receive_message_from_other_state(self, message):
+ def receive_message_after_transition(self, message):
"""Receive a message from the state before this state."""
self.receive_message(message)
def is_error(self):
"""Whether this state is an error state."""
return False
-
+
class FirstState(State):
"""This is the first state so one has a state to come from."""
@@ -118,6 +121,7 @@ def state_changed(self):
def transition_into(self, state):
"""Transition into a new state."""
+ # TODO: ensure that a transition only happens from one thread
self.state.leave(self)
self.state = state
self.state.enter(self)
@@ -156,6 +160,17 @@ def stop(self):
def is_scanner(self):
"""Whether this state machine is a scanner."""
return False
+
+ def run_update_loop(self, seconds_between_updates=0.5):
+ """Run the update messages in a loop."""
+ while 1:
+ self.update()
+ time.sleep(seconds_between_updates)
+
+ def run_update_loop_in_parallel(self, seconds_between_updates=0.5):
+ """Run the update loop in parallel."""
+ thread = Thread(target=self.run_update_loop, daemon=True)
+ thread.start()
class FinalState(State):
@@ -194,10 +209,60 @@ def _python_exit():
atexit.register(_python_exit)
-class RunningState(State):
- next_state = _initial_next_state = DoneRunning()
+class MessageReceivingTransition(State):
+ """Transition in a thread save manner.
+
+ The state transition takes place if messages are received.
+ This allows for thread save transitioning
+ if one calls state_machine.update().
+ """
+ def __init__(self):
+ """Create a new state"""
+ self.next_state = None
+ self.critical_section = RLock()
+
+ def is_waiting_for_a_message_to_transition_to_the_next_state(self):
+ """Return whether the state likes to transition."""
+ return self.next_state is not None
+
+ def transition_into(self, next_state):
+ """Transition into the next state but defer the transition until the parallel execution is finished.
+
+ When the execution is finished, the next incoming message will start a transition.
+ The next state receives the message.
+ """
+ with self.critical_section:
+ assert self.next_state is None, "Can only transition once."
+ self.next_state = next_state
+
+ def can_transition_on_message_receive(self):
+ """Whether this state can transition when a message is received."""
+ return self.is_waiting_for_a_message_to_transition_to_the_next_state()
+
+ def receive_message(self, message):
+ """Receive a message and transition when can_transition_on_message_receive()."""
+ if self.can_transition_on_message_receive():
+ super().transition_into(self.next_state)
+ self.next_state.receive_message_after_transition(message)
+ else:
+ super().receive_message(message)
+
+
+class ErrorAfterTransition(RuntimeError):
+ """There was an error after the state machine transitioned."""
+
+
+class RunningState(MessageReceivingTransition): # TODO: refactor running state into transition and run
+ """State which runs a parrallel execution.
+
+ Override the run() method to run this in parallel.
+ If the state did not transition during the run,
+ the state machine transitions into the
+ done_running_state"""
+
_stopped = False
+ done_running_state = DoneRunning
def should_stop(self):
""" Please stop running the threads.
@@ -205,16 +270,12 @@ def should_stop(self):
The Python program is exiting right now or it should be stopped.
"""
return _shutdown or self._stopped
-
- def is_waiting_for_a_message_to_transition_to_the_next_state(self):
- """Return whether the state likes to transition."""
- return self.next_state != self._initial_next_state
def enter(self, state_machine):
"""Enter the state and start the parallel execution."""
super().enter(state_machine)
self.executor = ThreadPoolExecutor(max_workers=1)
- self.future = self.executor.submit(self.run)
+ self.future = self.executor.submit(self._run)
def run(self):
"""This is called when the state machine enters the state.
@@ -226,9 +287,28 @@ def run(self):
If this is True, the program is exiting right now and you should stop running.
"""
+ def _run(self):
+ try:
+ self.run()
+ except:
+ ty, err, tb = sys.exc_info()
+ with self.critical_section:
+ if self.is_waiting_for_a_message_to_transition_to_the_next_state():
+ traceback.print_exception(ty, err, tb)
+ raise ErrorAfterTransition("Could not pass the error to the state machine:", err)
+ self.transition_into(ErrorRaisingState(err))
+ else:
+ with self.critical_section:
+ if not self.is_waiting_for_a_message_to_transition_to_the_next_state():
+ self.transition_into(self.done_running_state())
+
def is_running(self):
"""Whether this state is currently running."""
return not self.future.done()
+
+ def can_transition_on_message_receive(self):
+ """The transition can take place if the state is not running any more."""
+ return not self.is_running() and super().can_transition_on_message_receive()
def wait(self, timeout=None):
"""Wait for the parallel task to finish.
@@ -237,37 +317,10 @@ def wait(self, timeout=None):
"""
self.future.exception(timeout)
- def transition_into(self, next_state):
- """Transition into the next state but defer the transition until the parallel execution is finished.
-
- When the execution is finished, the next incoming message will start a transition.
- The next state receives the message.
- """
- self.next_state = next_state
-
- def receive_message(self, message):
- """Receive a message and transition when the parallel execution is done."""
- if self.is_running():
- super().receive_message(message)
- else:
- if self.future.exception() is not None: # Errors should never pass silently.
- self.next_state = self.get_error_state()
- super().transition_into(self.next_state)
- self.next_state.receive_message_from_other_state(message)
-
- def receive_message_from_other_state(self, message):
- """Discard messages from previous states if I am completed."""
- if not self.is_running():
- super().receive_message(message)
-
def stop(self):
"""Stop the state if it is running."""
self._stopped = True
self.wait()
-
- def get_error_state(self):
- """Return the error state."""
- return ErrorRaisingState(self.future.exception())
class PollingState(RunningState):
@@ -356,7 +409,7 @@ def state_changed(self, state_machine):
class TimedOut(State):
- """This is teh state when the timeout was reached."""
+ """This is the state when the timeout was reached."""
class TimingOut(PollingState):
diff --git a/software/openbookscanner/storage.py b/software/openbookscanner/storage.py
index 5f0d87b..b40f590 100644
--- a/software/openbookscanner/storage.py
+++ b/software/openbookscanner/storage.py
@@ -42,11 +42,11 @@ class UserDefinedStorageLocation(MessageDispatcher, LocalSubscriber):
default_storage = TemporaryStorageLocation
- def __init__(self):
+ def __init__(self, flask_server):
"""Create a new storage with user access."""
super().__init__()
self.storage = self.default_storage()
- self.server = FileServer()
+ self.server = FileServer(flask_server)
self.state_observers = []
def receive_new_image(self, message):
@@ -73,9 +73,6 @@ def toJSON(self):
"""Return a JSON represenation."""
return {"type": self.__class__.__name__, "storage": self.storage.toJSON(),
"description": self.__class__.__doc__}
-
- def run_in_parallel(self):
- """Run the server in parellel."""
- self.server.run_in_parallel()
+