├── .travis.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── amazonaws │ │ └── awsiotproxy │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── amazonaws │ │ │ └── awsiotproxy │ │ │ ├── CustomizedMqttEnvelope.java │ │ │ ├── CustomizedThing.java │ │ │ ├── ESP32CustomizedThing.java │ │ │ ├── MainActivity.java │ │ │ ├── MyDummyCustomizedThing.java │ │ │ ├── MyTLV.java │ │ │ ├── ProxyConfig.java │ │ │ └── ui │ │ │ └── main │ │ │ ├── DevicesFragment.java │ │ │ ├── MainFragment.java │ │ │ ├── PublishFragment.java │ │ │ ├── SubscribeFragment.java │ │ │ └── ThingChangeListener.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── devices_fragment.xml │ │ ├── devices_list_layout.xml │ │ ├── main_activity.xml │ │ ├── main_fragment.xml │ │ ├── publish_fragment.xml │ │ └── subscribe_fragment.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── raw │ │ └── awsconfiguration.json │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── amazonaws │ └── awsiotproxy │ └── ExampleUnitTest.java ├── build.gradle ├── doc ├── architecture-diagram.png ├── authentication.png ├── connect-with-esp.gif ├── sign-in.png └── tlv.png ├── esp32_patch └── 0001-aws-iot-proxy-adding-dummy-message-for-aws-iot-proxy.patch ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: oraclejdk8 3 | sudo: required 4 | dist: trusty 5 | 6 | notifications: 7 | email: false 8 | 9 | env: 10 | global: 11 | - ANDROID_API_LEVEL=29 12 | - ANDROID_BUILD_TOOLS_VERSION=29.0.3 13 | - ANDROID_EMULATOR_ABI=armeabi-v7a 14 | - ANDROID_EMULATOR_ABI_TAG=google_apis 15 | - ANDROID_EMULATOR_API_LEVEL=24 16 | 17 | android: 18 | components: 19 | - tools 20 | - platform-tools 21 | - extra 22 | - build-tools-$ANDROID_BUILD_TOOLS_VERSION 23 | - android-$ANDROID_API_LEVEL 24 | - android-$ANDROID_EMULATOR_API_LEVEL 25 | - extra-google-google_play_services 26 | - extra-google-m2repository 27 | - extra-android-m2repository 28 | - sys-img-armeabi-v7a-addon-$ANDROID_EMULATOR_ABI_TAG-google-$ANDROID_API_LEVEL 29 | - sys-img-$ANDROID_EMULATOR_ABI-android-$ANDROID_EMULATOR_API_LEVEL 30 | 31 | before_install: 32 | # SDK licenses 33 | - yes | sdkmanager "platforms;android-${ANDROID_API_LEVEL}" 34 | - yes | sdkmanager "platforms;android-${ANDROID_EMULATOR_API_LEVEL}" 35 | 36 | before_script: 37 | # Emulator 38 | # - yes | sdkmanager "system-images;android-$ANDROID_EMULATOR_API_LEVEL;$ANDROID_EMULATOR_ABI_TAG;$ANDROID_EMULATOR_ABI" 39 | - echo "y" | android update sdk -a --no-ui --filter android-$ANDROID_EMULATOR_API_LEVEL 40 | # - echo "y" | android update sdk -a --no-ui --filter sys-img-armeabi-v7a-android-24 41 | # - echo no | android create avd --force -n ${ANDROID_EMULATOR_ABI}-test -t android-$ANDROID_EMULATOR_API_LEVEL --abi $ANDROID_EMULATOR_ABI 42 | # - emulator -avd ${ANDROID_EMULATOR_ABI}-test -no-skin -no-audio -no-window & 43 | # - android-wait-for-emulator 44 | # - adb shell input keyevent 82 & 45 | 46 | script: 47 | - ./gradlew build 48 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | AWS IoT Proxy Mobile App for BLE Devices 3 |
4 |

5 | 6 |

7 | Build Status 8 |

9 | 10 | In order for Bluetooth Low Energy (BLE) devices to connect to AWS IoT, AWS has provided the [FreeRTOS BLE Library](https://docs.aws.amazon.com/freertos/latest/userguide/freertos-ble-library.html) for BLE devices to use MQTT, and [Mobile SDKs for Android and iOS](https://docs.aws.amazon.com/freertos/latest/userguide/freertos-ble-mobile.html) for mobile devices to act as connecting agents to AWS IoT. 11 | 12 | In order to use those technologies, developers need to integrate the FreeRTOS BLE Library into the BLE device. The integration is difficult for some BLE devices especially for brown-field devices that are already running in the field. For new BLE devices, some developers choose not do add additional components into the firmware. 13 | 14 | To address the need of such applications, this repository provides reference implementation of an Android app that can interact with BLE devices without requiring the device to run the FreeRTOS BLE Library. As long as the device runs a GATT server, this app can connect to it, convert the information sent by the BLE device into MQTT messages and publish them to AWS IoT. This app can be customized to subscribe to MQTT topics, convert messages into proprietary format then send them over to the BLE device. The diagram below illustrate this architecture. 15 | 16 | ![](doc/architecture-diagram.png) 17 | 18 | ## Prerequisites 19 | 20 | This proxy using AWS Cognito as credential provider. Refer to the “Set up AWS IoT and Amazon Cognito” section in [this document](https://docs.aws.amazon.com/freertos/latest/userguide/ble-demo.html) for how to set it up to work with this application. 21 | 22 | ![](doc/authentication.png) 23 | 24 | ## Quick Start 25 | 1. git clone this project. 26 | 2. Update **Thing ID**, **Broker Endpoint**, **IoT Policy name**, **AWS Region** in com/amazonaws/awsiotproxy/ProxyConfig.java. Refer to this document (https://docs.aws.amazon.com/freertos/latest/userguide/ble-demo.html#ble-sdk-app) and follow the instructions under “**To configure the Android SDK demo application**” to create the IoT Policy. 27 | 3. Update **Cognito Identity PoolId/Region**, **Cognito User PoolId/Region/AppClientId/AppClientSecret** in raw/awsconfiguration.json. Refer to this document (https://docs.aws.amazon.com/freertos/latest/userguide/ble-demo.html) and follow the instructions under “**Set up AWS IoT and Amazon Cognito**” to set up and get the values for those configurations. 28 | 4. Build the mobile app, install it on an Android device, launch it. 29 | 5. A sign in/sign up page will show up. User can sign in with Cognito user name/password, or choose to create a new account via sign up: 30 | ![](doc/sign-in.png) 31 | 6. On the **DEVICES** tab, a dummy device will be created base on the info in com/amazonaws/awsiotproxy/ProxyConfig.java. Click it to create connection with AWS IoT core. 32 | 7. After connected to AWS IoT core, dummy device will publish to topic **"proxy/test"** with a json format payload every 5 secs. 33 | 8. After connected to AWS IoT core, use **PUBLISH** and **SUBSCRIBE** tabs to publish/subscribe/unsubscribe to/from specific topic. 34 | 9. User can check MQTT messages on AWS IoT console. For more details, refer to this [document](https://docs.aws.amazon.com/iot/latest/developerguide/view-mqtt-messages.html); 35 | 36 | ## Use with [ESP32 gatt_server demo](https://github.com/espressif/esp-idf/tree/master/examples/bluetooth/bluedroid/ble/gatt_server) 37 | The Android application built in the previous step can work with an ESP32 device running with its gatt_server demo after you apply a patch contained in this project. 38 | 39 | 1. Install the ESP IDF (https://github.com/espressif/esp-idf). 40 | 2. Apply patch from this project. Assuming you have installed this project under and ESP IDF has been installed under : 41 | 42 | ```bash 43 | cp /esp32_patch/0001-aws-iot-proxy-adding-dummy-message-for-aws-iot-proxy.patch /examples/bluetooth/bluedroid/ble/gatt_server 44 | cd /examples/bluetooth/bluedroid/ble/gatt_server 45 | git apply 0001-aws-iot-proxy-adding-dummy-message-for-aws-iot-proxy.patch 46 | ``` 47 | 48 | 3. Build and flash ESP32: 49 | 50 | ```bash 51 | idf.py build 52 | idf.py -p /dev/ttyUSB0 flash 53 | ``` 54 | 55 | 4. Boot up the ESP32 device. Go to the mobile app, swipe down to scan new devices. The ESP32 should appear on the screen. 56 | 5. Click device in devices list to connect. 57 | 6. ESP32 will send dummy data to the mobile app, then the app will convert the data into JSON payload and publish to AWS IoT Core. 58 | 59 | ![](doc/connect-with-esp.gif) 60 | 61 | ## Customize the mobile app for use with proprietary protocol over GATT 62 | In this reference implementation, a CustomizedThing is abstracted as a java class to provide the following functionalities: 63 | 64 | * Connect to IoT: Connect to AWS IoT cloud as a Cognito user. 65 | * Publish to IoT: Publish message to specific topic. 66 | * Subscribe to IoT: Subscribe to specific topic. 67 | * Unsubscribe to IoT: Unsubscribe to specific topic. 68 | * Publish to Thing: When received message from subscribed topic, send it back to local devices. 69 | * Send ACK to Thing: Send ACK to device when publish/subscribe/unsubscribe successfully. 70 | 71 | To adapt it with private local protocol: 72 | 1. Extend from `class CustomizedThing`. 73 | 2. Create coder/decoder similar to `class MyTLV`, which supports decode messages from device to connect/publish/subscribe/unsubscribe behaviors and encode ACK/publish messages from Cloud/App to device. 74 | 75 | Since the data type of GATT characteristics operation is bytes array, user need to define several methods takes bytes array and `CustomizedMqttEnvelope` as parameters. Take `class MyTLV` as an example, which defines a simple TLV(Type-Length-Value) protocol: 76 | 77 | ![](doc/tlv.png) 78 | 79 | In this example protocol, we defined 7 types as blow: 80 | 81 | ```java 82 | public enum TLVType { 83 | INVALID, 84 | PUBACK, 85 | SUBACK, 86 | UNSUBACK, 87 | PUB, 88 | SUB, 89 | UNSUB, 90 | } 91 | ``` 92 | 93 | To make it adapt with Proxy, we defines constructor: 94 | 95 | * `MyTLV(CustomizedMqttEnvelope envelope)`: Create a `MyTLV` object with `CustomizedMqttEnvelope`. It will call `MyTLV.encode()` method inside to generate encoded bytes array write to device characteristics base on input envelope. 96 | * `MyTLV(@NonNull byte[] encodedBytesStream)`: Create a `MyTLV` object with encoded bytes array read from device characteristics . It will call `MyTLV.decode()` method to get type, length, and values from encoded bytes. After that, user can call `CustomizedMqttEnvelope.toCustomizedMqttEnvelope()` to get a `CustomizedMqttEnvelope` object. 97 | 98 | ## Security 99 | 100 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 101 | 102 | ## License 103 | 104 | This library is licensed under the MIT-0 License. See the [LICENSE](LICENSE) file. 105 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 29 5 | buildToolsVersion "29.0.3" 6 | 7 | defaultConfig { 8 | applicationId "com.amazonaws.awsiotproxy" 9 | minSdkVersion 23 10 | targetSdkVersion 29 11 | versionCode 1 12 | versionName "1.0" 13 | 14 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | 24 | lintOptions { 25 | abortOnError false 26 | } 27 | 28 | } 29 | 30 | dependencies { 31 | implementation fileTree(dir: 'libs', include: ['*.jar']) 32 | 33 | implementation 'androidx.appcompat:appcompat:1.0.2' 34 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 35 | implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0' 36 | implementation 'androidx.legacy:legacy-support-v4:1.0.0' 37 | testImplementation 'junit:junit:4.12' 38 | androidTestImplementation 'androidx.test.ext:junit:1.1.1' 39 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 40 | implementation 'software.amazon.freertos:amazonfreertossdk:1.1.0' 41 | implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.16.12' 42 | implementation 'com.amazonaws:aws-android-sdk-auth-userpools:2.16.12' 43 | implementation 'com.amazonaws:aws-android-sdk-auth-ui:2.16.12' 44 | implementation 'com.google.android.material:material:1.0.0' 45 | implementation 'androidx.recyclerview:recyclerview:1.1.0' 46 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" 47 | implementation 'org.bouncycastle:bcprov-jdk15on:1.65' 48 | } 49 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/amazonaws/awsiotproxy/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.amazonaws.awsiotproxy; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | 25 | assertEquals("com.amazonaws.awsiotproxy", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/CustomizedMqttEnvelope.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | import androidx.annotation.NonNull; 24 | 25 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos; 26 | 27 | public class CustomizedMqttEnvelope { 28 | public String topic; 29 | public AWSIotMqttQos qoS; 30 | 31 | public CustomizedMqttEnvelopeType envelopeType; 32 | public byte[] payload; 33 | 34 | public enum CustomizedMqttEnvelopeType { 35 | Publish, 36 | Subscribe, 37 | Unsubscribe, 38 | } 39 | 40 | /** 41 | * Instantiates a new CustomizedMqttEnvelope. 42 | * 43 | * @param topic Topic to publish/subscribe/unsubscribe. 44 | * @param qoS MQTT QoS. 45 | * @param envelopeType Request type. 46 | * @param payload Payload bytes stream. 47 | */ 48 | private CustomizedMqttEnvelope(String topic, AWSIotMqttQos qoS, CustomizedMqttEnvelopeType envelopeType, byte[] payload) { 49 | this.topic = topic; 50 | this.qoS = qoS; 51 | this.envelopeType = envelopeType; 52 | this.payload = payload; 53 | } 54 | 55 | public static CustomizedMqttEnvelope newPublishEnvelope(String topic, AWSIotMqttQos qoS, @NonNull final byte[] payload) { 56 | return new CustomizedMqttEnvelope(topic, qoS, CustomizedMqttEnvelopeType.Publish, payload); 57 | } 58 | 59 | public static CustomizedMqttEnvelope newSubscribeEnvelope(String topic, AWSIotMqttQos qoS) { 60 | return new CustomizedMqttEnvelope(topic, qoS, CustomizedMqttEnvelopeType.Subscribe, null); 61 | } 62 | 63 | public static CustomizedMqttEnvelope newUnsubscribeEnvelope(String topic) { 64 | return new CustomizedMqttEnvelope(topic, AWSIotMqttQos.QOS0, CustomizedMqttEnvelopeType.Unsubscribe, null); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/CustomizedThing.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | import android.util.Log; 24 | 25 | import androidx.annotation.NonNull; 26 | import androidx.annotation.Nullable; 27 | 28 | import com.amazonaws.auth.AWSCredentialsProvider; 29 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback; 30 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager; 31 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttMessageDeliveryCallback; 32 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback; 33 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos; 34 | 35 | import java.io.UnsupportedEncodingException; 36 | 37 | import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants.MqttConnectionState; 38 | 39 | public abstract class CustomizedThing { 40 | private static final String TAG = "CustomizedThing"; 41 | protected String mThingId; 42 | protected String mBrokerEndpoint; 43 | protected AWSIotMqttManager mIotMqttManager; 44 | private MqttConnectionState mMqttConnectionState = MqttConnectionState.MQTT_Disconnected; 45 | private ThingConnectionState mThingConnectionState = ThingConnectionState.Thing_Disconnected; 46 | private AWSCredentialsProvider mAWSCredential; 47 | private OnConnectionStateListener mOnConnectionStateListener; 48 | 49 | public enum ThingConnectionState { 50 | Thing_Disconnected, 51 | Thing_Connecting, 52 | Thing_Connected 53 | } 54 | 55 | /** 56 | * Instantiates a new Customized thing. 57 | * 58 | * @param thingId Unique client ID. 59 | * @param brokerEndpoint Broker endpoint. 60 | * @param awsCredentials AWS credentials. 61 | */ 62 | public CustomizedThing(String thingId, 63 | String brokerEndpoint, 64 | AWSCredentialsProvider awsCredentials) { 65 | this.mThingId = thingId; 66 | this.mBrokerEndpoint = brokerEndpoint; 67 | this.mAWSCredential = awsCredentials; 68 | } 69 | 70 | public String getThingId() { 71 | return mThingId; 72 | } 73 | 74 | public MqttConnectionState getMqttConnectionState() { 75 | return mMqttConnectionState; 76 | } 77 | 78 | public ThingConnectionState getThingConnectionState() { 79 | return mThingConnectionState; 80 | } 81 | 82 | public void setOnConnectionStateListener(@Nullable OnConnectionStateListener listener) { 83 | mOnConnectionStateListener = listener; 84 | } 85 | 86 | /** 87 | * Connect to AWS IoT core. 88 | */ 89 | public void connectToIoT() { 90 | if (mMqttConnectionState == MqttConnectionState.MQTT_Connected) { 91 | Log.w(TAG, "Already connected to IOT."); 92 | return; 93 | } 94 | if (mMqttConnectionState != MqttConnectionState.MQTT_Disconnected) { 95 | Log.w(TAG, "Previous connection is active, please retry or disconnect MQTT first."); 96 | return; 97 | } 98 | mIotMqttManager = new AWSIotMqttManager(mThingId, mBrokerEndpoint); 99 | 100 | AWSIotMqttClientStatusCallback mqttClientStatusCallback = new AWSIotMqttClientStatusCallback() { 101 | @Override 102 | public void onStatusChanged(AWSIotMqttClientStatus status, Throwable throwable) { 103 | Log.i(TAG, "MQTT connection status changed to: " + String.valueOf(status)); 104 | switch (status) { 105 | case Connected: 106 | setMqttConnectionState(MqttConnectionState.MQTT_Connected); 107 | break; 108 | case Connecting: 109 | case Reconnecting: 110 | setMqttConnectionState(MqttConnectionState.MQTT_Connecting); 111 | break; 112 | case ConnectionLost: 113 | setMqttConnectionState(MqttConnectionState.MQTT_Disconnected); 114 | break; 115 | default: 116 | Log.e(TAG, "Unknown MQTT connection state: " + status); 117 | return; 118 | } 119 | } 120 | }; 121 | mIotMqttManager.connect(mAWSCredential, mqttClientStatusCallback); 122 | 123 | } 124 | 125 | /** 126 | * Disconnect from AWS IoT core. 127 | */ 128 | public void disconnectFromIoT() { 129 | if (mIotMqttManager != null) { 130 | try { 131 | mIotMqttManager.disconnect(); 132 | mMqttConnectionState = MqttConnectionState.MQTT_Disconnected; 133 | } catch (Exception e) { 134 | Log.e(TAG, "MQTT disconnect error: ", e); 135 | } 136 | } 137 | } 138 | 139 | /** 140 | * Publish a message to a specific topic. 141 | * 142 | * @param topic Topic to publish. 143 | * @param qoS QoS. 144 | * @param payload Payload to publish. 145 | */ 146 | public void publishToIoT(final String topic, final AWSIotMqttQos qoS, @NonNull final byte[] payload) { 147 | if (mMqttConnectionState != MqttConnectionState.MQTT_Connected) { 148 | Log.e(TAG, "Cannot publish message to IoT because MQTT connection state" + 149 | " is not connected."); 150 | return; 151 | } 152 | AWSIotMqttMessageDeliveryCallback deliveryCallback = new AWSIotMqttMessageDeliveryCallback() { 153 | @Override 154 | public void statusChanged(MessageDeliveryStatus status, Object userData) { 155 | Log.d(TAG, "Publish msg delivery status: " + status.toString()); 156 | if (status == MessageDeliveryStatus.Success && qoS == AWSIotMqttQos.QOS1) { 157 | sendAckToThing(CustomizedMqttEnvelope.newPublishEnvelope(topic, qoS, payload)); 158 | } 159 | } 160 | }; 161 | try { 162 | Log.i(TAG, "Sending MQTT message to IoT on topic: " + topic 163 | + " message: " + new String(payload)); 164 | mIotMqttManager.publishData(payload, topic, qoS, deliveryCallback, null); 165 | } catch (Exception e) { 166 | Log.e(TAG, "Publish error.", e); 167 | } 168 | } 169 | 170 | /** 171 | * Subscribe to a specific topic. 172 | * 173 | * @param topic Topic to subscribe. 174 | * @param qoS QoS. 175 | */ 176 | public void subscribeToIoT(final String topic, final AWSIotMqttQos qoS) { 177 | if (mMqttConnectionState != MqttConnectionState.MQTT_Connected) { 178 | Log.e(TAG, "Cannot subscribe because MQTT state is not connected."); 179 | return; 180 | } 181 | 182 | try { 183 | Log.i(TAG, "Subscribing to IoT on topic : " + topic); 184 | mIotMqttManager.subscribeToTopic(topic, qoS, new AWSIotMqttNewMessageCallback() { 185 | @Override 186 | public void onMessageArrived(final String topic, final byte[] data) { 187 | try { 188 | Log.i(TAG, " Message arrived on topic: " + topic); 189 | Log.v(TAG, " Message: " + new String(data, "UTF-8")); 190 | CustomizedMqttEnvelope envelope = CustomizedMqttEnvelope.newPublishEnvelope( 191 | topic, qoS, data 192 | ); 193 | publishToThing(envelope); 194 | } catch (UnsupportedEncodingException e) { 195 | Log.e(TAG, "Message encoding error.", e); 196 | } 197 | } 198 | }); 199 | sendAckToThing(CustomizedMqttEnvelope.newSubscribeEnvelope(topic, qoS)); 200 | } catch (Exception e) { 201 | Log.e(TAG, "Subscription error.", e); 202 | } 203 | } 204 | 205 | /** 206 | * Unsubscribe from a specific topic. 207 | * 208 | * @param topic Topic to unsubscribe. 209 | */ 210 | public void unsubscribeToIoT(final String topic) { 211 | if (mMqttConnectionState != MqttConnectionState.MQTT_Connected) { 212 | Log.e(TAG, "Cannot unsubscribe because MQTT state is not connected."); 213 | return; 214 | } 215 | 216 | try { 217 | Log.i(TAG, "UnSubscribing to IoT on topic : " + topic); 218 | mIotMqttManager.unsubscribeTopic(topic); 219 | sendAckToThing(CustomizedMqttEnvelope.newUnsubscribeEnvelope(topic)); 220 | } catch (Exception e) { 221 | Log.e(TAG, "Subscription error.", e); 222 | } 223 | } 224 | 225 | public interface OnConnectionStateListener { 226 | /** 227 | * Called when MQTT connection state changed. 228 | * 229 | * @param thing Customized thing. 230 | * @param state New MQTT connection state. 231 | */ 232 | void onMqttConnectionStateChanged(CustomizedThing thing, MqttConnectionState state); 233 | 234 | /** 235 | * Called when Thing connection state changed. 236 | * 237 | * @param thing Customized thing. 238 | * @param state New thing connection state. 239 | */ 240 | void onThingConnectionStateChanged(CustomizedThing thing, ThingConnectionState state); 241 | } 242 | 243 | /** 244 | * Connect to local device. 245 | */ 246 | public abstract void connectToThing(); 247 | 248 | /** 249 | * Disconnect from local device. 250 | */ 251 | public abstract void disconnectFromThing(); 252 | 253 | protected void setMqttConnectionState(final MqttConnectionState state) { 254 | if (state == mMqttConnectionState) { 255 | return; 256 | } 257 | mMqttConnectionState = state; 258 | if (mOnConnectionStateListener != null) { 259 | mOnConnectionStateListener.onMqttConnectionStateChanged(this, mMqttConnectionState); 260 | } 261 | } 262 | 263 | protected void setThingConnectionState(final ThingConnectionState state) { 264 | if (state == mThingConnectionState) { 265 | return; 266 | } 267 | mThingConnectionState = state; 268 | if (mOnConnectionStateListener != null) { 269 | mOnConnectionStateListener.onThingConnectionStateChanged(this, mThingConnectionState); 270 | } 271 | } 272 | 273 | /** 274 | * Send publish/subscribe/unsubscribe ack back to thing. 275 | * 276 | * @param envelope Message passed when publish/subscribe/unsubscribe. 277 | */ 278 | protected abstract void sendAckToThing(final CustomizedMqttEnvelope envelope); 279 | 280 | /** 281 | * Request to publish message received from cloud to thing. 282 | * 283 | * @param envelope Received message from cloud. 284 | */ 285 | protected abstract void publishToThing(final CustomizedMqttEnvelope envelope); 286 | } 287 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ESP32CustomizedThing.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | import android.bluetooth.BluetoothDevice; 24 | import android.bluetooth.BluetoothGatt; 25 | import android.bluetooth.BluetoothGattCallback; 26 | import android.bluetooth.BluetoothGattCharacteristic; 27 | import android.bluetooth.BluetoothProfile; 28 | import android.content.Context; 29 | import android.os.AsyncTask; 30 | import android.util.Log; 31 | import android.widget.Toast; 32 | 33 | import com.amazonaws.auth.AWSCredentialsProvider; 34 | 35 | import java.util.List; 36 | import java.util.UUID; 37 | 38 | import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread; 39 | 40 | public class ESP32CustomizedThing extends CustomizedThing { 41 | private static final String TAG = "ESP32CustomizedThing"; 42 | public static final String SERVICE_UUID = "000000ee-0000-1000-8000-00805f9b34fb"; 43 | private static final String CHAR_UUID = "0000ee01-0000-1000-8000-00805f9b34fb"; 44 | private static final int ATT_MTU = 64; 45 | private static final int READ_PERIOD_MS = 5000; 46 | private static final UUID mServiceUuid = UUID.fromString(SERVICE_UUID); 47 | private static final UUID mCharUuid = UUID.fromString(CHAR_UUID); 48 | private Context mContext; 49 | private BluetoothDevice mDevice; 50 | private BluetoothGatt mDeviceGatt; 51 | 52 | /** 53 | * Instantiates a new Customized thing. 54 | * 55 | * @param thingId Unique client ID. 56 | * @param brokerEndpoint Broker endpoint. 57 | * @param awsCredentials AWS credentials. 58 | * @param context Context. 59 | * @param bluetoothDevice Bluetooth device. 60 | */ 61 | public ESP32CustomizedThing(String thingId, String brokerEndpoint, AWSCredentialsProvider awsCredentials, Context context, BluetoothDevice bluetoothDevice) { 62 | super(thingId, brokerEndpoint, awsCredentials); 63 | mContext = context; 64 | mDevice = bluetoothDevice; 65 | } 66 | 67 | @Override 68 | public void connectToThing() { 69 | mDeviceGatt = mDevice.connectGatt(mContext, false, new BluetoothGattCallback() { 70 | @Override 71 | public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 72 | switch (newState) { 73 | case BluetoothProfile.STATE_CONNECTED: 74 | setThingConnectionState(ThingConnectionState.Thing_Connected); 75 | gatt.discoverServices(); 76 | break; 77 | case BluetoothProfile.STATE_CONNECTING: 78 | setThingConnectionState(ThingConnectionState.Thing_Connecting); 79 | break; 80 | case BluetoothProfile.STATE_DISCONNECTED: 81 | default: 82 | gatt.close(); 83 | setThingConnectionState(ThingConnectionState.Thing_Disconnected); 84 | } 85 | } 86 | 87 | @Override 88 | public void onServicesDiscovered(BluetoothGatt gatt, int status) { 89 | if (gatt.getService(mServiceUuid) != null) { 90 | gatt.requestMtu(ATT_MTU); 91 | new BleReadTask(ESP32CustomizedThing.this).execute(); 92 | } 93 | } 94 | 95 | @Override 96 | public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 97 | if (status == BluetoothGatt.GATT_SUCCESS) { 98 | MyTLV tlv = new MyTLV(characteristic.getValue()); 99 | final CustomizedMqttEnvelope envelope = tlv.toCustomizedMqttEnvelope(); 100 | if (envelope.envelopeType == CustomizedMqttEnvelope.CustomizedMqttEnvelopeType.Publish) { 101 | new Thread(new Runnable() { 102 | @Override 103 | public void run() { 104 | runOnUiThread(new Runnable() { 105 | @Override 106 | public void run() { 107 | Toast.makeText(mContext, "Received from ESP32: " + new String(envelope.payload), Toast.LENGTH_SHORT).show(); 108 | } 109 | }); 110 | } 111 | }).start(); 112 | publishToIoT(envelope.topic, envelope.qoS, envelope.payload); 113 | } 114 | } 115 | } 116 | 117 | @Override 118 | public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 119 | if (status == BluetoothGatt.GATT_SUCCESS) { 120 | Log.d(TAG, "Sent back to thing: " + new String(characteristic.getValue())); 121 | } 122 | } 123 | 124 | @Override 125 | public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { 126 | super.onMtuChanged(gatt, mtu, status); 127 | Log.d(TAG, "MTU changed to " + mtu); 128 | } 129 | }); 130 | } 131 | 132 | @Override 133 | public void disconnectFromThing() { 134 | mDeviceGatt.disconnect(); 135 | } 136 | 137 | @Override 138 | protected void sendAckToThing(CustomizedMqttEnvelope envelope) { 139 | MyTLV tlv; 140 | 141 | switch (envelope.envelopeType) { 142 | case Publish: 143 | tlv = new MyTLV(MyTLV.TLVType.PUBACK, envelope.payload); 144 | break; 145 | case Subscribe: 146 | tlv = new MyTLV(MyTLV.TLVType.SUBACK, envelope.topic.getBytes()); 147 | break; 148 | case Unsubscribe: 149 | tlv = new MyTLV(MyTLV.TLVType.UNSUBACK, envelope.topic.getBytes()); 150 | break; 151 | default: 152 | return; 153 | } 154 | 155 | BluetoothGattCharacteristic characteristic = ESP32CustomizedThing.this.mDeviceGatt.getService(mServiceUuid).getCharacteristic(mCharUuid); 156 | 157 | characteristic.setValue(tlv.encodedBytesStream); 158 | mDeviceGatt.writeCharacteristic(characteristic); 159 | } 160 | 161 | @Override 162 | protected void publishToThing(CustomizedMqttEnvelope envelope) { 163 | if (envelope.envelopeType != CustomizedMqttEnvelope.CustomizedMqttEnvelopeType.Publish) { 164 | Log.e(TAG, "Unexpected message type"); 165 | return; 166 | } 167 | 168 | MyTLV tlv = new MyTLV(envelope); 169 | BluetoothGattCharacteristic characteristic = ESP32CustomizedThing.this.mDeviceGatt.getService(mServiceUuid).getCharacteristic(mCharUuid); 170 | 171 | characteristic.setValue(tlv.encodedBytesStream); 172 | mDeviceGatt.writeCharacteristic(characteristic); 173 | } 174 | 175 | private static class BleReadTask extends AsyncTask { 176 | 177 | private ESP32CustomizedThing mThing; 178 | 179 | public BleReadTask(ESP32CustomizedThing thing) { 180 | super(); 181 | mThing = thing; 182 | } 183 | 184 | @Override 185 | protected String doInBackground(String... strings) { 186 | while (mThing.getThingConnectionState() == ThingConnectionState.Thing_Connected) { 187 | try { 188 | Thread.sleep(READ_PERIOD_MS); 189 | } catch (InterruptedException e) { 190 | e.printStackTrace(); 191 | } 192 | List characteristics = mThing.mDeviceGatt.getService(mServiceUuid).getCharacteristics(); 193 | if (characteristics.size() == 0) { 194 | Log.e("TAG", "Can't find characteristic"); 195 | continue; 196 | } 197 | if (!mThing.mDeviceGatt.readCharacteristic(characteristics.get(0))) { 198 | Log.e("TAG", "Read characteristic error"); 199 | } 200 | } 201 | return null; 202 | } 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | import android.Manifest; 24 | import android.os.Bundle; 25 | import android.os.Handler; 26 | import android.os.HandlerThread; 27 | import android.util.Log; 28 | 29 | import androidx.appcompat.app.AppCompatActivity; 30 | 31 | import com.amazonaws.awsiotproxy.ui.main.MainFragment; 32 | import com.amazonaws.mobile.client.AWSMobileClient; 33 | import com.amazonaws.mobile.client.Callback; 34 | import com.amazonaws.mobile.client.SignInUIOptions; 35 | import com.amazonaws.mobile.client.UserStateDetails; 36 | import com.amazonaws.regions.Region; 37 | import com.amazonaws.services.iot.AWSIotClient; 38 | import com.amazonaws.services.iot.model.AttachPolicyRequest; 39 | 40 | import java.util.concurrent.CountDownLatch; 41 | 42 | public class MainActivity extends AppCompatActivity { 43 | private static final String TAG = "MainActivity"; 44 | private HandlerThread mAuthHandlerThread; 45 | private Handler mAuthHandler; 46 | 47 | @Override 48 | protected void onCreate(Bundle savedInstanceState) { 49 | super.onCreate(savedInstanceState); 50 | setContentView(R.layout.main_activity); 51 | if (savedInstanceState == null) { 52 | getSupportFragmentManager().beginTransaction() 53 | .replace(R.id.container, MainFragment.newInstance()) 54 | .commitNow(); 55 | } 56 | if (mAuthHandlerThread == null) { 57 | mAuthHandlerThread = new HandlerThread("SignInThread"); 58 | mAuthHandlerThread.start(); 59 | mAuthHandler = new Handler(mAuthHandlerThread.getLooper()); 60 | } 61 | final CountDownLatch latch = new CountDownLatch(1); 62 | AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback() { 63 | 64 | @Override 65 | public void onResult(UserStateDetails userStateDetails) { 66 | Log.i(TAG, "AWSMobileClient initialization onResult: " + userStateDetails.getUserState()); 67 | latch.countDown(); 68 | } 69 | 70 | @Override 71 | public void onError(Exception e) { 72 | Log.e(TAG, "Initialization error.", e); 73 | } 74 | } 75 | ); 76 | Log.d(TAG, "waiting for AWSMobileClient Initialization"); 77 | try { 78 | latch.await(); 79 | } catch (InterruptedException e) { 80 | e.printStackTrace(); 81 | } 82 | mAuthHandler.post(new Runnable() { 83 | @Override 84 | public void run() { 85 | if (AWSMobileClient.getInstance().isSignedIn()) { 86 | attachPolicy(); 87 | } else { 88 | AWSMobileClient.getInstance().showSignIn( 89 | MainActivity.this, 90 | SignInUIOptions.builder() 91 | .nextActivity(null) 92 | .build(), 93 | new Callback() { 94 | @Override 95 | public void onResult(UserStateDetails result) { 96 | Log.d(TAG, "onResult: " + result.getUserState()); 97 | switch (result.getUserState()) { 98 | case SIGNED_IN: 99 | Log.i(TAG, "logged in!"); 100 | attachPolicy(); 101 | break; 102 | case SIGNED_OUT: 103 | Log.i(TAG, "onResult: User did not choose to sign-in"); 104 | break; 105 | default: 106 | AWSMobileClient.getInstance().signOut(); 107 | break; 108 | } 109 | } 110 | 111 | @Override 112 | public void onError(Exception e) { 113 | Log.e(TAG, "onError: ", e); 114 | } 115 | } 116 | ); 117 | } 118 | } 119 | }); 120 | requestPermissions(new String[]{Manifest. 121 | permission.ACCESS_FINE_LOCATION}, 1); 122 | } 123 | 124 | private void attachPolicy() { 125 | AWSIotClient awsIotClient = new AWSIotClient(AWSMobileClient.getInstance()); 126 | awsIotClient.setRegion(Region.getRegion(ProxyConfig.region)); 127 | 128 | AttachPolicyRequest attachPolicyRequest = new AttachPolicyRequest() 129 | .withPolicyName(ProxyConfig.policy) 130 | .withTarget(AWSMobileClient.getInstance().getIdentityId()); 131 | awsIotClient.attachPolicy(attachPolicyRequest); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/MyDummyCustomizedThing.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | import android.content.Context; 24 | import android.os.Handler; 25 | import android.os.Message; 26 | import android.util.Log; 27 | import android.widget.Toast; 28 | 29 | import androidx.annotation.NonNull; 30 | 31 | import com.amazonaws.auth.AWSCredentialsProvider; 32 | 33 | import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants; 34 | 35 | import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread; 36 | 37 | public class MyDummyCustomizedThing extends CustomizedThing { 38 | private static final String TAG = "MyDummyCustomizedThing"; 39 | private static final int TO_APP = 0; 40 | private static final int TO_DEVICE = 1; 41 | private Handler mThingHandler; 42 | private Thread mDummyDeviceThread; 43 | private Context mContext; 44 | 45 | /** 46 | * Instantiates a new Dummy Customized thing. 47 | * 48 | * @param thingId Unique client ID. 49 | * @param brokerEndpoint Broker endpoint. 50 | * @param awsCredentials AWS credentials. 51 | * @param context Activity context. 52 | */ 53 | public MyDummyCustomizedThing(final String thingId, String brokerEndpoint, AWSCredentialsProvider awsCredentials, Context context) { 54 | super(thingId, brokerEndpoint, awsCredentials); 55 | this.mContext = context; 56 | if (mDummyDeviceThread == null) { 57 | mThingHandler = new Handler(new Handler.Callback() { 58 | @Override 59 | public boolean handleMessage(@NonNull Message msg) { 60 | byte[] encodedBytes = (byte[]) msg.obj; 61 | MyTLV tlvMsg = new MyTLV(encodedBytes); 62 | if (msg.what == TO_APP && getMqttConnectionState() == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) { 63 | CustomizedMqttEnvelope envelope = tlvMsg.toCustomizedMqttEnvelope(); 64 | /** 65 | * Dummy device to app 66 | */ 67 | if (envelope == null) { 68 | return false; 69 | } 70 | switch (envelope.envelopeType) { 71 | case Publish: 72 | publishToIoT(envelope.topic, envelope.qoS, envelope.payload); 73 | break; 74 | default: 75 | break; 76 | } 77 | } else if (msg.what == TO_DEVICE) { 78 | /** 79 | * App tp Dummy device 80 | */ 81 | Log.i(TAG, "Dummy device received" + new String((byte[]) msg.obj)); 82 | } 83 | return false; 84 | } 85 | }); 86 | } 87 | } 88 | 89 | public void runDevice() { 90 | if (mDummyDeviceThread != null) { 91 | return; 92 | } 93 | mDummyDeviceThread = new Thread(new Runnable() { 94 | @Override 95 | public void run() { 96 | while (getThingConnectionState() == ThingConnectionState.Thing_Connected) { 97 | if (getMqttConnectionState() != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) { 98 | try { 99 | Thread.sleep(1000); 100 | } catch (InterruptedException e) { 101 | e.printStackTrace(); 102 | } 103 | continue; 104 | } 105 | Message msg = Message.obtain(); 106 | msg.what = TO_APP; 107 | msg.obj = (Object) (new MyTLV(MyTLV.TLVType.PUB, 108 | "[proxy/test]0{name:dummy;temp:25.56;bat:98%}".getBytes())).encodedBytesStream; 109 | mThingHandler.sendMessage(msg); 110 | /** 111 | * This dummy device will request publish to cloud every 5000ms 112 | */ 113 | try { 114 | Thread.sleep(5000); 115 | } catch (InterruptedException e) { 116 | e.printStackTrace(); 117 | } 118 | } 119 | } 120 | }); 121 | mDummyDeviceThread.start(); 122 | } 123 | 124 | @Override 125 | public void connectToThing() { 126 | setThingConnectionState(ThingConnectionState.Thing_Connected); 127 | runDevice(); 128 | Log.i(TAG, "Connected to dummy device"); 129 | } 130 | 131 | @Override 132 | public void disconnectFromThing() { 133 | setThingConnectionState(ThingConnectionState.Thing_Disconnected); 134 | Log.i(TAG, "Disconnected from dummy device"); 135 | } 136 | 137 | @Override 138 | protected void sendAckToThing(final CustomizedMqttEnvelope message) { 139 | /** 140 | * Here we implement the adapter which transfer ACK message into dummy local 141 | * protocol(Customized TLV) 142 | */ 143 | MyTLV tlv; 144 | switch (message.envelopeType) { 145 | case Publish: 146 | tlv = new MyTLV(MyTLV.TLVType.PUBACK, message.payload); 147 | break; 148 | case Subscribe: 149 | tlv = new MyTLV(MyTLV.TLVType.SUBACK, message.topic.getBytes()); 150 | break; 151 | case Unsubscribe: 152 | tlv = new MyTLV(MyTLV.TLVType.UNSUBACK, message.topic.getBytes()); 153 | break; 154 | default: 155 | Log.e(TAG, "Unexpected message type"); 156 | return; 157 | } 158 | sendDataToThing(tlv.encodedBytesStream); 159 | } 160 | 161 | @Override 162 | protected void publishToThing(final CustomizedMqttEnvelope message) { 163 | /** 164 | * Here we implement the adapter which transfer CustomizedMqttEnvelope into 165 | * dummy local protocol(Customized TLV) 166 | */ 167 | if (message.envelopeType != CustomizedMqttEnvelope.CustomizedMqttEnvelopeType.Publish) { 168 | Log.e(TAG, "Unexpected message type"); 169 | return; 170 | } 171 | MyTLV tlv = new MyTLV(message); 172 | sendDataToThing(tlv.encodedBytesStream); 173 | new Thread(new Runnable() { 174 | @Override 175 | public void run() { 176 | runOnUiThread(new Runnable() { 177 | @Override 178 | public void run() { 179 | Toast.makeText(mContext, 180 | "Receive Topic:" + message.topic + "\n" + new String(message.payload), 181 | Toast.LENGTH_SHORT).show(); 182 | } 183 | }); 184 | } 185 | }).start(); 186 | } 187 | 188 | private void sendDataToThing(final byte[] data) { 189 | /** 190 | * Here we implement the logic to send encoded bytes stream back to thing. 191 | */ 192 | Message msg = Message.obtain(); 193 | msg.what = TO_DEVICE; 194 | msg.obj = (Object) data; 195 | mThingHandler.sendMessage(msg); 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/MyTLV.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | import android.util.Log; 24 | 25 | import androidx.annotation.NonNull; 26 | 27 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos; 28 | import com.google.gson.JsonObject; 29 | 30 | import java.util.Locale; 31 | 32 | /** 33 | * This is an example to implement private local protocol. 34 | */ 35 | public class MyTLV { 36 | private static final String TAG = "MyTLV"; 37 | private static final int HEAD_SIZE = 2; 38 | private TLVType mType; 39 | private int mLength; 40 | private byte[] mValue; 41 | public byte[] encodedBytesStream; 42 | 43 | public enum TLVType { 44 | INVALID, 45 | PUBACK, 46 | SUBACK, 47 | UNSUBACK, 48 | PUB, 49 | SUB, 50 | UNSUB, 51 | } 52 | 53 | public MyTLV(TLVType type, byte[] value) { 54 | this.mType = type; 55 | this.mValue = value; 56 | this.mLength = HEAD_SIZE + value.length; 57 | this.encode(); 58 | } 59 | 60 | /** 61 | * Base on encoded bytes stream from device generates the TLV package to app. 62 | * 63 | * @param encodedBytesStream Encoded bytes stream. 64 | */ 65 | public MyTLV(@NonNull byte[] encodedBytesStream) { 66 | this.encodedBytesStream = encodedBytesStream; 67 | this.decode(); 68 | } 69 | 70 | /** 71 | * Base on the received publish message generates the TLV package send to device. 72 | * 73 | * @param envelope Mqtt message. 74 | */ 75 | public MyTLV(CustomizedMqttEnvelope envelope) { 76 | if (envelope.envelopeType != CustomizedMqttEnvelope.CustomizedMqttEnvelopeType.Publish) { 77 | mType = TLVType.INVALID; 78 | return; 79 | } 80 | String raw; 81 | raw = String.format(Locale.US, "[%s]%d{%s}", envelope.topic, envelope.qoS.ordinal(), new String(envelope.payload)); 82 | 83 | mType = TLVType.PUB; 84 | mValue = raw.getBytes(); 85 | mLength = HEAD_SIZE + mValue.length; 86 | this.encode(); 87 | } 88 | 89 | public CustomizedMqttEnvelope toCustomizedMqttEnvelope() { 90 | 91 | if (mType != TLVType.PUB && mType != TLVType.SUB && mType != TLVType.UNSUB) { 92 | return null; 93 | } 94 | 95 | String raw = new String(mValue); 96 | String topic = raw.substring(raw.indexOf("[") + 1, raw.indexOf("]")); 97 | JsonObject jsonObject = new JsonObject(); 98 | CustomizedMqttEnvelope.CustomizedMqttEnvelopeType msgType; 99 | AWSIotMqttQos qos; 100 | 101 | try { 102 | int qosInt = Integer.parseInt(raw.substring(raw.indexOf("]") + 1, raw.indexOf("]") + 2)); 103 | /* Here we made json string base on raw payload */ 104 | String[] pairs = (raw.substring(raw.indexOf("{") + 1, raw.indexOf("}"))).split(";"); 105 | for (String pair : pairs) { 106 | String[] keyValue = pair.split(":"); 107 | jsonObject.addProperty(keyValue[0], keyValue[1]); 108 | } 109 | qos = AWSIotMqttQos.values()[qosInt]; 110 | } catch (Exception e) { 111 | qos = AWSIotMqttQos.QOS0; 112 | } 113 | 114 | switch (mType) { 115 | case PUB: 116 | return CustomizedMqttEnvelope.newPublishEnvelope(topic, qos, jsonObject.toString().getBytes()); 117 | case SUB: 118 | return CustomizedMqttEnvelope.newSubscribeEnvelope(topic, qos); 119 | case UNSUB: 120 | return CustomizedMqttEnvelope.newUnsubscribeEnvelope(topic); 121 | default: 122 | return null; 123 | } 124 | } 125 | 126 | private void encode() { 127 | try { 128 | encodedBytesStream = new byte[mLength]; 129 | encodedBytesStream[0] = (byte) (mType.ordinal()); 130 | encodedBytesStream[1] = (byte) (mLength); 131 | System.arraycopy(mValue, 0, encodedBytesStream, HEAD_SIZE, mValue.length); 132 | } catch (Exception e) { 133 | Log.e(TAG, "encode failed"); 134 | mType = TLVType.INVALID; 135 | } 136 | } 137 | 138 | private void decode() { 139 | try { 140 | mType = TLVType.values()[encodedBytesStream[0]]; 141 | mLength = encodedBytesStream.length; 142 | mValue = new byte[mLength - HEAD_SIZE]; 143 | System.arraycopy(encodedBytesStream, HEAD_SIZE, mValue, 0, mValue.length); 144 | } catch (Exception e) { 145 | Log.e(TAG, "decode failed"); 146 | mType = TLVType.INVALID; 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ProxyConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy; 22 | 23 | public final class ProxyConfig { 24 | public static final String thingId = "Thing Id"; 25 | public static final String brokerEndpoint = "Broker Endpoint"; 26 | public static final String policy = "Policy Name"; 27 | public static final String region = "AWS Region"; 28 | } -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ui/main/DevicesFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy.ui.main; 22 | 23 | import android.bluetooth.BluetoothAdapter; 24 | import android.bluetooth.BluetoothDevice; 25 | import android.bluetooth.BluetoothManager; 26 | import android.bluetooth.le.ScanCallback; 27 | import android.bluetooth.le.ScanFilter; 28 | import android.bluetooth.le.ScanResult; 29 | import android.bluetooth.le.ScanSettings; 30 | import android.content.Context; 31 | import android.content.Intent; 32 | import android.graphics.Color; 33 | import android.os.AsyncTask; 34 | import android.os.Bundle; 35 | 36 | import androidx.annotation.NonNull; 37 | import androidx.annotation.Nullable; 38 | import androidx.core.content.ContextCompat; 39 | import androidx.fragment.app.Fragment; 40 | 41 | import android.os.ParcelUuid; 42 | import android.view.LayoutInflater; 43 | import android.view.View; 44 | import android.view.ViewGroup; 45 | import android.widget.ProgressBar; 46 | import android.widget.TextView; 47 | import android.widget.Toast; 48 | 49 | import com.amazonaws.awsiotproxy.CustomizedThing; 50 | import com.amazonaws.awsiotproxy.ESP32CustomizedThing; 51 | import com.amazonaws.awsiotproxy.MyDummyCustomizedThing; 52 | import com.amazonaws.awsiotproxy.ProxyConfig; 53 | import com.amazonaws.awsiotproxy.R; 54 | import com.amazonaws.mobile.client.AWSMobileClient; 55 | 56 | import androidx.recyclerview.widget.DefaultItemAnimator; 57 | import androidx.recyclerview.widget.LinearLayoutManager; 58 | import androidx.recyclerview.widget.RecyclerView; 59 | import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; 60 | 61 | import java.lang.ref.WeakReference; 62 | import java.util.ArrayList; 63 | import java.util.List; 64 | 65 | import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants; 66 | 67 | import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread; 68 | 69 | 70 | public class DevicesFragment extends Fragment { 71 | 72 | private ArrayList mDevicesList = new ArrayList<>(); 73 | private SwipeRefreshLayout mSwipeRefreshLayout; 74 | private RecyclerView mDevicesRecyclerView; 75 | private DevicesRecyclerViewAdapter mDevicesRecyclerViewAdapter; 76 | private ArrayList mListeners = new ArrayList<>(); 77 | private BluetoothAdapter mBluetoothAdapter; 78 | private BluetoothManager mBluetoothManager; 79 | private CustomizedThing.OnConnectionStateListener mOnConnectionStateListener; 80 | 81 | public static DevicesFragment newInstance() { 82 | return new DevicesFragment(); 83 | } 84 | 85 | @Override 86 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 87 | Bundle savedInstanceState) { 88 | return inflater.inflate(R.layout.devices_fragment, container, false); 89 | } 90 | 91 | @Override 92 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 93 | super.onActivityCreated(savedInstanceState); 94 | mDevicesRecyclerView = getView().findViewById(R.id.devicesRecyclerView); 95 | mDevicesRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 96 | mDevicesRecyclerViewAdapter = new DevicesRecyclerViewAdapter(mDevicesList); 97 | mDevicesRecyclerView.setAdapter(mDevicesRecyclerViewAdapter); 98 | mDevicesRecyclerView.setItemAnimator(new DefaultItemAnimator()); 99 | mBluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE); 100 | mBluetoothAdapter = mBluetoothManager.getAdapter(); 101 | mSwipeRefreshLayout = getView().findViewById(R.id.devices); 102 | mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 103 | @Override 104 | public void onRefresh() { 105 | if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { 106 | Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 107 | startActivity(enableBtIntent); 108 | mSwipeRefreshLayout.setRefreshing(false); 109 | return; 110 | } 111 | new BleScanTask((DevicesFragment) getFragmentManager().getFragments().get(0)).execute(); 112 | } 113 | }); 114 | mOnConnectionStateListener = new CustomizedThing.OnConnectionStateListener() { 115 | @Override 116 | public void onMqttConnectionStateChanged(CustomizedThing thing, AmazonFreeRTOSConstants.MqttConnectionState state) { 117 | DevicesRecyclerViewAdapter.ViewHolder viewHolder = getViewHolderByThingId(thing.getThingId()); 118 | if (state == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) { 119 | if (viewHolder != null) { 120 | viewHolder.progressBar.setVisibility(View.INVISIBLE); 121 | viewHolder.deviceNameTextView.setBackgroundColor(Color.GREEN); 122 | } 123 | } 124 | if (state == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) { 125 | if (viewHolder != null) { 126 | viewHolder.progressBar.setVisibility(View.INVISIBLE); 127 | viewHolder.deviceNameTextView.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent)); 128 | thing.disconnectFromIoT(); 129 | } 130 | } 131 | } 132 | 133 | @Override 134 | public void onThingConnectionStateChanged(CustomizedThing thing, CustomizedThing.ThingConnectionState state) { 135 | if (state == CustomizedThing.ThingConnectionState.Thing_Connected) { 136 | makeToast("Thing Connected, Connecting to AWS"); 137 | thing.connectToIoT(); 138 | } 139 | if (state == CustomizedThing.ThingConnectionState.Thing_Disconnected) { 140 | makeToast("Thing Disconnected, Disconnecting from AWS"); 141 | thing.disconnectFromIoT(); 142 | } 143 | } 144 | }; 145 | /** 146 | * Here we created a dummy devices 147 | */ 148 | MyDummyCustomizedThing dummyThing = new MyDummyCustomizedThing(ProxyConfig.thingId, 149 | ProxyConfig.brokerEndpoint, 150 | AWSMobileClient.getInstance(), getActivity()); 151 | dummyThing.setOnConnectionStateListener(mOnConnectionStateListener); 152 | mDevicesList.add(dummyThing); 153 | makeToast("Swipe down to scan BLE devices"); 154 | } 155 | 156 | public void addThingChangeListener(ThingChangeListener listener) { 157 | if (listener != null && !mListeners.contains(listener)) { 158 | mListeners.add(listener); 159 | } 160 | } 161 | 162 | public void removeThingChangeListener(ThingChangeListener listener) { 163 | if (listener != null) { 164 | mListeners.remove(listener); 165 | } 166 | } 167 | 168 | private void notifyThingChangeListener(CustomizedThing thing) { 169 | for (ThingChangeListener listener : mListeners) { 170 | if (listener != null) { 171 | listener.onDevicesChanged(thing); 172 | } 173 | } 174 | } 175 | 176 | private void addNewEsp32(BluetoothDevice bluetoothDevice) { 177 | for (CustomizedThing existThing : mDevicesList) { 178 | if (bluetoothDevice.getName().equals(existThing.getThingId())) { 179 | return; 180 | } 181 | } 182 | ESP32CustomizedThing newThing = new ESP32CustomizedThing(bluetoothDevice.getName(), 183 | ProxyConfig.brokerEndpoint, AWSMobileClient.getInstance(), getContext(), bluetoothDevice); 184 | newThing.setOnConnectionStateListener(mOnConnectionStateListener); 185 | mDevicesList.add(newThing); 186 | mDevicesRecyclerViewAdapter.notifyDataSetChanged(); 187 | } 188 | 189 | private DevicesRecyclerViewAdapter.ViewHolder getViewHolderByThingId(final String thingId) { 190 | int pos = 0; 191 | for (pos = 0; pos < mDevicesList.size(); ++pos) { 192 | if (mDevicesList.get(pos).getThingId() == thingId) { 193 | return (DevicesRecyclerViewAdapter.ViewHolder) mDevicesRecyclerView.findViewHolderForAdapterPosition(pos); 194 | } 195 | } 196 | return null; 197 | } 198 | 199 | private void makeToast(final String msg) { 200 | new Thread(new Runnable() { 201 | @Override 202 | public void run() { 203 | runOnUiThread(new Runnable() { 204 | @Override 205 | public void run() { 206 | Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); 207 | } 208 | }); 209 | } 210 | }).start(); 211 | } 212 | 213 | public class DevicesRecyclerViewAdapter extends RecyclerView.Adapter { 214 | 215 | private ArrayList mDevicesList; 216 | 217 | public class ViewHolder extends RecyclerView.ViewHolder { 218 | TextView deviceNameTextView; 219 | ProgressBar progressBar; 220 | 221 | public ViewHolder(View view) { 222 | super(view); 223 | deviceNameTextView = view.findViewById(R.id.deviceNameTextView); 224 | progressBar = view.findViewById(R.id.progressBar); 225 | } 226 | } 227 | 228 | public DevicesRecyclerViewAdapter(ArrayList devicesList) { 229 | this.mDevicesList = devicesList; 230 | } 231 | 232 | @NonNull 233 | @Override 234 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 235 | View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.devices_list_layout, parent, false); 236 | ViewHolder viewHolder = new ViewHolder(view); 237 | view.setOnClickListener(new View.OnClickListener() { 238 | @Override 239 | public void onClick(View v) { 240 | CustomizedThing device = mDevicesList.get(mDevicesRecyclerView.getChildLayoutPosition(v)); 241 | if (device.getThingConnectionState() != CustomizedThing.ThingConnectionState.Thing_Connected) { 242 | makeToast("Connecting To Thing"); 243 | ((ViewHolder) mDevicesRecyclerView.getChildViewHolder(v)).progressBar.setVisibility(View.VISIBLE); 244 | device.connectToThing(); 245 | } else { 246 | makeToast("Disconnecting From Thing"); 247 | device.disconnectFromThing(); 248 | } 249 | notifyThingChangeListener(device); 250 | } 251 | }); 252 | return viewHolder; 253 | } 254 | 255 | @Override 256 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) { 257 | holder.deviceNameTextView.setText(mDevicesList.get(position).getThingId()); 258 | holder.progressBar.setVisibility(View.INVISIBLE); 259 | } 260 | 261 | @Override 262 | public int getItemCount() { 263 | return mDevicesList.size(); 264 | } 265 | } 266 | 267 | private static class BleScanTask extends AsyncTask { 268 | 269 | private WeakReference mFragmentReference; 270 | private static final int SCAN_PERIOD_MS = 3000; 271 | private ScanCallback mScanCallback; 272 | 273 | public BleScanTask(DevicesFragment fragment) { 274 | super(); 275 | mFragmentReference = new WeakReference<>(fragment); 276 | mScanCallback = new ScanCallback() { 277 | @Override 278 | public void onScanResult(int callbackType, ScanResult result) { 279 | super.onScanResult(callbackType, result); 280 | if (result != null) { 281 | mFragmentReference.get().addNewEsp32(result.getDevice()); 282 | } 283 | } 284 | }; 285 | } 286 | 287 | @Override 288 | protected String doInBackground(String... strings) { 289 | ParcelUuid parcelUuidMask = ParcelUuid.fromString(ESP32CustomizedThing.SERVICE_UUID); 290 | List filters = new ArrayList<>(); 291 | ScanFilter.Builder filterBuilder = new ScanFilter.Builder().setServiceUuid(parcelUuidMask); 292 | filters.add(filterBuilder.build()); 293 | ScanSettings.Builder settingBuilder = new ScanSettings.Builder(); 294 | mFragmentReference.get().mBluetoothAdapter.getBluetoothLeScanner().startScan(filters, settingBuilder.build(), mScanCallback); 295 | try { 296 | Thread.sleep(SCAN_PERIOD_MS); 297 | } catch (InterruptedException e) { 298 | e.printStackTrace(); 299 | } 300 | mFragmentReference.get().mBluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback); 301 | return null; 302 | } 303 | 304 | @Override 305 | protected void onPostExecute(String s) { 306 | super.onPostExecute(s); 307 | mFragmentReference.get().mSwipeRefreshLayout.setRefreshing(false); 308 | } 309 | } 310 | 311 | } 312 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ui/main/MainFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy.ui.main; 22 | 23 | import androidx.fragment.app.FragmentManager; 24 | import androidx.fragment.app.FragmentPagerAdapter; 25 | 26 | import android.os.Bundle; 27 | 28 | import androidx.annotation.NonNull; 29 | import androidx.annotation.Nullable; 30 | import androidx.fragment.app.Fragment; 31 | import androidx.viewpager.widget.ViewPager; 32 | 33 | import android.view.LayoutInflater; 34 | import android.view.View; 35 | import android.view.ViewGroup; 36 | 37 | import com.amazonaws.awsiotproxy.R; 38 | import com.google.android.material.tabs.TabLayout; 39 | 40 | import java.util.ArrayList; 41 | 42 | public class MainFragment extends Fragment { 43 | 44 | public static MainFragment newInstance() { 45 | return new MainFragment(); 46 | } 47 | 48 | private ArrayList mFragmentList = new ArrayList<>(); 49 | private String[] mTabString = {"DEVICES", "PUBLISH", "SUBSCRIBE"}; 50 | 51 | @Nullable 52 | @Override 53 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 54 | @Nullable Bundle savedInstanceState) { 55 | return inflater.inflate(R.layout.main_fragment, container, false); 56 | } 57 | 58 | @Override 59 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 60 | super.onActivityCreated(savedInstanceState); 61 | TabLayout tabLayout = getView().findViewById(R.id.tabLayout); 62 | ViewPager viewPager = getView().findViewById(R.id.viewPager); 63 | viewPager.setOffscreenPageLimit(mTabString.length - 1); 64 | MainFragmentAdapter fragmentAdapter = new MainFragmentAdapter(getChildFragmentManager()); 65 | 66 | for (String string : mTabString) { 67 | tabLayout.addTab(tabLayout.newTab().setText(string)); 68 | } 69 | mFragmentList.add(DevicesFragment.newInstance()); 70 | mFragmentList.add(PublishFragment.newInstance()); 71 | mFragmentList.add(SubscribeFragment.newInstance()); 72 | 73 | viewPager.setAdapter(fragmentAdapter); 74 | tabLayout.setupWithViewPager(viewPager); 75 | } 76 | 77 | public class MainFragmentAdapter extends FragmentPagerAdapter { 78 | public MainFragmentAdapter(FragmentManager fm) { 79 | super(fm); 80 | } 81 | 82 | @Override 83 | public int getCount() { 84 | return mFragmentList.size(); 85 | } 86 | 87 | @Override 88 | public Fragment getItem(int position) { 89 | return mFragmentList.get(position); 90 | } 91 | 92 | @Nullable 93 | @Override 94 | public CharSequence getPageTitle(int position) { 95 | return mTabString[position]; 96 | } 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ui/main/PublishFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy.ui.main; 22 | 23 | import android.os.Bundle; 24 | import android.view.LayoutInflater; 25 | import android.view.View; 26 | import android.view.ViewGroup; 27 | import android.widget.Button; 28 | import android.widget.RadioButton; 29 | import android.widget.RadioGroup; 30 | import android.widget.Toast; 31 | 32 | import androidx.annotation.NonNull; 33 | import androidx.annotation.Nullable; 34 | import androidx.fragment.app.Fragment; 35 | 36 | import com.amazonaws.awsiotproxy.CustomizedThing; 37 | import com.amazonaws.awsiotproxy.R; 38 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos; 39 | import com.google.android.material.textfield.TextInputLayout; 40 | 41 | import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants; 42 | 43 | public class PublishFragment extends Fragment implements ThingChangeListener { 44 | 45 | private Button mButtonPublish; 46 | private CustomizedThing mThing; 47 | private TextInputLayout mTopicInputLayout; 48 | private TextInputLayout mPayloadInputLayout; 49 | private RadioGroup mQosRadioGroup; 50 | 51 | public static PublishFragment newInstance() { 52 | return new PublishFragment(); 53 | } 54 | 55 | @Override 56 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 57 | @Nullable Bundle savedInstanceState) { 58 | return inflater.inflate(R.layout.publish_fragment, container, false); 59 | } 60 | 61 | @Override 62 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 63 | super.onActivityCreated(savedInstanceState); 64 | mTopicInputLayout = getView().findViewById(R.id.pubTopic); 65 | mPayloadInputLayout = getView().findViewById(R.id.pubPayload); 66 | mQosRadioGroup = getView().findViewById(R.id.pubQoSRadioGroup); 67 | 68 | mButtonPublish = getView().findViewById(R.id.buttonPublish); 69 | mButtonPublish.setOnClickListener(new View.OnClickListener() { 70 | @Override 71 | public void onClick(View v) { 72 | if (mThing != null && mThing.getMqttConnectionState() == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) { 73 | RadioButton selectedButton = getView().findViewById(mQosRadioGroup.getCheckedRadioButtonId()); 74 | int selectedIndex = mQosRadioGroup.indexOfChild(selectedButton); 75 | AWSIotMqttQos qos = selectedIndex == 0 ? AWSIotMqttQos.QOS0 : AWSIotMqttQos.QOS1; 76 | 77 | String topic = mTopicInputLayout.getEditText().getText().toString(); 78 | String payload = mPayloadInputLayout.getEditText().getText().toString(); 79 | 80 | mThing.publishToIoT(topic, qos, payload.getBytes()); 81 | Toast.makeText(getActivity(), "Published", Toast.LENGTH_SHORT).show(); 82 | } else { 83 | Toast.makeText(getActivity(), "Not Connected", Toast.LENGTH_SHORT).show(); 84 | } 85 | } 86 | }); 87 | ((DevicesFragment) getFragmentManager().getFragments().get(0)).addThingChangeListener(this); 88 | } 89 | 90 | 91 | @Override 92 | public void onDevicesChanged(CustomizedThing thing) { 93 | mThing = thing; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ui/main/SubscribeFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy.ui.main; 22 | 23 | import android.os.Bundle; 24 | import android.view.LayoutInflater; 25 | import android.view.View; 26 | import android.view.ViewGroup; 27 | import android.widget.Button; 28 | import android.widget.RadioButton; 29 | import android.widget.RadioGroup; 30 | import android.widget.Toast; 31 | 32 | import androidx.annotation.NonNull; 33 | import androidx.annotation.Nullable; 34 | import androidx.fragment.app.Fragment; 35 | 36 | import com.amazonaws.awsiotproxy.CustomizedThing; 37 | import com.amazonaws.awsiotproxy.R; 38 | import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos; 39 | import com.google.android.material.textfield.TextInputLayout; 40 | 41 | import software.amazon.freertos.amazonfreertossdk.AmazonFreeRTOSConstants; 42 | 43 | public class SubscribeFragment extends Fragment implements ThingChangeListener { 44 | 45 | private Button mButtonSubscribe; 46 | private Button mButtonUnsubscribe; 47 | private CustomizedThing mThing; 48 | private TextInputLayout mTopicInputLayout; 49 | private RadioGroup mQosRadioGroup; 50 | private View.OnClickListener mClickListener; 51 | 52 | public static SubscribeFragment newInstance() { 53 | return new SubscribeFragment(); 54 | } 55 | 56 | @Override 57 | public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 58 | @Nullable Bundle savedInstanceState) { 59 | return inflater.inflate(R.layout.subscribe_fragment, container, false); 60 | } 61 | 62 | @Override 63 | public void onActivityCreated(@Nullable Bundle savedInstanceState) { 64 | super.onActivityCreated(savedInstanceState); 65 | mTopicInputLayout = getView().findViewById(R.id.subTopic); 66 | mQosRadioGroup = getView().findViewById(R.id.subQoSRadioGroup); 67 | 68 | mClickListener = new View.OnClickListener() { 69 | @Override 70 | public void onClick(View v) { 71 | if (mThing != null && mThing.getMqttConnectionState() == AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Connected) { 72 | RadioButton selectedButton = getView().findViewById(mQosRadioGroup.getCheckedRadioButtonId()); 73 | int selectedIndex = mQosRadioGroup.indexOfChild(selectedButton); 74 | AWSIotMqttQos qos = selectedIndex == 0 ? AWSIotMqttQos.QOS0 : AWSIotMqttQos.QOS1; 75 | 76 | String topic = mTopicInputLayout.getEditText().getText().toString(); 77 | 78 | if (((Button) v).getId() == R.id.buttonSubscribe) { 79 | mThing.subscribeToIoT(topic, qos); 80 | Toast.makeText(getActivity(), "Subscribed", Toast.LENGTH_SHORT).show(); 81 | } else if (((Button) v).getId() == R.id.buttonUnsubscribe) { 82 | mThing.unsubscribeToIoT(topic); 83 | Toast.makeText(getActivity(), "Unsubscribed", Toast.LENGTH_SHORT).show(); 84 | } 85 | } else { 86 | Toast.makeText(getActivity(), "Not Connected", Toast.LENGTH_SHORT).show(); 87 | } 88 | } 89 | }; 90 | 91 | mButtonSubscribe = getView().findViewById(R.id.buttonSubscribe); 92 | mButtonSubscribe.setOnClickListener(mClickListener); 93 | 94 | mButtonUnsubscribe = getView().findViewById(R.id.buttonUnsubscribe); 95 | mButtonUnsubscribe.setOnClickListener(mClickListener); 96 | 97 | ((DevicesFragment) getFragmentManager().getFragments().get(0)).addThingChangeListener(this); 98 | } 99 | 100 | @Override 101 | public void onDevicesChanged(CustomizedThing thing) { 102 | mThing = thing; 103 | } 104 | } 105 | 106 | -------------------------------------------------------------------------------- /app/src/main/java/com/amazonaws/awsiotproxy/ui/main/ThingChangeListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * * SPDX-License-Identifier: MIT-0 5 | * * 6 | * * Permission is hereby granted, free of charge, to any person obtaining a copy of this 7 | * * software and associated documentation files (the "Software"), to deal in the Software 8 | * * without restriction, including without limitation the rights to use, copy, modify, 9 | * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 10 | * * permit persons to whom the Software is furnished to do so. 11 | * * 12 | * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 13 | * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 14 | * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 15 | * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 16 | * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 17 | * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 18 | * 19 | */ 20 | 21 | package com.amazonaws.awsiotproxy.ui.main; 22 | 23 | import com.amazonaws.awsiotproxy.CustomizedThing; 24 | 25 | public interface ThingChangeListener { 26 | void onDevicesChanged(CustomizedThing thing); 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/devices_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 29 | 30 | 31 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /app/src/main/res/layout/devices_list_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 26 | 27 | 32 | 33 | 39 | 40 | -------------------------------------------------------------------------------- /app/src/main/res/layout/main_activity.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 28 | -------------------------------------------------------------------------------- /app/src/main/res/layout/main_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 29 | 30 | 35 | 36 | 37 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /app/src/main/res/layout/publish_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 29 | 30 | 38 | 39 | 43 | 44 | 45 | 53 | 54 | 58 | 59 | 60 | 70 | 71 | 76 | 77 | 82 | 83 | 84 | 85 |