├── .gitignore ├── .google └── packaging.yaml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── androidthings │ │ └── sensorhub │ │ ├── AuthKeyGenerator.java │ │ ├── BoardDefaults.java │ │ ├── Parameters.java │ │ ├── SensorData.java │ │ ├── SensorHubActivity.java │ │ ├── TimerHelper.java │ │ ├── collector │ │ ├── Bmx280Collector.java │ │ ├── EventSensorCollector.java │ │ ├── MotionCollector.java │ │ └── SensorCollector.java │ │ └── iotcore │ │ ├── MessagePayload.java │ │ └── SensorHub.java │ └── res │ └── values │ └── strings.xml ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── rpi3_schematics.fzz ├── rpi3_schematics.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | /.idea 3 | .gradle 4 | /local.properties 5 | /gradle.properties 6 | /build 7 | .DS_Store 8 | /captures -------------------------------------------------------------------------------- /.google/packaging.yaml: -------------------------------------------------------------------------------- 1 | status: PUBLISHED 2 | technologies: [Android, Android Things] 3 | categories: [Android Things] 4 | languages: [Java] 5 | solutions: [IoT] 6 | github: androidthings/sensorhub-cloud-iot 7 | license: apache2 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 9 | 10 | * If you are an individual writing original source code and you're sure you 11 | own the intellectual property, then you'll need to sign an [individual CLA] 12 | (https://developers.google.com/open-source/cla/individual). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA] 15 | (https://developers.google.com/open-source/cla/corporate). 16 | 17 | Follow either of the two links above to access the appropriate CLA and 18 | instructions for how to sign and return it. Once we receive it, we'll be able to 19 | accept your pull requests. 20 | 21 | ## Contributing A Patch 22 | 23 | 1. Submit an issue describing your proposed change to the repo in question. 24 | 1. The repo owner will respond to your issue promptly. 25 | 1. If your proposed change is accepted, and you haven't already done so, sign a 26 | Contributor License Agreement (see details above). 27 | 1. Fork the desired repo, develop and test your code changes. 28 | 1. Ensure that your code adheres to the existing style in the sample to which 29 | you are contributing. Refer to the 30 | [Android Code Style Guide] 31 | (https://source.android.com/source/code-style.html) for the 32 | recommended coding standards for this organization. 33 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 34 | 1. Submit a pull request. 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2014 The Android Open Source Project 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cloud IoT Core Sensor Hub 2 | 3 | This sample shows how to implement a sensor hub on Android Things that collects 4 | sensor data from connected sensors and publish as telemetry events to Google 5 | Cloud IoT Core. 6 | 7 | > **Note:** The Android Things Console will be turned down for non-commercial 8 | > use on January 5, 2022. For more details, see the 9 | > [FAQ page](https://developer.android.com/things/faq). 10 | 11 | ## Introduction 12 | 13 | The sample showcases a sensor-based device publishing data to 14 | [Cloud IoT Core](https://cloud.google.com/iot-core/). Sensors can be 15 | added or removed dynamically, and the device will reconnect automatically to the 16 | cloud when power or connectivity is lost. 17 | 18 | Sensor data is collected and sent to Cloud IoT Core as telemetry events every 20 seconds by default, 19 | and it can be changed from the cloud with device config (cloud to device) messages. 20 | 21 | ## Pre-requisites 22 | 23 | - Android Things compatible board 24 | - Android Studio 2.2+ 25 | - 1 [bmp280 temperature and pressure](https://www.adafruit.com/product/2651) 26 | - 1 [PIR motion detector sensor](https://www.adafruit.com/product/189) or 1 button to simulate the 27 | motion detection 28 | - [Google Cloud Platform](https://cloud.google.com/) project with Cloud IoT Core enabled 29 | 30 | ## Schematics 31 | 32 | ![Schematics for Raspberry Pi 3](rpi3_schematics.png) 33 | 34 | ## Build and install 35 | 36 | On Android Studio, click on the "Run" button. 37 | If you prefer to run on the command line, type 38 | ``` 39 | ./gradlew installDebug 40 | adb shell am start com.example.androidthings.sensorhub/.SensorHubActivity 41 | ``` 42 | 43 | ## Prepare the device 44 | 45 | This sample will create a key pair (private and public) on the device on the 46 | first run. The private key will be saved to the Android Keystore, using a 47 | secure hardware if one is available. The public key will be printed to logcat 48 | and will be available as a file on your external storage location. 49 | 50 | You will need the public key to register your device to Cloud IoT Core. 51 | Here's how you can fetch it: 52 | 53 | ``` 54 | adb pull /sdcard/cloud_iot_auth_certificate.pem 55 | ``` 56 | 57 | or, depending on your platform: 58 | 59 | ``` 60 | adb -d shell "run-as com.example.androidthings.sensorhub cat /data/user/0/com.example.androidthings.sensorhub/files/cloud_iot_auth_certificate.pem" > cloud_iot_auth_certificate.pem 61 | ``` 62 | 63 | A new keypair is only generated again when the device is reflashed. 64 | 65 | ## Register the device 66 | 67 | With the `cloud_iot_auth_certificate.pem` file, you can register your device on 68 | Cloud IoT Core: 69 | 70 | ``` 71 | gcloud iot devices create --project= --region= --registry= --public-key path=cloud_iot_auth_certificate.pem,type= 72 | ``` 73 | 74 | Where: 75 | - `DEVICE_ID`: your device ID (it can be anything that identifies the device for you) 76 | - `PROJECT_ID`: your Cloud IoT Core project id 77 | - `CLOUD_REGION`: the cloud region for project registry 78 | - `REGISTRY_ID`: the registry name where this device should be registered 79 | - `CERTIFICATE_TYPE`: either "rsa-x509-pem" or "es256-x509-pem" depending on 80 | whether your device key algorithm is "RSA" or "EC" (see below) 81 | 82 | ## Configure the device 83 | 84 | Now that your device's public key is registered, you can set 85 | the device so that it can securely connect to Cloud IoT Core: 86 | 87 | ``` 88 | adb shell am start -e project_id -e cloud_region -e registry_id -e device_id -e key_algorithm com.example.androidthings.sensorhub/.SensorHubActivity 89 | ``` 90 | Where PROJECT_ID, CLOUD_REGION, REGISTRY_ID and DEVICE_ID must be the 91 | corresponding values used to register the device on Cloud IoT Core, and 92 | DEVICE_KEY_ALGORITHM must be the standard name of the algorithm to be used for generating 93 | the device authentication key. Currently "RSA" and "EC" are supported, and "RSA" 94 | is the default in case this argument is not defined. 95 | 96 | 97 | ## Testing 98 | 99 | If the registration and configuration steps were executed successfully, your 100 | device will immediately start publishing sensor data to Cloud IoT Core. 101 | 102 | You can pipe this data into other Google Cloud services. 103 | 104 | If you want to quickly check if messages are being published correctly, you 105 | can create a topic subscription (replace SUBSCRIPTION_NAME with any unique name 106 | you want): 107 | 108 | ``` 109 | gcloud pubsub subscriptions create projects/PROJECT_ID/subscriptions/SUBSCRIPTION_NAME --topic=projects/PROJECT_ID/topics/REGISTRY_ID 110 | ``` 111 | 112 | and then pull messages from this subscription: 113 | 114 | ``` 115 | gcloud pubsub subscriptions pull --auto-ack projects/PROJECT_ID/subscriptions/SUBSCRIPTION_NAME 116 | ``` 117 | 118 | 119 | ## Next steps 120 | 121 | Take a look at the [Cloud IoT Core documentation](https://cloud.google.com/iot/docs/) to learn how to pipe the 122 | data published by your devices into other Google Cloud services. 123 | 124 | ## License 125 | 126 | Copyright 2018 The Android Open Source Project, Inc. 127 | 128 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 129 | license agreements. See the NOTICE file distributed with this work for 130 | additional information regarding copyright ownership. The ASF licenses this 131 | file to you under the Apache License, Version 2.0 (the "License"); you may not 132 | use this file except in compliance with the License. You may obtain a copy of 133 | the License at 134 | 135 | http://www.apache.org/licenses/LICENSE-2.0 136 | 137 | Unless required by applicable law or agreed to in writing, software 138 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 139 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 140 | License for the specific language governing permissions and limitations under 141 | the License. 142 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | /.idea 3 | .gradle 4 | /local.properties 5 | /gradle.properties 6 | /build 7 | .DS_Store 8 | /captures 9 | 10 | # oauth credential 11 | /src/main/res/raw/credentials.json 12 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | 19 | android { 20 | compileSdkVersion 27 21 | 22 | defaultConfig { 23 | applicationId "com.example.androidthings.sensorhub" 24 | minSdkVersion 27 25 | targetSdkVersion 27 26 | versionCode 1 27 | versionName "1.0" 28 | } 29 | buildTypes { 30 | debug { 31 | buildConfigField "String", "PROJECT_ID", '"YOUR GOOGLE CLOUD PROJECT ID"' 32 | buildConfigField "String", "PUBSUB_TOPIC", '"YOUR GOOGLE CLOUD PUBSUB TOPIC"' 33 | } 34 | release { 35 | initWith(buildTypes.debug) 36 | 37 | minifyEnabled false 38 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 39 | } 40 | } 41 | packagingOptions { 42 | exclude 'META-INF/LICENSE' 43 | } 44 | compileOptions { 45 | targetCompatibility 1.8 46 | sourceCompatibility 1.8 47 | } 48 | } 49 | 50 | dependencies { 51 | testImplementation 'junit:junit:4.12' 52 | implementation 'com.android.support:support-annotations:27.1.1' 53 | compileOnly 'com.google.android.things:androidthings:1.0' 54 | implementation 'com.google.android.things.contrib:driver-bmx280:1.0' 55 | implementation 'com.google.android.things.contrib:driver-button:1.0' 56 | 57 | implementation 'com.google.android.things:cloud-iot-core:1.0.0' 58 | } 59 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/AuthKeyGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub; 17 | 18 | import android.os.Environment; 19 | import android.security.keystore.KeyGenParameterSpec; 20 | import android.security.keystore.KeyInfo; 21 | import android.security.keystore.KeyProperties; 22 | import android.util.Base64; 23 | import android.util.Log; 24 | 25 | import java.io.File; 26 | import java.io.FileNotFoundException; 27 | import java.io.FileOutputStream; 28 | import java.io.IOException; 29 | import java.io.OutputStream; 30 | import java.security.GeneralSecurityException; 31 | import java.security.Key; 32 | import java.security.KeyFactory; 33 | import java.security.KeyPair; 34 | import java.security.KeyPairGenerator; 35 | import java.security.KeyStore; 36 | import java.security.PrivateKey; 37 | import java.security.cert.Certificate; 38 | import java.security.cert.X509Certificate; 39 | import java.util.Arrays; 40 | import java.util.Collections; 41 | import java.util.List; 42 | 43 | import javax.security.auth.x500.X500Principal; 44 | 45 | /** 46 | * This class wraps the storage and access of the authentication key used for Cloud IoT. 47 | * It leverages the secure key storage on Android Things, using secure hardware storage 48 | * when available. 49 | *

50 | * This class supports RSA and EC authentication algorithms. 51 | */ 52 | public class AuthKeyGenerator { 53 | private static final String TAG = AuthKeyGenerator.class.getSimpleName(); 54 | 55 | private static final String DEFAULT_KEYSTORE = "AndroidKeyStore"; 56 | private static final String DEFAULT_ALIAS = "Cloud IoT Authentication"; 57 | 58 | public static final List SUPPORTED_KEY_ALGORITHMS = Collections.unmodifiableList( 59 | Arrays.asList(KeyProperties.KEY_ALGORITHM_RSA, KeyProperties.KEY_ALGORITHM_EC)); 60 | public static final String DEFAULT_KEY_ALGORITHM = KeyProperties.KEY_ALGORITHM_RSA; 61 | 62 | private static final int KEY_SIZE_RSA = 2048; 63 | private static final int KEY_SIZE_EC = 256; 64 | 65 | private final String keystoreName; 66 | private final String keyAlias; 67 | private final String keyAlgorithm; 68 | 69 | private Certificate certificate; 70 | private PrivateKey privateKey; 71 | 72 | /** 73 | * Create a new Cloud IoT Authentication wrapper using the default keystore and alias. 74 | */ 75 | public AuthKeyGenerator(String keyAlgorithm) throws GeneralSecurityException, IOException { 76 | this(DEFAULT_KEYSTORE, DEFAULT_ALIAS, keyAlgorithm); 77 | } 78 | 79 | /** 80 | * Create a new Cloud IoT Authentication wrapper using the specified keystore and alias (instead 81 | * of the defaults) 82 | * 83 | * @param keystoreName The keystore to load 84 | * @param keyAlias the alias in the keystore for Cloud IoT Authentication 85 | */ 86 | public AuthKeyGenerator(String keystoreName, String keyAlias, String keyAlgorithm) 87 | throws GeneralSecurityException, IOException { 88 | if (keyAlgorithm == null) { 89 | keyAlgorithm = DEFAULT_KEY_ALGORITHM; 90 | } 91 | if (!SUPPORTED_KEY_ALGORITHMS.contains(keyAlgorithm)) { 92 | throw new IllegalArgumentException("Invalid key algorithm " + keyAlgorithm + 93 | ". Supported are " + SUPPORTED_KEY_ALGORITHMS); 94 | } 95 | this.keystoreName = keystoreName; 96 | this.keyAlias = keyAlias; 97 | this.keyAlgorithm = keyAlgorithm; 98 | initialize(); 99 | } 100 | 101 | public void initialize() throws GeneralSecurityException, IOException { 102 | KeyStore ks = KeyStore.getInstance(keystoreName); 103 | ks.load(null); 104 | 105 | certificate = ks.getCertificate(keyAlias); 106 | if (certificate == null) { 107 | // generate key 108 | Log.w(TAG, "No auth certificate found for Cloud IoT Core. " + 109 | "Generating new certificate and key pair"); 110 | generateAuthenticationKey(); 111 | certificate = ks.getCertificate(keyAlias); 112 | } 113 | 114 | Log.i(TAG, "Loaded certificate: " + keyAlias); 115 | 116 | if (certificate instanceof X509Certificate) { 117 | X509Certificate x509Certificate = (X509Certificate) certificate; 118 | Log.d(TAG, "Subject: " + x509Certificate.getSubjectX500Principal().toString()); 119 | Log.d(TAG, "Issuer: " + x509Certificate.getIssuerX500Principal().toString()); 120 | Log.d(TAG, "Signature: " + Base64.encodeToString(x509Certificate.getSignature(), 121 | Base64.DEFAULT)); 122 | } 123 | 124 | Key key = ks.getKey(keyAlias, null); 125 | privateKey = (PrivateKey) key; 126 | 127 | if (isInSecureHardware()) { 128 | Log.i(TAG, "Private key is in secure hardware"); 129 | } else { 130 | Log.w(TAG, "Private key is NOT in secure hardware"); 131 | } 132 | 133 | exportPublicKey(); 134 | } 135 | 136 | private boolean isInSecureHardware() { 137 | try { 138 | KeyFactory factory = KeyFactory.getInstance(privateKey.getAlgorithm(), keystoreName); 139 | KeyInfo keyInfo = factory.getKeySpec(privateKey, KeyInfo.class); 140 | return keyInfo.isInsideSecureHardware(); 141 | } catch (GeneralSecurityException e) { 142 | Log.w(TAG, "Could not determine if private key is in secure hardware or not"); 143 | } 144 | return false; 145 | } 146 | 147 | public KeyPair getKeyPair() { 148 | return new KeyPair(certificate.getPublicKey(), privateKey); 149 | } 150 | 151 | /** 152 | * Generate a new key pair entry in the Android Keystore by using the KeyPairGenerator API. 153 | * This creates both a KeyPair and a self-signed certificate, both with the same alias, 154 | * using the {@link #keyAlgorithm} provided. 155 | */ 156 | private void generateAuthenticationKey() throws GeneralSecurityException { 157 | KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm, keystoreName); 158 | KeyGenParameterSpec.Builder specBuilder = 159 | new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_SIGN) 160 | .setCertificateSubject(new X500Principal("CN=unused")) 161 | .setDigests(KeyProperties.DIGEST_SHA256); 162 | 163 | if (keyAlgorithm.equals(KeyProperties.KEY_ALGORITHM_RSA)) { 164 | specBuilder.setKeySize(KEY_SIZE_RSA) 165 | .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1); 166 | } else if (keyAlgorithm.equals(KeyProperties.KEY_ALGORITHM_EC)) { 167 | specBuilder.setKeySize(KEY_SIZE_EC); 168 | } 169 | kpg.initialize(specBuilder.build()); 170 | 171 | kpg.generateKeyPair(); 172 | } 173 | 174 | /** 175 | * Exports the authentication certificate to a file on a known location. 176 | */ 177 | private void exportPublicKey() { 178 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 179 | try { 180 | File outFile = new File(Environment.getExternalStorageDirectory(), 181 | "cloud_iot_auth_certificate.pem"); 182 | try (FileOutputStream os = new FileOutputStream(outFile)) { 183 | writeCertificatePEM(os); 184 | } 185 | } catch (GeneralSecurityException | IOException e) { 186 | if (e instanceof FileNotFoundException && 187 | e.getMessage().contains("Permission denied")) { 188 | Log.e(TAG, "Unable to export certificate. Grant WRITE permission or " + 189 | "install with 'adb install -g'", e); 190 | } else { 191 | Log.e(TAG, "Unable to export certificate", e); 192 | } 193 | } 194 | } 195 | } 196 | 197 | /** 198 | * Writes the PEM-format encoded certificate 199 | * 200 | * @param os the output stream where the certificate will be written to 201 | */ 202 | private void writeCertificatePEM(OutputStream os) throws GeneralSecurityException, IOException { 203 | os.write("-----BEGIN CERTIFICATE-----\n".getBytes()); 204 | os.write(Base64.encode(certificate.getEncoded(), Base64.DEFAULT)); 205 | os.write("-----END CERTIFICATE-----\n".getBytes()); 206 | } 207 | 208 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/BoardDefaults.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub; 17 | 18 | import android.os.Build; 19 | 20 | @SuppressWarnings("WeakerAccess") 21 | public final class BoardDefaults { 22 | private static final String DEVICE_RPI3 = "rpi3"; 23 | private static final String DEVICE_RPI3BP = "rpi3bp"; 24 | private static final String DEVICE_IMX7D_PICO = "imx7d_pico"; 25 | 26 | public static String getI2cBusForSensors() { 27 | switch (Build.DEVICE) { 28 | case DEVICE_RPI3: 29 | case DEVICE_RPI3BP: 30 | return "I2C1"; 31 | case DEVICE_IMX7D_PICO: 32 | return "I2C1"; 33 | default: 34 | throw new IllegalArgumentException("Unknown device: " + Build.DEVICE); 35 | } 36 | } 37 | 38 | public static String getGPIOForMotionDetector() { 39 | switch (Build.DEVICE) { 40 | case DEVICE_RPI3: 41 | case DEVICE_RPI3BP: 42 | return "BCM21"; 43 | case DEVICE_IMX7D_PICO: 44 | return "GPIO6_IO14"; 45 | default: 46 | throw new IllegalArgumentException("Unknown device: " + Build.DEVICE); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/Parameters.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.androidthings.sensorhub; 18 | 19 | import android.content.SharedPreferences; 20 | import android.os.Bundle; 21 | import android.support.annotation.NonNull; 22 | import android.support.annotation.Nullable; 23 | import android.util.Log; 24 | 25 | import com.google.android.things.iotcore.ConnectionParams; 26 | 27 | /** 28 | * Container for the Cloud IoT Core initialization parameters 29 | */ 30 | public class Parameters { 31 | private static final String TAG = Parameters.class.getSimpleName(); 32 | 33 | private String projectId; 34 | private String registryId; 35 | private String cloudRegion; 36 | private String deviceId; 37 | private String keyAlgorithm; 38 | 39 | private Parameters() { 40 | } 41 | 42 | public String getProjectId() { 43 | return projectId; 44 | } 45 | 46 | public String getRegistryId() { 47 | return registryId; 48 | } 49 | 50 | public String getCloudRegion() { 51 | return cloudRegion; 52 | } 53 | 54 | public String getDeviceId() { 55 | return deviceId; 56 | } 57 | 58 | public String getKeyAlgorithm() { 59 | return keyAlgorithm; 60 | } 61 | 62 | public ConnectionParams getConnectionParams() { 63 | return new ConnectionParams.Builder() 64 | .setProjectId(getProjectId()) 65 | .setRegistry(getRegistryId(), getCloudRegion()) 66 | .setDeviceId(getDeviceId()) 67 | .build(); 68 | } 69 | 70 | private boolean isValid() { 71 | return projectId != null && 72 | registryId != null && 73 | cloudRegion != null && 74 | deviceId != null && 75 | (keyAlgorithm == null || 76 | AuthKeyGenerator.SUPPORTED_KEY_ALGORITHMS.contains(keyAlgorithm)); 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | return "Parameters{" + 82 | "projectId='" + projectId + '\'' + 83 | ", registryId='" + registryId + '\'' + 84 | ", cloudRegion='" + cloudRegion + '\'' + 85 | ", deviceId='" + deviceId + '\'' + 86 | ", keyAlgorithm='" + keyAlgorithm + '\'' + 87 | '}'; 88 | } 89 | 90 | public void saveToPreferences(SharedPreferences pref) { 91 | SharedPreferences.Editor editor = pref.edit(); 92 | editor.putString("project_id", getProjectId()); 93 | editor.putString("registry_id", getRegistryId()); 94 | editor.putString("device_id", getDeviceId()); 95 | editor.putString("cloud_region", getCloudRegion()); 96 | editor.putString("key_algorithm", getKeyAlgorithm()); 97 | editor.apply(); 98 | } 99 | 100 | /** 101 | * Construct a Parameters object from a SharedPreferences and an optional bundle. 102 | */ 103 | public static Parameters from(@NonNull SharedPreferences prefs, @Nullable Bundle bundle) { 104 | Parameters params = new Parameters(); 105 | params.projectId = prefs.getString("project_id", null); 106 | params.registryId = prefs.getString("registry_id", null); 107 | params.cloudRegion = prefs.getString("cloud_region", null); 108 | params.deviceId = prefs.getString("device_id", null); 109 | params.keyAlgorithm = prefs.getString("key_algorithm", null); 110 | if (bundle != null) { 111 | params.projectId = bundle.getString("project_id", params.projectId); 112 | params.registryId = bundle.getString("registry_id", params.registryId); 113 | params.cloudRegion = bundle.getString("cloud_region", params.cloudRegion); 114 | params.deviceId = bundle.getString("device_id", params.deviceId); 115 | params.keyAlgorithm = bundle.getString("key_algorithm", params.keyAlgorithm); 116 | } 117 | 118 | if (!params.isValid()) { 119 | Log.w(TAG, "Invalid parameters: " + params); 120 | return null; 121 | } 122 | return params; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/SensorData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.androidthings.sensorhub; 18 | 19 | public class SensorData { 20 | private long timestamp; 21 | private String sensorName; 22 | private float value; 23 | 24 | public SensorData(String sensorName, float value) { 25 | this(System.currentTimeMillis(), sensorName, value); 26 | } 27 | 28 | public SensorData(long timestamp, String sensorName, float value) { 29 | this.timestamp = timestamp; 30 | this.sensorName = sensorName; 31 | this.value = value; 32 | } 33 | 34 | public long getTimestamp() { 35 | return timestamp; 36 | } 37 | 38 | public String getSensorName() { 39 | return sensorName; 40 | } 41 | 42 | public float getValue() { 43 | return value; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return sensorName + " [" + timestamp + "] " + value; 49 | } 50 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/SensorHubActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub; 17 | 18 | import android.app.Activity; 19 | import android.content.Intent; 20 | import android.content.SharedPreferences; 21 | import android.os.Bundle; 22 | import android.util.Log; 23 | 24 | import com.example.androidthings.sensorhub.collector.Bmx280Collector; 25 | import com.example.androidthings.sensorhub.collector.MotionCollector; 26 | import com.example.androidthings.sensorhub.iotcore.SensorHub; 27 | 28 | import java.io.IOException; 29 | import java.security.GeneralSecurityException; 30 | 31 | public class SensorHubActivity extends Activity { 32 | 33 | private static final String TAG = SensorHubActivity.class.getSimpleName(); 34 | 35 | private static final String CONFIG_SHARED_PREFERENCES_KEY = "cloud_iot_config"; 36 | 37 | private SensorHub sensorHub; 38 | 39 | @Override 40 | protected void onNewIntent(Intent intent) { 41 | super.onNewIntent(intent); 42 | Log.d(TAG, "onNewIntent"); 43 | // getIntent() should always return the most recent 44 | setIntent(intent); 45 | } 46 | 47 | @Override 48 | protected void onResume() { 49 | super.onResume(); 50 | Log.d(TAG, "onResume"); 51 | SharedPreferences prefs = getSharedPreferences(CONFIG_SHARED_PREFERENCES_KEY, MODE_PRIVATE); 52 | Parameters params = readParameters(prefs, getIntent().getExtras()); 53 | if (params != null) { 54 | params.saveToPreferences(prefs); 55 | initializeHub(params); 56 | } 57 | } 58 | 59 | private void initializeHub(Parameters params) { 60 | if (sensorHub != null) { 61 | sensorHub.stop(); 62 | } 63 | 64 | Log.i(TAG, "Initialization parameters:\n" + 65 | " Project ID: " + params.getProjectId() + "\n" + 66 | " Region ID: " + params.getCloudRegion() + "\n" + 67 | " Registry ID: " + params.getRegistryId() + "\n" + 68 | " Device ID: " + params.getDeviceId() + "\n" + 69 | "Key algorithm: " + params.getKeyAlgorithm()); 70 | 71 | sensorHub = new SensorHub(params); 72 | sensorHub.registerSensorCollector(new Bmx280Collector( 73 | BoardDefaults.getI2cBusForSensors())); 74 | sensorHub.registerSensorCollector(new MotionCollector( 75 | BoardDefaults.getGPIOForMotionDetector())); 76 | 77 | try { 78 | sensorHub.start(); 79 | } catch (GeneralSecurityException | IOException e) { 80 | Log.e(TAG, "Cannot load keypair", e); 81 | } 82 | 83 | } 84 | 85 | @Override 86 | protected void onPause() { 87 | super.onPause(); 88 | Log.d(TAG, "onPause"); 89 | if (sensorHub != null) { 90 | sensorHub.stop(); 91 | } 92 | } 93 | 94 | private Parameters readParameters(SharedPreferences prefs, Bundle extras) { 95 | Parameters params = Parameters.from(prefs, extras); 96 | if (params == null) { 97 | String validAlgorithms = String.join(",", 98 | AuthKeyGenerator.SUPPORTED_KEY_ALGORITHMS); 99 | Log.w(TAG, "Postponing initialization until enough parameters are set. " + 100 | "Please configure via intent, for example: \n" + 101 | "adb shell am start " + 102 | "-e project_id -e cloud_region " + 103 | "-e registry_id -e device_id " + 104 | "[-e key_algorithm ] " + 105 | getPackageName() + "/." + 106 | getLocalClassName() + "\n"); 107 | } 108 | return params; 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/TimerHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub; 17 | 18 | import android.os.SystemClock; 19 | import android.util.Log; 20 | 21 | import java.util.Calendar; 22 | 23 | public class TimerHelper { 24 | private static final String TAG = TimerHelper.class.getSimpleName(); 25 | 26 | /** 27 | * Cutoff to consider a timestamp as valid. Some boards might take some time to update 28 | * their network time on the first time they boot, and we don't want to publish sensor data 29 | * with timestamps that we know are invalid. Sensor readings will be ignored until the 30 | * board's time (System.currentTimeMillis) is more recent than this constant. 31 | */ 32 | private static final long INITIAL_VALID_TIMESTAMP; 33 | static { 34 | Calendar calendar = Calendar.getInstance(); 35 | calendar.set(2016, 1, 1); 36 | INITIAL_VALID_TIMESTAMP = calendar.getTimeInMillis(); 37 | } 38 | 39 | public static long calculateNextRun(long eventsPerHour, long lastRun) { 40 | return lastRun + 60*60*1000L/eventsPerHour; 41 | } 42 | 43 | public static boolean canExecute(String loopType, boolean isReady) { 44 | long clockTime = System.currentTimeMillis(); 45 | if (clockTime < INITIAL_VALID_TIMESTAMP) { 46 | Log.d(TAG, loopType + " ignored because timestamp is invalid. " + 47 | "Please, set the device's date/time"); 48 | return false; 49 | } else if (!isReady) { 50 | Log.d(TAG, loopType + " ignored because IotCoreClient is not yet connected"); 51 | return false; 52 | } 53 | return true; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/collector/Bmx280Collector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub.collector; 17 | 18 | import android.util.Log; 19 | 20 | import com.example.androidthings.sensorhub.SensorData; 21 | import com.google.android.things.contrib.driver.bmx280.Bmx280; 22 | 23 | import java.io.IOException; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | public class Bmx280Collector implements SensorCollector { 28 | 29 | private static final String TAG = Bmx280Collector.class.getSimpleName(); 30 | 31 | private static final String SENSOR_TEMPERATURE = "temperature"; 32 | private static final String SENSOR_HUMIDITY = "humidity"; 33 | private static final String SENSOR_PRESSURE = "ambient_pressure"; 34 | 35 | private boolean isTemperatureEnabled; 36 | private boolean isPressureEnabled; 37 | private boolean isHumidityEnabled; 38 | 39 | private boolean isHumidityAvailable; 40 | 41 | private String i2cBus; 42 | private Bmx280 bmx280; 43 | 44 | public Bmx280Collector(String i2cBus) { 45 | this.i2cBus = i2cBus; 46 | // By default, enable all available sensors. Different initial state can be set by calling 47 | // setEnabled before activate. 48 | this.isTemperatureEnabled = true; 49 | this.isPressureEnabled = true; 50 | this.isHumidityEnabled = true; 51 | } 52 | 53 | @Override 54 | public boolean activate() { 55 | if (bmx280 != null) { 56 | return true; 57 | } 58 | try { 59 | bmx280 = new Bmx280(i2cBus); 60 | isHumidityAvailable = bmx280.hasHumiditySensor(); 61 | setEnabled(SENSOR_TEMPERATURE, isTemperatureEnabled); 62 | setEnabled(SENSOR_PRESSURE, isPressureEnabled); 63 | setEnabled(SENSOR_HUMIDITY, isHumidityAvailable && isHumidityEnabled); 64 | bmx280.setMode(Bmx280.MODE_NORMAL); 65 | Log.d(TAG, "BMx280 initialized"); 66 | return true; 67 | } catch (Throwable t) { 68 | Log.i(TAG, "Could not initialize BMx280 sensor on I2C bus " + i2cBus, t); 69 | } 70 | return false; 71 | } 72 | 73 | @Override 74 | public void setEnabled(String sensor, boolean enabled) { 75 | try { 76 | int overSampling = enabled ? Bmx280.OVERSAMPLING_1X : Bmx280.OVERSAMPLING_SKIPPED; 77 | switch (sensor) { 78 | case SENSOR_TEMPERATURE: 79 | if (bmx280 != null) { 80 | bmx280.setTemperatureOversampling(overSampling); 81 | } 82 | isTemperatureEnabled = enabled; 83 | break; 84 | case SENSOR_PRESSURE: 85 | if (bmx280 != null) { 86 | bmx280.setPressureOversampling(overSampling); 87 | } 88 | isPressureEnabled = enabled; 89 | break; 90 | case SENSOR_HUMIDITY: 91 | if (enabled && !isHumidityAvailable) { 92 | Log.i(TAG, "Humidity sensor not available. Ignoring request to enable it"); 93 | } else { 94 | if (bmx280 != null && isHumidityAvailable) { 95 | bmx280.setHumidityOversampling(overSampling); 96 | } 97 | isHumidityEnabled = enabled; 98 | } 99 | break; 100 | default: 101 | Log.w(TAG, "Unknown sensor " + sensor + ". Ignoring request"); 102 | } 103 | } catch (IOException ex) { 104 | Log.w(TAG, "Cannot set sensor " + sensor + " to " + enabled + ". Ignoring request", ex); 105 | } 106 | } 107 | 108 | @Override 109 | public boolean isEnabled(String sensor) { 110 | switch (sensor) { 111 | case SENSOR_TEMPERATURE: 112 | return isTemperatureEnabled; 113 | case SENSOR_PRESSURE: 114 | return isPressureEnabled; 115 | case SENSOR_HUMIDITY: 116 | return isHumidityAvailable && isHumidityEnabled; 117 | default: 118 | Log.w(TAG, "Unknown sensor " + sensor + ". Ignoring request"); 119 | } 120 | return false; 121 | } 122 | 123 | @Override 124 | public List getAvailableSensors() { 125 | List sensors = new ArrayList<>(); 126 | sensors.add(SENSOR_TEMPERATURE); 127 | sensors.add(SENSOR_PRESSURE); 128 | if (isHumidityAvailable) { 129 | sensors.add(SENSOR_HUMIDITY); 130 | } 131 | return sensors; 132 | } 133 | 134 | @Override 135 | public List getEnabledSensors() { 136 | List sensors = new ArrayList<>(); 137 | if (isEnabled(SENSOR_TEMPERATURE)) { 138 | sensors.add(SENSOR_TEMPERATURE); 139 | } 140 | if (isEnabled(SENSOR_PRESSURE)) { 141 | sensors.add(SENSOR_PRESSURE); 142 | } 143 | if (isEnabled(SENSOR_HUMIDITY)) { 144 | sensors.add(SENSOR_HUMIDITY); 145 | } 146 | return sensors; 147 | } 148 | 149 | @Override 150 | public void collectRecentReadings(List output) { 151 | if (bmx280 == null) { 152 | return; 153 | } 154 | try { 155 | if (isEnabled(SENSOR_TEMPERATURE) && isEnabled(SENSOR_PRESSURE)) { 156 | // If both temperature and pressure are enabled, we can read both with a single 157 | // I2C read, so we will report both values with the same timestamp 158 | long now = System.currentTimeMillis(); 159 | float[] data = bmx280.readTemperatureAndPressure(); 160 | output.add(new SensorData(now, SENSOR_TEMPERATURE, data[0])); 161 | output.add(new SensorData(now, SENSOR_PRESSURE, data[1])); 162 | } else if (isEnabled(SENSOR_TEMPERATURE)) { 163 | float data = bmx280.readTemperature(); 164 | output.add(new SensorData(SENSOR_TEMPERATURE, data)); 165 | } else if (isEnabled(SENSOR_PRESSURE)) { 166 | float data = bmx280.readPressure(); 167 | output.add(new SensorData(SENSOR_PRESSURE, data)); 168 | } 169 | if (isEnabled(SENSOR_HUMIDITY)) { 170 | output.add(new SensorData(SENSOR_HUMIDITY, bmx280.readHumidity())); 171 | } 172 | } catch (Throwable t) { 173 | Log.w(TAG, "Cannot collect BMx280 data. Ignoring it for now", t); 174 | } 175 | } 176 | 177 | @Override 178 | public void closeQuietly() { 179 | if (bmx280 != null) { 180 | try { 181 | bmx280.close(); 182 | } catch (IOException e) { 183 | // close quietly 184 | } 185 | bmx280 = null; 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/collector/EventSensorCollector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub.collector; 17 | 18 | import com.example.androidthings.sensorhub.SensorData; 19 | 20 | import java.util.List; 21 | 22 | /** 23 | * Special type of {@link SensorCollector} that allows collecting events when they happen. 24 | * For example, a motion sensor collector generates events when motion is detected, not at 25 | * regular intervals. Instances of this class can decide if they also want to report the 26 | * collected event as a regular sensor reading in {@link #collectRecentReadings(List)}. 27 | */ 28 | public interface EventSensorCollector extends SensorCollector { 29 | interface Callback { 30 | void onEventCollected(SensorData data); 31 | } 32 | void setEventCallback(Callback callback); 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/collector/MotionCollector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub.collector; 17 | 18 | import android.util.Log; 19 | 20 | import com.example.androidthings.sensorhub.SensorData; 21 | import com.google.android.things.contrib.driver.button.Button; 22 | 23 | import java.io.IOException; 24 | import java.util.ArrayList; 25 | import java.util.Collections; 26 | import java.util.List; 27 | 28 | public class MotionCollector implements EventSensorCollector { 29 | 30 | private static final String TAG = MotionCollector.class.getSimpleName(); 31 | 32 | private static final String SENSOR_TYPE_MOTION_DETECTION = "motion"; 33 | 34 | private String gpioPin; 35 | private Button button; 36 | private boolean enabled; 37 | private Callback eventCallback; 38 | private int lastReading; 39 | 40 | private Button.OnButtonEventListener buttonEventListener = ((button1, pressed) -> { 41 | if (eventCallback != null ) { 42 | int sensorReading = pressed ? 1 : 0; 43 | lastReading = sensorReading; 44 | Log.d(TAG, "On change " + SENSOR_TYPE_MOTION_DETECTION + ": " + sensorReading); 45 | SensorData data = new SensorData(SENSOR_TYPE_MOTION_DETECTION, sensorReading); 46 | eventCallback.onEventCollected(data); 47 | } 48 | }); 49 | 50 | public MotionCollector(String gpioPin) { 51 | this.gpioPin = gpioPin; 52 | } 53 | 54 | @Override 55 | public void setEventCallback(Callback eventCallback) { 56 | if (eventCallback != this.eventCallback) { 57 | this.eventCallback = eventCallback; 58 | } 59 | } 60 | 61 | @Override 62 | public boolean activate() { 63 | if (button != null) { 64 | return true; 65 | } 66 | try { 67 | button = new Button(gpioPin, Button.LogicState.PRESSED_WHEN_LOW); 68 | button.setOnButtonEventListener(buttonEventListener); 69 | enabled = true; 70 | Log.d(TAG, "Initialized motion detector"); 71 | return true; 72 | } catch (Throwable t) { 73 | Log.w(TAG, "Could not initialize motion detector on gpio pin " + gpioPin, t); 74 | } 75 | return false; 76 | } 77 | 78 | @Override 79 | public void setEnabled(String sensor, boolean enabled) { 80 | switch (sensor) { 81 | case SENSOR_TYPE_MOTION_DETECTION: 82 | this.enabled = enabled; 83 | break; 84 | default: 85 | Log.w(TAG, "Don't know what sensor is " + sensor + ". Ignoring."); 86 | } 87 | } 88 | 89 | @Override 90 | public boolean isEnabled(String sensor) { 91 | return enabled; 92 | } 93 | 94 | @Override 95 | public List getAvailableSensors() { 96 | return Collections.singletonList(SENSOR_TYPE_MOTION_DETECTION); 97 | } 98 | 99 | @Override 100 | public List getEnabledSensors() { 101 | List sensors = new ArrayList<>(); 102 | if (enabled) { 103 | sensors.add(SENSOR_TYPE_MOTION_DETECTION); 104 | } 105 | return sensors; 106 | } 107 | 108 | @Override 109 | public void collectRecentReadings(List output) { 110 | if (button != null) { 111 | output.add(new SensorData(SENSOR_TYPE_MOTION_DETECTION, lastReading)); 112 | } 113 | } 114 | 115 | @Override 116 | public void closeQuietly() { 117 | if (button != null) { 118 | try { 119 | button.close(); 120 | } catch (IOException e) { 121 | // close quietly 122 | } 123 | button = null; 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/collector/SensorCollector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub.collector; 17 | 18 | import com.example.androidthings.sensorhub.SensorData; 19 | 20 | import java.util.List; 21 | 22 | /** 23 | * Abstracts the process of reading sensor data from related sensors. 24 | */ 25 | public interface SensorCollector { 26 | boolean activate(); 27 | void setEnabled(String sensor, boolean enabled); 28 | boolean isEnabled(String sensor); 29 | List getAvailableSensors(); 30 | List getEnabledSensors(); 31 | void collectRecentReadings(List output); 32 | void closeQuietly(); 33 | } 34 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/iotcore/MessagePayload.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.androidthings.sensorhub.iotcore; 18 | 19 | import com.example.androidthings.sensorhub.SensorData; 20 | 21 | import org.json.JSONArray; 22 | import org.json.JSONException; 23 | import org.json.JSONObject; 24 | 25 | import java.util.Arrays; 26 | import java.util.List; 27 | 28 | /** 29 | * This class handles the serialization of the data objects to/from Strings used as 30 | * payloads on IotCore events. 31 | * 32 | * IotCore accepts arbitrary binary payloads and doesn't enforce any particular format. 33 | * 34 | */ 35 | public class MessagePayload { 36 | 37 | /** 38 | * Serialize a List of SensorData objects into a JSON string, for sending to the cloud 39 | * @param data List of SensorData objects to serialize 40 | * @return JSON String 41 | */ 42 | public static String createTelemetryMessagePayload(List data) { 43 | try { 44 | JSONObject messagePayload = new JSONObject(); 45 | JSONArray dataArray = new JSONArray(); 46 | for (SensorData el : data) { 47 | JSONObject sensor = new JSONObject(); 48 | sensor.put("timestamp_" + el.getSensorName(), 49 | el.getTimestamp()); 50 | sensor.put(el.getSensorName(), el.getValue()); 51 | dataArray.put(sensor); 52 | } 53 | messagePayload.put("data", dataArray); 54 | return messagePayload.toString(); 55 | } catch (JSONException e) { 56 | throw new IllegalArgumentException("Invalid message", e); 57 | } 58 | } 59 | 60 | /** 61 | * Compose and serialize some parameters as a JSON string, for sending to the IotCore as a 62 | * device state update 63 | * @return JSON String 64 | */ 65 | public static String createDeviceStateUpdatePayload(int version, int telemetryEventsPerHour, 66 | int stateUpdatesPerHour, List allSensors, List activeSensors) { 67 | try { 68 | JSONObject messagePayload = new JSONObject(); 69 | messagePayload.put("version", version); 70 | messagePayload.put("telemetry-events-per-hour", telemetryEventsPerHour); 71 | messagePayload.put("state-updates-per-hour", stateUpdatesPerHour); 72 | messagePayload.put("sensors", new JSONArray(allSensors)); 73 | messagePayload.put("active-sensors", new JSONArray(activeSensors)); 74 | return messagePayload.toString(); 75 | } catch (JSONException e) { 76 | throw new IllegalArgumentException("Invalid message", e); 77 | } 78 | } 79 | 80 | /** 81 | * De-serialize IotCore device configuration message payload as a JSON string. 82 | * 83 | * Format of the message should be similar to: 84 | *

 85 |      * {
 86 |      *      "version": 1,
 87 |      *      "telemetry-events-per-hour": 20,
 88 |      *      "state-updates-per-hour": 10,
 89 |      *      "active-sensors": ["motion", "temperature"]
 90 |      * }
 91 |      * 
92 | * 93 | * @param jsonPayload JSON of the device config message 94 | * @return JSON String 95 | */ 96 | public static DeviceConfig parseDeviceConfigPayload(String jsonPayload) { 97 | try { 98 | JSONObject message = new JSONObject(jsonPayload); 99 | DeviceConfig deviceConfig = new DeviceConfig(); 100 | deviceConfig.version = message.getInt("version"); 101 | deviceConfig.telemetryEventsPerHour = message.getInt("telemetry-events-per-hour"); 102 | deviceConfig.stateUpdatesPerHour = message.getInt("state-updates-per-hour"); 103 | JSONArray activeSensors = message.getJSONArray("active-sensors"); 104 | deviceConfig.activeSensors = new String[activeSensors.length()]; 105 | for (int i = 0; i < activeSensors.length(); i++) { 106 | deviceConfig.activeSensors[i] = activeSensors.getString(i); 107 | } 108 | return deviceConfig; 109 | } catch (JSONException e) { 110 | throw new IllegalArgumentException("Invalid message: \"" + jsonPayload + "\"", e); 111 | } 112 | } 113 | 114 | public static class DeviceConfig { 115 | public int version; 116 | public int telemetryEventsPerHour; 117 | public int stateUpdatesPerHour; 118 | public String[] activeSensors; 119 | 120 | @Override 121 | public String toString() { 122 | return "DeviceConfig{" + 123 | "version=" + version + 124 | ", telemetryEventsPerHour=" + telemetryEventsPerHour + 125 | ", stateUpdatesPerHour=" + stateUpdatesPerHour + 126 | ", activeSensors=" + Arrays.toString(activeSensors) + 127 | '}'; 128 | } 129 | } 130 | } -------------------------------------------------------------------------------- /app/src/main/java/com/example/androidthings/sensorhub/iotcore/SensorHub.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.androidthings.sensorhub.iotcore; 17 | 18 | import android.os.Handler; 19 | import android.os.HandlerThread; 20 | import android.os.SystemClock; 21 | import android.support.annotation.NonNull; 22 | import android.util.Log; 23 | 24 | import com.example.androidthings.sensorhub.AuthKeyGenerator; 25 | import com.example.androidthings.sensorhub.Parameters; 26 | import com.example.androidthings.sensorhub.SensorData; 27 | import com.example.androidthings.sensorhub.TimerHelper; 28 | import com.example.androidthings.sensorhub.collector.EventSensorCollector; 29 | import com.example.androidthings.sensorhub.collector.SensorCollector; 30 | import com.google.android.things.iotcore.ConnectionCallback; 31 | import com.google.android.things.iotcore.IotCoreClient; 32 | import com.google.android.things.iotcore.TelemetryEvent; 33 | 34 | import java.io.IOException; 35 | import java.security.GeneralSecurityException; 36 | import java.util.ArrayList; 37 | import java.util.Arrays; 38 | import java.util.Collections; 39 | import java.util.HashSet; 40 | import java.util.List; 41 | import java.util.concurrent.atomic.AtomicBoolean; 42 | 43 | public class SensorHub { 44 | private static final String TAG = "sensorhub"; 45 | 46 | private static final int DEFAULT_TELEMETRY_PER_HOUR = 60*3; // every 20 seconds 47 | private static final int DEFAULT_STATE_UPDATES_PER_HOUR = 60; // every minute 48 | 49 | private HandlerThread backgroundThread; 50 | private Handler eventsHandler; 51 | private Handler recurrentTasksHandler; 52 | 53 | /** 54 | * Version of the configuration reported in the device status state (device to cloud). 55 | * Device config messages (cloud to device) should use a version greater than this value, 56 | * otherwise it will be ignored. 57 | */ 58 | private int configurationVersion; 59 | 60 | private int telemetryEventsPerHour; 61 | private int stateUpdatesPerHour; 62 | 63 | private long lastTelemetryRun; 64 | private long lastStateUpdateRun; 65 | 66 | private List collectors; 67 | 68 | private Parameters params; 69 | private IotCoreClient iotCoreClient; 70 | 71 | private AtomicBoolean ready; 72 | 73 | public SensorHub(Parameters params) { 74 | this.ready = new AtomicBoolean(false); 75 | this.configurationVersion = 0; 76 | this.telemetryEventsPerHour = DEFAULT_TELEMETRY_PER_HOUR; 77 | this.stateUpdatesPerHour = DEFAULT_STATE_UPDATES_PER_HOUR; 78 | this.params = params; 79 | this.collectors = new ArrayList<>(); 80 | } 81 | 82 | 83 | /** 84 | * Register a sensor collector. When the SensorHub is started, it will fetch sensor readings 85 | * from the active collectors. 86 | * 87 | * Collectors that implement {@link EventSensorCollector} have their event callback overridden 88 | * to call the {@link #processSensorEvent(SensorData)} method. 89 | * 90 | * @param collector 91 | */ 92 | public void registerSensorCollector(@NonNull SensorCollector collector) { 93 | collectors.add(collector); 94 | if (collector instanceof EventSensorCollector) { 95 | ((EventSensorCollector) collector).setEventCallback(this::processSensorEvent); 96 | } 97 | } 98 | 99 | /** 100 | * Start sensor collection and reporting. 101 | * @throws GeneralSecurityException 102 | * @throws IOException 103 | */ 104 | public void start() throws GeneralSecurityException, IOException { 105 | initializeIfNeeded(); 106 | 107 | backgroundThread = new HandlerThread("IotCoreThread"); 108 | backgroundThread.start(); 109 | eventsHandler = new Handler(backgroundThread.getLooper()); 110 | recurrentTasksHandler = new Handler(backgroundThread.getLooper()); 111 | 112 | recurrentTasksHandler.post(recurrentTelemetryPublisher); 113 | recurrentTasksHandler.post(stateUpdatePublisher); 114 | } 115 | 116 | public void stop() { 117 | Log.d(TAG, "Stop SensorHub"); 118 | backgroundThread.quitSafely(); 119 | closeCollectors(); 120 | iotCoreClient.disconnect(); 121 | } 122 | 123 | private void initializeIfNeeded() { 124 | ready.set(false); 125 | AuthKeyGenerator keyGenerator = null; 126 | try { 127 | keyGenerator = new AuthKeyGenerator(params.getKeyAlgorithm()); 128 | } catch (GeneralSecurityException | IOException e) { 129 | throw new IllegalArgumentException("Cannot create a key generator", e); 130 | } 131 | iotCoreClient = new IotCoreClient.Builder() 132 | .setConnectionParams(params.getConnectionParams()) 133 | .setKeyPair(keyGenerator.getKeyPair()) 134 | .setConnectionCallback(new ConnectionCallback() { 135 | @Override 136 | public void onConnected() { 137 | Log.d(TAG, "Connected to IoT Core"); 138 | ready.set(true); 139 | } 140 | 141 | @Override 142 | public void onDisconnected(int i) { 143 | Log.d(TAG, "Disconnected from IoT Core"); 144 | } 145 | }) 146 | .setOnConfigurationListener(this::onConfigurationReceived) 147 | .build(); 148 | connectIfNeeded(); 149 | } 150 | 151 | private void connectIfNeeded() { 152 | if (iotCoreClient != null && !iotCoreClient.isConnected()) { 153 | iotCoreClient.connect(); 154 | } 155 | } 156 | 157 | private void onConfigurationReceived(byte[] bytes) { 158 | if (bytes.length == 0) { 159 | Log.w(TAG, "Ignoring empty device config event"); 160 | return; 161 | } 162 | MessagePayload.DeviceConfig deviceConfig = MessagePayload.parseDeviceConfigPayload( 163 | new String(bytes)); 164 | if (deviceConfig.version <= configurationVersion) { 165 | Log.w(TAG, "Ignoring device config message with old version. Current version: " + 166 | configurationVersion + ", Version received: " + deviceConfig.version); 167 | return; 168 | } 169 | Log.i(TAG, "Applying device config: " + deviceConfig); 170 | configurationVersion = deviceConfig.version; 171 | 172 | recurrentTasksHandler.post(() -> { 173 | reconfigure(deviceConfig); 174 | }); 175 | } 176 | 177 | private void reconfigure(MessagePayload.DeviceConfig deviceConfig) { 178 | telemetryEventsPerHour = deviceConfig.telemetryEventsPerHour; 179 | stateUpdatesPerHour = deviceConfig.stateUpdatesPerHour; 180 | 181 | HashSet toEnable = new HashSet<>(Arrays.asList(deviceConfig.activeSensors)); 182 | 183 | for (SensorCollector collector: collectors) { 184 | for (String sensor: collector.getAvailableSensors()) { 185 | boolean enable = toEnable.remove(sensor); 186 | collector.setEnabled(sensor, enable); 187 | } 188 | } 189 | 190 | if (!toEnable.isEmpty()) { 191 | Log.w(TAG, "Ignoring unknown sensors in device config active-sensors: " + 192 | toEnable); 193 | } 194 | 195 | // reconfigure recurrent tasks: 196 | recurrentTasksHandler.removeCallbacks(recurrentTelemetryPublisher); 197 | recurrentTasksHandler.removeCallbacks(stateUpdatePublisher); 198 | scheduleNextSensorCollection(); 199 | scheduleNextStatusUpdate(); 200 | } 201 | 202 | private void processSensorEvent(SensorData event) { 203 | if (eventsHandler == null) { 204 | Log.i(TAG, "Ignoring event because the background handler is " + 205 | "not running (has the event thread been initiated yet?). Event: " + 206 | event); 207 | return; 208 | } 209 | eventsHandler.post(() -> publishTelemetry(Collections.singletonList(event))); 210 | } 211 | 212 | private void publishTelemetry(List currentReadings) { 213 | String payload = MessagePayload.createTelemetryMessagePayload(currentReadings); 214 | Log.d(TAG, "Publishing telemetry: " + payload); 215 | if (iotCoreClient == null) { 216 | Log.w(TAG, "Ignoring sensor readings because IotCoreClient is not yet active."); 217 | return; 218 | } 219 | TelemetryEvent event = new TelemetryEvent(payload.getBytes(), 220 | null, TelemetryEvent.QOS_AT_LEAST_ONCE); 221 | iotCoreClient.publishTelemetry(event); 222 | } 223 | 224 | private void publishDeviceState() { 225 | List activeSensors = new ArrayList<>(); 226 | List allSensors = new ArrayList<>(); 227 | for (SensorCollector collector: collectors) { 228 | allSensors.addAll(collector.getAvailableSensors()); 229 | activeSensors.addAll(collector.getEnabledSensors()); 230 | } 231 | String payload = MessagePayload.createDeviceStateUpdatePayload( 232 | configurationVersion, telemetryEventsPerHour, stateUpdatesPerHour, 233 | allSensors, activeSensors); 234 | Log.d(TAG, "Publishing device state: " + payload); 235 | if (iotCoreClient == null) { 236 | Log.w(TAG, "Refusing to publishTelemetry device state because IotCoreClient is " + 237 | "not yet active."); 238 | return; 239 | } 240 | iotCoreClient.publishDeviceState(payload.getBytes()); 241 | } 242 | 243 | private List collectCurrentSensorsReadings() { 244 | List sensorsData = new ArrayList<>(); 245 | for (SensorCollector collector: collectors) { 246 | try { 247 | collector.activate(); 248 | collector.collectRecentReadings(sensorsData); 249 | } catch (Throwable t) { 250 | Log.e(TAG, "Cannot collect recent readings of " + 251 | collector.getAvailableSensors() + ", will try again in the next run.", t); 252 | } 253 | } 254 | Log.d(TAG, "collected sensor data: " + sensorsData); 255 | return sensorsData; 256 | } 257 | 258 | private void closeCollectors() { 259 | for (SensorCollector collector: collectors) { 260 | collector.closeQuietly(); 261 | } 262 | } 263 | 264 | private void scheduleNextSensorCollection() { 265 | long nextRun = TimerHelper.calculateNextRun(telemetryEventsPerHour, lastTelemetryRun); 266 | recurrentTasksHandler.postAtTime(recurrentTelemetryPublisher, nextRun); 267 | } 268 | 269 | private void scheduleNextStatusUpdate() { 270 | long nextRun = TimerHelper.calculateNextRun(stateUpdatesPerHour, lastStateUpdateRun); 271 | recurrentTasksHandler.postAtTime(stateUpdatePublisher, nextRun); 272 | } 273 | 274 | private final Runnable recurrentTelemetryPublisher = new Runnable() { 275 | @Override 276 | public void run() { 277 | lastTelemetryRun = SystemClock.uptimeMillis(); 278 | connectIfNeeded(); 279 | if (TimerHelper.canExecute("Telemetry loop", ready.get())) { 280 | try { 281 | List currentReadings = collectCurrentSensorsReadings(); 282 | publishTelemetry(currentReadings); 283 | } catch (Throwable t) { 284 | Log.e(TAG, "Cannot publish recurrent telemetry events, " + 285 | "will try again later", t); 286 | } 287 | } 288 | scheduleNextSensorCollection(); 289 | } 290 | }; 291 | 292 | private final Runnable stateUpdatePublisher = new Runnable() { 293 | @Override 294 | public void run() { 295 | lastStateUpdateRun = SystemClock.uptimeMillis(); 296 | connectIfNeeded(); 297 | if (TimerHelper.canExecute("State update loop", ready.get())) { 298 | try { 299 | publishDeviceState(); 300 | } catch (Throwable t) { 301 | Log.e(TAG, "Cannot publish device state, will try again later", t); 302 | } 303 | } 304 | scheduleNextStatusUpdate(); 305 | } 306 | }; 307 | 308 | } 309 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | Cloud IoT Sensor Hub 18 | 19 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | google() 20 | jcenter() 21 | } 22 | dependencies { 23 | classpath 'com.android.tools.build:gradle:3.1.2' 24 | 25 | // NOTE: Do not place your application dependencies here; they belong 26 | // in the individual module build.gradle files 27 | } 28 | } 29 | 30 | allprojects { 31 | repositories { 32 | google() 33 | jcenter() 34 | } 35 | } 36 | 37 | task clean(type: Delete) { 38 | delete rootProject.buildDir 39 | } 40 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androidthings/sensorhub-cloud-iot/70142ad26cdb6b0318e6f8bbf1a31b6337b8b487/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon May 07 17:37:14 PDT 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /rpi3_schematics.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androidthings/sensorhub-cloud-iot/70142ad26cdb6b0318e6f8bbf1a31b6337b8b487/rpi3_schematics.fzz -------------------------------------------------------------------------------- /rpi3_schematics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/androidthings/sensorhub-cloud-iot/70142ad26cdb6b0318e6f8bbf1a31b6337b8b487/rpi3_schematics.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | include ':app' 18 | --------------------------------------------------------------------------------