commit 1cc6ff0b72be554a6101a024c08a7008b7ba8e3a Author: Kapil Date: Tue Apr 23 14:58:57 2019 +0530 BLE application for LAMP device version 1.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a8936c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.gradle +/local.properties +/.idea +*.iml +.DS_Store +/build +/key* \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..de94be8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2015, Nordic Semiconductor +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of nRF Toolbox nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..2eddce8 --- /dev/null +++ b/README.md @@ -0,0 +1,134 @@ +# nRF Toolbox + +The nRF Toolbox is a container app that stores your Nordic Semiconductor apps for Bluetooth Low Energy in one location. + +It contains applications demonstrating standard Bluetooth LE profiles: +* **Cycling Speed and Cadence**, +* **Running Speed and Cadence**, +* **Heart Rate Monitor**, +* **Blood Pressure Monitor**, +* **Health Thermometer Monitor**, +* **Glucose Monitor**, +* **Continuous Glucose Monitor**, +* **Proximity Monitor** - supports multiple connections. + +Since version 1.10.0 the *nRF Toolbox* also supports the **Nordic UART Service** which may be used for bidirectional text communication between devices. + +**Note:** To get a smaller version, with only the DFU profile, switch to the *only_dfu* branch (this branch is not maintained anymore, so you have to update it on your own). + +### How to import to Android Studio + +The production version of nRF Toolbox depends on [Android BLE Library](https://github.com/NordicSemiconductor/Android-BLE-Library/) version 1.2.0, which is available on jcenter. + +**Note:** It is recommended to use the *develop* branch of this project. The new version will soon replace the current one. It is using the BLE Library v2 which is now in alpha version. Its API and stability has been improved. + +You may also include the BLE Library as a module. Clone the library project to the same root folder. + +If you are having issue like [#40](https://github.com/NordicSemiconductor/Android-nRF-Toolbox/issues/40) or [#41](https://github.com/NordicSemiconductor/Android-nRF-Toolbox/issues/41), the correct folders structure should look like this: + +![Folders structure](resources/structure.png) + +If you prefer a different name for BLE library, update the [*settings.gradle*](https://github.com/NordicSemiconductor/Android-nRF-Toolbox/blob/master/settings.gradle) file. + +**Note:** The nRF Toolbox app on *develop* branch depends on [Android BLE Common Library](https://github.com/NordicSemiconductor/Android-BLE-Common-Library/), which depends on the BLE Library v2. + +*DFULibrary* folder is optional, as the library is downloaded from jcenter repository automatically. Clone it only when you want to modify the code (not recommended). + +If you get ["Missing Feature Watch" error](https://github.com/NordicSemiconductor/Android-nRF-Toolbox/issues/41#issuecomment-355291101), switch the configuration to 'app'. + +### BleManager and how to use it + +**Note:** This section applies only to BLE Library v.1.x. The API has changed in v.2.x of the library. + +The nRF Toolbox application is a reference design demonstrating how to use the BLE API on Android. The main class responsible for managing connection to a single device is called [BleManager](https://github.com/NordicSemiconductor/Android-BLE-Library/blob/master/ble/src/main/java/no/nordicsemi/android/ble/BleManager.java). Each of the profiles listed above is using this manager and overriding it to add some profile-related functionality. The BleManager sends events using the [BleManagerCallbacks](https://github.com/NordicSemiconductor/Android-BLE-Library/blob/master/ble/src/main/java/no/nordicsemi/android/ble/BleManagerCallbacks.java) interface, which should be implemented by your controller. A profile's BleManager should override the BleManager and implement required methods, that is: +* ```Deque initGatt(BluetoothGatt)``` - method that defines initialization queue +* ```boolean isRequiredServiceSupported(BluetoothGatt)``` - method that verifies if the connected device is supported by the profile +* ```void onDeviceDisconnected()``` - method that releases device's resources + +There are 4 different solutions how to use the manager shown in different profiles. The very basic approach is used by the BPM, HRM and GLS profiles. Each of those activities holds a static reference to the manager. Keeping the manager as a static object protects from disposing it when device orientation changes and the activities are being destroyed and recreated. However, this approach does not allow to keep the connections in background mode and therefore is not a solution that should be used in any final application. + +A better implementation may be found in CSC, RSC, HTM and CGM. The BleManager instance is maintained by the running service. The service is started in order to connect to a device and stopped when user decides to disconnect from it. When an activity is destroyed it unbinds from the service, but the service is still running, so the incoming data may continue to be handled. All device-related data are kept be the service and may be obtained by a new activity when it binds to it in order to be shown to the user. + +As a third, the Proximity profile allows to connect to multiple sensors at the same time. It uses a different service implementation but still the BleManager is used to manage each connection. If the [shouldAutoConnect()](hhttps://github.com/NordicSemiconductor/Android-BLE-Library/blob/master/ble/src/main/java/no/nordicsemi/android/ble/BleManager.java#L246) method returns true for a connection, the manager will try to reconnect automatically to the device if a link was lost. You will also be notified about a device that got away using ```onLinklossOccurred(BluetoothDevice)```. + +The BleMulticonnectProfileService implementation, used by Proximity profile, does not save addresses of connected devices. When the service is killed it will not be able to reconnect to them after it's restarted, so this feature has been disabled. Also, when user removes the nRF Toolbox app from Recents, the service will be killed and all devices will be disconnected automatically. To change this behaviour a service would have to either save the addresses and reconnect to devices after it has restarted (but then removing the app from Recents would cause disconnection and immediate reconnection as the service is then killed and moved to another process), or would have to be implemented in a way that is using another [process](https://developer.android.com/guide/topics/manifest/service-element.html#proc). Then, however, it is not possible to bind to such service and data must be exchanged using a [Messenger](https://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample). Such approach is not demonstrated in nRF Toolbox. + +At last, the BleManager can be accessed from a ViewModel (see [Architecture Components](https://developer.android.com/topic/libraries/architecture/index.html)). Check out the [Android nRF Blinky](https://github.com/NordicSemiconductor/Android-nRF-Blinky) app for sample code. + +### Nordic UART Service + +The UART profile allows for fast prototyping of devices. The service itself it very simple, having just 2 characteristics, one for sending data and one for receiving. The data may be any byte array but it is very often used with just text. Each UART configuration in the nRF Toolbox consists of 9 programmable buttons. Each of them, when pressed, will send the stored command to the device. You may export your configuration to XML and share between other devices. Swipe the screen to right to show the log with all events. + +Since nRF Toolbox version 1.16.0 the UART profile supports also Android Wear devices (watches). If you have an Android watch, the application will automatically be installed on it after you install or update the application on the phone. Before you start playing with the watch, please open the UART profile on the phone so it could share your configurations to all wearables. + +Android Wear 2.0 support has been added in nRF Toolbox version 2.2.2. Now, after installing the app on the phone, you will be notified on the watch to download the watch-APK onto the watch. The app on the watch is not standalone. UART configurations must be configured on the phone. + +The wearable application may work in 2 modes: as a remote control of the phone, or directly connected to a UART device. + +1. Connect your phone to the UART device. After few seconds you should get a notification on the watch that your device is now connected. Swipe it left to see Disconnect button (will send a message to the phone to terminate the connection with UART target) and Open button. Click the Open button to see a list of your UART configurations. Click one and see the list of active buttons. When pressed the button will send a message to the phone using Google Play Services and the phone will send the command to the target device. In this mode you may have more than one watch connected to the phone and use both as remote controls. + + ![Scenario 1](resources/scenario_1.png) + +2. Open the applications menu on Android Wear watch and click nRF Toolbox. The watch will now scan for all nearby Bluetooth Smart devices and show you them on a list. Select your UART device to connect to it. A list of your configurations will be shown, like in 1. As that was a direct connection from the watch to the UART target the phone, or any other watch will not be notified about it. + + ![Scenario 2](resources/scenario_2.png) + +### Device Firmware Update + +The **Device Firmware Update (DFU)** profile allows you to update the application, bootloader and/or the Soft Device image over-the-air (OTA). It is compatible with Nordic Semiconductor nRF5 devices that have the SoftDevice and DFU Bootloader flashed. From version 1.11.0 onward, the nRF Toolbox has allowed to send the init packet (required since SDK 7.0). More information about the init packet may be found here: [init packet handling](https://github.com/NordicSemiconductor/Android-nRF-Connect/tree/master/init%20packet%20handling). + +The DFU has the following features: +- Scans for devices that are in DFU mode. +- Connects to devices in DFU mode and uploads the selected firmware (soft device, bootloader and/or application). +- Allows HEX or BIN file upload through your phone or tablet. +- Allows to update a soft device and bootloader from ZIP in one connection. +- Pause, resume, and cancel file uploads. +- Works in portrait and landscape orientation. +- Includes pre-installed examples that consist of the Bluetooth Smart heart rate service and running speed and cadence service. +- **Secure DFU** is supported since nRF Toolbox 1.17.0. + +#### DFU Settings + +To open the DFU settings click the *Settings* button in the top toolbar when on DFU profile. + +**Packet receipt notification procedure** - This switch allows you to turn on and off the packet receipt notification procedure. During the DFU operation the phone sends 20-bytes size packets to the DFU target. It may be configured that once every N packets the phone stops sending and awaits for the Packet Receipt Notification from the device. This feature is required by Android to sync sending data with the remote device, as the callback `onCharacteristicWrite(...)` that follows calling method `gatt.writeCharacteristic(...)` is invoked when the packet is written to the outgoing queue, not when physically transmitted. With this procedure disabled it may happen that the outgoing buffer will be overloaded and the communication stops. The same error may happen when the N number is too big, about 300-400. The receipt notification ensures that the outgoing queue is empty and the DFU target received all packets successfully. + +*Note:* Android 6.0 and newer does not require this option to be enabled. The buffer overflow is now handled correctly and the upload speed is much higher with this option disabled. + +**Number of packets** - This field allows you to set the N number describe above. By default it is set to 12. Depending on the phone model, devices may send and receive different number of packets in each connection interval. Nexus 4, for instance, may send just 1 packet (and receive 3 notifications) while Nexus 5 or 6 send and receive up to 4 packets. By customizing this value you may check which value allows for the fastest transmission on your phone/tablet. + +**MBR size** - This value is used only to convert HEX files into BIN files. If your packet is already in the BIN format, this value is ignored. The data from addresses lower then this value are being skipped while converting HEX to BIN. This is to prevent from sending the MBR (Master Boot Record) part from the HEX file that contains the Soft Device. The compiled Soft Device contains data that starts at address 0x0000 and contains the MBR. It is followed by the jump to address 0x1000 (default MBR size) where the Soft Device firmware starts. Only the Soft Device part must be sent over DFU. + +**Keep bond information** - When upgrading the application on a bonded device the DFU bootloader may be configured to preserve some pages of the application's memory intact, so that the new application may read them. The new application must know the old data format in order to read them correctly. Our HRS DFU sample stores the Long Term Key (LTK) and the Service Attributes in two first pages. However, the DFU Bootloader, by default, clears the whole application's memory when the new application upload completes, and the bond information is lost. In order to configure the number of pages to be preserved set the **DFU_APP_DATA_RESERVED** value in the *dfu_types.h* file in the DFU bootloader code (line ~56). To preserve two pages the value should be set to 0x0800. When your DFU bootloader has been modified to keep the bond information after updating the application set the switch to ON. Otherwise the bond information will be removed from the phone. + +**External MCU DFU** - The DFU service from the library, when connected to a DFU target, will check whether it is in application or in DFU bootloader mode. For DFU implementations from SDK 7.0 or newer this is done by reading the value of DFU Version characteristic. If the returned value is equal to 0x0100 (major = 0, minor = 1) it means that we are in the application mode and jump to the bootloader mode is required. + +However, for DFU implementations from older SDKs, where there was no DFU Version characteristic, the service must guess. If this option is set to false (default) it will count number of device's services. If the count is equal to 3 (Generic Access, Generic Attribute, DFU Service) it will assume that it's in DFU mode. If greater than 3 - in app mode. + +This guessing may not be always correct. One situation may be when the nRF chip is used to flash update on an external MCU using DFU. The DFU procedure may be implemented in the application, which may (and usually does) have more services. In such case set the value of this property to true. + +### Dependencies + +nRF Toolbox depends on [Android BLE Library](https://github.com/NordicSemiconductor/Android-BLE-Library/) which has to be cloned into the same root folder as this app. If you prefer a different name, update the [*settings.gradle*](https://github.com/NordicSemiconductor/Android-BLE-Library/blob/master/settings.gradle) file. + +In order to compile the project the **DFU Library is required**. This project may be found here: https://github.com/NordicSemiconductor/Android-DFU-Library. +Since version 1.16.1 it is imported automatically from *jcenter* repository and no special configuration is needed. If you want to make some modifications in the DFU Library, please clone the DFU Library to the same root as nRF Toolbox is cloned and name the library's folder **DFULibrary**. Add the dfu module in Project Structure and edit *app/build.gradle* file and *settings.gradle* files as describe in them. + +The nRF Toolbox also uses the nRF Logger API library which may be found here: https://github.com/NordicSemiconductor/nRF-Logger-API. The library is included in dependencies in *build.gradle* file. This library allows the app to create log entries in the [nRF Logger](https://play.google.com/store/apps/details?id=no.nordicsemi.android.log) application. Please, read the library documentation on GitHub for more information about the usage and permissions. + +The graph in HRM profile is created using the [AChartEngine v1.1.0](http://www.achartengine.org) contributed based on the [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0). + +### Note +- Android 4.3 or newer is required. +- Compatible with nRF5 devices running samples from the Nordic SDK and other devices implementing standard profiles. +- Development kits can be ordered from http://www.nordicsemi.com/eng/Buy-Online. +- The nRF51 or nRF52 SDKs and SoftDevices are available online at http://developer.nordicsemi.com. + +### Known problems +- Nexus 4 and Nexus 7 with Android 4.3 do not allow to unbind devices. +- Reconnection to bondable devices may not work on several tested phones. +- Nexus 4, 5 and 7 with Android 4.4 fails if reconnecting when Gatt Server is running. +- Reset of Bluetooth adapter may be required if other errors appear. + +### Known problems with DFU settings: +- Setting Package Receipt Notification to O (disabling) or less than ~400 may overflow the outgoing queue and hangs the Bluetooth adapter. Use values around 12 for better performance. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..e8fa30f --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,2 @@ +/build +*.iml diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..c3557e6 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,73 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 28 + buildToolsVersion "28.0.3" + + defaultConfig { + applicationId "no.nordicsemi.android.nrftoolbox" + minSdkVersion 18 + targetSdkVersion 28 + versionCode 69 + versionName "2.7.2" + resConfigs "en" + + vectorDrawables.useSupportLibrary = true + } + buildTypes { + debug { + minifyEnabled true + useProguard false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + release { + minifyEnabled true + useProguard true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + compileOptions { + targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_1_8 + } +} + +dependencies { + implementation project(':common') + implementation fileTree(dir: 'libs', include: ['*.jar']) + wearApp project(path: ':wear') + + // nRF Toolbox is using Play Service 10.2.0 in order to make the app working in China: + // https://developer.android.com/training/wearables/apps/creating-app-china.html + //noinspection GradleDependency + implementation 'com.google.android.gms:play-services-wearable:10.2.0' + + implementation 'androidx.appcompat:appcompat:1.1.0-alpha04' + implementation 'androidx.preference:preference:1.1.0-alpha04' + implementation 'com.google.android.material:material:1.1.0-alpha05' + + implementation 'no.nordicsemi.android:log:2.2.0' + implementation 'no.nordicsemi.android.support.v18:scanner:1.4.0' + + // The DFU Library is imported automatically from jcenter: + implementation 'no.nordicsemi.android:dfu:1.9.0' + // if you desire to build the DFU Library, clone the + // https://github.com/NordicSemiconductor/Android-DFU-Library project into DFULibrary folder, + // add it as a module into the project structure and uncomment the following line + // (and also the according lines in the settings.gradle): + // implementation project(':dfu') + + // Import the BLE Common Library. + // The BLE Common Library depends on BLE Library. It is enough to include the first one. + implementation 'no.nordicsemi.android:ble-common:2.1.1' + // The BLE Common Library may be included from jcenter. If you want to modify the code, + // clone both projects from GitHub and replace the line above with the following + // (and also the according lines in the settings.gradle): + // implementation project(':ble-common') + + implementation('org.simpleframework:simple-xml:2.7.1') { + exclude group: 'stax', module: 'stax-api' + exclude group: 'xpp3', module: 'xpp3' + } + implementation 'com.android.support:design:28.0.0' +} \ No newline at end of file diff --git a/app/libs/achartengine-1.2.0.jar b/app/libs/achartengine-1.2.0.jar new file mode 100644 index 0000000..21fe13d Binary files /dev/null and b/app/libs/achartengine-1.2.0.jar differ diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..6f9aa2c --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,81 @@ +-optimizationpasses 5 +-dontusemixedcaseclassnames +-dontskipnonpubliclibraryclasses +-dontskipnonpubliclibraryclassmembers +-dontpreverify +-dontshrink +-verbose + +-optimizations !code/simplification/arithmetic,!field/*,!class/merging/* + +-keepattributes *Annotation* +-keepattributes Signature + +-keepclasseswithmembernames class * { + native ; +} + +-keepclasseswithmembers class * { + public (android.content.Context, android.util.AttributeSet); +} + +-keep public class * extends android.app.Activity +-keep public class * extends android.app.Application +-keep public class * extends android.app.Service +-keep public class * extends android.content.BroadcastReceiver +-keep public class * extends android.content.ContentProvider +-keep public class * extends android.app.backup.BackupAgentHelper +-keep public class * extends android.preference.Preference +-keep public class com.android.vending.licensing.ILicensingService + +# The AndroidX library contains references to newer platform versions. +# Don't warn about those in case this app is linking against an older platform version. +-dontwarn androidx.** + +-keep class com.google.android.gms.** +-dontwarn com.google.android.gms.** + +# Java +-keep class java.** { *; } +-dontnote java.** +-dontwarn java.** + +-keep class javax.** { *; } +-dontnote javax.** +-dontwarn javax.** + +-keep class sun.misc.Unsafe { *; } +-dontnote sun.misc.Unsafe + +-keep class javax.xml.stream.XMLOutputFactory { *; } + +# (the rt.jar has them) +-dontwarn com.bea.xml.stream.XMLWriterBase +-dontwarn javax.xml.stream.events.** +-dontwarn javax.xml.stream.** + +# Simple XML +-keep public class org.simpleframework.** { *; } +-keep class org.simpleframework.xml.** { *; } +-keep class org.simpleframework.xml.core.** { *; } +-keep class org.simpleframework.xml.util.** { *; } + +-keepattributes ElementList, Root, InnerClasses, LineNumberTable + +-keepclasseswithmembers class * { + @org.simpleframework.xml.* ; +} + +# Chart Engine +-keep class org.achartengine.** { *; } +-dontnote org.achartengine.** + +# HTTP (might require legacyLibraries) ? +-dontnote org.apache.http.params.** +-dontnote org.apache.http.conn.scheme.** +-dontnote org.apache.http.conn.** +-dontnote android.net.http.** + +# DFU Library +-keep class no.nordicsemi.android.dfu.** { *; } + diff --git a/app/src/androidTest/java/no/nordicsemi/android/nrftoolbox/ApplicationTest.java b/app/src/androidTest/java/no/nordicsemi/android/nrftoolbox/ApplicationTest.java new file mode 100644 index 0000000..5e6a0ca --- /dev/null +++ b/app/src/androidTest/java/no/nordicsemi/android/nrftoolbox/ApplicationTest.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1ce41f7 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,297 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/AppHelpFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/AppHelpFragment.java new file mode 100644 index 0000000..6799f6c --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/AppHelpFragment.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox; + +import android.app.Dialog; +import android.content.pm.PackageManager.NameNotFoundException; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.appcompat.app.AlertDialog; + +public class AppHelpFragment extends DialogFragment { + private static final String ARG_TEXT = "ARG_TEXT"; + private static final String ARG_VERSION = "ARG_VERSION"; + + public static AppHelpFragment getInstance(final int aboutResId, final boolean appendVersion) { + final AppHelpFragment fragment = new AppHelpFragment(); + + final Bundle args = new Bundle(); + args.putInt(ARG_TEXT, aboutResId); + args.putBoolean(ARG_VERSION, appendVersion); + fragment.setArguments(args); + + return fragment; + } + + public static AppHelpFragment getInstance(final int aboutResId) { + final AppHelpFragment fragment = new AppHelpFragment(); + + final Bundle args = new Bundle(); + args.putInt(ARG_TEXT, aboutResId); + args.putBoolean(ARG_VERSION, false); + fragment.setArguments(args); + + return fragment; + } + + @Override + @NonNull + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final Bundle args = getArguments(); + final StringBuilder text = new StringBuilder(getString(args.getInt(ARG_TEXT))); + + final boolean appendVersion = args.getBoolean(ARG_VERSION); + if (appendVersion) { + try { + final String version = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName; + text.append(getString(R.string.about_version, version)); + } catch (final NameNotFoundException e) { + // do nothing + } + } + return new AlertDialog.Builder(getActivity()).setTitle(R.string.about_title).setMessage(text) + .setPositiveButton(R.string.ok, null).create(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/FeaturesActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/FeaturesActivity.java new file mode 100644 index 0000000..86709ee --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/FeaturesActivity.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox; + +import android.content.ActivityNotFoundException; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.content.res.Configuration; +import android.graphics.Color; +import android.graphics.ColorMatrix; +import android.graphics.ColorMatrixColorFilter; +import android.net.Uri; +import android.os.Bundle; + +import androidx.annotation.NonNull; +import androidx.core.view.GravityCompat; +import androidx.drawerlayout.widget.DrawerLayout; +import androidx.appcompat.app.ActionBarDrawerToggle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.GridView; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.List; + +import no.nordicsemi.android.nrftoolbox.adapter.AppAdapter; +import no.nordicsemi.android.nrftoolbox.hrs.HRSActivity; + +public class FeaturesActivity extends AppCompatActivity { + private static final String NRF_CONNECT_CATEGORY = "no.nordicsemi.android.nrftoolbox.LAUNCHER"; + private static final String UTILS_CATEGORY = "no.nordicsemi.android.nrftoolbox.UTILS"; + private static final String NRF_CONNECT_PACKAGE = "no.nordicsemi.android.mcp"; + private static final String NRF_CONNECT_CLASS = NRF_CONNECT_PACKAGE + ".DeviceListActivity"; + private static final String NRF_CONNECT_MARKET_URI = "market://details?id=no.nordicsemi.android.mcp"; + + // Extras that can be passed from NFC (see SplashscreenActivity) + public static final String EXTRA_APP = "application/vnd.no.nordicsemi.type.app"; + public static final String EXTRA_ADDRESS = "application/vnd.no.nordicsemi.type.address"; + + private DrawerLayout mDrawerLayout; + private ActionBarDrawerToggle mDrawerToggle; + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_features); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + + // ensure that Bluetooth exists + if (!ensureBLEExists()) + finish(); + + final DrawerLayout drawer = mDrawerLayout = findViewById(R.id.drawer_layout); + drawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + + // Set the drawer toggle as the DrawerListener + mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { + @Override + public void onDrawerSlide(final View drawerView, final float slideOffset) { + // Disable the Hamburger icon animation + super.onDrawerSlide(drawerView, 0); + } + }; + drawer.addDrawerListener(mDrawerToggle); + + // setup plug-ins in the drawer + //setupPluginsInDrawer(drawer.findViewById(R.id.plugin_container)); + + // configure the app grid + final GridView grid = findViewById(R.id.grid); + grid.setAdapter(new AppAdapter(this)); + grid.setEmptyView(findViewById(android.R.id.empty)); + + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + final Intent intent = getIntent(); + if (intent.hasExtra(EXTRA_APP) && intent.hasExtra(EXTRA_ADDRESS)) { + final String app = intent.getStringExtra(EXTRA_APP); + switch (app) { + case "HRM": + final Intent newIntent = new Intent(this, HRSActivity.class); + newIntent.putExtra(EXTRA_ADDRESS, intent.getByteArrayExtra(EXTRA_ADDRESS)); + newIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + startActivity(newIntent); + break; + default: + // other are not supported yet + break; + } + } + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.help, menu); + return true; + } + + @Override + protected void onPostCreate(final Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + // Sync the toggle state after onRestoreInstanceState has occurred. + mDrawerToggle.syncState(); + } + + @Override + public void onConfigurationChanged(@NonNull final Configuration newConfig) { + super.onConfigurationChanged(newConfig); + mDrawerToggle.onConfigurationChanged(newConfig); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + // Pass the event to ActionBarDrawerToggle, if it returns + // true, then it has handled the app icon touch event + if (mDrawerToggle.onOptionsItemSelected(item)) { + return true; + } + + switch (item.getItemId()) { + case R.id.action_about: + final AppHelpFragment fragment = AppHelpFragment.getInstance(R.string.about_text, true); + fragment.show(getSupportFragmentManager(), null); + break; + } + return true; + } + + /* + private void setupPluginsInDrawer(final ViewGroup container) { + final LayoutInflater inflater = LayoutInflater.from(this); + final PackageManager pm = getPackageManager(); + + // look for nRF Connect + final Intent nrfConnectIntent = new Intent(Intent.ACTION_MAIN); + nrfConnectIntent.addCategory(NRF_CONNECT_CATEGORY); + nrfConnectIntent.setClassName(NRF_CONNECT_PACKAGE, NRF_CONNECT_CLASS); + final ResolveInfo nrfConnectInfo = pm.resolveActivity(nrfConnectIntent, 0); + + // configure link to nRF Connect + final TextView nrfConnectItem = container.findViewById(R.id.link_mcp); + if (nrfConnectInfo == null) { + nrfConnectItem.setTextColor(Color.GRAY); + final ColorMatrix grayscale = new ColorMatrix(); + grayscale.setSaturation(0.0f); + nrfConnectItem.getCompoundDrawables()[0].mutate().setColorFilter(new ColorMatrixColorFilter(grayscale)); + } + nrfConnectItem.setOnClickListener(v -> { + Intent action = nrfConnectIntent; + if (nrfConnectInfo == null) + action = new Intent(Intent.ACTION_VIEW, Uri.parse(NRF_CONNECT_MARKET_URI)); + action.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + try { + startActivity(action); + } catch (final ActivityNotFoundException e) { + Toast.makeText(FeaturesActivity.this, R.string.no_application_play, Toast.LENGTH_SHORT).show(); + } + mDrawerLayout.closeDrawers(); + }); + + // look for other plug-ins + final Intent utilsIntent = new Intent(Intent.ACTION_MAIN); + utilsIntent.addCategory(UTILS_CATEGORY); + + final List appList = pm.queryIntentActivities(utilsIntent, 0); + for (final ResolveInfo info : appList) { + final View item = inflater.inflate(R.layout.drawer_plugin, container, false); + final ImageView icon = item.findViewById(android.R.id.icon); + final TextView label = item.findViewById(android.R.id.text1); + + label.setText(info.loadLabel(pm)); + icon.setImageDrawable(info.loadIcon(pm)); + item.setOnClickListener(v -> { + final Intent intent = new Intent(); + intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name)); + intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + mDrawerLayout.closeDrawers(); + }); + container.addView(item); + } + } + */ + + private boolean ensureBLEExists() { + if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show(); + return false; + } + return true; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/PermissionRationaleFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/PermissionRationaleFragment.java new file mode 100644 index 0000000..5a13ca0 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/PermissionRationaleFragment.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox; + +import android.app.Dialog; +import android.content.Context; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.appcompat.app.AlertDialog; + +public class PermissionRationaleFragment extends DialogFragment { + private static final String ARG_PERMISSION = "ARG_PERMISSION"; + private static final String ARG_TEXT = "ARG_TEXT"; + + private PermissionDialogListener mListener; + + public interface PermissionDialogListener { + void onRequestPermission(final String permission); + } + + @Override + public void onAttach(final Context context) { + super.onAttach(context); + + if (context instanceof PermissionDialogListener) { + mListener = (PermissionDialogListener) context; + } else { + throw new IllegalArgumentException("The parent activity must impelemnt PermissionDialogListener"); + } + } + + @Override + public void onDetach() { + super.onDetach(); + mListener = null; + } + + public static PermissionRationaleFragment getInstance(final int aboutResId, final String permission) { + final PermissionRationaleFragment fragment = new PermissionRationaleFragment(); + + final Bundle args = new Bundle(); + args.putInt(ARG_TEXT, aboutResId); + args.putString(ARG_PERMISSION, permission); + fragment.setArguments(args); + + return fragment; + } + + @Override + @NonNull + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final Bundle args = getArguments(); + final StringBuilder text = new StringBuilder(getString(args.getInt(ARG_TEXT))); + return new AlertDialog.Builder(getActivity()).setTitle(R.string.permission_title).setMessage(text) + .setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.ok, (dialog, which) -> mListener.onRequestPermission(args.getString(ARG_PERMISSION))).create(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/SplashscreenActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/SplashscreenActivity.java new file mode 100644 index 0000000..5eaa1e9 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/SplashscreenActivity.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox; + +import android.app.Activity; +import android.content.Intent; +import android.nfc.NdefMessage; +import android.nfc.NdefRecord; +import android.nfc.NfcAdapter; +import android.os.Bundle; +import android.os.Handler; +import android.os.Parcelable; + +public class SplashscreenActivity extends Activity { + /** Splash screen duration time in milliseconds */ + private static final int DELAY = 1000; + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_splashscreen); + + // Jump to SensorsActivity after DELAY milliseconds + new Handler().postDelayed(() -> { + final Intent newIntent = new Intent(SplashscreenActivity.this, FeaturesActivity.class); + newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + + // Handle NFC message, if app was opened using NFC AAR record + final Intent intent = getIntent(); + if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { + final Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); + if (rawMsgs != null) { + for (Parcelable rawMsg : rawMsgs) { + final NdefMessage msg = (NdefMessage) rawMsg; + final NdefRecord[] records = msg.getRecords(); + + for (NdefRecord record : records) { + if (record.getTnf() == NdefRecord.TNF_MIME_MEDIA) { + switch (record.toMimeType()) { + case FeaturesActivity.EXTRA_APP: + newIntent.putExtra(FeaturesActivity.EXTRA_APP, new String(record.getPayload())); + break; + case FeaturesActivity.EXTRA_ADDRESS: + newIntent.putExtra(FeaturesActivity.EXTRA_ADDRESS, invertEndianness(record.getPayload())); + break; + } + } + } + } + } + } + startActivity(newIntent); + finish(); + }, DELAY); + } + + @Override + public void onBackPressed() { + // do nothing. Protect from exiting the application when splash screen is shown + } + + /** + * Inverts endianness of the byte array. + * @param bytes input byte array + * @return byte array in opposite order + */ + private byte[] invertEndianness(final byte[] bytes) { + if (bytes == null) + return null; + final int length = bytes.length; + final byte[] result = new byte[length]; + for (int i = 0; i < length; i++) + result[i] = bytes[length - i - 1]; + return result; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/ToolboxApplication.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/ToolboxApplication.java new file mode 100644 index 0000000..4726754 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/ToolboxApplication.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2017, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox; + +import android.app.Application; +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.content.Context; +import android.os.Build; + +import no.nordicsemi.android.dfu.DfuServiceInitiator; + +public class ToolboxApplication extends Application { + public static final String CONNECTED_DEVICE_CHANNEL = "connected_device_channel"; + public static final String FILE_SAVED_CHANNEL = "file_saved_channel"; + public static final String PROXIMITY_WARNINGS_CHANNEL = "proximity_warnings_channel"; + + @Override + public void onCreate() { + super.onCreate(); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + DfuServiceInitiator.createDfuNotificationChannel(this); + + final NotificationChannel channel = new NotificationChannel(CONNECTED_DEVICE_CHANNEL, getString(R.string.channel_connected_devices_title), NotificationManager.IMPORTANCE_LOW); + channel.setDescription(getString(R.string.channel_connected_devices_description)); + channel.setShowBadge(false); + channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); + + final NotificationChannel fileChannel = new NotificationChannel(FILE_SAVED_CHANNEL, getString(R.string.channel_files_title), NotificationManager.IMPORTANCE_LOW); + fileChannel.setDescription(getString(R.string.channel_files_description)); + fileChannel.setShowBadge(false); + fileChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); + + final NotificationChannel proximityChannel = new NotificationChannel(PROXIMITY_WARNINGS_CHANNEL, getString(R.string.channel_proximity_warnings_title), NotificationManager.IMPORTANCE_LOW); + proximityChannel.setDescription(getString(R.string.channel_proximity_warnings_description)); + proximityChannel.setShowBadge(false); + proximityChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); + + final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + notificationManager.createNotificationChannel(channel); + notificationManager.createNotificationChannel(fileChannel); + notificationManager.createNotificationChannel(proximityChannel); + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/adapter/AppAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/adapter/AppAdapter.java new file mode 100644 index 0000000..d9116d0 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/adapter/AppAdapter.java @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.adapter; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import no.nordicsemi.android.nrftoolbox.R; + +public class AppAdapter extends BaseAdapter { + private static final String CATEGORY = "no.nordicsemi.android.nrftoolbox.LAUNCHER"; + private static final String NRF_CONNECT_PACKAGE = "no.nordicsemi.android.mcp"; + + private final Context mContext; + private final PackageManager mPackageManager; + private final LayoutInflater mInflater; + private final List mApplications; + + public AppAdapter(final Context context) { + mContext = context; + mInflater = LayoutInflater.from(context); + + // get nRF installed app plugins from package manager + final PackageManager pm = mPackageManager = context.getPackageManager(); + final Intent intent = new Intent(Intent.ACTION_MAIN); + intent.addCategory(CATEGORY); + + final List appList = mApplications = pm.queryIntentActivities(intent, 0); + // TODO remove the following loop after some time, when there will be no more MCP 1.1 at the market. + for (final ResolveInfo info : appList) { + if (NRF_CONNECT_PACKAGE.equals(info.activityInfo.packageName)) { + appList.remove(info); + break; + } + } + Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm)); + } + + @Override + public int getCount() { + return mApplications.size(); + } + + @Override + public Object getItem(int position) { + return mApplications.get(position); + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + if (view == null) { + view = mInflater.inflate(R.layout.feature_icon, parent, false); + + final ViewHolder holder = new ViewHolder(); + holder.view = view; + holder.icon = view.findViewById(R.id.icon); + holder.label = view.findViewById(R.id.label); + view.setTag(holder); + } + + final ResolveInfo info = mApplications.get(position); + final PackageManager pm = mPackageManager; + + final ViewHolder holder = (ViewHolder) view.getTag(); + holder.icon.setImageDrawable(info.loadIcon(pm)); + holder.label.setText(info.loadLabel(pm).toString().toUpperCase(Locale.US)); + holder.view.setOnClickListener(v -> { + final Intent intent = new Intent(); + intent.setComponent(new ComponentName(info.activityInfo.packageName, info.activityInfo.name)); + intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + mContext.startActivity(intent); + }); + + return view; + } + + private class ViewHolder { + private View view; + private ImageView icon; + private TextView label; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/app/ExpandableListActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/app/ExpandableListActivity.java new file mode 100644 index 0000000..8247c6d --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/app/ExpandableListActivity.java @@ -0,0 +1,299 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package no.nordicsemi.android.nrftoolbox.app; + +import android.app.Activity; +import android.database.Cursor; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.View; +import android.view.View.OnCreateContextMenuListener; +import android.widget.ExpandableListAdapter; +import android.widget.ExpandableListView; +import android.widget.SimpleCursorTreeAdapter; +import android.widget.SimpleExpandableListAdapter; + +import java.util.List; +import java.util.Map; + +import no.nordicsemi.android.nrftoolbox.R; + +/** + * An activity that displays an expandable list of items by binding to a data source implementing the ExpandableListAdapter, and exposes event handlers when the + * user selects an item. + *

+ * ExpandableListActivity hosts a {@link android.widget.ExpandableListView ExpandableListView} object that can be bound to different data sources that provide a + * two-levels of data (the top-level is group, and below each group are children). Binding, screen layout, and row layout are discussed in the following + * sections. + *

+ * Screen Layout + *

+ *

+ * ExpandableListActivity has a default layout that consists of a single, full-screen, centered expandable list. However, if you desire, you can customize the + * screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain an ExpandableListView object with + * the id "@android:id/list" (or {@link android.R.id#list} if it's in code) + *

+ * Optionally, your custom view can contain another view object of any type to display when the list view is empty. This "empty list" notifier must have an id + * "android:empty". Note that when an empty view is present, the expandable list view will be hidden when there is no data to display. + *

+ * The following code demonstrates an (ugly) custom screen layout. It has a list with a green background, and an alternate red "no data" message. + *

+ * + *
+ * <?xml version="1.0" encoding="UTF-8"?>
+ * <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ *         android:orientation="vertical"
+ *         android:layout_width="match_parent" 
+ *         android:layout_height="match_parent"
+ *         android:paddingLeft="8dp"
+ *         android:paddingRight="8dp">
+ * 
+ *     <ExpandableListView android:id="@id/android:list"
+ *               android:layout_width="match_parent" 
+ *               android:layout_height="match_parent"
+ *               android:background="#00FF00"
+ *               android:layout_weight="1"
+ *               android:drawSelectorOnTop="false"/>
+ * 
+ *     <TextView android:id="@id/android:empty"
+ *               android:layout_width="match_parent" 
+ *               android:layout_height="match_parent"
+ *               android:background="#FF0000"
+ *               android:text="No data"/>
+ * </LinearLayout>
+ * 
+ * + *

+ * Row Layout + *

+ * The {@link ExpandableListAdapter} set in the {@link ExpandableListActivity} via {@link #setListAdapter(ExpandableListAdapter)} provides the {@link View}s for + * each row. This adapter has separate methods for providing the group {@link View}s and child {@link View}s. There are a couple provided + * {@link ExpandableListAdapter}s that simplify use of adapters: {@link SimpleCursorTreeAdapter} and {@link SimpleExpandableListAdapter}. + *

+ * With these, you can specify the layout of individual rows for groups and children in the list. These constructor takes a few parameters that specify layout + * resources for groups and children. It also has additional parameters that let you specify which data field to associate with which object in the row layout + * resource. The {@link SimpleCursorTreeAdapter} fetches data from {@link Cursor}s and the {@link SimpleExpandableListAdapter} fetches data from {@link List}s + * of {@link Map}s. + *

+ *

+ * Android provides some standard row layout resources. These are in the {@link android.R.layout} class, and have names such as simple_list_item_1, + * simple_list_item_2, and two_line_list_item. The following layout XML is the source for the resource two_line_list_item, which displays two data fields,one + * above the other, for each list row. + *

+ * + *
+ * <?xml version="1.0" encoding="utf-8"?>
+ * <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ *     android:layout_width="match_parent"
+ *     android:layout_height="wrap_content"
+ *     android:orientation="vertical">
+ * 
+ *     <TextView android:id="@+id/text1"
+ *         android:textSize="16sp"
+ *         android:textStyle="bold"
+ *         android:layout_width="match_parent"
+ *         android:layout_height="wrap_content"/>
+ * 
+ *     <TextView android:id="@+id/text2"
+ *         android:textSize="16sp"
+ *         android:layout_width="match_parent"
+ *         android:layout_height="wrap_content"/>
+ * </LinearLayout>
+ * 
+ * + *

+ * You must identify the data bound to each TextView object in this layout. The syntax for this is discussed in the next section. + *

+ *

+ * Binding to Data + *

+ *

+ * You bind the ExpandableListActivity's ExpandableListView object to data using a class that implements the {@link android.widget.ExpandableListAdapter + * ExpandableListAdapter} interface. Android provides two standard list adapters: {@link android.widget.SimpleExpandableListAdapter SimpleExpandableListAdapter} + * for static data (Maps), and {@link android.widget.SimpleCursorTreeAdapter SimpleCursorTreeAdapter} for Cursor query results. + *

+ * + * @see #setListAdapter + * @see android.widget.ExpandableListView + */ +public class ExpandableListActivity extends AppCompatActivity implements + OnCreateContextMenuListener, + ExpandableListView.OnChildClickListener, ExpandableListView.OnGroupCollapseListener, + ExpandableListView.OnGroupExpandListener { + ExpandableListAdapter mAdapter; + ExpandableListView mList; + boolean mFinishedStart = false; + + /** + * Override this to populate the context menu when an item is long pressed. menuInfo will contain an + * {@link android.widget.ExpandableListView.ExpandableListContextMenuInfo} whose packedPosition is a packed position that should be used with + * {@link ExpandableListView#getPackedPositionType(long)} and the other similar methods. + *

+ * {@inheritDoc} + */ + @Override + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + } + + /** + * Override this for receiving callbacks when a child has been clicked. + *

+ * {@inheritDoc} + */ + @Override + public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, + int childPosition, long id) { + return false; + } + + /** + * Override this for receiving callbacks when a group has been collapsed. + */ + @Override + public void onGroupCollapse(int groupPosition) { + } + + /** + * Override this for receiving callbacks when a group has been expanded. + */ + @Override + public void onGroupExpand(int groupPosition) { + } + + /** + * Ensures the expandable list view has been created before Activity restores all of the view states. + * + * @see Activity#onRestoreInstanceState(Bundle) + */ + @Override + protected void onRestoreInstanceState(@NonNull Bundle state) { + ensureList(); + super.onRestoreInstanceState(state); + } + + /** + * Updates the screen state (current list and other views) when the content changes. + * + * @see androidx.appcompat.app.AppCompatActivity#onContentChanged() + */ + @Override + public void onContentChanged() { + super.onContentChanged(); + View emptyView = findViewById(R.id.empty); + mList = findViewById(R.id.list); + if (mList == null) { + throw new RuntimeException( + "Your content must have a ExpandableListView whose id attribute is " + + "'R.id.list'"); + } + if (emptyView != null) { + mList.setEmptyView(emptyView); + } + mList.setOnChildClickListener(this); + mList.setOnGroupExpandListener(this); + mList.setOnGroupCollapseListener(this); + + if (mFinishedStart) { + setListAdapter(mAdapter); + } + mFinishedStart = true; + } + + /** + * Provide the adapter for the expandable list. + */ + public void setListAdapter(ExpandableListAdapter adapter) { + synchronized (this) { + ensureList(); + mAdapter = adapter; + mList.setAdapter(adapter); + } + } + + /** + * Get the activity's expandable list view widget. This can be used to get the selection, set the selection, and many other useful functions. + * + * @see ExpandableListView + */ + public ExpandableListView getExpandableListView() { + ensureList(); + return mList; + } + + /** + * Get the ExpandableListAdapter associated with this activity's ExpandableListView. + */ + public ExpandableListAdapter getExpandableListAdapter() { + return mAdapter; + } + + private void ensureList() { + if (mList != null) { + return; + } + setContentView(R.layout.expandable_list_content); + } + + /** + * Gets the ID of the currently selected group or child. + * + * @return The ID of the currently selected group or child. + */ + public long getSelectedId() { + return mList.getSelectedId(); + } + + /** + * Gets the position (in packed position representation) of the currently selected group or child. Use {@link ExpandableListView#getPackedPositionType}, + * {@link ExpandableListView#getPackedPositionGroup}, and {@link ExpandableListView#getPackedPositionChild} to unpack the returned packed position. + * + * @return A packed position representation containing the currently selected group or child's position and type. + */ + public long getSelectedPosition() { + return mList.getSelectedPosition(); + } + + /** + * Sets the selection to the specified child. If the child is in a collapsed group, the group will only be expanded and child subsequently selected if + * shouldExpandGroup is set to true, otherwise the method will return false. + * + * @param groupPosition + * The position of the group that contains the child. + * @param childPosition + * The position of the child within the group. + * @param shouldExpandGroup + * Whether the child's group should be expanded if it is collapsed. + * @return Whether the selection was successfully set on the child. + */ + public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) { + return mList.setSelectedChild(groupPosition, childPosition, shouldExpandGroup); + } + + /** + * Sets the selection to the specified group. + * + * @param groupPosition + * The position of the group that should be selected. + */ + public void setSelectedGroup(int groupPosition) { + mList.setSelectedGroup(groupPosition); + } + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java new file mode 100644 index 0000000..5d5d6e6 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java @@ -0,0 +1,124 @@ +package no.nordicsemi.android.nrftoolbox.battery; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import android.util.Log; + +import java.util.UUID; + +import no.nordicsemi.android.ble.BleManager; +import no.nordicsemi.android.ble.callback.DataReceivedCallback; +import no.nordicsemi.android.ble.common.callback.battery.BatteryLevelDataCallback; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +/** + * The Ble Manager with Battery Service support. + * + * @param The profile callbacks type. + * @see BleManager + */ +@SuppressWarnings("WeakerAccess") +public abstract class BatteryManager extends LoggableBleManager { + /** Battery Service UUID. */ + private final static UUID BATTERY_SERVICE_UUID = UUID.fromString("0000180F-0000-1000-8000-00805f9b34fb"); + /** Battery Level characteristic UUID. */ + private final static UUID BATTERY_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A19-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mBatteryLevelCharacteristic; + /** Last received Battery Level value. */ + private Integer mBatteryLevel; + + /** + * The manager constructor. + * + * @param context context. + */ + public BatteryManager(final Context context) { + super(context); + } + + private DataReceivedCallback mBatteryLevelDataCallback = new BatteryLevelDataCallback() { + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + log(LogContract.Log.Level.APPLICATION,"Battery Level received: " + batteryLevel + "%"); + mBatteryLevel = batteryLevel; + mCallbacks.onBatteryLevelChanged(device, batteryLevel); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, final @NonNull Data data) { + log(Log.WARN, "Invalid Battery Level data received: " + data); + } + }; + + public void readBatteryLevelCharacteristic() { + if (isConnected()) { + readCharacteristic(mBatteryLevelCharacteristic) + .with(mBatteryLevelDataCallback) + .fail((device, status) -> log(Log.WARN,"Battery Level characteristic not found")) + .enqueue(); + } + } + + public void enableBatteryLevelCharacteristicNotifications() { + if (isConnected()) { + // If the Battery Level characteristic is null, the request will be ignored + setNotificationCallback(mBatteryLevelCharacteristic) + .with(mBatteryLevelDataCallback); + enableNotifications(mBatteryLevelCharacteristic) + .done(device -> log(Log.INFO, "Battery Level notifications enabled")) + .fail((device, status) -> log(Log.WARN, "Battery Level characteristic not found")) + .enqueue(); + } + } + + /** + * Disables Battery Level notifications on the Server. + */ + public void disableBatteryLevelCharacteristicNotifications() { + if (isConnected()) { + disableNotifications(mBatteryLevelCharacteristic) + .done(device -> log(Log.INFO, "Battery Level notifications disabled")) + .enqueue(); + } + } + + /** + * Returns the last received Battery Level value. + * The value is set to null when the device disconnects. + * @return Battery Level value, in percent. + */ + public Integer getBatteryLevel() { + return mBatteryLevel; + } + + protected abstract class BatteryManagerGattCallback extends BleManagerGattCallback { + + @Override + protected void initialize() { + readBatteryLevelCharacteristic(); + enableBatteryLevelCharacteristicNotifications(); + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(BATTERY_SERVICE_UUID); + if (service != null) { + mBatteryLevelCharacteristic = service.getCharacteristic(BATTERY_LEVEL_CHARACTERISTIC_UUID); + } + return mBatteryLevelCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + mBatteryLevelCharacteristic = null; + mBatteryLevel = null; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManagerCallbacks.java new file mode 100644 index 0000000..26a2905 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManagerCallbacks.java @@ -0,0 +1,7 @@ +package no.nordicsemi.android.nrftoolbox.battery; + +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.ble.common.profile.battery.BatteryLevelCallback; + +public interface BatteryManagerCallbacks extends BleManagerCallbacks, BatteryLevelCallback { +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMActivity.java new file mode 100644 index 0000000..b38f59e --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMActivity.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.bpm; + +import android.bluetooth.BluetoothDevice; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.widget.TextView; + +import java.util.Calendar; +import java.util.UUID; + +import no.nordicsemi.android.ble.common.profile.bp.BloodPressureMeasurementCallback; +import no.nordicsemi.android.ble.common.profile.bp.IntermediateCuffPressureCallback; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileActivity; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +// TODO The BPMActivity should be rewritten to use the service approach, like other do. +public class BPMActivity extends BleProfileActivity implements BPMManagerCallbacks { + @SuppressWarnings("unused") + private static final String TAG = "BPMActivity"; + + private TextView mSystolicView; + private TextView mSystolicUnitView; + private TextView mDiastolicView; + private TextView mDiastolicUnitView; + private TextView mMeanAPView; + private TextView mMeanAPUnitView; + private TextView mPulseView; + private TextView mTimestampView; + private TextView mBatteryLevelView; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_bpm); + setGUI(); + } + + private void setGUI() { + mSystolicView = findViewById(R.id.systolic); + mSystolicUnitView = findViewById(R.id.systolic_unit); + mDiastolicView = findViewById(R.id.diastolic); + mDiastolicUnitView = findViewById(R.id.diastolic_unit); + mMeanAPView = findViewById(R.id.mean_ap); + mMeanAPUnitView = findViewById(R.id.mean_ap_unit); + mPulseView = findViewById(R.id.pulse); + mTimestampView = findViewById(R.id.timestamp); + mBatteryLevelView = findViewById(R.id.battery); + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.bpm_feature_title; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.bpm_default_name; + } + + @Override + protected int getAboutTextId() { + return R.string.bpm_about_text; + } + + @Override + protected UUID getFilterUUID() { + return BPMManager.BP_SERVICE_UUID; + } + + @Override + protected LoggableBleManager initializeManager() { + final BPMManager manager = BPMManager.getBPMManager(getApplicationContext()); + manager.setGattCallbacks(this); + return manager; + } + + @Override + protected void setDefaultUI() { + mSystolicView.setText(R.string.not_available_value); + mSystolicUnitView.setText(null); + mDiastolicView.setText(R.string.not_available_value); + mDiastolicUnitView.setText(null); + mMeanAPView.setText(R.string.not_available_value); + mMeanAPUnitView.setText(null); + mPulseView.setText(R.string.not_available_value); + mTimestampView.setText(R.string.not_available); + mBatteryLevelView.setText(R.string.not_available); + } + + @Override + public void onServicesDiscovered(@NonNull final BluetoothDevice device, final boolean optionalServicesFound) { + // this may notify user or show some views + } + + @Override + public void onDeviceReady(@NonNull final BluetoothDevice device) { + // this may notify user + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + super.onDeviceDisconnected(device); + runOnUiThread(() -> mBatteryLevelView.setText(R.string.not_available)); + } + + @Override + public void onBloodPressureMeasurementReceived(@NonNull final BluetoothDevice device, + final float systolic, final float diastolic, final float meanArterialPressure, final int unit, + @Nullable final Float pulseRate, @Nullable final Integer userID, + @Nullable final BPMStatus status, @Nullable final Calendar calendar) { + runOnUiThread(() -> { + mSystolicView.setText(String.valueOf(systolic)); + mDiastolicView.setText(String.valueOf(diastolic)); + mMeanAPView.setText(String.valueOf(meanArterialPressure)); + if (pulseRate != null) + mPulseView.setText(String.valueOf(pulseRate)); + else + mPulseView.setText(R.string.not_available_value); + if (calendar != null) + mTimestampView.setText(getString(R.string.bpm_timestamp, calendar)); + else + mTimestampView.setText(R.string.not_available); + + mSystolicUnitView.setText(unit == BloodPressureMeasurementCallback.UNIT_mmHg ? R.string.bpm_unit_mmhg : R.string.bpm_unit_kpa); + mDiastolicUnitView.setText(unit == BloodPressureMeasurementCallback.UNIT_mmHg ? R.string.bpm_unit_mmhg : R.string.bpm_unit_kpa); + mMeanAPUnitView.setText(unit == BloodPressureMeasurementCallback.UNIT_mmHg ? R.string.bpm_unit_mmhg : R.string.bpm_unit_kpa); + }); + } + + @Override + public void onIntermediateCuffPressureReceived(@NonNull final BluetoothDevice device, final float cuffPressure, final int unit, + @Nullable final Float pulseRate, @Nullable final Integer userID, + @Nullable final BPMStatus status, @Nullable final Calendar calendar) { + runOnUiThread(() -> { + mSystolicView.setText(String.valueOf(cuffPressure)); + mDiastolicView.setText(R.string.not_available_value); + mMeanAPView.setText(R.string.not_available_value); + if (pulseRate != null) + mPulseView.setText(String.valueOf(pulseRate)); + else + mPulseView.setText(R.string.not_available_value); + if (calendar != null) + mTimestampView.setText(getString(R.string.bpm_timestamp, calendar)); + else + mTimestampView.setText(R.string.not_available); + + mSystolicUnitView.setText(unit == IntermediateCuffPressureCallback.UNIT_mmHg ? R.string.bpm_unit_mmhg : R.string.bpm_unit_kpa); + mDiastolicUnitView.setText(null); + mMeanAPUnitView.setText(null); + }); + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + runOnUiThread(() -> mBatteryLevelView.setText(getString(R.string.battery, batteryLevel))); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManager.java new file mode 100644 index 0000000..55c6458 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManager.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.bpm; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.util.Log; + +import java.util.Calendar; +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.bps.BloodPressureMeasurementDataCallback; +import no.nordicsemi.android.ble.common.callback.bps.IntermediateCuffPressureDataCallback; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.BloodPressureMeasurementParser; +import no.nordicsemi.android.nrftoolbox.parser.IntermediateCuffPressureParser; + +@SuppressWarnings({"unused", "WeakerAccess"}) +public class BPMManager extends BatteryManager { + /** Blood Pressure service UUID. */ + public final static UUID BP_SERVICE_UUID = UUID.fromString("00001810-0000-1000-8000-00805f9b34fb"); + /** Blood Pressure Measurement characteristic UUID. */ + private static final UUID BPM_CHARACTERISTIC_UUID = UUID.fromString("00002A35-0000-1000-8000-00805f9b34fb"); + /** Intermediate Cuff Pressure characteristic UUID. */ + private static final UUID ICP_CHARACTERISTIC_UUID = UUID.fromString("00002A36-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mBPMCharacteristic, mICPCharacteristic; + + private static BPMManager managerInstance = null; + + /** + * Returns the singleton implementation of BPMManager. + */ + public static synchronized BPMManager getBPMManager(final Context context) { + if (managerInstance == null) { + managerInstance = new BPMManager(context); + } + return managerInstance; + } + + private BPMManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving notification, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + + setNotificationCallback(mICPCharacteristic) + .with(new IntermediateCuffPressureDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + IntermediateCuffPressureParser.parse(data) + "\" received"); + + // Pass through received data + super.onDataReceived(device, data); + } + + @Override + public void onIntermediateCuffPressureReceived(@NonNull final BluetoothDevice device, + final float cuffPressure, final int unit, + @Nullable final Float pulseRate, @Nullable final Integer userID, + @Nullable final BPMStatus status, @Nullable final Calendar calendar) { + mCallbacks.onIntermediateCuffPressureReceived(device, cuffPressure, unit, pulseRate, userID, status, calendar); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(Log.WARN, "Invalid ICP data received: " + data); + } + }); + setIndicationCallback(mBPMCharacteristic) + .with(new BloodPressureMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + BloodPressureMeasurementParser.parse(data) + "\" received"); + + // Pass through received data + super.onDataReceived(device, data); + } + + @Override + public void onBloodPressureMeasurementReceived(@NonNull final BluetoothDevice device, + final float systolic, final float diastolic, final float meanArterialPressure, + final int unit, @Nullable final Float pulseRate, + @Nullable final Integer userID, @Nullable final BPMStatus status, + @Nullable final Calendar calendar) { + mCallbacks.onBloodPressureMeasurementReceived(device, systolic, diastolic, + meanArterialPressure, unit, pulseRate, userID, status, calendar); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(Log.WARN, "Invalid BPM data received: " + data); + } + }); + + enableNotifications(mICPCharacteristic) + .fail((device, status) -> log(Log.WARN, + "Intermediate Cuff Pressure characteristic not found")) + .enqueue(); + enableIndications(mBPMCharacteristic).enqueue(); + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(BP_SERVICE_UUID); + if (service != null) { + mBPMCharacteristic = service.getCharacteristic(BPM_CHARACTERISTIC_UUID); + mICPCharacteristic = service.getCharacteristic(ICP_CHARACTERISTIC_UUID); + } + return mBPMCharacteristic != null; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + super.isOptionalServiceSupported(gatt); // ignore the result of this + return mICPCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + mICPCharacteristic = null; + mBPMCharacteristic = null; + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManagerCallbacks.java new file mode 100644 index 0000000..75f550b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManagerCallbacks.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.bpm; + +import no.nordicsemi.android.ble.common.profile.bp.BloodPressureMeasurementCallback; +import no.nordicsemi.android.ble.common.profile.bp.IntermediateCuffPressureCallback; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +interface BPMManagerCallbacks extends BatteryManagerCallbacks, + BloodPressureMeasurementCallback, IntermediateCuffPressureCallback { + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSActivity.java new file mode 100644 index 0000000..ce6864d --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSActivity.java @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2016, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.cgms; + +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.util.SparseArray; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.ListView; +import android.widget.PopupMenu; +import android.widget.TextView; + +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; +import no.nordicsemi.android.nrftoolbox.proximity.ProximityService; + +public class CGMSActivity extends BleProfileServiceReadyActivity implements PopupMenu.OnMenuItemClickListener { + private View mControlPanelStd; + private View mControlPanelAbort; + private ListView mRecordsListView; + private TextView mBatteryLevelView; + private CGMSRecordsAdapter mCgmsRecordsAdapter; + + private CGMService.CGMSBinder mBinder; + + @Override + protected void onCreateView(Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_cgms); + setGUI(); + } + + @Override + protected void onInitialize(Bundle savedInstanceState) { + LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter()); + } + + private void setGUI() { + mRecordsListView = findViewById(R.id.list); + mControlPanelStd = findViewById(R.id.cgms_control_std); + mControlPanelAbort = findViewById(R.id.cgms_control_abort); + mBatteryLevelView = findViewById(R.id.battery); + + findViewById(R.id.action_last).setOnClickListener(v -> { + clearRecords(); + if (mBinder != null) { + mBinder.clear(); + mBinder.getLastRecord(); + } + }); + findViewById(R.id.action_all).setOnClickListener(v -> { + clearRecords(); + if (mBinder != null) { + clearRecords(); + mBinder.getAllRecords(); + } + }); + findViewById(R.id.action_abort).setOnClickListener(v -> { + if (mBinder != null) { + mBinder.abort(); + } + }); + + // create popup menu attached to the button More + findViewById(R.id.action_more).setOnClickListener(v -> { + PopupMenu menu = new PopupMenu(CGMSActivity.this, v); + menu.setOnMenuItemClickListener(CGMSActivity.this); + MenuInflater inflater = menu.getMenuInflater(); + inflater.inflate(R.menu.gls_more, menu.getMenu()); + menu.show(); + }); + } + + private void loadAdapter(SparseArray records) { + mCgmsRecordsAdapter.clear(); + for (int i = 0; i < records.size(); i++) { + mCgmsRecordsAdapter.addItem(records.valueAt(i)); + } + mCgmsRecordsAdapter.notifyDataSetChanged(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); + } + + @Override + protected void onServiceBound(final CGMService.CGMSBinder binder) { + mBinder = binder; + final SparseArray cgmsRecords = binder.getRecords(); + if (cgmsRecords != null && cgmsRecords.size() > 0) { + if (mCgmsRecordsAdapter == null) { + mCgmsRecordsAdapter = new CGMSRecordsAdapter(CGMSActivity.this); + mRecordsListView.setAdapter(mCgmsRecordsAdapter); + } + loadAdapter(cgmsRecords); + } + } + + @Override + protected void onServiceUnbound() { + mBinder = null; + } + + @Override + protected Class getServiceClass() { + return CGMService.class; + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.cgms_feature_title; + } + + @Override + protected int getAboutTextId() { + return R.string.cgms_about_text; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.cgms_default_name; + } + + @Override + protected UUID getFilterUUID() { + return CGMSManager.CGMS_UUID; + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // this may notify user or show some views + } + + private void setOperationInProgress(final boolean progress) { + runOnUiThread(() -> { + // setSupportProgressBarIndeterminateVisibility(progress); + mControlPanelStd.setVisibility(!progress ? View.VISIBLE : View.GONE); + mControlPanelAbort.setVisibility(progress ? View.VISIBLE : View.GONE); + }); + } + + public void onBatteryLevelChanged(final BluetoothDevice device, final int value) { + mBatteryLevelView.setText(getString(R.string.battery, value)); + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + setOperationInProgress(false); + mBatteryLevelView.setText(R.string.not_available); + } + + @Override + public void onError(final BluetoothDevice device, final String message, final int errorCode) { + super.onError(device, message, errorCode); + setOperationInProgress(false); + } + + @Override + protected void setDefaultUI() { + clearRecords(); + mBatteryLevelView.setText(R.string.not_available); + } + + @Override + public boolean onMenuItemClick(MenuItem menuItem) { + switch (menuItem.getItemId()) { + case R.id.action_refresh: + if(mBinder != null) + mBinder.refreshRecords(); + break; + case R.id.action_first: + if (mBinder != null) + mBinder.getFirstRecord(); + break; + case R.id.action_clear: + if (mBinder != null) + mBinder.clear(); + break; + case R.id.action_delete_all: + if (mBinder != null) + mBinder.deleteAllRecords(); + break; + } + return true; + } + + private void clearRecords() { + if (mCgmsRecordsAdapter != null) { + mCgmsRecordsAdapter.clear(); + mCgmsRecordsAdapter.notifyDataSetChanged(); + } + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(ProximityService.EXTRA_DEVICE); + + switch (action) { + case CGMService.BROADCAST_NEW_CGMS_VALUE: { + CGMSRecord cgmsRecord = intent.getExtras().getParcelable(CGMService.EXTRA_CGMS_RECORD); + if (mCgmsRecordsAdapter == null) { + mCgmsRecordsAdapter = new CGMSRecordsAdapter(CGMSActivity.this); + mRecordsListView.setAdapter(mCgmsRecordsAdapter); + } + mCgmsRecordsAdapter.addItem(cgmsRecord); + mCgmsRecordsAdapter.notifyDataSetChanged(); + break; + } + case CGMService.BROADCAST_DATA_SET_CLEAR: + // Update GUI + clearRecords(); + break; + case CGMService.OPERATION_STARTED: + // Update GUI + setOperationInProgress(true); + break; + case CGMService.BROADCAST_BATTERY_LEVEL: + final int batteryLevel = intent.getIntExtra(CGMService.EXTRA_BATTERY_LEVEL, 0); + // Update GUI + onBatteryLevelChanged(device, batteryLevel); + break; + case CGMService.OPERATION_FAILED: + // Update GUI + showToast(R.string.gls_operation_failed); + // breakthrough intended + default: + // Update GUI + setOperationInProgress(false); + } + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(CGMService.BROADCAST_NEW_CGMS_VALUE); + intentFilter.addAction(CGMService.BROADCAST_DATA_SET_CLEAR); + intentFilter.addAction(CGMService.OPERATION_STARTED); + intentFilter.addAction(CGMService.OPERATION_COMPLETED); + intentFilter.addAction(CGMService.OPERATION_SUPPORTED); + intentFilter.addAction(CGMService.OPERATION_NOT_SUPPORTED); + intentFilter.addAction(CGMService.OPERATION_ABORTED); + intentFilter.addAction(CGMService.OPERATION_FAILED); + intentFilter.addAction(CGMService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManager.java new file mode 100644 index 0000000..6588b19 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManager.java @@ -0,0 +1,445 @@ +/* + * Copyright (c) 2016, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.cgms; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.util.Log; +import android.util.SparseArray; + +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.RecordAccessControlPointDataCallback; +import no.nordicsemi.android.ble.common.callback.cgm.CGMFeatureDataCallback; +import no.nordicsemi.android.ble.common.callback.cgm.CGMSpecificOpsControlPointDataCallback; +import no.nordicsemi.android.ble.common.callback.cgm.CGMStatusDataCallback; +import no.nordicsemi.android.ble.common.callback.cgm.ContinuousGlucoseMeasurementDataCallback; +import no.nordicsemi.android.ble.common.data.RecordAccessControlPointData; +import no.nordicsemi.android.ble.common.data.cgm.CGMSpecificOpsControlPointData; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.CGMMeasurementParser; +import no.nordicsemi.android.nrftoolbox.parser.CGMSpecificOpsControlPointParser; +import no.nordicsemi.android.nrftoolbox.parser.RecordAccessControlPointParser; + +public class CGMSManager extends BatteryManager { + /** Cycling Speed and Cadence service UUID. */ + public static final UUID CGMS_UUID = UUID.fromString("0000181F-0000-1000-8000-00805f9b34fb"); + private static final UUID CGM_STATUS_UUID = UUID.fromString("00002AA9-0000-1000-8000-00805f9b34fb"); + private static final UUID CGM_FEATURE_UUID = UUID.fromString("00002AA8-0000-1000-8000-00805f9b34fb"); + private static final UUID CGM_MEASUREMENT_UUID = UUID.fromString("00002AA7-0000-1000-8000-00805f9b34fb"); + private static final UUID CGM_OPS_CONTROL_POINT_UUID = UUID.fromString("00002AAC-0000-1000-8000-00805f9b34fb"); + /** Record Access Control Point characteristic UUID. */ + private static final UUID RACP_UUID = UUID.fromString("00002A52-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mCGMStatusCharacteristic; + private BluetoothGattCharacteristic mCGMFeatureCharacteristic; + private BluetoothGattCharacteristic mCGMMeasurementCharacteristic; + private BluetoothGattCharacteristic mCGMSpecificOpsControlPointCharacteristic; + private BluetoothGattCharacteristic mRecordAccessControlPointCharacteristic; + + private SparseArray mRecords = new SparseArray<>(); + + /** A flag set to true if the remote device supports E2E CRC. */ + private boolean mSecured; + /** + * A flag set when records has been requested using RACP. This is to distinguish CGM packets + * received as continuous measurements or requested. + */ + private boolean mRecordAccessRequestInProgress; + /** + * The timestamp when the session has started. This is needed to display the user facing + * times of samples. + */ + private long mSessionStartTime; + + CGMSManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving notification, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + // Enable Battery service + super.initialize(); + + // Read CGM Feature characteristic, mainly to see if the device supports E2E CRC. + // This is not supported in the experimental CGMS from the SDK. + readCharacteristic(mCGMFeatureCharacteristic) + .with(new CGMFeatureDataCallback() { + @Override + public void onContinuousGlucoseMonitorFeaturesReceived(@NonNull final BluetoothDevice device, @NonNull final CGMFeatures features, + final int type, final int sampleLocation, final boolean secured) { + mSecured = features.e2eCrcSupported; + log(LogContract.Log.Level.APPLICATION, "E2E CRC feature " + (mSecured ? "supported" : "not supported")); + } + }) + .fail((device, status) -> log(Log.WARN, "Could not read CGM Feature characteristic")) + .enqueue(); + + // Check if the session is already started. This is not supported in the experimental CGMS from the SDK. + readCharacteristic(mCGMStatusCharacteristic) + .with(new CGMStatusDataCallback() { + @Override + public void onContinuousGlucoseMonitorStatusChanged(@NonNull final BluetoothDevice device, @NonNull final CGMStatus status, final int timeOffset, final boolean secured) { + if (!status.sessionStopped) { + mSessionStartTime = System.currentTimeMillis() - timeOffset * 60000L; + log(LogContract.Log.Level.APPLICATION, "Session already started"); + } + } + }) + .fail((device, status) -> log(Log.WARN, "Could not read CGM Status characteristic")) + .enqueue(); + + // Set notification and indication callbacks + setNotificationCallback(mCGMMeasurementCharacteristic) + .with(new ContinuousGlucoseMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + CGMMeasurementParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onContinuousGlucoseMeasurementReceived(@NonNull final BluetoothDevice device, + final float glucoseConcentration, + @Nullable final Float cgmTrend, + @Nullable final Float cgmQuality, + final CGMStatus status, + final int timeOffset, + final boolean secured) { + // If the CGM Status characteristic has not been read and the session was already started before, + // estimate the Session Start Time by subtracting timeOffset minutes from the current timestamp. + if (mSessionStartTime == 0 && !mRecordAccessRequestInProgress) { + mSessionStartTime = System.currentTimeMillis() - timeOffset * 60000L; + } + + // Calculate the sample timestamp based on the Session Start Time + final long timestamp = mSessionStartTime + (timeOffset * 60000L); // Sequence number is in minutes since Start Session + + final CGMSRecord record = new CGMSRecord(timeOffset, glucoseConcentration, timestamp); + mRecords.put(record.sequenceNumber, record); + mCallbacks.onCGMValueReceived(device, record); + } + + @Override + public void onContinuousGlucoseMeasurementReceivedWithCrcError(@NonNull final BluetoothDevice device, + @NonNull final Data data) { + log(Log.WARN, "Continuous Glucose Measurement record received with CRC error"); + } + }); + + setIndicationCallback(mCGMSpecificOpsControlPointCharacteristic) + .with(new CGMSpecificOpsControlPointDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + CGMSpecificOpsControlPointParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onCGMSpecificOpsOperationCompleted(@NonNull final BluetoothDevice device, + final int requestCode, final boolean secured) { + switch (requestCode) { + case CGM_OP_CODE_START_SESSION: + mSessionStartTime = System.currentTimeMillis(); + break; + case CGM_OP_CODE_STOP_SESSION: + mSessionStartTime = 0; + break; + } + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public void onCGMSpecificOpsOperationError(@NonNull final BluetoothDevice device, + final int requestCode, final int errorCode, + final boolean secured) { + switch (requestCode) { + case CGM_OP_CODE_START_SESSION: + if (errorCode == CGM_ERROR_PROCEDURE_NOT_COMPLETED) { + // Session was already started before. + // Looks like the CGM Status characteristic has not been read, + // otherwise we would have got the Session Start Time before. + // The Session Start Time will be calculated when a next CGM + // packet is received based on it's Time Offset. + } + case CGM_OP_CODE_STOP_SESSION: + mSessionStartTime = 0; + break; + } + } + + @Override + public void onCGMSpecificOpsResponseReceivedWithCrcError(@NonNull final BluetoothDevice device, + @NonNull final Data data) { + log(Log.ERROR, "Request failed: CRC error"); + } + }); + + setIndicationCallback(mRecordAccessControlPointCharacteristic) + .with(new RecordAccessControlPointDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onRecordAccessOperationCompleted(@NonNull final BluetoothDevice device, final int requestCode) { + switch (requestCode) { + case RACP_OP_CODE_ABORT_OPERATION: + mCallbacks.onOperationAborted(device); + break; + default: + mRecordAccessRequestInProgress = false; + mCallbacks.onOperationCompleted(device); + break; + } + } + + @Override + public void onRecordAccessOperationCompletedWithNoRecordsFound(@NonNull final BluetoothDevice device, + final int requestCode) { + mRecordAccessRequestInProgress = false; + mCallbacks.onOperationCompleted(device); + } + + @Override + public void onNumberOfRecordsReceived(@NonNull final BluetoothDevice device, final int numberOfRecords) { + mCallbacks.onNumberOfRecordsRequested(device, numberOfRecords); + if (numberOfRecords > 0) { + if (mRecords.size() > 0) { + final int sequenceNumber = mRecords.keyAt(mRecords.size() - 1) + 1; + writeCharacteristic(mRecordAccessControlPointCharacteristic, + RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo(sequenceNumber)) + .enqueue(); + } else { + writeCharacteristic(mRecordAccessControlPointCharacteristic, + RecordAccessControlPointData.reportAllStoredRecords()) + .enqueue(); + } + } else { + mRecordAccessRequestInProgress = false; + mCallbacks.onOperationCompleted(device); + } + } + + @Override + public void onRecordAccessOperationError(@NonNull final BluetoothDevice device, + final int requestCode, final int errorCode) { + log(Log.WARN, "Record Access operation failed (error " + errorCode + ")"); + if (errorCode == RACP_ERROR_OP_CODE_NOT_SUPPORTED) { + mCallbacks.onOperationNotSupported(device); + } else { + mCallbacks.onOperationFailed(device); + } + } + }); + + // Enable notifications and indications + enableNotifications(mCGMMeasurementCharacteristic) + .fail((device, status) -> log(Log.WARN, "Failed to enable Continuous Glucose Measurement notifications (" + status + ")")) + .enqueue(); + enableIndications(mCGMSpecificOpsControlPointCharacteristic) + .fail((device, status) -> log(Log.WARN, "Failed to enable CGM Specific Ops Control Point indications notifications (" + status + ")")) + .enqueue(); + enableIndications(mRecordAccessControlPointCharacteristic) + .fail((device, status) -> log(Log.WARN, "Failed to enabled Record Access Control Point indications (error " + status + ")")) + .enqueue(); + + // Start Continuous Glucose session if hasn't been started before + if (mSessionStartTime == 0L) { + writeCharacteristic(mCGMSpecificOpsControlPointCharacteristic, CGMSpecificOpsControlPointData.startSession(mSecured)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + CGMSpecificOpsControlPointParser.parse(data) + "\" sent")) + .fail((device, status) -> log(LogContract.Log.Level.ERROR, "Failed to start session (error " + status + ")")) + .enqueue(); + } + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(CGMS_UUID); + if (service != null) { + mCGMStatusCharacteristic = service.getCharacteristic(CGM_STATUS_UUID); + mCGMFeatureCharacteristic = service.getCharacteristic(CGM_FEATURE_UUID); + mCGMMeasurementCharacteristic = service.getCharacteristic(CGM_MEASUREMENT_UUID); + mCGMSpecificOpsControlPointCharacteristic = service.getCharacteristic(CGM_OPS_CONTROL_POINT_UUID); + mRecordAccessControlPointCharacteristic = service.getCharacteristic(RACP_UUID); + } + return mCGMMeasurementCharacteristic != null + && mCGMSpecificOpsControlPointCharacteristic != null + && mRecordAccessControlPointCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + mCGMStatusCharacteristic = null; + mCGMFeatureCharacteristic = null; + mCGMMeasurementCharacteristic = null; + mCGMSpecificOpsControlPointCharacteristic = null; + mRecordAccessControlPointCharacteristic = null; + } + }; + + /** + * Returns a list of CGM records obtained from this device. The key in the array is the + */ + public SparseArray getRecords() { + return mRecords; + } + + /** + * Clears the records list locally + */ + public void clear() { + mRecords.clear(); + mCallbacks.onDatasetCleared(getBluetoothDevice()); + } + + /** + * Sends the request to obtain the last (most recent) record from glucose device. + * The data will be returned to Glucose Measurement characteristic as a notification followed by + * Record Access Control Point indication with status code Success or other in case of error. + */ + public void getLastRecord() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + mRecordAccessRequestInProgress = true; + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportLastStoredRecord()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to obtain the first (oldest) record from glucose device. + * The data will be returned to Glucose Measurement characteristic as a notification followed by + * Record Access Control Point indication with status code Success or other in case of error. + */ + public void getFirstRecord() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + mRecordAccessRequestInProgress = true; + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportFirstStoredRecord()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends abort operation signal to the device. + */ + public void abort() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.abortOperation()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to obtain all records from glucose device. Initially we want to notify the + * user about the number of the records so the Report Number of Stored Records request is send. + * The data will be returned to Glucose Measurement characteristic as a notification followed by + * Record Access Control Point indication with status code Success or other in case of error. + */ + public void getAllRecords() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + mRecordAccessRequestInProgress = true; + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportNumberOfAllStoredRecords()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to obtain all records from glucose device. Initially we want to notify the + * user about the number of the records so the Report Number of Stored Records request is send. + * The data will be returned to Glucose Measurement characteristic as a notification followed by + * Record Access Control Point indication with status code Success or other in case of error. + */ + public void refreshRecords() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + if (mRecords.size() == 0) { + getAllRecords(); + } else { + mCallbacks.onOperationStarted(getBluetoothDevice()); + + // Obtain the last sequence number + final int sequenceNumber = mRecords.keyAt(mRecords.size() - 1) + 1; + mRecordAccessRequestInProgress = true; + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo(sequenceNumber)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + // Info: + // Operators OPERATOR_GREATER_THEN_OR_EQUAL, OPERATOR_LESS_THEN_OR_EQUAL and OPERATOR_RANGE are not supported by the CGMS sample from SDK + // The "Operation not supported" response will be received + } + } + + /** + * Sends the request to remove all stored records from the Continuous Glucose Monitor device. + * This feature is not supported by the CGMS sample from the SDK, so monitor will answer with + * the Op Code Not Supported error. + */ + public void deleteAllRecords() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.deleteAllStoredRecords()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } +} + diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManagerCallbacks.java new file mode 100644 index 0000000..8ba33af --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManagerCallbacks.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.cgms; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; + +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +public interface CGMSManagerCallbacks extends BatteryManagerCallbacks { + + void onCGMValueReceived(@NonNull final BluetoothDevice device, final CGMSRecord record); + + void onOperationStarted(final @NonNull BluetoothDevice device); + + void onOperationCompleted(final @NonNull BluetoothDevice device); + + void onOperationFailed(final @NonNull BluetoothDevice device); + + void onOperationAborted(final @NonNull BluetoothDevice device); + + void onOperationNotSupported(final @NonNull BluetoothDevice device); + + void onDatasetCleared(final @NonNull BluetoothDevice device); + + void onNumberOfRecordsRequested(final @NonNull BluetoothDevice device, final int value); + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecord.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecord.java new file mode 100644 index 0000000..ced03f2 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecord.java @@ -0,0 +1,49 @@ +package no.nordicsemi.android.nrftoolbox.cgms; + +import android.os.Parcel; +import android.os.Parcelable; + +class CGMSRecord implements Parcelable{ + /** Record sequence number. */ + protected int sequenceNumber; + /** The base time of the measurement (start time + sequenceNumber of minutes). */ + protected long timestamp; + /** The glucose concentration in mg/dL. */ + protected float glucoseConcentration; + + CGMSRecord(final int sequenceNumber, final float glucoseConcentration, final long timestamp) { + this.sequenceNumber = sequenceNumber; + this.glucoseConcentration = glucoseConcentration; + this.timestamp = timestamp; + } + + private CGMSRecord(final Parcel in) { + this.sequenceNumber = in.readInt(); + this.glucoseConcentration = in.readFloat(); + this.timestamp = in.readLong(); + } + + public static final Creator CREATOR = new Creator() { + @Override + public CGMSRecord createFromParcel(final Parcel in) { + return new CGMSRecord(in); + } + + @Override + public CGMSRecord[] newArray(final int size) { + return new CGMSRecord[size]; + } + }; + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(final Parcel parcel, final int flags) { + parcel.writeInt(sequenceNumber); + parcel.writeFloat(glucoseConcentration); + parcel.writeLong(timestamp); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecordsAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecordsAdapter.java new file mode 100644 index 0000000..0fb1359 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecordsAdapter.java @@ -0,0 +1,79 @@ +package no.nordicsemi.android.nrftoolbox.cgms; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.TextView; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import no.nordicsemi.android.nrftoolbox.R; + +public class CGMSRecordsAdapter extends BaseAdapter { + private final static SimpleDateFormat mTimeFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.US); + + private List mRecords; + private LayoutInflater mInflater; + + public CGMSRecordsAdapter(final Context context) { + mRecords = new ArrayList<>(); + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + + @Override + public int getCount() { + return mRecords.size(); + } + + @Override + public Object getItem(int i) { + return null; + } + + @Override + public long getItemId(int i) { + return i; + } + + @Override + public View getView(final int position, View convertView, ViewGroup parent) { + ViewHolder viewHolder; + if (convertView == null) { + convertView = mInflater.inflate(R.layout.activity_feature_cgms_item, parent, false); + viewHolder = new ViewHolder(); + viewHolder.concentration = convertView.findViewById(R.id.cgms_concentration); + viewHolder.time = convertView.findViewById(R.id.time); + viewHolder.details = convertView.findViewById(R.id.details); + convertView.setTag(viewHolder); + } else { + viewHolder = (ViewHolder) convertView.getTag(); + } + + final CGMSRecord cgmsRecord = mRecords.get(position); + viewHolder.concentration.setText(String.valueOf(cgmsRecord.glucoseConcentration)); + viewHolder.details.setText(viewHolder.details.getResources().getString(R.string.cgms_details, cgmsRecord.sequenceNumber)); + viewHolder.time.setText(mTimeFormat.format(new Date(cgmsRecord.timestamp))); + + return convertView; + } + + public void addItem(final CGMSRecord record) { + mRecords.add(record); + } + + public void clear() { + mRecords.clear(); + } + + private static class ViewHolder { + TextView time; + TextView details; + TextView concentration; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMService.java new file mode 100644 index 0000000..8f2f81a --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMService.java @@ -0,0 +1,290 @@ +package no.nordicsemi.android.nrftoolbox.cgms; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.util.SparseArray; + +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +public class CGMService extends BleProfileService implements CGMSManagerCallbacks { + private static final String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.cgms.ACTION_DISCONNECT"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + + public static final String BROADCAST_NEW_CGMS_VALUE = "no.nordicsemi.android.nrftoolbox.cgms.BROADCAST_NEW_CGMS_VALUE"; + public static final String BROADCAST_DATA_SET_CLEAR = "no.nordicsemi.android.nrftoolbox.cgms.BROADCAST_DATA_SET_CLEAR"; + public static final String OPERATION_STARTED = "no.nordicsemi.android.nrftoolbox.cgms.OPERATION_STARTED"; + public static final String OPERATION_COMPLETED = "no.nordicsemi.android.nrftoolbox.cgms.OPERATION_COMPLETED"; + public static final String OPERATION_SUPPORTED = "no.nordicsemi.android.nrftoolbox.cgms.OPERATION_SUPPORTED"; + public static final String OPERATION_NOT_SUPPORTED = "no.nordicsemi.android.nrftoolbox.cgms.OPERATION_NOT_SUPPORTED"; + public static final String OPERATION_FAILED = "no.nordicsemi.android.nrftoolbox.cgms.OPERATION_FAILED"; + public static final String OPERATION_ABORTED = "no.nordicsemi.android.nrftoolbox.cgms.OPERATION_ABORTED"; + public static final String EXTRA_CGMS_RECORD = "no.nordicsemi.android.nrftoolbox.cgms.EXTRA_CGMS_RECORD"; + public static final String EXTRA_DATA = "no.nordicsemi.android.nrftoolbox.cgms.EXTRA_DATA"; + + private final static int NOTIFICATION_ID = 229; + private final static int OPEN_ACTIVITY_REQ = 0; + private final static int DISCONNECT_REQ = 1; + + private CGMSManager mManager; + private final LocalBinder mBinder = new CGMSBinder(); + + /** + * This local binder is an interface for the bonded activity to operate with the RSC sensor + */ + + public class CGMSBinder extends LocalBinder { + /** + * Returns all records as a sparse array where sequence number is the key. + * + * @return the records list + */ + public SparseArray getRecords() { + return mManager.getRecords(); + } + + /** + * Clears the records list locally + */ + public void clear() { + if (mManager != null) + mManager.clear(); + } + + /** + * Sends the request to obtain the first (oldest) record from glucose device. + * The data will be returned to Glucose Measurement characteristic as a notification followed by Record Access Control + * Point indication with status code ({@link CGMSManager# RESPONSE_SUCCESS} or other in case of error. + */ + public void getFirstRecord() { + if (mManager != null) + mManager.getFirstRecord(); + } + + /** + * Sends the request to obtain the last (most recent) record from glucose device. + * The data will be returned to Glucose Measurement characteristic as a notification followed by Record Access + * Control Point indication with status code Success or other in case of error. + */ + public void getLastRecord() { + if (mManager != null) + mManager.getLastRecord(); + } + + /** + * Sends the request to obtain all records from glucose device. + * Initially we want to notify user about the number of the records so the Report Number of Stored Records is send. + * The data will be returned to Glucose Measurement characteristic as a series of notifications followed + * by Record Access Control Point indication with status code Success or other in case of error. + */ + public void getAllRecords() { + if (mManager != null) + mManager.getAllRecords(); + } + + /** + * Sends the request to obtain all records from glucose device with sequence number greater + * than the last one already obtained. The data will be returned to Glucose Measurement + * characteristic as a series of notifications followed by Record Access Control Point + * indication with status code Success or other in case of error. + */ + public void refreshRecords() { + if (mManager != null) + mManager.refreshRecords(); + } + + /** + * Sends abort operation signal to the device + */ + public void abort() { + if (mManager != null) + mManager.abort(); + } + + /** + * Sends Delete op code with All stored records parameter. This method may not be supported by the SDK sample. + */ + public void deleteAllRecords() { + if (mManager != null) + mManager.deleteAllRecords(); + } + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new CGMSManager(this); + } + + + @Override + public void onCreate() { + super.onCreate(); + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + // when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + // when the activity rebinds to the service, remove the notification + cancelNotification(); + } + + @Override + protected void onUnbind() { + // when the activity closes we need to show the notification that user is connected to the sensor + createNotification(R.string.csc_notification_connected_message, 0); + } + + /** + * Creates the notification + * + * @param messageResId the message resource id. The message must have one String parameter,
+ * f.e. <string name="name">%s is connected</string> + * @param defaults signals that will be used to notify the user + */ + private void createNotification(final int messageResId, final int defaults) { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, CGMSActivity.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + // both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[]{parentIntent, targetIntent}, PendingIntent.FLAG_UPDATE_CURRENT); + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.CONNECTED_DEVICE_CHANNEL); + builder.setContentIntent(pendingIntent); + builder.setContentTitle(getString(R.string.app_name)).setContentText(getString(messageResId, getDeviceName())); + builder.setSmallIcon(R.drawable.ic_stat_notify_cgms); + builder.setShowWhen(defaults != 0).setDefaults(defaults).setAutoCancel(true).setOngoing(true); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.csc_notification_action_disconnect), disconnectAction)); + + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + Logger.i(getLogSession(), "[Notification] Disconnect action pressed"); + if (isConnected()) + getBinder().disconnect(); + else + stopSelf(); + } + }; + + @Override + public void onCGMValueReceived(@NonNull final BluetoothDevice device, final CGMSRecord record) { + final Intent broadcast = new Intent(BROADCAST_NEW_CGMS_VALUE); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_CGMS_RECORD, record); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onOperationStarted(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(OPERATION_STARTED); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, true); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onOperationCompleted(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(OPERATION_COMPLETED); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, true); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onOperationFailed(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(OPERATION_FAILED); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, true); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onOperationAborted(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(OPERATION_ABORTED); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, true); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onOperationNotSupported(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(OPERATION_NOT_SUPPORTED); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, false); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDatasetCleared(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_DATA_SET_CLEAR); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onNumberOfRecordsRequested(@NonNull final BluetoothDevice device, final int value) { + if (value == 0) + showToast(R.string.gls_progress_zero); + else + showToast(getResources().getQuantityString(R.plurals.gls_progress, value, value)); + + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, batteryLevel); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCActivity.java new file mode 100644 index 0000000..399fb06 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCActivity.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.csc; + +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.view.Menu; +import android.widget.TextView; + +import java.util.Locale; +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.csc.settings.SettingsActivity; +import no.nordicsemi.android.nrftoolbox.csc.settings.SettingsFragment; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; + +public class CSCActivity extends BleProfileServiceReadyActivity { + private TextView mSpeedView; + private TextView mSpeedUnitView; + private TextView mCadenceView; + private TextView mDistanceView; + private TextView mDistanceUnitView; + private TextView mTotalDistanceView; + private TextView mTotalDistanceUnitView; + private TextView mGearRatioView; + private TextView mBatteryLevelView; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_csc); + setGui(); + } + + @Override + protected void onInitialize(final Bundle savedInstanceState) { + LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); + } + + private void setGui() { + mSpeedView = findViewById(R.id.speed); + mSpeedUnitView = findViewById(R.id.speed_unit); + mCadenceView = findViewById(R.id.cadence); + mDistanceView = findViewById(R.id.distance); + mDistanceUnitView = findViewById(R.id.distance_unit); + mTotalDistanceView = findViewById(R.id.distance_total); + mTotalDistanceUnitView = findViewById(R.id.distance_total_unit); + mGearRatioView = findViewById(R.id.ratio); + mBatteryLevelView = findViewById(R.id.battery); + } + + @Override + protected void onResume() { + super.onResume(); + setDefaultUI(); + } + + @Override + protected void setDefaultUI() { + mSpeedView.setText(R.string.not_available_value); + mCadenceView.setText(R.string.not_available_value); + mDistanceView.setText(R.string.not_available_value); + mTotalDistanceView.setText(R.string.not_available_value); + mGearRatioView.setText(R.string.not_available_value); + mBatteryLevelView.setText(R.string.not_available); + + setUnits(); + } + + private void setUnits() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_M_S: // [m/s] + mSpeedUnitView.setText(R.string.csc_speed_unit_m_s); + mDistanceUnitView.setText(R.string.csc_distance_unit_m); + mTotalDistanceUnitView.setText(R.string.csc_total_distance_unit_km); + break; + case SettingsFragment.SETTINGS_UNIT_KM_H: // [km/h] + mSpeedUnitView.setText(R.string.csc_speed_unit_km_h); + mDistanceUnitView.setText(R.string.csc_distance_unit_m); + mTotalDistanceUnitView.setText(R.string.csc_total_distance_unit_km); + break; + case SettingsFragment.SETTINGS_UNIT_MPH: // [mph] + mSpeedUnitView.setText(R.string.csc_speed_unit_mph); + mDistanceUnitView.setText(R.string.csc_distance_unit_yd); + mTotalDistanceUnitView.setText(R.string.csc_total_distance_unit_mile); + break; + } + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.csc_feature_title; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.csc_default_name; + } + + @Override + protected int getAboutTextId() { + return R.string.csc_about_text; + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.settings_and_about, menu); + return true; + } + + @Override + protected boolean onOptionsItemSelected(final int itemId) { + switch (itemId) { + case R.id.action_settings: + final Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + break; + } + return true; + } + + @Override + protected Class getServiceClass() { + return CSCService.class; + } + + @Override + protected UUID getFilterUUID() { + return CSCManager.CYCLING_SPEED_AND_CADENCE_SERVICE_UUID; + } + + @Override + protected void onServiceBound(final CSCService.CSCBinder binder) { + // not used + } + + @Override + protected void onServiceUnbound() { + // not used + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // not used + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + mBatteryLevelView.setText(R.string.not_available); + } + + private void onMeasurementReceived(final BluetoothDevice device, float speed, float distance, float totalDistance) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_KM_H: + speed = speed * 3.6f; + // pass through intended + case SettingsFragment.SETTINGS_UNIT_M_S: + if (distance < 1000) { // 1 km in m + mDistanceView.setText(String.format(Locale.US, "%.0f", distance)); + mDistanceUnitView.setText(R.string.csc_distance_unit_m); + } else { + mDistanceView.setText(String.format(Locale.US, "%.2f", distance / 1000.0f)); + mDistanceUnitView.setText(R.string.csc_distance_unit_km); + } + + mTotalDistanceView.setText(String.format(Locale.US, "%.2f", totalDistance / 1000.0f)); + break; + case SettingsFragment.SETTINGS_UNIT_MPH: + speed = speed * 2.2369f; + if (distance < 1760) { // 1 mile in yrs + mDistanceView.setText(String.format(Locale.US, "%.0f", distance)); + mDistanceUnitView.setText(R.string.csc_distance_unit_yd); + } else { + mDistanceView.setText(String.format(Locale.US, "%.2f", distance / 1760.0f)); + mDistanceUnitView.setText(R.string.csc_distance_unit_mile); + } + + mTotalDistanceView.setText(String.format(Locale.US, "%.2f", totalDistance / 1609.31f)); + break; + } + + mSpeedView.setText(String.format(Locale.US, "%.1f", speed)); + } + + private void onGearRatioUpdate(final BluetoothDevice device, final int cadence, final float ratio) { + mCadenceView.setText(String.format(Locale.US, "%d", cadence)); + mGearRatioView.setText(String.format(Locale.US, "%.1f", ratio)); + } + + public void onBatteryLevelChanged(final BluetoothDevice device, final int value) { + mBatteryLevelView.setText(getString(R.string.battery, value)); + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(CSCService.EXTRA_DEVICE); + + if (CSCService.BROADCAST_WHEEL_DATA.equals(action)) { + final float speed = intent.getFloatExtra(CSCService.EXTRA_SPEED, 0.0f); // [m/s] + final float distance = intent.getFloatExtra(CSCService.EXTRA_DISTANCE, 0); + final float totalDistance = intent.getFloatExtra(CSCService.EXTRA_TOTAL_DISTANCE, 0); + // Update GUI + onMeasurementReceived(device, speed, distance, totalDistance); + } else if (CSCService.BROADCAST_CRANK_DATA.equals(action)) { + final float ratio = intent.getFloatExtra(CSCService.EXTRA_GEAR_RATIO, 0); + final int cadence = intent.getIntExtra(CSCService.EXTRA_CADENCE, 0); + // Update GUI + onGearRatioUpdate(device, cadence, ratio); + } else if (CSCService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(CSCService.EXTRA_BATTERY_LEVEL, 0); + // Update GUI + onBatteryLevelChanged(device, batteryLevel); + } + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(CSCService.BROADCAST_WHEEL_DATA); + intentFilter.addAction(CSCService.BROADCAST_CRANK_DATA); + intentFilter.addAction(CSCService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManager.java new file mode 100644 index 0000000..c4feef5 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManager.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.csc; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import androidx.annotation.NonNull; +import android.util.Log; + +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.csc.CyclingSpeedAndCadenceMeasurementDataCallback; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.csc.settings.SettingsFragment; +import no.nordicsemi.android.nrftoolbox.parser.CSCMeasurementParser; + +public class CSCManager extends BatteryManager { + /** Cycling Speed and Cadence service UUID. */ + public final static UUID CYCLING_SPEED_AND_CADENCE_SERVICE_UUID = UUID.fromString("00001816-0000-1000-8000-00805f9b34fb"); + /** Cycling Speed and Cadence Measurement characteristic UUID. */ + private final static UUID CSC_MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00002A5B-0000-1000-8000-00805f9b34fb"); + + private final SharedPreferences preferences; + private BluetoothGattCharacteristic mCSCMeasurementCharacteristic; + + CSCManager(final Context context) { + super(context); + preferences = PreferenceManager.getDefaultSharedPreferences(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving indication, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + + // CSC characteristic is required + setNotificationCallback(mCSCMeasurementCharacteristic) + .with(new CyclingSpeedAndCadenceMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, final @NonNull Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + CSCMeasurementParser.parse(data) + "\" received"); + + // Pass through received data + super.onDataReceived(device, data); + } + + @Override + public float getWheelCircumference() { + return Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_WHEEL_SIZE, + String.valueOf(SettingsFragment.SETTINGS_WHEEL_SIZE_DEFAULT))); + } + + @Override + public void onDistanceChanged(@NonNull final BluetoothDevice device, + final float totalDistance, final float distance, final float speed) { + mCallbacks.onDistanceChanged(device, totalDistance, distance, speed); + } + + @Override + public void onCrankDataChanged(@NonNull final BluetoothDevice device, + final float crankCadence, final float gearRatio) { + mCallbacks.onCrankDataChanged(device, crankCadence, gearRatio); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, + final @NonNull Data data) { + log(Log.WARN, "Invalid CSC Measurement data received: " + data); + } + }); + enableNotifications(mCSCMeasurementCharacteristic).enqueue(); + } + + @Override + public boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(CYCLING_SPEED_AND_CADENCE_SERVICE_UUID); + if (service != null) { + mCSCMeasurementCharacteristic = service.getCharacteristic(CSC_MEASUREMENT_CHARACTERISTIC_UUID); + } + return mCSCMeasurementCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + mCSCMeasurementCharacteristic = null; + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManagerCallbacks.java new file mode 100644 index 0000000..12035da --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManagerCallbacks.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.csc; + +import no.nordicsemi.android.ble.common.profile.csc.CyclingSpeedAndCadenceCallback; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +interface CSCManagerCallbacks extends BatteryManagerCallbacks, CyclingSpeedAndCadenceCallback { +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCService.java new file mode 100644 index 0000000..2a99f0c --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCService.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.csc; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +public class CSCService extends BleProfileService implements CSCManagerCallbacks { + @SuppressWarnings("unused") + private static final String TAG = "CSCService"; + + public static final String BROADCAST_WHEEL_DATA = "no.nordicsemi.android.nrftoolbox.csc.BROADCAST_WHEEL_DATA"; + /** Speed in meters per second. */ + public static final String EXTRA_SPEED = "no.nordicsemi.android.nrftoolbox.csc.EXTRA_SPEED"; + /** Distance in meters. */ + public static final String EXTRA_DISTANCE = "no.nordicsemi.android.nrftoolbox.csc.EXTRA_DISTANCE"; + /** Total distance in meters. */ + public static final String EXTRA_TOTAL_DISTANCE = "no.nordicsemi.android.nrftoolbox.csc.EXTRA_TOTAL_DISTANCE"; + + public static final String BROADCAST_CRANK_DATA = "no.nordicsemi.android.nrftoolbox.csc.BROADCAST_CRANK_DATA"; + public static final String EXTRA_GEAR_RATIO = "no.nordicsemi.android.nrftoolbox.csc.EXTRA_GEAR_RATIO"; + public static final String EXTRA_CADENCE = "no.nordicsemi.android.nrftoolbox.csc.EXTRA_CADENCE"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + + private static final String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.csc.ACTION_DISCONNECT"; + + private final static int NOTIFICATION_ID = 200; + private final static int OPEN_ACTIVITY_REQ = 0; + private final static int DISCONNECT_REQ = 1; + + private final LocalBinder mBinder = new CSCBinder(); + private CSCManager mManager; + + /** + * This local binder is an interface for the bonded activity to operate with the RSC sensor + */ + class CSCBinder extends LocalBinder { + // empty + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new CSCManager(this); + } + + @Override + public void onCreate() { + super.onCreate(); + + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + // when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + // when the activity rebinds to the service, remove the notification + cancelNotification(); + + if (isConnected()) { + // This method will read the Battery Level value, if possible and then try to enable battery notifications (if it has NOTIFY property). + // If the Battery Level characteristic has only the NOTIFY property, it will only try to enable notifications. + mManager.readBatteryLevelCharacteristic(); + } + } + + @Override + protected void onUnbind() { + // When we are connected, but the application is not open, we are not really interested in battery level notifications. + // But we will still be receiving other values, if enabled. + if (isConnected()) + mManager.disableBatteryLevelCharacteristicNotifications(); + + // when the activity closes we need to show the notification that user is connected to the sensor + createNotification(R.string.csc_notification_connected_message, 0); + } + + @Override + public void onDistanceChanged(@NonNull final BluetoothDevice device, final float totalDistance, final float distance, final float speed) { + final Intent broadcast = new Intent(BROADCAST_WHEEL_DATA); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_SPEED, speed); + broadcast.putExtra(EXTRA_DISTANCE, distance); + broadcast.putExtra(EXTRA_TOTAL_DISTANCE, totalDistance); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onCrankDataChanged(@NonNull final BluetoothDevice device, final float crankCadence, final float gearRatio) { + final Intent broadcast = new Intent(BROADCAST_CRANK_DATA); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_GEAR_RATIO, gearRatio); + broadcast.putExtra(EXTRA_CADENCE, (int) crankCadence); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, batteryLevel); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * Creates the notification + * + * @param messageResId + * the message resource id. The message must have one String parameter,
+ * f.e. <string name="name">%s is connected</string> + * @param defaults + * signals that will be used to notify the user + */ + private void createNotification(final int messageResId, final int defaults) { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, CSCActivity.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + // both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[] { parentIntent, targetIntent }, PendingIntent.FLAG_UPDATE_CURRENT); + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.CONNECTED_DEVICE_CHANNEL); + builder.setContentIntent(pendingIntent); + builder.setContentTitle(getString(R.string.app_name)).setContentText(getString(messageResId, getDeviceName())); + builder.setSmallIcon(R.drawable.ic_stat_notify_csc); + builder.setShowWhen(defaults != 0).setDefaults(defaults).setAutoCancel(true).setOngoing(true); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.csc_notification_action_disconnect), disconnectAction)); + + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + Logger.i(getLogSession(), "[Notification] Disconnect action pressed"); + if (isConnected()) + getBinder().disconnect(); + else + stopSelf(); + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsActivity.java new file mode 100644 index 0000000..ebbf512 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsActivity.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.csc.settings; + +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; + +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsActivity extends AppCompatActivity { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // Display the fragment as the main content. + getSupportFragmentManager().beginTransaction().replace(R.id.content, new SettingsFragment()).commit(); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsFragment.java new file mode 100644 index 0000000..2a3b41b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsFragment.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.csc.settings; + +import android.content.SharedPreferences; +import android.os.Bundle; +import androidx.preference.PreferenceScreen; + +import androidx.preference.PreferenceFragmentCompat; +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { + public static final String SETTINGS_WHEEL_SIZE = "settings_wheel_size"; + public static final int SETTINGS_WHEEL_SIZE_DEFAULT = 2340; + public static final String SETTINGS_UNIT = "settings_csc_unit"; + public static final int SETTINGS_UNIT_M_S = 0; // [m/s] + public static final int SETTINGS_UNIT_KM_H = 1; // [m/s] + public static final int SETTINGS_UNIT_MPH = 2; // [m/s] + public static final int SETTINGS_UNIT_DEFAULT = SETTINGS_UNIT_KM_H; + + @Override + public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { + addPreferencesFromResource(R.xml.settings_csc); + + // set initial values + updateWheelSizeSummary(); + } + + @Override + public void onResume() { + super.onResume(); + + // attach the preference change listener. It will update the summary below interval preference + getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + } + + @Override + public void onPause() { + super.onPause(); + + // unregister listener + getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + } + + @Override + public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) { + if (SETTINGS_WHEEL_SIZE.equals(key)) { + updateWheelSizeSummary(); + } + } + + private void updateWheelSizeSummary() { + final PreferenceScreen screen = getPreferenceScreen(); + final SharedPreferences preferences = getPreferenceManager().getSharedPreferences(); + + final String value = preferences.getString(SETTINGS_WHEEL_SIZE, String.valueOf(SETTINGS_WHEEL_SIZE_DEFAULT)); + screen.findPreference(SETTINGS_WHEEL_SIZE).setSummary(getString(R.string.csc_settings_wheel_diameter_summary, value)); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuActivity.java new file mode 100644 index 0000000..8851727 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuActivity.java @@ -0,0 +1,862 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.dfu; + +import android.Manifest; +import android.app.ActivityManager; +import android.app.ActivityManager.RunningServiceInfo; +import android.app.LoaderManager.LoaderCallbacks; +import android.app.NotificationManager; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.Context; +import android.content.CursorLoader; +import android.content.Intent; +import android.content.Loader; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.preference.PreferenceManager; +import android.provider.MediaStore; +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.fragment.app.DialogFragment; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.text.TextUtils; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.webkit.MimeTypeMap; +import android.widget.Button; +import android.widget.ListView; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import java.io.File; + +import no.nordicsemi.android.dfu.DfuProgressListener; +import no.nordicsemi.android.dfu.DfuProgressListenerAdapter; +import no.nordicsemi.android.dfu.DfuServiceInitiator; +import no.nordicsemi.android.dfu.DfuServiceListenerHelper; +import no.nordicsemi.android.nrftoolbox.AppHelpFragment; +import no.nordicsemi.android.nrftoolbox.PermissionRationaleFragment; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.dfu.adapter.FileBrowserAppsAdapter; +import no.nordicsemi.android.nrftoolbox.dfu.fragment.UploadCancelFragment; +import no.nordicsemi.android.nrftoolbox.dfu.fragment.ZipInfoFragment; +import no.nordicsemi.android.nrftoolbox.dfu.settings.SettingsActivity; +import no.nordicsemi.android.nrftoolbox.dfu.settings.SettingsFragment; +import no.nordicsemi.android.nrftoolbox.scanner.ScannerFragment; +import no.nordicsemi.android.nrftoolbox.utility.FileHelper; + +/** + * DfuActivity is the main DFU activity It implements DFUManagerCallbacks to receive callbacks from DFUManager class It implements + * DeviceScannerFragment.OnDeviceSelectedListener callback to receive callback when device is selected from scanning dialog The activity supports portrait and + * landscape orientations + */ +public class DfuActivity extends AppCompatActivity implements LoaderCallbacks, ScannerFragment.OnDeviceSelectedListener, + UploadCancelFragment.CancelFragmentListener, PermissionRationaleFragment.PermissionDialogListener { + private static final String TAG = "DfuActivity"; + + private static final String PREFS_DEVICE_NAME = "no.nordicsemi.android.nrftoolbox.dfu.PREFS_DEVICE_NAME"; + private static final String PREFS_FILE_NAME = "no.nordicsemi.android.nrftoolbox.dfu.PREFS_FILE_NAME"; + private static final String PREFS_FILE_TYPE = "no.nordicsemi.android.nrftoolbox.dfu.PREFS_FILE_TYPE"; + private static final String PREFS_FILE_SCOPE = "no.nordicsemi.android.nrftoolbox.dfu.PREFS_FILE_SCOPE"; + private static final String PREFS_FILE_SIZE = "no.nordicsemi.android.nrftoolbox.dfu.PREFS_FILE_SIZE"; + + private static final String DATA_DEVICE = "device"; + private static final String DATA_FILE_TYPE = "file_type"; + private static final String DATA_FILE_TYPE_TMP = "file_type_tmp"; + private static final String DATA_FILE_PATH = "file_path"; + private static final String DATA_FILE_STREAM = "file_stream"; + private static final String DATA_INIT_FILE_PATH = "init_file_path"; + private static final String DATA_INIT_FILE_STREAM = "init_file_stream"; + private static final String DATA_STATUS = "status"; + private static final String DATA_SCOPE = "scope"; + private static final String DATA_DFU_COMPLETED = "dfu_completed"; + private static final String DATA_DFU_ERROR = "dfu_error"; + + private static final String EXTRA_URI = "uri"; + + private static final int PERMISSION_REQ = 25; + private static final int ENABLE_BT_REQ = 0; + private static final int SELECT_FILE_REQ = 1; + private static final int SELECT_INIT_FILE_REQ = 2; + + private TextView mDeviceNameView; + private TextView mFileNameView; + private TextView mFileTypeView; + private TextView mFileScopeView; + private TextView mFileSizeView; + private TextView mFileStatusView; + private TextView mTextPercentage; + private TextView mTextUploading; + private ProgressBar mProgressBar; + + private Button mSelectFileButton, mUploadButton, mConnectButton; + + private BluetoothDevice mSelectedDevice; + private String mFilePath; + private Uri mFileStreamUri; + private String mInitFilePath; + private Uri mInitFileStreamUri; + private int mFileType; + private int mFileTypeTmp; // This value is being used when user is selecting a file not to overwrite the old value (in case he/she will cancel selecting file) + private Integer mScope; + private boolean mStatusOk; + /** Flag set to true in {@link #onRestart()} and to false in {@link #onPause()}. */ + private boolean mResumed; + /** Flag set to true if DFU operation was completed while {@link #mResumed} was false. */ + private boolean mDfuCompleted; + /** The error message received from DFU service while {@link #mResumed} was false. */ + private String mDfuError; + + /** + * The progress listener receives events from the DFU Service. + * If is registered in onCreate() and unregistered in onDestroy() so methods here may also be called + * when the screen is locked or the app went to the background. This is because the UI needs to have the + * correct information after user comes back to the activity and this information can't be read from the service + * as it might have been killed already (DFU completed or finished with error). + */ + private final DfuProgressListener mDfuProgressListener = new DfuProgressListenerAdapter() { + @Override + public void onDeviceConnecting(final String deviceAddress) { + mProgressBar.setIndeterminate(true); + mTextPercentage.setText(R.string.dfu_status_connecting); + } + + @Override + public void onDfuProcessStarting(final String deviceAddress) { + mProgressBar.setIndeterminate(true); + mTextPercentage.setText(R.string.dfu_status_starting); + } + + @Override + public void onEnablingDfuMode(final String deviceAddress) { + mProgressBar.setIndeterminate(true); + mTextPercentage.setText(R.string.dfu_status_switching_to_dfu); + } + + @Override + public void onFirmwareValidating(final String deviceAddress) { + mProgressBar.setIndeterminate(true); + mTextPercentage.setText(R.string.dfu_status_validating); + } + + @Override + public void onDeviceDisconnecting(final String deviceAddress) { + mProgressBar.setIndeterminate(true); + mTextPercentage.setText(R.string.dfu_status_disconnecting); + } + + @Override + public void onDfuCompleted(final String deviceAddress) { + mTextPercentage.setText(R.string.dfu_status_completed); + if (mResumed) { + // let's wait a bit until we cancel the notification. When canceled immediately it will be recreated by service again. + new Handler().postDelayed(() -> { + onTransferCompleted(); + + // if this activity is still open and upload process was completed, cancel the notification + final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + manager.cancel(DfuService.NOTIFICATION_ID); + }, 200); + } else { + // Save that the DFU process has finished + mDfuCompleted = true; + } + } + + @Override + public void onDfuAborted(final String deviceAddress) { + mTextPercentage.setText(R.string.dfu_status_aborted); + // let's wait a bit until we cancel the notification. When canceled immediately it will be recreated by service again. + new Handler().postDelayed(() -> { + onUploadCanceled(); + + // if this activity is still open and upload process was completed, cancel the notification + final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + manager.cancel(DfuService.NOTIFICATION_ID); + }, 200); + } + + @Override + public void onProgressChanged(final String deviceAddress, final int percent, final float speed, final float avgSpeed, final int currentPart, final int partsTotal) { + mProgressBar.setIndeterminate(false); + mProgressBar.setProgress(percent); + mTextPercentage.setText(getString(R.string.dfu_uploading_percentage, percent)); + if (partsTotal > 1) + mTextUploading.setText(getString(R.string.dfu_status_uploading_part, currentPart, partsTotal)); + else + mTextUploading.setText(R.string.dfu_status_uploading); + } + + @Override + public void onError(final String deviceAddress, final int error, final int errorType, final String message) { + if (mResumed) { + showErrorMessage(message); + + // We have to wait a bit before canceling notification. This is called before DfuService creates the last notification. + new Handler().postDelayed(() -> { + // if this activity is still open and upload process was completed, cancel the notification + final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + manager.cancel(DfuService.NOTIFICATION_ID); + }, 200); + } else { + mDfuError = message; + } + } + }; + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_feature_dfu); + isBLESupported(); + if (!isBLEEnabled()) { + showBLEDialog(); + } + setGUI(); + + // Try to create sample files + if (FileHelper.newSamplesAvailable(this)) { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { + FileHelper.createSamples(this); + } else { + final DialogFragment dialog = PermissionRationaleFragment.getInstance(R.string.permission_sd_text, Manifest.permission.WRITE_EXTERNAL_STORAGE); + dialog.show(getSupportFragmentManager(), null); + } + } + + // restore saved state + mFileType = DfuService.TYPE_AUTO; // Default + if (savedInstanceState != null) { + mFileType = savedInstanceState.getInt(DATA_FILE_TYPE); + mFileTypeTmp = savedInstanceState.getInt(DATA_FILE_TYPE_TMP); + mFilePath = savedInstanceState.getString(DATA_FILE_PATH); + mFileStreamUri = savedInstanceState.getParcelable(DATA_FILE_STREAM); + mInitFilePath = savedInstanceState.getString(DATA_INIT_FILE_PATH); + mInitFileStreamUri = savedInstanceState.getParcelable(DATA_INIT_FILE_STREAM); + mSelectedDevice = savedInstanceState.getParcelable(DATA_DEVICE); + mStatusOk = mStatusOk || savedInstanceState.getBoolean(DATA_STATUS); + mScope = savedInstanceState.containsKey(DATA_SCOPE) ? savedInstanceState.getInt(DATA_SCOPE) : null; + mUploadButton.setEnabled(mSelectedDevice != null && mStatusOk); + mDfuCompleted = savedInstanceState.getBoolean(DATA_DFU_COMPLETED); + mDfuError = savedInstanceState.getString(DATA_DFU_ERROR); + } + + DfuServiceListenerHelper.registerProgressListener(this, mDfuProgressListener); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + DfuServiceListenerHelper.unregisterProgressListener(this, mDfuProgressListener); + } + + @Override + protected void onSaveInstanceState(final Bundle outState) { + super.onSaveInstanceState(outState); + outState.putInt(DATA_FILE_TYPE, mFileType); + outState.putInt(DATA_FILE_TYPE_TMP, mFileTypeTmp); + outState.putString(DATA_FILE_PATH, mFilePath); + outState.putParcelable(DATA_FILE_STREAM, mFileStreamUri); + outState.putString(DATA_INIT_FILE_PATH, mInitFilePath); + outState.putParcelable(DATA_INIT_FILE_STREAM, mInitFileStreamUri); + outState.putParcelable(DATA_DEVICE, mSelectedDevice); + outState.putBoolean(DATA_STATUS, mStatusOk); + if (mScope != null) outState.putInt(DATA_SCOPE, mScope); + outState.putBoolean(DATA_DFU_COMPLETED, mDfuCompleted); + outState.putString(DATA_DFU_ERROR, mDfuError); + } + + private void setGUI() { + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + mDeviceNameView = findViewById(R.id.device_name); + mFileNameView = findViewById(R.id.file_name); + mFileTypeView = findViewById(R.id.file_type); + mFileScopeView = findViewById(R.id.file_scope); + mFileSizeView = findViewById(R.id.file_size); + mFileStatusView = findViewById(R.id.file_status); + mSelectFileButton = findViewById(R.id.action_select_file); + mUploadButton = findViewById(R.id.action_upload); + mConnectButton = findViewById(R.id.action_connect); + mTextPercentage = findViewById(R.id.textviewProgress); + mTextUploading = findViewById(R.id.textviewUploading); + mProgressBar = findViewById(R.id.progressbar_file); + + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + if (isDfuServiceRunning()) { + // Restore image file information + mDeviceNameView.setText(preferences.getString(PREFS_DEVICE_NAME, "")); + mFileNameView.setText(preferences.getString(PREFS_FILE_NAME, "")); + mFileTypeView.setText(preferences.getString(PREFS_FILE_TYPE, "")); + mFileScopeView.setText(preferences.getString(PREFS_FILE_SCOPE, "")); + mFileSizeView.setText(preferences.getString(PREFS_FILE_SIZE, "")); + mFileStatusView.setText(R.string.dfu_file_status_ok); + mStatusOk = true; + showProgressBar(); + } + } + + @Override + protected void onResume() { + super.onResume(); + mResumed = true; + if (mDfuCompleted) + onTransferCompleted(); + if (mDfuError != null) + showErrorMessage(mDfuError); + if (mDfuCompleted || mDfuError != null) { + // if this activity is still open and upload process was completed, cancel the notification + final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + manager.cancel(DfuService.NOTIFICATION_ID); + mDfuCompleted = false; + mDfuError = null; + } + } + + @Override + protected void onPause() { + super.onPause(); + mResumed = false; + } + + @Override + public void onRequestPermission(final String permission) { + ActivityCompat.requestPermissions(this, new String[] { permission }, PERMISSION_REQ); + } + + @Override + public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + switch (requestCode) { + case PERMISSION_REQ: { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + // We have been granted the Manifest.permission.WRITE_EXTERNAL_STORAGE permission. Now we may proceed with exporting. + FileHelper.createSamples(this); + } else { + Toast.makeText(this, R.string.no_required_permission, Toast.LENGTH_SHORT).show(); + } + break; + } + } + } + + private void isBLESupported() { + if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + showToast(R.string.no_ble); + finish(); + } + } + + private boolean isBLEEnabled() { + final BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); + final BluetoothAdapter adapter = manager.getAdapter(); + return adapter != null && adapter.isEnabled(); + } + + private void showBLEDialog() { + final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, ENABLE_BT_REQ); + } + + private void showDeviceScanningDialog() { + final ScannerFragment dialog = ScannerFragment.getInstance(null); // Device that is advertising directly does not have the GENERAL_DISCOVERABLE nor LIMITED_DISCOVERABLE flag set. + dialog.show(getSupportFragmentManager(), "scan_fragment"); + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.settings_and_about, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + break; + case R.id.action_about: + final AppHelpFragment fragment = AppHelpFragment.getInstance(R.string.dfu_about_text); + fragment.show(getSupportFragmentManager(), "help_fragment"); + break; + case R.id.action_settings: + final Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + break; + } + return true; + } + + @Override + protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { + if (resultCode != RESULT_OK) + return; + + switch (requestCode) { + case SELECT_FILE_REQ: { + // clear previous data + mFileType = mFileTypeTmp; + mFilePath = null; + mFileStreamUri = null; + + // and read new one + final Uri uri = data.getData(); + /* + * The URI returned from application may be in 'file' or 'content' schema. 'File' schema allows us to create a File object and read details from if + * directly. Data from 'Content' schema must be read by Content Provider. To do that we are using a Loader. + */ + if (uri.getScheme().equals("file")) { + // the direct path to the file has been returned + final String path = uri.getPath(); + final File file = new File(path); + mFilePath = path; + + updateFileInfo(file.getName(), file.length(), mFileType); + } else if (uri.getScheme().equals("content")) { + // an Uri has been returned + mFileStreamUri = uri; + // if application returned Uri for streaming, let's us it. Does it works? + // FIXME both Uris works with Google Drive app. Why both? What's the difference? How about other apps like DropBox? + final Bundle extras = data.getExtras(); + if (extras != null && extras.containsKey(Intent.EXTRA_STREAM)) + mFileStreamUri = extras.getParcelable(Intent.EXTRA_STREAM); + + // file name and size must be obtained from Content Provider + final Bundle bundle = new Bundle(); + bundle.putParcelable(EXTRA_URI, uri); + getLoaderManager().restartLoader(SELECT_FILE_REQ, bundle, this); + } + break; + } + case SELECT_INIT_FILE_REQ: { + mInitFilePath = null; + mInitFileStreamUri = null; + + // and read new one + final Uri uri = data.getData(); + /* + * The URI returned from application may be in 'file' or 'content' schema. 'File' schema allows us to create a File object and read details from if + * directly. Data from 'Content' schema must be read by Content Provider. To do that we are using a Loader. + */ + if (uri.getScheme().equals("file")) { + // the direct path to the file has been returned + mInitFilePath = uri.getPath(); + mFileStatusView.setText(R.string.dfu_file_status_ok_with_init); + } else if (uri.getScheme().equals("content")) { + // an Uri has been returned + mInitFileStreamUri = uri; + // if application returned Uri for streaming, let's us it. Does it works? + // FIXME both Uris works with Google Drive app. Why both? What's the difference? How about other apps like DropBox? + final Bundle extras = data.getExtras(); + if (extras != null && extras.containsKey(Intent.EXTRA_STREAM)) + mInitFileStreamUri = extras.getParcelable(Intent.EXTRA_STREAM); + mFileStatusView.setText(R.string.dfu_file_status_ok_with_init); + } + break; + } + default: + break; + } + } + + @Override + public Loader onCreateLoader(final int id, final Bundle args) { + final Uri uri = args.getParcelable(EXTRA_URI); + /* + * Some apps, f.e. Google Drive allow to select file that is not on the device. There is no "_data" column handled by that provider. Let's try to obtain + * all columns and than check which columns are present. + */ + // final String[] projection = new String[] { MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.SIZE, MediaStore.MediaColumns.DATA }; + return new CursorLoader(this, uri, null /* all columns, instead of projection */, null, null, null); + } + + @Override + public void onLoaderReset(final Loader loader) { + mFileNameView.setText(null); + mFileTypeView.setText(null); + mFileSizeView.setText(null); + mFilePath = null; + mFileStreamUri = null; + mStatusOk = false; + } + + @Override + public void onLoadFinished(final Loader loader, final Cursor data) { + if (data != null && data.moveToNext()) { + /* + * Here we have to check the column indexes by name as we have requested for all. The order may be different. + */ + final String fileName = data.getString(data.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)/* 0 DISPLAY_NAME */); + final int fileSize = data.getInt(data.getColumnIndex(MediaStore.MediaColumns.SIZE) /* 1 SIZE */); + String filePath = null; + final int dataIndex = data.getColumnIndex(MediaStore.MediaColumns.DATA); + if (dataIndex != -1) + filePath = data.getString(dataIndex /* 2 DATA */); + if (!TextUtils.isEmpty(filePath)) + mFilePath = filePath; + + updateFileInfo(fileName, fileSize, mFileType); + } else { + mFileNameView.setText(null); + mFileTypeView.setText(null); + mFileSizeView.setText(null); + mFilePath = null; + mFileStreamUri = null; + mFileStatusView.setText(R.string.dfu_file_status_error); + mStatusOk = false; + } + } + + /** + * Updates the file information on UI + * + * @param fileName file name + * @param fileSize file length + */ + private void updateFileInfo(final String fileName, final long fileSize, final int fileType) { + mFileNameView.setText(fileName); + switch (fileType) { + case DfuService.TYPE_AUTO: + mFileTypeView.setText(getResources().getStringArray(R.array.dfu_file_type)[0]); + break; + case DfuService.TYPE_SOFT_DEVICE: + mFileTypeView.setText(getResources().getStringArray(R.array.dfu_file_type)[1]); + break; + case DfuService.TYPE_BOOTLOADER: + mFileTypeView.setText(getResources().getStringArray(R.array.dfu_file_type)[2]); + break; + case DfuService.TYPE_APPLICATION: + mFileTypeView.setText(getResources().getStringArray(R.array.dfu_file_type)[3]); + break; + } + mFileSizeView.setText(getString(R.string.dfu_file_size_text, fileSize)); + mFileScopeView.setText(getString(R.string.not_available)); + final String extension = mFileType == DfuService.TYPE_AUTO ? "(?i)ZIP" : "(?i)HEX|BIN"; // (?i) = case insensitive + final boolean statusOk = mStatusOk = MimeTypeMap.getFileExtensionFromUrl(fileName).matches(extension); + mFileStatusView.setText(statusOk ? R.string.dfu_file_status_ok : R.string.dfu_file_status_invalid); + mUploadButton.setEnabled(mSelectedDevice != null && statusOk); + + // Ask the user for the Init packet file if HEX or BIN files are selected. In case of a ZIP file the Init packets should be included in the ZIP. + if (statusOk) { + if (fileType != DfuService.TYPE_AUTO) { + mScope = null; + mFileScopeView.setText(getString(R.string.not_available)); + new AlertDialog.Builder(this).setTitle(R.string.dfu_file_init_title).setMessage(R.string.dfu_file_init_message) + .setNegativeButton(R.string.no, (dialog, which) -> { + mInitFilePath = null; + mInitFileStreamUri = null; + }).setPositiveButton(R.string.yes, (dialog, which) -> { + final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType(DfuService.MIME_TYPE_OCTET_STREAM); + intent.addCategory(Intent.CATEGORY_OPENABLE); + startActivityForResult(intent, SELECT_INIT_FILE_REQ); + }).show(); + } else { + new AlertDialog.Builder(this).setTitle(R.string.dfu_file_scope_title).setCancelable(false) + .setSingleChoiceItems(R.array.dfu_file_scope, 0, (dialog, which) -> { + switch (which) { + case 0: + mScope = null; + break; + case 1: + mScope = DfuServiceInitiator.SCOPE_SYSTEM_COMPONENTS; + break; + case 2: + mScope = DfuServiceInitiator.SCOPE_APPLICATION; + break; + } + }).setPositiveButton(R.string.ok, (dialogInterface, i) -> { + int index; + if (mScope == null) { + index = 0; + } else if (mScope == DfuServiceInitiator.SCOPE_SYSTEM_COMPONENTS) { + index = 1; + } else { + index = 2; + } + mFileScopeView.setText(getResources().getStringArray(R.array.dfu_file_scope)[index]); + }).show(); + } + } + } + + /** + * Called when the question mark was pressed + * + * @param view a button that was pressed + */ + public void onSelectFileHelpClicked(final View view) { + new AlertDialog.Builder(this).setTitle(R.string.dfu_help_title).setMessage(R.string.dfu_help_message).setPositiveButton(R.string.ok, null) + .show(); + } + + /** + * Called when Select File was pressed + * + * @param view a button that was pressed + */ + public void onSelectFileClicked(final View view) { + mFileTypeTmp = mFileType; + int index = 0; + switch (mFileType) { + case DfuService.TYPE_AUTO: + index = 0; + break; + case DfuService.TYPE_SOFT_DEVICE: + index = 1; + break; + case DfuService.TYPE_BOOTLOADER: + index = 2; + break; + case DfuService.TYPE_APPLICATION: + index = 3; + break; + } + // Show a dialog with file types + new AlertDialog.Builder(this).setTitle(R.string.dfu_file_type_title) + .setSingleChoiceItems(R.array.dfu_file_type, index, (dialog, which) -> { + switch (which) { + case 0: + mFileTypeTmp = DfuService.TYPE_AUTO; + break; + case 1: + mFileTypeTmp = DfuService.TYPE_SOFT_DEVICE; + break; + case 2: + mFileTypeTmp = DfuService.TYPE_BOOTLOADER; + break; + case 3: + mFileTypeTmp = DfuService.TYPE_APPLICATION; + break; + } + }).setPositiveButton(R.string.ok, (dialog, which) -> openFileChooser()).setNeutralButton(R.string.dfu_file_info, (dialog, which) -> { + final ZipInfoFragment fragment = new ZipInfoFragment(); + fragment.show(getSupportFragmentManager(), "help_fragment"); + }).setNegativeButton(R.string.cancel, null).show(); + } + + private void openFileChooser() { + final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType(mFileTypeTmp == DfuService.TYPE_AUTO ? DfuService.MIME_TYPE_ZIP : DfuService.MIME_TYPE_OCTET_STREAM); + intent.addCategory(Intent.CATEGORY_OPENABLE); + if (intent.resolveActivity(getPackageManager()) != null) { + // file browser has been found on the device + startActivityForResult(intent, SELECT_FILE_REQ); + } else { + // there is no any file browser app, let's try to download one + final View customView = getLayoutInflater().inflate(R.layout.app_file_browser, null); + final ListView appsList = customView.findViewById(android.R.id.list); + appsList.setAdapter(new FileBrowserAppsAdapter(this)); + appsList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + appsList.setItemChecked(0, true); + new AlertDialog.Builder(this).setTitle(R.string.dfu_alert_no_filebrowser_title).setView(customView) + .setNegativeButton(R.string.no, (dialog, which) -> dialog.dismiss()).setPositiveButton(R.string.ok, (dialog, which) -> { + final int pos = appsList.getCheckedItemPosition(); + if (pos >= 0) { + final String query = getResources().getStringArray(R.array.dfu_app_file_browser_action)[pos]; + final Intent storeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query)); + startActivity(storeIntent); + } + }).show(); + } + } + + /** + * Callback of UPDATE/CANCEL button on DfuActivity + */ + public void onUploadClicked(final View view) { + if (isDfuServiceRunning()) { + showUploadCancelDialog(); + return; + } + + // Check whether the selected file is a HEX file (we are just checking the extension) + if (!mStatusOk) { + Toast.makeText(this, R.string.dfu_file_status_invalid_message, Toast.LENGTH_LONG).show(); + return; + } + + // Save current state in order to restore it if user quit the Activity + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final SharedPreferences.Editor editor = preferences.edit(); + editor.putString(PREFS_DEVICE_NAME, mSelectedDevice.getName()); + editor.putString(PREFS_FILE_NAME, mFileNameView.getText().toString()); + editor.putString(PREFS_FILE_TYPE, mFileTypeView.getText().toString()); + editor.putString(PREFS_FILE_SCOPE, mFileScopeView.getText().toString()); + editor.putString(PREFS_FILE_SIZE, mFileSizeView.getText().toString()); + editor.apply(); + + showProgressBar(); + + final boolean keepBond = preferences.getBoolean(SettingsFragment.SETTINGS_KEEP_BOND, false); + final boolean forceDfu = preferences.getBoolean(SettingsFragment.SETTINGS_ASSUME_DFU_NODE, false); + final boolean enablePRNs = preferences.getBoolean(SettingsFragment.SETTINGS_PACKET_RECEIPT_NOTIFICATION_ENABLED, Build.VERSION.SDK_INT < Build.VERSION_CODES.M); + String value = preferences.getString(SettingsFragment.SETTINGS_NUMBER_OF_PACKETS, String.valueOf(DfuServiceInitiator.DEFAULT_PRN_VALUE)); + int numberOfPackets; + try { + numberOfPackets = Integer.parseInt(value); + } catch (final NumberFormatException e) { + numberOfPackets = DfuServiceInitiator.DEFAULT_PRN_VALUE; + } + + final DfuServiceInitiator starter = new DfuServiceInitiator(mSelectedDevice.getAddress()) + .setDeviceName(mSelectedDevice.getName()) + .setKeepBond(keepBond) + .setForceDfu(forceDfu) + .setPacketsReceiptNotificationsEnabled(enablePRNs) + .setPacketsReceiptNotificationsValue(numberOfPackets) + .setUnsafeExperimentalButtonlessServiceInSecureDfuEnabled(true); + if (mFileType == DfuService.TYPE_AUTO) { + starter.setZip(mFileStreamUri, mFilePath); + if (mScope != null) + starter.setScope(mScope); + } else { + starter.setBinOrHex(mFileType, mFileStreamUri, mFilePath).setInitFile(mInitFileStreamUri, mInitFilePath); + } + starter.start(this, DfuService.class); + } + + private void showUploadCancelDialog() { + final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); + final Intent pauseAction = new Intent(DfuService.BROADCAST_ACTION); + pauseAction.putExtra(DfuService.EXTRA_ACTION, DfuService.ACTION_PAUSE); + manager.sendBroadcast(pauseAction); + + final UploadCancelFragment fragment = UploadCancelFragment.getInstance(); + fragment.show(getSupportFragmentManager(), TAG); + } + + /** + * Callback of CONNECT/DISCONNECT button on DfuActivity + */ + public void onConnectClicked(final View view) { + if (isBLEEnabled()) { + showDeviceScanningDialog(); + } else { + showBLEDialog(); + } + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + mSelectedDevice = device; + mUploadButton.setEnabled(mStatusOk); + mDeviceNameView.setText(name != null ? name : getString(R.string.not_available)); + } + + @Override + public void onDialogCanceled() { + // do nothing + } + + private void showProgressBar() { + mProgressBar.setVisibility(View.VISIBLE); + mTextPercentage.setVisibility(View.VISIBLE); + mTextPercentage.setText(null); + mTextUploading.setText(R.string.dfu_status_uploading); + mTextUploading.setVisibility(View.VISIBLE); + mConnectButton.setEnabled(false); + mSelectFileButton.setEnabled(false); + mUploadButton.setEnabled(true); + mUploadButton.setText(R.string.dfu_action_upload_cancel); + } + + private void onTransferCompleted() { + clearUI(true); + showToast(R.string.dfu_success); + } + + public void onUploadCanceled() { + clearUI(false); + showToast(R.string.dfu_aborted); + } + + @Override + public void onCancelUpload() { + mProgressBar.setIndeterminate(true); + mTextUploading.setText(R.string.dfu_status_aborting); + mTextPercentage.setText(null); + } + + private void showErrorMessage(final String message) { + clearUI(false); + showToast("Upload failed: " + message); + } + + private void clearUI(final boolean clearDevice) { + mProgressBar.setVisibility(View.INVISIBLE); + mTextPercentage.setVisibility(View.INVISIBLE); + mTextUploading.setVisibility(View.INVISIBLE); + mConnectButton.setEnabled(true); + mSelectFileButton.setEnabled(true); + mUploadButton.setEnabled(false); + mUploadButton.setText(R.string.dfu_action_upload); + if (clearDevice) { + mSelectedDevice = null; + mDeviceNameView.setText(R.string.dfu_default_name); + } + // Application may have lost the right to these files if Activity was closed during upload (grant uri permission). Clear file related values. + mFileNameView.setText(null); + mFileTypeView.setText(null); + mFileScopeView.setText(null); + mFileSizeView.setText(null); + mFileStatusView.setText(R.string.dfu_file_status_no_file); + mFilePath = null; + mFileStreamUri = null; + mInitFilePath = null; + mInitFileStreamUri = null; + mStatusOk = false; + } + + private void showToast(final int messageResId) { + Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show(); + } + + private void showToast(final String message) { + Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); + } + + private boolean isDfuServiceRunning() { + final ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); + for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (DfuService.class.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuInitiatorActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuInitiatorActivity.java new file mode 100644 index 0000000..b236ec6 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuInitiatorActivity.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.dfu; + +import android.bluetooth.BluetoothDevice; +import android.content.Intent; +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.scanner.ScannerFragment; + +/** + * The activity is started only by a remote connected computer using ADB. It shows a list of DFU-supported devices in range and allows user to select target device. The HEX file will be uploaded to + * selected device using {@link DfuService}. + */ +public class DfuInitiatorActivity extends AppCompatActivity implements ScannerFragment.OnDeviceSelectedListener { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // The activity must be started with a path to the HEX file + final Intent intent = getIntent(); + if (!intent.hasExtra(DfuService.EXTRA_FILE_PATH)) + finish(); + + if (savedInstanceState == null) { + final ScannerFragment fragment = ScannerFragment.getInstance(null); // Device that is advertising directly does not have the GENERAL_DISCOVERABLE nor LIMITED_DISCOVERABLE flag set. + fragment.show(getSupportFragmentManager(), null); + } + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + final Intent intent = getIntent(); + final String overwrittenName = intent.getStringExtra(DfuService.EXTRA_DEVICE_NAME); + final String path = intent.getStringExtra(DfuService.EXTRA_FILE_PATH); + final String initPath = intent.getStringExtra(DfuService.EXTRA_INIT_FILE_PATH); + final String address = device.getAddress(); + final String finalName = overwrittenName == null ? (name != null ? name : getString(R.string.not_available)) : overwrittenName; + final int type = intent.getIntExtra(DfuService.EXTRA_FILE_TYPE, DfuService.TYPE_AUTO); + final boolean keepBond = intent.getBooleanExtra(DfuService.EXTRA_KEEP_BOND, false); + + // Start DFU service with data provided in the intent + final Intent service = new Intent(this, DfuService.class); + service.putExtra(DfuService.EXTRA_DEVICE_ADDRESS, address); + service.putExtra(DfuService.EXTRA_DEVICE_NAME, finalName); + service.putExtra(DfuService.EXTRA_FILE_TYPE, type); + service.putExtra(DfuService.EXTRA_FILE_PATH, path); + if (intent.hasExtra(DfuService.EXTRA_INIT_FILE_PATH)) + service.putExtra(DfuService.EXTRA_INIT_FILE_PATH, initPath); + service.putExtra(DfuService.EXTRA_KEEP_BOND, keepBond); + service.putExtra(DfuService.EXTRA_UNSAFE_EXPERIMENTAL_BUTTONLESS_DFU, true); + startService(service); + finish(); + } + + @Override + public void onDialogCanceled() { + finish(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuService.java new file mode 100644 index 0000000..2b16b59 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuService.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.dfu; + +import android.app.Activity; + +import no.nordicsemi.android.dfu.DfuBaseService; + +public class DfuService extends DfuBaseService { + + @Override + protected Class getNotificationTarget() { + /* + * As a target activity the NotificationActivity is returned, not the MainActivity. This is because the notification must create a new task: + * + * intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + * + * when user press it. Using NotificationActivity we can check whether the new activity is a root activity (that means no other activity was open before) + * or that there is other activity already open. In the later case the notificationActivity will just be closed. System will restore the previous activity. + * However if the application has been closed during upload and user click the notification a NotificationActivity will be launched as a root activity. + * It will create and start the main activity and terminate itself. + * + * This method may be used to restore the target activity in case the application was closed or is open. It may also be used to recreate an activity + * history (see NotificationActivity). + */ + return NotificationActivity.class; + } + + @Override + protected boolean isDebug() { + // return BuildConfig.DEBUG; + return true; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/NotificationActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/NotificationActivity.java new file mode 100644 index 0000000..1b02671 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/NotificationActivity.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.dfu; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; + +public class NotificationActivity extends Activity { + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // If this activity is the root activity of the task, the app is not running + if (isTaskRoot()) { + // Start the app before finishing + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent startAppIntent = new Intent(this, DfuActivity.class); + startAppIntent.putExtras(getIntent().getExtras()); + startActivities(new Intent[] { parentIntent, startAppIntent }); + } + + // Now finish, which will drop the user in to the activity that was at the top + // of the task stack + finish(); + } +} \ No newline at end of file diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/adapter/FileBrowserAppsAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/adapter/FileBrowserAppsAdapter.java new file mode 100644 index 0000000..b21a28b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/adapter/FileBrowserAppsAdapter.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.dfu.adapter; + +import android.content.Context; +import android.content.res.Resources; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.TextView; + +import no.nordicsemi.android.nrftoolbox.R; + +/** + * This adapter displays some file browser applications that can be used to select HEX file. It is used when there is no such app already installed on the device. The hardcoded apps and Google Play + * URLs are specified in res/values/strings_dfu.xml. + */ +public class FileBrowserAppsAdapter extends BaseAdapter { + private final LayoutInflater mInflater; + private final Resources mResources; + + public FileBrowserAppsAdapter(final Context context) { + mInflater = LayoutInflater.from(context); + mResources = context.getResources(); + } + + @Override + public int getCount() { + return mResources.getStringArray(R.array.dfu_app_file_browser).length; + } + + @Override + public Object getItem(int position) { + return mResources.getStringArray(R.array.dfu_app_file_browser_action)[position]; + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View view = convertView; + if (view == null) { + view = mInflater.inflate(R.layout.app_file_browser_item, parent, false); + } + + final TextView item = (TextView) view; + item.setText(mResources.getStringArray(R.array.dfu_app_file_browser)[position]); + item.getCompoundDrawablesRelative()[0].setLevel(position); + return view; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/UploadCancelFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/UploadCancelFragment.java new file mode 100644 index 0000000..0fac518 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/UploadCancelFragment.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.dfu.fragment; + +import android.app.Activity; +import android.app.Dialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.appcompat.app.AlertDialog; +import android.util.Log; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.dfu.DfuService; + +/** + * When cancel button is pressed during uploading this fragment shows uploading cancel dialog + */ +public class UploadCancelFragment extends DialogFragment { + private static final String TAG = "UploadCancelFragment"; + + private CancelFragmentListener mListener; + + public interface CancelFragmentListener { + void onCancelUpload(); + } + + public static UploadCancelFragment getInstance() { + return new UploadCancelFragment(); + } + + @Override + public void onAttach(final Activity activity) { + super.onAttach(activity); + + try { + mListener = (CancelFragmentListener) activity; + } catch (final ClassCastException e) { + Log.d(TAG, "The parent Activity must implement CancelFragmentListener interface"); + } + } + + @NonNull + @Override + public Dialog onCreateDialog(final Bundle savedInstanceState) { + return new AlertDialog.Builder(getActivity()).setTitle(R.string.dfu_confirmation_dialog_title).setMessage(R.string.dfu_upload_dialog_cancel_message).setCancelable(false) + .setPositiveButton(R.string.yes, (dialog, whichButton) -> { + final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity()); + final Intent pauseAction = new Intent(DfuService.BROADCAST_ACTION); + pauseAction.putExtra(DfuService.EXTRA_ACTION, DfuService.ACTION_ABORT); + manager.sendBroadcast(pauseAction); + + mListener.onCancelUpload(); + }).setNegativeButton(R.string.no, (dialog, which) -> dialog.cancel()).create(); + } + + @Override + public void onCancel(final DialogInterface dialog) { + final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity()); + final Intent pauseAction = new Intent(DfuService.BROADCAST_ACTION); + pauseAction.putExtra(DfuService.EXTRA_ACTION, DfuService.ACTION_RESUME); + manager.sendBroadcast(pauseAction); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/ZipInfoFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/ZipInfoFragment.java new file mode 100644 index 0000000..154cd38 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/ZipInfoFragment.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.dfu.fragment; + +import android.app.Dialog; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.appcompat.app.AlertDialog; +import android.view.LayoutInflater; +import android.view.View; + +import no.nordicsemi.android.nrftoolbox.R; + +public class ZipInfoFragment extends DialogFragment { + + @Override + @NonNull + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_zip_info, null); + return new AlertDialog.Builder(getActivity()).setView(view).setTitle(R.string.dfu_file_info).setPositiveButton(R.string.ok, null).create(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/AboutDfuPreference.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/AboutDfuPreference.java new file mode 100644 index 0000000..fc04998 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/AboutDfuPreference.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.dfu.settings; + +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.util.AttributeSet; +import android.widget.Toast; + +import androidx.preference.Preference; +import no.nordicsemi.android.nrftoolbox.R; + +public class AboutDfuPreference extends Preference { + + public AboutDfuPreference(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public AboutDfuPreference(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } + + @Override + protected void onClick() { + final Context context = getContext(); + final Intent intent = new Intent(Intent.ACTION_VIEW, + Uri.parse("https://www.nordicsemi.com/DocLib/Content/SDK_Doc/nRF5_SDK/v15-3-0/ble_sdk_app_dfu_bootloader")); + intent.addCategory(Intent.CATEGORY_DEFAULT); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // is browser installed? + if (intent.resolveActivity(context.getPackageManager()) != null) + context.startActivity(intent); + else { + Toast.makeText(getContext(), R.string.no_application, Toast.LENGTH_LONG).show(); + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsActivity.java new file mode 100644 index 0000000..a957f33 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsActivity.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.dfu.settings; + +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; + +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsActivity extends AppCompatActivity { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // Display the fragment as the main content. + getSupportFragmentManager().beginTransaction().replace(R.id.content, new SettingsFragment()).commit(); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsFragment.java new file mode 100644 index 0000000..aaaf5de --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsFragment.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.dfu.settings; + +import android.content.SharedPreferences; +import android.os.Build; +import android.os.Bundle; +import androidx.appcompat.app.AlertDialog; +import android.text.TextUtils; + +import androidx.preference.PreferenceFragmentCompat; +import androidx.preference.PreferenceScreen; +import no.nordicsemi.android.dfu.DfuServiceInitiator; +import no.nordicsemi.android.dfu.DfuSettingsConstants; +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsFragment extends PreferenceFragmentCompat implements DfuSettingsConstants, SharedPreferences.OnSharedPreferenceChangeListener { + public static final String SETTINGS_KEEP_BOND = "settings_keep_bond"; + + @Override + public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { + addPreferencesFromResource(R.xml.settings_dfu); + + // set initial values + updateNumberOfPacketsSummary(); + updateMBRSize(); + } + + @Override + public void onResume() { + super.onResume(); + + // attach the preference change listener. It will update the summary below interval preference + getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); + } + + @Override + public void onPause() { + super.onPause(); + + // unregister listener + getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); + } + + @Override + public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) { + final SharedPreferences preferences = getPreferenceManager().getSharedPreferences(); + + if (SETTINGS_PACKET_RECEIPT_NOTIFICATION_ENABLED.equals(key)) { + final boolean disabled = !preferences.getBoolean(SETTINGS_PACKET_RECEIPT_NOTIFICATION_ENABLED, true); + if (disabled && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { + new AlertDialog.Builder(requireContext()).setMessage(R.string.dfu_settings_dfu_number_of_packets_info).setTitle(R.string.dfu_settings_dfu_information) + .setPositiveButton(R.string.ok, null).show(); + } + } else if (SETTINGS_NUMBER_OF_PACKETS.equals(key)) { + updateNumberOfPacketsSummary(); + } else if (SETTINGS_MBR_SIZE.equals(key)) { + updateMBRSize(); + } else if (SETTINGS_ASSUME_DFU_NODE.equals(key) && sharedPreferences.getBoolean(key, false)) { + new AlertDialog.Builder(requireContext()).setMessage(R.string.dfu_settings_dfu_assume_dfu_mode_info).setTitle(R.string.dfu_settings_dfu_information) + .setPositiveButton(R.string.ok, null) + .show(); + } + } + + private void updateNumberOfPacketsSummary() { + final PreferenceScreen screen = getPreferenceScreen(); + final SharedPreferences preferences = getPreferenceManager().getSharedPreferences(); + + String value = preferences.getString(SETTINGS_NUMBER_OF_PACKETS, String.valueOf(SETTINGS_NUMBER_OF_PACKETS_DEFAULT)); + // Security check + if (TextUtils.isEmpty(value)) { + value = String.valueOf(SETTINGS_NUMBER_OF_PACKETS_DEFAULT); + preferences.edit().putString(SETTINGS_NUMBER_OF_PACKETS, value).apply(); + } + screen.findPreference(SETTINGS_NUMBER_OF_PACKETS).setSummary(value); + + final int valueInt = Integer.parseInt(value); + if (valueInt > 200 && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { + new AlertDialog.Builder(requireContext()).setMessage(R.string.dfu_settings_dfu_number_of_packets_info).setTitle(R.string.dfu_settings_dfu_information) + .setPositiveButton(R.string.ok, null) + .show(); + } + } + + private void updateMBRSize() { + final PreferenceScreen screen = getPreferenceScreen(); + final SharedPreferences preferences = getPreferenceManager().getSharedPreferences(); + + final String value = preferences.getString(SETTINGS_MBR_SIZE, String.valueOf(DfuServiceInitiator.DEFAULT_MBR_SIZE)); + screen.findPreference(SETTINGS_MBR_SIZE).setSummary(value); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/ExpandableRecordAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/ExpandableRecordAdapter.java new file mode 100644 index 0000000..85712de --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/ExpandableRecordAdapter.java @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.gls; + +import android.content.Context; +import android.content.res.Resources; +import android.util.Pair; +import android.util.SparseArray; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseExpandableListAdapter; +import android.widget.TextView; + +import no.nordicsemi.android.nrftoolbox.R; + +public class ExpandableRecordAdapter extends BaseExpandableListAdapter {; + private final GlucoseManager mGlucoseManager; + private final LayoutInflater mInflater; + private final Context mContext; + private SparseArray mRecords; + + public ExpandableRecordAdapter(final Context context, final GlucoseManager manager) { + mGlucoseManager = manager; + mContext = context; + mInflater = LayoutInflater.from(context); + mRecords = manager.getRecords().clone(); + } + + @Override + public void notifyDataSetChanged() { + mRecords = mGlucoseManager.getRecords().clone(); + super.notifyDataSetChanged(); + } + + @Override + public int getGroupCount() { + return mRecords.size(); + } + + @Override + public Object getGroup(final int groupPosition) { + return mRecords.valueAt(groupPosition); + } + + @Override + public long getGroupId(final int groupPosition) { + return mRecords.keyAt(groupPosition); + } + + @Override + public View getGroupView(final int position, boolean isExpanded, final View convertView, final ViewGroup parent) { + View view = convertView; + if (view == null) { + view = mInflater.inflate(R.layout.activity_feature_gls_item, parent, false); + + final GroupViewHolder holder = new GroupViewHolder(); + holder.time = view.findViewById(R.id.time); + holder.details = view.findViewById(R.id.details); + holder.concentration = view.findViewById(R.id.gls_concentration); + view.setTag(holder); + } + final GlucoseRecord record = (GlucoseRecord) getGroup(position); + if (record == null) + return view; // this may happen during closing the activity + final GroupViewHolder holder = (GroupViewHolder) view.getTag(); + holder.time.setText(mContext.getString(R.string.gls_timestamp, record.time)); + try { + holder.details.setText(mContext.getResources().getStringArray(R.array.gls_type)[record.type]); + } catch (final ArrayIndexOutOfBoundsException e) { + holder.details.setText(mContext.getResources().getStringArray(R.array.gls_type)[0]); + } + if (record.unit == GlucoseRecord.UNIT_kgpl) { + holder.concentration.setText(mContext.getString(R.string.gls_value, record.glucoseConcentration * 100000.0f)); + } else { + holder.concentration.setText(mContext.getString(R.string.gls_value, record.glucoseConcentration * 1000.0f)); + } + return view; + } + + @Override + public int getChildrenCount(final int groupPosition) { + final GlucoseRecord record = (GlucoseRecord) getGroup(groupPosition); + int count = 1 + (record.status != 0 ? 1 : 0); // Sample Location and optional Sensor Status Annunciation + if (record.context != null) { + final GlucoseRecord.MeasurementContext context = record.context; + if (context.carbohydrateId != 0) + count += 1; // Carbohydrate ID and units + if (context.meal != 0) + count += 1; // Meal + if (context.tester != 0) + count += 1; // Tester + if (context.health != 0) + count += 1; // Health + if (context.exerciseDuration != 0) + count += 1; // Duration and intensity + if (context.medicationId != 0) + count += 1; // Medication ID and quantity (with unit) + if (context.HbA1c != 0) + count += 1; // HbA1c + } + return count; + } + + @Override + public Object getChild(final int groupPosition, final int childPosition) { + final Resources resources = mContext.getResources(); + final GlucoseRecord record = (GlucoseRecord) getGroup(groupPosition); + String tmp; + switch (childIdToItemId(childPosition, record)) { + case 0: + try { + tmp = resources.getStringArray(R.array.gls_location)[record.sampleLocation]; + } catch (final ArrayIndexOutOfBoundsException e) { + tmp = resources.getStringArray(R.array.gls_location)[0]; + } + return new Pair<>(resources.getString(R.string.gls_location_title), tmp); + case 1: { // sensor status annunciation + final StringBuilder builder = new StringBuilder(); + final int status = record.status; + for (int i = 0; i < 12; ++i) + if ((status & (1 << i)) > 0) + builder.append(resources.getStringArray(R.array.gls_status_annunciation)[i]).append("\n"); + builder.setLength(builder.length() - 1); + return new Pair<>(resources.getString(R.string.gls_status_annunciation_title), builder.toString()); + } + case 2: { // carbohydrate id and unit + try { + tmp = resources.getStringArray(R.array.gls_context_carbohydrare)[record.context.carbohydrateId]; + } catch (final ArrayIndexOutOfBoundsException e) { + tmp = resources.getStringArray(R.array.gls_context_carbohydrare)[0]; + } + return new Pair<>(resources.getString(R.string.gls_context_carbohydrare_title), tmp + " (" + record.context.carbohydrateUnits + " g)"); + } + case 3: { // meal + try { + tmp = resources.getStringArray(R.array.gls_context_meal)[record.context.meal]; + } catch (final ArrayIndexOutOfBoundsException e) { + tmp = resources.getStringArray(R.array.gls_context_meal)[0]; + } + return new Pair<>(resources.getString(R.string.gls_context_meal_title), tmp); + } + case 4: { // tester + try { + tmp = resources.getStringArray(R.array.gls_context_tester)[record.context.tester]; + } catch (final ArrayIndexOutOfBoundsException e) { + tmp = resources.getStringArray(R.array.gls_context_tester)[0]; + } + return new Pair<>(resources.getString(R.string.gls_context_tester_title), tmp); + } + case 5: { // health + try { + tmp = resources.getStringArray(R.array.gls_context_health)[record.context.health]; + } catch (final ArrayIndexOutOfBoundsException e) { + tmp = resources.getStringArray(R.array.gls_context_health)[0]; + } + return new Pair<>(resources.getString(R.string.gls_context_health_title), tmp); + } + case 6: { // exercise duration and intensity + return new Pair<>(resources.getString(R.string.gls_context_exercise_title), resources.getString(R.string.gls_context_exercise, record.context.exerciseDuration, record.context.exerciseIntensity)); + } + case 7: { // medication ID and quantity + try { + tmp = resources.getStringArray(R.array.gls_context_medication_id)[record.context.medicationId]; + } catch (final ArrayIndexOutOfBoundsException e) { + tmp = resources.getStringArray(R.array.gls_context_medication_id)[0]; + } + final int resId = record.context.medicationUnit == GlucoseRecord.UNIT_kgpl ? R.string.gls_context_medication_kg : R.string.gls_context_medication_l; + return new Pair<>(resources.getString(R.string.gls_context_medication_title), resources.getString(resId, tmp, record.context.medicationQuantity)); + } + case 8: { // HbA1c value + return new Pair<>(resources.getString(R.string.gls_context_hba1c_title), resources.getString(R.string.gls_context_hba1c, record.context.HbA1c)); + } + default: + return new Pair<>("Not implemented", "The value exists but is not shown"); + } + } + + private int childIdToItemId(final int childPosition, final GlucoseRecord record) { + int itemId = 0; + int child = childPosition; + + // Location is required + if (itemId == childPosition) + return itemId; + + if (++itemId > 0 && record.status != 0 && --child == 0) return itemId; + if (record.context != null) { + if (++itemId > 0 && record.context.carbohydrateId != 0 && --child == 0) return itemId; + if (++itemId > 0 && record.context.meal != 0 && --child == 0) return itemId; + if (++itemId > 0 && record.context.tester != 0 && --child == 0) return itemId; + if (++itemId > 0 && record.context.health != 0 && --child == 0) return itemId; + if (++itemId > 0 && record.context.exerciseDuration != 0 && --child == 0) return itemId; + if (++itemId > 0 && record.context.medicationId != 0 && --child == 0) return itemId; + if (++itemId > 0 && record.context.HbA1c != 0 && --child == 0) return itemId; + } + throw new IllegalArgumentException("No item ID for position " + childPosition); + } + + @Override + public long getChildId(final int groupPosition, final int childPosition) { + return groupPosition + childPosition; + } + + @SuppressWarnings("unchecked") + @Override + public View getChildView(final int groupPosition, final int childPosition, final boolean isLastChild, final View convertView, final ViewGroup parent) { + View view = convertView; + if (view == null) { + view = mInflater.inflate(R.layout.activity_feature_gls_subitem, parent, false); + final ChildViewHolder holder = new ChildViewHolder(); + holder.title = view.findViewById(android.R.id.text1); + holder.details = view.findViewById(android.R.id.text2); + view.setTag(holder); + } + final Pair value = (Pair) getChild(groupPosition, childPosition); + final ChildViewHolder holder = (ChildViewHolder) view.getTag(); + holder.title.setText(value.first); + holder.details.setText(value.second); + return view; + } + + @Override + public boolean hasStableIds() { + return true; + } + + @Override + public boolean isChildSelectable(final int groupPosition, final int childPosition) { + return false; + } + + private class GroupViewHolder { + private TextView time; + private TextView details; + private TextView concentration; + } + + private class ChildViewHolder { + private TextView title; + private TextView details; + } + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseActivity.java new file mode 100644 index 0000000..2528a37 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseActivity.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.gls; + +import android.bluetooth.BluetoothDevice; +import android.os.Bundle; +import androidx.annotation.NonNull; +import android.util.SparseArray; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.BaseExpandableListAdapter; +import android.widget.PopupMenu; +import android.widget.TextView; + +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileExpandableListActivity; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +// TODO The GlucoseActivity should be rewritten to use the service approach, like other do. +public class GlucoseActivity extends BleProfileExpandableListActivity implements PopupMenu.OnMenuItemClickListener, GlucoseManagerCallbacks { + @SuppressWarnings("unused") + private static final String TAG = "GlucoseActivity"; + + private BaseExpandableListAdapter mAdapter; + private GlucoseManager mGlucoseManager; + + private View mControlPanelStd; + private View mControlPanelAbort; + private TextView mUnitView; + private TextView mBatteryLevelView; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_gls); + setGUI(); + } + + private void setGUI() { + mUnitView = findViewById(R.id.unit); + mControlPanelStd = findViewById(R.id.gls_control_std); + mControlPanelAbort = findViewById(R.id.gls_control_abort); + mBatteryLevelView = findViewById(R.id.battery); + + findViewById(R.id.action_last).setOnClickListener(v -> mGlucoseManager.getLastRecord()); + findViewById(R.id.action_all).setOnClickListener(v -> mGlucoseManager.getAllRecords()); + findViewById(R.id.action_abort).setOnClickListener(v -> mGlucoseManager.abort()); + + // create popup menu attached to the button More + findViewById(R.id.action_more).setOnClickListener(v -> { + PopupMenu menu = new PopupMenu(GlucoseActivity.this, v); + menu.setOnMenuItemClickListener(GlucoseActivity.this); + MenuInflater inflater = menu.getMenuInflater(); + inflater.inflate(R.menu.gls_more, menu.getMenu()); + menu.show(); + }); + + setListAdapter(mAdapter = new ExpandableRecordAdapter(this, mGlucoseManager)); + } + + @Override + protected LoggableBleManager initializeManager() { + GlucoseManager manager = mGlucoseManager = GlucoseManager.getGlucoseManager(getApplicationContext()); + manager.setGattCallbacks(this); + return manager; + } + + @Override + public boolean onMenuItemClick(final MenuItem item) { + switch (item.getItemId()) { + case R.id.action_refresh: + mGlucoseManager.refreshRecords(); + break; + case R.id.action_first: + mGlucoseManager.getFirstRecord(); + break; + case R.id.action_clear: + mGlucoseManager.clear(); + break; + case R.id.action_delete_all: + mGlucoseManager.deleteAllRecords(); + break; + } + return true; + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.gls_feature_title; + } + + @Override + protected int getAboutTextId() { + return R.string.gls_about_text; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.gls_default_name; + } + + @Override + protected UUID getFilterUUID() { + return GlucoseManager.GLS_SERVICE_UUID; + } + + @Override + protected void setDefaultUI() { + mGlucoseManager.clear(); + mBatteryLevelView.setText(R.string.not_available); + } + + private void setOperationInProgress(final boolean progress) { + runOnUiThread(() -> { + mControlPanelStd.setVisibility(!progress ? View.VISIBLE : View.GONE); + mControlPanelAbort.setVisibility(progress ? View.VISIBLE : View.GONE); + }); + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + super.onDeviceDisconnected(device); + setOperationInProgress(false); + runOnUiThread(() -> mBatteryLevelView.setText(R.string.not_available)); + } + + @Override + public void onOperationStarted(final BluetoothDevice device) { + setOperationInProgress(true); + } + + @Override + public void onOperationCompleted(final BluetoothDevice device) { + setOperationInProgress(false); + + runOnUiThread(() -> { + final SparseArray records = mGlucoseManager.getRecords(); + if (records.size() > 0) { + final int unit = records.valueAt(0).unit; + mUnitView.setVisibility(View.VISIBLE); + mUnitView.setText(unit == GlucoseRecord.UNIT_kgpl ? R.string.gls_unit_mgpdl : R.string.gls_unit_mmolpl); + } else { + mUnitView.setVisibility(View.GONE); + } + mAdapter.notifyDataSetChanged(); + }); + } + + @Override + public void onOperationAborted(final BluetoothDevice device) { + setOperationInProgress(false); + } + + @Override + public void onOperationNotSupported(final BluetoothDevice device) { + setOperationInProgress(false); + showToast(R.string.gls_operation_not_supported); + } + + @Override + public void onOperationFailed(final BluetoothDevice device) { + setOperationInProgress(false); + showToast(R.string.gls_operation_failed); + } + + @Override + public void onDatasetChanged(final BluetoothDevice device) { + // Do nothing. Refreshing the list is done in onOperationCompleted + } + + @Override + public void onNumberOfRecordsRequested(final BluetoothDevice device, final int value) { + if (value == 0) + showToast(R.string.gls_progress_zero); + else + showToast(getResources().getQuantityString(R.plurals.gls_progress, value, value)); + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + runOnUiThread(() -> mBatteryLevelView.setText(getString(R.string.battery, batteryLevel))); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManager.java new file mode 100644 index 0000000..6c8ad25 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManager.java @@ -0,0 +1,407 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.gls; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import android.os.Handler; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.util.Log; +import android.util.SparseArray; + +import java.util.Calendar; +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.RecordAccessControlPointDataCallback; +import no.nordicsemi.android.ble.common.callback.glucose.GlucoseMeasurementContextDataCallback; +import no.nordicsemi.android.ble.common.callback.glucose.GlucoseMeasurementDataCallback; +import no.nordicsemi.android.ble.common.data.RecordAccessControlPointData; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.GlucoseMeasurementContextParser; +import no.nordicsemi.android.nrftoolbox.parser.GlucoseMeasurementParser; +import no.nordicsemi.android.nrftoolbox.parser.RecordAccessControlPointParser; +import no.nordicsemi.android.nrftoolbox.utility.DebugLogger; + +@SuppressWarnings("unused") +public class GlucoseManager extends BatteryManager { + private static final String TAG = "GlucoseManager"; + + /** Glucose service UUID */ + public final static UUID GLS_SERVICE_UUID = UUID.fromString("00001808-0000-1000-8000-00805f9b34fb"); + /** Glucose Measurement characteristic UUID */ + private final static UUID GM_CHARACTERISTIC = UUID.fromString("00002A18-0000-1000-8000-00805f9b34fb"); + /** Glucose Measurement Context characteristic UUID */ + private final static UUID GM_CONTEXT_CHARACTERISTIC = UUID.fromString("00002A34-0000-1000-8000-00805f9b34fb"); + /** Glucose Feature characteristic UUID */ + private final static UUID GF_CHARACTERISTIC = UUID.fromString("00002A51-0000-1000-8000-00805f9b34fb"); + /** Record Access Control Point characteristic UUID */ + private final static UUID RACP_CHARACTERISTIC = UUID.fromString("00002A52-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mGlucoseMeasurementCharacteristic; + private BluetoothGattCharacteristic mGlucoseMeasurementContextCharacteristic; + private BluetoothGattCharacteristic mRecordAccessControlPointCharacteristic; + + private final SparseArray mRecords = new SparseArray<>(); + private Handler mHandler; + private static GlucoseManager mInstance; + + /** + * Returns the singleton implementation of GlucoseManager. + */ + public static GlucoseManager getGlucoseManager(final Context context) { + if (mInstance == null) + mInstance = new GlucoseManager(context); + return mInstance; + } + + private GlucoseManager(final Context context) { + super(context); + mHandler = new Handler(); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving notification, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + + // The gatt.setCharacteristicNotification(...) method is called in BleManager during + // enabling notifications or indications + // (see BleManager#internalEnableNotifications/Indications). + // However, on Samsung S3 with Android 4.3 it looks like the 2 gatt calls + // (gatt.setCharacteristicNotification(...) and gatt.writeDescriptor(...)) are called + // too quickly, or from a wrong thread, and in result the notification listener is not + // set, causing onCharacteristicChanged(...) callback never being called when a + // notification comes. Enabling them here, like below, solves the problem. + // However... the original approach works for the Battery Level CCCD, which makes it + // even weirder. + /* + gatt.setCharacteristicNotification(mGlucoseMeasurementCharacteristic, true); + if (mGlucoseMeasurementContextCharacteristic != null) { + device.setCharacteristicNotification(mGlucoseMeasurementContextCharacteristic, true); + } + device.setCharacteristicNotification(mRecordAccessControlPointCharacteristic, true); + */ + setNotificationCallback(mGlucoseMeasurementCharacteristic) + .with(new GlucoseMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + GlucoseMeasurementParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onGlucoseMeasurementReceived(@NonNull final BluetoothDevice device, final int sequenceNumber, + @NonNull final Calendar time, @Nullable final Float glucoseConcentration, + @Nullable final Integer unit, @Nullable final Integer type, + @Nullable final Integer sampleLocation, @Nullable final GlucoseStatus status, + final boolean contextInformationFollows) { + final GlucoseRecord record = new GlucoseRecord(); + record.sequenceNumber = sequenceNumber; + record.time = time; + record.glucoseConcentration = glucoseConcentration != null ? glucoseConcentration : 0; + record.unit = unit != null ? unit : UNIT_kg_L; + record.type = type != null ? type : 0; + record.sampleLocation = sampleLocation != null ? sampleLocation : 0; + record.status = status != null ? status.value : 0; + + // insert the new record to storage + mRecords.put(record.sequenceNumber, record); + mHandler.post(() -> { + // if there is no context information following the measurement data, + // notify callback about the new record + if (!contextInformationFollows) + mCallbacks.onDatasetChanged(device); + }); + } + }); + + setNotificationCallback(mGlucoseMeasurementContextCharacteristic) + .with(new GlucoseMeasurementContextDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + GlucoseMeasurementContextParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onGlucoseMeasurementContextReceived(@NonNull final BluetoothDevice device, final int sequenceNumber, + @Nullable final Carbohydrate carbohydrate, @Nullable final Float carbohydrateAmount, + @Nullable final Meal meal, @Nullable final Tester tester, + @Nullable final Health health, @Nullable final Integer exerciseDuration, + @Nullable final Integer exerciseIntensity, @Nullable final Medication medication, + @Nullable final Float medicationAmount, @Nullable final Integer medicationUnit, + @Nullable final Float HbA1c) { + final GlucoseRecord record = mRecords.get(sequenceNumber); + if (record == null) { + DebugLogger.w(TAG, "Context information with unknown sequence number: " + sequenceNumber); + return; + } + final GlucoseRecord.MeasurementContext context = new GlucoseRecord.MeasurementContext(); + record.context = context; + context.carbohydrateId = carbohydrate != null ? carbohydrate.value : 0; + context.carbohydrateUnits = carbohydrateAmount != null ? carbohydrateAmount : 0; + context.meal = meal != null ? meal.value : 0; + context.tester = tester != null ? tester.value : 0; + context.health = health != null ? health.value : 0; + context.exerciseDuration = exerciseDuration != null ? exerciseDuration : 0; + context.exerciseIntensity = exerciseIntensity != null ? exerciseIntensity : 0; + context.medicationId = medication != null ? medication.value : 0; + context.medicationQuantity = medicationAmount != null ? medicationAmount : 0; + context.medicationUnit = medicationUnit != null ? medicationUnit : UNIT_mg; + context.HbA1c = HbA1c != null ? HbA1c : 0; + + mHandler.post(() -> { + // notify callback about the new record + mCallbacks.onDatasetChanged(device); + }); + } + }); + + setIndicationCallback(mRecordAccessControlPointCharacteristic) + .with(new RecordAccessControlPointDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onRecordAccessOperationCompleted(@NonNull final BluetoothDevice device, final int requestCode) { + switch (requestCode) { + case RACP_OP_CODE_ABORT_OPERATION: + mCallbacks.onOperationAborted(device); + break; + default: + mCallbacks.onOperationCompleted(device); + break; + } + } + + @Override + public void onRecordAccessOperationCompletedWithNoRecordsFound(@NonNull final BluetoothDevice device, final int requestCode) { + mCallbacks.onOperationCompleted(device); + } + + @Override + public void onNumberOfRecordsReceived(@NonNull final BluetoothDevice device, final int numberOfRecords) { + mCallbacks.onNumberOfRecordsRequested(device, numberOfRecords); + if (numberOfRecords > 0) { + if (mRecords.size() > 0) { + final int sequenceNumber = mRecords.keyAt(mRecords.size() - 1) + 1; + writeCharacteristic(mRecordAccessControlPointCharacteristic, + RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo(sequenceNumber)) + .enqueue(); + } else { + writeCharacteristic(mRecordAccessControlPointCharacteristic, + RecordAccessControlPointData.reportAllStoredRecords()) + .enqueue(); + } + } else { + mCallbacks.onOperationCompleted(device); + } + } + + @Override + public void onRecordAccessOperationError(@NonNull final BluetoothDevice device, + final int requestCode, final int errorCode) { + log(Log.WARN, "Record Access operation failed (error " + errorCode + ")"); + if (errorCode == RACP_ERROR_OP_CODE_NOT_SUPPORTED) { + mCallbacks.onOperationNotSupported(device); + } else { + mCallbacks.onOperationFailed(device); + } + } + }); + + enableNotifications(mGlucoseMeasurementCharacteristic).enqueue(); + enableNotifications(mGlucoseMeasurementContextCharacteristic).enqueue(); + enableIndications(mRecordAccessControlPointCharacteristic) + .fail((device, status) -> log(Log.WARN, "Failed to enabled Record Access Control Point indications (error " + status + ")")) + .enqueue(); + } + + @Override + public boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(GLS_SERVICE_UUID); + if (service != null) { + mGlucoseMeasurementCharacteristic = service.getCharacteristic(GM_CHARACTERISTIC); + mGlucoseMeasurementContextCharacteristic = service.getCharacteristic(GM_CONTEXT_CHARACTERISTIC); + mRecordAccessControlPointCharacteristic = service.getCharacteristic(RACP_CHARACTERISTIC); + } + return mGlucoseMeasurementCharacteristic != null && mRecordAccessControlPointCharacteristic != null; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull BluetoothGatt gatt) { + super.isOptionalServiceSupported(gatt); + return mGlucoseMeasurementContextCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + mGlucoseMeasurementCharacteristic = null; + mGlucoseMeasurementContextCharacteristic = null; + mRecordAccessControlPointCharacteristic = null; + } + }; + + /** + * Returns all records as a sparse array where sequence number is the key. + * + * @return the records list. + */ + public SparseArray getRecords() { + return mRecords; + } + + /** + * Clears the records list locally. + */ + public void clear() { + mRecords.clear(); + mCallbacks.onOperationCompleted(getBluetoothDevice()); + } + + /** + * Sends the request to obtain the last (most recent) record from glucose device. The data will + * be returned to Glucose Measurement characteristic as a notification followed by Record Access + * Control Point indication with status code Success or other in case of error. + */ + public void getLastRecord() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportLastStoredRecord()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to obtain the first (oldest) record from glucose device. The data will be + * returned to Glucose Measurement characteristic as a notification followed by Record Access + * Control Point indication with status code Success or other in case of error. + */ + public void getFirstRecord() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportFirstStoredRecord()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to obtain all records from glucose device. Initially we want to notify user + * about the number of the records so the 'Report Number of Stored Records' is send. The data + * will be returned to Glucose Measurement characteristic as a notification followed by + * Record Access Control Point indication with status code Success or other in case of error. + */ + public void getAllRecords() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.reportNumberOfAllStoredRecords()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to obtain from the glucose device all records newer than the newest one + * from local storage. The data will be returned to Glucose Measurement characteristic as + * a notification followed by Record Access Control Point indication with status code Success + * or other in case of error. + *

+ * Refresh button will not download records older than the oldest in the local memory. + * E.g. if you have pressed Last and then Refresh, than it will try to get only newer records. + * However if there are no records, it will download all existing (using {@link #getAllRecords()}). + */ + public void refreshRecords() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + if (mRecords.size() == 0) { + getAllRecords(); + } else { + mCallbacks.onOperationStarted(getBluetoothDevice()); + + // obtain the last sequence number + final int sequenceNumber = mRecords.keyAt(mRecords.size() - 1) + 1; + + writeCharacteristic(mRecordAccessControlPointCharacteristic, + RecordAccessControlPointData.reportStoredRecordsGreaterThenOrEqualTo(sequenceNumber)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + // Info: + // Operators OPERATOR_LESS_THEN_OR_EQUAL and OPERATOR_RANGE are not supported by Nordic Semiconductor Glucose Service in SDK 4.4.2. + } + } + + /** + * Sends abort operation signal to the device. + */ + public void abort() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.abortOperation()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } + + /** + * Sends the request to delete all data from the device. A Record Access Control Point + * indication with status code Success (or other in case of error) will be send. + */ + public void deleteAllRecords() { + if (mRecordAccessControlPointCharacteristic == null) + return; + + clear(); + mCallbacks.onOperationStarted(getBluetoothDevice()); + writeCharacteristic(mRecordAccessControlPointCharacteristic, RecordAccessControlPointData.deleteAllStoredRecords()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, "\"" + RecordAccessControlPointParser.parse(data) + "\" sent")) + .enqueue(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManagerCallbacks.java new file mode 100644 index 0000000..dff848f --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManagerCallbacks.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.gls; + +import android.bluetooth.BluetoothDevice; + +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +public interface GlucoseManagerCallbacks extends BatteryManagerCallbacks { + + void onOperationStarted(final BluetoothDevice device); + + void onOperationCompleted(final BluetoothDevice device); + + void onOperationFailed(final BluetoothDevice device); + + void onOperationAborted(final BluetoothDevice device); + + void onOperationNotSupported(final BluetoothDevice device); + + void onDatasetChanged(final BluetoothDevice device); + + void onNumberOfRecordsRequested(final BluetoothDevice device, final int value); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseRecord.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseRecord.java new file mode 100644 index 0000000..f83c173 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseRecord.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.gls; + +import java.util.Calendar; + +public class GlucoseRecord { + public static final int UNIT_kgpl = 0; + public static final int UNIT_molpl = 1; + + /** Record sequence number */ + protected int sequenceNumber; + /** The base time of the measurement */ + protected Calendar time; + /** Time offset of the record */ + protected int timeOffset; + /** The glucose concentration. 0 if not present */ + protected float glucoseConcentration; + /** Concentration unit. One of the following: {@link GlucoseRecord#UNIT_kgpl}, {@link GlucoseRecord#UNIT_molpl} */ + protected int unit; + /** The type of the record. 0 if not present */ + protected int type; + /** The sample location. 0 if unknown */ + protected int sampleLocation; + /** Sensor status annunciation flags. 0 if not present */ + protected int status; + + protected MeasurementContext context; + + public static class MeasurementContext { + public static final int UNIT_kg = 0; + public static final int UNIT_l = 1; + + /** + * One of the following:
+ * 0 Not present
+ * 1 Breakfast
+ * 2 Lunch
+ * 3 Dinner
+ * 4 Snack
+ * 5 Drink
+ * 6 Supper
+ * 7 Brunch + */ + protected int carbohydrateId; + /** Number of kilograms of carbohydrate */ + protected float carbohydrateUnits; + /** + * One of the following:
+ * 0 Not present
+ * 1 Preprandial (before meal)
+ * 2 Postprandial (after meal)
+ * 3 Fasting
+ * 4 Casual (snacks, drinks, etc.)
+ * 5 Bedtime + */ + protected int meal; + /** + * One of the following:
+ * 0 Not present
+ * 1 Self
+ * 2 Health Care Professional
+ * 3 Lab test
+ * 15 Tester value not available + */ + protected int tester; + /** + * One of the following:
+ * 0 Not present
+ * 1 Minor health issues
+ * 2 Major health issues
+ * 3 During menses
+ * 4 Under stress
+ * 5 No health issues
+ * 15 Tester value not available + */ + protected int health; + /** Exercise duration in seconds. 0 if not present */ + protected int exerciseDuration; + /** Exercise intensity in percent. 0 if not present */ + protected int exerciseIntensity; + /** + * One of the following:
+ * 0 Not present
+ * 1 Rapid acting insulin
+ * 2 Short acting insulin
+ * 3 Intermediate acting insulin
+ * 4 Long acting insulin
+ * 5 Pre-mixed insulin + */ + protected int medicationId; + /** Quantity of medication. See {@link #medicationUnit} for the unit. */ + protected float medicationQuantity; + /** One of the following: {@link GlucoseRecord.MeasurementContext#UNIT_kg}, {@link GlucoseRecord.MeasurementContext#UNIT_l}. */ + protected int medicationUnit; + /** HbA1c value. 0 if not present */ + protected float HbA1c; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSActivity.java new file mode 100644 index 0000000..da5ec71 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSActivity.java @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hrs; + +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.Intent; +import android.graphics.Point; +import android.os.Bundle; +import android.os.Handler; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.achartengine.GraphicalView; + +import java.util.List; +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileActivity; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +/** + * HRSActivity is the main Heart rate activity. It implements HRSManagerCallbacks to receive callbacks from HRSManager class. The activity supports portrait and landscape orientations. The activity + * uses external library AChartEngine to show real time graph of HR values. + */ +// TODO The HRSActivity should be rewritten to use the service approach, like other do. +public class HRSActivity extends BleProfileActivity implements HRSManagerCallbacks { + @SuppressWarnings("unused") + private final String TAG = "HRSActivity"; + + private final static String GRAPH_STATUS = "graph_status"; + private final static String GRAPH_COUNTER = "graph_counter"; + private final static String HR_VALUE = "hr_value"; + + private final static int REFRESH_INTERVAL = 1000; // 1 second interval + + private Handler mHandler = new Handler(); + + private boolean isGraphInProgress = false; + + private GraphicalView mGraphView; + private LineGraphView mLineGraph; + private TextView mHRSValue, mHRSPosition; + private TextView mBatteryLevelView; + + private int mHrmValue = 0; + private int mCounter = 0; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_hrs); + setGUI(); + } + + private void setGUI() { + mLineGraph = LineGraphView.getLineGraphView(); + mHRSValue = findViewById(R.id.text_hrs_value); + mHRSPosition = findViewById(R.id.text_hrs_position); + mBatteryLevelView = findViewById(R.id.battery); + showGraph(); + } + + private void showGraph() { + mGraphView = mLineGraph.getView(this); + ViewGroup layout = findViewById(R.id.graph_hrs); + layout.addView(mGraphView); + } + + @Override + protected void onStart() { + super.onStart(); + + final Intent intent = getIntent(); + if (!isDeviceConnected() && intent.hasExtra(FeaturesActivity.EXTRA_ADDRESS)) { + final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(getIntent().getByteArrayExtra(FeaturesActivity.EXTRA_ADDRESS)); + onDeviceSelected(device, device.getName()); + + intent.removeExtra(FeaturesActivity.EXTRA_APP); + intent.removeExtra(FeaturesActivity.EXTRA_ADDRESS); + } + } + + @Override + protected void onRestoreInstanceState(@NonNull final Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + + isGraphInProgress = savedInstanceState.getBoolean(GRAPH_STATUS); + mCounter = savedInstanceState.getInt(GRAPH_COUNTER); + mHrmValue = savedInstanceState.getInt(HR_VALUE); + + if (isGraphInProgress) + startShowGraph(); + } + + @Override + protected void onSaveInstanceState(final Bundle outState) { + super.onSaveInstanceState(outState); + + outState.putBoolean(GRAPH_STATUS, isGraphInProgress); + outState.putInt(GRAPH_COUNTER, mCounter); + outState.putInt(HR_VALUE, mHrmValue); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + + stopShowGraph(); + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.hrs_feature_title; + } + + @Override + protected int getAboutTextId() { + return R.string.hrs_about_text; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.hrs_default_name; + } + + @Override + protected UUID getFilterUUID() { + return HRSManager.HR_SERVICE_UUID; + } + + private void updateGraph(final int hrmValue) { + mCounter++; + mLineGraph.addValue(new Point(mCounter, hrmValue)); + mGraphView.repaint(); + } + + private Runnable mRepeatTask = new Runnable() { + @Override + public void run() { + if (mHrmValue > 0) + updateGraph(mHrmValue); + if (isGraphInProgress) + mHandler.postDelayed(mRepeatTask, REFRESH_INTERVAL); + } + }; + + void startShowGraph() { + isGraphInProgress = true; + mRepeatTask.run(); + } + + void stopShowGraph() { + isGraphInProgress = false; + mHandler.removeCallbacks(mRepeatTask); + } + + @Override + protected LoggableBleManager initializeManager() { + final HRSManager manager = HRSManager.getInstance(getApplicationContext()); + manager.setGattCallbacks(this); + return manager; + } + + @Override + public void onServicesDiscovered(@NonNull final BluetoothDevice device, final boolean optionalServicesFound) { + // this may notify user or show some views + } + + @Override + public void onDeviceReady(@NonNull final BluetoothDevice device) { + startShowGraph(); + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + runOnUiThread(() -> mBatteryLevelView.setText(getString(R.string.battery, batteryLevel))); + } + + @Override + public void onBodySensorLocationReceived(@NonNull final BluetoothDevice device, final int sensorLocation) { + runOnUiThread(() -> { + if (sensorLocation >= SENSOR_LOCATION_FIRST && sensorLocation <= SENSOR_LOCATION_LAST) { + mHRSPosition.setText(getResources().getStringArray(R.array.hrs_locations)[sensorLocation]); + } else { + mHRSPosition.setText(R.string.hrs_location_other); + } + }); + } + + @Override + public void onHeartRateMeasurementReceived(@NonNull final BluetoothDevice device, final int heartRate, + @Nullable final Boolean contactDetected, + @Nullable final Integer energyExpanded, + @Nullable final List rrIntervals) { + mHrmValue = heartRate; + runOnUiThread(() -> mHRSValue.setText(getString(R.string.hrs_value, heartRate))); + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + super.onDeviceDisconnected(device); + runOnUiThread(() -> { + mHRSValue.setText(R.string.not_available_value); + mHRSPosition.setText(R.string.not_available); + mBatteryLevelView.setText(R.string.not_available); + stopShowGraph(); + }); + } + + @Override + protected void setDefaultUI() { + mHRSValue.setText(R.string.not_available_value); + mHRSPosition.setText(R.string.not_available); + mBatteryLevelView.setText(R.string.not_available); + clearGraph(); + } + + private void clearGraph() { + mLineGraph.clearGraph(); + mGraphView.repaint(); + mCounter = 0; + mHrmValue = 0; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManager.java new file mode 100644 index 0000000..861d640 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManager.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hrs; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.util.Log; + +import java.util.List; +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.hr.BodySensorLocationDataCallback; +import no.nordicsemi.android.ble.common.callback.hr.HeartRateMeasurementDataCallback; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.BodySensorLocationParser; +import no.nordicsemi.android.nrftoolbox.parser.HeartRateMeasurementParser; + +/** + * HRSManager class performs BluetoothGatt operations for connection, service discovery, + * enabling notification and reading characteristics. + * All operations required to connect to device with BLE Heart Rate Service and reading + * heart rate values are performed here. + */ +public class HRSManager extends BatteryManager { + static final UUID HR_SERVICE_UUID = UUID.fromString("0000180D-0000-1000-8000-00805f9b34fb"); + private static final UUID BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID = UUID.fromString("00002A38-0000-1000-8000-00805f9b34fb"); + private static final UUID HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00002A37-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mHeartRateCharacteristic, mBodySensorLocationCharacteristic; + + private static HRSManager managerInstance = null; + + /** + * Singleton implementation of HRSManager class. + */ + public static synchronized HRSManager getInstance(final Context context) { + if (managerInstance == null) { + managerInstance = new HRSManager(context); + } + return managerInstance; + } + + private HRSManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving notification, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + readCharacteristic(mBodySensorLocationCharacteristic) + .with(new BodySensorLocationDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + BodySensorLocationParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onBodySensorLocationReceived(@NonNull final BluetoothDevice device, + final int sensorLocation) { + mCallbacks.onBodySensorLocationReceived(device, sensorLocation); + } + }) + .fail((device, status) -> log(Log.WARN, "Body Sensor Location characteristic not found")) + .enqueue(); + setNotificationCallback(mHeartRateCharacteristic) + .with(new HeartRateMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + HeartRateMeasurementParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onHeartRateMeasurementReceived(@NonNull final BluetoothDevice device, + final int heartRate, + @Nullable final Boolean contactDetected, + @Nullable final Integer energyExpanded, + @Nullable final List rrIntervals) { + mCallbacks.onHeartRateMeasurementReceived(device, heartRate, contactDetected, energyExpanded, rrIntervals); + } + }); + enableNotifications(mHeartRateCharacteristic).enqueue(); + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(HR_SERVICE_UUID); + if (service != null) { + mHeartRateCharacteristic = service.getCharacteristic(HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID); + } + return mHeartRateCharacteristic != null; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + super.isOptionalServiceSupported(gatt); + final BluetoothGattService service = gatt.getService(HR_SERVICE_UUID); + if (service != null) { + mBodySensorLocationCharacteristic = service.getCharacteristic(BODY_SENSOR_LOCATION_CHARACTERISTIC_UUID); + } + return mBodySensorLocationCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + mBodySensorLocationCharacteristic = null; + mHeartRateCharacteristic = null; + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManagerCallbacks.java new file mode 100644 index 0000000..79f1870 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManagerCallbacks.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hrs; + +import no.nordicsemi.android.ble.common.profile.hr.BodySensorLocationCallback; +import no.nordicsemi.android.ble.common.profile.hr.HeartRateMeasurementCallback; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +interface HRSManagerCallbacks extends BatteryManagerCallbacks, BodySensorLocationCallback, HeartRateMeasurementCallback { + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/LineGraphView.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/LineGraphView.java new file mode 100644 index 0000000..b3844c6 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/LineGraphView.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hrs; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.Paint.Align; +import android.graphics.Point; + +import org.achartengine.ChartFactory; +import org.achartengine.GraphicalView; +import org.achartengine.chart.PointStyle; +import org.achartengine.model.TimeSeries; +import org.achartengine.model.XYMultipleSeriesDataset; +import org.achartengine.renderer.XYMultipleSeriesRenderer; +import org.achartengine.renderer.XYSeriesRenderer; + +/** + * This class uses external library AChartEngine to show dynamic real time line graph for HR values + */ +public class LineGraphView { + //TimeSeries will hold the data in x,y format for single chart + private TimeSeries mSeries = new TimeSeries("Heart Rate"); + //XYMultipleSeriesDataset will contain all the TimeSeries + private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset(); + //XYMultipleSeriesRenderer will contain all XYSeriesRenderer and it can be used to set the properties of whole Graph + private XYMultipleSeriesRenderer mMultiRenderer = new XYMultipleSeriesRenderer(); + private static LineGraphView mInstance = null; + + /** + * singleton implementation of LineGraphView class + */ + public static synchronized LineGraphView getLineGraphView() { + if (mInstance == null) { + mInstance = new LineGraphView(); + } + return mInstance; + } + + /** + * This constructor will set some properties of single chart and some properties of whole graph + */ + public LineGraphView() { + //add single line chart mSeries + mDataset.addSeries(mSeries); + + //XYSeriesRenderer is used to set the properties like chart color, style of each point, etc. of single chart + final XYSeriesRenderer seriesRenderer = new XYSeriesRenderer(); + //set line chart color to Black + seriesRenderer.setColor(Color.BLACK); + //set line chart style to square points + seriesRenderer.setPointStyle(PointStyle.SQUARE); + seriesRenderer.setFillPoints(true); + + final XYMultipleSeriesRenderer renderer = mMultiRenderer; + //set whole graph background color to transparent color + renderer.setBackgroundColor(Color.TRANSPARENT); + renderer.setMargins(new int[] { 50, 65, 40, 5 }); // top, left, bottom, right + renderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01)); + renderer.setAxesColor(Color.BLACK); + renderer.setAxisTitleTextSize(24); + renderer.setShowGrid(true); + renderer.setGridColor(Color.LTGRAY); + renderer.setLabelsColor(Color.BLACK); + renderer.setYLabelsColor(0, Color.DKGRAY); + renderer.setYLabelsAlign(Align.RIGHT); + renderer.setYLabelsPadding(4.0f); + renderer.setXLabelsColor(Color.DKGRAY); + renderer.setLabelsTextSize(20); + renderer.setLegendTextSize(20); + //Disable zoom + renderer.setPanEnabled(false, false); + renderer.setZoomEnabled(false, false); + //set title to x-axis and y-axis + renderer.setXTitle(" Time (seconds)"); + renderer.setYTitle(" BPM"); + renderer.addSeriesRenderer(seriesRenderer); + } + + /** + * return graph view to activity + */ + public GraphicalView getView(Context context) { + final GraphicalView graphView = ChartFactory.getLineChartView(context, mDataset, mMultiRenderer); + return graphView; + } + + /** + * add new x,y value to chart + */ + public void addValue(Point p) { + mSeries.add(p.x, p.y); + } + + /** + * clear all previous values of chart + */ + public void clearGraph() { + mSeries.clear(); + } + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSActivity.java new file mode 100644 index 0000000..59626cb --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSActivity.java @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hts; + +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.view.Menu; +import android.widget.TextView; + +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.hts.settings.SettingsActivity; +import no.nordicsemi.android.nrftoolbox.hts.settings.SettingsFragment; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; + +/** + * HTSActivity is the main Health Thermometer activity. It implements {@link HTSManagerCallbacks} + * to receive callbacks from {@link HTSManager} class. The activity supports portrait and landscape + * orientations. + */ +public class HTSActivity extends BleProfileServiceReadyActivity { + @SuppressWarnings("unused") + private final String TAG = "HTSActivity"; + + private TextView mTempValue; + private TextView mUnit; + private TextView mBatteryLevelView; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_hts); + setGUI(); + } + + @Override + protected void onInitialize(final Bundle savedInstanceState) { + LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); + } + + private void setGUI() { + mTempValue = findViewById(R.id.text_hts_value); + mUnit = findViewById(R.id.text_hts_unit); + mBatteryLevelView = findViewById(R.id.battery); + } + + @Override + protected void onResume() { + super.onResume(); + setUnits(); + } + + @Override + protected void setDefaultUI() { + mTempValue.setText(R.string.not_available_value); + mBatteryLevelView.setText(R.string.not_available); + + setUnits(); + } + + private void setUnits() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_C: + mUnit.setText(R.string.hts_unit_celsius); + break; + case SettingsFragment.SETTINGS_UNIT_F: + mUnit.setText(R.string.hts_unit_fahrenheit); + break; + case SettingsFragment.SETTINGS_UNIT_K: + mUnit.setText(R.string.hts_unit_kelvin); + break; + } + } + + @Override + protected void onServiceBound(final HTSService.HTSBinder binder) { + onTemperatureMeasurementReceived(binder.getTemperature()); + } + + @Override + protected void onServiceUnbound() { + // not used + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.hts_feature_title; + } + + @Override + protected int getAboutTextId() { + return R.string.hts_about_text; + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.settings_and_about, menu); + return true; + } + + @Override + protected boolean onOptionsItemSelected(final int itemId) { + switch (itemId) { + case R.id.action_settings: + final Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + break; + } + return true; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.hts_default_name; + } + + @Override + protected UUID getFilterUUID() { + return HTSManager.HT_SERVICE_UUID; + } + + @Override + protected Class getServiceClass() { + return HTSService.class; + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, boolean optionalServicesFound) { + // this may notify user or show some views + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + mBatteryLevelView.setText(R.string.not_available); + } + + private void onTemperatureMeasurementReceived(Float value) { + if (value != null) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, + String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_F: + value = value * 1.8f + 32f; + break; + case SettingsFragment.SETTINGS_UNIT_K: + value += 273.15f; + break; + case SettingsFragment.SETTINGS_UNIT_C: + break; + } + mTempValue.setText(getString(R.string.hts_value, value)); + } else { + mTempValue.setText(R.string.not_available_value); + } + } + + public void onBatteryLevelChanged(final int value) { + mBatteryLevelView.setText(getString(R.string.battery, value)); + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + + if (HTSService.BROADCAST_HTS_MEASUREMENT.equals(action)) { + final float value = intent.getFloatExtra(HTSService.EXTRA_TEMPERATURE, 0.0f); + // Update GUI + onTemperatureMeasurementReceived(value); + } else if (HTSService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(HTSService.EXTRA_BATTERY_LEVEL, 0); + // Update GUI + onBatteryLevelChanged(batteryLevel); + } + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(HTSService.BROADCAST_HTS_MEASUREMENT); + intentFilter.addAction(HTSService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManager.java new file mode 100644 index 0000000..732d616 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManager.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hts; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import java.util.Calendar; +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.ht.TemperatureMeasurementDataCallback; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.TemperatureMeasurementParser; + +/** + * HTSManager class performs BluetoothGatt operations for connection, service discovery, enabling + * indication and reading characteristics. All operations required to connect to device with BLE HT + * Service and reading health thermometer values are performed here. + * HTSActivity implements HTSManagerCallbacks in order to receive callbacks of BluetoothGatt operations. + */ +public class HTSManager extends BatteryManager { + /** Health Thermometer service UUID */ + public final static UUID HT_SERVICE_UUID = UUID.fromString("00001809-0000-1000-8000-00805f9b34fb"); + /** Health Thermometer Measurement characteristic UUID */ + private static final UUID HT_MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mHTCharacteristic; + + HTSManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving indication, etc.. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + @Override + protected void initialize() { + super.initialize(); + setIndicationCallback(mHTCharacteristic) + .with(new TemperatureMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + TemperatureMeasurementParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onTemperatureMeasurementReceived(@NonNull final BluetoothDevice device, + final float temperature, final int unit, + @Nullable final Calendar calendar, + @Nullable final Integer type) { + mCallbacks.onTemperatureMeasurementReceived(device, temperature, unit, calendar, type); + } + }); + enableIndications(mHTCharacteristic).enqueue(); + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(HT_SERVICE_UUID); + if (service != null) { + mHTCharacteristic = service.getCharacteristic(HT_MEASUREMENT_CHARACTERISTIC_UUID); + } + return mHTCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + mHTCharacteristic = null; + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManagerCallbacks.java new file mode 100644 index 0000000..c8053b0 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManagerCallbacks.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.hts; + +import no.nordicsemi.android.ble.common.profile.ht.TemperatureMeasurementCallback; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +/** + * Interface {@link HTSManagerCallbacks} must be implemented by {@link HTSActivity} in order + * to receive callbacks from {@link HTSManager}. + */ +interface HTSManagerCallbacks extends BatteryManagerCallbacks, TemperatureMeasurementCallback { + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSService.java new file mode 100644 index 0000000..811740e --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSService.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.hts; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import java.util.Calendar; + +import no.nordicsemi.android.ble.common.profile.ht.TemperatureMeasurementCallback; +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +@SuppressWarnings("FieldCanBeLocal") +public class HTSService extends BleProfileService implements HTSManagerCallbacks { + public static final String BROADCAST_HTS_MEASUREMENT = "no.nordicsemi.android.nrftoolbox.hts.BROADCAST_HTS_MEASUREMENT"; + public static final String EXTRA_TEMPERATURE = "no.nordicsemi.android.nrftoolbox.hts.EXTRA_TEMPERATURE"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + + private final static String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.hts.ACTION_DISCONNECT"; + + private final static int NOTIFICATION_ID = 267; + private final static int OPEN_ACTIVITY_REQ = 0; + private final static int DISCONNECT_REQ = 1; + /** The last received temperature value in Celsius degrees. */ + private Float mTemp; + + @SuppressWarnings("unused") + private HTSManager mManager; + + private final LocalBinder mBinder = new HTSBinder(); + + /** + * This local binder is an interface for the bonded activity to operate with the HTS sensor + */ + class HTSBinder extends LocalBinder { + /** + * Returns the last received temperature value. + * + * @return Temperature value in Celsius. + */ + Float getTemperature() { + return mTemp; + } + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new HTSManager(this); + } + + @Override + public void onCreate() { + super.onCreate(); + + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + // when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + // when the activity rebinds to the service, remove the notification + cancelNotification(); + } + + @Override + protected void onUnbind() { + // when the activity closes we need to show the notification that user is connected to the sensor + createNotification(R.string.hts_notification_connected_message, 0); + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + mTemp = null; + } + + @Override + public void onTemperatureMeasurementReceived(@NonNull final BluetoothDevice device, + final float temperature, final int unit, + @Nullable final Calendar calendar, + @Nullable final Integer type) { + mTemp = TemperatureMeasurementCallback.toCelsius(temperature, unit); + + final Intent broadcast = new Intent(BROADCAST_HTS_MEASUREMENT); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_TEMPERATURE, mTemp); + // ignore the rest + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + if (!mBound) { + // Here we may update the notification to display the current temperature. + // TODO modify the notification here + } + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, batteryLevel); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * Creates the notification + * + * @param messageResId + * message resource id. The message must have one String parameter,
+ * f.e. <string name="name">%s is connected</string> + * @param defaults + * signals that will be used to notify the user + */ + private void createNotification(final int messageResId, final int defaults) { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, HTSActivity.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + // both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[] { parentIntent, targetIntent }, PendingIntent.FLAG_UPDATE_CURRENT); + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.CONNECTED_DEVICE_CHANNEL); + builder.setContentIntent(pendingIntent); + builder.setContentTitle(getString(R.string.app_name)).setContentText(getString(messageResId, getDeviceName())); + builder.setSmallIcon(R.drawable.ic_stat_notify_hts); + builder.setShowWhen(defaults != 0).setDefaults(defaults).setAutoCancel(true).setOngoing(true); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.hts_notification_action_disconnect), disconnectAction)); + + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + Logger.i(getLogSession(), "[Notification] Disconnect action pressed"); + if (isConnected()) + getBinder().disconnect(); + else + stopSelf(); + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsActivity.java new file mode 100644 index 0000000..30065d7 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsActivity.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.hts.settings; + +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; + +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsActivity extends AppCompatActivity { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // Display the fragment as the main content. + getSupportFragmentManager().beginTransaction().replace(R.id.content, new SettingsFragment()).commit(); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsFragment.java new file mode 100644 index 0000000..27bd3d7 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsFragment.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.hts.settings; + +import android.os.Bundle; +import android.preference.PreferenceFragment; + +import androidx.preference.PreferenceFragmentCompat; +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsFragment extends PreferenceFragmentCompat { + public static final String SETTINGS_UNIT = "settings_hts_unit"; + public static final int SETTINGS_UNIT_C = 0; // [C] + public static final int SETTINGS_UNIT_F = 1; // [F] + public static final int SETTINGS_UNIT_K = 2; // [K] + public static final int SETTINGS_UNIT_DEFAULT = SETTINGS_UNIT_C; + + @Override + public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { + addPreferencesFromResource(R.xml.settings_hts); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/AlertLevelParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/AlertLevelParser.java new file mode 100644 index 0000000..68ff78b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/AlertLevelParser.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import android.bluetooth.BluetoothGattCharacteristic; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class AlertLevelParser { + public static String parse(final BluetoothGattCharacteristic characteristic) { + return parse(Data.from(characteristic)); + } + + /** + * Parses the alert level. + * + * @param data + * @return alert level in human readable format + */ + public static String parse(final Data data) { + final int value = data.getIntValue(Data.FORMAT_UINT8, 0); + + switch (value) { + case 0: + return "No Alert"; + case 1: + return "Mild Alert"; + case 2: + return "High Alert"; + default: + return "Reserved value (" + value + ")"; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BloodPressureMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BloodPressureMeasurementParser.java new file mode 100644 index 0000000..9351730 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BloodPressureMeasurementParser.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class BloodPressureMeasurementParser { + + public static String parse(final Data data) { + final StringBuilder builder = new StringBuilder(); + + // first byte - flags + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + final int unitType = flags & 0x01; + final boolean timestampPresent = (flags & 0x02) > 0; + final boolean pulseRatePresent = (flags & 0x04) > 0; + final boolean userIdPresent = (flags & 0x08) > 0; + final boolean statusPresent = (flags & 0x10) > 0; + + // following bytes - systolic, diastolic and mean arterial pressure + final float systolic = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + final float diastolic = data.getFloatValue(Data.FORMAT_SFLOAT, offset + 2); + final float meanArterialPressure = data.getFloatValue(Data.FORMAT_SFLOAT, offset + 4); + final String unit = unitType == 0 ? " mmHg" : " kPa"; + offset += 6; + builder.append("Systolic: ").append(systolic).append(unit); + builder.append("\nDiastolic: ").append(diastolic).append(unit); + builder.append("\nMean AP: ").append(meanArterialPressure).append(unit); + + // parse timestamp if present + if (timestampPresent) { + builder.append("\nTimestamp: ").append(DateTimeParser.parse(data, offset)); + offset += 7; + } + + // parse pulse rate if present + if (pulseRatePresent) { + final float pulseRate = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + builder.append("\nPulse: ").append(pulseRate).append(" bpm"); + } + + if (userIdPresent) { + final int userId = data.getIntValue(Data.FORMAT_UINT8, offset); + offset += 1; + builder.append("\nUser ID: ").append(userId); + } + + if (statusPresent) { + final int status = data.getIntValue(Data.FORMAT_UINT16, offset); + // offset += 2; + if ((status & 0x0001) > 0) + builder.append("\nBody movement detected"); + if ((status & 0x0002) > 0) + builder.append("\nCuff too lose"); + if ((status & 0x0004) > 0) + builder.append("\nIrregular pulse detected"); + if ((status & 0x0018) == 0x0008) + builder.append("\nPulse rate exceeds upper limit"); + if ((status & 0x0018) == 0x0010) + builder.append("\nPulse rate is less than lower limit"); + if ((status & 0x0018) == 0x0018) + builder.append("\nPulse rate range: Reserved for future use "); + if ((status & 0x0020) > 0) + builder.append("\nImproper measurement position"); + } + + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BodySensorLocationParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BodySensorLocationParser.java new file mode 100644 index 0000000..22d1731 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BodySensorLocationParser.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class BodySensorLocationParser { + + public static String parse(final Data data) { + final int value = data.getIntValue(Data.FORMAT_UINT8, 0); + + switch (value) { + case 6: return "Foot"; + case 5: return "Ear Lobe"; + case 4: return "Hand"; + case 3: return "Finger"; + case 2: return "Wrist"; + case 1: return "Chest"; + case 0: + default: return "Other"; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMMeasurementParser.java new file mode 100644 index 0000000..6c9c807 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMMeasurementParser.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import java.util.Locale; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class CGMMeasurementParser { + private static final int FLAGS_CGM_TREND_INFO_PRESENT = 1; + private static final int FLAGS_CGM_QUALITY_PRESENT = 1 << 1; + private static final int FLAGS_SENSOR_STATUS_ANNUNCIATION_WARNING_OCTET_PRESENT = 1 << 2; + private static final int FLAGS_SENSOR_STATUS_ANNUNCIATION_CAL_TEMP_OCTET_PRESENT = 1 << 3; + private static final int FLAGS_SENSOR_STATUS_ANNUNCIATION_STATUS_OCTET_PRESENT = 1 << 4; + + private static final int SSA_SESSION_STOPPED = 1; + private static final int SSA_DEVICE_BATTERY_LOW = 1 << 1; + private static final int SSA_SENSOR_TYPE_INCORRECT = 1 << 2; + private static final int SSA_SENSOR_MALFUNCTION = 1 << 3; + private static final int SSA_DEVICE_SPEC_ALERT = 1 << 4; + private static final int SSA_GENERAL_DEVICE_FAULT = 1 << 5; + + private static final int SSA_TIME_SYNC_REQUIRED = 1 << 8; + private static final int SSA_CALIBRATION_NOT_ALLOWED = 1 << 9; + private static final int SSA_CALIBRATION_RECOMMENDED = 1 << 10; + private static final int SSA_CALIBRATION_REQUIRED = 1 << 11; + private static final int SSA_SENSOR_TEMP_TOO_HIGH = 1 << 12; + private static final int SSA_SENSOR_TEMP_TOO_LOW = 1 << 13; + + private static final int SSA_RESULT_LOWER_THAN_PATIENT_LOW_LEVEL = 1 << 16; + private static final int SSA_RESULT_HIGHER_THAN_PATIENT_HIGH_LEVEL = 1 << 17; + private static final int SSA_RESULT_LOWER_THAN_HYPO_LEVEL = 1 << 18; + private static final int SSA_RESULT_HIGHER_THAN_HYPER_LEVEL = 1 << 19; + private static final int SSA_SENSOR_RATE_OF_DECREASE_EXCEEDED = 1 << 20; + private static final int SSA_SENSOR_RATE_OF_INCREASE_EXCEEDED = 1 << 21; + private static final int SSA_RESULT_LOWER_THAN_DEVICE_CAN_PROCESS = 1 << 22; + private static final int SSA_RESULT_HIGHER_THAN_DEVICE_CAN_PROCESS = 1 << 23; + + public static String parse(final Data data) { + // The CGM Measurement characteristic is a variable length structure containing one or more CGM Measurement records + int totalSize = data.getValue().length; + + final StringBuilder builder = new StringBuilder(); + int offset = 0; + while (offset < totalSize) { + offset += parseRecord(builder, data, offset); + if (offset < totalSize) + builder.append("\n\n"); + } + return builder.toString(); + } + + private static int parseRecord(final StringBuilder builder, final Data data, int offset) { + // Read size and flags bytes + final int size = data.getIntValue(Data.FORMAT_UINT8, offset++); + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + /* + * false CGM Trend Information is not preset + * true CGM Trend Information is preset + */ + final boolean cgmTrendInformationPresent = (flags & FLAGS_CGM_TREND_INFO_PRESENT) > 0; + + /* + * false CGM Quality is not preset + * true CGM Quality is preset + */ + final boolean cgmQualityPresent = (flags & FLAGS_CGM_QUALITY_PRESENT) > 0; + + /* + * false Sensor Status Annunciation - Warning-Octet is not preset + * true Sensor Status Annunciation - Warning-Octet is preset + */ + final boolean ssaWarningOctetPresent = (flags & FLAGS_SENSOR_STATUS_ANNUNCIATION_WARNING_OCTET_PRESENT) > 0; + + /* + * false Sensor Status Annunciation - Calibration/Temp-Octet is not preset + * true Sensor Status Annunciation - Calibration/Temp-Octet is preset + */ + final boolean ssaCalTempOctetPresent = (flags & FLAGS_SENSOR_STATUS_ANNUNCIATION_CAL_TEMP_OCTET_PRESENT) > 0; + + /* + * false Sensor Status Annunciation - Status-Octet is not preset + * true Sensor Status Annunciation - Status-Octet is preset + */ + final boolean ssaStatusOctetPresent = (flags & FLAGS_SENSOR_STATUS_ANNUNCIATION_STATUS_OCTET_PRESENT) > 0; + + // Read CGM Glucose Concentration + final float glucoseConcentration = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + + // Read time offset + final int timeOffset = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + + builder.append("Glucose concentration: ").append(glucoseConcentration).append(" mg/dL\n"); + builder.append("Sequence number: ").append(timeOffset).append(" (Time Offset in min)\n"); + + if (ssaWarningOctetPresent) { + final int ssaWarningOctet = data.getIntValue(Data.FORMAT_UINT8, offset++); + builder.append("Warnings:\n"); + if ((ssaWarningOctet & SSA_SESSION_STOPPED) > 0) + builder.append("- Session Stopped\n"); + if ((ssaWarningOctet & SSA_DEVICE_BATTERY_LOW) > 0) + builder.append("- Device Battery Low\n"); + if ((ssaWarningOctet & SSA_SENSOR_TYPE_INCORRECT) > 0) + builder.append("- Sensor Type Incorrect\n"); + if ((ssaWarningOctet & SSA_SENSOR_MALFUNCTION) > 0) + builder.append("- Sensor Malfunction\n"); + if ((ssaWarningOctet & SSA_DEVICE_SPEC_ALERT) > 0) + builder.append("- Device Specific Alert\n"); + if ((ssaWarningOctet & SSA_GENERAL_DEVICE_FAULT) > 0) + builder.append("- General Device Fault\n"); + } + + if (ssaCalTempOctetPresent) { + final int ssaCalTempOctet = data.getIntValue(Data.FORMAT_UINT8, offset++); + builder.append("Cal/Temp Info:\n"); + if ((ssaCalTempOctet & SSA_TIME_SYNC_REQUIRED) > 0) + builder.append("- Time Synchronization Required\n"); + if ((ssaCalTempOctet & SSA_CALIBRATION_NOT_ALLOWED) > 0) + builder.append("- Calibration Not Allowed\n"); + if ((ssaCalTempOctet & SSA_CALIBRATION_RECOMMENDED) > 0) + builder.append("- Calibration Recommended\n"); + if ((ssaCalTempOctet & SSA_CALIBRATION_REQUIRED) > 0) + builder.append("- Calibration Required\n"); + if ((ssaCalTempOctet & SSA_SENSOR_TEMP_TOO_HIGH) > 0) + builder.append("- Sensor Temp Too High\n"); + if ((ssaCalTempOctet & SSA_SENSOR_TEMP_TOO_LOW) > 0) + builder.append("- Sensor Temp Too Low\n"); + } + + if (ssaStatusOctetPresent) { + final int ssaStatusOctet = data.getIntValue(Data.FORMAT_UINT8, offset++); + builder.append("Status:\n"); + if ((ssaStatusOctet & SSA_RESULT_LOWER_THAN_PATIENT_LOW_LEVEL) > 0) + builder.append("- Result Lower then Patient Low Level\n"); + if ((ssaStatusOctet & SSA_RESULT_HIGHER_THAN_PATIENT_HIGH_LEVEL) > 0) + builder.append("- Result Higher then Patient High Level\n"); + if ((ssaStatusOctet & SSA_RESULT_LOWER_THAN_HYPO_LEVEL) > 0) + builder.append("- Result Lower then Hypo Level\n"); + if ((ssaStatusOctet & SSA_RESULT_HIGHER_THAN_HYPER_LEVEL) > 0) + builder.append("- Result Higher then Hyper Level\n"); + if ((ssaStatusOctet & SSA_SENSOR_RATE_OF_DECREASE_EXCEEDED) > 0) + builder.append("- Sensor Rate of Decrease Exceeded\n"); + if ((ssaStatusOctet & SSA_SENSOR_RATE_OF_INCREASE_EXCEEDED) > 0) + builder.append("- Sensor Rate of Increase Exceeded\n"); + if ((ssaStatusOctet & SSA_RESULT_LOWER_THAN_DEVICE_CAN_PROCESS) > 0) + builder.append("- Result Lower then Device Can Process\n"); + if ((ssaStatusOctet & SSA_RESULT_HIGHER_THAN_DEVICE_CAN_PROCESS) > 0) + builder.append("- Result Higher then Device Can Process\n"); + } + + if (cgmTrendInformationPresent) { + final float trend = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + builder.append("Trend: ").append(trend).append(" mg/dL/min\n"); + } + + if (cgmQualityPresent) { + final float quality = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + builder.append("Quality: ").append(quality).append("%\n"); + } + + if (size > offset + 1) { + final int crc = data.getIntValue(Data.FORMAT_UINT16, offset); + // offset += 2; + builder.append(String.format(Locale.US, "E2E-CRC: 0x%04X\n", crc)); + } + builder.setLength(builder.length() - 1); // Remove last \n + return size; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMSpecificOpsControlPointParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMSpecificOpsControlPointParser.java new file mode 100644 index 0000000..c8afc88 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMSpecificOpsControlPointParser.java @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class CGMSpecificOpsControlPointParser { + private final static int OP_SET_CGM_COMMUNICATION_INTERVAL = 1; + private final static int OP_GET_CGM_COMMUNICATION_INTERVAL = 2; + private final static int OP_CGM_COMMUNICATION_INTERVAL_RESPONSE = 3; + private final static int OP_SET_GLUCOSE_CALIBRATION_VALUE = 4; + private final static int OP_GET_GLUCOSE_CALIBRATION_VALUE = 5; + private final static int OP_GLUCOSE_CALIBRATION_VALUE_RESPONSE = 6; + private final static int OP_SET_PATIENT_HIGH_ALERT_LEVEL = 7; + private final static int OP_GET_PATIENT_HIGH_ALERT_LEVEL = 8; + private final static int OP_PATIENT_HIGH_ALERT_LEVEL_RESPONSE = 9; + private final static int OP_SET_PATIENT_LOW_ALERT_LEVEL = 10; + private final static int OP_GET_PATIENT_LOW_ALERT_LEVEL = 11; + private final static int OP_PATIENT_LOW_ALERT_LEVEL_RESPONSE = 12; + private final static int OP_SET_HYPO_ALERT_LEVEL = 13; + private final static int OP_GET_HYPO_ALERT_LEVEL = 14; + private final static int OP_HYPO_ALERT_LEVEL_RESPONSE = 15; + private final static int OP_SET_HYPER_ALERT_LEVEL = 16; + private final static int OP_GET_HYPER_ALERT_LEVEL = 17; + private final static int OP_HYPER_ALERT_LEVEL_RESPONSE = 18; + private final static int OP_SET_RATE_OF_DECREASE_ALERT_LEVEL = 19; + private final static int OP_GET_RATE_OF_DECREASE_ALERT_LEVEL = 20; + private final static int OP_RATE_OF_DECREASE_ALERT_LEVEL_RESPONSE = 21; + private final static int OP_SET_RATE_OF_INCREASE_ALERT_LEVEL = 22; + private final static int OP_GET_RATE_OF_INCREASE_ALERT_LEVEL = 23; + private final static int OP_RATE_OF_INCREASE_ALERT_LEVEL_RESPONSE = 24; + private final static int OP_RESET_DEVICE_SPECIFIC_ALERT = 25; + private final static int OP_CODE_START_SESSION = 26; + private final static int OP_CODE_STOP_SESSION = 27; + private final static int OP_CODE_RESPONSE_CODE = 28; + + // TODO this parser does not support E2E-CRC! + + public static String parse(final Data data) { + int offset = 0; + final int opCode = data.getIntValue(Data.FORMAT_UINT8, offset++); + + final StringBuilder builder = new StringBuilder(); + builder.append(parseOpCode(opCode)); + switch (opCode) { + case OP_SET_CGM_COMMUNICATION_INTERVAL: + case OP_CGM_COMMUNICATION_INTERVAL_RESPONSE: { + final int interval = data.getIntValue(Data.FORMAT_UINT8, offset); + builder.append(" to ").append(interval).append(" min"); + break; + } + case OP_SET_GLUCOSE_CALIBRATION_VALUE: { + final float calConcentration = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + final int calTime = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + final int calTypeSampleLocation = data.getIntValue(Data.FORMAT_UINT8, offset++); + final int calType = calTypeSampleLocation & 0x0F; + final int calSampleLocation = (calTypeSampleLocation & 0xF0) >> 4; + final int calNextCalibrationTime = data.getIntValue(Data.FORMAT_UINT16, offset); + // offset += 2; + // final int calCalibrationDataRecordNumber = data.getIntValue(Data.FORMAT_UINT16, offset); + // offset += 2; + // final int calStatus = data.getIntValue(Data.FORMAT_UINT8, offset++); + + builder.append(" to:\n"); + builder.append("Glucose Concentration of Calibration: ").append(calConcentration).append(" mg/dL\n"); + builder.append("Time: ").append(calTime).append(" min\n"); + builder.append("Type: ").append(parseType(calType)).append("\n"); + builder.append("Sample Location: ").append(parseSampleLocation(calSampleLocation)).append("\n"); + builder.append("Next Calibration Time: ").append(parseNextCalibrationTime(calNextCalibrationTime)).append(" min\n"); // field ignored on Set + // builder.append("Data Record Number: ").append(calCalibrationDataRecordNumber).append("\n"); // field ignored on Set + // parseStatus(builder, calStatus); // field ignored on Set + break; + } + case OP_GET_GLUCOSE_CALIBRATION_VALUE: { + final int calibrationRecordNumber = data.getIntValue(Data.FORMAT_UINT16, offset); + builder.append(": ").append(parseRecordNumber(calibrationRecordNumber)); + break; + } + case OP_GLUCOSE_CALIBRATION_VALUE_RESPONSE: { + final float calConcentration = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + final int calTime = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + final int calTypeSampleLocation = data.getIntValue(Data.FORMAT_UINT8, offset++); + final int calType = calTypeSampleLocation & 0x0F; + final int calSampleLocation = (calTypeSampleLocation & 0xF0) >> 4; + final int calNextCalibrationTime = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + final int calCalibrationDataRecordNumber = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + final int calStatus = data.getIntValue(Data.FORMAT_UINT8, offset); + + builder.append(":\n"); + if (calCalibrationDataRecordNumber > 0) { + builder.append("Glucose Concentration of Calibration: ").append(calConcentration).append(" mg/dL\n"); + builder.append("Time: ").append(calTime).append(" min\n"); + builder.append("Type: ").append(parseType(calType)).append("\n"); + builder.append("Sample Location: ").append(parseSampleLocation(calSampleLocation)).append("\n"); + builder.append("Next Calibration Time: ").append(parseNextCalibrationTime(calNextCalibrationTime)).append("\n"); + builder.append("Data Record Number: ").append(calCalibrationDataRecordNumber); + parseStatus(builder, calStatus); + } else { + builder.append("No Calibration Data Stored"); + } + break; + } + case OP_SET_PATIENT_HIGH_ALERT_LEVEL: + case OP_SET_PATIENT_LOW_ALERT_LEVEL: + case OP_SET_HYPO_ALERT_LEVEL: + case OP_SET_HYPER_ALERT_LEVEL: { + final float level = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + builder.append(" to: ").append(level).append(" mg/dL"); + break; + } + case OP_PATIENT_HIGH_ALERT_LEVEL_RESPONSE: + case OP_PATIENT_LOW_ALERT_LEVEL_RESPONSE: + case OP_HYPO_ALERT_LEVEL_RESPONSE: + case OP_HYPER_ALERT_LEVEL_RESPONSE: { + final float level = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + builder.append(": ").append(level).append(" mg/dL"); + break; + } + case OP_SET_RATE_OF_DECREASE_ALERT_LEVEL: + case OP_SET_RATE_OF_INCREASE_ALERT_LEVEL: { + final float level = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + builder.append(" to: ").append(level).append(" mg/dL/min"); + break; + } + case OP_RATE_OF_DECREASE_ALERT_LEVEL_RESPONSE: + case OP_RATE_OF_INCREASE_ALERT_LEVEL_RESPONSE: { + final float level = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + builder.append(": ").append(level).append(" mg/dL/min"); + break; + } + case OP_CODE_RESPONSE_CODE: + final int requestOpCode = data.getIntValue(Data.FORMAT_UINT8, offset++); + final int responseCode = data.getIntValue(Data.FORMAT_UINT8, offset++); + builder.append(" to ").append(parseOpCode(requestOpCode)).append(": ").append(parseResponseCode(responseCode)); + break; + } + + return builder.toString(); + } + + private static String parseOpCode(final int code) { + switch (code) { + case OP_SET_CGM_COMMUNICATION_INTERVAL: + return "Set CGM Communication Interval"; + case OP_GET_CGM_COMMUNICATION_INTERVAL: + return "Get CGM Communication Interval"; + case OP_CGM_COMMUNICATION_INTERVAL_RESPONSE: + return "CGM Communication Interval"; + case OP_SET_GLUCOSE_CALIBRATION_VALUE: + return "Set CGM Calibration Value"; + case OP_GET_GLUCOSE_CALIBRATION_VALUE: + return "Get CGM Calibration Value"; + case OP_GLUCOSE_CALIBRATION_VALUE_RESPONSE: + return "CGM Calibration Value"; + case OP_SET_PATIENT_HIGH_ALERT_LEVEL: + return "Set Patient High Alert Level"; + case OP_GET_PATIENT_HIGH_ALERT_LEVEL: + return "Get Patient High Alert Level"; + case OP_PATIENT_HIGH_ALERT_LEVEL_RESPONSE: + return "Patient High Alert Level"; + case OP_SET_PATIENT_LOW_ALERT_LEVEL: + return "Set Patient Low Alert Level"; + case OP_GET_PATIENT_LOW_ALERT_LEVEL: + return "Get Patient Low Alert Level"; + case OP_PATIENT_LOW_ALERT_LEVEL_RESPONSE: + return "Patient Low Alert Level"; + case OP_SET_HYPO_ALERT_LEVEL: + return "Set Hypo Alert Level"; + case OP_GET_HYPO_ALERT_LEVEL: + return "Get Hypo Alert Level"; + case OP_HYPO_ALERT_LEVEL_RESPONSE: + return "Hypo Alert Level"; + case OP_SET_HYPER_ALERT_LEVEL: + return "Set Hyper Alert Level"; + case OP_GET_HYPER_ALERT_LEVEL: + return "Get Hyper Alert Level"; + case OP_HYPER_ALERT_LEVEL_RESPONSE: + return "Hyper Alert Level"; + case OP_SET_RATE_OF_DECREASE_ALERT_LEVEL: + return "Set Rate of Decrease Alert Level"; + case OP_GET_RATE_OF_DECREASE_ALERT_LEVEL: + return "Get Rate of Decrease Alert Level"; + case OP_RATE_OF_DECREASE_ALERT_LEVEL_RESPONSE: + return "Rate of Decrease Alert Level"; + case OP_SET_RATE_OF_INCREASE_ALERT_LEVEL: + return "Set Rate of Increase Alert Level"; + case OP_GET_RATE_OF_INCREASE_ALERT_LEVEL: + return "Get Rate of Increase Alert Level"; + case OP_RATE_OF_INCREASE_ALERT_LEVEL_RESPONSE: + return "Rate of Increase Alert Level"; + case OP_RESET_DEVICE_SPECIFIC_ALERT: + return "Reset Device Specific Alert"; + case OP_CODE_START_SESSION: + return "Start Session"; + case OP_CODE_STOP_SESSION: + return "Stop Session"; + case OP_CODE_RESPONSE_CODE: + return "Response"; + default: + return "Reserved for future use (" + code + ")"; + } + } + + private static String parseResponseCode(final int code) { + switch (code) { + case 1: return "Success"; + case 2: return "Op Code not supported"; + case 3: return "Invalid Operand"; + case 4: return "Procedure not completed"; + case 5: return "Parameter out of range"; + default: + return "Reserved for future use (" + code + ")"; + } + } + + private static String parseType(final int type) { + switch (type) { + case 1: return "Capillary Whole blood"; + case 2: return "Capillary Plasma"; + case 3: return "Capillary Whole blood"; + case 4: return "Venous Plasma"; + case 5: return "Arterial Whole blood"; + case 6: return "Arterial Plasma"; + case 7: return "Undetermined Whole blood"; + case 8: return "Undetermined Plasma"; + case 9: return "Interstitial Fluid (ISF)"; + case 10: return "Control Solution"; + default: return "Reserved for future use (" + type + ")"; + } + } + + private static String parseSampleLocation(final int location) { + switch (location) { + case 1: return "Finger"; + case 2: return "Alternate Site Test (AST)"; + case 3: return "Earlobe"; + case 4: return "Control solution"; + case 5: return "Subcutaneous tissue"; + case 15: return "Sample Location value not available"; + default: return "Reserved for future use (" + location + ")"; + } + } + + private static String parseNextCalibrationTime(final int time) { + if (time == 0) + return "Calibration Required Instantly"; + return time + " min"; + } + + private static String parseRecordNumber(final int time) { + if (time == 0xFFFF) + return "Last Calibration Data"; + return String.valueOf(time); + } + + private static void parseStatus(final StringBuilder builder, final int status) { + if (status == 0) + return; + builder.append("\nStatus:\n"); + if ((status & 1) > 0) + builder.append("- Calibration Data rejected"); + if ((status & 2) > 0) + builder.append("- Calibration Data out of range"); + if ((status & 4) > 0) + builder.append("- Calibration Process pending"); + if ((status & 0xF8) > 0) + builder.append("- Reserved for future use (").append(status).append(")"); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CSCMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CSCMeasurementParser.java new file mode 100644 index 0000000..a5a28cc --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CSCMeasurementParser.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class CSCMeasurementParser { + private static final byte WHEEL_REV_DATA_PRESENT = 0x01; // 1 bit + private static final byte CRANK_REV_DATA_PRESENT = 0x02; // 1 bit + + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getByte(offset); // 1 byte + offset += 1; + + final boolean wheelRevPresent = (flags & WHEEL_REV_DATA_PRESENT) > 0; + final boolean crankRevPreset = (flags & CRANK_REV_DATA_PRESENT) > 0; + + int wheelRevolutions = 0; + int lastWheelEventTime = 0; + if (wheelRevPresent) { + wheelRevolutions = data.getIntValue(Data.FORMAT_UINT32, offset); + offset += 4; + + lastWheelEventTime = data.getIntValue(Data.FORMAT_UINT16, offset); // 1/1024 s + offset += 2; + } + + int crankRevolutions = 0; + int lastCrankEventTime = 0; + if (crankRevPreset) { + crankRevolutions = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + + lastCrankEventTime = data.getIntValue(Data.FORMAT_UINT16, offset); + //offset += 2; + } + + final StringBuilder builder = new StringBuilder(); + if (wheelRevPresent) { + builder.append("Wheel rev: ").append(wheelRevolutions).append(",\n"); + builder.append("Last wheel event time: ").append(lastWheelEventTime).append(",\n"); + } + if (crankRevPreset) { + builder.append("Crank rev: ").append(crankRevolutions).append(",\n"); + builder.append("Last crank event time: ").append(lastCrankEventTime).append(",\n"); + } + if (!wheelRevPresent && !crankRevPreset) { + builder.append("No wheel or crank data"); + } + builder.setLength(builder.length() - 2); + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/DateTimeParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/DateTimeParser.java new file mode 100644 index 0000000..5e3e79b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/DateTimeParser.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import java.util.Calendar; +import java.util.Locale; + +import no.nordicsemi.android.ble.common.callback.DateTimeDataCallback; +import no.nordicsemi.android.ble.data.Data; + +public class DateTimeParser { + /** + * Parses the date and time info. + * + * @param data + * @return time in human readable format + */ + public static String parse(final Data data) { + return parse(data, 0); + } + + /** + * Parses the date and time info. This data has 7 bytes + * + * @param data + * @param offset + * offset to start reading the time + * @return time in human readable format + */ + /* package */static String parse(final Data data, final int offset) { + final Calendar calendar = DateTimeDataCallback.readDateTime(data, offset); + return String.format(Locale.US, "%1$te %1$tb %1$tY, %1$tH:%1$tM:%1$tS", calendar); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementContextParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementContextParser.java new file mode 100644 index 0000000..8a81440 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementContextParser.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class GlucoseMeasurementContextParser { + private static final int UNIT_kg = 0; + private static final int UNIT_l = 1; + + public static String parse(final Data data) { + final StringBuilder builder = new StringBuilder(); + + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset); + offset += 1; + + final boolean carbohydratePresent = (flags & 0x01) > 0; + final boolean mealPresent = (flags & 0x02) > 0; + final boolean testerHealthPresent = (flags & 0x04) > 0; + final boolean exercisePresent = (flags & 0x08) > 0; + final boolean medicationPresent = (flags & 0x10) > 0; + final int medicationUnit = (flags & 0x20) > 0 ? UNIT_l : UNIT_kg; + final boolean hbA1cPresent = (flags & 0x40) > 0; + final boolean moreFlagsPresent = (flags & 0x80) > 0; + + final int sequenceNumber = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + + if (moreFlagsPresent) // not supported yet + offset += 1; + + builder.append("Sequence number: ").append(sequenceNumber); + + if (carbohydratePresent) { + final int carbohydrateId = data.getIntValue(Data.FORMAT_UINT8, offset); + final float carbohydrateUnits = data.getFloatValue(Data.FORMAT_SFLOAT, offset + 1); + builder.append("\nCarbohydrate: ").append(getCarbohydrate(carbohydrateId)).append(" (").append(carbohydrateUnits).append(carbohydrateUnits == UNIT_kg ? "kg" : "l").append(")"); + offset += 3; + } + + if (mealPresent) { + final int meal = data.getIntValue(Data.FORMAT_UINT8, offset); + builder.append("\nMeal: ").append(getMeal(meal)); + offset += 1; + } + + if (testerHealthPresent) { + final int testerHealth = data.getIntValue(Data.FORMAT_UINT8, offset); + final int tester = (testerHealth & 0xF0) >> 4; + final int health = (testerHealth & 0x0F); + builder.append("\nTester: ").append(getTester(tester)); + builder.append("\nHealth: ").append(getHealth(health)); + offset += 1; + } + + if (exercisePresent) { + final int exerciseDuration = data.getIntValue(Data.FORMAT_UINT16, offset); + final int exerciseIntensity = data.getIntValue(Data.FORMAT_UINT8, offset + 2); + builder.append("\nExercise duration: ").append(exerciseDuration).append("s (intensity ").append(exerciseIntensity).append("%)"); + offset += 3; + } + + if (medicationPresent) { + final int medicationId = data.getIntValue(Data.FORMAT_UINT8, offset); + final float medicationQuantity = data.getFloatValue(Data.FORMAT_SFLOAT, offset + 1); + builder.append("\nMedication: ").append(getMedicationId(medicationId)).append(" (").append(medicationQuantity).append(medicationUnit == UNIT_kg ? "kg" : "l"); + offset += 3; + } + + if (hbA1cPresent) { + final float HbA1c = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + builder.append("\nHbA1c: ").append(HbA1c).append("%"); + } + return builder.toString(); + } + + private static String getCarbohydrate(final int id) { + switch (id) { + case 1: + return "Breakfast"; + case 2: + return "Lunch"; + case 3: + return "Dinner"; + case 4: + return "Snack"; + case 5: + return "Drink"; + case 6: + return "Supper"; + case 7: + return "Brunch"; + default: + return "Reserved for future use (" + id + ")"; + } + } + + private static String getMeal(final int id) { + switch (id) { + case 1: + return "Preprandial (before meal)"; + case 2: + return "Postprandial (after meal)"; + case 3: + return "Fasting"; + case 4: + return "Casual (snacks, drinks, etc.)"; + case 5: + return "Bedtime"; + default: + return "Reserved for future use (" + id + ")"; + } + } + + private static String getTester(final int id) { + switch (id) { + case 1: + return "Self"; + case 2: + return "Health Care Professional"; + case 3: + return "Lab test"; + case 4: + return "Casual (snacks, drinks, etc.)"; + case 15: + return "Tester value not available"; + default: + return "Reserved for future use (" + id + ")"; + } + } + + private static String getHealth(final int id) { + switch (id) { + case 1: + return "Minor health issues"; + case 2: + return "Major health issues"; + case 3: + return "During menses"; + case 4: + return "Under stress"; + case 5: + return "No health issues"; + case 15: + return "Health value not available"; + default: + return "Reserved for future use (" + id + ")"; + } + } + + private static String getMedicationId(final int id) { + switch (id) { + case 1: + return "Rapid acting insulin"; + case 2: + return "Short acting insulin"; + case 3: + return "Intermediate acting insulin"; + case 4: + return "Long acting insulin"; + case 5: + return "Pre-mixed insulin"; + default: + return "Reserved for future use (" + id + ")"; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementParser.java new file mode 100644 index 0000000..18d59b4 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementParser.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class GlucoseMeasurementParser { + private static final int UNIT_kgpl = 0; + private static final int UNIT_molpl = 1; + + private static final int STATUS_DEVICE_BATTERY_LOW = 0x0001; + private static final int STATUS_SENSOR_MALFUNCTION = 0x0002; + private static final int STATUS_SAMPLE_SIZE_FOR_BLOOD_OR_CONTROL_SOLUTION_INSUFFICIENT = 0x0004; + private static final int STATUS_STRIP_INSERTION_ERROR = 0x0008; + private static final int STATUS_STRIP_TYPE_INCORRECT_FOR_DEVICE = 0x0010; + private static final int STATUS_SENSOR_RESULT_TOO_HIGH = 0x0020; + private static final int STATUS_SENSOR_RESULT_TOO_LOW = 0x0040; + private static final int STATUS_SENSOR_TEMPERATURE_TOO_HIGH = 0x0080; + private static final int STATUS_SENSOR_TEMPERATURE_TOO_LOW = 0x0100; + private static final int STATUS_SENSOR_READ_INTERRUPTED = 0x0200; + private static final int STATUS_GENERAL_DEVICE_FAULT = 0x0400; + private static final int STATUS_TIME_FAULT = 0x0800; + + public static String parse(final Data data) { + final StringBuilder builder = new StringBuilder(); + + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset); + offset += 1; + + final boolean timeOffsetPresent = (flags & 0x01) > 0; + final boolean typeAndLocationPresent = (flags & 0x02) > 0; + final int concentrationUnit = (flags & 0x04) > 0 ? UNIT_molpl : UNIT_kgpl; + final boolean sensorStatusAnnunciationPresent = (flags & 0x08) > 0; + final boolean contextInfoFollows = (flags & 0x10) > 0; + + // create and fill the new record + final int sequenceNumber = data.getIntValue(Data.FORMAT_UINT16, offset); + builder.append("Sequence Number: ").append(sequenceNumber); + offset += 2; + + builder.append("\nBase Time: ").append(DateTimeParser.parse(data, offset)); + offset += 7; + + if (timeOffsetPresent) { + // time offset is ignored in the current release + final int timeOffset = data.getIntValue(Data.FORMAT_SINT16, offset); + builder.append("\nTime Offset: ").append(timeOffset).append(" min"); + offset += 2; + } + + if (typeAndLocationPresent) { + final float glucoseConcentration = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + final int typeAndLocation = data.getIntValue(Data.FORMAT_UINT8, offset + 2); + final int type = (typeAndLocation & 0xF0) >> 4; // TODO this way or around? + final int sampleLocation = (typeAndLocation & 0x0F); + builder.append("\nGlucose Concentration: ").append(glucoseConcentration).append(concentrationUnit == UNIT_kgpl ? " kg/l" : " mol/l"); + builder.append("\nSample Type: ").append(getType(type)); + builder.append("\nSample Location: ").append(getLocation(sampleLocation)); + offset += 3; + } + + if (sensorStatusAnnunciationPresent) { + final int status = data.getIntValue(Data.FORMAT_UINT16, offset); + builder.append("Status:\n").append(getStatusAnnunciation(status)); + } + + builder.append("\nContext information follows: ").append(contextInfoFollows); + return builder.toString(); + } + + private static String getType(final int type) { + switch (type) { + case 1: + return "Capillary Whole blood"; + case 2: + return "Capillary Plasma"; + case 3: + return "Venous Whole blood"; + case 4: + return "Venous Plasma"; + case 5: + return "Arterial Whole blood"; + case 6: + return "Arterial Plasma"; + case 7: + return "Undetermined Whole blood"; + case 8: + return "Undetermined Plasma"; + case 9: + return "Interstitial Fluid (ISF)"; + case 10: + return "Control Solution"; + default: + return "Reserved for future use (" + type + ")"; + } + } + + private static String getLocation(final int location) { + switch (location) { + case 1: + return "Finger"; + case 2: + return "Alternate Site Test (AST)"; + case 3: + return "Earlobe"; + case 4: + return "Control solution"; + case 15: + return "Value not available"; + default: + return "Reserved for future use (" + location + ")"; + } + } + + private static String getStatusAnnunciation(final int status) { + final StringBuilder builder = new StringBuilder(); + if ((status & STATUS_DEVICE_BATTERY_LOW) > 0) + builder.append("\nDevice battery low at time of measurement"); + if ((status & STATUS_SENSOR_MALFUNCTION) > 0) + builder.append("\nSensor malfunction or faulting at time of measurement"); + if ((status & STATUS_SAMPLE_SIZE_FOR_BLOOD_OR_CONTROL_SOLUTION_INSUFFICIENT) > 0) + builder.append("\nSample size for blood or control solution insufficient at time of measurement"); + if ((status & STATUS_STRIP_INSERTION_ERROR) > 0) + builder.append("\nStrip insertion error"); + if ((status & STATUS_STRIP_TYPE_INCORRECT_FOR_DEVICE) > 0) + builder.append("\nStrip type incorrect for device"); + if ((status & STATUS_SENSOR_RESULT_TOO_HIGH) > 0) + builder.append("\nSensor result higher than the device can process"); + if ((status & STATUS_SENSOR_RESULT_TOO_LOW) > 0) + builder.append("\nSensor result lower than the device can process"); + if ((status & STATUS_SENSOR_TEMPERATURE_TOO_HIGH) > 0) + builder.append("\nSensor temperature too high for valid test/result at time of measurement"); + if ((status & STATUS_SENSOR_TEMPERATURE_TOO_LOW) > 0) + builder.append("\nSensor temperature too low for valid test/result at time of measurement"); + if ((status & STATUS_SENSOR_READ_INTERRUPTED) > 0) + builder.append("\nSensor read interrupted because strip was pulled too soon at time of measurement"); + if ((status & STATUS_GENERAL_DEVICE_FAULT) > 0) + builder.append("\nGeneral device fault has occurred in the sensor"); + if ((status & STATUS_TIME_FAULT) > 0) + builder.append("\nTime fault has occurred in the sensor and time may be inaccurate"); + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/HeartRateMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/HeartRateMeasurementParser.java new file mode 100644 index 0000000..9622072 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/HeartRateMeasurementParser.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class HeartRateMeasurementParser { + private static final byte HEART_RATE_VALUE_FORMAT = 0x01; // 1 bit + private static final byte SENSOR_CONTACT_STATUS = 0x06; // 2 bits + private static final byte ENERGY_EXPANDED_STATUS = 0x08; // 1 bit + private static final byte RR_INTERVAL = 0x10; // 1 bit + + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + /* + * false Heart Rate Value Format is set to UINT8. Units: beats per minute (bpm) + * true Heart Rate Value Format is set to UINT16. Units: beats per minute (bpm) + */ + final boolean value16bit = (flags & HEART_RATE_VALUE_FORMAT) > 0; + + /* + * 0 Sensor Contact feature is not supported in the current connection + * 1 Sensor Contact feature is not supported in the current connection + * 2 Sensor Contact feature is supported, but contact is not detected + * 3 Sensor Contact feature is supported and contact is detected + */ + final int sensorContactStatus = (flags & SENSOR_CONTACT_STATUS) >> 1; + + /* + * false Energy Expended field is not present + * true Energy Expended field is present. Units: kilo Joules + */ + final boolean energyExpandedStatus = (flags & ENERGY_EXPANDED_STATUS) > 0; + + /* + * false RR-Interval values are not present. + * true One or more RR-Interval values are present. Units: 1/1024 seconds + */ + final boolean rrIntervalStatus = (flags & RR_INTERVAL) > 0; + + // heart rate value is 8 or 16 bit long + int heartRateValue = data.getIntValue(value16bit ? Data.FORMAT_UINT16 : Data.FORMAT_UINT8, offset++); // bits per minute + if (value16bit) + offset++; + + // energy expanded value is present if a flag was set + int energyExpanded = -1; + if (energyExpandedStatus) + energyExpanded = data.getIntValue(Data.FORMAT_UINT16, offset); + offset += 2; + + // RR-interval is set when a flag is set + final List rrIntervals = new ArrayList<>(); + if (rrIntervalStatus) { + for (int o = offset; o < data.getValue().length; o += 2) { + final int units = data.getIntValue(Data.FORMAT_UINT16, o); + rrIntervals.add(units * 1000.0f / 1024.0f); // RR interval is in [1/1024s] + } + } + + final StringBuilder builder = new StringBuilder(); + builder.append("Heart Rate Measurement: ").append(heartRateValue).append(" bpm"); + switch (sensorContactStatus) { + case 0: + case 1: + builder.append(",\nSensor Contact Not Supported"); + break; + case 2: + builder.append(",\nContact is NOT Detected"); + break; + case 3: + builder.append(",\nContact is Detected"); + break; + } + if (energyExpandedStatus) + builder.append(",\nEnergy Expanded: ").append(energyExpanded).append(" kJ"); + if (rrIntervalStatus) { + builder.append(",\nRR Interval: "); + for (final Float interval : rrIntervals) + builder.append(String.format(Locale.US, "%.02f ms, ", interval)); + builder.setLength(builder.length() - 2); // remove the ", " at the end + } + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/IntermediateCuffPressureParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/IntermediateCuffPressureParser.java new file mode 100644 index 0000000..632dc5e --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/IntermediateCuffPressureParser.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class IntermediateCuffPressureParser { + public static String parse(final Data data) { + final StringBuilder builder = new StringBuilder(); + + // first byte - flags + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + final int unitType = flags & 0x01; + final boolean timestampPresent = (flags & 0x02) > 0; + final boolean pulseRatePresent = (flags & 0x04) > 0; + final boolean userIdPresent = (flags & 0x08) > 0; + final boolean statusPresent = (flags & 0x10) > 0; + + // following bytes - pressure + final float pressure = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + final String unit = unitType == 0 ? " mmHg" : " kPa"; + offset += 6; + builder.append("Cuff pressure: ").append(pressure).append(unit); + + // parse timestamp if present + if (timestampPresent) { + builder.append("Timestamp: ").append(DateTimeParser.parse(data, offset)); + offset += 7; + } + + // parse pulse rate if present + if (pulseRatePresent) { + final float pulseRate = data.getFloatValue(Data.FORMAT_SFLOAT, offset); + offset += 2; + builder.append("\nPulse: ").append(pulseRate).append(" bpm"); + } + + if (userIdPresent) { + final int userId = data.getIntValue(Data.FORMAT_UINT8, offset); + offset += 1; + builder.append("\nUser ID: ").append(userId); + } + + if (statusPresent) { + final int status = data.getIntValue(Data.FORMAT_UINT16, offset); + // offset += 2; + if ((status & 0x0001) > 0) + builder.append("\nBody movement detected"); + if ((status & 0x0002) > 0) + builder.append("\nCuff too lose"); + if ((status & 0x0004) > 0) + builder.append("\nIrregular pulse detected"); + if ((status & 0x0018) == 0x0008) + builder.append("\nPulse rate exceeds upper limit"); + if ((status & 0x0018) == 0x0010) + builder.append("\nPulse rate is less than lower limit"); + if ((status & 0x0018) == 0x0018) + builder.append("\nPulse rate range: Reserved for future use "); + if ((status & 0x0020) > 0) + builder.append("\nImproper measurement position"); + } + + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RSCMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RSCMeasurementParser.java new file mode 100644 index 0000000..6d19622 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RSCMeasurementParser.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import java.util.Locale; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class RSCMeasurementParser { + private static final byte INSTANTANEOUS_STRIDE_LENGTH_PRESENT = 0x01; // 1 bit + private static final byte TOTAL_DISTANCE_PRESENT = 0x02; // 1 bit + private static final byte WALKING_OR_RUNNING_STATUS_BITS = 0x04; // 1 bit + + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getValue()[offset]; // 1 byte + offset += 1; + + final boolean islmPresent = (flags & INSTANTANEOUS_STRIDE_LENGTH_PRESENT) > 0; + final boolean tdPreset = (flags & TOTAL_DISTANCE_PRESENT) > 0; + final boolean running = (flags & WALKING_OR_RUNNING_STATUS_BITS) > 0; + final boolean walking = !running; + + final float instantaneousSpeed = (float) data.getIntValue(Data.FORMAT_UINT16, offset) / 256.0f; // 1/256 m/s + offset += 2; + + final int instantaneousCadence = data.getIntValue(Data.FORMAT_UINT8, offset); + offset += 1; + + float instantaneousStrideLength = 0; + if (islmPresent) { + instantaneousStrideLength = (float) data.getIntValue(Data.FORMAT_UINT16, offset) / 100.0f; // 1/100 m + offset += 2; + } + + float totalDistance = 0; + if (tdPreset) { + totalDistance = (float) data.getIntValue(Data.FORMAT_UINT32, offset) / 10.0f; + // offset += 4; + } + + final StringBuilder builder = new StringBuilder(); + builder.append(String.format(Locale.US, "Speed: %.2f m/s, Cadence: %d RPM,\n", instantaneousSpeed, instantaneousCadence)); + if (islmPresent) + builder.append(String.format(Locale.US, "Instantaneous Stride Length: %.2f m,\n", instantaneousStrideLength)); + if (tdPreset) + builder.append(String.format(Locale.US, "Total Distance: %.1f m,\n", totalDistance)); + if (walking) + builder.append("Status: WALKING"); + else + builder.append("Status: RUNNING"); + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RecordAccessControlPointParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RecordAccessControlPointParser.java new file mode 100644 index 0000000..0ef5954 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RecordAccessControlPointParser.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class RecordAccessControlPointParser { + private final static int OP_CODE_REPORT_STORED_RECORDS = 1; + private final static int OP_CODE_DELETE_STORED_RECORDS = 2; + private final static int OP_CODE_ABORT_OPERATION = 3; + private final static int OP_CODE_REPORT_NUMBER_OF_RECORDS = 4; + private final static int OP_CODE_NUMBER_OF_STORED_RECORDS_RESPONSE = 5; + private final static int OP_CODE_RESPONSE_CODE = 6; + + private final static int OPERATOR_NULL = 0; + private final static int OPERATOR_ALL_RECORDS = 1; + private final static int OPERATOR_LESS_THEN_OR_EQUAL = 2; + private final static int OPERATOR_GREATER_THEN_OR_EQUAL = 3; + private final static int OPERATOR_WITHING_RANGE = 4; + private final static int OPERATOR_FIRST_RECORD = 5; + private final static int OPERATOR_LAST_RECORD = 6; + + private final static int RESPONSE_SUCCESS = 1; + private final static int RESPONSE_OP_CODE_NOT_SUPPORTED = 2; + private final static int RESPONSE_INVALID_OPERATOR = 3; + private final static int RESPONSE_OPERATOR_NOT_SUPPORTED = 4; + private final static int RESPONSE_INVALID_OPERAND = 5; + private final static int RESPONSE_NO_RECORDS_FOUND = 6; + private final static int RESPONSE_ABORT_UNSUCCESSFUL = 7; + private final static int RESPONSE_PROCEDURE_NOT_COMPLETED = 8; + private final static int RESPONSE_OPERAND_NOT_SUPPORTED = 9; + + public static String parse(final Data data) { + final StringBuilder builder = new StringBuilder(); + final int opCode = data.getIntValue(Data.FORMAT_UINT8, 0); + final int operator = data.getIntValue(Data.FORMAT_UINT8, 1); + + switch (opCode) { + case OP_CODE_REPORT_STORED_RECORDS: + case OP_CODE_DELETE_STORED_RECORDS: + case OP_CODE_ABORT_OPERATION: + case OP_CODE_REPORT_NUMBER_OF_RECORDS: + builder.append(getOpCode(opCode)).append("\n"); + break; + case OP_CODE_NUMBER_OF_STORED_RECORDS_RESPONSE: { + builder.append(getOpCode(opCode)).append(": "); + final int value = data.getIntValue(Data.FORMAT_UINT16, 2); + builder.append(value).append("\n"); + break; + } + case OP_CODE_RESPONSE_CODE: { + builder.append(getOpCode(opCode)).append(" for "); + final int targetOpCode = data.getIntValue(Data.FORMAT_UINT8, 2); + builder.append(getOpCode(targetOpCode)).append(": "); + final int status = data.getIntValue(Data.FORMAT_UINT8, 3); + builder.append(getStatus(status)).append("\n"); + break; + } + } + + switch (operator) { + case OPERATOR_ALL_RECORDS: + case OPERATOR_FIRST_RECORD: + case OPERATOR_LAST_RECORD: + builder.append("Operator: ").append(getOperator(operator)).append("\n"); + break; + case OPERATOR_GREATER_THEN_OR_EQUAL: + case OPERATOR_LESS_THEN_OR_EQUAL: { + final int filter = data.getIntValue(Data.FORMAT_UINT8, 2); + final int value = data.getIntValue(Data.FORMAT_UINT16, 3); + builder.append("Operator: ").append(getOperator(operator)).append(" ").append(value).append(" (filter: ").append(filter).append(")\n"); + break; + } + case OPERATOR_WITHING_RANGE: { + final int filter = data.getIntValue(Data.FORMAT_UINT8, 2); + final int value1 = data.getIntValue(Data.FORMAT_UINT16, 3); + final int value2 = data.getIntValue(Data.FORMAT_UINT16, 5); + builder.append("Operator: ").append(getOperator(operator)).append(" ").append(value1).append("-").append(value2).append(" (filter: ").append(filter).append(")\n"); + break; + } + } + if (builder.length() > 0) + builder.setLength(builder.length() - 1); + + return builder.toString(); + } + + private static String getOpCode(final int opCode) { + switch (opCode) { + case OP_CODE_REPORT_STORED_RECORDS: + return "Report stored records"; + case OP_CODE_DELETE_STORED_RECORDS: + return "Delete stored records"; + case OP_CODE_ABORT_OPERATION: + return "Abort operation"; + case OP_CODE_REPORT_NUMBER_OF_RECORDS: + return "Report number of stored records"; + case OP_CODE_NUMBER_OF_STORED_RECORDS_RESPONSE: + return "Number of stored records response"; + case OP_CODE_RESPONSE_CODE: + return "Response Code"; + default: + return "Reserved for future use"; + } + } + + private static String getOperator(final int operator) { + switch (operator) { + case OPERATOR_NULL: + return "Null"; + case OPERATOR_ALL_RECORDS: + return "All records"; + case OPERATOR_LESS_THEN_OR_EQUAL: + return "Less than or equal to"; + case OPERATOR_GREATER_THEN_OR_EQUAL: + return "Greater than or equal to"; + case OPERATOR_WITHING_RANGE: + return "Within range of"; + case OPERATOR_FIRST_RECORD: + return "First record(i.e. oldest record)"; + case OPERATOR_LAST_RECORD: + return "Last record (i.e. most recent record)"; + default: + return "Reserved for future use"; + } + } + + private static String getStatus(final int status) { + switch (status) { + case RESPONSE_SUCCESS: + return "Success"; + case RESPONSE_OP_CODE_NOT_SUPPORTED: + return "Operation not supported"; + case RESPONSE_INVALID_OPERATOR: + return "Invalid operator"; + case RESPONSE_OPERATOR_NOT_SUPPORTED: + return "Operator not supported"; + case RESPONSE_INVALID_OPERAND: + return "Invalid operand"; + case RESPONSE_NO_RECORDS_FOUND: + return "No records found"; + case RESPONSE_ABORT_UNSUCCESSFUL: + return "Abort unsuccessful"; + case RESPONSE_PROCEDURE_NOT_COMPLETED: + return "Procedure not completed"; + case RESPONSE_OPERAND_NOT_SUPPORTED: + return "Operand not supported"; + default: + return "Reserved for future use"; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureMeasurementParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureMeasurementParser.java new file mode 100644 index 0000000..cdefad7 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureMeasurementParser.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import java.util.Locale; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class TemperatureMeasurementParser { + private static final byte TEMPERATURE_UNIT_FLAG = 0x01; // 1 bit + private static final byte TIMESTAMP_FLAG = 0x02; // 1 bits + private static final byte TEMPERATURE_TYPE_FLAG = 0x04; // 1 bit + + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + /* + * false Temperature is in Celsius degrees + * true Temperature is in Fahrenheit degrees + */ + final boolean fahrenheit = (flags & TEMPERATURE_UNIT_FLAG) > 0; + + /* + * false No Timestamp in the packet + * true There is a timestamp information + */ + final boolean timestampIncluded = (flags & TIMESTAMP_FLAG) > 0; + + /* + * false Temperature type is not included + * true Temperature type included in the packet + */ + final boolean temperatureTypeIncluded = (flags & TEMPERATURE_TYPE_FLAG) > 0; + + final float tempValue = data.getFloatValue(Data.FORMAT_FLOAT, offset); + offset += 4; + + String dateTime = null; + if (timestampIncluded) { + dateTime = DateTimeParser.parse(data, offset); + offset += 7; + } + + String type = null; + if (temperatureTypeIncluded) { + type = TemperatureTypeParser.parse(data, offset); + // offset++; + } + + final StringBuilder builder = new StringBuilder(); + builder.append(String.format(Locale.US, "%.02f", tempValue)); + + if (fahrenheit) + builder.append("°F"); + else + builder.append("°C"); + + if (timestampIncluded) + builder.append("\nTime: ").append(dateTime); + if (temperatureTypeIncluded) + builder.append("\nType: ").append(type); + return builder.toString(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureTypeParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureTypeParser.java new file mode 100644 index 0000000..10d755e --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureTypeParser.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +@SuppressWarnings("ConstantConditions") +public class TemperatureTypeParser { + + public static String parse(final Data data) { + return parse(data, 0); + } + + /* package */static String parse(final Data data, final int offset) { + final int type = data.getValue()[offset]; + + switch (type) { + case 1: + return "Armpit"; + case 2: + return "Body (general)"; + case 3: + return "Ear (usually ear lobe)"; + case 4: + return "Finger"; + case 5: + return "Gastro-intestinal Tract"; + case 6: + return "Mouth"; + case 7: + return "Rectum"; + case 8: + return "Toe"; + case 9: + return "Tympanum (ear drum)"; + default: + return "Unknown"; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemplateParser.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemplateParser.java new file mode 100644 index 0000000..ed0490a --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemplateParser.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.parser; + +import no.nordicsemi.android.ble.data.Data; + +// TODO this method may be used for developing purposes to log the data from your device using the nRF Logger application. + +@SuppressWarnings("ConstantConditions") +public class TemplateParser { + // TODO add some flags, if needed + private static final byte HEART_RATE_VALUE_FORMAT = 0x01; // 1 bit + + /** + * This method converts the value of the characteristic to the String. The String is then logged in the nRF logger log session + * @param data the characteristic data to be parsed + * @return human readable value of the characteristic + */ + @SuppressWarnings("UnusedAssignment") + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + /* + * In the template we are using the HRM values as an example. + * false Heart Rate Value Format is set to UINT8. Units: beats per minute (bpm) + * true Heart Rate Value Format is set to UINT16. Units: beats per minute (bpm) + */ + final boolean value16bit = (flags & HEART_RATE_VALUE_FORMAT) > 0; + + // heart rate value is 8 or 16 bit long + int value = data.getIntValue(value16bit ? Data.FORMAT_UINT16 : Data.FORMAT_UINT8, offset++); // bits per minute + if (value16bit) + offset++; + + // TODO parse more data + + return "Template Measurement: " + value + " bpm"; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileActivity.java new file mode 100644 index 0000000..e9ea7ee --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileActivity.java @@ -0,0 +1,440 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.profile; + +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.UUID; + +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.LocalLogSession; +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.AppHelpFragment; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.scanner.ScannerFragment; +import no.nordicsemi.android.nrftoolbox.utility.DebugLogger; + +@SuppressWarnings("unused") +public abstract class BleProfileActivity extends AppCompatActivity implements BleManagerCallbacks, ScannerFragment.OnDeviceSelectedListener { + private static final String TAG = "BaseProfileActivity"; + + private static final String SIS_CONNECTION_STATUS = "connection_status"; + private static final String SIS_DEVICE_NAME = "device_name"; + protected static final int REQUEST_ENABLE_BT = 2; + + private LoggableBleManager mBleManager; + + private TextView mDeviceNameView; + private Button mConnectButton; + private ILogSession mLogSession; + + private boolean mDeviceConnected = false; + private String mDeviceName; + + @Override + protected final void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + ensureBLESupported(); + if (!isBLEEnabled()) { + showBLEDialog(); + } + + /* + * We use the managers using a singleton pattern. It's not recommended for the Android, because the singleton instance remains after Activity has been + * destroyed but it's simple and is used only for this demo purpose. In final application Managers should be created as a non-static objects in + * Services. The Service should implement ManagerCallbacks interface. The application Activity may communicate with such Service using binding, + * broadcast listeners, local broadcast listeners (see support.v4 library), or messages. See the Proximity profile for Service approach. + */ + mBleManager = initializeManager(); + + // In onInitialize method a final class may register local broadcast receivers that will listen for events from the service + onInitialize(savedInstanceState); + // The onCreateView class should... create the view + onCreateView(savedInstanceState); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + + // Common nRF Toolbox view references are obtained here + setUpView(); + // View is ready to be used + onViewCreated(savedInstanceState); + } + + /** + * You may do some initialization here. This method is called from {@link #onCreate(Bundle)} before the view was created. + */ + protected void onInitialize(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called from {@link #onCreate(Bundle)}. This method should build the activity UI, i.e. using {@link #setContentView(int)}. + * Use to obtain references to views. Connect/Disconnect button and the device name view are manager automatically. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected abstract void onCreateView(final Bundle savedInstanceState); + + /** + * Called after the view has been created. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected void onViewCreated(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called after the view and the toolbar has been created. + */ + protected final void setUpView() { + // set GUI + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + mConnectButton = findViewById(R.id.action_connect); + mDeviceNameView = findViewById(R.id.device_name); + } + + @Override + public void onBackPressed() { + mBleManager.disconnect().enqueue(); + super.onBackPressed(); + } + + @Override + protected void onSaveInstanceState(final Bundle outState) { + super.onSaveInstanceState(outState); + outState.putBoolean(SIS_CONNECTION_STATUS, mDeviceConnected); + outState.putString(SIS_DEVICE_NAME, mDeviceName); + } + + @Override + protected void onRestoreInstanceState(final @NonNull Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + mDeviceConnected = savedInstanceState.getBoolean(SIS_CONNECTION_STATUS); + mDeviceName = savedInstanceState.getString(SIS_DEVICE_NAME); + + if (mDeviceConnected) { + mConnectButton.setText(R.string.action_disconnect); + } else { + mConnectButton.setText(R.string.action_connect); + } + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.help, menu); + return true; + } + + /** + * Use this method to handle menu actions other than home and about. + * + * @param itemId the menu item id + * @return true if action has been handled + */ + protected boolean onOptionsItemSelected(final int itemId) { + // Overwrite when using menu other than R.menu.help + return false; + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + final int id = item.getItemId(); + switch (id) { + case android.R.id.home: + onBackPressed(); + break; + case R.id.action_about: + final AppHelpFragment fragment = AppHelpFragment.getInstance(getAboutTextId()); + fragment.show(getSupportFragmentManager(), "help_fragment"); + break; + default: + return onOptionsItemSelected(id); + } + return true; + } + + /** + * Called when user press CONNECT or DISCONNECT button. See layout files -> onClick attribute. + */ + public void onConnectClicked(final View view) { + if (isBLEEnabled()) { + if (!mDeviceConnected) { + setDefaultUI(); + showDeviceScanningDialog(getFilterUUID()); + } else { + mBleManager.disconnect().enqueue(); + } + } else { + showBLEDialog(); + } + } + + /** + * Returns the title resource id that will be used to create logger session. If 0 is returned (default) logger will not be used. + * + * @return the title resource id + */ + protected int getLoggerProfileTitle() { + return 0; + } + + /** + * This method may return the local log content provider authority if local log sessions are supported. + * + * @return local log session content provider URI + */ + protected Uri getLocalAuthorityLogger() { + return null; + } + + /** + * This method returns whether autoConnect option should be used. + * + * @return true to use autoConnect feature, false (default) otherwise. + */ + protected boolean shouldAutoConnect() { + return false; + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + final int titleId = getLoggerProfileTitle(); + if (titleId > 0) { + mLogSession = Logger.newSession(getApplicationContext(), getString(titleId), device.getAddress(), name); + // If nRF Logger is not installed we may want to use local logger + if (mLogSession == null && getLocalAuthorityLogger() != null) { + mLogSession = LocalLogSession.newSession(getApplicationContext(), getLocalAuthorityLogger(), device.getAddress(), name); + } + } + mDeviceName = name; + mBleManager.setLogger(mLogSession); + mBleManager.connect(device) + .useAutoConnect(shouldAutoConnect()) + .retry(3, 100) + .enqueue(); + } + + @Override + public void onDialogCanceled() { + // do nothing + } + + @Override + public void onDeviceConnecting(@NonNull final BluetoothDevice device) { + runOnUiThread(() -> { + mDeviceNameView.setText(mDeviceName != null ? mDeviceName : getString(R.string.not_available)); + mConnectButton.setText(R.string.action_connecting); + }); + } + + @Override + public void onDeviceConnected(@NonNull final BluetoothDevice device) { + mDeviceConnected = true; + runOnUiThread(() -> mConnectButton.setText(R.string.action_disconnect)); + } + + @Override + public void onDeviceDisconnecting(@NonNull final BluetoothDevice device) { + runOnUiThread(() -> mConnectButton.setText(R.string.action_disconnecting)); + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + mDeviceConnected = false; + mBleManager.close(); + runOnUiThread(() -> { + mConnectButton.setText(R.string.action_connect); + mDeviceNameView.setText(getDefaultDeviceName()); + }); + } + + @Override + public void onLinkLossOccurred(@NonNull final BluetoothDevice device) { + mDeviceConnected = false; + } + + @Override + public void onServicesDiscovered(@NonNull final BluetoothDevice device, boolean optionalServicesFound) { + // this may notify user or show some views + } + + @Override + public void onDeviceReady(@NonNull final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBondingRequired(@NonNull final BluetoothDevice device) { + showToast(R.string.bonding); + } + + @Override + public void onBonded(@NonNull final BluetoothDevice device) { + showToast(R.string.bonded); + } + + @Override + public void onBondingFailed(@NonNull final BluetoothDevice device) { + showToast(R.string.bonding_failed); + } + + @Override + public void onError(@NonNull final BluetoothDevice device, @NonNull final String message, final int errorCode) { + DebugLogger.e(TAG, "Error occurred: " + message + ", error code: " + errorCode); + showToast(message + " (" + errorCode + ")"); + } + + @Override + public void onDeviceNotSupported(@NonNull final BluetoothDevice device) { + showToast(R.string.not_supported); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param message a message to be shown + */ + protected void showToast(final String message) { + runOnUiThread(() -> Toast.makeText(BleProfileActivity.this, message, Toast.LENGTH_SHORT).show()); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param messageResId an resource id of the message to be shown + */ + protected void showToast(final int messageResId) { + runOnUiThread(() -> Toast.makeText(BleProfileActivity.this, messageResId, Toast.LENGTH_SHORT).show()); + } + + /** + * Returns true if the device is connected. Services may not have been discovered yet. + */ + protected boolean isDeviceConnected() { + return mDeviceConnected; + } + + /** + * Returns the name of the device that the phone is currently connected to or was connected last time + */ + protected String getDeviceName() { + return mDeviceName; + } + + /** + * Initializes the Bluetooth Low Energy manager. A manager is used to communicate with profile's services. + * + * @return the manager that was created + */ + protected abstract LoggableBleManager initializeManager(); + + /** + * Restores the default UI before reconnecting + */ + protected abstract void setDefaultUI(); + + /** + * Returns the default device name resource id. The real device name is obtained when connecting to the device. This one is used when device has + * disconnected. + * + * @return the default device name resource id + */ + protected abstract int getDefaultDeviceName(); + + /** + * Returns the string resource id that will be shown in About box + * + * @return the about resource id + */ + protected abstract int getAboutTextId(); + + /** + * The UUID filter is used to filter out available devices that does not have such UUID in their advertisement packet. See also: + * {@link #isChangingConfigurations()}. + * + * @return the required UUID or null + */ + protected abstract UUID getFilterUUID(); + + /** + * Shows the scanner fragment. + * + * @param filter the UUID filter used to filter out available devices. The fragment will always show all bonded devices as there is no information about their + * services + * @see #getFilterUUID() + */ + private void showDeviceScanningDialog(final UUID filter) { + runOnUiThread(() -> { + final ScannerFragment dialog = ScannerFragment.getInstance(filter); + dialog.show(getSupportFragmentManager(), "scan_fragment"); + }); + } + + /** + * Returns the log session. Log session is created when the device was selected using the {@link ScannerFragment} and released when user press DISCONNECT. + * + * @return the logger session or null + */ + protected ILogSession getLogSession() { + return mLogSession; + } + + private void ensureBLESupported() { + if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show(); + finish(); + } + } + + protected boolean isBLEEnabled() { + final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); + final BluetoothAdapter adapter = bluetoothManager.getAdapter(); + return adapter != null && adapter.isEnabled(); + } + + protected void showBLEDialog() { + final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileExpandableListActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileExpandableListActivity.java new file mode 100644 index 0000000..a7058bc --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileExpandableListActivity.java @@ -0,0 +1,443 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.profile; + +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.appcompat.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.UUID; + +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.LocalLogSession; +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.AppHelpFragment; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.app.ExpandableListActivity; +import no.nordicsemi.android.nrftoolbox.scanner.ScannerFragment; +import no.nordicsemi.android.nrftoolbox.utility.DebugLogger; + +@SuppressWarnings("unused") +public abstract class BleProfileExpandableListActivity extends ExpandableListActivity implements BleManagerCallbacks, ScannerFragment.OnDeviceSelectedListener { + private static final String TAG = "BaseProfileActivity"; + + private static final String SIS_CONNECTION_STATUS = "connection_status"; + private static final String SIS_DEVICE_NAME = "device_name"; + protected static final int REQUEST_ENABLE_BT = 2; + + private LoggableBleManager mBleManager; + + private TextView mDeviceNameView; + private Button mConnectButton; + private ILogSession mLogSession; + + private boolean mDeviceConnected = false; + private String mDeviceName; + + @Override + protected final void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + ensureBLESupported(); + if (!isBLEEnabled()) { + showBLEDialog(); + } + + /* + * We use the managers using a singleton pattern. It's not recommended for the Android, because the singleton instance remains after Activity has been + * destroyed but it's simple and is used only for this demo purpose. In final application Managers should be created as a non-static objects in + * Services. The Service should implement ManagerCallbacks interface. The application Activity may communicate with such Service using binding, + * broadcast listeners, local broadcast listeners (see support.v4 library), or messages. See the Proximity profile for Service approach. + */ + mBleManager = initializeManager(); + + // In onInitialize method a final class may register local broadcast receivers that will listen for events from the service + onInitialize(savedInstanceState); + // The onCreateView class should... create the view + onCreateView(savedInstanceState); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + + // Common nRF Toolbox view references are obtained here + setUpView(); + // View is ready to be used + onViewCreated(savedInstanceState); + } + + /** + * You may do some initialization here. This method is called from {@link #onCreate(Bundle)} before the view was created. + */ + @SuppressWarnings("unused") + protected void onInitialize(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called from {@link #onCreate(Bundle)}. This method should build the activity UI, i.e. using {@link #setContentView(int)}. + * Use to obtain references to views. Connect/Disconnect button and the device name view are manager automatically. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected abstract void onCreateView(final Bundle savedInstanceState); + + /** + * Called after the view has been created. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + @SuppressWarnings("unused") + protected void onViewCreated(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called after the view and the toolbar has been created. + */ + protected final void setUpView() { + // set GUI + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + mConnectButton = findViewById(R.id.action_connect); + mDeviceNameView = findViewById(R.id.device_name); + } + + @Override + public void onBackPressed() { + mBleManager.disconnect().enqueue(); + super.onBackPressed(); + } + + @Override + protected void onSaveInstanceState(final Bundle outState) { + super.onSaveInstanceState(outState); + outState.putBoolean(SIS_CONNECTION_STATUS, mDeviceConnected); + outState.putString(SIS_DEVICE_NAME, mDeviceName); + } + + @Override + protected void onRestoreInstanceState(final @NonNull Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + mDeviceConnected = savedInstanceState.getBoolean(SIS_CONNECTION_STATUS); + mDeviceName = savedInstanceState.getString(SIS_DEVICE_NAME); + + if (mDeviceConnected) { + mConnectButton.setText(R.string.action_disconnect); + } else { + mConnectButton.setText(R.string.action_connect); + } + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.help, menu); + return true; + } + + /** + * Use this method to handle menu actions other than home and about. + * + * @param itemId the menu item id + * @return true if action has been handled + */ + @SuppressWarnings("unused") + protected boolean onOptionsItemSelected(final int itemId) { + // Overwrite when using menu other than R.menu.help + return false; + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + final int id = item.getItemId(); + switch (id) { + case android.R.id.home: + onBackPressed(); + break; + case R.id.action_about: + final AppHelpFragment fragment = AppHelpFragment.getInstance(getAboutTextId()); + fragment.show(getSupportFragmentManager(), "help_fragment"); + break; + default: + return onOptionsItemSelected(id); + } + return true; + } + + /** + * Called when user press CONNECT or DISCONNECT button. See layout files -> onClick attribute. + */ + public void onConnectClicked(final View view) { + if (isBLEEnabled()) { + if (!mDeviceConnected) { + setDefaultUI(); + showDeviceScanningDialog(getFilterUUID()); + } else { + mBleManager.disconnect().enqueue(); + } + } else { + showBLEDialog(); + } + } + + /** + * Returns the title resource id that will be used to create logger session. If 0 is returned (default) logger will not be used. + * + * @return the title resource id + */ + protected int getLoggerProfileTitle() { + return 0; + } + + /** + * This method may return the local log content provider authority if local log sessions are supported. + * + * @return local log session content provider URI + */ + protected Uri getLocalAuthorityLogger() { + return null; + } + + /** + * This method returns whether autoConnect option should be used. + * + * @return true to use autoConnect feature, false (default) otherwise. + */ + protected boolean shouldAutoConnect() { + return false; + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + final int titleId = getLoggerProfileTitle(); + if (titleId > 0) { + mLogSession = Logger.newSession(getApplicationContext(), getString(titleId), device.getAddress(), name); + // If nRF Logger is not installed we may want to use local logger + if (mLogSession == null && getLocalAuthorityLogger() != null) { + mLogSession = LocalLogSession.newSession(getApplicationContext(), getLocalAuthorityLogger(), device.getAddress(), name); + } + } + mDeviceName = name; + mBleManager.setLogger(mLogSession); + mBleManager.connect(device) + .useAutoConnect(shouldAutoConnect()) + .retry(3, 100) + .enqueue(); + } + + @Override + public void onDialogCanceled() { + // do nothing + } + + @Override + public void onDeviceConnecting(@NonNull final BluetoothDevice device) { + runOnUiThread(() -> { + mDeviceNameView.setText(mDeviceName != null ? mDeviceName : getString(R.string.not_available)); + mConnectButton.setText(R.string.action_connecting); + }); + } + + @Override + public void onDeviceConnected(@NonNull final BluetoothDevice device) { + mDeviceConnected = true; + runOnUiThread(() -> mConnectButton.setText(R.string.action_disconnect)); + } + + @Override + public void onDeviceDisconnecting(@NonNull final BluetoothDevice device) { + runOnUiThread(() -> mConnectButton.setText(R.string.action_disconnecting)); + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + mDeviceConnected = false; + mBleManager.close(); + runOnUiThread(() -> { + mConnectButton.setText(R.string.action_connect); + mDeviceNameView.setText(getDefaultDeviceName()); + }); + } + + @Override + public void onLinkLossOccurred(@NonNull final BluetoothDevice device) { + mDeviceConnected = false; + } + + @Override + public void onServicesDiscovered(@NonNull final BluetoothDevice device, boolean optionalServicesFound) { + // this may notify user or show some views + } + + @Override + public void onDeviceReady(@NonNull final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBondingRequired(@NonNull final BluetoothDevice device) { + showToast(R.string.bonding); + } + + @Override + public void onBonded(@NonNull final BluetoothDevice device) { + showToast(R.string.bonded); + } + + @Override + public void onBondingFailed(@NonNull final BluetoothDevice device) { + showToast(R.string.bonding_failed); + } + + @Override + public void onError(@NonNull final BluetoothDevice device, @NonNull final String message, final int errorCode) { + DebugLogger.e(TAG, "Error occurred: " + message + ", error code: " + errorCode); + showToast(message + " (" + errorCode + ")"); + } + + @Override + public void onDeviceNotSupported(@NonNull final BluetoothDevice device) { + showToast(R.string.not_supported); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param message a message to be shown + */ + protected void showToast(final String message) { + runOnUiThread(() -> Toast.makeText(BleProfileExpandableListActivity.this, message, Toast.LENGTH_SHORT).show()); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param messageResId an resource id of the message to be shown + */ + protected void showToast(final int messageResId) { + runOnUiThread(() -> Toast.makeText(BleProfileExpandableListActivity.this, messageResId, Toast.LENGTH_SHORT).show()); + } + + /** + * Returns true if the device is connected. Services may not have been discovered yet. + */ + protected boolean isDeviceConnected() { + return mDeviceConnected; + } + + /** + * Returns the name of the device that the phone is currently connected to or was connected last time + */ + protected String getDeviceName() { + return mDeviceName; + } + + /** + * Initializes the Bluetooth Low Energy manager. A manager is used to communicate with profile's services. + * + * @return the manager that was created + */ + protected abstract LoggableBleManager initializeManager(); + + /** + * Restores the default UI before reconnecting + */ + protected abstract void setDefaultUI(); + + /** + * Returns the default device name resource id. The real device name is obtained when connecting to the device. This one is used when device has + * disconnected. + * + * @return the default device name resource id + */ + protected abstract int getDefaultDeviceName(); + + /** + * Returns the string resource id that will be shown in About box + * + * @return the about resource id + */ + protected abstract int getAboutTextId(); + + /** + * The UUID filter is used to filter out available devices that does not have such UUID in their advertisement packet. See also: + * {@link #isChangingConfigurations()}. + * + * @return the required UUID or null + */ + protected abstract UUID getFilterUUID(); + + /** + * Shows the scanner fragment. + * + * @param filter the UUID filter used to filter out available devices. The fragment will always show all bonded devices as there is no information about their + * services + * @see #getFilterUUID() + */ + private void showDeviceScanningDialog(final UUID filter) { + runOnUiThread(() -> { + final ScannerFragment dialog = ScannerFragment.getInstance(filter); + dialog.show(getSupportFragmentManager(), "scan_fragment"); + }); + } + + /** + * Returns the log session. Log session is created when the device was selected using the {@link ScannerFragment} and released when user press DISCONNECT. + * + * @return the logger session or null + */ + protected ILogSession getLogSession() { + return mLogSession; + } + + private void ensureBLESupported() { + if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show(); + finish(); + } + } + + protected boolean isBLEEnabled() { + final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); + final BluetoothAdapter adapter = bluetoothManager.getAdapter(); + return adapter != null && adapter.isEnabled(); + } + + protected void showBLEDialog() { + final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileService.java new file mode 100644 index 0000000..e63c377 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileService.java @@ -0,0 +1,603 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.profile; + +import android.app.Service; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.net.Uri; +import android.os.Binder; +import android.os.Handler; +import android.os.IBinder; +import androidx.annotation.NonNull; +import androidx.annotation.StringRes; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.util.Log; +import android.widget.Toast; + +import no.nordicsemi.android.ble.BleManager; +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.ble.utils.ILogger; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.Logger; + +@SuppressWarnings("unused") +public abstract class BleProfileService extends Service implements BleManagerCallbacks { + @SuppressWarnings("unused") + private static final String TAG = "BleProfileService"; + + public static final String BROADCAST_CONNECTION_STATE = "no.nordicsemi.android.nrftoolbox.BROADCAST_CONNECTION_STATE"; + public static final String BROADCAST_SERVICES_DISCOVERED = "no.nordicsemi.android.nrftoolbox.BROADCAST_SERVICES_DISCOVERED"; + public static final String BROADCAST_DEVICE_READY = "no.nordicsemi.android.nrftoolbox.DEVICE_READY"; + public static final String BROADCAST_BOND_STATE = "no.nordicsemi.android.nrftoolbox.BROADCAST_BOND_STATE"; + @Deprecated + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String BROADCAST_ERROR = "no.nordicsemi.android.nrftoolbox.BROADCAST_ERROR"; + + /** The parameter passed when creating the service. Must contain the address of the sensor that we want to connect to */ + public static final String EXTRA_DEVICE_ADDRESS = "no.nordicsemi.android.nrftoolbox.EXTRA_DEVICE_ADDRESS"; + /** The key for the device name that is returned in {@link #BROADCAST_CONNECTION_STATE} with state {@link #STATE_CONNECTED}. */ + public static final String EXTRA_DEVICE_NAME = "no.nordicsemi.android.nrftoolbox.EXTRA_DEVICE_NAME"; + public static final String EXTRA_DEVICE = "no.nordicsemi.android.nrftoolbox.EXTRA_DEVICE"; + public static final String EXTRA_LOG_URI = "no.nordicsemi.android.nrftoolbox.EXTRA_LOG_URI"; + public static final String EXTRA_CONNECTION_STATE = "no.nordicsemi.android.nrftoolbox.EXTRA_CONNECTION_STATE"; + public static final String EXTRA_BOND_STATE = "no.nordicsemi.android.nrftoolbox.EXTRA_BOND_STATE"; + public static final String EXTRA_SERVICE_PRIMARY = "no.nordicsemi.android.nrftoolbox.EXTRA_SERVICE_PRIMARY"; + public static final String EXTRA_SERVICE_SECONDARY = "no.nordicsemi.android.nrftoolbox.EXTRA_SERVICE_SECONDARY"; + @Deprecated + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + public static final String EXTRA_ERROR_MESSAGE = "no.nordicsemi.android.nrftoolbox.EXTRA_ERROR_MESSAGE"; + public static final String EXTRA_ERROR_CODE = "no.nordicsemi.android.nrftoolbox.EXTRA_ERROR_CODE"; + + public static final int STATE_LINK_LOSS = -1; + public static final int STATE_DISCONNECTED = 0; + public static final int STATE_CONNECTED = 1; + public static final int STATE_CONNECTING = 2; + public static final int STATE_DISCONNECTING = 3; + + private LoggableBleManager mBleManager; + private Handler mHandler; + + protected boolean mBound; + private boolean mActivityIsChangingConfiguration; + private BluetoothDevice mBluetoothDevice; + private String mDeviceName; + private ILogSession mLogSession; + + private final BroadcastReceiver mBluetoothStateBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); + final ILogger logger = getBinder(); + + final String stateString = "[Broadcast] Action received: " + BluetoothAdapter.ACTION_STATE_CHANGED + ", state changed to " + state2String(state); + logger.log(Log.DEBUG, stateString); + + switch (state) { + case BluetoothAdapter.STATE_ON: + onBluetoothEnabled(); + break; + case BluetoothAdapter.STATE_TURNING_OFF: + case BluetoothAdapter.STATE_OFF: + onBluetoothDisabled(); + break; + } + } + + private String state2String(final int state) { + switch (state) { + case BluetoothAdapter.STATE_TURNING_ON: + return "TURNING ON"; + case BluetoothAdapter.STATE_ON: + return "ON"; + case BluetoothAdapter.STATE_TURNING_OFF: + return "TURNING OFF"; + case BluetoothAdapter.STATE_OFF: + return "OFF"; + default: + return "UNKNOWN (" + state + ")"; + } + } + }; + + public class LocalBinder extends Binder implements ILogger { + /** + * Disconnects from the sensor. + */ + public final void disconnect() { + final int state = mBleManager.getConnectionState(); + if (state == BluetoothGatt.STATE_DISCONNECTED || state == BluetoothGatt.STATE_DISCONNECTING) { + mBleManager.close(); + onDeviceDisconnected(mBluetoothDevice); + return; + } + + mBleManager.disconnect().enqueue(); + } + + /** + * Sets whether the bound activity if changing configuration or not. + * If false, we will turn off battery level notifications in onUnbind(..) method below. + * @param changing true if the bound activity is finishing + */ + public void setActivityIsChangingConfiguration(final boolean changing) { + mActivityIsChangingConfiguration = changing; + } + + /** + * Returns the device address + * + * @return device address + */ + public String getDeviceAddress() { + return mBluetoothDevice.getAddress(); + } + + /** + * Returns the device name + * + * @return the device name + */ + public String getDeviceName() { + return mDeviceName; + } + + /** + * Returns the Bluetooth device + * + * @return the Bluetooth device + */ + public BluetoothDevice getBluetoothDevice() { + return mBluetoothDevice; + } + + /** + * Returns true if the device is connected to the sensor. + * + * @return true if device is connected to the sensor, false otherwise + */ + public boolean isConnected() { + return mBleManager.isConnected(); + } + + + /** + * Returns the connection state of given device. + * @return the connection state, as in {@link BleManager#getConnectionState()}. + */ + public int getConnectionState() { + return mBleManager.getConnectionState(); + } + + /** + * Returns the log session that can be used to append log entries. + * The log session is created when the service is being created. + * The method returns null if the nRF Logger app was not installed. + * + * @return the log session + */ + public ILogSession getLogSession() { + return mLogSession; + } + + @Override + public void log(final int level, @NonNull final String message) { + Logger.log(mLogSession, level, message); + } + + @Override + public void log(final int level, final @StringRes int messageRes, final Object... params) { + Logger.log(mLogSession, level, messageRes, params); + } + } + + /** + * Returns a handler that is created in onCreate(). + * The handler may be used to postpone execution of some operations or to run them in UI thread. + */ + protected Handler getHandler() { + return mHandler; + } + + /** + * Returns the binder implementation. This must return class implementing the additional manager interface that may be used in the bound activity. + * + * @return the service binder + */ + protected LocalBinder getBinder() { + // default implementation returns the basic binder. You can overwrite the LocalBinder with your own, wider implementation + return new LocalBinder(); + } + + @Override + public IBinder onBind(final Intent intent) { + mBound = true; + return getBinder(); + } + + @Override + public final void onRebind(final Intent intent) { + mBound = true; + + if (!mActivityIsChangingConfiguration) + onRebind(); + } + + /** + * Called when the activity has rebound to the service after being recreated. + * This method is not called when the activity was killed to be recreated when the phone orientation changed + * if prior to being killed called {@link BleProfileService.LocalBinder#setActivityIsChangingConfiguration(boolean)} with parameter true. + */ + protected void onRebind() { + // empty default implementation + } + + @Override + public final boolean onUnbind(final Intent intent) { + mBound = false; + + if (!mActivityIsChangingConfiguration) + onUnbind(); + + // We want the onRebind method be called if anything else binds to it again + return true; + } + + /** + * Called when the activity has unbound from the service before being finished. + * This method is not called when the activity is killed to be recreated when the phone orientation changed. + */ + protected void onUnbind() { + // empty default implementation + } + + @SuppressWarnings("unchecked") + @Override + public void onCreate() { + super.onCreate(); + + mHandler = new Handler(); + + // Initialize the manager + mBleManager = initializeManager(); + mBleManager.setGattCallbacks(this); + + // Register broadcast receivers + registerReceiver(mBluetoothStateBroadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); + + // Service has now been created + onServiceCreated(); + + // Call onBluetoothEnabled if Bluetooth enabled + final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + if (bluetoothAdapter.isEnabled()) { + onBluetoothEnabled(); + } + } + + /** + * Called when the service has been created, before the {@link #onBluetoothEnabled()} is called. + */ + protected void onServiceCreated() { + // empty default implementation + } + + /** + * Initializes the Ble Manager responsible for connecting to a single device. + * @return a new BleManager object + */ + @SuppressWarnings("rawtypes") + protected abstract LoggableBleManager initializeManager(); + + /** + * This method returns whether autoConnect option should be used. + * + * @return true to use autoConnect feature, false (default) otherwise. + */ + protected boolean shouldAutoConnect() { + return false; + } + + @Override + public int onStartCommand(final Intent intent, final int flags, final int startId) { + if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS)) + throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key"); + + final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI); + mLogSession = Logger.openSession(getApplicationContext(), logUri); + mDeviceName = intent.getStringExtra(EXTRA_DEVICE_NAME); + + Logger.i(mLogSession, "Service started"); + + final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); + final String deviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); + mBluetoothDevice = adapter.getRemoteDevice(deviceAddress); + + mBleManager.setLogger(mLogSession); + onServiceStarted(); + mBleManager.connect(mBluetoothDevice) + .useAutoConnect(shouldAutoConnect()) + .retry(3, 100) + .enqueue(); + return START_REDELIVER_INTENT; + } + + /** + * Called when the service has been started. The device name and address are set. + * The BLE Manager will try to connect to the device after this method finishes. + */ + protected void onServiceStarted() { + // empty default implementation + } + + @Override + public void onTaskRemoved(final Intent rootIntent) { + super.onTaskRemoved(rootIntent); + // This method is called when user removed the app from Recents. + // By default, the service will be killed and recreated immediately after that. + // However, all managed devices will be lost and devices will be disconnected. + stopSelf(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + // Unregister broadcast receivers + unregisterReceiver(mBluetoothStateBroadcastReceiver); + + // shutdown the manager + mBleManager.close(); + Logger.i(mLogSession, "Service destroyed"); + mBleManager = null; + mBluetoothDevice = null; + mDeviceName = null; + mLogSession = null; + mHandler = null; + } + + /** + * Method called when Bluetooth Adapter has been disabled. + */ + protected void onBluetoothDisabled() { + // empty default implementation + } + + /** + * This method is called when Bluetooth Adapter has been enabled and + * after the service was created if Bluetooth Adapter was enabled at that moment. + * This method could initialize all Bluetooth related features, for example open the GATT server. + */ + protected void onBluetoothEnabled() { + // empty default implementation + } + + @Override + public void onDeviceConnecting(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceConnected(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTED); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_DEVICE_NAME, mDeviceName); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceDisconnecting(@NonNull final BluetoothDevice device) { + // Notify user about changing the state to DISCONNECTING + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_DISCONNECTING); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * This method should return false if the service needs to do some asynchronous work after if has disconnected from the device. + * In that case the {@link #stopService()} method must be called when done. + * @return true (default) to automatically stop the service when device is disconnected. False otherwise. + */ + protected boolean stopWhenDisconnected() { + return true; + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + // Note 1: Do not use the device argument here unless you change calling onDeviceDisconnected from the binder above + + // Note 2: if BleManager#shouldAutoConnect() for this device returned true, this callback will be + // invoked ONLY when user requested disconnection (using Disconnect button). If the device + // disconnects due to a link loss, the onLinkLossOccurred(BluetoothDevice) method will be called instead. + + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_DISCONNECTED); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + if (stopWhenDisconnected()) + stopService(); + } + + protected void stopService() { + // user requested disconnection. We must stop the service + Logger.v(mLogSession, "Stopping service..."); + stopSelf(); + } + + @Override + public void onLinkLossOccurred(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_LINK_LOSS); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onServicesDiscovered(@NonNull final BluetoothDevice device, final boolean optionalServicesFound) { + final Intent broadcast = new Intent(BROADCAST_SERVICES_DISCOVERED); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_SERVICE_PRIMARY, true); + broadcast.putExtra(EXTRA_SERVICE_SECONDARY, optionalServicesFound); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceReady(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_DEVICE_READY); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceNotSupported(@NonNull final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_SERVICES_DISCOVERED); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_SERVICE_PRIMARY, false); + broadcast.putExtra(EXTRA_SERVICE_SECONDARY, false); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + // no need for disconnecting, it will be disconnected by the manager automatically + } + + @Override + public void onBatteryValueReceived(@NonNull final BluetoothDevice device, final int value) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, value); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBondingRequired(@NonNull final BluetoothDevice device) { + showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding); + + final Intent broadcast = new Intent(BROADCAST_BOND_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDING); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBonded(@NonNull final BluetoothDevice device) { + showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonded); + + final Intent broadcast = new Intent(BROADCAST_BOND_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBondingFailed(@NonNull final BluetoothDevice device) { + showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding_failed); + + final Intent broadcast = new Intent(BROADCAST_BOND_STATE); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onError(@NonNull final BluetoothDevice device, @NonNull final String message, final int errorCode) { + final Intent broadcast = new Intent(BROADCAST_ERROR); + broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); + broadcast.putExtra(EXTRA_ERROR_MESSAGE, message); + broadcast.putExtra(EXTRA_ERROR_CODE, errorCode); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param messageResId + * an resource id of the message to be shown + */ + protected void showToast(final int messageResId) { + mHandler.post(() -> Toast.makeText(BleProfileService.this, messageResId, Toast.LENGTH_SHORT).show()); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param message + * a message to be shown + */ + protected void showToast(final String message) { + mHandler.post(() -> Toast.makeText(BleProfileService.this, message, Toast.LENGTH_SHORT).show()); + } + + /** + * Returns the log session that can be used to append log entries. The method returns null if the nRF Logger app was not installed. It is safe to use logger when + * {@link #onServiceStarted()} has been called. + * + * @return the log session + */ + protected ILogSession getLogSession() { + return mLogSession; + } + + /** + * Returns the device address + * + * @return device address + */ + protected String getDeviceAddress() { + return mBluetoothDevice.getAddress(); + } + + /** + * Returns the Bluetooth device object + * + * @return bluetooth device + */ + protected BluetoothDevice getBluetoothDevice() { + return mBluetoothDevice; + } + + /** + * Returns the device name + * + * @return the device name + */ + protected String getDeviceName() { + return mDeviceName; + } + + /** + * Returns true if the device is connected to the sensor. + * + * @return true if device is connected to the sensor, false otherwise + */ + protected boolean isConnected() { + return mBleManager != null && mBleManager.isConnected(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileServiceReadyActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileServiceReadyActivity.java new file mode 100644 index 0000000..ce2069b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileServiceReadyActivity.java @@ -0,0 +1,671 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.profile; + +import android.app.Service; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.IBinder; +import androidx.annotation.NonNull; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import java.util.UUID; + +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.LocalLogSession; +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.AppHelpFragment; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.scanner.ScannerFragment; +import no.nordicsemi.android.nrftoolbox.utility.DebugLogger; + +/** + *

+ * The {@link BleProfileServiceReadyActivity} activity is designed to be the base class for profile activities that uses services in order to connect to the + * device. When user press CONNECT button a service is created and the activity binds to it. The service tries to connect to the service and notifies the + * activity using Local Broadcasts ({@link LocalBroadcastManager}). See {@link BleProfileService} for messages. If the device is not in range it will listen for + * it and connect when it become visible. The service exists until user will press DISCONNECT button. + *

+ *

+ * When user closes the activity (f.e. by pressing Back button) while being connected, the Service remains working. It's still connected to the device or still + * listens for it. When entering back to the activity, activity will to bind to the service and refresh UI. + *

+ */ +@SuppressWarnings("unused") +public abstract class BleProfileServiceReadyActivity extends AppCompatActivity implements + ScannerFragment.OnDeviceSelectedListener, BleManagerCallbacks { + private static final String TAG = "BleProfileServiceReadyActivity"; + + private static final String SIS_DEVICE_NAME = "device_name"; + private static final String SIS_DEVICE = "device"; + private static final String LOG_URI = "log_uri"; + protected static final int REQUEST_ENABLE_BT = 2; + + private E mService; + + private TextView mDeviceNameView; + private Button mConnectButton; + + private ILogSession mLogSession; + private BluetoothDevice mBluetoothDevice; + private String mDeviceName; + + private final BroadcastReceiver mCommonBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + // Check if the broadcast applies the connected device + if (!isBroadcastForThisDevice(intent)) + return; + + final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BleProfileService.EXTRA_DEVICE); + final String action = intent.getAction(); + switch (action) { + case BleProfileService.BROADCAST_CONNECTION_STATE: { + final int state = intent.getIntExtra(BleProfileService.EXTRA_CONNECTION_STATE, BleProfileService.STATE_DISCONNECTED); + + switch (state) { + case BleProfileService.STATE_CONNECTED: { + mDeviceName = intent.getStringExtra(BleProfileService.EXTRA_DEVICE_NAME); + onDeviceConnected(bluetoothDevice); + break; + } + case BleProfileService.STATE_DISCONNECTED: { + onDeviceDisconnected(bluetoothDevice); + mDeviceName = null; + break; + } + case BleProfileService.STATE_LINK_LOSS: { + onLinkLossOccurred(bluetoothDevice); + break; + } + case BleProfileService.STATE_CONNECTING: { + onDeviceConnecting(bluetoothDevice); + break; + } + case BleProfileService.STATE_DISCONNECTING: { + onDeviceDisconnecting(bluetoothDevice); + break; + } + default: + // there should be no other actions + break; + } + break; + } + case BleProfileService.BROADCAST_SERVICES_DISCOVERED: { + final boolean primaryService = intent.getBooleanExtra(BleProfileService.EXTRA_SERVICE_PRIMARY, false); + final boolean secondaryService = intent.getBooleanExtra(BleProfileService.EXTRA_SERVICE_SECONDARY, false); + + if (primaryService) { + onServicesDiscovered(bluetoothDevice, secondaryService); + } else { + onDeviceNotSupported(bluetoothDevice); + } + break; + } + case BleProfileService.BROADCAST_DEVICE_READY: { + onDeviceReady(bluetoothDevice); + break; + } + case BleProfileService.BROADCAST_BOND_STATE: { + final int state = intent.getIntExtra(BleProfileService.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); + switch (state) { + case BluetoothDevice.BOND_BONDING: + onBondingRequired(bluetoothDevice); + break; + case BluetoothDevice.BOND_BONDED: + onBonded(bluetoothDevice); + break; + } + break; + } + case BleProfileService.BROADCAST_ERROR: { + final String message = intent.getStringExtra(BleProfileService.EXTRA_ERROR_MESSAGE); + final int errorCode = intent.getIntExtra(BleProfileService.EXTRA_ERROR_CODE, 0); + onError(bluetoothDevice, message, errorCode); + break; + } + } + } + }; + + private ServiceConnection mServiceConnection = new ServiceConnection() { + @SuppressWarnings("unchecked") + @Override + public void onServiceConnected(final ComponentName name, final IBinder service) { + final E bleService = mService = (E) service; + mBluetoothDevice = bleService.getBluetoothDevice(); + mLogSession = mService.getLogSession(); + Logger.d(mLogSession, "Activity bound to the service"); + onServiceBound(bleService); + + // Update UI + mDeviceName = bleService.getDeviceName(); + mDeviceNameView.setText(mDeviceName); + mConnectButton.setText(R.string.action_disconnect); + + // And notify user if device is connected + if (bleService.isConnected()) { + onDeviceConnected(mBluetoothDevice); + } else { + // If the device is not connected it means that either it is still connecting, + // or the link was lost and service is trying to connect to it (autoConnect=true). + onDeviceConnecting(mBluetoothDevice); + } + } + + @Override + public void onServiceDisconnected(final ComponentName name) { + // Note: this method is called only when the service is killed by the system, + // not when it stops itself or is stopped by the activity. + // It will be called only when there is critically low memory, in practice never + // when the activity is in foreground. + Logger.d(mLogSession, "Activity disconnected from the service"); + mDeviceNameView.setText(getDefaultDeviceName()); + mConnectButton.setText(R.string.action_connect); + + mService = null; + mDeviceName = null; + mBluetoothDevice = null; + mLogSession = null; + onServiceUnbound(); + } + }; + + @Override + protected final void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + ensureBLESupported(); + if (!isBLEEnabled()) { + showBLEDialog(); + } + + // Restore the old log session + if (savedInstanceState != null) { + final Uri logUri = savedInstanceState.getParcelable(LOG_URI); + mLogSession = Logger.openSession(getApplicationContext(), logUri); + } + + // In onInitialize method a final class may register local broadcast receivers that will listen for events from the service + onInitialize(savedInstanceState); + // The onCreateView class should... create the view + onCreateView(savedInstanceState); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + + // Common nRF Toolbox view references are obtained here + setUpView(); + // View is ready to be used + onViewCreated(savedInstanceState); + + LocalBroadcastManager.getInstance(this).registerReceiver(mCommonBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onStart() { + super.onStart(); + + /* + * If the service has not been started before, the following lines will not start it. + * However, if it's running, the Activity will bind to it and notified via mServiceConnection. + */ + final Intent service = new Intent(this, getServiceClass()); + // We pass 0 as a flag so the service will not be created if not exists. + bindService(service, mServiceConnection, 0); + + /* + * When user exited the UARTActivity while being connected, the log session is kept in + * the service. We may not get it before binding to it so in this case this event will + * not be logged (mLogSession is null until onServiceConnected(..) is called). + * It will, however, be logged after the orientation changes. + */ + } + + @Override + protected void onStop() { + super.onStop(); + + try { + // We don't want to perform some operations (e.g. disable Battery Level notifications) + // in the service if we are just rotating the screen. However, when the activity will + // disappear, we may want to disable some device features to reduce the battery + // consumption. + if (mService != null) + mService.setActivityIsChangingConfiguration(isChangingConfigurations()); + + unbindService(mServiceConnection); + mService = null; + + Logger.d(mLogSession, "Activity unbound from the service"); + onServiceUnbound(); + mDeviceName = null; + mBluetoothDevice = null; + mLogSession = null; + } catch (final IllegalArgumentException e) { + // do nothing, we were not connected to the sensor + } + } + + @Override + protected void onDestroy() { + super.onDestroy(); + + LocalBroadcastManager.getInstance(this).unregisterReceiver(mCommonBroadcastReceiver); + } + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(BleProfileService.BROADCAST_CONNECTION_STATE); + intentFilter.addAction(BleProfileService.BROADCAST_SERVICES_DISCOVERED); + intentFilter.addAction(BleProfileService.BROADCAST_DEVICE_READY); + intentFilter.addAction(BleProfileService.BROADCAST_BOND_STATE); + intentFilter.addAction(BleProfileService.BROADCAST_ERROR); + return intentFilter; + } + + /** + * Called when activity binds to the service. The parameter is the object returned in {@link Service#onBind(Intent)} method in your service. The method is + * called when device gets connected or is created while sensor was connected before. You may use the binder as a sensor interface. + */ + protected abstract void onServiceBound(E binder); + + /** + * Called when activity unbinds from the service. You may no longer use this binder because the sensor was disconnected. This method is also called when you + * leave the activity being connected to the sensor in the background. + */ + protected abstract void onServiceUnbound(); + + /** + * Returns the service class for sensor communication. The service class must derive from {@link BleProfileService} in order to operate with this class. + * + * @return the service class + */ + protected abstract Class getServiceClass(); + + /** + * Returns the service interface that may be used to communicate with the sensor. This will return null if the device is disconnected from the + * sensor. + * + * @return the service binder or null + */ + protected E getService() { + return mService; + } + + /** + * You may do some initialization here. This method is called from {@link #onCreate(Bundle)} before the view was created. + */ + protected void onInitialize(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called from {@link #onCreate(Bundle)}. This method should build the activity UI, i.e. using {@link #setContentView(int)}. + * Use to obtain references to views. Connect/Disconnect button, the device name view are manager automatically. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected abstract void onCreateView(final Bundle savedInstanceState); + + /** + * Called after the view has been created. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected void onViewCreated(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called after the view and the toolbar has been created. + */ + protected final void setUpView() { + // set GUI + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + mConnectButton = findViewById(R.id.action_connect); + mDeviceNameView = findViewById(R.id.device_name); + } + + @Override + protected void onSaveInstanceState(final Bundle outState) { + super.onSaveInstanceState(outState); + outState.putString(SIS_DEVICE_NAME, mDeviceName); + outState.putParcelable(SIS_DEVICE, mBluetoothDevice); + if (mLogSession != null) + outState.putParcelable(LOG_URI, mLogSession.getSessionUri()); + } + + @Override + protected void onRestoreInstanceState(final @NonNull Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + mDeviceName = savedInstanceState.getString(SIS_DEVICE_NAME); + mBluetoothDevice = savedInstanceState.getParcelable(SIS_DEVICE); + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.help, menu); + return true; + } + + /** + * Use this method to handle menu actions other than home and about. + * + * @param itemId the menu item id + * @return true if action has been handled + */ + protected boolean onOptionsItemSelected(final int itemId) { + // Overwrite when using menu other than R.menu.help + return false; + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + final int id = item.getItemId(); + switch (id) { + case android.R.id.home: + onBackPressed(); + break; + case R.id.action_about: + final AppHelpFragment fragment = AppHelpFragment.getInstance(getAboutTextId()); + fragment.show(getSupportFragmentManager(), "help_fragment"); + break; + default: + return onOptionsItemSelected(id); + } + return true; + } + + /** + * Called when user press CONNECT or DISCONNECT button. See layout files -> onClick attribute. + */ + public void onConnectClicked(final View view) { + if (isBLEEnabled()) { + if (mService == null) { + setDefaultUI(); + showDeviceScanningDialog(getFilterUUID()); + } else { + mService.disconnect(); + } + } else { + showBLEDialog(); + } + } + + /** + * Returns the title resource id that will be used to create logger session. If 0 is returned (default) logger will not be used. + * + * @return the title resource id + */ + protected int getLoggerProfileTitle() { + return 0; + } + + /** + * This method may return the local log content provider authority if local log sessions are supported. + * + * @return local log session content provider URI + */ + protected Uri getLocalAuthorityLogger() { + return null; + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + final int titleId = getLoggerProfileTitle(); + if (titleId > 0) { + mLogSession = Logger.newSession(getApplicationContext(), getString(titleId), device.getAddress(), name); + // If nRF Logger is not installed we may want to use local logger + if (mLogSession == null && getLocalAuthorityLogger() != null) { + mLogSession = LocalLogSession.newSession(getApplicationContext(), getLocalAuthorityLogger(), device.getAddress(), name); + } + } + mBluetoothDevice = device; + mDeviceName = name; + + // The device may not be in the range but the service will try to connect to it if it reach it + Logger.d(mLogSession, "Creating service..."); + final Intent service = new Intent(this, getServiceClass()); + service.putExtra(BleProfileService.EXTRA_DEVICE_ADDRESS, device.getAddress()); + service.putExtra(BleProfileService.EXTRA_DEVICE_NAME, name); + if (mLogSession != null) + service.putExtra(BleProfileService.EXTRA_LOG_URI, mLogSession.getSessionUri()); + startService(service); + Logger.d(mLogSession, "Binding to the service..."); + bindService(service, mServiceConnection, 0); + } + + @Override + public void onDialogCanceled() { + // do nothing + } + + @Override + public void onDeviceConnecting(final BluetoothDevice device) { + mDeviceNameView.setText(mDeviceName != null ? mDeviceName : getString(R.string.not_available)); + mConnectButton.setText(R.string.action_connecting); + } + + @Override + public void onDeviceConnected(final BluetoothDevice device) { + mDeviceNameView.setText(mDeviceName); + mConnectButton.setText(R.string.action_disconnect); + } + + @Override + public void onDeviceDisconnecting(final BluetoothDevice device) { + mConnectButton.setText(R.string.action_disconnecting); + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + mConnectButton.setText(R.string.action_connect); + mDeviceNameView.setText(getDefaultDeviceName()); + + try { + Logger.d(mLogSession, "Unbinding from the service..."); + unbindService(mServiceConnection); + mService = null; + + Logger.d(mLogSession, "Activity unbound from the service"); + onServiceUnbound(); + mDeviceName = null; + mBluetoothDevice = null; + mLogSession = null; + } catch (final IllegalArgumentException e) { + // do nothing. This should never happen but does... + } + } + + @Override + public void onLinkLossOccurred(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // empty default implementation + } + + @Override + public void onDeviceReady(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBondingRequired(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBonded(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBondingFailed(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onError(final BluetoothDevice device, final String message, final int errorCode) { + DebugLogger.e(TAG, "Error occurred: " + message + ", error code: " + errorCode); + showToast(message + " (" + errorCode + ")"); + } + + @Override + public void onDeviceNotSupported(final BluetoothDevice device) { + showToast(R.string.not_supported); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param message a message to be shown + */ + protected void showToast(final String message) { + runOnUiThread(() -> Toast.makeText(BleProfileServiceReadyActivity.this, message, Toast.LENGTH_LONG).show()); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param messageResId an resource id of the message to be shown + */ + protected void showToast(final int messageResId) { + runOnUiThread(() -> Toast.makeText(BleProfileServiceReadyActivity.this, messageResId, Toast.LENGTH_SHORT).show()); + } + + /** + * Returns true if the device is connected. Services may not have been discovered yet. + */ + protected boolean isDeviceConnected() { + return mService != null && mService.isConnected(); + } + + /** + * Returns the name of the device that the phone is currently connected to or was connected last time + */ + protected String getDeviceName() { + return mDeviceName; + } + + /** + * Restores the default UI before reconnecting + */ + protected abstract void setDefaultUI(); + + /** + * Returns the default device name resource id. The real device name is obtained when connecting to the device. This one is used when device has + * disconnected. + * + * @return the default device name resource id + */ + protected abstract int getDefaultDeviceName(); + + /** + * Returns the string resource id that will be shown in About box + * + * @return the about resource id + */ + protected abstract int getAboutTextId(); + + /** + * The UUID filter is used to filter out available devices that does not have such UUID in their advertisement packet. See also: + * {@link #isChangingConfigurations()}. + * + * @return the required UUID or null + */ + protected abstract UUID getFilterUUID(); + + /** + * Checks the {@link BleProfileService#EXTRA_DEVICE} in the given intent and compares it with the connected BluetoothDevice object. + * @param intent intent received via a broadcast from the service + * @return true if the data in the intent apply to the connected device, false otherwise + */ + protected boolean isBroadcastForThisDevice(final Intent intent) { + final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BleProfileService.EXTRA_DEVICE); + return mBluetoothDevice != null && mBluetoothDevice.equals(bluetoothDevice); + } + + /** + * Shows the scanner fragment. + * + * @param filter the UUID filter used to filter out available devices. The fragment will always show all bonded devices as there is no information about their + * services + * @see #getFilterUUID() + */ + private void showDeviceScanningDialog(final UUID filter) { + final ScannerFragment dialog = ScannerFragment.getInstance(filter); + dialog.show(getSupportFragmentManager(), "scan_fragment"); + } + + /** + * Returns the log session. Log session is created when the device was selected using the {@link ScannerFragment} and released when user press DISCONNECT. + * + * @return the logger session or null + */ + protected ILogSession getLogSession() { + return mLogSession; + } + + private void ensureBLESupported() { + if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show(); + finish(); + } + } + + protected boolean isBLEEnabled() { + final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); + final BluetoothAdapter adapter = bluetoothManager.getAdapter(); + return adapter != null && adapter.isEnabled(); + } + + protected void showBLEDialog() { + final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/LoggableBleManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/LoggableBleManager.java new file mode 100644 index 0000000..1b4685c --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/LoggableBleManager.java @@ -0,0 +1,48 @@ +package no.nordicsemi.android.nrftoolbox.profile; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import android.util.Log; + +import no.nordicsemi.android.ble.BleManager; +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.log.Logger; + +/** + * The manager that logs to nRF Logger. If nRF Logger is not installed, logs are ignored. + * + * @param the callbacks class. + */ +public abstract class LoggableBleManager extends BleManager { + private ILogSession mLogSession; + + /** + * The manager constructor. + *

+ * After constructing the manager, the callbacks object must be set with + * {@link #setGattCallbacks(BleManagerCallbacks)}. + * + * @param context the context. + */ + public LoggableBleManager(@NonNull final Context context) { + super(context); + } + + /** + * Sets the log session to log into. + * + * @param session nRF Logger log session to log inti, or null, if nRF Logger is not installed. + */ + public void setLogger(@Nullable final ILogSession session) { + mLogSession = session; + } + + @Override + public void log(final int priority, @NonNull final String message) { + Logger.log(mLogSession, LogContract.Log.Level.fromPriority(priority), message); + Log.println(priority, "BleManager", message); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileService.java new file mode 100644 index 0000000..9d651f8 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileService.java @@ -0,0 +1,621 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.profile.multiconnect; + +import android.app.Service; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Binder; +import android.os.Handler; +import android.os.IBinder; +import androidx.annotation.NonNull; +import androidx.annotation.StringRes; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.util.Log; +import android.widget.Toast; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import no.nordicsemi.android.ble.BleManager; +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.ble.utils.ILogger; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +public abstract class BleMulticonnectProfileService extends Service implements BleManagerCallbacks { + @SuppressWarnings("unused") + private static final String TAG = "BleMultiProfileService"; + + public static final String BROADCAST_CONNECTION_STATE = "no.nordicsemi.android.nrftoolbox.BROADCAST_CONNECTION_STATE"; + public static final String BROADCAST_SERVICES_DISCOVERED = "no.nordicsemi.android.nrftoolbox.BROADCAST_SERVICES_DISCOVERED"; + public static final String BROADCAST_DEVICE_READY = "no.nordicsemi.android.nrftoolbox.DEVICE_READY"; + public static final String BROADCAST_BOND_STATE = "no.nordicsemi.android.nrftoolbox.BROADCAST_BOND_STATE"; + @Deprecated + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String BROADCAST_ERROR = "no.nordicsemi.android.nrftoolbox.BROADCAST_ERROR"; + + public static final String EXTRA_DEVICE = "no.nordicsemi.android.nrftoolbox.EXTRA_DEVICE"; + public static final String EXTRA_CONNECTION_STATE = "no.nordicsemi.android.nrftoolbox.EXTRA_CONNECTION_STATE"; + public static final String EXTRA_BOND_STATE = "no.nordicsemi.android.nrftoolbox.EXTRA_BOND_STATE"; + public static final String EXTRA_SERVICE_PRIMARY = "no.nordicsemi.android.nrftoolbox.EXTRA_SERVICE_PRIMARY"; + public static final String EXTRA_SERVICE_SECONDARY = "no.nordicsemi.android.nrftoolbox.EXTRA_SERVICE_SECONDARY"; + @Deprecated + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + public static final String EXTRA_ERROR_MESSAGE = "no.nordicsemi.android.nrftoolbox.EXTRA_ERROR_MESSAGE"; + public static final String EXTRA_ERROR_CODE = "no.nordicsemi.android.nrftoolbox.EXTRA_ERROR_CODE"; + + public static final int STATE_LINK_LOSS = -1; + public static final int STATE_DISCONNECTED = 0; + public static final int STATE_CONNECTED = 1; + public static final int STATE_CONNECTING = 2; + public static final int STATE_DISCONNECTING = 3; + + private HashMap> mBleManagers; + private List mManagedDevices; + private Handler mHandler; + + protected boolean mBound; + private boolean mActivityIsChangingConfiguration; + + private final BroadcastReceiver mBluetoothStateBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); + final int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.STATE_OFF); + + switch (state) { + case BluetoothAdapter.STATE_ON: + // On older phones (tested on Nexus 4 with Android 5.0.1) the Bluetooth requires some time + // after it has been enabled before some operations can start. Starting the GATT server here + // without a delay is very likely to cause a DeadObjectException from BluetoothManager#openGattServer(...). + mHandler.postDelayed(() -> onBluetoothEnabled(), 600); + break; + case BluetoothAdapter.STATE_TURNING_OFF: + case BluetoothAdapter.STATE_OFF: + if (previousState != BluetoothAdapter.STATE_TURNING_OFF && previousState != BluetoothAdapter.STATE_OFF) + onBluetoothDisabled(); + break; + } + } + }; + + public class LocalBinder extends Binder implements ILogger, IDeviceLogger { + /** + * Returns an unmodifiable list of devices managed by the service. + * The returned devices do not need to be connected at tha moment. Each of them was however created + * using {@link #connect(BluetoothDevice)} method so they might have been connected before and disconnected. + * @return unmodifiable list of devices managed by the service + */ + public final List getManagedDevices() { + return Collections.unmodifiableList(mManagedDevices); + } + + /** + * Connects to the given device. If the device is already connected this method does nothing. + * @param device target Bluetooth device + */ + public void connect(final BluetoothDevice device) { + connect(device, null); + } + + /** + * Adds the given device to managed and stars connecting to it. If the device is already connected this method does nothing. + * @param device target Bluetooth device + * @param session log session that has to be used by the device + */ + @SuppressWarnings("unchecked") + public void connect(final BluetoothDevice device, final ILogSession session) { + // If a device is in managed devices it means that it's already connected, or was connected + // using autoConnect and the link was lost but Android is already trying to connect to it. + if (mManagedDevices.contains(device)) + return; + mManagedDevices.add(device); + + LoggableBleManager manager = mBleManagers.get(device); + if (manager != null) { + if (session != null) + manager.setLogger(session); + manager.connect(device).enqueue(); + } else { + mBleManagers.put(device, manager = initializeManager()); + manager.setGattCallbacks(BleMulticonnectProfileService.this); + manager.setLogger(session); + manager.connect(device) + .fail((d, status) -> { + mManagedDevices.remove(device); + mBleManagers.remove(device); + }) + .enqueue(10000); + } + } + + /** + * Disconnects the given device and removes the associated BleManager object. + * If the list of BleManagers is empty while the last activity unbinds from the service, + * the service will stop itself. + * @param device target device to disconnect and forget + */ + public void disconnect(final BluetoothDevice device) { + final BleManager manager = mBleManagers.get(device); + if (manager != null && manager.isConnected()) { + manager.disconnect().enqueue(); + } + mManagedDevices.remove(device); + } + + /** + * Returns true if the device is connected to the sensor. + * @param device the target device + * @return true if device is connected to the sensor, false otherwise + */ + public final boolean isConnected(final BluetoothDevice device) { + final BleManager manager = mBleManagers.get(device); + return manager != null && manager.isConnected(); + } + + /** + * Returns true if the device has finished initializing. + * @param device the target device + * @return true if device is connected to the sensor and has finished + * initializing. False otherwise. + */ + public final boolean isReady(final BluetoothDevice device) { + final BleManager manager = mBleManagers.get(device); + return manager != null && manager.isReady(); + } + + /** + * Returns the connection state of given device. + * @param device the target device + * @return the connection state, as in {@link BleManager#getConnectionState()}. + */ + public final int getConnectionState(final BluetoothDevice device) { + final BleManager manager = mBleManagers.get(device); + return manager != null ? manager.getConnectionState() : BluetoothGatt.STATE_DISCONNECTED; + } + + /** + * Returns the last received battery level value. + * @param device the device of which battery level should be returned + * @return battery value or -1 if no value was received or Battery Level characteristic was not found + * @deprecated Keep battery value in your manager instead. + */ + @Deprecated + public int getBatteryValue(final BluetoothDevice device) { + final BleManager manager = mBleManagers.get(device); + return manager.getBatteryValue(); + } + + /** + * Sets whether the bound activity if changing configuration or not. + * If false, we will turn off battery level notifications in onUnbind(..) method below. + * @param changing true if the bound activity is finishing + */ + public final void setActivityIsChangingConfiguration(final boolean changing) { + mActivityIsChangingConfiguration = changing; + } + + @Override + public void log(final BluetoothDevice device, final int level, final String message) { + final BleManager manager = mBleManagers.get(device); + if (manager != null) + manager.log(level, message); + } + + @Override + public void log(final BluetoothDevice device, final int level, @StringRes final int messageRes, final Object... params) { + final BleManager manager = mBleManagers.get(device); + if (manager != null) + manager.log(level, messageRes, params); + } + + @Override + public void log(final int level, @NonNull final String message) { + for (final BleManager manager : mBleManagers.values()) + manager.log(level, message); + } + + @Override + public void log(final int level, @StringRes final int messageRes, final Object... params) { + for (final BleManager manager : mBleManagers.values()) + manager.log(level, messageRes, params); + } + } + + /** + * Returns a handler that is created in onCreate(). + * The handler may be used to postpone execution of some operations or to run them in UI thread. + */ + protected Handler getHandler() { + return mHandler; + } + + /** + * Returns the binder implementation. This must return class implementing the additional manager interface that may be used in the bound activity. + * + * @return the service binder + */ + protected LocalBinder getBinder() { + // default implementation returns the basic binder. You can overwrite the LocalBinder with your own, wider implementation + return new LocalBinder(); + } + + @Override + public IBinder onBind(final Intent intent) { + mBound = true; + return getBinder(); + } + + @Override + public final void onRebind(final Intent intent) { + mBound = true; + + if (!mActivityIsChangingConfiguration) { + onRebind(); + } + } + + /** + * Called when the activity has rebound to the service after being recreated. + * This method is not called when the activity was killed to be recreated when the phone orientation changed + * if prior to being killed called {@link LocalBinder#setActivityIsChangingConfiguration(boolean)} with parameter true. + */ + protected void onRebind() { + // empty default implementation + } + + @Override + public final boolean onUnbind(final Intent intent) { + mBound = false; + + if (!mActivityIsChangingConfiguration) { + if (!mManagedDevices.isEmpty()) { + onUnbind(); + } else { + // The last activity has disconnected from the service and there are no devices to manage. The service may be stopped. + stopSelf(); + } + } + + // We want the onRebind method be called if anything else binds to it again + return true; + } + + /** + * Called when the activity has unbound from the service before being finished. + * This method is not called when the activity is killed to be recreated when the phone orientation changed. + */ + protected void onUnbind() { + // empty default implementation + } + + @Override + public void onCreate() { + super.onCreate(); + + mHandler = new Handler(); + + // Initialize the map of BLE managers + mBleManagers = new HashMap<>(); + mManagedDevices = new ArrayList<>(); + + // Register broadcast receivers + registerReceiver(mBluetoothStateBroadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); + + // Service has now been created + onServiceCreated(); + + // Call onBluetoothEnabled if Bluetooth enabled + final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + if (bluetoothAdapter.isEnabled()) { + onBluetoothEnabled(); + } + } + + /** + * Called when the service has been created, before the {@link #onBluetoothEnabled()} is called. + */ + protected void onServiceCreated() { + // empty default implementation + } + + /** + * Initializes the Ble Manager responsible for connecting to a single device. + * @return a new BleManager object + */ + @SuppressWarnings("rawtypes") + protected abstract LoggableBleManager initializeManager(); + + @Override + public int onStartCommand(final Intent intent, final int flags, final int startId) { + onServiceStarted(); + // The service does not save addresses of managed devices. + // A bound activity will be required to add connections again. + return START_NOT_STICKY; + } + + /** + * Called when the service has been started. + */ + protected void onServiceStarted() { + // empty default implementation + } + + @Override + public void onTaskRemoved(final Intent rootIntent) { + super.onTaskRemoved(rootIntent); + // This method is called when user removed the app from Recents. + // By default, the service will be killed and recreated immediately after that. + // However, all managed devices will be lost and devices will be disconnected. + stopSelf(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + onServiceStopped(); + mHandler = null; + } + + /** + * Called when the service has been stopped. + */ + protected void onServiceStopped() { + // Unregister broadcast receivers + unregisterReceiver(mBluetoothStateBroadcastReceiver); + + // The managers map may not be empty if the service was killed by the system + for (final BleManager manager : mBleManagers.values()) { + // Service is being destroyed, no need to disconnect manually. + manager.close(); + manager.log(Log.INFO, "Service destroyed"); + } + mBleManagers.clear(); + mManagedDevices.clear(); + mBleManagers = null; + mManagedDevices = null; + } + + /** + * Method called when Bluetooth Adapter has been disabled. + */ + protected void onBluetoothDisabled() { + // do nothing, BleManagers have their own Bluetooth State broadcast received and will close themselves + } + + /** + * This method is called when Bluetooth Adapter has been enabled. It is also called + * after the service was created if Bluetooth Adapter was enabled at that moment. + * This method could initialize all Bluetooth related features, for example open the GATT server. + * Make sure you call super.onBluetoothEnabled() at this methods reconnects to + * devices that were connected before the Bluetooth was turned off. + */ + protected void onBluetoothEnabled() { + for (final BluetoothDevice device : mManagedDevices) { + final BleManager manager = mBleManagers.get(device); + if (!manager.isConnected()) + manager.connect(device).enqueue(); + } + } + + @Override + public void onDeviceConnecting(final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING); + LocalBroadcastManager.getInstance(BleMulticonnectProfileService.this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceConnected(final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTED); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceDisconnecting(final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_DISCONNECTING); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + // Note: if BleManager#shouldAutoConnect() for this device returned true, this callback will be + // invoked ONLY when user requested disconnection (using Disconnect button). If the device + // disconnects due to a link loss, the onLinkLossOccurred(BluetoothDevice) method will be called instead. + + // We no longer want to keep the device in the service + mManagedDevices.remove(device); + // The BleManager is not removed from the HashMap in order to keep the device's log session. + // mBleManagers.remove(device); + + // Do not use the device argument here unless you change calling onDeviceDisconnected from the binder above + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_DISCONNECTED); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + // When user disconnected the last device while the activity was not bound the service can be stopped + if (!mBound && mManagedDevices.isEmpty()) { + stopSelf(); + } + } + + @Override + public void onLinkLossOccurred(final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_LINK_LOSS); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + final Intent broadcast = new Intent(BROADCAST_SERVICES_DISCOVERED); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_SERVICE_PRIMARY, true); + broadcast.putExtra(EXTRA_SERVICE_SECONDARY, optionalServicesFound); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceReady(final BluetoothDevice device) { + final Intent broadcast = new Intent(BROADCAST_DEVICE_READY); + broadcast.putExtra(EXTRA_DEVICE, device); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onDeviceNotSupported(final BluetoothDevice device) { + // We don't like this device, remove it from both collections + mManagedDevices.remove(device); + mBleManagers.remove(device); + + final Intent broadcast = new Intent(BROADCAST_SERVICES_DISCOVERED); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_SERVICE_PRIMARY, false); + broadcast.putExtra(EXTRA_SERVICE_SECONDARY, false); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + // no need for disconnecting, it will be disconnected by the manager automatically + } + + @Override + public void onBatteryValueReceived(final BluetoothDevice device, final int value) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, value); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBondingRequired(final BluetoothDevice device) { + showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding); + + final Intent broadcast = new Intent(BROADCAST_BOND_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDING); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBonded(final BluetoothDevice device) { + showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonded); + + final Intent broadcast = new Intent(BROADCAST_BOND_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onBondingFailed(final BluetoothDevice device) { + showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding_failed); + + final Intent broadcast = new Intent(BROADCAST_BOND_STATE); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + @Override + public void onError(final BluetoothDevice device, final String message, final int errorCode) { + final Intent broadcast = new Intent(BROADCAST_ERROR); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_ERROR_MESSAGE, message); + broadcast.putExtra(EXTRA_ERROR_CODE, errorCode); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param messageResId + * an resource id of the message to be shown + */ + protected void showToast(final int messageResId) { + mHandler.post(() -> Toast.makeText(BleMulticonnectProfileService.this, messageResId, Toast.LENGTH_SHORT).show()); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param message + * a message to be shown + */ + protected void showToast(final String message) { + mHandler.post(() -> Toast.makeText(BleMulticonnectProfileService.this, message, Toast.LENGTH_SHORT).show()); + } + + /** + * Returns the {@link BleManager} object associated with given device, or null if such has not been created. + * To create a BleManager call the {@link LocalBinder#connect(BluetoothDevice)} method must be called. + * @param device the target device + * @return the BleManager or null + */ + protected BleManager getBleManager(final BluetoothDevice device) { + return mBleManagers.get(device); + } + + /** + * Returns unmodifiable list of all managed devices. They don't have to be connected at the moment. + * @return list of managed devices + */ + protected List getManagedDevices() { + return Collections.unmodifiableList(mManagedDevices); + } + + /** + * Returns a list of those managed devices that are connected at the moment. + * @return list of connected devices + */ + protected List getConnectedDevices() { + final List list = new ArrayList<>(); + for (BluetoothDevice device : mManagedDevices) { + if (mBleManagers.get(device).isConnected()) + list.add(device); + } + return Collections.unmodifiableList(list); + } + + /** + * Returns true if the device is connected to the sensor. + * @param device the target device + * @return true if device is connected to the sensor, false otherwise + */ + protected boolean isConnected(final BluetoothDevice device) { + final BleManager manager = mBleManagers.get(device); + return manager != null && manager.isConnected(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java new file mode 100644 index 0000000..d3bad57 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java @@ -0,0 +1,549 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.profile.multiconnect; + +import android.app.Service; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.IBinder; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Toast; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import no.nordicsemi.android.ble.BleManagerCallbacks; +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.LocalLogSession; +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.AppHelpFragment; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.scanner.ScannerFragment; +import no.nordicsemi.android.nrftoolbox.utility.DebugLogger; + +/** + *

+ * The {@link BleMulticonnectProfileServiceReadyActivity} activity is designed to be the base class for profile activities that uses services in order to connect + * more than one device at the same time. A service extending {@link BleMulticonnectProfileService} is created when the activity is created, and the activity binds to it. + * The service returns a binder that may be used to connect, disconnect or manage devices, and notifies the + * activity using Local Broadcasts ({@link LocalBroadcastManager}). See {@link BleMulticonnectProfileService} for messages. If the device is not in range it will listen for + * it and connect when it become visible. The service exists until all managed devices have been disconnected and unmanaged and the last activity unbinds from it. + *

+ *

+ * When user closes the activity (e.g. by pressing Back button) while being connected, the Service remains working. It's remains connected to the devices or still + * listens for updates from them. When entering back to the activity, activity will to bind to the service and refresh UI. + *

+ */ +public abstract class BleMulticonnectProfileServiceReadyActivity extends AppCompatActivity implements + ScannerFragment.OnDeviceSelectedListener, BleManagerCallbacks { + private static final String TAG = "BleMulticonnectProfileServiceReadyActivity"; + + protected static final int REQUEST_ENABLE_BT = 2; + + private E mService; + private List mManagedDevices; + + private final BroadcastReceiver mCommonBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BleMulticonnectProfileService.EXTRA_DEVICE); + final String action = intent.getAction(); + switch (action) { + case BleMulticonnectProfileService.BROADCAST_CONNECTION_STATE: { + final int state = intent.getIntExtra(BleMulticonnectProfileService.EXTRA_CONNECTION_STATE, BleMulticonnectProfileService.STATE_DISCONNECTED); + + switch (state) { + case BleMulticonnectProfileService.STATE_CONNECTED: { + onDeviceConnected(bluetoothDevice); + break; + } + case BleMulticonnectProfileService.STATE_DISCONNECTED: { + onDeviceDisconnected(bluetoothDevice); + break; + } + case BleMulticonnectProfileService.STATE_LINK_LOSS: { + onLinkLossOccurred(bluetoothDevice); + break; + } + case BleMulticonnectProfileService.STATE_CONNECTING: { + onDeviceConnecting(bluetoothDevice); + break; + } + case BleMulticonnectProfileService.STATE_DISCONNECTING: { + onDeviceDisconnecting(bluetoothDevice); + break; + } + default: + // there should be no other actions + break; + } + break; + } + case BleMulticonnectProfileService.BROADCAST_SERVICES_DISCOVERED: { + final boolean primaryService = intent.getBooleanExtra(BleMulticonnectProfileService.EXTRA_SERVICE_PRIMARY, false); + final boolean secondaryService = intent.getBooleanExtra(BleMulticonnectProfileService.EXTRA_SERVICE_SECONDARY, false); + + if (primaryService) { + onServicesDiscovered(bluetoothDevice, secondaryService); + } else { + onDeviceNotSupported(bluetoothDevice); + } + break; + } + case BleMulticonnectProfileService.BROADCAST_DEVICE_READY: { + onDeviceReady(bluetoothDevice); + break; + } + case BleMulticonnectProfileService.BROADCAST_BOND_STATE: { + final int state = intent.getIntExtra(BleMulticonnectProfileService.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE); + switch (state) { + case BluetoothDevice.BOND_BONDING: + onBondingRequired(bluetoothDevice); + break; + case BluetoothDevice.BOND_BONDED: + onBonded(bluetoothDevice); + break; + } + break; + } + case BleMulticonnectProfileService.BROADCAST_BATTERY_LEVEL: { + final int value = intent.getIntExtra(BleMulticonnectProfileService.EXTRA_BATTERY_LEVEL, -1); + if (value > 0) + onBatteryValueReceived(bluetoothDevice, value); + break; + } + case BleMulticonnectProfileService.BROADCAST_ERROR: { + final String message = intent.getStringExtra(BleMulticonnectProfileService.EXTRA_ERROR_MESSAGE); + final int errorCode = intent.getIntExtra(BleMulticonnectProfileService.EXTRA_ERROR_CODE, 0); + onError(bluetoothDevice, message, errorCode); + break; + } + } + } + }; + + private ServiceConnection mServiceConnection = new ServiceConnection() { + @SuppressWarnings("unchecked") + @Override + public void onServiceConnected(final ComponentName name, final IBinder service) { + final E bleService = mService = (E) service; + bleService.log(Log.DEBUG, "Activity bound to the service"); + mManagedDevices.addAll(bleService.getManagedDevices()); + onServiceBound(bleService); + + // and notify user if device is connected + for (final BluetoothDevice device : mManagedDevices) { + if (bleService.isConnected(device)) + onDeviceConnected(device); + } + } + + @Override + public void onServiceDisconnected(final ComponentName name) { + mService = null; + onServiceUnbound(); + } + }; + + @Override + protected final void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mManagedDevices = new ArrayList<>(); + + ensureBLESupported(); + if (!isBLEEnabled()) { + showBLEDialog(); + } + + // In onInitialize method a final class may register local broadcast receivers that will listen for events from the service + onInitialize(savedInstanceState); + // The onCreateView class should... create the view + onCreateView(savedInstanceState); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + + // Common nRF Toolbox view references are obtained here + setUpView(); + // View is ready to be used + onViewCreated(savedInstanceState); + + LocalBroadcastManager.getInstance(this).registerReceiver(mCommonBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onStart() { + super.onStart(); + + /* + * In comparison to BleProfileServiceReadyActivity this activity always starts the service when started. + * Connecting to a device is done by calling mService.connect(BluetoothDevice) method, not startService(...) like there. + * The service will stop itself when all devices it manages were disconnected and unmanaged and the last activity unbinds from it. + */ + final Intent service = new Intent(this, getServiceClass()); + startService(service); + bindService(service, mServiceConnection, 0); + } + + @Override + protected void onStop() { + super.onStop(); + + if (mService != null) { + // We don't want to perform some operations (e.g. disable Battery Level notifications) in the service if we are just rotating the screen. + // However, when the activity will disappear, we may want to disable some device features to reduce the battery consumption. + mService.setActivityIsChangingConfiguration(isChangingConfigurations()); + // Log it here as there is no callback when the service gets unbound + // and the mService will not be available later (the activity doesn't keep log sessions) + mService.log(Log.DEBUG, "Activity unbound from the service"); + } + + unbindService(mServiceConnection); + mService = null; + + onServiceUnbound(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + + LocalBroadcastManager.getInstance(this).unregisterReceiver(mCommonBroadcastReceiver); + } + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(BleMulticonnectProfileService.BROADCAST_CONNECTION_STATE); + intentFilter.addAction(BleMulticonnectProfileService.BROADCAST_SERVICES_DISCOVERED); + intentFilter.addAction(BleMulticonnectProfileService.BROADCAST_DEVICE_READY); + intentFilter.addAction(BleMulticonnectProfileService.BROADCAST_BOND_STATE); + intentFilter.addAction(BleMulticonnectProfileService.BROADCAST_BATTERY_LEVEL); + intentFilter.addAction(BleMulticonnectProfileService.BROADCAST_ERROR); + return intentFilter; + } + + /** + * Called when activity binds to the service. The parameter is the object returned in {@link Service#onBind(Intent)} method in your service. + * It is safe to obtain managed devices now. + */ + protected abstract void onServiceBound(E binder); + + /** + * Called when activity unbinds from the service. You may no longer use this binder methods. + */ + protected abstract void onServiceUnbound(); + + /** + * Returns the service class for sensor communication. The service class must derive from {@link BleMulticonnectProfileService} in order to operate with this class. + * + * @return the service class + */ + protected abstract Class getServiceClass(); + + /** + * Returns the service interface that may be used to communicate with the sensor. This will return null if the device is disconnected from the + * sensor. + * + * @return the service binder or null + */ + protected E getService() { + return mService; + } + + /** + * You may do some initialization here. This method is called from {@link #onCreate(Bundle)} before the view was created. + */ + protected void onInitialize(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called from {@link #onCreate(Bundle)}. This method should build the activity UI, i.e. using {@link #setContentView(int)}. + * Use to obtain references to views. Connect/Disconnect button and the device name view are manager automatically. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected abstract void onCreateView(final Bundle savedInstanceState); + + /** + * Called after the view has been created. + * + * @param savedInstanceState contains the data it most recently supplied in {@link #onSaveInstanceState(Bundle)}. + * Note: Otherwise it is null. + */ + protected void onViewCreated(final Bundle savedInstanceState) { + // empty default implementation + } + + /** + * Called after the view and the toolbar has been created. + */ + protected final void setUpView() { + // set GUI + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.help, menu); + return true; + } + + /** + * Use this method to handle menu actions other than home and about. + * + * @param itemId the menu item id + * @return true if action has been handled + */ + protected boolean onOptionsItemSelected(final int itemId) { + // Overwrite when using menu other than R.menu.help + return false; + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + final int id = item.getItemId(); + switch (id) { + case android.R.id.home: + onBackPressed(); + break; + case R.id.action_about: + final AppHelpFragment fragment = AppHelpFragment.getInstance(getAboutTextId()); + fragment.show(getSupportFragmentManager(), "help_fragment"); + break; + default: + return onOptionsItemSelected(id); + } + return true; + } + + /** + * Called when user press ADD DEVICE button. See layout files -> onClick attribute. + */ + public void onAddDeviceClicked(final View view) { + if (isBLEEnabled()) { + showDeviceScanningDialog(getFilterUUID()); + } else { + showBLEDialog(); + } + } + + /** + * Returns the title resource id that will be used to create logger session. If 0 is returned (default) logger will not be used. + * + * @return the title resource id + */ + protected int getLoggerProfileTitle() { + return 0; + } + + /** + * This method may return the local log content provider authority if local log sessions are supported. + * + * @return local log session content provider URI + */ + protected Uri getLocalAuthorityLogger() { + return null; + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + final int titleId = getLoggerProfileTitle(); + ILogSession logSession = null; + if (titleId > 0) { + logSession = Logger.newSession(getApplicationContext(), getString(titleId), device.getAddress(), name); + // If nRF Logger is not installed we may want to use local logger + if (logSession == null && getLocalAuthorityLogger() != null) { + logSession = LocalLogSession.newSession(getApplicationContext(), getLocalAuthorityLogger(), device.getAddress(), name); + } + } + + mService.connect(device, logSession); + } + + @Override + public void onDialogCanceled() { + // do nothing + } + + @Override + public void onDeviceConnecting(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onDeviceDisconnecting(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onLinkLossOccurred(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // empty default implementation + } + + @Override + public void onDeviceReady(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBondingRequired(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBonded(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onBondingFailed(final BluetoothDevice device) { + // empty default implementation + } + + @Override + public void onDeviceNotSupported(final BluetoothDevice device) { + showToast(R.string.not_supported); + } + + @Override + public final boolean shouldEnableBatteryLevelNotifications(final BluetoothDevice device) { + // This method will never be called. + // Please see BleMulticonnectProfileService#shouldEnableBatteryLevelNotifications(BluetoothDevice) instead. + throw new UnsupportedOperationException("This method should not be called"); + } + + @Override + public void onBatteryValueReceived(final BluetoothDevice device, final int value) { + // empty default implementation + } + + @Override + public void onError(final BluetoothDevice device, final String message, final int errorCode) { + DebugLogger.e(TAG, "Error occurred: " + message + ", error code: " + errorCode); + showToast(message + " (" + errorCode + ")"); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param message a message to be shown + */ + protected void showToast(final String message) { + runOnUiThread(() -> Toast.makeText(BleMulticonnectProfileServiceReadyActivity.this, message, Toast.LENGTH_LONG).show()); + } + + /** + * Shows a message as a Toast notification. This method is thread safe, you can call it from any thread + * + * @param messageResId an resource id of the message to be shown + */ + protected void showToast(final int messageResId) { + runOnUiThread(() -> Toast.makeText(BleMulticonnectProfileServiceReadyActivity.this, messageResId, Toast.LENGTH_SHORT).show()); + } + + /** + * Returns the string resource id that will be shown in About box + * + * @return the about resource id + */ + protected abstract int getAboutTextId(); + + /** + * The UUID filter is used to filter out available devices that does not have such UUID in their advertisement packet. See also: + * {@link #isChangingConfigurations()}. + * + * @return the required UUID or null + */ + protected abstract UUID getFilterUUID(); + + /** + * Returns unmodifiable list of managed devices. Managed device is a device the was selected on ScannerFragment until it's removed from the managed list. + * It does not have to be connected at that moment. + * @return unmodifiable list of managed devices + */ + protected List getManagedDevices() { + return Collections.unmodifiableList(mManagedDevices); + } + + /** + * Returns true if the device is connected. Services may not have been discovered yet. + * @param device the device to check if it's connected + */ + protected boolean isDeviceConnected(final BluetoothDevice device) { + return mService != null && mService.isConnected(device); + } + + /** + * Shows the scanner fragment. + * + * @param filter the UUID filter used to filter out available devices. The fragment will always show all bonded devices as there is no information about their + * services + * @see #getFilterUUID() + */ + private void showDeviceScanningDialog(final UUID filter) { + final ScannerFragment dialog = ScannerFragment.getInstance(filter); + dialog.show(getSupportFragmentManager(), "scan_fragment"); + } + + private void ensureBLESupported() { + if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { + Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show(); + finish(); + } + } + + protected boolean isBLEEnabled() { + final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); + final BluetoothAdapter adapter = bluetoothManager.getAdapter(); + return adapter != null && adapter.isEnabled(); + } + + protected void showBLEDialog() { + final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); + startActivityForResult(enableIntent, REQUEST_ENABLE_BT); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/IDeviceLogger.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/IDeviceLogger.java new file mode 100644 index 0000000..59d6d59 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/IDeviceLogger.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.profile.multiconnect; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.StringRes; + +public interface IDeviceLogger { + /** + * Logs the given message with given log level into the device's log session. + * @param device the target device + * @param level the log level + * @param message the message to be logged + */ + void log(final BluetoothDevice device, final int level, final String message); + + /** + * Logs the given message with given log level into the device's log session. + * @param device the target device + * @param level the log level + * @param messageRes string resource id + * @param params additional (optional) parameters used to fill the message + */ + void log(final BluetoothDevice device, final int level, @StringRes final int messageRes, final Object... params); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/DeviceAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/DeviceAdapter.java new file mode 100644 index 0000000..c41538b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/DeviceAdapter.java @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2016, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageButton; +import android.widget.ProgressBar; +import android.widget.TextView; + +import java.util.List; + +import no.nordicsemi.android.nrftoolbox.R; + +public class DeviceAdapter extends RecyclerView.Adapter { + private final ProximityService.ProximityBinder mService; + private final List mDevices; + + DeviceAdapter(final ProximityService.ProximityBinder binder) { + mService = binder; + mDevices = mService.getManagedDevices(); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) { + final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_feature_proximity_item, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { + holder.bind(mDevices.get(position)); + } + + @Override + public int getItemCount() { + return mDevices.size(); + } + + public void onDeviceAdded(final BluetoothDevice device) { + final int position = mDevices.indexOf(device); + if (position == -1) { + notifyItemInserted(mDevices.size() - 1); + } else { + // This may happen when Bluetooth adapter was switched off and on again + // while there were devices on the list. + notifyItemChanged(position); + } + } + + public void onDeviceRemoved(final BluetoothDevice device) { + notifyDataSetChanged(); // we don't have position of the removed device here + } + + public void onDeviceStateChanged(final BluetoothDevice device) { + final int position = mDevices.indexOf(device); + if (position >= 0) + notifyItemChanged(position); + } + + public void onBatteryValueReceived(final BluetoothDevice device) { + final int position = mDevices.indexOf(device); + if (position >= 0) + notifyItemChanged(position); + } + + class ViewHolder extends RecyclerView.ViewHolder { + private TextView nameView; + private TextView addressView; + private TextView batteryView; + private ImageButton actionButton; + private ProgressBar progress; + + ViewHolder(final View itemView) { + super(itemView); + + nameView = itemView.findViewById(R.id.name); + addressView = itemView.findViewById(R.id.address); + batteryView = itemView.findViewById(R.id.battery); + actionButton = itemView.findViewById(R.id.action_find_silent); + progress = itemView.findViewById(R.id.progress); + + // Configure FIND / SILENT button + actionButton.setOnClickListener(v -> { + final int position = getAdapterPosition(); + final BluetoothDevice device = mDevices.get(position); + mService.toggleImmediateAlert(device); + }); + + // Configure Disconnect button + itemView.findViewById(R.id.action_disconnect).setOnClickListener(v -> { + final int position = getAdapterPosition(); + final BluetoothDevice device = mDevices.get(position); + mService.disconnect(device); + // The device might have not been connected, so there will be no callback + onDeviceRemoved(device); + }); + } + + private void bind(final BluetoothDevice device) { + final boolean ready = mService.isReady(device); + + String name = device.getName(); + if (TextUtils.isEmpty(name)) + name = nameView.getResources().getString(R.string.proximity_default_device_name); + nameView.setText(name); + addressView.setText(device.getAddress()); + + final boolean on = mService.isImmediateAlertOn(device); + actionButton.setImageResource(on ? R.drawable.ic_stat_notify_proximity_silent : R.drawable.ic_stat_notify_proximity_find); + actionButton.setVisibility(ready ? View.VISIBLE : View.GONE); + progress.setVisibility(ready ? View.GONE : View.VISIBLE); + + final Integer batteryValue = mService.getBatteryLevel(device); + if (batteryValue != null) { + batteryView.getCompoundDrawables()[0 /*left*/].setLevel(batteryValue); + batteryView.setVisibility(View.VISIBLE); + batteryView.setText(batteryView.getResources().getString(R.string.battery, batteryValue)); + batteryView.setAlpha(ready ? 1.0f : 0.5f); + } else { + batteryView.setVisibility(View.GONE); + } + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/LinkLossFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/LinkLossFragment.java new file mode 100644 index 0000000..23f0450 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/LinkLossFragment.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.app.Dialog; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.appcompat.app.AlertDialog; + +import no.nordicsemi.android.nrftoolbox.R; + +public class LinkLossFragment extends DialogFragment { + private static final String ARG_NAME = "name"; + + private String mName; + + public static LinkLossFragment getInstance(String name) { + final LinkLossFragment fragment = new LinkLossFragment(); + + final Bundle args = new Bundle(); + args.putString(ARG_NAME, name); + fragment.setArguments(args); + + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mName = getArguments().getString(ARG_NAME); + } + + @NonNull + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + return new AlertDialog.Builder(requireContext()) + .setTitle(getString(R.string.app_name)) + .setMessage(getString(R.string.proximity_notification_link_loss_alert, mName)) + .setPositiveButton(R.string.ok, null) + .create(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityActivity.java new file mode 100644 index 0000000..bab1d05 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityActivity.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.multiconnect.BleMulticonnectProfileService; +import no.nordicsemi.android.nrftoolbox.profile.multiconnect.BleMulticonnectProfileServiceReadyActivity; +import no.nordicsemi.android.nrftoolbox.widget.DividerItemDecoration; + +public class ProximityActivity extends BleMulticonnectProfileServiceReadyActivity { + private RecyclerView mDevicesView; + private DeviceAdapter mAdapter; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_proximity); + setGUI(); + } + + @Override + protected void onInitialize(final Bundle savedInstanceState) { + LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); + } + + private void setGUI() { + final RecyclerView recyclerView = mDevicesView = findViewById(android.R.id.list); + recyclerView.setLayoutManager(new LinearLayoutManager(this)); + recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.proximity_feature_title; + } + + @Override + protected void onServiceBound(final ProximityService.ProximityBinder binder) { + mDevicesView.setAdapter(mAdapter = new DeviceAdapter(binder)); + } + + @Override + protected void onServiceUnbound() { + mDevicesView.setAdapter(mAdapter = null); + } + + @Override + protected Class getServiceClass() { + return ProximityService.class; + } + + @Override + protected int getAboutTextId() { + return R.string.proximity_about_text; + } + + @Override + protected UUID getFilterUUID() { + return ProximityManager.LINK_LOSS_SERVICE_UUID; + } + + @Override + public void onDeviceConnecting(final BluetoothDevice device) { + if (mAdapter != null) + mAdapter.onDeviceAdded(device); + } + + @Override + public void onDeviceConnected(final BluetoothDevice device) { + if (mAdapter != null) + mAdapter.onDeviceStateChanged(device); + } + + @Override + public void onDeviceReady(final BluetoothDevice device) { + if (mAdapter != null) + mAdapter.onDeviceStateChanged(device); + } + + @Override + public void onDeviceDisconnecting(final BluetoothDevice device) { + if (mAdapter != null) + mAdapter.onDeviceStateChanged(device); + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + if (mAdapter != null) + mAdapter.onDeviceRemoved(device); + } + + @Override + public void onDeviceNotSupported(final BluetoothDevice device) { + super.onDeviceNotSupported(device); + if (mAdapter != null) + mAdapter.onDeviceRemoved(device); + } + + @Override + public void onLinkLossOccurred(final BluetoothDevice device) { + if (mAdapter != null) + mAdapter.onDeviceStateChanged(device); + + // The link loss may also be called when Bluetooth adapter was disabled + if (BluetoothAdapter.getDefaultAdapter().isEnabled()) + showLinkLossDialog(device.getName()); + } + + @SuppressWarnings("unused") + private void onBatteryLevelChanged(final BluetoothDevice device, final int batteryLevel) { + if (mAdapter != null) + mAdapter.onBatteryValueReceived(device); // Value will be obtained from the service + } + + @SuppressWarnings("unused") + private void onRemoteAlarmSwitched(final BluetoothDevice device, final boolean on) { + if (mAdapter != null) + mAdapter.onDeviceStateChanged(device); // Value will be obtained from the service + } + + private void showLinkLossDialog(final String name) { + try { + final LinkLossFragment dialog = LinkLossFragment.getInstance(name); + dialog.show(getSupportFragmentManager(), "scan_fragment"); + } catch (final Exception e) { + // the activity must have been destroyed + } + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(ProximityService.EXTRA_DEVICE); + + if (ProximityService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(ProximityService.EXTRA_BATTERY_LEVEL, 0); + // Update GUI + onBatteryLevelChanged(device, batteryLevel); + } else if (ProximityService.BROADCAST_ALARM_SWITCHED.equals(action)) { + final boolean on = intent.getBooleanExtra(ProximityService.EXTRA_ALARM_STATE, false); + // Update GUI + onRemoteAlarmSwitched(device, on); + } + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(ProximityService.BROADCAST_BATTERY_LEVEL); + intentFilter.addAction(ProximityService.BROADCAST_ALARM_SWITCHED); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManager.java new file mode 100644 index 0000000..315ebf6 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManager.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import android.util.Log; + +import java.util.UUID; + +import no.nordicsemi.android.ble.callback.FailCallback; +import no.nordicsemi.android.ble.common.data.alert.AlertLevelData; +import no.nordicsemi.android.ble.error.GattError; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.AlertLevelParser; + +@SuppressWarnings("WeakerAccess") +class ProximityManager extends BatteryManager { + /** Link Loss service UUID. */ + final static UUID LINK_LOSS_SERVICE_UUID = UUID.fromString("00001803-0000-1000-8000-00805f9b34fb"); + /** Immediate Alert service UUID. */ + private final static UUID IMMEDIATE_ALERT_SERVICE_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); + /** Alert Level characteristic UUID. */ + private static final UUID ALERT_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A06-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mAlertLevelCharacteristic, mLinkLossCharacteristic; + private boolean mAlertOn; + + ProximityManager(final Context context) { + super(context); + } + + @Override + protected boolean shouldAutoConnect() { + return true; + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving indication, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + writeCharacteristic(mLinkLossCharacteristic, AlertLevelData.highAlert()) + .done(device -> log(Log.INFO, "Link loss alert level set")) + .fail((device, status) -> log(Log.WARN, "Failed to set link loss level: " + status)) + .enqueue(); + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService llService = gatt.getService(LINK_LOSS_SERVICE_UUID); + if (llService != null) { + mLinkLossCharacteristic = llService.getCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID); + } + return mLinkLossCharacteristic != null; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + super.isOptionalServiceSupported(gatt); + final BluetoothGattService iaService = gatt.getService(IMMEDIATE_ALERT_SERVICE_UUID); + if (iaService != null) { + mAlertLevelCharacteristic = iaService.getCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID); + } + return mAlertLevelCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + mAlertLevelCharacteristic = null; + mLinkLossCharacteristic = null; + // Reset the alert flag + mAlertOn = false; + } + }; + + /** + * Toggles the immediate alert on the target device. + */ + public void toggleImmediateAlert() { + writeImmediateAlert(!mAlertOn); + } + + /** + * Writes the HIGH ALERT or NO ALERT command to the target device. + * + * @param on true to enable the alarm on proximity tag, false to disable it. + */ + public void writeImmediateAlert(final boolean on) { + if (!isConnected()) + return; + + writeCharacteristic(mAlertLevelCharacteristic, on ? AlertLevelData.highAlert() : AlertLevelData.noAlert()) + .before(device -> log(Log.VERBOSE, + on ? "Setting alarm to HIGH..." : "Disabling alarm...")) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + AlertLevelParser.parse(data) + "\" sent")) + .done(device -> { + mAlertOn = on; + mCallbacks.onRemoteAlarmSwitched(device, on); + }) + .fail((device, status) -> log(Log.WARN, + status == FailCallback.REASON_NULL_ATTRIBUTE ? + "Alert Level characteristic not found" : + GattError.parse(status))) + .enqueue(); + } + + /** + * Returns true if the alert has been enabled on the proximity tag, false otherwise. + */ + boolean isAlertEnabled() { + return mAlertOn; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManagerCallbacks.java new file mode 100644 index 0000000..9d2b867 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManagerCallbacks.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; + +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +interface ProximityManagerCallbacks extends BatteryManagerCallbacks { + // No additional methods + void onRemoteAlarmSwitched(@NonNull final BluetoothDevice device, final boolean on); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManager.java new file mode 100644 index 0000000..b381d3d --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManager.java @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; +import android.bluetooth.BluetoothGattServer; +import android.bluetooth.BluetoothGattServerCallback; +import android.bluetooth.BluetoothGattService; +import android.bluetooth.BluetoothManager; +import android.bluetooth.BluetoothProfile; +import android.content.Context; +import android.os.Handler; +import android.util.Log; + +import java.util.UUID; + +import no.nordicsemi.android.error.GattError; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.parser.AlertLevelParser; +import no.nordicsemi.android.nrftoolbox.profile.multiconnect.IDeviceLogger; +import no.nordicsemi.android.nrftoolbox.utility.ParserUtils; + +class ProximityServerManager { + private final String TAG = "ProximityServerManager"; + + /** Immediate Alert service UUID */ + final static UUID IMMEDIATE_ALERT_SERVICE_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb"); + /** Linkloss service UUID */ + final static UUID LINKLOSS_SERVICE_UUID = UUID.fromString("00001803-0000-1000-8000-00805f9b34fb"); + /** Alert Level characteristic UUID */ + private static final UUID ALERT_LEVEL_CHARACTERISTIC_UUID = UUID.fromString("00002A06-0000-1000-8000-00805f9b34fb"); + + private final static byte[] HIGH_ALERT = { 0x02 }; + private final static byte[] MILD_ALERT = { 0x01 }; + private final static byte[] NO_ALERT = { 0x00 }; + + private BluetoothGattServer mBluetoothGattServer; + private ProximityServerManagerCallbacks mCallbacks; + private IDeviceLogger mLogger; + private Handler mHandler; + private OnServerOpenCallback mOnServerOpenCallback; + private boolean mServerReady; + + public interface OnServerOpenCallback { + /** + * Method called when the GATT server was created and all services were added successfully. + */ + void onGattServerOpen(); + /** + * Method called when the GATT server failed to open and initialize services. + * -1 is returned when the server failed to start. + */ + void onGattServerFailed(final int error); + } + + ProximityServerManager(final ProximityServerManagerCallbacks callbacks) { + mHandler = new Handler(); + mCallbacks = callbacks; + } + + /** + * Sets the logger object. Logger is used to create logs in nRF Logger application. + * + * @param logger the logger object + */ + public void setLogger(final IDeviceLogger logger) { + mLogger = logger; + } + + /** + * Opens GATT server and creates 2 services: Link Loss Service and Immediate Alert Service. + * The callback is called when initialization is complete. + * + * @param context the context. + * @param callback optional callback notifying when all services has been added. + */ + public void openGattServer(final Context context, final OnServerOpenCallback callback) { + // Is the server already open? + if (mBluetoothGattServer != null) { + if (callback != null) + callback.onGattServerOpen(); + return; + } + + mOnServerOpenCallback = callback; + + final BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); + mBluetoothGattServer = manager.openGattServer(context, mGattServerCallbacks); + if (mBluetoothGattServer != null) { + // Start adding services one by one. The onServiceAdded method will be called when it completes. + addImmediateAlertService(); + } else { + if (callback != null) + callback.onGattServerFailed(-1); + mOnServerOpenCallback = null; + } + } + + /** + * Returns true if GATT server was opened and configured correctly. + * False if hasn't been opened, was closed, of failed to start. + */ + public boolean isServerReady() { + return mServerReady; + } + + /** + * Closes the GATT server. It will also disconnect all existing connections. + * If the service has already been closed, or hasn't been open, this method does nothing. + */ + public void closeGattServer() { + if (mBluetoothGattServer != null) { + mBluetoothGattServer.close(); + mBluetoothGattServer = null; + mOnServerOpenCallback = null; + mServerReady = false; + } + } + + /** + * This method notifies the Android that the Proximity profile will use the server connection + * to given device. If the server hasn't been open this method does nothing. + * The {@link #cancelConnection(BluetoothDevice)} method should be called when the connection + * is no longer used. + * + * @param device the target device. + */ + public void openConnection(final BluetoothDevice device) { + if (mBluetoothGattServer != null) { + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Creating server connection..."); + mLogger.log(device, LogContract.Log.Level.DEBUG, "server.connect(device, autoConnect = true)"); + mBluetoothGattServer.connect(device, true); // In proximity the autoConnect is true + } + } + + /** + * Cancels the connection to the given device. This notifies Android that this profile will + * no longer use this connection and it can be disconnected. In practice, this method does + * not disconnect, so if the remote device decides still to use the phone's GATT server it + * will be able to do so. + *

+ * This bug/feature can be tested using a proximity tag that does not release its connection + * when it got disconnected: + *

    + *
  1. Connect to your Proximity Tag.
  2. + *
  3. Verify that the bidirectional connection works - test the FIND ME button in + * nRF Toolbox and the FIND PHONE button on the tag.
  4. + *
  5. Disconnect from the tag
  6. + *
  7. When the device disappear from the list of devices click the FIND PHONE button on + * the tag. Your phone should still trigger an alarm, as the connection tag->phone + * is still active.
  8. + *
+ * In order to avoid this issue make sure that your tag disconnects gently from phone when it + * got disconnected itself. + * + * @param device the device that will no longer be used. + */ + public void cancelConnection(final BluetoothDevice device) { + if (mBluetoothGattServer != null) { + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Cancelling server connection..."); + mLogger.log(device, LogContract.Log.Level.DEBUG, "server.cancelConnection(device)"); + mBluetoothGattServer.cancelConnection(device); + } + } + + private void addImmediateAlertService() { + /* + * This method must be called in UI thread. It works fine on Nexus devices but if called + * from other thread (e.g. from onServiceAdded in gatt server callback) it hangs the app. + */ + final BluetoothGattCharacteristic alertLevel = + new BluetoothGattCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID, + BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, + BluetoothGattCharacteristic.PERMISSION_WRITE); + alertLevel.setValue(NO_ALERT); + final BluetoothGattService immediateAlertService = + new BluetoothGattService(IMMEDIATE_ALERT_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); + immediateAlertService.addCharacteristic(alertLevel); + mBluetoothGattServer.addService(immediateAlertService); + } + + private void addLinkLossService() { + /* + * This method must be called in UI thread. It works fine on Nexus devices but if called + * from other thread (e.g. from onServiceAdded in gatt server callback) it hangs the app. + */ + final BluetoothGattCharacteristic linkLossAlertLevel = + new BluetoothGattCharacteristic(ALERT_LEVEL_CHARACTERISTIC_UUID, + BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ, + BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ); + linkLossAlertLevel.setValue(HIGH_ALERT); + final BluetoothGattService linkLossService = + new BluetoothGattService(LINKLOSS_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); + linkLossService.addCharacteristic(linkLossAlertLevel); + mBluetoothGattServer.addService(linkLossService); + } + + private final BluetoothGattServerCallback mGattServerCallbacks = new BluetoothGattServerCallback() { + @Override + public void onServiceAdded(final int status, final BluetoothGattService service) { + if (status == BluetoothGatt.GATT_SUCCESS) { + // Adding another service from callback thread fails on Samsung S4 with Android 4.3 + mHandler.post(() -> { + if (IMMEDIATE_ALERT_SERVICE_UUID.equals(service.getUuid())) { + addLinkLossService(); + } else { + mServerReady = true; + // Both services has been added + if (mOnServerOpenCallback != null) + mOnServerOpenCallback.onGattServerOpen(); + mOnServerOpenCallback = null; + } + }); + } else { + Log.e(TAG, "GATT Server failed to add service, status: " + status); + if (mOnServerOpenCallback != null) + mOnServerOpenCallback.onGattServerFailed(status); + mOnServerOpenCallback = null; + } + } + + @Override + public void onConnectionStateChange(final BluetoothDevice device, final int status, final int newState) { + mLogger.log(device, LogContract.Log.Level.DEBUG, + "[Server callback] Connection state changed with status: " + status + + " and new state: " + newState + " (" + stateToString(newState) + ")"); + if (status == BluetoothGatt.GATT_SUCCESS) { + if (newState == BluetoothGatt.STATE_CONNECTED) { + mLogger.log(device, LogContract.Log.Level.INFO, + "[Server] Device with address " + device.getAddress() + " connected"); + } else { + mLogger.log(device, LogContract.Log.Level.INFO, "[Server] Device disconnected"); + mCallbacks.onAlarmStopped(device); + } + } else { + mLogger.log(device, LogContract.Log.Level.ERROR, "[Server] Error " + status + + " (0x" + Integer.toHexString(status) + "): " + GattError.parseConnectionError(status)); + } + } + + @Override + public void onCharacteristicReadRequest(final BluetoothDevice device, final int requestId, + final int offset, final BluetoothGattCharacteristic characteristic) { + mLogger.log(device, LogContract.Log.Level.DEBUG, + "[Server callback] Read request for characteristic " + characteristic.getUuid() + + " (requestId=" + requestId + ", offset=" + offset + ")"); + mLogger.log(device, LogContract.Log.Level.INFO, + "[Server] READ request for characteristic " + characteristic.getUuid() + " received"); + + byte[] value = characteristic.getValue(); + if (value != null && offset > 0) { + byte[] offsetValue = new byte[value.length - offset]; + System.arraycopy(value, offset, offsetValue, 0, offsetValue.length); + value = offsetValue; + } + if (value != null) { + mLogger.log(device, LogContract.Log.Level.DEBUG, + "server.sendResponse(GATT_SUCCESS, value=" + ParserUtils.parseDebug(value) + ")"); + } else { + mLogger.log(device, LogContract.Log.Level.DEBUG, "server.sendResponse(GATT_SUCCESS, value=null)"); + } + mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value); + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Response sent"); + } + + @Override + public void onCharacteristicWriteRequest(final BluetoothDevice device, final int requestId, + final BluetoothGattCharacteristic characteristic, final boolean preparedWrite, + final boolean responseNeeded, final int offset, final byte[] value) { + mLogger.log(device, LogContract.Log.Level.DEBUG, "[Server callback] Write request to characteristic " + characteristic.getUuid() + + " (requestId=" + requestId + ", prepareWrite=" + preparedWrite + ", responseNeeded=" + responseNeeded + + ", offset=" + offset + ", value=" + ParserUtils.parseDebug(value) + ")"); + final String writeType = !responseNeeded ? "WRITE NO RESPONSE" : "WRITE COMMAND"; + mLogger.log(device, LogContract.Log.Level.INFO, "[Server] " + writeType + + " request for characteristic " + characteristic.getUuid() + " received, value: " + ParserUtils.parse(value)); + + if (offset == 0) { + characteristic.setValue(value); + } else { + final byte[] currentValue = characteristic.getValue(); + final byte[] newValue = new byte[currentValue.length + value.length]; + System.arraycopy(currentValue, 0, newValue, 0, currentValue.length); + System.arraycopy(value, 0, newValue, offset, value.length); + characteristic.setValue(newValue); + } + + if (!preparedWrite && value != null && value.length == 1) { // small validation + if (value[0] != NO_ALERT[0]) { + mLogger.log(device, LogContract.Log.Level.APPLICATION, + "[Server] Immediate alarm request received: " + AlertLevelParser.parse(characteristic)); + mCallbacks.onAlarmTriggered(device); + } else { + mLogger.log(device, LogContract.Log.Level.APPLICATION, + "[Server] Immediate alarm request received: OFF"); + mCallbacks.onAlarmStopped(device); + } + } + + mLogger.log(device, LogContract.Log.Level.DEBUG, "server.sendResponse(GATT_SUCCESS, offset=" + + offset + ", value=" + ParserUtils.parseDebug(value) + ")"); + mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null); + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Response sent"); + } + + @Override + public void onDescriptorReadRequest(final BluetoothDevice device, final int requestId, + final int offset, final BluetoothGattDescriptor descriptor) { + mLogger.log(device, LogContract.Log.Level.DEBUG, + "[Server callback] Write request to descriptor " + descriptor.getUuid() + " (requestId=" + requestId + ", offset=" + offset + ")"); + mLogger.log(device, LogContract.Log.Level.INFO, + "[Server] READ request for descriptor " + descriptor.getUuid() + " received"); + // This method is not supported + mLogger.log(device, LogContract.Log.Level.WARNING, "[Server] Operation not supported"); + mLogger.log(device, LogContract.Log.Level.DEBUG, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)"); + mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, offset, null); + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Response sent"); + } + + @Override + public void onDescriptorWriteRequest(final BluetoothDevice device, final int requestId, + final BluetoothGattDescriptor descriptor, final boolean preparedWrite, + final boolean responseNeeded, final int offset, final byte[] value) { + mLogger.log(device, LogContract.Log.Level.DEBUG, "[Server callback] Write request to descriptor " + descriptor.getUuid() + + " (requestId=" + requestId + ", prepareWrite=" + preparedWrite + ", responseNeeded=" + responseNeeded + + ", offset=" + offset + ", value=" + ParserUtils.parse(value) + ")"); + mLogger.log(device, LogContract.Log.Level.INFO, "[Server] READ request for descriptor " + descriptor.getUuid() + " received"); + // This method is not supported + mLogger.log(device, LogContract.Log.Level.WARNING, "[Server] Operation not supported"); + mLogger.log(device, LogContract.Log.Level.DEBUG, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)"); + mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, offset, null); + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Response sent"); + } + + @Override + public void onExecuteWrite(final BluetoothDevice device, final int requestId, final boolean execute) { + mLogger.log(device, LogContract.Log.Level.DEBUG, + "[Server callback] Execute write request (requestId=" + requestId + ", execute=" + execute + ")"); + // This method is not supported + mLogger.log(device, LogContract.Log.Level.WARNING, "[Server] Operation not supported"); + mLogger.log(device, LogContract.Log.Level.DEBUG, "[Server] server.sendResponse(GATT_REQUEST_NOT_SUPPORTED)"); + mBluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED, 0, null); + mLogger.log(device, LogContract.Log.Level.VERBOSE, "[Server] Response sent"); + } + }; + + /** + * Converts the connection state to String value. + * + * @param state the connection state. + * @return The state as String. + */ + private String stateToString(final int state) { + switch (state) { + case BluetoothProfile.STATE_CONNECTED: + return "CONNECTED"; + case BluetoothProfile.STATE_CONNECTING: + return "CONNECTING"; + case BluetoothProfile.STATE_DISCONNECTING: + return "DISCONNECTING"; + default: + return "DISCONNECTED"; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManagerCallbacks.java new file mode 100644 index 0000000..9270d33 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManagerCallbacks.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; + +public interface ProximityServerManagerCallbacks { + void onAlarmTriggered(@NonNull final BluetoothDevice device); + + void onAlarmStopped(@NonNull final BluetoothDevice device); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityService.java new file mode 100644 index 0000000..b9a195e --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityService.java @@ -0,0 +1,570 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.proximity; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.core.app.NotificationManagerCompat; +import androidx.core.content.ContextCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.text.TextUtils; +import android.util.Log; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; +import no.nordicsemi.android.nrftoolbox.profile.multiconnect.BleMulticonnectProfileService; + +public class ProximityService extends BleMulticonnectProfileService implements ProximityManagerCallbacks, ProximityServerManagerCallbacks { + @SuppressWarnings("unused") + private static final String TAG = "ProximityService"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + + public static final String BROADCAST_ALARM_SWITCHED = "no.nordicsemi.android.nrftoolbox.BROADCAST_ALARM_SWITCHED"; + public static final String EXTRA_ALARM_STATE = "no.nordicsemi.android.nrftoolbox.EXTRA_ALARM_STATE"; + + private final static String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.proximity.ACTION_DISCONNECT"; + private final static String ACTION_FIND = "no.nordicsemi.android.nrftoolbox.proximity.ACTION_FIND"; + private final static String ACTION_SILENT = "no.nordicsemi.android.nrftoolbox.proximity.ACTION_SILENT"; + + private final static String PROXIMITY_GROUP_ID = "proximity_connected_tags"; + private final static int NOTIFICATION_ID = 1000; + private final static int OPEN_ACTIVITY_REQ = 0; + private final static int DISCONNECT_REQ = 1; + private final static int FIND_REQ = 2; + private final static int SILENT_REQ = 3; + + private final ProximityBinder mBinder = new ProximityBinder(); + private ProximityServerManager mServerManager; + private MediaPlayer mMediaPlayer; + private int mOriginalVolume; + /** + * When a device starts an alarm on the phone it is added to this list. + * Alarm is disabled when this list is empty. + */ + private List mDevicesWithAlarm; + + private int mAttempt; + private final static int MAX_ATTEMPTS = 1; + + /** + * This local binder is an interface for the bonded activity to operate with the proximity + * sensor. + */ + public class ProximityBinder extends LocalBinder { + /** + * Toggles the Immediate Alert on given remote device. + * + * @param device the connected device. + */ + public void toggleImmediateAlert(final BluetoothDevice device) { + final ProximityManager manager = (ProximityManager) getBleManager(device); + manager.toggleImmediateAlert(); + } + + /** + * Returns the current alarm state on given device. This value is not read from the device, + * it's just the last value written to it (initially false). + * + * @param device the connected device. + * @return True if alarm has been enabled, false if disabled. + */ + public boolean isImmediateAlertOn(final BluetoothDevice device) { + final ProximityManager manager = (ProximityManager) getBleManager(device); + return manager.isAlertEnabled(); + } + + /** + * Returns the last received battery level value. + * + * @param device the device of which battery level should be returned. + * @return Battery value or null if no value was received or Battery Level characteristic + * was not found, or the device is disconnected. + */ + public Integer getBatteryLevel(final BluetoothDevice device) { + final ProximityManager manager = (ProximityManager) getBleManager(device); + return manager.getBatteryLevel(); + } + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return new ProximityManager(this); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing + * Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final BluetoothDevice device = intent.getParcelableExtra(EXTRA_DEVICE); + mBinder.log(device, LogContract.Log.Level.INFO, "[Notification] DISCONNECT action pressed"); + mBinder.disconnect(device); + } + }; + + /** + * This broadcast receiver listens for {@link #ACTION_FIND} or {@link #ACTION_SILENT} that may + * be fired by pressing Find me action button on the notification. + */ + private final BroadcastReceiver mToggleAlarmActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final BluetoothDevice device = intent.getParcelableExtra(EXTRA_DEVICE); + switch (intent.getAction()) { + case ACTION_FIND: + mBinder.log(device, LogContract.Log.Level.INFO, "[Notification] FIND action pressed"); + break; + case ACTION_SILENT: + mBinder.log(device, LogContract.Log.Level.INFO, "[Notification] SILENT action pressed"); + break; + } + mBinder.toggleImmediateAlert(device); + } + }; + + @Override + protected void onServiceCreated() { + mServerManager = new ProximityServerManager(this); + mServerManager.setLogger(mBinder); + + initializeAlarm(); + + registerReceiver(mDisconnectActionBroadcastReceiver, new IntentFilter(ACTION_DISCONNECT)); + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_FIND); + filter.addAction(ACTION_SILENT); + registerReceiver(mToggleAlarmActionBroadcastReceiver, filter); + } + + @Override + public void onServiceStopped() { + cancelNotifications(); + + // Close the GATT server. If it hasn't been opened this method does nothing + mServerManager.closeGattServer(); + + releaseAlarm(); + + unregisterReceiver(mDisconnectActionBroadcastReceiver); + unregisterReceiver(mToggleAlarmActionBroadcastReceiver); + + super.onServiceStopped(); + } + + @Override + protected void onBluetoothEnabled() { + mAttempt = 0; + getHandler().post(new Runnable() { + @Override + public void run() { + final Runnable that = this; + // Start the GATT Server only if Bluetooth is enabled + mServerManager.openGattServer(ProximityService.this, + new ProximityServerManager.OnServerOpenCallback() { + @Override + public void onGattServerOpen() { + // We are now ready to reconnect devices + ProximityService.super.onBluetoothEnabled(); + } + + @Override + public void onGattServerFailed(final int error) { + mServerManager.closeGattServer(); + + if (mAttempt < MAX_ATTEMPTS) { + mAttempt++; + getHandler().postDelayed(that, 2000); + } else { + showToast(getString(R.string.proximity_server_error, error)); + // GATT server failed to start, but we may connect as a client + ProximityService.super.onBluetoothEnabled(); + } + } + }); + } + }); + } + + @Override + protected void onBluetoothDisabled() { + super.onBluetoothDisabled(); + // Close the GATT server + mServerManager.closeGattServer(); + } + + @Override + protected void onRebind() { + // When the activity rebinds to the service, remove the notification + cancelNotifications(); + + // This method will read the Battery Level value from each connected device, if possible + // and then try to enable battery notifications (if it has NOTIFY property). + // If the Battery Level characteristic has only the NOTIFY property, it will only try to + // enable notifications. + for (final BluetoothDevice device : getManagedDevices()) { + final ProximityManager manager = (ProximityManager) getBleManager(device); + manager.readBatteryLevelCharacteristic(); + manager.enableBatteryLevelCharacteristicNotifications(); + } + } + + @Override + public void onUnbind() { + // When we are connected, but the application is not open, we are not really interested + // in battery level notifications. But we will still be receiving other values, if enabled. + for (final BluetoothDevice device : getManagedDevices()) { + final ProximityManager manager = (ProximityManager) getBleManager(device); + manager.disableBatteryLevelCharacteristicNotifications(); + } + + createBackgroundNotification(); + } + + @Override + public void onDeviceConnected(final BluetoothDevice device) { + super.onDeviceConnected(device); + + if (!mBound) { + createBackgroundNotification(); + } + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + super.onServicesDiscovered(device, optionalServicesFound); + mServerManager.openConnection(device); + } + + @Override + public void onLinkLossOccurred(final BluetoothDevice device) { + mServerManager.cancelConnection(device); + stopAlarm(device); + super.onLinkLossOccurred(device); + + if (!mBound) { + createBackgroundNotification(); + if (BluetoothAdapter.getDefaultAdapter().isEnabled()) + createLinkLossNotification(device); + else + cancelNotification(device); + } + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + mServerManager.cancelConnection(device); + stopAlarm(device); + super.onDeviceDisconnected(device); + + if (!mBound) { + cancelNotification(device); + createBackgroundNotification(); + } + } + + @Override + public void onAlarmTriggered(@NonNull final BluetoothDevice device) { + playAlarm(device); + } + + @Override + public void onAlarmStopped(@NonNull final BluetoothDevice device) { + stopAlarm(device); + } + + @Override + public void onRemoteAlarmSwitched(@NonNull final BluetoothDevice device, final boolean on) { + final Intent broadcast = new Intent(BROADCAST_ALARM_SWITCHED); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_ALARM_STATE, on); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + if (!mBound) { + createBackgroundNotification(); + } + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, device); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, batteryLevel); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + private void createBackgroundNotification() { + final List connectedDevices = getConnectedDevices(); + for (final BluetoothDevice device : connectedDevices) { + createNotificationForConnectedDevice(device); + } + createSummaryNotification(); + } + + private void createSummaryNotification() { + final NotificationCompat.Builder builder = getNotificationBuilder(); + builder.setColor(ContextCompat.getColor(this, R.color.actionBarColorDark)); + builder.setShowWhen(false).setDefaults(0); + // An ongoing notification will not be shown on Android Wear. + builder.setOngoing(true); + builder.setGroup(PROXIMITY_GROUP_ID).setGroupSummary(true); + builder.setContentTitle(getString(R.string.app_name)); + + final List managedDevices = getManagedDevices(); + final List connectedDevices = getConnectedDevices(); + if (connectedDevices.isEmpty()) { + // No connected devices + final int numberOfManagedDevices = managedDevices.size(); + if (numberOfManagedDevices == 1) { + final String name = getDeviceName(managedDevices.get(0)); + // We don't use plurals here, as we only have the default language and 'one' is not + // in every language (versions differ in %d or %s) and throw an exception in e.g. in Chinese. + builder.setContentText(getString(R.string.proximity_notification_text_nothing_connected_one_disconnected, name)); + } else { + builder.setContentText(getString(R.string.proximity_notification_text_nothing_connected_number_disconnected, numberOfManagedDevices)); + } + } else { + // There are some proximity tags connected + final StringBuilder text = new StringBuilder(); + + final int numberOfConnectedDevices = connectedDevices.size(); + if (numberOfConnectedDevices == 1) { + final String name = getDeviceName(connectedDevices.get(0)); + text.append(getString(R.string.proximity_notification_summary_text_name, name)); + } else { + text.append(getString(R.string.proximity_notification_summary_text_number, numberOfConnectedDevices)); + } + + // If there are some disconnected devices, also print them + final int numberOfDisconnectedDevices = managedDevices.size() - numberOfConnectedDevices; + if (numberOfDisconnectedDevices == 1) { + text.append(", "); + // Find the single disconnected device to get its name + for (final BluetoothDevice device : managedDevices) { + if (!isConnected(device)) { + final String name = getDeviceName(device); + text.append(getString(R.string.proximity_notification_text_nothing_connected_one_disconnected, name)); + break; + } + } + } else if (numberOfDisconnectedDevices > 1) { + text.append(", "); + // If there are more, just write number of them + text.append(getString(R.string.proximity_notification_text_nothing_connected_number_disconnected, numberOfDisconnectedDevices)); + } + text.append("."); + builder.setContentText(text); + } + + final Notification notification = builder.build(); + final NotificationManagerCompat nm = NotificationManagerCompat.from(this); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Creates the notification for given connected device. + * Adds 3 action buttons: DISCONNECT, FIND and SILENT which perform given action on the device. + */ + private void createNotificationForConnectedDevice(final BluetoothDevice device) { + final NotificationCompat.Builder builder = getNotificationBuilder(); + builder.setColor(ContextCompat.getColor(this, R.color.actionBarColorDark)); + builder.setGroup(PROXIMITY_GROUP_ID).setDefaults(0); + // An ongoing notification will not be shown on Android Wear. + builder.setOngoing(true); + builder.setContentTitle(getString(R.string.proximity_notification_text, getDeviceName(device))); + + // Add DISCONNECT action + final Intent disconnect = new Intent(ACTION_DISCONNECT); + disconnect.putExtra(EXTRA_DEVICE, device); + final PendingIntent disconnectAction = + PendingIntent.getBroadcast(this, DISCONNECT_REQ + device.hashCode(), + disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.proximity_action_disconnect), disconnectAction)); + // This will keep the same order of notification even after an action was clicked on one of them. + builder.setSortKey(getDeviceName(device) + device.getAddress()); + + // Add FIND or SILENT action + final ProximityManager manager = (ProximityManager) getBleManager(device); + if (manager.isAlertEnabled()) { + final Intent silentAllIntent = new Intent(ACTION_SILENT); + silentAllIntent.putExtra(EXTRA_DEVICE, device); + final PendingIntent silentAction = + PendingIntent.getBroadcast(this, SILENT_REQ + device.hashCode(), + silentAllIntent, PendingIntent.FLAG_UPDATE_CURRENT); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_stat_notify_proximity_silent, getString(R.string.proximity_action_silent), silentAction)); + } else { + final Intent findAllIntent = new Intent(ACTION_FIND); + findAllIntent.putExtra(EXTRA_DEVICE, device); + final PendingIntent findAction = + PendingIntent.getBroadcast(this, FIND_REQ + device.hashCode(), + findAllIntent, PendingIntent.FLAG_UPDATE_CURRENT); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_stat_notify_proximity_find, getString(R.string.proximity_action_find), findAction)); + } + + final Notification notification = builder.build(); + final NotificationManagerCompat nm = NotificationManagerCompat.from(this); + nm.notify(device.getAddress(), NOTIFICATION_ID, notification); + } + + /** + * Creates a notification showing information about a device that got disconnected. + */ + private void createLinkLossNotification(final BluetoothDevice device) { + final NotificationCompat.Builder builder = getNotificationBuilder(); + builder.setColor(ContextCompat.getColor(this, R.color.orange)); + + final Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); + // Make sure the sound is played even in DND mode + builder.setSound(notificationUri, AudioManager.STREAM_ALARM); + builder.setPriority(NotificationCompat.PRIORITY_HIGH); + builder.setCategory(NotificationCompat.CATEGORY_ALARM); + builder.setShowWhen(true); + // An ongoing notification would not be shown on Android Wear. + builder.setOngoing(false); + // This notification is to be shown not in a group + + final String name = getDeviceName(device); + builder.setContentTitle(getString(R.string.proximity_notification_link_loss_alert, name)); + builder.setTicker(getString(R.string.proximity_notification_link_loss_alert, name)); + + final Notification notification = builder.build(); + final NotificationManagerCompat nm = NotificationManagerCompat.from(this); + nm.notify(device.getAddress(), NOTIFICATION_ID, notification); + } + + private NotificationCompat.Builder getNotificationBuilder() { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, ProximityActivity.class); + + // Both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[] { parentIntent, targetIntent }, PendingIntent.FLAG_UPDATE_CURRENT); + + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.PROXIMITY_WARNINGS_CHANNEL); + builder.setContentIntent(pendingIntent).setAutoCancel(false); + builder.setSmallIcon(R.drawable.ic_stat_notify_proximity); + return builder; + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotifications() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + + final List managedDevices = getManagedDevices(); + for (final BluetoothDevice device : managedDevices) { + nm.cancel(device.getAddress(), NOTIFICATION_ID); + } + } + + /** + * Cancels the existing notification for given device. If there is no active notification this method does nothing + */ + private void cancelNotification(final BluetoothDevice device) { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(device.getAddress(), NOTIFICATION_ID); + } + + private void initializeAlarm() { + mDevicesWithAlarm = new LinkedList<>(); + mMediaPlayer = new MediaPlayer(); + mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); + mMediaPlayer.setLooping(true); + mMediaPlayer.setVolume(1.0f, 1.0f); + try { + mMediaPlayer.setDataSource(this, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)); + } catch (final IOException e) { + Log.e(TAG, "Initialize Alarm failed: ", e); + } + } + + private void releaseAlarm() { + mMediaPlayer.release(); + mMediaPlayer = null; + } + + private void playAlarm(final BluetoothDevice device) { + final boolean alarmPlaying = !mDevicesWithAlarm.isEmpty(); + if (!mDevicesWithAlarm.contains(device)) + mDevicesWithAlarm.add(device); + + if (!alarmPlaying) { + // Save the current alarm volume and set it to max + final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + mOriginalVolume = am.getStreamVolume(AudioManager.STREAM_ALARM); + am.setStreamVolume(AudioManager.STREAM_ALARM, am.getStreamMaxVolume(AudioManager.STREAM_ALARM), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); + try { + mMediaPlayer.prepare(); + mMediaPlayer.start(); + } catch (final IOException e) { + Log.e(TAG, "Prepare Alarm failed: ", e); + } + } + } + + private void stopAlarm(final BluetoothDevice device) { + mDevicesWithAlarm.remove(device); + if (mDevicesWithAlarm.isEmpty() && mMediaPlayer.isPlaying()) { + mMediaPlayer.stop(); + // Restore original volume + final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + am.setStreamVolume(AudioManager.STREAM_ALARM, mOriginalVolume, 0); + } + } + + private String getDeviceName(final BluetoothDevice device) { + String name = device.getName(); + if (TextUtils.isEmpty(name)) + name = getString(R.string.proximity_default_device_name); + return name; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCActivity.java new file mode 100644 index 0000000..2d052b0 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCActivity.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.rsc; + +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.view.Menu; +import android.widget.TextView; + +import java.util.Locale; +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; +import no.nordicsemi.android.nrftoolbox.rsc.settings.SettingsActivity; +import no.nordicsemi.android.nrftoolbox.rsc.settings.SettingsFragment; + +public class RSCActivity extends BleProfileServiceReadyActivity { + private TextView mSpeedView; + private TextView mSpeedUnitView; + private TextView mCadenceView; + private TextView mDistanceView; + private TextView mDistanceUnitView; + private TextView mTotalDistanceView; + private TextView mTotalDistanceUnitView; + private TextView mStridesCountView; + private TextView mActivityView; + private TextView mBatteryLevelView; + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_rsc); + setGui(); + } + + @Override + protected void onInitialize(final Bundle savedInstanceState) { + LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); + } + + private void setGui() { + mSpeedView = findViewById(R.id.speed); + mSpeedUnitView = findViewById(R.id.speed_unit); + mCadenceView = findViewById(R.id.cadence); + mDistanceView = findViewById(R.id.distance); + mDistanceUnitView = findViewById(R.id.distance_unit); + mTotalDistanceView = findViewById(R.id.total_distance); + mTotalDistanceUnitView = findViewById(R.id.total_distance_unit); + mStridesCountView = findViewById(R.id.strides); + mActivityView = findViewById(R.id.activity); + mBatteryLevelView = findViewById(R.id.battery); + } + + @Override + protected void onResume() { + super.onResume(); + setDefaultUI(); + } + + @Override + protected void setDefaultUI() { + mSpeedView.setText(R.string.not_available_value); + mCadenceView.setText(R.string.not_available_value); + mDistanceView.setText(R.string.not_available_value); + mTotalDistanceView.setText(R.string.not_available_value); + mStridesCountView.setText(R.string.not_available_value); + mActivityView.setText(R.string.not_available); + mBatteryLevelView.setText(R.string.not_available); + + setUnits(); + } + + private void setUnits() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_M_S: // [m/s] + mSpeedUnitView.setText(R.string.rsc_speed_unit_m_s); + mDistanceUnitView.setText(R.string.rsc_distance_unit_m); + mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_km); + break; + case SettingsFragment.SETTINGS_UNIT_KM_H: // [km/h] + mSpeedUnitView.setText(R.string.rsc_speed_unit_km_h); + mDistanceUnitView.setText(R.string.rsc_distance_unit_m); + mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_km); + break; + case SettingsFragment.SETTINGS_UNIT_MPH: // [mph] + mSpeedUnitView.setText(R.string.rsc_speed_unit_mph); + mDistanceUnitView.setText(R.string.rsc_distance_unit_yd); + mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_mile); + break; + } + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.rsc_feature_title; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.rsc_default_name; + } + + @Override + protected int getAboutTextId() { + return R.string.rsc_about_text; + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.settings_and_about, menu); + return true; + } + + @Override + protected boolean onOptionsItemSelected(final int itemId) { + switch (itemId) { + case R.id.action_settings: + final Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + break; + } + return true; + } + + @Override + protected Class getServiceClass() { + return RSCService.class; + } + + @Override + protected UUID getFilterUUID() { + return RSCManager.RUNNING_SPEED_AND_CADENCE_SERVICE_UUID; + } + + @Override + protected void onServiceBound(final RSCService.RSCBinder binder) { + // not used + } + + @Override + protected void onServiceUnbound() { + // not used + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // not used + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + mBatteryLevelView.setText(R.string.not_available); + } + + private void onMeasurementReceived(float speed, int cadence, long totalDistance, final boolean running) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_KM_H: + speed = speed * 3.6f; + // pass through intended + case SettingsFragment.SETTINGS_UNIT_M_S: + if (totalDistance == -1) { + mTotalDistanceView.setText(R.string.not_available); + mTotalDistanceUnitView.setText(null); + } else { + mTotalDistanceView.setText(String.format(Locale.US, "%.2f", totalDistance / 1000.0f)); // 1 km in m + mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_km); + } + break; + case SettingsFragment.SETTINGS_UNIT_MPH: + speed = speed * 2.2369f; + if (totalDistance == -1) { + mTotalDistanceView.setText(R.string.not_available); + mTotalDistanceUnitView.setText(null); + } else { + mTotalDistanceView.setText(String.format(Locale.US, "%.2f", totalDistance / 1609.31f)); // 1 mile in m + mTotalDistanceUnitView.setText(R.string.rsc_total_distance_unit_mile); + } + break; + } + + mSpeedView.setText(String.format(Locale.US, "%.1f", speed)); + mCadenceView.setText(String.format(Locale.US, "%d", cadence)); + mActivityView.setText(running ? R.string.rsc_running : R.string.rsc_walking); + } + + private void onStripesUpdate(final long distance, final int strides) { + if (distance == -1) { + mDistanceView.setText(R.string.not_available); + mDistanceUnitView.setText(R.string.rsc_distance_unit_m); + } else { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT))); + + switch (unit) { + case SettingsFragment.SETTINGS_UNIT_KM_H: + case SettingsFragment.SETTINGS_UNIT_M_S: + if (distance < 100000L) { // 1 km in cm + mDistanceView.setText(String.format(Locale.US, "%.1f", distance / 100.0f)); + mDistanceUnitView.setText(R.string.rsc_distance_unit_m); + } else { + mDistanceView.setText(String.format(Locale.US, "%.2f", distance / 100000.0f)); + mDistanceUnitView.setText(R.string.rsc_distance_unit_km); + } + break; + case SettingsFragment.SETTINGS_UNIT_MPH: + if (distance < 160931L) { // 1 mile in cm + mDistanceView.setText(String.format(Locale.US, "%.1f", distance / 91.4392f)); + mDistanceUnitView.setText(R.string.rsc_distance_unit_yd); + } else { + mDistanceView.setText(String.format(Locale.US, "%.2f", distance / 160931.23f)); + mDistanceUnitView.setText(R.string.rsc_distance_unit_mile); + } + break; + } + } + + mStridesCountView.setText(String.valueOf(strides)); + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + + if (RSCService.BROADCAST_RSC_MEASUREMENT.equals(action)) { + final float speed = intent.getFloatExtra(RSCService.EXTRA_SPEED, 0.0f); + final int cadence = intent.getIntExtra(RSCService.EXTRA_CADENCE, 0); + final long totalDistance = intent.getLongExtra(RSCService.EXTRA_TOTAL_DISTANCE, -1); + final boolean running = intent.getBooleanExtra(RSCService.EXTRA_ACTIVITY, false); + // Update GUI + onMeasurementReceived(speed, cadence, totalDistance, running); + } else if (RSCService.BROADCAST_STRIDES_UPDATE.equals(action)) { + final int strides = intent.getIntExtra(RSCService.EXTRA_STRIDES, 0); + final long distance = intent.getLongExtra(RSCService.EXTRA_DISTANCE, -1); + // Update GUI + onStripesUpdate(distance, strides); + } + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(RSCService.BROADCAST_RSC_MEASUREMENT); + intentFilter.addAction(RSCService.BROADCAST_STRIDES_UPDATE); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManager.java new file mode 100644 index 0000000..aeb7ba8 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManager.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.rsc; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import java.util.UUID; + +import no.nordicsemi.android.ble.common.callback.rsc.RunningSpeedAndCadenceMeasurementDataCallback; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.RSCMeasurementParser; + +public class RSCManager extends BatteryManager { + /** Running Speed and Cadence Measurement service UUID */ + public static final UUID RUNNING_SPEED_AND_CADENCE_SERVICE_UUID = UUID.fromString("00001814-0000-1000-8000-00805f9b34fb"); + /** Running Speed and Cadence Measurement characteristic UUID */ + private static final UUID RSC_MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00002A53-0000-1000-8000-00805f9b34fb"); + + private BluetoothGattCharacteristic mRSCMeasurementCharacteristic; + + RSCManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving indication, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + setNotificationCallback(mRSCMeasurementCharacteristic) + .with(new RunningSpeedAndCadenceMeasurementDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, "\"" + RSCMeasurementParser.parse(data) + "\" received"); + super.onDataReceived(device, data); + } + + @Override + public void onRSCMeasurementReceived(@NonNull final BluetoothDevice device, final boolean running, + final float instantaneousSpeed, final int instantaneousCadence, + @Nullable final Integer strideLength, + @Nullable final Long totalDistance) { + mCallbacks.onRSCMeasurementReceived(device, running, instantaneousSpeed, + instantaneousCadence, strideLength, totalDistance); + } + }); + enableNotifications(mRSCMeasurementCharacteristic).enqueue(); + } + + @Override + public boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(RUNNING_SPEED_AND_CADENCE_SERVICE_UUID); + if (service != null) { + mRSCMeasurementCharacteristic = service.getCharacteristic(RSC_MEASUREMENT_CHARACTERISTIC_UUID); + } + return mRSCMeasurementCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + mRSCMeasurementCharacteristic = null; + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManagerCallbacks.java new file mode 100644 index 0000000..1a06cd2 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManagerCallbacks.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.rsc; + +import no.nordicsemi.android.ble.common.profile.rsc.RunningSpeedAndCadenceMeasurementCallback; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; + +interface RSCManagerCallbacks extends BatteryManagerCallbacks, RunningSpeedAndCadenceMeasurementCallback { + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCService.java new file mode 100644 index 0000000..0448033 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCService.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.rsc; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Handler; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +public class RSCService extends BleProfileService implements RSCManagerCallbacks { + private static final String TAG = "RSCService"; + + public static final String BROADCAST_RSC_MEASUREMENT = "no.nordicsemi.android.nrftoolbox.rsc.BROADCAST_RSC_MEASUREMENT"; + public static final String EXTRA_SPEED = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_SPEED"; + public static final String EXTRA_CADENCE = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_CADENCE"; + public static final String EXTRA_STRIDE_LENGTH = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_STRIDE_LENGTH"; + public static final String EXTRA_TOTAL_DISTANCE = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_TOTAL_DISTANCE"; + public static final String EXTRA_ACTIVITY = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_ACTIVITY"; + + public static final String BROADCAST_STRIDES_UPDATE = "no.nordicsemi.android.nrftoolbox.rsc.BROADCAST_STRIDES_UPDATE"; + public static final String EXTRA_STRIDES = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_STRIDES"; + public static final String EXTRA_DISTANCE = "no.nordicsemi.android.nrftoolbox.rsc.EXTRA_DISTANCE"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + + private final static String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.rsc.ACTION_DISCONNECT"; + + private RSCManager mManager; + + /** The last value of a cadence */ + private float mCadence; + /** Trip distance in cm */ + private long mDistance; + /** Stride length in cm */ + private Integer mStrideLength; + /** Number of steps in the trip */ + private int mStepsNumber; + private boolean mTaskInProgress; + private final Handler mHandler = new Handler(); + + private final static int NOTIFICATION_ID = 200; + private final static int OPEN_ACTIVITY_REQ = 0; + private final static int DISCONNECT_REQ = 1; + + private final LocalBinder mBinder = new RSCBinder(); + + /** + * This local binder is an interface for the bound activity to operate with the RSC sensor. + */ + class RSCBinder extends LocalBinder { + // empty + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new RSCManager(this); + } + + @Override + public void onCreate() { + super.onCreate(); + + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + // when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + // when the activity rebinds to the service, remove the notification + cancelNotification(); + + if (isConnected()) { + // This method will read the Battery Level value, if possible and then try to enable battery notifications (if it has NOTIFY property). + // If the Battery Level characteristic has only the NOTIFY property, it will only try to enable notifications. + mManager.readBatteryLevelCharacteristic(); + } + } + + @Override + protected void onUnbind() { + // When we are connected, but the application is not open, we are not really interested in battery level notifications. + // But we will still be receiving other values, if enabled. + if (isConnected()) + mManager.disableBatteryLevelCharacteristicNotifications(); + + // when the activity closes we need to show the notification that user is connected to the sensor + createNotification(R.string.rsc_notification_connected_message, 0); + } + + private final Runnable mUpdateStridesTask = new Runnable() { + @Override + public void run() { + if (!isConnected()) + return; + + mStepsNumber++; + mDistance += mStrideLength; // [cm] + final Intent broadcast = new Intent(BROADCAST_STRIDES_UPDATE); + broadcast.putExtra(EXTRA_STRIDES, mStepsNumber); + broadcast.putExtra(EXTRA_DISTANCE, mDistance); + LocalBroadcastManager.getInstance(RSCService.this).sendBroadcast(broadcast); + + if (mCadence > 0) { + final long interval = (long) (1000.0f * 60.0f / mCadence); + mHandler.postDelayed(mUpdateStridesTask, interval); + } else { + mTaskInProgress = false; + } + } + }; + + @Override + public void onRSCMeasurementReceived(@NonNull final BluetoothDevice device, final boolean running, + final float instantaneousSpeed, final int instantaneousCadence, + @Nullable final Integer strideLength, + @Nullable final Long totalDistance) { + final Intent broadcast = new Intent(BROADCAST_RSC_MEASUREMENT); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_SPEED, instantaneousSpeed); + broadcast.putExtra(EXTRA_CADENCE, instantaneousCadence); + broadcast.putExtra(EXTRA_STRIDE_LENGTH, strideLength); + broadcast.putExtra(EXTRA_TOTAL_DISTANCE, totalDistance); + broadcast.putExtra(EXTRA_ACTIVITY, running); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + // Start strides counter if not in progress + mCadence = instantaneousCadence; + if (strideLength != null) { + mStrideLength = strideLength; + } + if (!mTaskInProgress && strideLength != null && instantaneousCadence > 0) { + mTaskInProgress = true; + + final long interval = (long) (1000.0f * 60.0f / mCadence); + mHandler.postDelayed(mUpdateStridesTask, interval); + } + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int value) { + final Intent broadcast = new Intent(BROADCAST_BATTERY_LEVEL); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_BATTERY_LEVEL, value); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * Creates the notification + * + * @param messageResId + * message resource id. The message must have one String parameter,
+ * f.e. <string name="name">%s is connected</string> + * @param defaults + * signals that will be used to notify the user + */ + private void createNotification(final int messageResId, final int defaults) { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, RSCActivity.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + // both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[] { parentIntent, targetIntent }, PendingIntent.FLAG_UPDATE_CURRENT); + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.CONNECTED_DEVICE_CHANNEL); + builder.setContentIntent(pendingIntent); + builder.setContentTitle(getString(R.string.app_name)).setContentText(getString(messageResId, getDeviceName())); + builder.setSmallIcon(R.drawable.ic_stat_notify_rsc); + builder.setShowWhen(defaults != 0).setDefaults(defaults).setAutoCancel(true).setOngoing(true); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.rsc_notification_action_disconnect), disconnectAction)); + + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + Logger.i(getLogSession(), "[Notification] Disconnect action pressed"); + if (isConnected()) + getBinder().disconnect(); + else + stopSelf(); + } + }; + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsActivity.java new file mode 100644 index 0000000..fb22c16 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsActivity.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.rsc.settings; + +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; + +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsActivity extends AppCompatActivity { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // Display the fragment as the main content. + getSupportFragmentManager().beginTransaction().replace(R.id.content, new SettingsFragment()).commit(); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsFragment.java new file mode 100644 index 0000000..367309b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsFragment.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.rsc.settings; + +import android.os.Bundle; +import android.preference.PreferenceFragment; + +import androidx.preference.PreferenceFragmentCompat; +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsFragment extends PreferenceFragmentCompat { + public static final String SETTINGS_UNIT = "settings_rsc_unit"; + public static final int SETTINGS_UNIT_M_S = 0; // [m/s] + public static final int SETTINGS_UNIT_KM_H = 1; // [m/s] + public static final int SETTINGS_UNIT_MPH = 2; // [m/s] + public static final int SETTINGS_UNIT_DEFAULT = SETTINGS_UNIT_KM_H; + + @Override + public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { + addPreferencesFromResource(R.xml.settings_rsc); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/DeviceListAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/DeviceListAdapter.java new file mode 100644 index 0000000..cae8572 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/DeviceListAdapter.java @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.scanner; + +import android.bluetooth.BluetoothDevice; +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; +import android.widget.TextView; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.support.v18.scanner.ScanResult; + +/** + * DeviceListAdapter class is list adapter for showing scanned Devices name, address and RSSI image based on RSSI values. + */ +public class DeviceListAdapter extends BaseAdapter { + private static final int TYPE_TITLE = 0; + private static final int TYPE_ITEM = 1; + private static final int TYPE_EMPTY = 2; + + private final ArrayList mListBondedValues = new ArrayList<>(); + private final ArrayList mListValues = new ArrayList<>(); + private final Context mContext; + + public DeviceListAdapter(final Context context) { + mContext = context; + } + + /** + * Sets a list of bonded devices. + * @param devices list of bonded devices. + */ + public void addBondedDevices(final Set devices) { + final List bondedDevices = mListBondedValues; + for (BluetoothDevice device : devices) { + bondedDevices.add(new ExtendedBluetoothDevice(device)); + } + notifyDataSetChanged(); + } + + /** + * Updates the list of not bonded devices. + * @param results list of results from the scanner + */ + public void update(final List results) { + for (final ScanResult result : results) { + final ExtendedBluetoothDevice device = findDevice(result); + if (device == null) { + mListValues.add(new ExtendedBluetoothDevice(result)); + } else { + device.name = result.getScanRecord() != null ? result.getScanRecord().getDeviceName() : null; + device.rssi = result.getRssi(); + } + } + notifyDataSetChanged(); + } + + private ExtendedBluetoothDevice findDevice(final ScanResult result) { + for (final ExtendedBluetoothDevice device : mListBondedValues) + if (device.matches(result)) + return device; + for (final ExtendedBluetoothDevice device : mListValues) + if (device.matches(result)) + return device; + return null; + } + + public void clearDevices() { + mListValues.clear(); + notifyDataSetChanged(); + } + + @Override + public int getCount() { + final int bondedCount = mListBondedValues.size() + 1; // 1 for the title + final int availableCount = mListValues.isEmpty() ? 2 : mListValues.size() + 1; // 1 for title, 1 for empty text + if (bondedCount == 1) + return availableCount; + return bondedCount + availableCount; + } + + @Override + public Object getItem(int position) { + final int bondedCount = mListBondedValues.size() + 1; // 1 for the title + if (mListBondedValues.isEmpty()) { + if (position == 0) + return R.string.scanner_subtitle_not_bonded; + else + return mListValues.get(position - 1); + } else { + if (position == 0) + return R.string.scanner_subtitle_bonded; + if (position < bondedCount) + return mListBondedValues.get(position - 1); + if (position == bondedCount) + return R.string.scanner_subtitle_not_bonded; + return mListValues.get(position - bondedCount - 1); + } + } + + @Override + public int getViewTypeCount() { + return 3; + } + + @Override + public boolean areAllItemsEnabled() { + return false; + } + + @Override + public boolean isEnabled(int position) { + return getItemViewType(position) == TYPE_ITEM; + } + + @Override + public int getItemViewType(int position) { + if (position == 0) + return TYPE_TITLE; + + if (!mListBondedValues.isEmpty() && position == mListBondedValues.size() + 1) + return TYPE_TITLE; + + if (position == getCount() - 1 && mListValues.isEmpty()) + return TYPE_EMPTY; + + return TYPE_ITEM; + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public View getView(int position, View oldView, ViewGroup parent) { + final LayoutInflater inflater = LayoutInflater.from(mContext); + final int type = getItemViewType(position); + + View view = oldView; + switch (type) { + case TYPE_EMPTY: + if (view == null) { + view = inflater.inflate(R.layout.device_list_empty, parent, false); + } + break; + case TYPE_TITLE: + if (view == null) { + view = inflater.inflate(R.layout.device_list_title, parent, false); + } + final TextView title = (TextView) view; + title.setText((Integer) getItem(position)); + break; + default: + if (view == null) { + view = inflater.inflate(R.layout.device_list_row, parent, false); + final ViewHolder holder = new ViewHolder(); + holder.name = view.findViewById(R.id.name); + holder.address = view.findViewById(R.id.address); + holder.rssi = view.findViewById(R.id.rssi); + view.setTag(holder); + } + + final ExtendedBluetoothDevice device = (ExtendedBluetoothDevice) getItem(position); + final ViewHolder holder = (ViewHolder) view.getTag(); + final String name = device.name; + holder.name.setText(name != null ? name : mContext.getString(R.string.not_available)); + holder.address.setText(device.device.getAddress()); + if (!device.isBonded || device.rssi != ExtendedBluetoothDevice.NO_RSSI) { + final int rssiPercent = (int) (100.0f * (127.0f + device.rssi) / (127.0f + 20.0f)); + holder.rssi.setImageLevel(rssiPercent); + holder.rssi.setVisibility(View.VISIBLE); + } else { + holder.rssi.setVisibility(View.GONE); + } + break; + } + + return view; + } + + private class ViewHolder { + private TextView name; + private TextView address; + private ImageView rssi; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ExtendedBluetoothDevice.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ExtendedBluetoothDevice.java new file mode 100644 index 0000000..7a248b5 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ExtendedBluetoothDevice.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.scanner; + +import android.bluetooth.BluetoothDevice; + +import no.nordicsemi.android.support.v18.scanner.ScanResult; + +public class ExtendedBluetoothDevice { + /* package */ static final int NO_RSSI = -1000; + public final BluetoothDevice device; + /** The name is not parsed by some Android devices, f.e. Sony Xperia Z1 with Android 4.3 (C6903). It needs to be parsed manually. */ + public String name; + public int rssi; + public boolean isBonded; + + public ExtendedBluetoothDevice(final ScanResult scanResult) { + this.device = scanResult.getDevice(); + this.name = scanResult.getScanRecord() != null ? scanResult.getScanRecord().getDeviceName() : null; + this.rssi = scanResult.getRssi(); + this.isBonded = false; + } + + public ExtendedBluetoothDevice(final BluetoothDevice device) { + this.device = device; + this.name = device.getName(); + this.rssi = NO_RSSI; + this.isBonded = true; + } + + public boolean matches(final ScanResult scanResult) { + return device.getAddress().equals(scanResult.getDevice().getAddress()); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ScannerFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ScannerFragment.java new file mode 100644 index 0000000..65727d2 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ScannerFragment.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.scanner; + +import android.Manifest; +import android.app.Dialog; +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.Context; +import android.content.DialogInterface; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.ParcelUuid; +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.fragment.app.DialogFragment; +import androidx.core.content.ContextCompat; +import androidx.appcompat.app.AlertDialog; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.Button; +import android.widget.ListView; +import android.widget.Toast; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat; +import no.nordicsemi.android.support.v18.scanner.ScanCallback; +import no.nordicsemi.android.support.v18.scanner.ScanFilter; +import no.nordicsemi.android.support.v18.scanner.ScanResult; +import no.nordicsemi.android.support.v18.scanner.ScanSettings; + +/** + * ScannerFragment class scan required BLE devices and shows them in a list. This class scans and filter + * devices with standard BLE Service UUID and devices with custom BLE Service UUID. It contains a + * list and a button to scan/cancel. There is a interface {@link OnDeviceSelectedListener} which is + * implemented by activity in order to receive selected device. The scanning will continue to scan + * for 5 seconds and then stop. + */ +public class ScannerFragment extends DialogFragment { + private final static String TAG = "ScannerFragment"; + + private final static String PARAM_UUID = "param_uuid"; + private final static long SCAN_DURATION = 5000; + + private final static int REQUEST_PERMISSION_REQ_CODE = 34; // any 8-bit number + + private BluetoothAdapter mBluetoothAdapter; + private OnDeviceSelectedListener mListener; + private DeviceListAdapter mAdapter; + private final Handler mHandler = new Handler(); + private Button mScanButton; + + private View mPermissionRationale; + + private ParcelUuid mUuid; + + private boolean mIsScanning = false; + + public static ScannerFragment getInstance(final UUID uuid) { + final ScannerFragment fragment = new ScannerFragment(); + + final Bundle args = new Bundle(); + if (uuid != null) + args.putParcelable(PARAM_UUID, new ParcelUuid(uuid)); + fragment.setArguments(args); + return fragment; + } + + /** + * Interface required to be implemented by activity. + */ + public interface OnDeviceSelectedListener { + /** + * Fired when user selected the device. + * + * @param device + * the device to connect to + * @param name + * the device name. Unfortunately on some devices {@link BluetoothDevice#getName()} + * always returns null, i.e. Sony Xperia Z1 (C6903) with Android 4.3. + * The name has to be parsed manually form the Advertisement packet. + */ + void onDeviceSelected(final BluetoothDevice device, final String name); + + /** + * Fired when scanner dialog has been cancelled without selecting a device. + */ + void onDialogCanceled(); + } + + /** + * This will make sure that {@link OnDeviceSelectedListener} interface is implemented by activity. + */ + @Override + public void onAttach(final Context context) { + super.onAttach(context); + try { + this.mListener = (OnDeviceSelectedListener) context; + } catch (final ClassCastException e) { + throw new ClassCastException(context.toString() + " must implement OnDeviceSelectedListener"); + } + } + + @Override + public void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + final Bundle args = getArguments(); + if (args != null && args.containsKey(PARAM_UUID)) { + mUuid = args.getParcelable(PARAM_UUID); + } + + final BluetoothManager manager = (BluetoothManager) requireContext().getSystemService(Context.BLUETOOTH_SERVICE); + if (manager != null) { + mBluetoothAdapter = manager.getAdapter(); + } + } + + @Override + public void onDestroyView() { + stopScan(); + super.onDestroyView(); + } + + @NonNull + @Override + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final AlertDialog.Builder builder = new AlertDialog.Builder(requireContext()); + final View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_device_selection, null); + final ListView listview = dialogView.findViewById(android.R.id.list); + + listview.setEmptyView(dialogView.findViewById(android.R.id.empty)); + listview.setAdapter(mAdapter = new DeviceListAdapter(getActivity())); + + builder.setTitle(R.string.scanner_title); + final AlertDialog dialog = builder.setView(dialogView).create(); + listview.setOnItemClickListener((parent, view, position, id) -> { + stopScan(); + dialog.dismiss(); + final ExtendedBluetoothDevice d = (ExtendedBluetoothDevice) mAdapter.getItem(position); + mListener.onDeviceSelected(d.device, d.name); + }); + + mPermissionRationale = dialogView.findViewById(R.id.permission_rationale); // this is not null only on API23+ + + mScanButton = dialogView.findViewById(R.id.action_cancel); + mScanButton.setOnClickListener(v -> { + if (v.getId() == R.id.action_cancel) { + if (mIsScanning) { + dialog.cancel(); + } else { + startScan(); + } + } + }); + + addBoundDevices(); + if (savedInstanceState == null) + startScan(); + return dialog; + } + + @Override + public void onCancel(DialogInterface dialog) { + super.onCancel(dialog); + + mListener.onDialogCanceled(); + } + + @Override + public void onRequestPermissionsResult(final int requestCode, final @NonNull String[] permissions, final @NonNull int[] grantResults) { + switch (requestCode) { + case REQUEST_PERMISSION_REQ_CODE: { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + // We have been granted the Manifest.permission.ACCESS_COARSE_LOCATION permission. Now we may proceed with scanning. + startScan(); + } else { + mPermissionRationale.setVisibility(View.VISIBLE); + Toast.makeText(getActivity(), R.string.no_required_permission, Toast.LENGTH_SHORT).show(); + } + break; + } + } + } + + /** + * Scan for 5 seconds and then stop scanning when a BluetoothLE device is found then mLEScanCallback + * is activated This will perform regular scan for custom BLE Service UUID and then filter out. + * using class ScannerServiceParser + */ + private void startScan() { + // Since Android 6.0 we need to obtain either Manifest.permission.ACCESS_COARSE_LOCATION or Manifest.permission.ACCESS_FINE_LOCATION to be able to scan for + // Bluetooth LE devices. This is related to beacons as proximity devices. + // On API older than Marshmallow the following code does nothing. + if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // When user pressed Deny and still wants to use this functionality, show the rationale + if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) && mPermissionRationale.getVisibility() == View.GONE) { + mPermissionRationale.setVisibility(View.VISIBLE); + return; + } + + requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSION_REQ_CODE); + return; + } + + // Hide the rationale message, we don't need it anymore. + if (mPermissionRationale != null) + mPermissionRationale.setVisibility(View.GONE); + + mAdapter.clearDevices(); + mScanButton.setText(R.string.scanner_action_cancel); + + final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner(); + final ScanSettings settings = new ScanSettings.Builder() + .setLegacy(false) + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(1000).setUseHardwareBatchingIfSupported(false).build(); + final List filters = new ArrayList<>(); + filters.add(new ScanFilter.Builder().setServiceUuid(mUuid).build()); + scanner.startScan(filters, settings, scanCallback); + + mIsScanning = true; + mHandler.postDelayed(() -> { + if (mIsScanning) { + stopScan(); + } + }, SCAN_DURATION); + } + + /** + * Stop scan if user tap Cancel button + */ + private void stopScan() { + if (mIsScanning) { + mScanButton.setText(R.string.scanner_action_scan); + + final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner(); + scanner.stopScan(scanCallback); + + mIsScanning = false; + } + } + + private ScanCallback scanCallback = new ScanCallback() { + @Override + public void onScanResult(final int callbackType, final ScanResult result) { + // do nothing + } + + @Override + public void onBatchScanResults(final List results) { + mAdapter.update(results); + } + + @Override + public void onScanFailed(final int errorCode) { + // should never be called + } + }; + + private void addBoundDevices() { + final Set devices = mBluetoothAdapter.getBondedDevices(); + mAdapter.addBondedDevices(devices); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/Readme.txt b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/Readme.txt new file mode 100644 index 0000000..aa3ffa4 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/Readme.txt @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + + nRF Toolbox demonstrates how to implement the Bluetooth Smart features in an Android application. + It consists of number of profiles, like Heart Rate, Blood Pressure etc. that may be use as is to communicate with real devices. + They use the Bluetooth SIG adopted profiles, that may be found here: https://developer.bluetooth.org/gatt/profiles/Pages/ProfilesHome.aspx + + The Template Profile has been created to give a quick start with implementing proprietary services. Just start modifying 4 classes inside + the template package to implement features you need. + + Below you will find a short step-by-step tutorial: + + 1. The template consists of the following files: + - TemplateActivity - the main class that is responsible for managing the view of your profile + - TemplateService - the service that is started whenever you connect to a device. I handles the Bluetooth Smart communication using the... + - TemplateManager - the manager that handles all the BLE logic required to communicate with the device. The TemplateManager derives from + the BleManager which handles most of the event itself and propagates the data-relevant to deriving class. You don't + have to, or even shouldn't modify the BleManager (unless you want to change the default behaviour). + - TemplateManagerCallbacks - the interface with a list of callbacks that the TemplateManager can call. Each method is usually related to one + BLE event, e.g. receiving a new value of the characteristic.\ + - TemplateParser - an optional class in the .parser package that is responsible for converting the characteristic value to String. + This is used only for debugging. The String returned by the parse(..) method is then logged into the nRF Logger application + (if such installed). + - /settings/SettingsActivity and /settings/SettingsFragment - classes used to present user preferences. A stub implementation in the template. + - /res/layout/activity_feature_template.xml - the layout file for the TemplateActivity + - /res/values/strings_template.xml - a set of strings used in the layout file + - /res/xml/settings/template.xml - the user settings configuration + - /res/drawable/(x)hdpi/ic_template_feature.png - the template profile icon (HDPI, XHDPI). Please, keep the files size. + - /res/drawable/(x)hdpi/ic_stat_notify_template - the icon that is used in the notification + +2. The communication between the components goes as follows: + - User clicks the CONNECT button and selects a target device on TemplateActivity. + - The base class of the TemplateActivity starts the service given by getServiceClass() method. + - The service starts and initializes the TemplateManager. TemplateActivity binds to the service and is being given the TemplateBinder object (the service API) as a result. + - The manager connects to the device using Bluetooth Smart and discovers its services. + - The manager initializes the device. Initialization is done using the list of actions given by the initGatt(..) method in the TemplateManager. + Initialization usually contains enabling notifications, writing some initial values etc. + - When initialization is complete the manager calls the onDeviceReady() callback. + - The service sends the BROADCAST_DEVICE_READY broadcast to the activity. Communication from the Service to the Activity is always done using the LocalBroadcastManager broadcasts. + - The base class of the TemplateActivity listens to the broadcasts and calls appropriate methods. + + - When a custom event occurs, for example a notification is received, the manager parses the incoming data and calls the proper callback. + - The callback implementation in the TemplateService sends a broadcast message with values given in parameters. + - The TemplateActivity, which had registered a broadcast receiver before, listens to the broadcasts, reads the values and present them to users. + + - Communication Activity->Service is done using the API in the TemplateBinder. You may find the example of how to use it in the ProximityActivity. + +3. Please read the files listed above and the TODO messages for more information what to modify in the files. + +4. Remember to add your activities and the service in the AndroidManifest.xml file. The nRF Toolbox lists all activities with the following intent filter: + + + + + +5. Feel free to rename the nRF Toolbox application (/res/values/strings.xml ->app_name), change the toolbar colors (/res/values/color.xml -> actionBarColor, actionBarColorDark). + In order to remove unused profiles from the main FeaturesActivity just comment out their intent-filter tags in the AndroidManifest.xml file. diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateActivity.java new file mode 100644 index 0000000..60778ce --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateActivity.java @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.template; + +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.view.Menu; +import android.widget.EditText; +import android.widget.Switch; +import android.widget.TextView; + + +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; +import no.nordicsemi.android.nrftoolbox.template.settings.SettingsActivity; + + +/** + * Modify the Template Activity to match your needs. + */ +public class TemplateActivity extends BleProfileServiceReadyActivity { + @SuppressWarnings("unused") + private final String TAG = "TemplateActivity"; + + // TODO change view references to match your need + private TextView mValueView; + private TextView mHeatingStatusView; + private EditText mTimeValueView; + private EditText mTempValueView; + private Integer mSetTime ; + private Integer mSetTemp ; + private Switch mHeatingState ; + + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + // TODO modify the layout file(s). By default the activity shows only one field - the Heart Rate value as a sample + setContentView(R.layout.activity_feature_template); + setGUI(); + } + + private void setGUI() { + // TODO assign your views to fields + mValueView = findViewById(R.id.value); + mTimeValueView = findViewById(R.id.u_time); + mTempValueView = findViewById(R.id.u_temp); + mHeatingState = findViewById(R.id.heating_state); + mHeatingStatusView= findViewById(R.id.heating_status_text); + + mHeatingState.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + getService().heatingSwitch(1); + mSetTime = Integer.parseInt(mTimeValueView.getText().toString()); + getService().sendTimeDuration(mSetTime); + mSetTemp = Integer.parseInt(mTempValueView.getText().toString()); + getService().sendTemp(mSetTemp); + } + else { + getService().heatingSwitch(0); + } + mHeatingStatusView.setText(isChecked ? R.string.Heating_block_on : R.string.Heating_block_off); + }); + + + findViewById(R.id.time_set_button).setOnClickListener(v -> { + if (isDeviceConnected()) { + + mSetTime = Integer.parseInt(mTimeValueView.getText().toString()); + getService().sendTimeDuration(mSetTime); + } + }); + + findViewById(R.id.temp_set_button).setOnClickListener(v -> { + if (isDeviceConnected()) { + mSetTemp = Integer.parseInt(mTempValueView.getText().toString()); + getService().sendTemp(mSetTemp); + } + }); + } + + @Override + protected void onInitialize(final Bundle savedInstanceState) { + LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, makeIntentFilter()); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); + } + + @Override + protected void setDefaultUI() { + // TODO clear your UI + mValueView.setText(R.string.not_available_value); + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.template_feature_title; + } + + @Override + protected int getAboutTextId() { + return R.string.template_about_text; + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.settings_and_about, menu); + return true; + } + + @Override + protected boolean onOptionsItemSelected(final int itemId) { + switch (itemId) { + case R.id.action_settings: + final Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + break; + } + return true; + } + + @Override + protected int getDefaultDeviceName() { + return R.string.template_default_name; + } + + @Override + protected UUID getFilterUUID() { + // TODO this method may return the UUID of the service that is required to be in the advertisement packet of a device in order to be listed on the Scanner dialog. + // If null is returned no filtering is done. + return TemplateManager.SERVICE_UUID; + } + + @Override + protected Class getServiceClass() { + return TemplateService.class; + } + + @Override + protected void onServiceBound(final TemplateService.TemplateBinder binder) { + // not used + } + + @Override + protected void onServiceUnbound() { + // not used + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // this may notify user or show some views + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + } + + // Handling updates from the device + @SuppressWarnings("unused") + private void setValueOnView(@NonNull final BluetoothDevice device, final int value) { + // TODO assign the value to a view + mValueView.setText(String.valueOf(value)); + } + + @SuppressWarnings("unused") + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int value) { + +} + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(TemplateService.EXTRA_DEVICE); + + if (TemplateService.BROADCAST_TEMPLATE_MEASUREMENT.equals(action)) { + final int value = intent.getIntExtra(TemplateService.EXTRA_DATA, 0); + // Update GUI + setValueOnView(device, value); + } else if (TemplateService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(TemplateService.EXTRA_BATTERY_LEVEL, 0); + // Update GUI + onBatteryLevelChanged(device, batteryLevel); + } + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(TemplateService.BROADCAST_TEMPLATE_MEASUREMENT); + intentFilter.addAction(TemplateService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManager.java new file mode 100644 index 0000000..514e850 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManager.java @@ -0,0 +1,283 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.template; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; + +import android.util.Log; + +import java.util.UUID; + +import no.nordicsemi.android.ble.BleManager; +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.battery.BatteryManager; +import no.nordicsemi.android.nrftoolbox.parser.TemplateParser; +import no.nordicsemi.android.nrftoolbox.template.callback.TemplateDataCallback; + + +/** + * Modify to template manager to match your requirements. + * The TemplateManager extends {@link BatteryManager}, but it may easily extend {@link BleManager} + * instead if you don't need Battery Service support. If not, also modify the + * {@link TemplateManagerCallbacks} to extend {@link no.nordicsemi.android.ble.BleManagerCallbacks} + * and replace BatteryManagerGattCallback to BleManagerGattCallback in this class. + */ +public class TemplateManager extends BatteryManager { + // TODO Replace the services and characteristics below to match your device. + /** + * The service UUID. + */ + static final UUID SERVICE_UUID = UUID.fromString("00001500-1212-efde-1523-785feabcd123"); // Heart Rate service + /** + * A UUID of a characteristic with notify property. + */ + //private static final UUID MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00001501-1212-efde-1523-785feabcd123"); // Heart Rate Measurement + //private static final UUID TEMPERATURE_CHARACTERISTIC_UUID = UUID.fromString("00001501-1212-efde-1523-785feabcd123"); // Heart Rate Measurement + /** + * A UUID of a characteristic with read property. + */ + //private static final UUID READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001502-1212-efde-1523-785feabcd123"); // Body Sensor Location + private static final UUID TEMP_READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001501-1212-efde-1523-785feabcd123"); // Body Sensor Location + /** + * A UUID of a characteristic with write property. + */ + private static final UUID TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001502-1212-efde-1523-785feabcd123"); // Device Name + /** + * A UUID of a characteristic with write property. + */ + private static final UUID TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001503-1212-efde-1523-785feabcd123"); // Device Name + /** + * A UUID of a characteristic with write property. + */ + private static final UUID AMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001504-1212-efde-1523-785feabcd123"); // Device Name + + /** + * Some other service UUID. + */ + private static final UUID OTHER_SERVICE_UUID = UUID.fromString("00001800-0000-1000-8000-00805f9b34fb"); // Generic Access service + /** + * A UUID of a characteristic with write property. + */ + private static final UUID READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001801-0000-1000-8000-00805f9b34fb"); // Device Name + + + // TODO Add more services and characteristics references. + + private BluetoothGattCharacteristic mReadBlockTempCharacteristic, mSetAmpTempCharacteristic, mSetAmpTimeCharacteristic, mAmpStartStopCharacteristic, mRequiredCharacteristic, mDeviceNameCharacteristic, mOptionalCharacteristic; + + public TemplateManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving indication, etc. + */ + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + // Initialize the Battery Manager. It will enable Battery Level notifications. + // Remove it if you don't need this feature. + super.initialize(); + + // TODO Initialize your manager here. + // Initialization is done once, after the device is connected. Usually it should + // enable notifications or indications on some characteristics, write some data or + // read some features / version. + // After the initialization is complete, the onDeviceReady(...) method will be called. + + // Increase the MTU + requestMtu(43)//requestMtu(43) + .with((device, mtu) -> log(LogContract.Log.Level.APPLICATION, "MTU changed to " + mtu)) + .done(device -> { + // You may do some logic in here that should be done when the request finished successfully. + // In case of MTU this method is called also when the MTU hasn't changed, or has changed + // to a different (lower) value. Use .with(...) to get the MTU value. + }) + .fail((device, status) -> log(Log.WARN, "MTU change not supported")) + .enqueue(); + + // Set notification callback + setNotificationCallback(mReadBlockTempCharacteristic) + // This callback will be called each time the notification is received + .with(new TemplateDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, TemplateParser.parse(data)); + super.onDataReceived(device, data); + } + + @Override + public void onSampleValueReceived(@NonNull final BluetoothDevice device, final int value) { + // Let's lass received data to the service + mCallbacks.onSampleValueReceived(device, value); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(Log.WARN, "Invalid data received: " + data); + } + }); + + // Enable notifications + enableNotifications(mReadBlockTempCharacteristic) + // Method called after the data were sent (data will contain 0x0100 in this case) + .with((device, data) -> log(Log.DEBUG, "Data sent: " + data)) + // Method called when the request finished successfully. This will be called after .with(..) callback + .done(device -> log(LogContract.Log.Level.APPLICATION, "Notifications enabled successfully")) + // Methods called in case of an error, for example when the characteristic does not have Notify property + .fail((device, status) -> log(Log.WARN, "Failed to enable notifications")) + .enqueue(); + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + // TODO Initialize required characteristics. + // It should return true if all has been discovered (that is that device is supported). + final BluetoothGattService service = gatt.getService(SERVICE_UUID); + if (service != null) { + mReadBlockTempCharacteristic = service.getCharacteristic(TEMP_READABLE_CHARACTERISTIC_UUID); + mSetAmpTimeCharacteristic = service.getCharacteristic(TIME_WRITABLE_CHARACTERISTIC_UUID); + mSetAmpTempCharacteristic = service.getCharacteristic(TEMP_WRITABLE_CHARACTERISTIC_UUID); + mAmpStartStopCharacteristic = service.getCharacteristic(AMP_WRITABLE_CHARACTERISTIC_UUID); + } + final BluetoothGattService otherService = gatt.getService(OTHER_SERVICE_UUID); + if (otherService != null) { + mDeviceNameCharacteristic = otherService.getCharacteristic(READABLE_CHARACTERISTIC_UUID); + } + + return mReadBlockTempCharacteristic != null && mSetAmpTimeCharacteristic != null && mSetAmpTempCharacteristic!= null && mAmpStartStopCharacteristic != null ; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + // Initialize Battery characteristic + super.isOptionalServiceSupported(gatt); + + // TODO If there are some optional characteristics, initialize them there. + final BluetoothGattService service = gatt.getService(SERVICE_UUID); + if (service != null) { + mOptionalCharacteristic = service.getCharacteristic(READABLE_CHARACTERISTIC_UUID); + } + return mOptionalCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + // Release Battery Service + super.onDeviceDisconnected(); + + // TODO Release references to your characteristics. + mRequiredCharacteristic = null; + mDeviceNameCharacteristic = null; + mOptionalCharacteristic = null; + } + + @Override + protected void onDeviceReady() { + super.onDeviceReady(); + + // Initialization is now ready. + // The service or activity has been notified with no.nordicsemi.android.ble.BatteryManagerCallbacks#onDeviceReady(). + // TODO Do some extra logic here, of remove onDeviceReady(). + + // Device is ready, let's read something here. Usually there is nothing else to be done + // here, as all had been done during initialization. + readCharacteristic(mReadBlockTempCharacteristic) + .with((device, data) -> { + // Characteristic value has been read + // Let's do some magic with it. + if (data.size() > 0) { + final Integer value = data.getIntValue(Data.FORMAT_UINT8, 0); + log(LogContract.Log.Level.APPLICATION, "Value '" + value + "' has been read!"); + } else { + log(Log.WARN, "Value is empty!"); + } + }) + .enqueue(); + } + }; + + // TODO Define manager's API + + /** + * This method will write important data to the device. + * + * @param parameter parameter to be written. + */ + + + //Heating Switch + void heatingSwitch(int state) { + log(Log.WARN, "Write time duration \"" + state + "\""); + //final byte time_in_byte = time_duration.getBytes()[0]; + final byte state_in_byte = (byte) state; + writeCharacteristic(mAmpStartStopCharacteristic, Data.opCode(state_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Heating State")) + .split() + .enqueue(); + + } + + //Set Time + void sendTimeDuration(int time_duration) { + log(Log.WARN, "Write time duration \"" + time_duration + "\""); + //final byte time_in_byte = time_duration.getBytes()[0]; + final byte time_in_byte = (byte) time_duration; + writeCharacteristic(mSetAmpTimeCharacteristic, Data.opCode(time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + + } + + + //Set Temp + void sendTemp(int temp) { + log(Log.WARN, "Write temp \"" + temp + "\""); + //final byte temp_in_byte = temp.getBytes()[0]; + final byte temp_in_byte = (byte) temp; + + writeCharacteristic(mSetAmpTempCharacteristic, Data.opCode(temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + + } + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManagerCallbacks.java new file mode 100644 index 0000000..05b03d8 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManagerCallbacks.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package no.nordicsemi.android.nrftoolbox.template; + +import no.nordicsemi.android.nrftoolbox.battery.BatteryManagerCallbacks; +import no.nordicsemi.android.nrftoolbox.template.callback.TemplateCharacteristicCallback; + +/** + * Interface {@link TemplateManagerCallbacks} must be implemented by {@link TemplateService} + * in order to receive callbacks from {@link TemplateManager} + */ +interface TemplateManagerCallbacks extends BatteryManagerCallbacks, TemplateCharacteristicCallback { + + // Callbacks are called when a data has been received/written to a remote device. + // This is the way how the manager notifies the activity about this event. + + // TODO add more callbacks. + // If you need, create more ...Callback interfaces and extend this interface with them. +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateService.java new file mode 100644 index 0000000..7c927be --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateService.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.template; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +public class TemplateService extends BleProfileService implements TemplateManagerCallbacks { + public static final String BROADCAST_TEMPLATE_MEASUREMENT = "no.nordicsemi.android.nrftoolbox.template.BROADCAST_MEASUREMENT"; + public static final String EXTRA_DATA = "no.nordicsemi.android.nrftoolbox.template.EXTRA_DATA"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.nordicsemi.android.nrftoolbox.EXTRA_BATTERY_LEVEL"; + + private final static String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.template.ACTION_DISCONNECT"; + + private final static int NOTIFICATION_ID = 864; + private final static int OPEN_ACTIVITY_REQ = 0; + private final static int DISCONNECT_REQ = 1; + + private TemplateManager mManager; + + private final LocalBinder mBinder = new TemplateBinder(); + + /** + * This local binder is an interface for the bound activity to operate with the sensor. + */ + class TemplateBinder extends LocalBinder { + // TODO Define service API that may be used by a bound Activity + + /** + * Sends some important data to the device. + * + * @param parameter some parameter. + */ + + public void heatingSwitch(int state){ + mManager.heatingSwitch(state); + } + public void sendTimeDuration(int time) { + mManager.sendTimeDuration(time); + } + public void sendTemp(int temp) { + mManager.sendTemp(temp); + } + + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new TemplateManager(this); + } + + @Override + public void onCreate() { + super.onCreate(); + + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + // when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + // when the activity rebinds to the service, remove the notification + cancelNotification(); + } + + @Override + protected void onUnbind() { + // when the activity closes we need to show the notification that user is connected to the sensor + createNotification(R.string.template_notification_connected_message, 0); + } + + @Override + public void onSampleValueReceived(@NonNull final BluetoothDevice device, final int value) { + final Intent broadcast = new Intent(BROADCAST_TEMPLATE_MEASUREMENT); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, value); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + if (!mBound) { + // Here we may update the notification to display the current value. + // TODO modify the notification here + } + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + + } + + /** + * Creates the notification. + * + * @param messageResId message resource id. The message must have one String parameter,
+ * f.e. <string name="name">%s is connected</string> + * @param defaults signals that will be used to notify the user + */ + private void createNotification(final int messageResId, final int defaults) { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, TemplateActivity.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + // both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[]{parentIntent, targetIntent}, PendingIntent.FLAG_UPDATE_CURRENT); + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.CONNECTED_DEVICE_CHANNEL); + builder.setContentIntent(pendingIntent); + builder.setContentTitle(getString(R.string.app_name)).setContentText(getString(messageResId, getDeviceName())); + builder.setSmallIcon(R.drawable.ic_stat_notify_template); + builder.setShowWhen(defaults != 0).setDefaults(defaults).setAutoCancel(true).setOngoing(true); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.template_notification_action_disconnect), disconnectAction)); + + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + Logger.i(getLogSession(), "[Notification] Disconnect action pressed"); + if (isConnected()) + getBinder().disconnect(); + else + stopSelf(); + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateCharacteristicCallback.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateCharacteristicCallback.java new file mode 100644 index 0000000..34e6d44 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateCharacteristicCallback.java @@ -0,0 +1,21 @@ +package no.nordicsemi.android.nrftoolbox.template.callback; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; + +/** + * This class defines your characteristic API. + * In this example (that is the HRM characteristic, which the template is based on), is notifying + * with a value (Heart Rate). The single method just returns the value and ignores other + * optional data from Heart Rate Measurement characteristic for simplicity. + */ +public interface TemplateCharacteristicCallback { + + /** + * Called when a value is received. + * + * @param device a device from which the value was obtained. + * @param value the new value. + */ + void onSampleValueReceived(@NonNull final BluetoothDevice device, int value); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateDataCallback.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateDataCallback.java new file mode 100644 index 0000000..1ec05f9 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateDataCallback.java @@ -0,0 +1,47 @@ +package no.nordicsemi.android.nrftoolbox.template.callback; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; + +import no.nordicsemi.android.ble.callback.profile.ProfileDataCallback; +import no.nordicsemi.android.ble.data.Data; + +/** + * This is a sample data callback, that's based on Heart Rate Measurement characteristic. + * It parses the HR value and ignores other optional data for simplicity. + * Check {@link no.nordicsemi.android.ble.common.callback.hr.HeartRateMeasurementDataCallback} + * for full implementation. + * + * TODO Modify the content to parse your data. + */ +@SuppressWarnings("ConstantConditions") +public abstract class TemplateDataCallback implements ProfileDataCallback, TemplateCharacteristicCallback { + + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + if (data.size() < 2) { + onInvalidDataReceived(device, data); + return; + } + + // Read flags + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset); + final int hearRateType = (flags & 0x01) == 0 ? Data.FORMAT_UINT8 : Data.FORMAT_UINT16; + offset += 1; + + // Validate packet length. The type's lower nibble is its length. + if (data.size() < 1 + (hearRateType & 0x0F)) { + onInvalidDataReceived(device, data); + return; + } + + final int value = data.getIntValue(hearRateType, offset); + // offset += hearRateType & 0xF; + + // ... + + // Report the parsed value(s) + onSampleValueReceived(device, value); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsActivity.java new file mode 100644 index 0000000..00f410d --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsActivity.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.template.settings; + +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; + +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsActivity extends AppCompatActivity { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_settings); + + final Toolbar toolbar = findViewById(R.id.toolbar_actionbar); + setSupportActionBar(toolbar); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // Display the fragment as the main content. + getSupportFragmentManager().beginTransaction().replace(R.id.content, new SettingsFragment()).commit(); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + onBackPressed(); + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsFragment.java new file mode 100644 index 0000000..3475b49 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsFragment.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.template.settings; + +import android.os.Bundle; +import android.preference.PreferenceFragment; + +import androidx.preference.PreferenceFragmentCompat; +import no.nordicsemi.android.nrftoolbox.R; + +public class SettingsFragment extends PreferenceFragmentCompat { + public static final String SETTINGS_DATA = "settings_template_data"; // TODO values matching those in settings_template.xml file in /res/xml + public static final int SETTINGS_VARIANT_A = 0; + public static final int SETTINGS_VARIANT_B = 1; + public static final int SETTINGS_VARIANT_DEFAULT = SETTINGS_VARIANT_A; + + @Override + public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) { + addPreferencesFromResource(R.xml.settings_template); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTActivity.java new file mode 100644 index 0000000..efce6fa --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTActivity.java @@ -0,0 +1,826 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.Manifest; +import android.animation.ArgbEvaluator; +import android.animation.ValueAnimator; +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.TransitionDrawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Environment; +import android.os.Handler; +import android.preference.PreferenceManager; +import androidx.annotation.NonNull; +import com.google.android.material.snackbar.Snackbar; +import androidx.core.app.ActivityCompat; +import androidx.fragment.app.DialogFragment; +import androidx.core.app.NotificationCompat; +import androidx.core.content.ContextCompat; +import androidx.slidingpanelayout.widget.SlidingPaneLayout; +import androidx.appcompat.app.AlertDialog; +import android.util.Log; +import android.view.Menu; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ListView; +import android.widget.Toast; + +import com.google.android.gms.common.api.GoogleApiClient; + +import org.simpleframework.xml.Serializer; +import org.simpleframework.xml.core.Persister; +import org.simpleframework.xml.strategy.Strategy; +import org.simpleframework.xml.strategy.Type; +import org.simpleframework.xml.strategy.Visitor; +import org.simpleframework.xml.strategy.VisitorStrategy; +import org.simpleframework.xml.stream.Format; +import org.simpleframework.xml.stream.HyphenStyle; +import org.simpleframework.xml.stream.InputNode; +import org.simpleframework.xml.stream.NodeMap; +import org.simpleframework.xml.stream.OutputNode; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.util.UUID; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.dfu.adapter.FileBrowserAppsAdapter; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileServiceReadyActivity; +import no.nordicsemi.android.nrftoolbox.uart.database.DatabaseHelper; +import no.nordicsemi.android.nrftoolbox.uart.domain.Command; +import no.nordicsemi.android.nrftoolbox.uart.domain.UartConfiguration; +import no.nordicsemi.android.nrftoolbox.uart.wearable.UARTConfigurationSynchronizer; +import no.nordicsemi.android.nrftoolbox.utility.FileHelper; +import no.nordicsemi.android.nrftoolbox.widget.ClosableSpinner; + +public class UARTActivity extends BleProfileServiceReadyActivity implements UARTInterface, + UARTNewConfigurationDialogFragment.NewConfigurationDialogListener, UARTConfigurationsAdapter.ActionListener, AdapterView.OnItemSelectedListener, + GoogleApiClient.ConnectionCallbacks { + private final static String TAG = "UARTActivity"; + + private final static String PREFS_BUTTON_ENABLED = "prefs_uart_enabled_"; + private final static String PREFS_BUTTON_COMMAND = "prefs_uart_command_"; + private final static String PREFS_BUTTON_ICON = "prefs_uart_icon_"; + /** This preference keeps the ID of the selected configuration. */ + private final static String PREFS_CONFIGURATION = "configuration_id"; + /** This preference is set to true when initial data synchronization for wearables has been completed. */ + private final static String PREFS_WEAR_SYNCED = "prefs_uart_synced"; + private final static String SIS_EDIT_MODE = "sis_edit_mode"; + + private final static int SELECT_FILE_REQ = 2678; // random + private final static int PERMISSION_REQ = 24; // random, 8-bit + + UARTConfigurationSynchronizer mWearableSynchronizer; + + /** The current configuration. */ + private UartConfiguration mConfiguration; + private DatabaseHelper mDatabaseHelper; + private SharedPreferences mPreferences; + private UARTConfigurationsAdapter mConfigurationsAdapter; + private ClosableSpinner mConfigurationSpinner; + private SlidingPaneLayout mSlider; + private View mContainer; + private UARTService.UARTBinder mServiceBinder; + private ConfigurationListener mConfigurationListener; + private boolean mEditMode; + + public interface ConfigurationListener { + void onConfigurationModified(); + void onConfigurationChanged(final UartConfiguration configuration); + void setEditMode(final boolean editMode); + } + + public void setConfigurationListener(final ConfigurationListener listener) { + mConfigurationListener = listener; + } + + @Override + protected Class getServiceClass() { + return UARTService.class; + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.uart_feature_title; + } + + @Override + protected Uri getLocalAuthorityLogger() { + return UARTLocalLogContentProvider.AUTHORITY_URI; + } + + @Override + protected void setDefaultUI() { + // empty + } + + @Override + protected void onServiceBound(final UARTService.UARTBinder binder) { + mServiceBinder = binder; + } + + @Override + protected void onServiceUnbound() { + mServiceBinder = null; + } + + @Override + protected void onInitialize(final Bundle savedInstanceState) { + mPreferences = PreferenceManager.getDefaultSharedPreferences(this); + mDatabaseHelper = new DatabaseHelper(this); + ensureFirstConfiguration(mDatabaseHelper); + mConfigurationsAdapter = new UARTConfigurationsAdapter(this, this, mDatabaseHelper.getConfigurationsNames()); + + // Initialize Wearable synchronizer + mWearableSynchronizer = UARTConfigurationSynchronizer.from(this, this); + } + + /** + * Method called when Google API Client connects to Wearable.API. + */ + @Override + public void onConnected(final Bundle bundle) { + // Ensure the Wearable API was connected + if (!mWearableSynchronizer.hasConnectedApi()) + return; + + if (!mPreferences.getBoolean(PREFS_WEAR_SYNCED, false)) { + new Thread(() -> { + final Cursor cursor = mDatabaseHelper.getConfigurations(); + try { + while (cursor.moveToNext()) { + final long id = cursor.getLong(0 /* _ID */); + try { + final String xml = cursor.getString(2 /* XML */); + final Format format = new Format(new HyphenStyle()); + final Serializer serializer = new Persister(format); + final UartConfiguration configuration = serializer.read(UartConfiguration.class, xml); + mWearableSynchronizer.onConfigurationAddedOrEdited(id, configuration).await(); + } catch (final Exception e) { + Log.w(TAG, "Deserializing configuration with id " + id + " failed", e); + } + } + mPreferences.edit().putBoolean(PREFS_WEAR_SYNCED, true).apply(); + } finally { + cursor.close(); + } + }).start(); + } + } + + /** + * Method called then Google API client connection was suspended. + * @param cause the cause of suspension + */ + @Override + public void onConnectionSuspended(final int cause) { + // dp nothing + } + + @Override + protected void onDestroy() { + super.onDestroy(); + mWearableSynchronizer.close(); + } + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_uart); + + mContainer = findViewById(R.id.container); + // Setup the sliding pane if it exists + final SlidingPaneLayout slidingPane = mSlider = findViewById(R.id.sliding_pane); + if (slidingPane != null) { + slidingPane.setSliderFadeColor(Color.TRANSPARENT); + slidingPane.setShadowResourceLeft(R.drawable.shadow_r); + slidingPane.setPanelSlideListener(new SlidingPaneLayout.SimplePanelSlideListener() { + @Override + public void onPanelClosed(final View panel) { + // Close the keyboard + final UARTLogFragment logFragment = (UARTLogFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_log); + logFragment.onFragmentHidden(); + } + }); + } + } + + @Override + protected void onViewCreated(final Bundle savedInstanceState) { + getSupportActionBar().setDisplayShowTitleEnabled(false); + + final ClosableSpinner configurationSpinner = mConfigurationSpinner = findViewById(R.id.toolbar_spinner); + configurationSpinner.setOnItemSelectedListener(this); + configurationSpinner.setAdapter(mConfigurationsAdapter); + configurationSpinner.setSelection(mConfigurationsAdapter.getItemPosition(mPreferences.getLong(PREFS_CONFIGURATION, 0))); + } + + @Override + protected void onRestoreInstanceState(final @NonNull Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + + mEditMode = savedInstanceState.getBoolean(SIS_EDIT_MODE); + setEditMode(mEditMode, false); + } + + @Override + public void onSaveInstanceState(final Bundle outState) { + super.onSaveInstanceState(outState); + + outState.putBoolean(SIS_EDIT_MODE, mEditMode); + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + // do nothing + } + + @Override + public void onDeviceSelected(final BluetoothDevice device, final String name) { + // The super method starts the service + super.onDeviceSelected(device, name); + + // Notify the log fragment about it + final UARTLogFragment logFragment = (UARTLogFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_log); + logFragment.onServiceStarted(); + } + + @Override + protected int getDefaultDeviceName() { + return R.string.uart_default_name; + } + + @Override + protected int getAboutTextId() { + return R.string.uart_about_text; + } + + @Override + protected UUID getFilterUUID() { + return null; // not used + } + + @Override + public void send(final String text) { + if (mServiceBinder != null) + mServiceBinder.send(text); + } + + public void setEditMode(final boolean editMode) { + setEditMode(editMode, true); + invalidateOptionsMenu(); + } + + @Override + public void onBackPressed() { + if (mSlider != null && mSlider.isOpen()) { + mSlider.closePane(); + return; + } + if (mEditMode) { + setEditMode(false); + return; + } + super.onBackPressed(); + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + getMenuInflater().inflate(R.menu.uart_menu_configurations, menu); + getMenuInflater().inflate(mEditMode ? R.menu.uart_menu_config : R.menu.uart_menu, menu); + + final int configurationsCount = mDatabaseHelper.getConfigurationsCount(); + menu.findItem(R.id.action_remove).setVisible(configurationsCount > 1); + return super.onCreateOptionsMenu(menu); + } + + @Override + protected boolean onOptionsItemSelected(int itemId) { + final String name = mConfiguration.getName(); + switch (itemId) { + case R.id.action_configure: + setEditMode(!mEditMode); + return true; + case R.id.action_show_log: + mSlider.openPane(); + return true; + case R.id.action_share: { + final String xml = mDatabaseHelper.getConfiguration(mConfigurationSpinner.getSelectedItemId()); + + final Intent intent = new Intent(Intent.ACTION_SEND); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.setType("text/xml"); + intent.putExtra(Intent.EXTRA_TEXT, xml); + intent.putExtra(Intent.EXTRA_SUBJECT, mConfiguration.getName()); + try { + startActivity(intent); + } catch (final ActivityNotFoundException e) { + Toast.makeText(this, R.string.no_uri_application, Toast.LENGTH_SHORT).show(); + } + return true; + } + case R.id.action_export: { + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { + exportConfiguration(); + } else { + ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, PERMISSION_REQ); + } + return true; + } + case R.id.action_rename: { + final DialogFragment fragment = UARTNewConfigurationDialogFragment.getInstance(name, false); + fragment.show(getSupportFragmentManager(), null); + // onNewConfiguration(name, false) will be called when user press OK + return true; + } + case R.id.action_duplicate: { + final DialogFragment fragment = UARTNewConfigurationDialogFragment.getInstance(name, true); + fragment.show(getSupportFragmentManager(), null); + // onNewConfiguration(name, true) will be called when user press OK + return true; + } + case R.id.action_remove: { + mDatabaseHelper.removeDeletedServerConfigurations(); // just to be sure nothing has left + final UartConfiguration removedConfiguration = mConfiguration; + final long id = mDatabaseHelper.deleteConfiguration(name); + if (id >= 0) + mWearableSynchronizer.onConfigurationDeleted(id); + refreshConfigurations(); + + final Snackbar snackbar = Snackbar.make(mContainer, R.string.uart_configuration_deleted, Snackbar.LENGTH_INDEFINITE).setAction(R.string.uart_action_undo, v -> { + final long id1 = mDatabaseHelper.restoreDeletedServerConfiguration(name); + if (id1 >= 0) + mWearableSynchronizer.onConfigurationAddedOrEdited(id1, removedConfiguration); + refreshConfigurations(); + }); + snackbar.setDuration(5000); // This is not an error + snackbar.show(); + return true; + } + } + return false; + } + + @Override + public void onRequestPermissionsResult(final int requestCode, final @NonNull String[] permissions, final @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + switch (requestCode) { + case PERMISSION_REQ: { + if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { + // We have been granted the Manifest.permission.WRITE_EXTERNAL_STORAGE permission. Now we may proceed with exporting. + exportConfiguration(); + } else { + Toast.makeText(this, R.string.no_required_permission, Toast.LENGTH_SHORT).show(); + } + break; + } + } + } + + @Override + public void onItemSelected(final AdapterView parent, final View view, final int position, final long id) { + if (position > 0) { // FIXME this is called twice after rotation. + try { + final String xml = mDatabaseHelper.getConfiguration(id); + final Format format = new Format(new HyphenStyle()); + final Serializer serializer = new Persister(format); + mConfiguration = serializer.read(UartConfiguration.class, xml); + mConfigurationListener.onConfigurationChanged(mConfiguration); + } catch (final Exception e) { + Log.e(TAG, "Selecting configuration failed", e); + + String message; + if (e.getLocalizedMessage() != null) + message = e.getLocalizedMessage(); + else if (e.getCause() != null && e.getCause().getLocalizedMessage() != null) + message = e.getCause().getLocalizedMessage(); + else + message = "Unknown error"; + final String msg = message; + Snackbar.make(mContainer, R.string.uart_configuration_loading_failed, Snackbar.LENGTH_INDEFINITE).setAction(R.string.uart_action_details, v -> new AlertDialog.Builder(UARTActivity.this).setMessage(msg).setTitle(R.string.uart_action_details).setPositiveButton(R.string.ok, null).show()).show(); + return; + } + + mPreferences.edit().putLong(PREFS_CONFIGURATION, id).apply(); + } + } + + @Override + public void onNothingSelected(final AdapterView parent) { + // do nothing + } + + @Override + public void onNewConfigurationClick() { + // No item has been selected. We must close the spinner manually. + mConfigurationSpinner.close(); + + // Open the dialog + final DialogFragment fragment = UARTNewConfigurationDialogFragment.getInstance(null, false); + fragment.show(getSupportFragmentManager(), null); + + // onNewConfiguration(null, false) will be called when user press OK + } + + @Override + public void onImportClick() { + // No item has been selected. We must close the spinner manually. + mConfigurationSpinner.close(); + + final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("text/xml"); + intent.addCategory(Intent.CATEGORY_OPENABLE); + if (intent.resolveActivity(getPackageManager()) != null) { + // file browser has been found on the device + startActivityForResult(intent, SELECT_FILE_REQ); + } else { + // there is no any file browser app, let's try to download one + final View customView = getLayoutInflater().inflate(R.layout.app_file_browser, null); + final ListView appsList = customView.findViewById(android.R.id.list); + appsList.setAdapter(new FileBrowserAppsAdapter(this)); + appsList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + appsList.setItemChecked(0, true); + new AlertDialog.Builder(this).setTitle(R.string.dfu_alert_no_filebrowser_title).setView(customView).setNegativeButton(R.string.no, (dialog, which) -> dialog.dismiss()).setPositiveButton(R.string.yes, (dialog, which) -> { + final int pos = appsList.getCheckedItemPosition(); + if (pos >= 0) { + final String query = getResources().getStringArray(R.array.dfu_app_file_browser_action)[pos]; + final Intent storeIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(query)); + startActivity(storeIntent); + } + }).show(); + } + } + + @Override + protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + if (resultCode == Activity.RESULT_CANCELED) + return; + + switch (requestCode) { + case SELECT_FILE_REQ: { + // clear previous data + final Uri uri = data.getData(); + /* + * The URI returned from application may be in 'file' or 'content' schema. + * 'File' schema allows us to create a File object and read details from if directly. + * Data from 'Content' schema must be read with use of a Content Provider. To do that we are using a Loader. + */ + if (uri.getScheme().equals("file")) { + // The direct path to the file has been returned + final String path = uri.getPath(); + try { + final FileInputStream fis = new FileInputStream(path); + loadConfiguration(fis); + } catch (final FileNotFoundException e) { + Toast.makeText(this, R.string.uart_configuration_load_error, Toast.LENGTH_LONG).show(); + } + } else if (uri.getScheme().equals("content")) { + // An Uri has been returned + Uri u = uri; + + // If application returned Uri for streaming, let's us it. Does it works? + final Bundle extras = data.getExtras(); + if (extras != null && extras.containsKey(Intent.EXTRA_STREAM)) + u = extras.getParcelable(Intent.EXTRA_STREAM); + + try { + final InputStream is = getContentResolver().openInputStream(u); + loadConfiguration(is); + } catch (final FileNotFoundException e) { + Toast.makeText(this, R.string.uart_configuration_load_error, Toast.LENGTH_LONG).show(); + } + } + break; + } + } + } + + public void onCommandChanged(final int index, final String message, final boolean active, final int eol, final int iconIndex) { + final Command command = mConfiguration.getCommands()[index]; + + command.setCommand(message); + command.setActive(active); + command.setEol(eol); + command.setIconIndex(iconIndex); + mConfigurationListener.onConfigurationModified(); + saveConfiguration(); + } + + @Override + public void onNewConfiguration(final String name, final boolean duplicate) { + final boolean exists = mDatabaseHelper.configurationExists(name); + if (exists) { + Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show(); + return; + } + + UartConfiguration configuration = mConfiguration; + if (!duplicate) + configuration = new UartConfiguration(); + configuration.setName(name); + + try { + final Format format = new Format(new HyphenStyle()); + final Strategy strategy = new VisitorStrategy(new CommentVisitor()); + final Serializer serializer = new Persister(strategy, format); + final StringWriter writer = new StringWriter(); + serializer.write(configuration, writer); + final String xml = writer.toString(); + + final long id = mDatabaseHelper.addConfiguration(name, xml); + mWearableSynchronizer.onConfigurationAddedOrEdited(id, configuration); + refreshConfigurations(); + selectConfiguration(mConfigurationsAdapter.getItemPosition(id)); + } catch (final Exception e) { + Log.e(TAG, "Error while creating a new configuration", e); + } + } + + @Override + public void onRenameConfiguration(final String newName) { + final boolean exists = mDatabaseHelper.configurationExists(newName); + if (exists) { + Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show(); + return; + } + + final String oldName = mConfiguration.getName(); + mConfiguration.setName(newName); + + try { + final Format format = new Format(new HyphenStyle()); + final Strategy strategy = new VisitorStrategy(new CommentVisitor()); + final Serializer serializer = new Persister(strategy, format); + final StringWriter writer = new StringWriter(); + serializer.write(mConfiguration, writer); + final String xml = writer.toString(); + + mDatabaseHelper.renameConfiguration(oldName, newName, xml); + mWearableSynchronizer.onConfigurationAddedOrEdited(mPreferences.getLong(PREFS_CONFIGURATION, 0), mConfiguration); + refreshConfigurations(); + } catch (final Exception e) { + Log.e(TAG, "Error while renaming configuration", e); + } + } + + private void refreshConfigurations() { + mConfigurationsAdapter.swapCursor(mDatabaseHelper.getConfigurationsNames()); + mConfigurationsAdapter.notifyDataSetChanged(); + invalidateOptionsMenu(); + } + + private void selectConfiguration(final int position) { + mConfigurationSpinner.setSelection(position); + } + + /** + * Updates the ActionBar background color depending on whether we are in edit mode or not. + * + * @param editMode + * true to show edit mode, false otherwise + * @param change + * if true the background will change with animation, otherwise immediately + */ + @SuppressLint("NewApi") + private void setEditMode(final boolean editMode, final boolean change) { + mEditMode = editMode; + mConfigurationListener.setEditMode(editMode); + if (!change) { + final ColorDrawable color = new ColorDrawable(); + int darkColor = 0; + if (editMode) { + color.setColor(ContextCompat.getColor(this, R.color.orange)); + darkColor = ContextCompat.getColor(this, R.color.dark_orange); + } else { + color.setColor(ContextCompat.getColor(this, R.color.actionBarColor)); + darkColor = ContextCompat.getColor(this, R.color.actionBarColorDark); + } + getSupportActionBar().setBackgroundDrawable(color); + + // Since Lollipop the status bar color may also be changed + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + getWindow().setStatusBarColor(darkColor); + } else { + final TransitionDrawable transition = (TransitionDrawable) getResources().getDrawable( + editMode ? R.drawable.start_edit_mode : R.drawable.stop_edit_mode); + transition.setCrossFadeEnabled(true); + getSupportActionBar().setBackgroundDrawable(transition); + transition.startTransition(200); + + // Since Lollipop the status bar color may also be changed + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + final int colorFrom = ContextCompat.getColor(this, editMode ? R.color.actionBarColorDark : R.color.dark_orange); + final int colorTo = ContextCompat.getColor(this, !editMode ? R.color.actionBarColorDark : R.color.dark_orange); + + final ValueAnimator anim = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo); + anim.setDuration(200); + anim.addUpdateListener(animation -> getWindow().setStatusBarColor((Integer) animation.getAnimatedValue())); + anim.start(); + } + + if (mSlider != null && editMode) { + mSlider.closePane(); + } + } + } + + /** + * Saves the given configuration in the database. + */ + private void saveConfiguration() { + final UartConfiguration configuration = mConfiguration; + try { + final Format format = new Format(new HyphenStyle()); + final Strategy strategy = new VisitorStrategy(new CommentVisitor()); + final Serializer serializer = new Persister(strategy, format); + final StringWriter writer = new StringWriter(); + serializer.write(configuration, writer); + final String xml = writer.toString(); + + mDatabaseHelper.updateConfiguration(configuration.getName(), xml); + mWearableSynchronizer.onConfigurationAddedOrEdited(mPreferences.getLong(PREFS_CONFIGURATION, 0), configuration); + } catch (final Exception e) { + Log.e(TAG, "Error while creating a new configuration", e); + } + } + + /** + * Loads the configuration from the given input stream. + * @param is the input stream + */ + private void loadConfiguration(final InputStream is) { + try { + final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + final StringBuilder builder = new StringBuilder(); + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + builder.append(line).append("\n"); + } + final String xml = builder.toString(); + + final Format format = new Format(new HyphenStyle()); + final Serializer serializer = new Persister(format); + final UartConfiguration configuration = serializer.read(UartConfiguration.class, xml); + + final String name = configuration.getName(); + if (!mDatabaseHelper.configurationExists(name)) { + final long id = mDatabaseHelper.addConfiguration(name, xml); + mWearableSynchronizer.onConfigurationAddedOrEdited(id, configuration); + refreshConfigurations(); + new Handler().post(() -> selectConfiguration(mConfigurationsAdapter.getItemPosition(id))); + } else { + Toast.makeText(this, R.string.uart_configuration_name_already_taken, Toast.LENGTH_LONG).show(); + } + } catch (final Exception e) { + Log.e(TAG, "Loading configuration failed", e); + + String message; + if (e.getLocalizedMessage() != null) + message = e.getLocalizedMessage(); + else if (e.getCause() != null && e.getCause().getLocalizedMessage() != null) + message = e.getCause().getLocalizedMessage(); + else + message = "Unknown error"; + final String msg = message; + Snackbar.make(mContainer, R.string.uart_configuration_loading_failed, Snackbar.LENGTH_INDEFINITE).setAction(R.string.uart_action_details, v -> new AlertDialog.Builder(UARTActivity.this).setMessage(msg).setTitle(R.string.uart_action_details).setPositiveButton(R.string.ok, null).show()).show(); + } + } + + private void exportConfiguration() { + // TODO this may not work if the SD card is not available. (Lenovo A806, email from 11.03.2015) + final File folder = new File(Environment.getExternalStorageDirectory(), FileHelper.NORDIC_FOLDER); + if (!folder.exists()) + folder.mkdir(); + final File serverFolder = new File(folder, FileHelper.UART_FOLDER); + if (!serverFolder.exists()) + serverFolder.mkdir(); + + final String fileName = mConfiguration.getName() + ".xml"; + final File file = new File(serverFolder, fileName); + try { + file.createNewFile(); + final FileOutputStream fos = new FileOutputStream(file); + final OutputStreamWriter writer = new OutputStreamWriter(fos); + writer.append(mDatabaseHelper.getConfiguration(mConfigurationSpinner.getSelectedItemId())); + writer.close(); + + // Notify user about the file + final Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setDataAndType(FileHelper.getContentUri(this, file), "text/xml"); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final PendingIntent pendingIntent = PendingIntent.getActivity(this, 420, intent, 0); + final Notification notification = new NotificationCompat.Builder(this, ToolboxApplication.FILE_SAVED_CHANNEL).setContentIntent(pendingIntent).setContentTitle(fileName).setContentText(getText(R.string.uart_configuration_export_succeeded)) + .setAutoCancel(true).setShowWhen(true).setTicker(getText(R.string.uart_configuration_export_succeeded_ticker)).setSmallIcon(android.R.drawable.stat_notify_sdcard).build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(fileName, 823, notification); + } catch (final Exception e) { + Log.e(TAG, "Error while exporting configuration", e); + Toast.makeText(this, R.string.uart_configuration_save_error, Toast.LENGTH_SHORT).show(); + } + } + + /** + * Converts the old configuration, stored in preferences, into the first XML configuration and saves it to the database. + * If there is already any configuration in the database this method does nothing. + */ + private void ensureFirstConfiguration(final DatabaseHelper mDatabaseHelper) { + // This method ensures that the "old", single configuration has been saved to the database. + if (mDatabaseHelper.getConfigurationsCount() == 0) { + final UartConfiguration configuration = new UartConfiguration(); + configuration.setName("First configuration"); + final Command[] commands = configuration.getCommands(); + + for (int i = 0; i < 9; ++i) { + final String cmd = mPreferences.getString(PREFS_BUTTON_COMMAND + i, null); + if (cmd != null) { + final Command command = new Command(); + command.setCommand(cmd); + command.setActive(mPreferences.getBoolean(PREFS_BUTTON_ENABLED + i, false)); + command.setEol(0); // default one + command.setIconIndex(mPreferences.getInt(PREFS_BUTTON_ICON + i, 0)); + commands[i] = command; + } + } + + try { + final Format format = new Format(new HyphenStyle()); + final Strategy strategy = new VisitorStrategy(new CommentVisitor()); + final Serializer serializer = new Persister(strategy, format); + final StringWriter writer = new StringWriter(); + serializer.write(configuration, writer); + final String xml = writer.toString(); + + mDatabaseHelper.addConfiguration(configuration.getName(), xml); + } catch (final Exception e) { + Log.e(TAG, "Error while creating default configuration", e); + } + } + } + + /** + * The comment visitor will add comments to the XML during saving. + */ + private class CommentVisitor implements Visitor { + @Override + public void read(final Type type, final NodeMap node) throws Exception { + // do nothing + } + + @Override + public void write(final Type type, final NodeMap node) throws Exception { + if (type.getType().equals(Command[].class)) { + OutputNode element = node.getNode(); + + StringBuilder builder = new StringBuilder("A configuration must have 9 commands, one for each button.\n Possible icons are:"); + for (Command.Icon icon : Command.Icon.values()) + builder.append("\n - ").append(icon.toString()); + element.setComment(builder.toString()); + } + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTButtonAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTButtonAdapter.java new file mode 100644 index 0000000..7a25d8a --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTButtonAdapter.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.ImageView; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.uart.domain.Command; +import no.nordicsemi.android.nrftoolbox.uart.domain.UartConfiguration; + +public class UARTButtonAdapter extends BaseAdapter { + private UartConfiguration mConfiguration; + private boolean mEditMode; + + public UARTButtonAdapter(final UartConfiguration configuration) { + mConfiguration = configuration; + } + + public void setEditMode(final boolean editMode) { + mEditMode = editMode; + notifyDataSetChanged(); + } + + public void setConfiguration(final UartConfiguration configuration) { + mConfiguration = configuration; + notifyDataSetChanged(); + } + + @Override + public int getCount() { + return mConfiguration != null ? mConfiguration.getCommands().length : 0; + } + + @Override + public Object getItem(final int position) { + return mConfiguration.getCommands()[position]; + } + + @Override + public long getItemId(final int position) { + return position; + } + + @Override + public boolean hasStableIds() { + return true; + } + + @Override + public boolean areAllItemsEnabled() { + return false; + } + + @Override + public boolean isEnabled(int position) { + final Command command = (Command) getItem(position); + return mEditMode || (command != null && command.isActive()); + } + + @Override + public View getView(final int position, final View convertView, final ViewGroup parent) { + View view = convertView; + if (view == null) { + final LayoutInflater inflater = LayoutInflater.from(parent.getContext()); + view = inflater.inflate(R.layout.feature_uart_button, parent, false); + } + view.setEnabled(isEnabled(position)); + view.setActivated(mEditMode); + + // Update image + final Command command = (Command) getItem(position); + final ImageView image = (ImageView) view; + final boolean active = command != null && command.isActive(); + if (active) { + final int icon = command.getIconIndex(); + image.setImageResource(R.drawable.uart_button); + image.setImageLevel(icon); + } else + image.setImageDrawable(null); + + return view; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTConfigurationsAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTConfigurationsAdapter.java new file mode 100644 index 0000000..1c4b25b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTConfigurationsAdapter.java @@ -0,0 +1,127 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.content.Context; +import android.database.Cursor; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.TextView; + +import no.nordicsemi.android.nrftoolbox.R; + +public class UARTConfigurationsAdapter extends CursorAdapter { + final Context mContext; + final ActionListener mListener; + + public interface ActionListener { + void onNewConfigurationClick(); + void onImportClick(); + } + + public UARTConfigurationsAdapter(final Context context, final ActionListener listener, final Cursor c) { + super(context, c, 0); + mContext = context; + mListener = listener; + } + + @Override + public int getCount() { + return super.getCount() + 1; // One for buttons at the top + } + + @Override + public boolean isEmpty() { + return super.getCount() == 0; + } + + @Override + public boolean hasStableIds() { + return true; + } + + @Override + public long getItemId(final int position) { + if (position > 0) + return super.getItemId(position - 1); + return 0; + } + + public int getItemPosition(final long id) { + final Cursor cursor = getCursor(); + if (cursor == null) + return 1; + + if (cursor.moveToFirst()) + do { + if (cursor.getLong(0 /* _ID */) == id) + return cursor.getPosition() + 1; + } while (cursor.moveToNext()); + return 1; // should never happen + } + + @Override + public View getView(final int position, final View convertView, final ViewGroup parent) { + if (position == 0) { + // This empty view should never be visible. Only positions 1+ are valid. Position 0 is reserved for action buttons. + // It is only created temporally when activity is created. + return LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_spinner_item, parent, false); + } + return super.getView(position - 1, convertView, parent); + } + + @Override + public View getDropDownView(final int position, final View convertView, final ViewGroup parent) { + if (position == 0) { + return newToolbarView(mContext, parent); + } + if (convertView instanceof ViewGroup) + return super.getDropDownView(position - 1, null, parent); + return super.getDropDownView(position - 1, convertView, parent); + } + + @Override + public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { + return LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_spinner_item, parent, false); + } + + @Override + public View newDropDownView(final Context context, final Cursor cursor, final ViewGroup parent) { + return LayoutInflater.from(mContext).inflate(R.layout.feature_uart_dropdown_item, parent, false); + } + + public View newToolbarView(final Context context, final ViewGroup parent) { + final View view = LayoutInflater.from(context).inflate(R.layout.feature_uart_dropdown_title, parent, false); + view.findViewById(R.id.action_add).setOnClickListener(v -> mListener.onNewConfigurationClick()); + view.findViewById(R.id.action_import).setOnClickListener(v -> mListener.onImportClick()); + return view; + } + + @Override + public void bindView(final View view, final Context context, final Cursor cursor) { + final String name = cursor.getString(1 /* NAME */); + ((TextView) view).setText(name); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTControlFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTControlFragment.java new file mode 100644 index 0000000..374b53b --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTControlFragment.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.content.Context; +import android.os.Bundle; +import androidx.fragment.app.Fragment; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.GridView; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.uart.domain.Command; +import no.nordicsemi.android.nrftoolbox.uart.domain.UartConfiguration; + +public class UARTControlFragment extends Fragment implements GridView.OnItemClickListener, UARTActivity.ConfigurationListener { + private final static String TAG = "UARTControlFragment"; + private final static String SIS_EDIT_MODE = "sis_edit_mode"; + + private UartConfiguration mConfiguration; + private UARTButtonAdapter mAdapter; + private boolean mEditMode; + + @Override + public void onAttach(final Context context) { + super.onAttach(context); + + try { + ((UARTActivity)context).setConfigurationListener(this); + } catch (final ClassCastException e) { + Log.e(TAG, "The parent activity must implement EditModeListener"); + } + } + + @Override + public void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (savedInstanceState != null) { + mEditMode = savedInstanceState.getBoolean(SIS_EDIT_MODE); + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + ((UARTActivity)getActivity()).setConfigurationListener(null); + } + + @Override + public void onSaveInstanceState(final Bundle outState) { + outState.putBoolean(SIS_EDIT_MODE, mEditMode); + } + + @Override + public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_feature_uart_control, container, false); + + final GridView grid = view.findViewById(R.id.grid); + grid.setAdapter(mAdapter = new UARTButtonAdapter(mConfiguration)); + grid.setOnItemClickListener(this); + mAdapter.setEditMode(mEditMode); + + return view; + } + + @Override + public void onItemClick(final AdapterView parent, final View view, final int position, final long id) { + if (mEditMode) { + Command command = mConfiguration.getCommands()[position]; + if (command == null) + mConfiguration.getCommands()[position] = command = new Command(); + final UARTEditDialog dialog = UARTEditDialog.getInstance(position, command); + dialog.show(getChildFragmentManager(), null); + } else { + final Command command = (Command)mAdapter.getItem(position); + final Command.Eol eol = command.getEol(); + String text = command.getCommand(); + if (text == null) + text = ""; + switch (eol) { + case CR_LF: + text = text.replaceAll("\n", "\r\n"); + break; + case CR: + text = text.replaceAll("\n", "\r"); + break; + } + final UARTInterface uart = (UARTInterface) getActivity(); + uart.send(text); + } + } + + @Override + public void onConfigurationModified() { + mAdapter.notifyDataSetChanged(); + } + + @Override + public void onConfigurationChanged(final UartConfiguration configuration) { + mConfiguration = configuration; + mAdapter.setConfiguration(configuration); + } + + @Override + public void setEditMode(final boolean editMode) { + mEditMode = editMode; + mAdapter.setEditMode(mEditMode); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTEditDialog.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTEditDialog.java new file mode 100644 index 0000000..9277019 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTEditDialog.java @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.app.Dialog; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.appcompat.app.AlertDialog; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.GridView; +import android.widget.ImageView; +import android.widget.RadioGroup; + +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.uart.domain.Command; + +public class UARTEditDialog extends DialogFragment implements View.OnClickListener, GridView.OnItemClickListener { + private final static String ARG_INDEX = "index"; + private final static String ARG_COMMAND = "command"; + private final static String ARG_EOL = "eol"; + private final static String ARG_ICON_INDEX = "iconIndex"; + private int mActiveIcon; + + private EditText mField; + private CheckBox mActiveCheckBox; + private RadioGroup mEOLGroup; + private IconAdapter mIconAdapter; + + public static UARTEditDialog getInstance(final int index, final Command command) { + final UARTEditDialog fragment = new UARTEditDialog(); + + final Bundle args = new Bundle(); + args.putInt(ARG_INDEX, index); + args.putString(ARG_COMMAND, command.getCommand()); + args.putInt(ARG_EOL, command.getEol().index); + args.putInt(ARG_ICON_INDEX, command.getIconIndex()); + fragment.setArguments(args); + + return fragment; + } + + @NonNull + @Override + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final LayoutInflater inflater = LayoutInflater.from(getActivity()); + + // Read button configuration + final Bundle args = getArguments(); + final int index = args.getInt(ARG_INDEX); + final String command = args.getString(ARG_COMMAND); + final int eol = args.getInt(ARG_EOL); + final int iconIndex = args.getInt(ARG_ICON_INDEX); + final boolean active = true; // change to active by default + mActiveIcon = iconIndex; + + // Create view + final View view = inflater.inflate(R.layout.feature_uart_dialog_edit, null); + final EditText field = mField = view.findViewById(R.id.field); + final GridView grid = view.findViewById(R.id.grid); + final CheckBox checkBox = mActiveCheckBox = view.findViewById(R.id.active); + checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> { + field.setEnabled(isChecked); + grid.setEnabled(isChecked); + if (mIconAdapter != null) + mIconAdapter.notifyDataSetChanged(); + }); + + final RadioGroup eolGroup = mEOLGroup = view.findViewById(R.id.uart_eol); + switch (Command.Eol.values()[eol]) { + case CR_LF: + eolGroup.check(R.id.uart_eol_cr_lf); + break; + case CR: + eolGroup.check(R.id.uart_eol_cr); + break; + case LF: + default: + eolGroup.check(R.id.uart_eol_lf); + break; + } + + field.setText(command); + field.setEnabled(active); + checkBox.setChecked(active); + grid.setOnItemClickListener(this); + grid.setEnabled(active); + grid.setAdapter(mIconAdapter = new IconAdapter()); + + // As we want to have some validation we can't user the DialogInterface.OnClickListener as it's always dismissing the dialog. + final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setCancelable(false).setTitle(R.string.uart_edit_title).setPositiveButton(R.string.ok, null) + .setNegativeButton(R.string.cancel, null).setView(view).show(); + final Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); + okButton.setOnClickListener(this); + return dialog; + } + + @Override + public void onClick(final View v) { + final boolean active = mActiveCheckBox.isChecked(); + final String command = mField.getText().toString(); + int eol; + + switch (mEOLGroup.getCheckedRadioButtonId()) { + case R.id.uart_eol_cr_lf: + eol = Command.Eol.CR_LF.index; + break; + case R.id.uart_eol_cr: + eol = Command.Eol.CR.index; + break; + case R.id.uart_eol_lf: + default: + eol = Command.Eol.LF.index; + break; + } + + // Save values + final Bundle args = getArguments(); + final int index = args.getInt(ARG_INDEX); + + dismiss(); + final UARTActivity parent = (UARTActivity) getActivity(); + parent.onCommandChanged(index, command, active, eol, mActiveIcon); + } + + @Override + public void onItemClick(final AdapterView parent, final View view, final int position, final long id) { + mActiveIcon = position; + mIconAdapter.notifyDataSetChanged(); + } + + private class IconAdapter extends BaseAdapter { + private final int SIZE = 20; + + @Override + public int getCount() { + return SIZE; + } + + @Override + public Object getItem(final int position) { + return position; + } + + @Override + public long getItemId(final int position) { + return position; + } + + @Override + public View getView(final int position, final View convertView, final ViewGroup parent) { + View view = convertView; + if (view == null) { + view = LayoutInflater.from(getActivity()).inflate(R.layout.feature_uart_dialog_edit_icon, parent, false); + } + final ImageView image = (ImageView) view; + image.setImageLevel(position); + image.setActivated(position == mActiveIcon && mActiveCheckBox.isChecked()); + return view; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTInterface.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTInterface.java new file mode 100644 index 0000000..6619ca5 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTInterface.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + + +public interface UARTInterface { + + void send(final String text); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLocalLogContentProvider.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLocalLogContentProvider.java new file mode 100644 index 0000000..c196a36 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLocalLogContentProvider.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.net.Uri; + +import no.nordicsemi.android.log.localprovider.LocalLogContentProvider; + +public class UARTLocalLogContentProvider extends LocalLogContentProvider { + /** The authority for the contacts provider. */ + public final static String AUTHORITY = "no.nordicsemi.android.nrftoolbox.uart.log"; + /** A content:// style uri to the authority for the log provider. */ + public final static Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY); + + @Override + protected Uri getAuthorityUri() { + return AUTHORITY_URI; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogAdapter.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogAdapter.java new file mode 100644 index 0000000..ffaa413 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogAdapter.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.content.Context; +import android.database.Cursor; +import android.graphics.Color; +import androidx.annotation.NonNull; +import android.util.SparseIntArray; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.TextView; + +import java.util.Calendar; + +import no.nordicsemi.android.log.LogContract.Log.Level; +import no.nordicsemi.android.nrftoolbox.R; + +public class UARTLogAdapter extends CursorAdapter { + private static final SparseIntArray mColors = new SparseIntArray(); + + static { + mColors.put(Level.DEBUG, 0xFF009CDE); + mColors.put(Level.VERBOSE, 0xFFB8B056); + mColors.put(Level.INFO, Color.BLACK); + mColors.put(Level.APPLICATION, 0xFF238C0F); + mColors.put(Level.WARNING, 0xFFD77926); + mColors.put(Level.ERROR, Color.RED); + } + + UARTLogAdapter(@NonNull final Context context) { + super(context, null, 0); + } + + @Override + public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { + final View view = LayoutInflater.from(context).inflate(R.layout.log_item, parent, false); + + final ViewHolder holder = new ViewHolder(); + holder.time = view.findViewById(R.id.time); + holder.data = view.findViewById(R.id.data); + view.setTag(holder); + return view; + } + + @Override + public void bindView(final View view, final Context context, final Cursor cursor) { + final ViewHolder holder = (ViewHolder) view.getTag(); + final Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(cursor.getLong(1 /* TIME */)); + holder.time.setText(context.getString(R.string.log, calendar)); + + final int level = cursor.getInt(2 /* LEVEL */); + holder.data.setText(cursor.getString(3 /* DATA */)); + holder.data.setTextColor(mColors.get(level)); + } + + @Override + public boolean isEnabled(int position) { + return false; + } + + private class ViewHolder { + private TextView time; + private TextView data; + } + +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogFragment.java new file mode 100644 index 0000000..bf2f511 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogFragment.java @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.ServiceConnection; +import android.database.Cursor; +import android.os.Bundle; +import android.os.IBinder; +import androidx.annotation.NonNull; +import androidx.fragment.app.ListFragment; +import androidx.loader.app.LoaderManager; +import androidx.loader.content.CursorLoader; +import androidx.loader.content.Loader; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.CursorAdapter; +import android.widget.EditText; +import android.widget.ListView; + +import no.nordicsemi.android.log.ILogSession; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; + +public class UARTLogFragment extends ListFragment implements LoaderManager.LoaderCallbacks { + private static final String SIS_LOG_SCROLL_POSITION = "sis_scroll_position"; + private static final int LOG_SCROLL_NULL = -1; + private static final int LOG_SCROLLED_TO_BOTTOM = -2; + + private static final int LOG_REQUEST_ID = 1; + private static final String[] LOG_PROJECTION = {LogContract.Log._ID, LogContract.Log.TIME, LogContract.Log.LEVEL, LogContract.Log.DATA}; + + /** + * The service UART interface that may be used to send data to the target. + */ + private UARTInterface mUARTInterface; + /** + * The adapter used to populate the list with log entries. + */ + private CursorAdapter mLogAdapter; + /** + * The log session created to log events related with the target device. + */ + private ILogSession mLogSession; + + private EditText mField; + private Button mSendButton; + + /** + * The last list view position. + */ + private int mLogScrollPosition; + + /** + * The receiver that listens for {@link BleProfileService#BROADCAST_CONNECTION_STATE} action. + */ + private final BroadcastReceiver mCommonBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + // This receiver listens only for the BleProfileService.BROADCAST_CONNECTION_STATE action, no need to check it. + final int state = intent.getIntExtra(BleProfileService.EXTRA_CONNECTION_STATE, BleProfileService.STATE_DISCONNECTED); + + switch (state) { + case BleProfileService.STATE_CONNECTED: { + onDeviceConnected(); + break; + } + case BleProfileService.STATE_DISCONNECTED: { + onDeviceDisconnected(); + break; + } + case BleProfileService.STATE_CONNECTING: + case BleProfileService.STATE_DISCONNECTING: + // current implementation does nothing in this states + default: + // there should be no other actions + break; + } + } + }; + + private ServiceConnection mServiceConnection = new ServiceConnection() { + @Override + public void onServiceConnected(final ComponentName name, final IBinder service) { + final UARTService.UARTBinder bleService = (UARTService.UARTBinder) service; + mUARTInterface = bleService; + mLogSession = bleService.getLogSession(); + + // Start the loader + if (mLogSession != null) { + getLoaderManager().restartLoader(LOG_REQUEST_ID, null, UARTLogFragment.this); + } + + // and notify user if device is connected + if (bleService.isConnected()) + onDeviceConnected(); + } + + @Override + public void onServiceDisconnected(final ComponentName name) { + onDeviceDisconnected(); + mUARTInterface = null; + } + }; + + @Override + public void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + LocalBroadcastManager.getInstance(requireContext()).registerReceiver(mCommonBroadcastReceiver, makeIntentFilter()); + + // Load the last log list view scroll position + if (savedInstanceState != null) { + mLogScrollPosition = savedInstanceState.getInt(SIS_LOG_SCROLL_POSITION); + } + } + + @Override + public void onStart() { + super.onStart(); + + /* + * If the service has not been started before the following lines will not start it. However, if it's running, the Activity will be bound to it + * and notified via mServiceConnection. + */ + final Intent service = new Intent(getActivity(), UARTService.class); + requireActivity().bindService(service, mServiceConnection, 0); // we pass 0 as a flag so the service will not be created if not exists + } + + @Override + public void onStop() { + super.onStop(); + + try { + requireActivity().unbindService(mServiceConnection); + mUARTInterface = null; + } catch (final IllegalArgumentException e) { + // do nothing, we were not connected to the sensor + } + } + + @Override + public void onSaveInstanceState(@NonNull final Bundle outState) { + super.onSaveInstanceState(outState); + + // Save the last log list view scroll position + final ListView list = getListView(); + final boolean scrolledToBottom = list.getCount() > 0 && list.getLastVisiblePosition() == list.getCount() - 1; + outState.putInt(SIS_LOG_SCROLL_POSITION, scrolledToBottom ? LOG_SCROLLED_TO_BOTTOM : list.getFirstVisiblePosition()); + } + + @Override + public void onDestroy() { + LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(mCommonBroadcastReceiver); + super.onDestroy(); + } + + @Override + public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { + final View view = inflater.inflate(R.layout.fragment_feature_uart_log, container, false); + + final EditText field = mField = view.findViewById(R.id.field); + field.setOnEditorActionListener((v, actionId, event) -> { + if (actionId == EditorInfo.IME_ACTION_SEND) { + onSendClicked(); + return true; + } + return false; + }); + + final Button sendButton = mSendButton = view.findViewById(R.id.action_send); + sendButton.setOnClickListener(v -> onSendClicked()); + return view; + } + + @Override + public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + // Create the log adapter, initially with null cursor + mLogAdapter = new UARTLogAdapter(requireContext()); + setListAdapter(mLogAdapter); + } + + @NonNull + @Override + public Loader onCreateLoader(final int id, final Bundle args) { + switch (id) { + case LOG_REQUEST_ID: { + return new CursorLoader(requireContext(), mLogSession.getSessionEntriesUri(), LOG_PROJECTION, null, null, LogContract.Log.TIME); + } + } + throw new UnsupportedOperationException("Could not create loader with ID " + id); + } + + @Override + public void onLoadFinished(@NonNull final Loader loader, final Cursor data) { + // Here we have to restore the old saved scroll position, or scroll to the bottom if before adding new events it was scrolled to the bottom. + final ListView list = getListView(); + final int position = mLogScrollPosition; + final boolean scrolledToBottom = position == LOG_SCROLLED_TO_BOTTOM || (list.getCount() > 0 && list.getLastVisiblePosition() == list.getCount() - 1); + + mLogAdapter.swapCursor(data); + + if (position > LOG_SCROLL_NULL) { + list.setSelectionFromTop(position, 0); + } else { + if (scrolledToBottom) + list.setSelection(list.getCount() - 1); + } + mLogScrollPosition = LOG_SCROLL_NULL; + } + + @Override + public void onLoaderReset(@NonNull final Loader loader) { + mLogAdapter.swapCursor(null); + } + + private void onSendClicked() { + final String text = mField.getText().toString(); + + mUARTInterface.send(text); + + mField.setText(null); + mField.requestFocus(); + } + + /** + * Method called when user selected a device on the scanner dialog after the service has been started. + * Here we may bind this fragment to it. + */ + public void onServiceStarted() { + // The service has been started, bind to it + final Intent service = new Intent(getActivity(), UARTService.class); + requireActivity().bindService(service, mServiceConnection, 0); + } + + /** + * This method is called when user closes the pane in horizontal orientation. The EditText is no longer visible so we need to close the soft keyboard here. + */ + public void onFragmentHidden() { + final InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null) { + imm.hideSoftInputFromWindow(mField.getWindowToken(), 0); + } + } + + /** + * Method called when the target device has connected. + */ + protected void onDeviceConnected() { + mField.setEnabled(true); + mSendButton.setEnabled(true); + } + + /** + * Method called when user disconnected from the target UART device or the connection was lost. + */ + protected void onDeviceDisconnected() { + mField.setEnabled(false); + mSendButton.setEnabled(false); + } + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(BleProfileService.BROADCAST_CONNECTION_STATE); + return intentFilter; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManager.java new file mode 100644 index 0000000..3089ef1 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManager.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import androidx.annotation.NonNull; +import android.text.TextUtils; + +import java.util.UUID; + +import no.nordicsemi.android.ble.WriteRequest; +import no.nordicsemi.android.log.LogContract; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; + +public class UARTManager extends LoggableBleManager { + /** Nordic UART Service UUID */ + private final static UUID UART_SERVICE_UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); + /** RX characteristic UUID */ + private final static UUID UART_RX_CHARACTERISTIC_UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"); + /** TX characteristic UUID */ + private final static UUID UART_TX_CHARACTERISTIC_UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"); + + private BluetoothGattCharacteristic mRXCharacteristic, mTXCharacteristic; + /** + * A flag indicating whether Long Write can be used. It's set to false if the UART RX + * characteristic has only PROPERTY_WRITE_NO_RESPONSE property and no PROPERTY_WRITE. + * If you set it to false here, it will never use Long Write. + * + * TODO change this flag if you don't want to use Long Write even with Write Request. + */ + private boolean mUseLongWrite = true; + + UARTManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BleManagerGattCallback getGattCallback() { + return mGattCallback; + } + + /** + * BluetoothGatt callbacks for connection/disconnection, service discovery, + * receiving indication, etc. + */ + private final BleManagerGattCallback mGattCallback = new BleManagerGattCallback() { + + @Override + protected void initialize() { + setNotificationCallback(mTXCharacteristic) + .with((device, data) -> { + final String text = data.getStringValue(0); + log(LogContract.Log.Level.APPLICATION, "\"" + text + "\" received"); + mCallbacks.onDataReceived(device, text); + }); + requestMtu(260).enqueue(); + enableNotifications(mTXCharacteristic).enqueue(); + } + + @Override + public boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(UART_SERVICE_UUID); + if (service != null) { + mRXCharacteristic = service.getCharacteristic(UART_RX_CHARACTERISTIC_UUID); + mTXCharacteristic = service.getCharacteristic(UART_TX_CHARACTERISTIC_UUID); + } + + boolean writeRequest = false; + boolean writeCommand = false; + if (mRXCharacteristic != null) { + final int rxProperties = mRXCharacteristic.getProperties(); + writeRequest = (rxProperties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0; + writeCommand = (rxProperties & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0; + + // Set the WRITE REQUEST type when the characteristic supports it. + // This will allow to send long write (also if the characteristic support it). + // In case there is no WRITE REQUEST property, this manager will divide texts + // longer then MTU-3 bytes into up to MTU-3 bytes chunks. + if (writeRequest) + mRXCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); + else + mUseLongWrite = false; + } + + return mRXCharacteristic != null && mTXCharacteristic != null && (writeRequest || writeCommand); + } + + @Override + protected void onDeviceDisconnected() { + mRXCharacteristic = null; + mTXCharacteristic = null; + mUseLongWrite = true; + } + }; + + // This has been moved to the service in BleManager v2.0. + /*@Override + protected boolean shouldAutoConnect() { + // We want the connection to be kept + return true; + }*/ + + /** + * Sends the given text to RX characteristic. + * @param text the text to be sent + */ + public void send(final String text) { + // Are we connected? + if (mRXCharacteristic == null) + return; + + if (!TextUtils.isEmpty(text)) { + final WriteRequest request = writeCharacteristic(mRXCharacteristic, text.getBytes()) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.getStringValue(0) + "\" sent")); + if (!mUseLongWrite) { + // This will automatically split the long data into MTU-3-byte long packets. + request.split(); + } + request.enqueue(); + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManagerCallbacks.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManagerCallbacks.java new file mode 100644 index 0000000..4a5bf24 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManagerCallbacks.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.bluetooth.BluetoothDevice; + +import no.nordicsemi.android.ble.BleManagerCallbacks; + +public interface UARTManagerCallbacks extends BleManagerCallbacks { + + void onDataReceived(final BluetoothDevice device, final String data); + + void onDataSent(final BluetoothDevice device, final String data); +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTNewConfigurationDialogFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTNewConfigurationDialogFragment.java new file mode 100644 index 0000000..d6820e0 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTNewConfigurationDialogFragment.java @@ -0,0 +1,134 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.app.Dialog; +import android.content.Context; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.appcompat.app.AlertDialog; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; + +import no.nordicsemi.android.nrftoolbox.R; + +public class UARTNewConfigurationDialogFragment extends DialogFragment implements View.OnClickListener { + private static final String NAME = "name"; + private static final String DUPLICATE = "duplicate"; + + private EditText mEditText; + + private NewConfigurationDialogListener mListener; + + public interface NewConfigurationDialogListener { + /** + * Creates a new configuration with given name. + * @param name the name + * @param duplicate true if configuration is to be duplicated + */ + void onNewConfiguration(final String name, final boolean duplicate); + + /** + * Renames the current configuration with given name. + * @param newName the new name + */ + void onRenameConfiguration(final String newName); + } + + @Override + public void onAttach(final Context context) { + super.onAttach(context); + + if (context instanceof NewConfigurationDialogListener) { + mListener = (NewConfigurationDialogListener) context; + } else { + throw new IllegalArgumentException("The parent activity must implement NewConfigurationDialogListener"); + } + } + + @Override + public void onDetach() { + super.onDetach(); + mListener = null; + } + + public static DialogFragment getInstance(final String name, final boolean duplicate) { + final DialogFragment dialog = new UARTNewConfigurationDialogFragment(); + + final Bundle args = new Bundle(); + args.putString(NAME, name); + args.putBoolean(DUPLICATE, duplicate); + dialog.setArguments(args); + + return dialog; + } + + @Override + @NonNull + public Dialog onCreateDialog(final Bundle savedInstanceState) { + final Context context = getActivity(); + + final Bundle args = getArguments(); + final String oldName = args.getString(NAME); + final boolean duplicate = args.getBoolean(DUPLICATE); + final int titleResId = duplicate || oldName == null ? R.string.uart_new_configuration_title : R.string.uart_rename_configuration_title; + + final LayoutInflater inflater = LayoutInflater.from(getActivity()); + final View view = inflater.inflate(R.layout.feature_uart_dialog_new_configuration, null); + final EditText editText = mEditText = view.findViewById(R.id.name); + editText.setText(args.getString(NAME)); + final View actionClear = view.findViewById(R.id.action_clear); + actionClear.setOnClickListener(v -> editText.setText(null)); + + final AlertDialog dialog = new AlertDialog.Builder(context).setTitle(titleResId).setView(view).setNegativeButton(R.string.cancel, null) + .setPositiveButton(R.string.ok, null).setCancelable(false).show(); // this must be show() or the getButton() below will return null. + + final Button okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); + okButton.setOnClickListener(this); + + return dialog; + } + + @Override + public void onClick(final View v) { + final String newName = mEditText.getText().toString().trim(); + if (TextUtils.isEmpty(newName)) { + mEditText.setError(getString(R.string.uart_empty_name_error)); + return; + } + + final String oldName = getArguments().getString(NAME); + final boolean duplicate = getArguments().getBoolean(DUPLICATE); + + if (duplicate || TextUtils.isEmpty(oldName)) + mListener.onNewConfiguration(newName, duplicate); + else { + mListener.onRenameConfiguration(newName); + } + dismiss(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTService.java new file mode 100644 index 0000000..2e885ff --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTService.java @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import androidx.annotation.NonNull; +import androidx.core.app.NotificationCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.text.TextUtils; +import android.util.Log; + +import com.google.android.gms.common.api.GoogleApiClient; +import com.google.android.gms.wearable.MessageApi; +import com.google.android.gms.wearable.Node; +import com.google.android.gms.wearable.NodeApi; +import com.google.android.gms.wearable.Wearable; + +import no.nordicsemi.android.log.Logger; +import no.nordicsemi.android.nrftoolbox.FeaturesActivity; +import no.nordicsemi.android.nrftoolbox.R; +import no.nordicsemi.android.nrftoolbox.ToolboxApplication; +import no.nordicsemi.android.nrftoolbox.profile.BleProfileService; +import no.nordicsemi.android.nrftoolbox.profile.LoggableBleManager; +import no.nordicsemi.android.nrftoolbox.wearable.common.Constants; + +public class UARTService extends BleProfileService implements UARTManagerCallbacks { + private static final String TAG = "UARTService"; + + public static final String BROADCAST_UART_TX = "no.nordicsemi.android.nrftoolbox.uart.BROADCAST_UART_TX"; + public static final String BROADCAST_UART_RX = "no.nordicsemi.android.nrftoolbox.uart.BROADCAST_UART_RX"; + public static final String EXTRA_DATA = "no.nordicsemi.android.nrftoolbox.uart.EXTRA_DATA"; + + /** A broadcast message with this action and the message in {@link Intent#EXTRA_TEXT} will be sent t the UART device. */ + public final static String ACTION_SEND = "no.nordicsemi.android.nrftoolbox.uart.ACTION_SEND"; + /** A broadcast message with this action is triggered when a message is received from the UART device. */ + private final static String ACTION_RECEIVE = "no.nordicsemi.android.nrftoolbox.uart.ACTION_RECEIVE"; + /** Action send when user press the DISCONNECT button on the notification. */ + public final static String ACTION_DISCONNECT = "no.nordicsemi.android.nrftoolbox.uart.ACTION_DISCONNECT"; + /** A source of an action. */ + public final static String EXTRA_SOURCE = "no.nordicsemi.android.nrftoolbox.uart.EXTRA_SOURCE"; + public final static int SOURCE_NOTIFICATION = 0; + public final static int SOURCE_WEARABLE = 1; + public final static int SOURCE_3RD_PARTY = 2; + + private final static int NOTIFICATION_ID = 349; // random + private final static int OPEN_ACTIVITY_REQ = 67; // random + private final static int DISCONNECT_REQ = 97; // random + + private GoogleApiClient mGoogleApiClient; + private UARTManager mManager; + + private final LocalBinder mBinder = new UARTBinder(); + + public class UARTBinder extends LocalBinder implements UARTInterface { + @Override + public void send(final String text) { + mManager.send(text); + } + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new UARTManager(this); + } + + @Override + protected boolean shouldAutoConnect() { + return true; + } + + @Override + public void onCreate() { + super.onCreate(); + + registerReceiver(mDisconnectActionBroadcastReceiver, new IntentFilter(ACTION_DISCONNECT)); + registerReceiver(mIntentBroadcastReceiver, new IntentFilter(ACTION_SEND)); + + mGoogleApiClient = new GoogleApiClient.Builder(this) + .addApi(Wearable.API) + .build(); + mGoogleApiClient.connect(); + } + + @Override + public void onDestroy() { + // when user has disconnected from the sensor, we have to cancel the notification that we've created some milliseconds before using unbindService + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + unregisterReceiver(mIntentBroadcastReceiver); + + mGoogleApiClient.disconnect(); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + // when the activity rebinds to the service, remove the notification + cancelNotification(); + } + + @Override + protected void onUnbind() { + // when the activity closes we need to show the notification that user is connected to the sensor + createNotification(R.string.uart_notification_connected_message, 0); + } + + @Override + public void onDeviceConnected(@NonNull final BluetoothDevice device) { + super.onDeviceConnected(device); + sendMessageToWearables(Constants.UART.DEVICE_CONNECTED, notNull(getDeviceName())); + } + + @Override + protected boolean stopWhenDisconnected() { + return false; + } + + @Override + public void onDeviceDisconnected(@NonNull final BluetoothDevice device) { + super.onDeviceDisconnected(device); + sendMessageToWearables(Constants.UART.DEVICE_DISCONNECTED, notNull(getDeviceName())); + } + + @Override + public void onLinkLossOccurred(@NonNull final BluetoothDevice device) { + super.onLinkLossOccurred(device); + sendMessageToWearables(Constants.UART.DEVICE_LINKLOSS, notNull(getDeviceName())); + } + + private String notNull(final String name) { + if (!TextUtils.isEmpty(name)) + return name; + return getString(R.string.not_available); + } + + @Override + public void onDataReceived(final BluetoothDevice device, final String data) { + final Intent broadcast = new Intent(BROADCAST_UART_RX); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, data); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + // send the data received to other apps, e.g. the Tasker + final Intent globalBroadcast = new Intent(ACTION_RECEIVE); + globalBroadcast.putExtra(BluetoothDevice.EXTRA_DEVICE, getBluetoothDevice()); + globalBroadcast.putExtra(Intent.EXTRA_TEXT, data); + sendBroadcast(globalBroadcast); + } + + @Override + public void onDataSent(final BluetoothDevice device, final String data) { + final Intent broadcast = new Intent(BROADCAST_UART_TX); + broadcast.putExtra(EXTRA_DEVICE, getBluetoothDevice()); + broadcast.putExtra(EXTRA_DATA, data); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + } + + /** + * Sends the given message to all connected wearables. If the path is equal to {@link Constants.UART#DEVICE_DISCONNECTED} the service will be stopped afterwards. + * @param path message path + * @param message the message + */ + private void sendMessageToWearables(final @NonNull String path, final @NonNull String message) { + if(mGoogleApiClient.isConnected()) { + new Thread(() -> { + NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); + for(Node node : nodes.getNodes()) { + Logger.v(getLogSession(), "[WEAR] Sending message '" + path + "' to " + node.getDisplayName()); + final MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, message.getBytes()).await(); + if(result.getStatus().isSuccess()){ + Logger.i(getLogSession(), "[WEAR] Message sent"); + } else { + Logger.w(getLogSession(), "[WEAR] Sending message failed: " + result.getStatus().getStatusMessage()); + Log.w(TAG, "Failed to send " + path + " to " + node.getDisplayName()); + } + } + if (Constants.UART.DEVICE_DISCONNECTED.equals(path)) + stopService(); + }).start(); + } else { + if (Constants.UART.DEVICE_DISCONNECTED.equals(path)) + stopService(); + } + } + + /** + * Creates the notification + * + * @param messageResId + * message resource id. The message must have one String parameter,
+ * f.e. <string name="name">%s is connected</string> + * @param defaults + * signals that will be used to notify the user + */ + private void createNotification(final int messageResId, final int defaults) { + final Intent parentIntent = new Intent(this, FeaturesActivity.class); + parentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Intent targetIntent = new Intent(this, UARTActivity.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + disconnect.putExtra(EXTRA_SOURCE, SOURCE_NOTIFICATION); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + // both activities above have launchMode="singleTask" in the AndroidManifest.xml file, so if the task is already running, it will be resumed + final PendingIntent pendingIntent = PendingIntent.getActivities(this, OPEN_ACTIVITY_REQ, new Intent[] { parentIntent, targetIntent }, PendingIntent.FLAG_UPDATE_CURRENT); + final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ToolboxApplication.CONNECTED_DEVICE_CHANNEL); + builder.setContentIntent(pendingIntent); + builder.setContentTitle(getString(R.string.app_name)).setContentText(getString(messageResId, getDeviceName())); + builder.setSmallIcon(R.drawable.ic_stat_notify_uart); + builder.setShowWhen(defaults != 0).setDefaults(defaults).setAutoCancel(true).setOngoing(true); + builder.addAction(new NotificationCompat.Action(R.drawable.ic_action_bluetooth, getString(R.string.uart_notification_action_disconnect), disconnectAction)); + + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + /** + * Cancels the existing notification. If there is no active notification this method does nothing + */ + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + /** + * This broadcast receiver listens for {@link #ACTION_DISCONNECT} that may be fired by pressing Disconnect action button on the notification. + */ + private final BroadcastReceiver mDisconnectActionBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final int source = intent.getIntExtra(EXTRA_SOURCE, SOURCE_NOTIFICATION); + switch (source) { + case SOURCE_NOTIFICATION: + Logger.i(getLogSession(), "[Notification] Disconnect action pressed"); + break; + case SOURCE_WEARABLE: + Logger.i(getLogSession(), "[WEAR] '" + Constants.ACTION_DISCONNECT + "' message received"); + break; + } + if (isConnected()) + getBinder().disconnect(); + else + stopSelf(); + } + }; + + /** + * Broadcast receiver that listens for {@link #ACTION_SEND} from other apps. Sends the String or int content of the {@link Intent#EXTRA_TEXT} extra to the remote device. + * The integer content will be sent as String (65 -> "65", not 65 -> "A"). + */ + private BroadcastReceiver mIntentBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(final Context context, final Intent intent) { + final boolean hasMessage = intent.hasExtra(Intent.EXTRA_TEXT); + if (hasMessage) { + String message = intent.getStringExtra(Intent.EXTRA_TEXT); + if (message == null) { + final int intValue = intent.getIntExtra(Intent.EXTRA_TEXT, Integer.MIN_VALUE); // how big is the chance of such data? + if (intValue != Integer.MIN_VALUE) + message = String.valueOf(intValue); + } + + if (message != null) { + final int source = intent.getIntExtra(EXTRA_SOURCE, SOURCE_3RD_PARTY); + switch (source) { + case SOURCE_WEARABLE: + Logger.i(getLogSession(), "[WEAR] '" + Constants.UART.COMMAND + "' message received with data: \"" + message + "\""); + break; + case SOURCE_3RD_PARTY: + default: + Logger.i(getLogSession(), "[Broadcast] " + ACTION_SEND + " broadcast received with data: \"" + message + "\""); + break; + } + mManager.send(message); + return; + } + } + // No data od incompatible type of EXTRA_TEXT + if (!hasMessage) + Logger.i(getLogSession(), "[Broadcast] " + ACTION_SEND + " broadcast received no data."); + else + Logger.i(getLogSession(), "[Broadcast] " + ACTION_SEND + " broadcast received incompatible data type. Only String and int are supported."); + } + }; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/ConfigurationContract.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/ConfigurationContract.java new file mode 100644 index 0000000..c0a40d1 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/ConfigurationContract.java @@ -0,0 +1,38 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ +package no.nordicsemi.android.nrftoolbox.uart.database; + +import android.provider.BaseColumns; + +public class ConfigurationContract { + + protected interface ConfigurationColumns { + /** The XML with configuration. */ + String XML = "xml"; + } + + public final class Configuration implements BaseColumns, NameColumns, ConfigurationColumns, UndoColumns { + private Configuration() { + // empty + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/DatabaseHelper.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/DatabaseHelper.java new file mode 100644 index 0000000..e636aaf --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/DatabaseHelper.java @@ -0,0 +1,259 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ +package no.nordicsemi.android.nrftoolbox.uart.database; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.provider.BaseColumns; + +public class DatabaseHelper { + /** Database file name */ + private static final String DATABASE_NAME = "toolbox_uart.db"; + /** Database version */ + private static final int DATABASE_VERSION = 1; + + private interface Tables { + /** Configurations table. See {@link ConfigurationContract.Configuration} for column names. */ + String CONFIGURATIONS = "configurations"; + } + + private static final String[] ID_PROJECTION = new String[] { BaseColumns._ID }; + private static final String[] NAME_PROJECTION = new String[] { BaseColumns._ID, NameColumns.NAME }; + private static final String[] XML_PROJECTION = new String[] { BaseColumns._ID, ConfigurationContract.Configuration.XML }; + private static final String[] CONFIGURATION_PROJECTION = new String[] { BaseColumns._ID, NameColumns.NAME, ConfigurationContract.Configuration.XML }; + + private static final String ID_SELECTION = BaseColumns._ID + "=?"; + private static final String NAME_SELECTION = NameColumns.NAME + "=?"; + private static final String DELETED_SELECTION = UndoColumns.DELETED + "=1"; + private static final String NOT_DELETED_SELECTION = UndoColumns.DELETED + "=0"; + + private static SQLiteHelper mDatabaseHelper; + private static SQLiteDatabase mDatabase; + private final ContentValues mValues = new ContentValues(); + private final String[] mSingleArg = new String[1]; + + public DatabaseHelper(final Context context) { + if (mDatabaseHelper == null) { + mDatabaseHelper = new SQLiteHelper(context); + mDatabase = mDatabaseHelper.getWritableDatabase(); + } + } + + /** + * Returns number of saved configurations. + */ + public int getConfigurationsCount() { + final Cursor cursor = mDatabase.query(Tables.CONFIGURATIONS, ID_PROJECTION, NOT_DELETED_SELECTION, null, null, null, null); + try { + return cursor.getCount(); + } finally { + cursor.close(); + } + } + + /** + * Returns the list of all saved configurations. + * @return cursor + */ + public Cursor getConfigurations() { + return mDatabase.query(Tables.CONFIGURATIONS, CONFIGURATION_PROJECTION, NOT_DELETED_SELECTION, null, null, null, ConfigurationContract.Configuration.NAME + " ASC"); + } + + /** + * Returns the list of names of all saved configurations. + * @return cursor + */ + public Cursor getConfigurationsNames() { + return mDatabase.query(Tables.CONFIGURATIONS, NAME_PROJECTION, NOT_DELETED_SELECTION, null, null, null, ConfigurationContract.Configuration.NAME + " ASC"); + } + + /** + * Returns the XML wth the configuration by id. + * @param id the configuration id in the DB + * @return the XML with configuration or null + */ + public String getConfiguration(final long id) { + mSingleArg[0] = String.valueOf(id); + + final Cursor cursor = mDatabase.query(Tables.CONFIGURATIONS, XML_PROJECTION, ID_SELECTION, mSingleArg, null, null, null); + try { + if (cursor.moveToNext()) + return cursor.getString(1 /* XML */); + return null; + } finally { + cursor.close(); + } + } + + /** + * Adds new configuration to the database. + * @param name the configuration name + * @param configuration the XML + * @return the id or -1 if error occurred + */ + public long addConfiguration(final String name, final String configuration) { + final ContentValues values = mValues; + values.clear(); + values.put(ConfigurationContract.Configuration.NAME, name); + values.put(ConfigurationContract.Configuration.XML, configuration); + values.put(ConfigurationContract.Configuration.DELETED, 0); + return mDatabase.replace(Tables.CONFIGURATIONS, null, values); + } + + /** + * Updates the configuration with the given name with the new XML + * @param name the configuration name to be updated + * @param configuration the new XML with configuration + * @return number of rows updated + */ + public int updateConfiguration(final String name, final String configuration) { + mSingleArg[0] = name; + + final ContentValues values = mValues; + values.clear(); + values.put(ConfigurationContract.Configuration.XML, configuration); + values.put(ConfigurationContract.Configuration.DELETED, 0); + return mDatabase.update(Tables.CONFIGURATIONS, values, NAME_SELECTION, mSingleArg); + } + + /** + * Marks the configuration with given name as deleted. If may be restored or removed permanently afterwards. + * @param name the configuration name + * @return id of the deleted configuration + */ + public long deleteConfiguration(final String name) { + mSingleArg[0] = name; + + final ContentValues values = mValues; + values.clear(); + values.put(ConfigurationContract.Configuration.DELETED, 1); + mDatabase.update(Tables.CONFIGURATIONS, values, NAME_SELECTION, mSingleArg); + + final Cursor cursor = mDatabase.query(Tables.CONFIGURATIONS, ID_PROJECTION, NAME_SELECTION, mSingleArg, null, null, null); + try { + if (cursor.moveToNext()) + return cursor.getLong(0 /* _ID */); + return -1; + } finally { + cursor.close(); + } + } + + public int removeDeletedServerConfigurations() { + return mDatabase.delete(Tables.CONFIGURATIONS, DELETED_SELECTION, null); + } + + /** + * Restores deleted configuration. Returns the ID of the first one. + * @return the DI of the restored configuration. + */ + public long restoreDeletedServerConfiguration(final String name) { + mSingleArg[0] = name; + + final ContentValues values = mValues; + values.clear(); + values.put(ConfigurationContract.Configuration.DELETED, 0); + mDatabase.update(Tables.CONFIGURATIONS, values, NAME_SELECTION, mSingleArg); + + final Cursor cursor = mDatabase.query(Tables.CONFIGURATIONS, ID_PROJECTION, NAME_SELECTION, mSingleArg, null, null, null); + try { + if (cursor.moveToNext()) + return cursor.getLong(0 /* _ID */); + return -1; + } finally { + cursor.close(); + } + } + + /** + * Renames the server configuration and replaces its XML (name inside has changed). + * @param oldName the old name to look for + * @param newName the new configuration name + * @param configuration the new XML + * @return number of rows affected + */ + public int renameConfiguration(final String oldName, final String newName, final String configuration) { + mSingleArg[0] = oldName; + + final ContentValues values = mValues; + values.clear(); + values.put(ConfigurationContract.Configuration.NAME, newName); + values.put(ConfigurationContract.Configuration.XML, configuration); + return mDatabase.update(Tables.CONFIGURATIONS, values, NAME_SELECTION, mSingleArg); + } + + /** + * Returns true if a configuration with given name was found in the database. + * @param name the name to check + * @return true if such name exists, false otherwise + */ + public boolean configurationExists(final String name) { + mSingleArg[0] = name; + + final Cursor cursor = mDatabase.query(Tables.CONFIGURATIONS, NAME_PROJECTION, NAME_SELECTION + " AND " + NOT_DELETED_SELECTION, mSingleArg, null, null, null); + try { + return cursor.getCount() > 0; + } finally { + cursor.close(); + } + } + + private class SQLiteHelper extends SQLiteOpenHelper { + + /** + * The SQL code that creates the Server Configurations: + * + *
+		 * ----------------------------------------------------------------------------
+		 *                            CONFIGURATIONS                           |
+		 * ----------------------------------------------------------------------------
+		 * | _id (int, pk, auto increment) | name (text) | xml (text) | deleted (int) |
+		 * ----------------------------------------------------------------------------
+		 * 
+ */ + private static final String CREATE_CONFIGURATIONS = "CREATE TABLE " + Tables.CONFIGURATIONS+ "(" + ConfigurationContract.Configuration._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + + ConfigurationContract.Configuration.NAME + " TEXT UNIQUE NOT NULL, " + ConfigurationContract.Configuration.XML + " TEXT NOT NULL, " + ConfigurationContract.Configuration.DELETED +" INTEGER NOT NULL DEFAULT(0))"; + + private static final String DROP_IF_EXISTS = "DROP TABLE IF EXISTS "; + + public SQLiteHelper(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onCreate(final SQLiteDatabase db) { + db.execSQL(CREATE_CONFIGURATIONS); + } + + @Override + public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { + // This method does nothing for now. + switch (oldVersion) { + case 1: + // do nothing + } + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/NameColumns.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/NameColumns.java new file mode 100644 index 0000000..65aba51 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/NameColumns.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart.database; + +public interface NameColumns { + /** The name */ + String NAME = "name"; +} \ No newline at end of file diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/UndoColumns.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/UndoColumns.java new file mode 100644 index 0000000..12ff898 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/UndoColumns.java @@ -0,0 +1,27 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ +package no.nordicsemi.android.nrftoolbox.uart.database; + +public interface UndoColumns { + /** The 'deleted' flag */ + String DELETED = "deleted"; +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/Command.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/Command.java new file mode 100644 index 0000000..e364c55 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/Command.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart.domain; + +import org.simpleframework.xml.Attribute; +import org.simpleframework.xml.Root; +import org.simpleframework.xml.Text; + +@Root +public class Command { + public enum Icon { + LEFT(0), + UP(1), + RIGHT(2), + DOWN(3), + SETTINGS(4), + REW(5), + PLAY(6), + PAUSE(7), + STOP(8), + FWD(9), + INFO(10), + NUMBER_1(11), + NUMBER_2(12), + NUMBER_3(13), + NUMBER_4(14), + NUMBER_5(15), + NUMBER_6(16), + NUMBER_7(17), + NUMBER_8(18), + NUMBER_9(19); + + public final int index; + + Icon(final int index) { + this.index = index; + } + } + + public enum Eol { + LF(0), + CR(1), + CR_LF(2); + + public final int index; + + Eol(final int index) { + this.index = index; + } + } + + @Text(required = false) + private String command; + + @Attribute(required = false) + private boolean active = false; + + @Attribute(required = false) + private Eol eol = Eol.LF; + + @Attribute(required = false) + private Icon icon = Icon.LEFT; + + /** + * Sets the command. + * @param command the command that will be sent to UART device + */ + public void setCommand(final String command) { + this.command = command; + } + + /** + * Sets whether the command is active. + * @param active true to make it active + */ + public void setActive(final boolean active) { + this.active = active; + } + + /** + * Sets the new line type. + * @param eol end of line terminator + */ + public void setEol(final int eol) { + this.eol = Eol.values()[eol]; + } + + /** + * Sets the icon index. + * @param index index of the icon. + */ + public void setIconIndex(final int index) { + this.icon = Icon.values()[index]; + } + + /** + * Returns the command that will be sent to UART device. + * @return the command + */ + public String getCommand() { + return command; + } + + /** + * Returns whether the icon is active. + * @return true if it's active + */ + public boolean isActive() { + return active; + } + + /** + * Returns the new line type. + * @return end of line terminator + */ + public Eol getEol() { + return eol; + } + + /** + * Returns the icon index. + * @return the icon index + */ + public int getIconIndex() { + return icon.index; + } + /** + * Returns the EOL index. + * @return the EOL index + */ + public int getEolIndex() { + return eol.index; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/UartConfiguration.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/UartConfiguration.java new file mode 100644 index 0000000..981f48c --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/UartConfiguration.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart.domain; + +import org.simpleframework.xml.Attribute; +import org.simpleframework.xml.ElementArray; +import org.simpleframework.xml.Root; +import org.simpleframework.xml.core.PersistenceException; +import org.simpleframework.xml.core.Validate; + +@Root +public class UartConfiguration { + public static final int COMMANDS_COUNT = 9; + + @Attribute(required = false, empty = "Unnamed") + private String name; + + @ElementArray + private Command[] commands = new Command[COMMANDS_COUNT]; + + /** + * Returns the field name + * + * @return optional name + */ + public String getName() { + return name; + } + + /** + * Sets the name to specified value + * @param name the new name + */ + public void setName(final String name) { + this.name = name; + } + + /** + * Returns the array of commands. There is always 9 of them. + * @return the commands array + */ + public Command[] getCommands() { + return commands; + } + + @Validate + private void validate() throws PersistenceException{ + if (commands == null || commands.length != COMMANDS_COUNT) + throw new PersistenceException("There must be always " + COMMANDS_COUNT + " commands in a configuration."); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/wearable/UARTConfigurationSynchronizer.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/wearable/UARTConfigurationSynchronizer.java new file mode 100644 index 0000000..696a078 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/wearable/UARTConfigurationSynchronizer.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.uart.wearable; + +import android.content.Context; +import android.net.Uri; + +import com.google.android.gms.common.api.GoogleApiClient; +import com.google.android.gms.common.api.PendingResult; +import com.google.android.gms.wearable.DataApi; +import com.google.android.gms.wearable.DataMap; +import com.google.android.gms.wearable.PutDataMapRequest; +import com.google.android.gms.wearable.PutDataRequest; +import com.google.android.gms.wearable.Wearable; + +import java.util.ArrayList; + +import no.nordicsemi.android.nrftoolbox.uart.domain.Command; +import no.nordicsemi.android.nrftoolbox.uart.domain.UartConfiguration; +import no.nordicsemi.android.nrftoolbox.wearable.common.Constants; + +public class UARTConfigurationSynchronizer { + private static final String WEAR_URI_PREFIX = "wear:"; // no / at the end as the path already has it + + private static UARTConfigurationSynchronizer mInstance; + private GoogleApiClient mGoogleApiClient; + + /** + * Initializes the synchronizer. + * @param context the activity context + * @param listener the connection callbacks listener + */ + public static UARTConfigurationSynchronizer from(final Context context, final GoogleApiClient.ConnectionCallbacks listener) { + if (mInstance == null) + mInstance = new UARTConfigurationSynchronizer(); + + mInstance.init(context, listener); + return mInstance; + } + + private UARTConfigurationSynchronizer() { + // private constructor + } + + private void init(final Context context, final GoogleApiClient.ConnectionCallbacks listener) { + if (mGoogleApiClient != null) + return; + + mGoogleApiClient = new GoogleApiClient.Builder(context) + .addApiIfAvailable(Wearable.API) + .addConnectionCallbacks(listener) + .build(); + mGoogleApiClient.connect(); + } + + /** + * Closes the synchronizer. + */ + public void close() { + if (mGoogleApiClient != null) + mGoogleApiClient.disconnect(); + mGoogleApiClient = null; + } + + /** + * Returns true if Wearable API has been connected. + */ + public boolean hasConnectedApi() { + return mGoogleApiClient != null && mGoogleApiClient.isConnected() && mGoogleApiClient.hasConnectedApi(Wearable.API); + } + + /** + * Synchronizes the UART configurations between handheld and wearables. + * Call this when configuration has been created or altered. + * @return pending result + */ + public PendingResult onConfigurationAddedOrEdited(final long id, final UartConfiguration configuration) { + if (!hasConnectedApi()) + return null; + + final PutDataMapRequest mapRequest = PutDataMapRequest.create(Constants.UART.CONFIGURATIONS + "/" + id); + final DataMap map = mapRequest.getDataMap(); + map.putString(Constants.UART.Configuration.NAME, configuration.getName()); + final ArrayList commands = new ArrayList<>(UartConfiguration.COMMANDS_COUNT); + for (Command command : configuration.getCommands()) { + if (command != null && command.isActive()) { + final DataMap item = new DataMap(); + item.putInt(Constants.UART.Configuration.Command.ICON_ID, command.getIconIndex()); + item.putString(Constants.UART.Configuration.Command.MESSAGE, command.getCommand()); + item.putInt(Constants.UART.Configuration.Command.EOL, command.getEolIndex()); + commands.add(item); + } + } + map.putDataMapArrayList(Constants.UART.Configuration.COMMANDS, commands); + final PutDataRequest request = mapRequest.asPutDataRequest(); + return Wearable.DataApi.putDataItem(mGoogleApiClient, request); + } + + /** + * Synchronizes the UART configurations between handheld and wearables. + * Call this when configuration has been deleted. + * @return pending result + */ + public PendingResult onConfigurationDeleted(final long id) { + if (!hasConnectedApi()) + return null; + return Wearable.DataApi.deleteDataItems(mGoogleApiClient, id2Uri(id)); + } + + /** + * Creates URI without nodeId. + * @param id the configuration id in the database + * @return Uri that may be used to delete the associated DataMap. + */ + private Uri id2Uri(final long id) { + return Uri.parse(WEAR_URI_PREFIX + Constants.UART.CONFIGURATIONS + "/" + id); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/FileHelper.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/FileHelper.java new file mode 100644 index 0000000..a0aef68 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/FileHelper.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.utility; + +import android.content.ContentValues; +import android.content.Context; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.net.Uri; +import android.os.Environment; +import android.preference.PreferenceManager; +import android.provider.BaseColumns; +import android.provider.MediaStore; +import android.widget.Toast; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import no.nordicsemi.android.nrftoolbox.R; + +public class FileHelper { + private static final String TAG = "FileHelper"; + + private static final String PREFS_SAMPLES_VERSION = "no.nordicsemi.android.nrftoolbox.dfu.PREFS_SAMPLES_VERSION"; + private static final int CURRENT_SAMPLES_VERSION = 4; + + public static final String NORDIC_FOLDER = "Nordic Semiconductor"; + public static final String UART_FOLDER = "UART Configurations"; + public static final String BOARD_FOLDER = "Board"; + public static final String BOARD_NRF6310_FOLDER = "nrf6310"; + public static final String BOARD_PCA10028_FOLDER = "pca10028"; + public static final String BOARD_PCA10036_FOLDER = "pca10036"; + + public static boolean newSamplesAvailable(final Context context) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final int version = preferences.getInt(PREFS_SAMPLES_VERSION, 0); + return version < CURRENT_SAMPLES_VERSION; + } + + public static void createSamples(final Context context) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final int version = preferences.getInt(PREFS_SAMPLES_VERSION, 0); + if (version == CURRENT_SAMPLES_VERSION) + return; + + /* + * Copy example HEX files to the external storage. Files will be copied if the DFU Applications folder is missing + */ + final File root = new File(Environment.getExternalStorageDirectory(), "Nordic Semiconductor"); + if (!root.exists()) { + root.mkdir(); + } + final File board = new File(root, "Board"); + if (!board.exists()) { + board.mkdir(); + } + final File nrf6310 = new File(board, "nrf6310"); + if (!nrf6310.exists()) { + nrf6310.mkdir(); + } + final File pca10028 = new File(board, "pca10028"); + if (!pca10028.exists()) { + pca10028.mkdir(); + } + + // Remove old files. Those will be moved to a new folder structure + new File(root, "ble_app_hrs_s110_v6_0_0.hex").delete(); + new File(root, "ble_app_rscs_s110_v6_0_0.hex").delete(); + new File(root, "ble_app_hrs_s110_v7_0_0.hex").delete(); + new File(root, "ble_app_rscs_s110_v7_0_0.hex").delete(); + new File(root, "blinky_arm_s110_v7_0_0.hex").delete(); + new File(root, "dfu_2_0.bat").delete(); // This file has been migrated to 3.0 + new File(root, "dfu_3_0.bat").delete(); // This file has been migrated to 3.1 + new File(root, "dfu_2_0.sh").delete(); // This file has been migrated to 3.0 + new File(root, "dfu_3_0.sh").delete(); // This file has been migrated to 3.1 + new File(root, "README.txt").delete(); // This file has been modified to match v.3.0+ + + boolean oldCopied = false; + boolean newCopied = false; + + // nrf6310 files + File f = new File(nrf6310, "ble_app_hrs_s110_v6_0_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_s110_v6_0_0, f); + oldCopied = true; + } + f = new File(nrf6310, "ble_app_rscs_s110_v6_0_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_rscs_s110_v6_0_0, f); + oldCopied = true; + } + f = new File(nrf6310, "ble_app_hrs_s110_v7_0_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_s110_v7_0_0, f); + oldCopied = true; + } + f = new File(nrf6310, "ble_app_rscs_s110_v7_0_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_rscs_s110_v7_0_0, f); + oldCopied = true; + } + f = new File(nrf6310, "blinky_arm_s110_v7_0_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.blinky_arm_s110_v7_0_0, f); + oldCopied = true; + } + // PCA10028 files + f = new File(pca10028, "blinky_s110_v7_1_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.blinky_s110_v7_1_0, f); + oldCopied = true; + } + f = new File(pca10028, "blinky_s110_v7_1_0_ext_init.dat"); + if (!f.exists()) { + copyRawResource(context, R.raw.blinky_s110_v7_1_0_ext_init, f); + oldCopied = true; + } + f = new File(pca10028, "ble_app_hrs_dfu_s110_v7_1_0.hex"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_dfu_s110_v7_1_0, f); + oldCopied = true; + } + f = new File(pca10028, "ble_app_hrs_dfu_s110_v7_1_0_ext_init.dat"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_dfu_s110_v7_1_0_ext_init, f); + oldCopied = true; + } + new File(root, "ble_app_hrs_dfu_s110_v8_0_0.zip").delete(); // name changed + f = new File(pca10028, "ble_app_hrs_dfu_s110_v8_0_0_sdk_v8_0.zip"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_dfu_s110_v8_0_0_sdk_v8_0, f); + newCopied = true; + } + f = new File(pca10028, "ble_app_hrs_dfu_s110_v8_0_0_sdk_v9_0.zip"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_dfu_s110_v8_0_0_sdk_v9_0, f); + newCopied = true; + } + f = new File(pca10028, "ble_app_hrs_dfu_all_in_one_sdk_v9_0.zip"); + if (!f.exists()) { + copyRawResource(context, R.raw.ble_app_hrs_dfu_all_in_one_sdk_v9_0, f); + newCopied = true; + } + + if (oldCopied) + Toast.makeText(context, R.string.dfu_example_files_created, Toast.LENGTH_SHORT).show(); + else if (newCopied) + Toast.makeText(context, R.string.dfu_example_new_files_created, Toast.LENGTH_SHORT).show(); + + // Scripts + newCopied = false; + f = new File(root, "dfu_3_1.bat"); + if (!f.exists()) { + copyRawResource(context, R.raw.dfu_win_3_1, f); + newCopied = true; + } + f = new File(root, "dfu_3_1.sh"); + if (!f.exists()) { + copyRawResource(context, R.raw.dfu_mac_3_1, f); + newCopied = true; + } + f = new File(root, "README.txt"); + if (!f.exists()) { + copyRawResource(context, R.raw.readme, f); + } + if (newCopied) + Toast.makeText(context, R.string.dfu_scripts_created, Toast.LENGTH_SHORT).show(); + + // Save the current version + preferences.edit().putInt(PREFS_SAMPLES_VERSION, CURRENT_SAMPLES_VERSION).apply(); + } + + /** + * Copies the file from res/raw with given id to given destination file. If dest does not exist it will be created. + * + * @param context activity context + * @param rawResId the resource id + * @param dest destination file + */ + private static void copyRawResource(final Context context, final int rawResId, final File dest) { + try { + final InputStream is = context.getResources().openRawResource(rawResId); + final FileOutputStream fos = new FileOutputStream(dest); + + final byte[] buf = new byte[1024]; + int read; + try { + while ((read = is.read(buf)) > 0) + fos.write(buf, 0, read); + } finally { + is.close(); + fos.close(); + } + } catch (final IOException e) { + DebugLogger.e(TAG, "Error while copying HEX file " + e.toString()); + } + } + + public static Uri getContentUri(final Context context, final File file) { + final String filePath = file.getAbsolutePath(); + final Uri uri = MediaStore.Files.getContentUri("external"); + final Cursor cursor = context.getContentResolver().query( + uri, + new String[]{BaseColumns._ID}, + MediaStore.Files.FileColumns.DATA + "=? ", + new String[]{filePath}, null); + try { + if (cursor != null && cursor.moveToFirst()) { + final int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); + return Uri.withAppendedPath(uri, String.valueOf(id)); + } else { + if (file.exists()) { + final ContentValues values = new ContentValues(); + values.put(MediaStore.Files.FileColumns.DATA, filePath); + return context.getContentResolver().insert(uri, values); + } else { + return null; + } + } + } finally { + cursor.close(); + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/ParserUtils.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/ParserUtils.java new file mode 100644 index 0000000..5e11b14 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/ParserUtils.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.utility; + +public class ParserUtils extends no.nordicsemi.android.ble.utils.ParserUtils { + + public static String parseDebug(final byte[] data) { + if (data == null || data.length == 0) + return ""; + + final char[] out = new char[data.length * 2]; + for (int j = 0; j < data.length; j++) { + int v = data[j] & 0xFF; + out[j * 2] = HEX_ARRAY[v >>> 4]; + out[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; + } + return "0x" + new String(out); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/wearable/MainWearableListenerService.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/wearable/MainWearableListenerService.java new file mode 100644 index 0000000..30661f5 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/wearable/MainWearableListenerService.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.wearable; + +import android.content.Intent; + +import com.google.android.gms.wearable.MessageEvent; +import com.google.android.gms.wearable.WearableListenerService; + +import no.nordicsemi.android.nrftoolbox.uart.UARTService; +import no.nordicsemi.android.nrftoolbox.wearable.common.Constants; + +/** + * The main listener for messages from Wearable devices. There may be only one such service per application so it has to handle messages from all profiles. + */ +public class MainWearableListenerService extends WearableListenerService { + + @Override + public void onMessageReceived(final MessageEvent messageEvent) { + switch (messageEvent.getPath()) { + case Constants.ACTION_DISCONNECT: { + // A disconnect message was sent. The information which profile should be disconnected is in the data. + final String profile = new String(messageEvent.getData()); + + switch (profile) { + // Currently only UART profile has Wear support + case Constants.UART.PROFILE: { + final Intent disconnectIntent = new Intent(UARTService.ACTION_DISCONNECT); + disconnectIntent.putExtra(UARTService.EXTRA_SOURCE, UARTService.SOURCE_WEARABLE); + sendBroadcast(disconnectIntent); + break; + } + } + break; + } + case Constants.UART.COMMAND: { + final String command = new String(messageEvent.getData()); + + final Intent intent = new Intent(UARTService.ACTION_SEND); + intent.putExtra(UARTService.EXTRA_SOURCE, UARTService.SOURCE_WEARABLE); + intent.putExtra(Intent.EXTRA_TEXT, command); + sendBroadcast(intent); + } + default: + super.onMessageReceived(messageEvent); + break; + } + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ClosableSpinner.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ClosableSpinner.java new file mode 100644 index 0000000..baf19ed --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ClosableSpinner.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package no.nordicsemi.android.nrftoolbox.widget; + +import android.content.Context; +import android.util.AttributeSet; + +public class ClosableSpinner extends androidx.appcompat.widget.AppCompatSpinner { + public ClosableSpinner(Context context, AttributeSet attrs) { + super(context, attrs); + } + + public void close() { + super.onDetachedFromWindow(); + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/DividerItemDecoration.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/DividerItemDecoration.java new file mode 100644 index 0000000..9d317f6 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/DividerItemDecoration.java @@ -0,0 +1,111 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ + +package no.nordicsemi.android.nrftoolbox.widget; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import android.view.View; + +public class DividerItemDecoration extends RecyclerView.ItemDecoration { + + private static final int[] ATTRS = new int[]{ + android.R.attr.listDivider + }; + + public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; + + public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; + + private Drawable mDivider; + + private int mOrientation; + + public DividerItemDecoration(Context context, int orientation) { + final TypedArray a = context.obtainStyledAttributes(ATTRS); + mDivider = a.getDrawable(0); + a.recycle(); + setOrientation(orientation); + } + + public void setOrientation(int orientation) { + if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { + throw new IllegalArgumentException("invalid orientation"); + } + mOrientation = orientation; + } + + @Override + public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { + if (mOrientation == VERTICAL_LIST) { + drawVertical(c, parent); + } else { + drawHorizontal(c, parent); + } + } + + public void drawVertical(Canvas c, RecyclerView parent) { + final int left = parent.getPaddingLeft(); + final int right = parent.getWidth() - parent.getPaddingRight(); + + final int childCount = parent.getChildCount(); + for (int i = 0; i < childCount; i++) { + final View child = parent.getChildAt(i); + final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child + .getLayoutParams(); + final int top = child.getBottom() + params.bottomMargin; + final int bottom = top + mDivider.getIntrinsicHeight(); + mDivider.setBounds(left, top, right, bottom); + mDivider.draw(c); + } + } + + public void drawHorizontal(Canvas c, RecyclerView parent) { + final int top = parent.getPaddingTop(); + final int bottom = parent.getHeight() - parent.getPaddingBottom(); + + final int childCount = parent.getChildCount(); + for (int i = 0; i < childCount; i++) { + final View child = parent.getChildAt(i); + final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child + .getLayoutParams(); + final int left = child.getRight() + params.rightMargin; + final int right = left + mDivider.getIntrinsicHeight(); + mDivider.setBounds(left, top, right, bottom); + mDivider.draw(c); + } + } + + @Override + public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { + if (mOrientation == VERTICAL_LIST) { + outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); + } else { + outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundLinearLayout.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundLinearLayout.java new file mode 100644 index 0000000..c6e9598 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundLinearLayout.java @@ -0,0 +1,148 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ + +package no.nordicsemi.android.nrftoolbox.widget; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.NinePatchDrawable; +import android.os.Build; +import androidx.annotation.NonNull; +import android.util.AttributeSet; +import android.widget.LinearLayout; + +import no.nordicsemi.android.nrftoolbox.R; + +public class ForegroundLinearLayout extends LinearLayout { + + private Drawable mForegroundSelector; + private Rect mRectPadding; + private boolean mUseBackgroundPadding = false; + + public ForegroundLinearLayout(Context context) { + super(context); + } + + public ForegroundLinearLayout(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public ForegroundLinearLayout(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ForegroundLinearLayout, + defStyle, 0); + + final Drawable d = a.getDrawable(R.styleable.ForegroundRelativeLayout_foreground); + if (d != null) { + setForeground(d); + } + + a.recycle(); + + if (this.getBackground() instanceof NinePatchDrawable) { + final NinePatchDrawable npd = (NinePatchDrawable) this.getBackground(); + mRectPadding = new Rect(); + if (npd.getPadding(mRectPadding)) { + mUseBackgroundPadding = true; + } + } + } + + @Override + protected void drawableStateChanged() { + super.drawableStateChanged(); + + if (mForegroundSelector != null && mForegroundSelector.isStateful()) { + mForegroundSelector.setState(getDrawableState()); + } + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + + if (mForegroundSelector != null) { + if (mUseBackgroundPadding) { + mForegroundSelector.setBounds(mRectPadding.left, mRectPadding.top, w - mRectPadding.right, h - mRectPadding.bottom); + } else { + mForegroundSelector.setBounds(0, 0, w, h); + } + } + } + + @Override + protected void dispatchDraw(@NonNull Canvas canvas) { + super.dispatchDraw(canvas); + + if (mForegroundSelector != null) { + mForegroundSelector.draw(canvas); + } + } + + @Override + protected boolean verifyDrawable(Drawable who) { + return super.verifyDrawable(who) || (who == mForegroundSelector); + } + + @Override + public void jumpDrawablesToCurrentState() { + super.jumpDrawablesToCurrentState(); + if (mForegroundSelector != null) mForegroundSelector.jumpToCurrentState(); + } + + public void setForeground(Drawable drawable) { + if (mForegroundSelector != drawable) { + if (mForegroundSelector != null) { + mForegroundSelector.setCallback(null); + unscheduleDrawable(mForegroundSelector); + } + + mForegroundSelector = drawable; + + if (drawable != null) { + setWillNotDraw(false); + drawable.setCallback(this); + if (drawable.isStateful()) { + drawable.setState(getDrawableState()); + } + } else { + setWillNotDraw(true); + } + requestLayout(); + invalidate(); + } + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + @Override + public void drawableHotspotChanged(float x, float y) { + super.drawableHotspotChanged(x, y); + if (mForegroundSelector != null) { + mForegroundSelector.setHotspot(x, y); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundRelativeLayout.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundRelativeLayout.java new file mode 100644 index 0000000..c3aa280 --- /dev/null +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundRelativeLayout.java @@ -0,0 +1,148 @@ +/************************************************************************************************************************************************* + * Copyright (c) 2015, Nordic Semiconductor + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ************************************************************************************************************************************************/ + +package no.nordicsemi.android.nrftoolbox.widget; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.NinePatchDrawable; +import android.os.Build; +import androidx.annotation.NonNull; +import android.util.AttributeSet; +import android.widget.RelativeLayout; + +import no.nordicsemi.android.nrftoolbox.R; + +public class ForegroundRelativeLayout extends RelativeLayout { + + private Drawable mForegroundSelector; + private Rect mRectPadding; + private boolean mUseBackgroundPadding = false; + + public ForegroundRelativeLayout(Context context) { + super(context); + } + + public ForegroundRelativeLayout(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public ForegroundRelativeLayout(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ForegroundRelativeLayout, + defStyle, 0); + + final Drawable d = a.getDrawable(R.styleable.ForegroundRelativeLayout_foreground); + if (d != null) { + setForeground(d); + } + + a.recycle(); + + if (this.getBackground() instanceof NinePatchDrawable) { + final NinePatchDrawable npd = (NinePatchDrawable) this.getBackground(); + mRectPadding = new Rect(); + if (npd.getPadding(mRectPadding)) { + mUseBackgroundPadding = true; + } + } + } + + @Override + protected void drawableStateChanged() { + super.drawableStateChanged(); + + if (mForegroundSelector != null && mForegroundSelector.isStateful()) { + mForegroundSelector.setState(getDrawableState()); + } + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + + if (mForegroundSelector != null) { + if (mUseBackgroundPadding) { + mForegroundSelector.setBounds(mRectPadding.left, mRectPadding.top, w - mRectPadding.right, h - mRectPadding.bottom); + } else { + mForegroundSelector.setBounds(0, 0, w, h); + } + } + } + + @Override + protected void dispatchDraw(@NonNull Canvas canvas) { + super.dispatchDraw(canvas); + + if (mForegroundSelector != null) { + mForegroundSelector.draw(canvas); + } + } + + @Override + protected boolean verifyDrawable(Drawable who) { + return super.verifyDrawable(who) || (who == mForegroundSelector); + } + + @Override + public void jumpDrawablesToCurrentState() { + super.jumpDrawablesToCurrentState(); + if (mForegroundSelector != null) mForegroundSelector.jumpToCurrentState(); + } + + public void setForeground(Drawable drawable) { + if (mForegroundSelector != drawable) { + if (mForegroundSelector != null) { + mForegroundSelector.setCallback(null); + unscheduleDrawable(mForegroundSelector); + } + + mForegroundSelector = drawable; + + if (drawable != null) { + setWillNotDraw(false); + drawable.setCallback(this); + if (drawable.isStateful()) { + drawable.setState(getDrawableState()); + } + } else { + setWillNotDraw(true); + } + requestLayout(); + invalidate(); + } + } + + @TargetApi(Build.VERSION_CODES.LOLLIPOP) + @Override + public void drawableHotspotChanged(float x, float y) { + super.drawableHotspotChanged(x, y); + if (mForegroundSelector != null) { + mForegroundSelector.setHotspot(x, y); + } + } +} \ No newline at end of file diff --git a/app/src/main/res/animator/click_animator.xml b/app/src/main/res/animator/click_animator.xml new file mode 100644 index 0000000..7b316a4 --- /dev/null +++ b/app/src/main/res/animator/click_animator.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/color/button_color.xml b/app/src/main/res/color/button_color.xml new file mode 100644 index 0000000..2c87a8e --- /dev/null +++ b/app/src/main/res/color/button_color.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/color/menu_text.xml b/app/src/main/res/color/menu_text.xml new file mode 100644 index 0000000..c6d777f --- /dev/null +++ b/app/src/main/res/color/menu_text.xml @@ -0,0 +1,26 @@ + + + + + + diff --git a/app/src/main/res/drawable-hdpi/battery.png b/app/src/main/res/drawable-hdpi/battery.png new file mode 100644 index 0000000..dd83f9b Binary files /dev/null and b/app/src/main/res/drawable-hdpi/battery.png differ diff --git a/app/src/main/res/drawable-hdpi/drawer_shadow.9.png b/app/src/main/res/drawable-hdpi/drawer_shadow.9.png new file mode 100644 index 0000000..236bff5 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/drawer_shadow.9.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_bluetooth.png b/app/src/main/res/drawable-hdpi/ic_action_bluetooth.png new file mode 100644 index 0000000..fce1884 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_bluetooth.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_action_disconnect.png b/app/src/main/res/drawable-hdpi/ic_action_disconnect.png new file mode 100644 index 0000000..e64801e Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_action_disconnect.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_bpm_feature.png b/app/src/main/res/drawable-hdpi/ic_bpm_feature.png new file mode 100644 index 0000000..875f8a2 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_bpm_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_cgms_feature.png b/app/src/main/res/drawable-hdpi/ic_cgms_feature.png new file mode 100644 index 0000000..6e05b92 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_cgms_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_csc_feature.png b/app/src/main/res/drawable-hdpi/ic_csc_feature.png new file mode 100644 index 0000000..8a105bd Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_csc_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_dfu_feature.png b/app/src/main/res/drawable-hdpi/ic_dfu_feature.png new file mode 100644 index 0000000..db59fae Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_dfu_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_glucose_feature.png b/app/src/main/res/drawable-hdpi/ic_glucose_feature.png new file mode 100644 index 0000000..9ea9243 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_glucose_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_help.png b/app/src/main/res/drawable-hdpi/ic_help.png new file mode 100644 index 0000000..459bed7 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_help.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_hrs_feature.png b/app/src/main/res/drawable-hdpi/ic_hrs_feature.png new file mode 100644 index 0000000..650a4da Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_hrs_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_hts_feature.png b/app/src/main/res/drawable-hdpi/ic_hts_feature.png new file mode 100644 index 0000000..de2f119 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_hts_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_proximity_feature.png b/app/src/main/res/drawable-hdpi/ic_proximity_feature.png new file mode 100644 index 0000000..5b80a88 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_proximity_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_rsc_feature.png b/app/src/main/res/drawable-hdpi/ic_rsc_feature.png new file mode 100644 index 0000000..8e45929 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_rsc_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_rssi_0_bar.png b/app/src/main/res/drawable-hdpi/ic_rssi_0_bar.png new file mode 100644 index 0000000..40d094f Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_rssi_0_bar.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_rssi_1_bar.png b/app/src/main/res/drawable-hdpi/ic_rssi_1_bar.png new file mode 100644 index 0000000..72b6996 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_rssi_1_bar.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_rssi_2_bars.png b/app/src/main/res/drawable-hdpi/ic_rssi_2_bars.png new file mode 100644 index 0000000..dfa10ec Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_rssi_2_bars.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_rssi_3_bars.png b/app/src/main/res/drawable-hdpi/ic_rssi_3_bars.png new file mode 100644 index 0000000..ae512db Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_rssi_3_bars.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_cgms.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_cgms.png new file mode 100644 index 0000000..2b783a8 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_cgms.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_csc.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_csc.png new file mode 100644 index 0000000..ddc2e25 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_csc.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_hts.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_hts.png new file mode 100644 index 0000000..4fed093 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_hts.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_proximity.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_proximity.png new file mode 100644 index 0000000..af0b454 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_proximity.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_rsc.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_rsc.png new file mode 100644 index 0000000..14ed163 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_rsc.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_template.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_template.png new file mode 100644 index 0000000..fc09568 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_template.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_notify_uart.png b/app/src/main/res/drawable-hdpi/ic_stat_notify_uart.png new file mode 100644 index 0000000..a081193 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_notify_uart.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_template_feature.png b/app/src/main/res/drawable-hdpi/ic_template_feature.png new file mode 100644 index 0000000..fef8a41 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_template_feature.png differ diff --git a/app/src/main/res/drawable-hdpi/proximity_lock_open.png b/app/src/main/res/drawable-hdpi/proximity_lock_open.png new file mode 100644 index 0000000..e2c0f28 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/proximity_lock_open.png differ diff --git a/app/src/main/res/drawable-hdpi/shadow_l.png b/app/src/main/res/drawable-hdpi/shadow_l.png new file mode 100644 index 0000000..b007003 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/shadow_l.png differ diff --git a/app/src/main/res/drawable-hdpi/shadow_r.png b/app/src/main/res/drawable-hdpi/shadow_r.png new file mode 100644 index 0000000..ae07b59 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/shadow_r.png differ diff --git a/app/src/main/res/drawable-v21/button.xml b/app/src/main/res/drawable-v21/button.xml new file mode 100644 index 0000000..4ce2cf2 --- /dev/null +++ b/app/src/main/res/drawable-v21/button.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/ic_feature_bg.xml b/app/src/main/res/drawable-v21/ic_feature_bg.xml new file mode 100644 index 0000000..28a32b0 --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_feature_bg.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable-v21/ic_icon_button_background.xml b/app/src/main/res/drawable-v21/ic_icon_button_background.xml new file mode 100644 index 0000000..6b1e883 --- /dev/null +++ b/app/src/main/res/drawable-v21/ic_icon_button_background.xml @@ -0,0 +1,18 @@ + + + + diff --git a/app/src/main/res/drawable-v21/uart_button_activated.xml b/app/src/main/res/drawable-v21/uart_button_activated.xml new file mode 100644 index 0000000..e00d0b7 --- /dev/null +++ b/app/src/main/res/drawable-v21/uart_button_activated.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable-v21/uart_button_background.xml b/app/src/main/res/drawable-v21/uart_button_background.xml new file mode 100644 index 0000000..c2a1769 --- /dev/null +++ b/app/src/main/res/drawable-v21/uart_button_background.xml @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable-v21/uart_button_normal.xml b/app/src/main/res/drawable-v21/uart_button_normal.xml new file mode 100644 index 0000000..e754af7 --- /dev/null +++ b/app/src/main/res/drawable-v21/uart_button_normal.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable-xhdpi/app_drive.png b/app/src/main/res/drawable-xhdpi/app_drive.png new file mode 100644 index 0000000..e640551 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/app_drive.png differ diff --git a/app/src/main/res/drawable-xhdpi/app_file_manager.png b/app/src/main/res/drawable-xhdpi/app_file_manager.png new file mode 100644 index 0000000..1f3c55b Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/app_file_manager.png differ diff --git a/app/src/main/res/drawable-xhdpi/app_google_play.png b/app/src/main/res/drawable-xhdpi/app_google_play.png new file mode 100644 index 0000000..14e0258 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/app_google_play.png differ diff --git a/app/src/main/res/drawable-xhdpi/app_total_commander.png b/app/src/main/res/drawable-xhdpi/app_total_commander.png new file mode 100644 index 0000000..406c6cc Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/app_total_commander.png differ diff --git a/app/src/main/res/drawable-xhdpi/btn_default_focused_holo_light.9.png b/app/src/main/res/drawable-xhdpi/btn_default_focused_holo_light.9.png new file mode 100644 index 0000000..73488f3 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/btn_default_focused_holo_light.9.png differ diff --git a/app/src/main/res/drawable-xhdpi/drawer_shadow.9.png b/app/src/main/res/drawable-xhdpi/drawer_shadow.9.png new file mode 100644 index 0000000..fabe9d9 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/drawer_shadow.9.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_bluetooth.png b/app/src/main/res/drawable-xhdpi/ic_action_bluetooth.png new file mode 100644 index 0000000..920f5ca Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_bluetooth.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_action_disconnect.png b/app/src/main/res/drawable-xhdpi/ic_action_disconnect.png new file mode 100644 index 0000000..44d6145 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_action_disconnect.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_bpm_feature.png b/app/src/main/res/drawable-xhdpi/ic_bpm_feature.png new file mode 100644 index 0000000..681e261 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_bpm_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_cgms_feature.png b/app/src/main/res/drawable-xhdpi/ic_cgms_feature.png new file mode 100644 index 0000000..c18519d Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_cgms_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_csc_feature.png b/app/src/main/res/drawable-xhdpi/ic_csc_feature.png new file mode 100644 index 0000000..ba5e624 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_csc_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_dfu_feature.png b/app/src/main/res/drawable-xhdpi/ic_dfu_feature.png new file mode 100644 index 0000000..d7065e0 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_dfu_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_glucose_feature.png b/app/src/main/res/drawable-xhdpi/ic_glucose_feature.png new file mode 100644 index 0000000..99ab2f5 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_glucose_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_help.png b/app/src/main/res/drawable-xhdpi/ic_help.png new file mode 100644 index 0000000..0e67d7c Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_help.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_hrs_feature.png b/app/src/main/res/drawable-xhdpi/ic_hrs_feature.png new file mode 100644 index 0000000..d28b50d Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_hrs_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_hts_feature.png b/app/src/main/res/drawable-xhdpi/ic_hts_feature.png new file mode 100644 index 0000000..c86d709 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_hts_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_hts_feature_black.png b/app/src/main/res/drawable-xhdpi/ic_hts_feature_black.png new file mode 100644 index 0000000..e4351f6 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_hts_feature_black.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_nrf_connect_feature_fg.png b/app/src/main/res/drawable-xhdpi/ic_nrf_connect_feature_fg.png new file mode 100644 index 0000000..e13cf3b Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_nrf_connect_feature_fg.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_proximity_feature.png b/app/src/main/res/drawable-xhdpi/ic_proximity_feature.png new file mode 100644 index 0000000..d0e7de1 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_proximity_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_rsc_feature.png b/app/src/main/res/drawable-xhdpi/ic_rsc_feature.png new file mode 100644 index 0000000..3f81e0b Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_rsc_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_cgms.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_cgms.png new file mode 100644 index 0000000..4ff0268 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_cgms.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_csc.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_csc.png new file mode 100644 index 0000000..d0f3466 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_csc.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_hts.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_hts.png new file mode 100644 index 0000000..a335593 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_hts.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_proximity.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_proximity.png new file mode 100644 index 0000000..a43b04f Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_proximity.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_rsc.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_rsc.png new file mode 100644 index 0000000..2ab1689 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_rsc.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_template.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_template.png new file mode 100644 index 0000000..8b4925d Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_template.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_notify_uart.png b/app/src/main/res/drawable-xhdpi/ic_stat_notify_uart.png new file mode 100644 index 0000000..4255d2b Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_notify_uart.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_template_feature.png b/app/src/main/res/drawable-xhdpi/ic_template_feature.png new file mode 100644 index 0000000..ac88d4a Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_template_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_1.png b/app/src/main/res/drawable-xhdpi/ic_uart_1.png new file mode 100644 index 0000000..d737be5 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_1.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_1_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_1_small.png new file mode 100644 index 0000000..cf8880f Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_1_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_2.png b/app/src/main/res/drawable-xhdpi/ic_uart_2.png new file mode 100644 index 0000000..db2432c Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_2.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_2_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_2_small.png new file mode 100644 index 0000000..855a88c Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_2_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_3.png b/app/src/main/res/drawable-xhdpi/ic_uart_3.png new file mode 100644 index 0000000..7664f4f Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_3.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_3_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_3_small.png new file mode 100644 index 0000000..6c40e48 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_3_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_4.png b/app/src/main/res/drawable-xhdpi/ic_uart_4.png new file mode 100644 index 0000000..1f00c16 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_4.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_4_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_4_small.png new file mode 100644 index 0000000..68b32fd Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_4_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_5.png b/app/src/main/res/drawable-xhdpi/ic_uart_5.png new file mode 100644 index 0000000..190332e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_5.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_5_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_5_small.png new file mode 100644 index 0000000..192fde1 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_5_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_6.png b/app/src/main/res/drawable-xhdpi/ic_uart_6.png new file mode 100644 index 0000000..7b8879c Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_6.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_6_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_6_small.png new file mode 100644 index 0000000..1aa1c47 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_6_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_7.png b/app/src/main/res/drawable-xhdpi/ic_uart_7.png new file mode 100644 index 0000000..3e12930 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_7.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_7_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_7_small.png new file mode 100644 index 0000000..03293e5 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_7_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_8.png b/app/src/main/res/drawable-xhdpi/ic_uart_8.png new file mode 100644 index 0000000..80d2911 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_8.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_8_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_8_small.png new file mode 100644 index 0000000..3a25ec4 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_8_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_9.png b/app/src/main/res/drawable-xhdpi/ic_uart_9.png new file mode 100644 index 0000000..3bf4196 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_9.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_9_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_9_small.png new file mode 100644 index 0000000..d2290c5 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_9_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_about.png b/app/src/main/res/drawable-xhdpi/ic_uart_about.png new file mode 100644 index 0000000..a7bdf34 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_about.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_about_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_about_small.png new file mode 100644 index 0000000..3be3152 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_about_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_down.png b/app/src/main/res/drawable-xhdpi/ic_uart_down.png new file mode 100644 index 0000000..5107082 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_down.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_down_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_down_small.png new file mode 100644 index 0000000..76937f5 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_down_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_feature.png b/app/src/main/res/drawable-xhdpi/ic_uart_feature.png new file mode 100644 index 0000000..f173944 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_feature.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_forward.png b/app/src/main/res/drawable-xhdpi/ic_uart_forward.png new file mode 100644 index 0000000..cd5040e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_forward.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_forward_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_forward_small.png new file mode 100644 index 0000000..fec2018 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_forward_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_left.png b/app/src/main/res/drawable-xhdpi/ic_uart_left.png new file mode 100644 index 0000000..c8c63a9 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_left.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_left_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_left_small.png new file mode 100644 index 0000000..ed8ac91 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_left_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_pause.png b/app/src/main/res/drawable-xhdpi/ic_uart_pause.png new file mode 100644 index 0000000..293f712 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_pause.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_pause_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_pause_small.png new file mode 100644 index 0000000..504389a Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_pause_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_play.png b/app/src/main/res/drawable-xhdpi/ic_uart_play.png new file mode 100644 index 0000000..97ff9b0 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_play.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_play_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_play_small.png new file mode 100644 index 0000000..7f709bb Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_play_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_rewind.png b/app/src/main/res/drawable-xhdpi/ic_uart_rewind.png new file mode 100644 index 0000000..3e66f69 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_rewind.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_rewind_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_rewind_small.png new file mode 100644 index 0000000..27a2b9e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_rewind_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_right.png b/app/src/main/res/drawable-xhdpi/ic_uart_right.png new file mode 100644 index 0000000..4ac16d0 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_right.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_right_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_right_small.png new file mode 100644 index 0000000..5f30474 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_right_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_settings.png b/app/src/main/res/drawable-xhdpi/ic_uart_settings.png new file mode 100644 index 0000000..fe5fec4 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_settings.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_settings_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_settings_small.png new file mode 100644 index 0000000..999d0f0 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_settings_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_stop.png b/app/src/main/res/drawable-xhdpi/ic_uart_stop.png new file mode 100644 index 0000000..c86dbb1 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_stop.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_stop_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_stop_small.png new file mode 100644 index 0000000..2b07de4 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_stop_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_up.png b/app/src/main/res/drawable-xhdpi/ic_uart_up.png new file mode 100644 index 0000000..5411d8c Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_up.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_uart_up_small.png b/app/src/main/res/drawable-xhdpi/ic_uart_up_small.png new file mode 100644 index 0000000..60ac6b0 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_uart_up_small.png differ diff --git a/app/src/main/res/drawable-xhdpi/proximity_lock_open.png b/app/src/main/res/drawable-xhdpi/proximity_lock_open.png new file mode 100644 index 0000000..d400031 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/proximity_lock_open.png differ diff --git a/app/src/main/res/drawable-xhdpi/shadow_l.png b/app/src/main/res/drawable-xhdpi/shadow_l.png new file mode 100644 index 0000000..b007003 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/shadow_l.png differ diff --git a/app/src/main/res/drawable-xhdpi/shadow_r.png b/app/src/main/res/drawable-xhdpi/shadow_r.png new file mode 100644 index 0000000..ae07b59 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/shadow_r.png differ diff --git a/app/src/main/res/drawable-xhdpi/zip.png b/app/src/main/res/drawable-xhdpi/zip.png new file mode 100644 index 0000000..eb96135 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/zip.png differ diff --git a/app/src/main/res/drawable-xxhdpi/action_bar_shadow.9.png b/app/src/main/res/drawable-xxhdpi/action_bar_shadow.9.png new file mode 100644 index 0000000..c4e8083 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/action_bar_shadow.9.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_add_normal.png b/app/src/main/res/drawable-xxhdpi/ic_action_add_normal.png new file mode 100644 index 0000000..9e16b1f Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_add_normal.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_add_pressed.png b/app/src/main/res/drawable-xxhdpi/ic_action_add_pressed.png new file mode 100644 index 0000000..e4b6217 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_add_pressed.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_bluetooth.png b/app/src/main/res/drawable-xxhdpi/ic_action_bluetooth.png new file mode 100644 index 0000000..860c758 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_bluetooth.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_clear_normal.png b/app/src/main/res/drawable-xxhdpi/ic_action_clear_normal.png new file mode 100644 index 0000000..c03cb87 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_clear_normal.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_clear_pressed.png b/app/src/main/res/drawable-xxhdpi/ic_action_clear_pressed.png new file mode 100644 index 0000000..ed70b4e Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_clear_pressed.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_disconnect.png b/app/src/main/res/drawable-xxhdpi/ic_action_disconnect.png new file mode 100644 index 0000000..035ff88 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_disconnect.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_download_normal.png b/app/src/main/res/drawable-xxhdpi/ic_action_download_normal.png new file mode 100644 index 0000000..bde2379 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_download_normal.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_action_download_pressed.png b/app/src/main/res/drawable-xxhdpi/ic_action_download_pressed.png new file mode 100644 index 0000000..2d91bc3 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_action_download_pressed.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_action_bluetooth.png b/app/src/main/res/drawable-xxxhdpi/ic_action_bluetooth.png new file mode 100644 index 0000000..90d8a34 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_action_bluetooth.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_action_disconnect.png b/app/src/main/res/drawable-xxxhdpi/ic_action_disconnect.png new file mode 100644 index 0000000..b650848 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_action_disconnect.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_battery_alert.png b/app/src/main/res/drawable-xxxhdpi/ic_battery_alert.png new file mode 100644 index 0000000..6dfdb8f Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_battery_alert.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_battery_full.png b/app/src/main/res/drawable-xxxhdpi/ic_battery_full.png new file mode 100644 index 0000000..3503f6f Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_battery_full.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_proximity_tag.png b/app/src/main/res/drawable-xxxhdpi/ic_proximity_tag.png new file mode 100644 index 0000000..501500e Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_proximity_tag.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_find.png b/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_find.png new file mode 100644 index 0000000..e676b17 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_find.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_silent.png b/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_silent.png new file mode 100644 index 0000000..419d1ef Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_silent.png differ diff --git a/app/src/main/res/drawable/app_file_browser.xml b/app/src/main/res/drawable/app_file_browser.xml new file mode 100644 index 0000000..09b9238 --- /dev/null +++ b/app/src/main/res/drawable/app_file_browser.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/app_sm_logo.png b/app/src/main/res/drawable/app_sm_logo.png new file mode 100644 index 0000000..97b6eac Binary files /dev/null and b/app/src/main/res/drawable/app_sm_logo.png differ diff --git a/app/src/main/res/drawable/button.xml b/app/src/main/res/drawable/button.xml new file mode 100644 index 0000000..fe22380 --- /dev/null +++ b/app/src/main/res/drawable/button.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/button_n.xml b/app/src/main/res/drawable/button_n.xml new file mode 100644 index 0000000..0b90321 --- /dev/null +++ b/app/src/main/res/drawable/button_n.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/button_p.xml b/app/src/main/res/drawable/button_p.xml new file mode 100644 index 0000000..d79ca8a --- /dev/null +++ b/app/src/main/res/drawable/button_p.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_action_add.xml b/app/src/main/res/drawable/ic_action_add.xml new file mode 100644 index 0000000..b5f0f25 --- /dev/null +++ b/app/src/main/res/drawable/ic_action_add.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_action_clear.xml b/app/src/main/res/drawable/ic_action_clear.xml new file mode 100644 index 0000000..88047bc --- /dev/null +++ b/app/src/main/res/drawable/ic_action_clear.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_action_download.xml b/app/src/main/res/drawable/ic_action_download.xml new file mode 100644 index 0000000..e0953c2 --- /dev/null +++ b/app/src/main/res/drawable/ic_action_download.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_battery.xml b/app/src/main/res/drawable/ic_battery.xml new file mode 100644 index 0000000..afde310 --- /dev/null +++ b/app/src/main/res/drawable/ic_battery.xml @@ -0,0 +1,27 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_feature_bg.xml b/app/src/main/res/drawable/ic_feature_bg.xml new file mode 100644 index 0000000..b06fc4d --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_bg.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_feature_bg_n.xml b/app/src/main/res/drawable/ic_feature_bg_n.xml new file mode 100644 index 0000000..35242a5 --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_bg_n.xml @@ -0,0 +1,27 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_feature_bg_p.xml b/app/src/main/res/drawable/ic_feature_bg_p.xml new file mode 100644 index 0000000..9a567f4 --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_bg_p.xml @@ -0,0 +1,27 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_feature_small_bg.xml b/app/src/main/res/drawable/ic_feature_small_bg.xml new file mode 100644 index 0000000..8134d3d --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_small_bg.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_feature_small_bg_n.xml b/app/src/main/res/drawable/ic_feature_small_bg_n.xml new file mode 100644 index 0000000..6137705 --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_small_bg_n.xml @@ -0,0 +1,29 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_feature_small_bg_p.xml b/app/src/main/res/drawable/ic_feature_small_bg_p.xml new file mode 100644 index 0000000..3361815 --- /dev/null +++ b/app/src/main/res/drawable/ic_feature_small_bg_p.xml @@ -0,0 +1,29 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_nrf_connect_feature_small.xml b/app/src/main/res/drawable/ic_nrf_connect_feature_small.xml new file mode 100644 index 0000000..60e5eed --- /dev/null +++ b/app/src/main/res/drawable/ic_nrf_connect_feature_small.xml @@ -0,0 +1,26 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_rssi_bar.xml b/app/src/main/res/drawable/ic_rssi_bar.xml new file mode 100644 index 0000000..e37a8b7 --- /dev/null +++ b/app/src/main/res/drawable/ic_rssi_bar.xml @@ -0,0 +1,28 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/nordic_logo.xml b/app/src/main/res/drawable/nordic_logo.xml new file mode 100644 index 0000000..14679a6 --- /dev/null +++ b/app/src/main/res/drawable/nordic_logo.xml @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/nordic_logo_horiz_white.xml b/app/src/main/res/drawable/nordic_logo_horiz_white.xml new file mode 100644 index 0000000..af91623 --- /dev/null +++ b/app/src/main/res/drawable/nordic_logo_horiz_white.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/start_edit_mode.xml b/app/src/main/res/drawable/start_edit_mode.xml new file mode 100644 index 0000000..de9d619 --- /dev/null +++ b/app/src/main/res/drawable/start_edit_mode.xml @@ -0,0 +1,28 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/stop_edit_mode.xml b/app/src/main/res/drawable/stop_edit_mode.xml new file mode 100644 index 0000000..d5491ef --- /dev/null +++ b/app/src/main/res/drawable/stop_edit_mode.xml @@ -0,0 +1,28 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/uart_button.xml b/app/src/main/res/drawable/uart_button.xml new file mode 100644 index 0000000..0abfeb5 --- /dev/null +++ b/app/src/main/res/drawable/uart_button.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/uart_button_background.xml b/app/src/main/res/drawable/uart_button_background.xml new file mode 100644 index 0000000..3c1580e --- /dev/null +++ b/app/src/main/res/drawable/uart_button_background.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/uart_button_small.xml b/app/src/main/res/drawable/uart_button_small.xml new file mode 100644 index 0000000..fb981d2 --- /dev/null +++ b/app/src/main/res/drawable/uart_button_small.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/drawable/uart_dialog_button_background.xml b/app/src/main/res/drawable/uart_dialog_button_background.xml new file mode 100644 index 0000000..fd4991f --- /dev/null +++ b/app/src/main/res/drawable/uart_dialog_button_background.xml @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout-land/activity_feature_bpm.xml b/app/src/main/res/layout-land/activity_feature_bpm.xml new file mode 100644 index 0000000..b03b233 --- /dev/null +++ b/app/src/main/res/layout-land/activity_feature_bpm.xml @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout-land/activity_feature_cgms.xml b/app/src/main/res/layout-land/activity_feature_cgms.xml new file mode 100644 index 0000000..45dfc77 --- /dev/null +++ b/app/src/main/res/layout-land/activity_feature_cgms.xml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +