diff --git a/README.md b/README.md deleted file mode 100644 index 2eddce8..0000000 --- a/README.md +++ /dev/null @@ -1,134 +0,0 @@ -# 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/build.gradle b/app/build.gradle index c3557e6..320161c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,28 +1,34 @@ apply plugin: 'com.android.application' +apply plugin: 'com.google.gms.google-services' +apply plugin: 'com.google.firebase.crashlytics' + android { - compileSdkVersion 28 - buildToolsVersion "28.0.3" + compileSdkVersion 29 + buildToolsVersion "29.0.3" defaultConfig { - applicationId "no.nordicsemi.android.nrftoolbox" + applicationId "no.spca.android.iisc" minSdkVersion 18 - targetSdkVersion 28 - versionCode 69 - versionName "2.7.2" + targetSdkVersion 29 + versionCode 78 + versionName "2.9.0" resConfigs "en" + multiDexEnabled true + vectorDrawables.useSupportLibrary = true } buildTypes { debug { - minifyEnabled true - useProguard false + minifyEnabled false + shrinkResources false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } release { minifyEnabled true - useProguard true + shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } @@ -33,41 +39,70 @@ android { } dependencies { - implementation project(':common') implementation fileTree(dir: 'libs', include: ['*.jar']) - wearApp project(path: ':wear') + implementation 'androidx.constraintlayout:constraintlayout:2.0.4' - // 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 'androidx.appcompat:appcompat:1.3.0-alpha01' + implementation 'androidx.preference:preference:1.1.1' + implementation 'de.hdodenhof:circleimageview:3.1.0' implementation 'no.nordicsemi.android:log:2.2.0' - implementation 'no.nordicsemi.android.support.v18:scanner:1.4.0' + implementation 'no.nordicsemi.android.support.v18:scanner:1.4.3' + implementation 'org.apache.poi:poi:4.0.0' + implementation 'org.apache.poi:poi-ooxml:4.0.0' + implementation 'com.android.support:multidex:1.0.1' + + implementation 'com.jjoe64:graphview:4.2.2' + + implementation 'no.nordicsemi.android:dfu:1.10.3' + + implementation 'androidx.appcompat:appcompat:1.1.0-alpha04' + + + implementation 'com.hbb20:ccp:2.4.0' + implementation 'androidx.preference:preference:1.1.0-alpha04' + implementation 'com.google.android.material:material:1.1.0-alpha05' + implementation 'com.google.android.material:material:1.1.0' + + implementation 'com.google.firebase:firebase-database:16.0.4' + + implementation 'androidx.appcompat:appcompat:1.1.0-alpha04' + + implementation 'com.google.firebase:firebase-auth:16.0.5' + + + implementation 'androidx.preference:preference:1.1.0-alpha04' + + implementation 'no.nordicsemi.android:log:2.2.0' + implementation 'com.chaos.view:pinview:1.4.3' + implementation "androidx.browser:browser:1.3.0" + + + implementation 'com.github.bumptech.glide:glide:4.11.0' + implementation 'com.firebaseui:firebase-ui-database:7.1.1' + + + implementation 'com.hbb20:ccp:2.4.0' + + implementation 'com.google.firebase:firebase-auth:20.0.1' + + implementation 'com.google.android.material:material:1.0.0' + + implementation 'com.github.PhilJay:MPAndroidChart:v2.0.9' + + implementation 'com.google.firebase:firebase-crashlytics:17.1.1' + + + + implementation 'com.google.firebase:firebase-storage:16.0.4' - // 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/google-services.json b/app/google-services.json new file mode 100644 index 0000000..c74f56e --- /dev/null +++ b/app/google-services.json @@ -0,0 +1,48 @@ +{ + "project_info": { + "project_number": "373562439004", + "firebase_url": "https://spca-1133f-default-rtdb.firebaseio.com", + "project_id": "spca-1133f", + "storage_bucket": "spca-1133f.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:373562439004:android:10f9cf941182ebbdc8bd99", + "android_client_info": { + "package_name": "no.spca.android.iisc" + } + }, + "oauth_client": [ + { + "client_id": "373562439004-md3mf893e0m3mn45a9v3tdtlquqv09bg.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "no.spca.android.iisc", + "certificate_hash": "4dd609cfc14941b104eab9dd18d6a02dca970fb4" + } + }, + { + "client_id": "373562439004-hpejfuaulqq5kfes9n8s8uepcfio686q.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyCVnXHQZEvsXbuEPN9X_8dU_kZX3e_mUH4" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "373562439004-hpejfuaulqq5kfes9n8s8uepcfio686q.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/app/src/androidTest/java/no/nordicsemi/android/nrftoolbox/ApplicationTest.java b/app/src/androidTest/java/no/nordicsemi/android/nrftoolbox/ApplicationTest.java deleted file mode 100644 index 5e6a0ca..0000000 --- a/app/src/androidTest/java/no/nordicsemi/android/nrftoolbox/ApplicationTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 index 1ce41f7..db1f8fa 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,297 +1,126 @@ - - + - - - - - - - + + + + + + + + + + + + + + + - + - + + + - - - - + + + - - + - + + + - - + + - + - - - - - - + + - - - - - + - - - - - + + + + + - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + - - ---> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + \ No newline at end of file diff --git a/app/src/main/assets/fa-solid-900.ttf b/app/src/main/assets/fa-solid-900.ttf new file mode 100644 index 0000000..7c59512 Binary files /dev/null and b/app/src/main/assets/fa-solid-900.ttf differ diff --git a/app/src/main/assets/labels.txt b/app/src/main/assets/labels.txt new file mode 100644 index 0000000..0dcf43b --- /dev/null +++ b/app/src/main/assets/labels.txt @@ -0,0 +1,2 @@ +0 negative +1 positive diff --git a/app/src/main/assets/model.tflite b/app/src/main/assets/model.tflite new file mode 100644 index 0000000..1df51dc Binary files /dev/null and b/app/src/main/assets/model.tflite differ diff --git a/app/src/main/ic_launcher-playstore.png b/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000..1c52cad Binary files /dev/null and b/app/src/main/ic_launcher-playstore.png differ diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/AppHelpFragment.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/AppHelpFragment.java deleted file mode 100644 index 6799f6c..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/AppHelpFragment.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 deleted file mode 100644 index 86709ee..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/FeaturesActivity.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * 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/SplashscreenActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/SplashscreenActivity.java deleted file mode 100644 index 5eaa1e9..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/SplashscreenActivity.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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/app/ExpandableListActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/app/ExpandableListActivity.java deleted file mode 100644 index 8247c6d..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/app/ExpandableListActivity.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * 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/bpm/BPMActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMActivity.java deleted file mode 100644 index b38f59e..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMActivity.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * 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 deleted file mode 100644 index 55c6458..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManager.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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 deleted file mode 100644 index 75f550b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/bpm/BPMManagerCallbacks.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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 deleted file mode 100644 index ce6864d..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSActivity.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * 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 deleted file mode 100644 index 6588b19..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManager.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * 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 deleted file mode 100644 index 8ba33af..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSManagerCallbacks.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 deleted file mode 100644 index ced03f2..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecord.java +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 0fb1359..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMSRecordsAdapter.java +++ /dev/null @@ -1,79 +0,0 @@ -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 deleted file mode 100644 index 8f2f81a..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/cgms/CGMService.java +++ /dev/null @@ -1,290 +0,0 @@ -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 deleted file mode 100644 index 399fb06..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCActivity.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * 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 deleted file mode 100644 index c4feef5..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManager.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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 deleted file mode 100644 index 12035da..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCManagerCallbacks.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2a99f0c..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/CSCService.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * 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 deleted file mode 100644 index ebbf512..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsActivity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2a3b41b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/csc/settings/SettingsFragment.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 deleted file mode 100644 index 8851727..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuActivity.java +++ /dev/null @@ -1,862 +0,0 @@ -/* - * 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 deleted file mode 100644 index b236ec6..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuInitiatorActivity.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2b16b59..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/DfuService.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 deleted file mode 100644 index 1b02671..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/NotificationActivity.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 deleted file mode 100644 index b21a28b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/adapter/FileBrowserAppsAdapter.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 deleted file mode 100644 index 0fac518..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/UploadCancelFragment.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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 deleted file mode 100644 index 154cd38..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/fragment/ZipInfoFragment.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 deleted file mode 100644 index fc04998..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/AboutDfuPreference.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 deleted file mode 100644 index a957f33..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsActivity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index aaaf5de..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/dfu/settings/SettingsFragment.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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 deleted file mode 100644 index 85712de..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/ExpandableRecordAdapter.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2528a37..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseActivity.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * 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 deleted file mode 100644 index 6c8ad25..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManager.java +++ /dev/null @@ -1,407 +0,0 @@ -/* - * 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 deleted file mode 100644 index dff848f..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseManagerCallbacks.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 deleted file mode 100644 index f83c173..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/gls/GlucoseRecord.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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 deleted file mode 100644 index da5ec71..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSActivity.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * 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 deleted file mode 100644 index 861d640..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManager.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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 deleted file mode 100644 index 79f1870..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/HRSManagerCallbacks.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 deleted file mode 100644 index b3844c6..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hrs/LineGraphView.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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 deleted file mode 100644 index 59626cb..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSActivity.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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 deleted file mode 100644 index 732d616..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManager.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 deleted file mode 100644 index c8053b0..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSManagerCallbacks.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 deleted file mode 100644 index 811740e..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/HTSService.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * 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 deleted file mode 100644 index 30065d7..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsActivity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index 27bd3d7..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/hts/settings/SettingsFragment.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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 deleted file mode 100644 index 68ff78b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/AlertLevelParser.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9351730..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BloodPressureMeasurementParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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 deleted file mode 100644 index 22d1731..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/BodySensorLocationParser.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 deleted file mode 100644 index 6c9c807..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMMeasurementParser.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * 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 deleted file mode 100644 index c8afc88..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CGMSpecificOpsControlPointParser.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * 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 deleted file mode 100644 index a5a28cc..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/CSCMeasurementParser.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 deleted file mode 100644 index 5e3e79b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/DateTimeParser.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 deleted file mode 100644 index 8a81440..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementContextParser.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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 deleted file mode 100644 index 18d59b4..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/GlucoseMeasurementParser.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9622072..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/HeartRateMeasurementParser.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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 deleted file mode 100644 index 632dc5e..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/IntermediateCuffPressureParser.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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 deleted file mode 100644 index 6d19622..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RSCMeasurementParser.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 deleted file mode 100644 index 0ef5954..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/RecordAccessControlPointParser.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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 deleted file mode 100644 index cdefad7..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureMeasurementParser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 deleted file mode 100644 index 10d755e..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemperatureTypeParser.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 deleted file mode 100644 index ed0490a..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/parser/TemplateParser.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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/multiconnect/IDeviceLogger.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/IDeviceLogger.java deleted file mode 100644 index 59d6d59..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/IDeviceLogger.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 deleted file mode 100644 index c41538b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/DeviceAdapter.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * 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 deleted file mode 100644 index 23f0450..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/LinkLossFragment.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 deleted file mode 100644 index bab1d05..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityActivity.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * 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 deleted file mode 100644 index 315ebf6..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManager.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9d2b867..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityManagerCallbacks.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 deleted file mode 100644 index b381d3d..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManager.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9270d33..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityServerManagerCallbacks.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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 deleted file mode 100644 index b9a195e..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/proximity/ProximityService.java +++ /dev/null @@ -1,570 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2d052b0..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCActivity.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * 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 deleted file mode 100644 index aeb7ba8..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManager.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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 deleted file mode 100644 index 1a06cd2..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCManagerCallbacks.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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 deleted file mode 100644 index 0448033..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/RSCService.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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 deleted file mode 100644 index fb22c16..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsActivity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index 367309b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/rsc/settings/SettingsFragment.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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/ExtendedBluetoothDevice.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ExtendedBluetoothDevice.java deleted file mode 100644 index 7a248b5..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ExtendedBluetoothDevice.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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/template/Readme.txt b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/Readme.txt deleted file mode 100644 index aa3ffa4..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/Readme.txt +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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 deleted file mode 100644 index 60778ce..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateActivity.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * 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 deleted file mode 100644 index 514e850..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManager.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * 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 deleted file mode 100644 index 05b03d8..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateManagerCallbacks.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7c927be..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/TemplateService.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * 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 deleted file mode 100644 index 34e6d44..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateCharacteristicCallback.java +++ /dev/null @@ -1,21 +0,0 @@ -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/settings/SettingsActivity.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsActivity.java deleted file mode 100644 index 00f410d..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsActivity.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 deleted file mode 100644 index 3475b49..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/settings/SettingsFragment.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 deleted file mode 100644 index efce6fa..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTActivity.java +++ /dev/null @@ -1,826 +0,0 @@ -/* - * 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 deleted file mode 100644 index 7a25d8a..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTButtonAdapter.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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 deleted file mode 100644 index 1c4b25b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTConfigurationsAdapter.java +++ /dev/null @@ -1,127 +0,0 @@ -/************************************************************************************************************************************************* - * 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 deleted file mode 100644 index 374b53b..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTControlFragment.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9277019..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTEditDialog.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * 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 deleted file mode 100644 index 6619ca5..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTInterface.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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 deleted file mode 100644 index c196a36..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLocalLogContentProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 deleted file mode 100644 index ffaa413..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogAdapter.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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 deleted file mode 100644 index bf2f511..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTLogFragment.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * 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 deleted file mode 100644 index 3089ef1..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManager.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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 deleted file mode 100644 index 4a5bf24..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTManagerCallbacks.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 deleted file mode 100644 index d6820e0..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTNewConfigurationDialogFragment.java +++ /dev/null @@ -1,134 +0,0 @@ -/************************************************************************************************************************************************* - * 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 deleted file mode 100644 index 2e885ff..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/UARTService.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * 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 deleted file mode 100644 index c0a40d1..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/ConfigurationContract.java +++ /dev/null @@ -1,38 +0,0 @@ -/************************************************************************************************************************************************* - * 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 deleted file mode 100644 index e636aaf..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/DatabaseHelper.java +++ /dev/null @@ -1,259 +0,0 @@ -/************************************************************************************************************************************************* - * 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 deleted file mode 100644 index 65aba51..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/NameColumns.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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 deleted file mode 100644 index 12ff898..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/database/UndoColumns.java +++ /dev/null @@ -1,27 +0,0 @@ -/************************************************************************************************************************************************* - * 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 deleted file mode 100644 index e364c55..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/Command.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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 deleted file mode 100644 index 981f48c..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/domain/UartConfiguration.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 deleted file mode 100644 index 696a078..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/uart/wearable/UARTConfigurationSynchronizer.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * 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 deleted file mode 100644 index a0aef68..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/FileHelper.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * 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 deleted file mode 100644 index 5e11b14..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/utility/ParserUtils.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 deleted file mode 100644 index 30661f5..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/wearable/MainWearableListenerService.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 deleted file mode 100644 index baf19ed..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ClosableSpinner.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9d317f6..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/DividerItemDecoration.java +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************************************************************************************* - * 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 deleted file mode 100644 index c6e9598..0000000 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundLinearLayout.java +++ /dev/null @@ -1,148 +0,0 @@ -/************************************************************************************************************************************************* - * 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/spca/android/iisc/DebugLogger.java b/app/src/main/java/no/spca/android/iisc/DebugLogger.java new file mode 100644 index 0000000..2945d15 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/DebugLogger.java @@ -0,0 +1,51 @@ + +package no.spca.android.iisc; + +import android.util.Log; + + +public class DebugLogger { + public static void v(final String tag, final String text) { + if (BuildConfig.DEBUG) + Log.v(tag, text); + } + + public static void d(final String tag, final String text) { + if (BuildConfig.DEBUG) { + Log.d(tag, text); + } + } + + public static void i(final String tag, final String text) { + if (BuildConfig.DEBUG) + Log.i(tag, text); + } + + public static void w(final String tag, final String text) { + if (BuildConfig.DEBUG) { + Log.w(tag, text); + } + } + + public static void e(final String tag, final String text) { + if (BuildConfig.DEBUG) + Log.e(tag, text); + } + + public static void e(final String tag, final String text, final Throwable e) { + if (BuildConfig.DEBUG) + Log.e(tag, text, e); + } + + public static void wtf(final String tag, final String text) { + if (BuildConfig.DEBUG) { + Log.wtf(tag, text); + } + } + + public static void wtf(final String tag, final String text, final Throwable e) { + if (BuildConfig.DEBUG) { + Log.wtf(tag, text, e); + } + } +} diff --git a/app/src/main/java/no/spca/android/iisc/FeaturesActivity.java b/app/src/main/java/no/spca/android/iisc/FeaturesActivity.java new file mode 100644 index 0000000..40b1b76 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/FeaturesActivity.java @@ -0,0 +1,95 @@ + +package no.spca.android.iisc; + +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.Configuration; +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.View; +import android.widget.GridView; +import android.widget.Toast; + +import no.spca.android.iisc.adapter.AppAdapter; + +public class FeaturesActivity extends AppCompatActivity { + 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); + + if (!ensureBLEExists()) + finish(); + + final DrawerLayout drawer = mDrawerLayout = findViewById(R.id.drawer_layout); + drawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); + + mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { + @Override + public void onDrawerSlide(final View drawerView, final float slideOffset) { + super.onDrawerSlide(drawerView, 0); + } + }; + drawer.addDrawerListener(mDrawerToggle); + + //setupPluginsInDrawer(drawer.findViewById(R.id.plugin_container)); + + 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) { + + default: + break; + } + } + } + + + + @Override + protected void onPostCreate(final Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + mDrawerToggle.syncState(); + } + + @Override + public void onConfigurationChanged(@NonNull final Configuration newConfig) { + super.onConfigurationChanged(newConfig); + mDrawerToggle.onConfigurationChanged(newConfig); + } + + + + + + 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/spca/android/iisc/FontAwesome.java b/app/src/main/java/no/spca/android/iisc/FontAwesome.java new file mode 100644 index 0000000..9fdf1eb --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/FontAwesome.java @@ -0,0 +1,35 @@ +package no.spca.android.iisc; + + +import android.content.Context; +import android.graphics.Typeface; +import android.util.AttributeSet; + +import androidx.appcompat.widget.AppCompatTextView; + +public class FontAwesome extends AppCompatTextView { + + + public FontAwesome(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } + + public FontAwesome(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public FontAwesome(Context context) { + super(context); + init(); + } + + private void init() { + + Typeface tf = Typeface.createFromAsset(getContext().getAssets(), + "fa-solid-900.ttf"); + setTypeface(tf); + } + +} \ No newline at end of file diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/ToolboxApplication.java b/app/src/main/java/no/spca/android/iisc/NotificationData.java similarity index 56% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/ToolboxApplication.java rename to app/src/main/java/no/spca/android/iisc/NotificationData.java index 4726754..2cbd996 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/ToolboxApplication.java +++ b/app/src/main/java/no/spca/android/iisc/NotificationData.java @@ -1,26 +1,6 @@ -/* - * 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; + +package no.spca.android.iisc; import android.app.Application; import android.app.Notification; @@ -31,12 +11,14 @@ import android.os.Build; import no.nordicsemi.android.dfu.DfuServiceInitiator; -public class ToolboxApplication extends Application { +public class NotificationData 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(); diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/PermissionRationaleFragment.java b/app/src/main/java/no/spca/android/iisc/PermissionRationaleFragment.java similarity index 52% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/PermissionRationaleFragment.java rename to app/src/main/java/no/spca/android/iisc/PermissionRationaleFragment.java index 5a13ca0..dc39f42 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/PermissionRationaleFragment.java +++ b/app/src/main/java/no/spca/android/iisc/PermissionRationaleFragment.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc; import android.app.Dialog; import android.content.Context; @@ -28,6 +8,7 @@ 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"; diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/About.java b/app/src/main/java/no/spca/android/iisc/SPCA/About.java new file mode 100644 index 0000000..8951113 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/About.java @@ -0,0 +1,21 @@ +package no.spca.android.iisc.SPCA; + +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; + +import no.spca.android.iisc.R; + + +public class About extends NavigationTop { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + LayoutInflater inflater = (LayoutInflater) this + .getSystemService(LAYOUT_INFLATER_SERVICE); + View contentView = inflater.inflate(R.layout.activity_about, null, false); + draw.addView(contentView, 0); + + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/AddTest.java b/app/src/main/java/no/spca/android/iisc/SPCA/AddTest.java new file mode 100644 index 0000000..f236262 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/AddTest.java @@ -0,0 +1,870 @@ +package no.spca.android.iisc.SPCA; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.media.MediaPlayer; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import android.os.CountDownTimer; +import android.os.Handler; +import android.text.TextWatcher; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + + +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.Task; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; + +import java.io.File; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.profile.BleProfileService; +import no.spca.android.iisc.profile.BleProfileServiceReadyActivity; + + + +public class AddTest extends BleProfileServiceReadyActivity { + @SuppressWarnings("unused") + private final String TAG = "AddTest"; + + private TextView mValueView; + private TextView mCycleView; + private EditText mFETempValueView; + private EditText mFETimeValueView; + + String acttime; + + private TextView mHeatingStatusView; + private int seconds1 ,seconds2; + private Switch mHeatingState ; + + private EditText mDTimeValueView; + private Integer mDSetTime ; + private EditText mLTimeValueView; + private Integer mLSetTime ; + private EditText mOTimeValueView; + private Integer mOSetTime ; + private String time1,time2,time3; + private Date date1,date2,date3; +private EditText prtocol; + + MediaPlayer msound; + + private final int valuedata=0; + private final int j=0; + private final Handler handler = new Handler(); + private Runnable runnable; + + + private EditText mATimeValueView; + private Integer mASetTime ; + private EditText mETimeValueView; + private Integer mESetTime ; + private TextWatcher txtwt; + + private Button next; + Button connect; + + + + + + private EditText mDTempValueView; + private Integer mDSetTemp ; + private EditText mATempValueView; + private Integer mASetTemp ; + private EditText mETempValueView; + private Integer mESetTemp ; + + private EditText mLTempValueView; + private Integer mLSetTemp ; + private EditText mOTempValueView; + private Integer mOSetTemp ; + private long diff=0; + private long diffSeconds=0; + private long diffMinutes=0; + private long diffHours=0; + private long diff1=0; + private long diffSeconds1=0; + private long diffMinutes1=0; + + private long diffHours1=0; + private Integer mSSetTemp ; + private Integer mSSetTime; + + private int FLAG=0; + + + private int count=0; + private int valuw=0; + + int i=0; + private DatabaseReference TestRef; + private ProgressDialog loadingBar; + private Button save; + private String TestRandomKey,saveCurrentDate, saveCurrentTime,number; + + + + private EditText mNPcrCView; + private Integer mNPcrC ; + private Timer T; + + + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_feature_template); + loadingBar = new ProgressDialog(this); + + setGUI(); + + next = findViewById(R.id.action_next); + connect = findViewById(R.id.action_connect); + msound= MediaPlayer.create(AddTest.this,R.raw.notification); + + next.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + connect.performClick(); + + + Intent intent = new Intent(AddTest.this, GraphActivity.class); + + + intent.putExtra("key6",acttime); + + startActivity(intent); + + } + }); + save=findViewById(R.id.action_save); + + save.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + ValidateProductData(); + } + }); + + + + } + + private void setGUI() { + mValueView = findViewById(R.id.Temp_Value); + mCycleView = findViewById(R.id.RemTime_Value); + + mDTempValueView = findViewById(R.id.D_Temp_Set); + mDTimeValueView = findViewById(R.id.D_Time_Set); + mATempValueView = findViewById(R.id.A_Temp_Set); + mATimeValueView = findViewById(R.id.A_Time_Set); + mETempValueView = findViewById(R.id.E_Temp_Set); + mETimeValueView = findViewById(R.id.E_Time_Set); + mLTempValueView=findViewById(R.id.L_Temp_Set); + mOTempValueView=findViewById(R.id.O_Temp_Set); + mLTimeValueView = findViewById(R.id.L_Time_Set); + + mOTimeValueView = findViewById(R.id.O_Time_Set); + mFETimeValueView=findViewById(R.id.S_Time_Set); + mFETempValueView=findViewById(R.id.S_Temp_Set); + + T=new Timer(); + + + SharedPreferences preferences689 = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + + number = preferences689.getString("Phone", null); + + + + TestRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + + + + + + + + + + + + + mNPcrCView = findViewById(R.id.N_Pcr_C); +prtocol=findViewById(R.id.protocol_name); + + mHeatingState = findViewById(R.id.heating_state); + mHeatingStatusView= findViewById(R.id.heating_status_text); + //mValueView.setText("fff"); + + + + mHeatingState.setOnCheckedChangeListener((buttonView, isChecked) -> { + if(connect.getText().equals("CONNECT")) + { + Toast.makeText(AddTest.this, "Please connect to device", Toast.LENGTH_SHORT).show(); + + } + else { + if (isChecked) { + startCounter(); + + + i = 1; + if (date2 != null && date1 != null) { + SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + try { + date1 = format.parse(time1); + date2 = format.parse(time2); + diff = (date2.getTime() - date1.getTime()); + diffSeconds = diff / 1000 % 60; + diffMinutes = diff / (60 * 1000) % 60; + diffHours = diff / (60 * 60 * 1000); + + + + } catch (ParseException e) { + e.printStackTrace(); + } + + + } + + Log.e("main", "error data inside " + valuedata); + + getService().heatingSwitch(1); + + mDSetTemp = Integer.parseInt(mDTempValueView.getText().toString()); + getService().sendDTemp(mDSetTemp); + + + mDSetTime = Integer.parseInt(mDTimeValueView.getText().toString()); + getService().sendDTime(mDSetTime); + + mLSetTemp = Integer.parseInt(mLTempValueView.getText().toString()); + getService().sendLTemp(mLSetTemp); + mLSetTime = Integer.parseInt(mLTimeValueView.getText().toString()); + getService().sendLTime(mLSetTime); + + mOSetTemp = Integer.parseInt(mOTempValueView.getText().toString()); + getService().sendOTemp(mOSetTemp); + mOSetTime = Integer.parseInt(mOTimeValueView.getText().toString()); + getService().sendOTime(mOSetTime); + + + mASetTemp = Integer.parseInt(mATempValueView.getText().toString()); + getService().sendATemp(mASetTemp); + mASetTime = Integer.parseInt(mATimeValueView.getText().toString()); + getService().sendATime(mASetTime); + + mESetTemp = Integer.parseInt(mETempValueView.getText().toString()); + getService().sendETemp(mESetTemp); + mESetTime = Integer.parseInt(mETimeValueView.getText().toString()); + getService().sendETime(mESetTime); + + + mSSetTemp = Integer.parseInt(mFETempValueView.getText().toString()); + getService().sendLTemp(mSSetTemp); + mSSetTime = Integer.parseInt(mFETimeValueView.getText().toString()); + getService().sendLTime(mSSetTime); + + + mNPcrC = Integer.parseInt(mNPcrCView.getText().toString()); + getService().sendNPcrN(mNPcrC); + Log.e("main", "error 34" + mDSetTemp); + + Log.e("main", "error 2 " + mDSetTemp); + Log.e("main", "error data box " + valuedata); + + + + + } else { + getService().heatingSwitch(0); + } + mHeatingStatusView.setText(isChecked ? R.string.Heating_block_on : R.string.Heating_block_off); + } + }); + + + + } + + @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() { + mValueView.setText("wait"); + mCycleView.setText("wait"); + + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.template_feature_title; + } + + + + + @Override + protected int getDefaultDeviceName() { + return R.string.template_default_name; + } + + @Override + protected UUID getFilterUUID() { + return CycleManager.SERVICE_UUID; + } + + @Override + protected Class getServiceClass() { + return CycleService.class; + } + + @Override + protected void onServiceBound(final CycleService.TemplateBinder binder) { + } + + @Override + protected void onServiceUnbound() { + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + } + + @SuppressWarnings("unused") + private void setValueOnView(@NonNull final BluetoothDevice device, int value) { + } + + + + + + @SuppressWarnings("unused") + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int value) { + + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_DEVICE); + + if (no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT.equals(action)) { + int value = intent.getIntExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_DATA, 0); + setValueOnView(device, value); + valuw=value; + if(value==0) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time1 = df.format(Calendar.getInstance().getTime()); + + + Log.e("main", "error 403 " +time1); + + + + //cycle 1 start + + + } + + else if(value ==1 ) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time2 = df.format(Calendar.getInstance().getTime()); + + Log.e("main", "error 404 " +time2); + LocalDateTime date = LocalDateTime.now(); + seconds1 = date.toLocalTime().toSecondOfDay(); + + + + } + else if(value ==2 ) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time3 = df.format(Calendar.getInstance().getTime()); + + try { + date1 = df.parse(time1); + date2 = df.parse(time2); + date3=df.parse(time3); + + } catch (ParseException e) { + e.printStackTrace(); + } + Log.e("main", "date 1 " + date2.getTime()); + Log.e("main", "date 2 " + date1.getTime()); + + + diff1 = date3.getTime() - date2.getTime(); + Log.e("main", "difference minute " + diffMinutes); + + + Log.e("main", "difference minute " + diffMinutes); + + diffSeconds1 = diff1 / 1000 % 60; + diffMinutes1 = diff1 / (60 * 1000) % 60; + diffHours1 = diff1/ (60 * 60 * 1000); + Log.e("main", "date difference " + diffMinutes1); + + + + Log.e("main", "error 404 " +time2); + + + + + } + + if(time1 !=null && time2 !=null &&diffSeconds1==1 ) { + + SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + try { + date1 = format.parse(time1); + date2 = format.parse(time2); + Log.e("main", "date 1 " + date2.getTime()); + Log.e("main", "date 2 " + date1.getTime()); + + + diff = date2.getTime() - date1.getTime(); + Log.e("main", "difference minute " + diffMinutes); + + diffSeconds = diff / 1000 % 60; + diffMinutes = diff / (60 * 1000) % 60; + diffHours = diff / (60 * 60 * 1000); + Log.e("main", "date difference " + diffMinutes); + FLAG=1; + + + + } catch (ParseException e) { + e.printStackTrace(); + } + + } + else + { + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + } else if (no.spca.android.iisc.SPCA.CycleService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_BATTERY_LEVEL, 0); + onBatteryLevelChanged(device, batteryLevel); + } + + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT); + intentFilter.addAction(no.spca.android.iisc.SPCA.CycleService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } + private void startCounter1() + { + T.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + + count++; + Log.e("main", "Currnet " + count); + + + } + }); + } + }, 10000, 10000); + + + } + + private void startCounter() + + { + + + + T.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + + if(FLAG==1) + { + mNPcrC=mNPcrC-1; + long cycle=mNPcrC.longValue(); + acttime=String.valueOf(diff*cycle); + //acttime="20444444" + connect.performClick(); + + + Intent intent = new Intent(AddTest.this, GraphActivity.class); + + + intent.putExtra("key6",acttime); + + startActivity(intent); + T.cancel(); + } + + + + } + }); + } + }, 1000, 1000); + + + + + } + private void countdown(long second) + { + new CountDownTimer(second, 1000) { + + public void onTick(long millisUntilFinished) { + next.setEnabled(true); + acttime=String.valueOf(second); + + //Log.d("LOGGER", "sec: " + millisUntilFinished / 1000); + //Log.d("LOGGER", "sec: " + millisUntilFinished / 1000); + long diffSecondsl = millisUntilFinished / 1000 % 60; + long diffMinutesl = millisUntilFinished / (60 * 1000) % 60; + long diffhourl = millisUntilFinished / (60 *60 * 1000) % 60; + mValueView.setText(diffhourl+"h"+diffMinutesl+"m"+diffSecondsl+"s"); + + int cyclecurrent=(mNPcrC-valuw)+1; + if(cyclecurrent<0) + { + + mCycleView.setText("Finish"); + + } + else { + + mCycleView.setText(String.valueOf(cyclecurrent)); + } + } + + public void onFinish() { + msound.start(); + msound.setLooping(true); + + mValueView.setText("Finish"); + mCycleView.setText("Finish"); + } + }.start(); + + } + private void countDownStart() { + new CountDownTimer(30000, 1000) { + + public void onTick(long millisUntilFinished) { + // Log.d("LOGGER", "seconds remaining: " + millisUntilFinished / 1000); + + mValueView.setText("sec " + millisUntilFinished / 1000); + } + + public void onFinish() { + mValueView.setText("Finish"); + } + }.start(); + + } + + @Override + public void onPointerCaptureChanged(boolean hasCapture) { + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } + private void ValidateProductData() + { + + if (!isOnline()) { + //Create an alertdialog + AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(AddTest.this); + Checkbuilder.setTitle("No Internet Connection !"); + Checkbuilder.setMessage("Check Your Internet Connection."); + //Builder Retry Button + + Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + dialog.cancel(); + } + }); + + Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + + AlertDialog alert = Checkbuilder.create(); + alert.show(); + + } + else { + StoreProductInformation(); + } + + } + + + + + + + private void StoreProductInformation() + { + loadingBar.setTitle("Add Test"); + loadingBar.setMessage("Please wait while we are adding the Test Details ."); + loadingBar.setCanceledOnTouchOutside(false); + loadingBar.show(); + + Calendar calendar = Calendar.getInstance(); + + SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy"); + saveCurrentDate = currentDate.format(calendar.getTime()); + + SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a"); + saveCurrentTime = currentTime.format(calendar.getTime()); + + TestRandomKey = saveCurrentDate + saveCurrentTime+number; + + + + + + if (!isOnline()) { + //Create an alertdialog + AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(AddTest.this); + Checkbuilder.setTitle("No Internet Connection !"); + Checkbuilder.setMessage("Check Your Internet Connection."); + //Builder Retry Button + + Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + dialog.cancel(); + } + }); + + Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + + AlertDialog alert = Checkbuilder.create(); + alert.show(); + + } else { + + SaveProductInfoToDatabase(); + } + + + + } + private void SaveProductInfoToDatabase() + { + HashMap productMap = new HashMap<>(); + + + productMap.put("Time", saveCurrentTime); + productMap.put("rev_trans_temp",mLTempValueView.getText().toString()); + productMap.put("rev_trans_time",mLTimeValueView.getText().toString()); + productMap.put("intial_den_temp",mOTempValueView.getText().toString()); + + productMap.put("intial_den_time",mOTimeValueView.getText().toString()); + productMap.put("den_temp",mDTempValueView.getText().toString()); + productMap.put("den_time",mDTimeValueView.getText().toString()); + productMap.put("ann_temp",mATempValueView.getText().toString()); + productMap.put("ann_time",mATimeValueView.getText().toString()); + + productMap.put("ext_temp",mETempValueView.getText().toString()); + productMap.put("ext_time",mETimeValueView.getText().toString()); + + productMap.put("fext_temp",mFETempValueView.getText().toString()); + productMap.put("fext_time",mFETimeValueView.getText().toString()); + productMap.put("no_of_pcr_cycle",mNPcrCView.getText().toString()); +productMap.put("name_protocol",prtocol.getText().toString()); + productMap.put("date_protocol", saveCurrentDate); + + + + + + + + productMap.put("Sample_Date",saveCurrentDate ); + productMap.put("random_key",TestRandomKey); + + + + + TestRef.child(TestRandomKey).updateChildren(productMap) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) + { + if (task.isSuccessful()) { + loadingBar.dismiss(); + Toast.makeText(AddTest.this, "Protocol is added successfully ", Toast.LENGTH_SHORT).show(); + + } + else + { + loadingBar.dismiss(); + String message = task.getException().toString(); + Toast.makeText(AddTest.this, "Error: " + message, Toast.LENGTH_SHORT).show(); + } + } + }); + } + + + + @Override + public void onBackPressed() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setCancelable(false); + builder.setMessage("Do you want to Exit ?"); + + builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + Intent intent = new Intent(AddTest.this, MainActivity.class); + connect.performClick(); + + finish(); + startActivity(intent); + + + + + } + }); + builder.setNegativeButton("No", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + + + + @Override + protected void onPause() { + super.onPause(); + msound.release(); + } + + + + @Override + public void onResume() { + super.onResume(); + msound=MediaPlayer.create(this,R.raw.notification); + } + + +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/CreatePassword.java b/app/src/main/java/no/spca/android/iisc/SPCA/CreatePassword.java new file mode 100644 index 0000000..d275c5d --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/CreatePassword.java @@ -0,0 +1,110 @@ +package no.spca.android.iisc.SPCA; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; + +import androidx.appcompat.app.AppCompatActivity; + +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.Model.RegisterHelper; + + +public class CreatePassword extends AppCompatActivity { + private Button next; + + String name,phonenumber,num1,num2; + private EditText passworddata; + private EditText ConfirmPassword; + + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_create__password); + passworddata=findViewById(R.id.password); + ConfirmPassword=findViewById(R.id.confirmpassword); + next=findViewById(R.id.next); + + next.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + num1 = ConfirmPassword.getText().toString(); + num2 = passworddata.getText().toString(); + if (!isOnline()) { + //Create an alertdialog + AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(CreatePassword.this); + Checkbuilder.setTitle("No Internet Connection !"); + Checkbuilder.setMessage("Check Your Internet Connection."); + //Builder Retry Button + + Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + dialog.cancel(); + } + }); + + Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + + AlertDialog alert = Checkbuilder.create(); + alert.show(); + + } else { + + + if (num1.equals(num2)) { + Intent intent = new Intent(CreatePassword.this, LoginScreen.class); + name = getIntent().getStringExtra("username"); + + String phonenumberk = getIntent().getStringExtra("mobile"); + phonenumber = phonenumberk; + + FirebaseDatabase rootNode = FirebaseDatabase.getInstance(); + DatabaseReference reference = rootNode.getReference("USERS"); + RegisterHelper addNewUser = new RegisterHelper(name, phonenumber, num1); + + reference.child(phonenumber).setValue(addNewUser); + intent.putExtra("mobile", phonenumber); + intent.putExtra("username", name); + + Toast.makeText(CreatePassword.this, "You are Registered Successfully ", Toast.LENGTH_SHORT).show(); + startActivity(intent); + + + } else { + ConfirmPassword.setError("Password does not match"); + } + } + } + + }); + + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/CycleManager.java b/app/src/main/java/no/spca/android/iisc/SPCA/CycleManager.java new file mode 100644 index 0000000..9e29383 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/CycleManager.java @@ -0,0 +1,357 @@ + +package no.spca.android.iisc.SPCA; + +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.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.spca.android.iisc.battery.BatteryManager; +import no.spca.android.iisc.SPCA.callback.CycleDataCallback; +import no.spca.android.iisc.parser.CycleParser; + +public class CycleManager extends BatteryManager { + + static final UUID SERVICE_UUID = UUID.fromString("00001500-1212-efde-1523-785feabcd123"); private static final UUID TEMP_READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001514-1212-efde-1523-785feabcd123"); private static final UUID CLOCK_READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001514-1212-efde-1523-785feabcd123"); private static final UUID D_TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001504-1212-efde-1523-785feabcd123"); private static final UUID A_TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001506-1212-efde-1523-785feabcd123"); private static final UUID E_TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001508-1212-efde-1523-785feabcd123"); private static final UUID L_TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001515-1212-efde-1523-785feabcd123"); private static final UUID O_TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001502-1212-efde-1523-785feabcd123"); private static final UUID S_TEMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001510-1212-efde-1523-785feabcd123"); private static final UUID D_TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001505-1212-efde-1523-785feabcd123"); private static final UUID A_TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001507-1212-efde-1523-785feabcd123"); private static final UUID E_TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001509-1212-efde-1523-785feabcd123"); private static final UUID L_TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001516-1212-efde-1523-785feabcd123"); private static final UUID O_TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001503-1212-efde-1523-785feabcd123"); private static final UUID S_TIME_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001511-1212-efde-1523-785feabcd123"); private static final UUID N_PCR_C_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001512-1212-efde-1523-785feabcd123"); private static final UUID AMP_WRITABLE_CHARACTERISTIC_UUID = UUID.fromString("00001513-1212-efde-1523-785feabcd123"); private static final UUID OTHER_SERVICE_UUID = UUID.fromString("00001800-0000-1000-8000-00805f9b34fb"); private static final UUID READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001801-0000-1000-8000-00805f9b34fb"); private BluetoothGattCharacteristic mReadBlockTempCharacteristic, mSetDTempCharacteristic, mSetDTimeCharacteristic, mSetATempCharacteristic, mSetATimeCharacteristic, mSetETempCharacteristic, mSetETimeCharacteristic, mSetNPcrCCharacteristic, mAmpStartStopCharacteristic, mDeviceNameCharacteristic, mRequiredCharacteristic, mOptionalCharacteristic + ,mReadclockCharacteristic,mSetLTempCharacteristic,mSetOTempCharacteristic,mSetLTimeCharacteristic,mSetOTimeCharacteristic,mSetSTimeCharacteristic, mSetSTempCharacteristic; + + public CycleManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + super.initialize(); + requestMtu(43)//requestMtu(43) + .with((device, mtu) -> log(LogContract.Log.Level.APPLICATION, "MTU changed to " + mtu)) + .done(device -> { + }) + .fail((device, status) -> log(Log.WARN, "MTU change not supported")) + .enqueue(); + + setNotificationCallback(mReadBlockTempCharacteristic) + .with(new CycleDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, CycleParser.parse(data)); + super.onDataReceived(device, data); + } + + @Override + public void onSampleValueReceived(@NonNull final BluetoothDevice device, final int value) { + mCallbacks.onSampleValueReceived(device, value); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(Log.WARN, "Invalid data received: " + data); + } + }); + + enableNotifications(mReadBlockTempCharacteristic) + .with((device, data) -> log(Log.DEBUG, "Data sent: " + data)) + .done(device -> log(LogContract.Log.Level.APPLICATION, "Notifications enabled successfully")) + .fail((device, status) -> log(Log.WARN, "Failed to enable notifications")) + .enqueue(); + + + } + + + + + + + + + + + + + + + + + + + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(SERVICE_UUID); + if (service != null) { + mReadBlockTempCharacteristic = service.getCharacteristic(TEMP_READABLE_CHARACTERISTIC_UUID); + mReadclockCharacteristic=service.getCharacteristic(CLOCK_READABLE_CHARACTERISTIC_UUID); + mSetDTempCharacteristic = service.getCharacteristic(D_TEMP_WRITABLE_CHARACTERISTIC_UUID); + mSetDTimeCharacteristic = service.getCharacteristic(D_TIME_WRITABLE_CHARACTERISTIC_UUID); + mSetATempCharacteristic = service.getCharacteristic(A_TEMP_WRITABLE_CHARACTERISTIC_UUID); + mSetATimeCharacteristic = service.getCharacteristic(A_TIME_WRITABLE_CHARACTERISTIC_UUID); + mSetETempCharacteristic = service.getCharacteristic(E_TEMP_WRITABLE_CHARACTERISTIC_UUID); + mSetETimeCharacteristic = service.getCharacteristic(E_TIME_WRITABLE_CHARACTERISTIC_UUID); + + mSetLTempCharacteristic = service.getCharacteristic(L_TEMP_WRITABLE_CHARACTERISTIC_UUID); + mSetLTimeCharacteristic = service.getCharacteristic(L_TIME_WRITABLE_CHARACTERISTIC_UUID); + mSetOTempCharacteristic = service.getCharacteristic(O_TEMP_WRITABLE_CHARACTERISTIC_UUID); + mSetOTimeCharacteristic = service.getCharacteristic(O_TIME_WRITABLE_CHARACTERISTIC_UUID); +mSetSTimeCharacteristic=service.getCharacteristic(S_TIME_WRITABLE_CHARACTERISTIC_UUID); + mSetSTempCharacteristic=service.getCharacteristic(S_TEMP_WRITABLE_CHARACTERISTIC_UUID); + + + mSetNPcrCCharacteristic = service.getCharacteristic(N_PCR_C_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 && mReadclockCharacteristic != null && mSetDTempCharacteristic != null && mSetDTimeCharacteristic!= null && mSetATempCharacteristic != null && mSetATimeCharacteristic!= null && mSetETempCharacteristic != null && mSetLTempCharacteristic != null && mSetETimeCharacteristic!= null && mSetOTempCharacteristic != null && mSetLTimeCharacteristic!= null && mSetSTimeCharacteristic!= null && mSetSTempCharacteristic!= null && mSetOTimeCharacteristic!= null && mSetNPcrCCharacteristic!= null && mAmpStartStopCharacteristic != null ; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + super.isOptionalServiceSupported(gatt); + + final BluetoothGattService service = gatt.getService(SERVICE_UUID); + if (service != null) { + mOptionalCharacteristic = service.getCharacteristic(READABLE_CHARACTERISTIC_UUID); + } + return mOptionalCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + + mRequiredCharacteristic = null; + mDeviceNameCharacteristic = null; + mOptionalCharacteristic = null; + } + + @Override + protected void onDeviceReady() { + super.onDeviceReady(); + + readCharacteristic(mReadBlockTempCharacteristic) + .with((device, data) -> { + 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(); + readCharacteristic(mReadclockCharacteristic) + .with((device, data) -> { + 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(); + } + + }; + + + + + + + + + + + + + + + + + + + + //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 sendDTime(int d_time) { + log(Log.WARN, "Write D Time Duration \"" + d_time + "\""); + final byte d_time_in_byte = (byte) d_time; + writeCharacteristic(mSetDTimeCharacteristic, Data.opCode(d_time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + } + void sendATime(int a_time) { + log(Log.WARN, "Write A Time Duration \"" + a_time + "\""); + final byte a_time_in_byte = (byte) a_time; + writeCharacteristic(mSetATimeCharacteristic, Data.opCode(a_time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + } + + void sendLTime(int l_time) { + log(Log.WARN, "Write A Time Duration \"" + l_time + "\""); + final byte l_time_in_byte = (byte) l_time; + writeCharacteristic(mSetLTimeCharacteristic, Data.opCode(l_time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + } + void sendOTime(int o_time) { + log(Log.WARN, "Write A Time Duration \"" + o_time + "\""); + final byte a_time_in_byte = (byte) o_time; + writeCharacteristic(mSetOTimeCharacteristic, Data.opCode(a_time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + } + void sendSTime(int s_time) { + log(Log.WARN, "Write A Time Duration \"" + s_time + "\""); + final byte s_time_in_byte = (byte) s_time; + writeCharacteristic(mSetSTimeCharacteristic, Data.opCode(s_time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + } + + + void sendETime(int e_time) { + log(Log.WARN, "Write E Time Duration \"" + e_time + "\""); + final byte e_time_in_byte = (byte) e_time; + writeCharacteristic(mSetETimeCharacteristic, Data.opCode(e_time_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Time")) + .split() + .enqueue(); + } + + + //Set Temp + void sendDTemp(int d_temp) { + log(Log.WARN, "Write D temp \"" + d_temp + "\""); + final byte d_temp_in_byte = (byte) d_temp; + writeCharacteristic(mSetDTempCharacteristic, Data.opCode(d_temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + + void sendSTemp(int s_temp) { + log(Log.WARN, "Write D temp \"" + s_temp + "\""); + final byte s_temp_in_byte = (byte) s_temp; + writeCharacteristic(mSetSTempCharacteristic, Data.opCode(s_temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + + + + + + + + + + void sendLTemp(int l_temp) { + log(Log.WARN, "Write D temp \"" + l_temp + "\""); + final byte l_temp_in_byte = (byte) l_temp; + writeCharacteristic(mSetLTempCharacteristic, Data.opCode(l_temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + + + + void sendOTemp(int o_temp) { + log(Log.WARN, "Write D temp \"" + o_temp + "\""); + final byte d_temp_in_byte = (byte) o_temp; + writeCharacteristic(mSetOTempCharacteristic, Data.opCode(d_temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + + + + + + + + + + void sendATemp(int a_temp) { + log(Log.WARN, "Write A temp \"" + a_temp + "\""); + final byte a_temp_in_byte = (byte) a_temp; + writeCharacteristic(mSetATempCharacteristic, Data.opCode(a_temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + void sendETemp(int e_temp) { + log(Log.WARN, "Write E temp \"" + e_temp + "\""); + final byte e_temp_in_byte = (byte) e_temp; + writeCharacteristic(mSetETempCharacteristic, Data.opCode(e_temp_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + + void sendNPcrC(int n_pcr_c) { + log(Log.WARN, "Write E temp \"" + n_pcr_c + "\""); + final byte n_pcr_c_in_byte = (byte) n_pcr_c; + writeCharacteristic(mSetNPcrCCharacteristic, Data.opCode(n_pcr_c_in_byte)) + .with((device, data) -> log(LogContract.Log.Level.APPLICATION, + "\"" + data.size() + "\" Set Temp")) + .split() + .enqueue(); + } + + + +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/CycleService.java b/app/src/main/java/no/spca/android/iisc/SPCA/CycleService.java new file mode 100644 index 0000000..2ab0a26 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/CycleService.java @@ -0,0 +1,209 @@ + + +package no.spca.android.iisc.SPCA; + +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.spca.android.iisc.FeaturesActivity; +import no.spca.android.iisc.R; +import no.spca.android.iisc.NotificationData; +import no.spca.android.iisc.profile.BleProfileService; +import no.spca.android.iisc.profile.LoggableBleManager; + +public class CycleService extends BleProfileService implements SPCAManagerCallbacks { + public static final String BROADCAST_TEMPLATE_MEASUREMENT = "no.spca.android.iisc.template.BROADCAST_MEASUREMENT"; + + public static final String EXTRA_DATA = "no.spca.android.iisc.template.EXTRA_DATA"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.spca.android.iisc.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.spca.android.iisc.EXTRA_BATTERY_LEVEL"; + + private final static String ACTION_DISCONNECT = "no.spca.android.iisc.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 CycleManager mManager; + + private final LocalBinder mBinder = new TemplateBinder(); + + class TemplateBinder extends LocalBinder { + + + public void heatingSwitch(int state){ + mManager.heatingSwitch(state); + } + public void sendDTemp(int d_temp) { + mManager.sendDTemp(d_temp); + } + public void sendATemp(int a_temp) { + mManager.sendATemp(a_temp); + } + public void sendETemp(int e_temp) { + mManager.sendETemp(e_temp); + } + + public void sendSTemp(int s_temp) { + mManager.sendSTemp(s_temp); + } + + + + public void sendLTemp(int l_temp) { + mManager.sendLTemp(l_temp); + } + public void sendOTemp(int o_temp) { + mManager.sendOTemp(o_temp); + } + + + + + public void sendDTime(int d_time) { + mManager.sendDTime(d_time); + } + public void sendATime(int a_time) { + mManager.sendATime(a_time); + } + public void sendETime(int e_time) { + mManager.sendETime(e_time); + } + + + + + + + + + public void sendSTime(int s_time) { + mManager.sendSTime(s_time); + } + + public void sendLTime(int l_time) { + mManager.sendLTime(l_time); + } + public void sendOTime(int o_time) { mManager.sendOTime(o_time); } + + + public void sendNPcrN(int n_pcr_c) { + mManager.sendNPcrC(n_pcr_c); + } + + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new CycleManager(this); + } + + @Override + public void onCreate() { + super.onCreate(); + + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + cancelNotification(); + } + + @Override + protected void onUnbind() { + 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) { + } + } + + + + + + + + + + + + + + + + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + + } + + + 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, AddTest.class); + + 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, NotificationData.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); + final Notification notification = builder.build(); + final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + nm.notify(NOTIFICATION_ID, notification); + } + + + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + + 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/spca/android/iisc/SPCA/Datashow.java b/app/src/main/java/no/spca/android/iisc/SPCA/Datashow.java new file mode 100644 index 0000000..0b7d77f --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/Datashow.java @@ -0,0 +1,648 @@ + +package no.spca.android.iisc.SPCA; + +import android.app.ProgressDialog; +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.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import android.os.CountDownTimer; +import android.os.Handler; +import android.util.Log; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Switch; +import android.widget.TextView; + + +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.ValueEventListener; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.Model.Tests; +import no.spca.android.iisc.profile.BleProfileService; +import no.spca.android.iisc.profile.BleProfileServiceReadyActivity; + + + +public class Datashow extends BleProfileServiceReadyActivity { + @SuppressWarnings("unused") + private final String TAG = "AddTest"; + + private TextView mValueView; + private EditText mFETempValueView; + private EditText mFETimeValueView; + private String TestID = ""; + + private TextView mCycleView; + private ProgressDialog loadingBar; + private String number; + + + private DatabaseReference TestRef; + + private TextView mHeatingStatusView; + private int seconds1 ,seconds2; + private Switch mHeatingState ; + + private EditText mDTimeValueView; + private Integer mDSetTime ; + private EditText mLTimeValueView; + private Integer mLSetTime ; + private EditText mOTimeValueView; + private Integer mOSetTime ; + private String time1,time2,time3; + private Date date1,date2,date3; + + + + private final int valuedata=0; + private final int j=0; + private final Handler handler = new Handler(); + private Runnable runnable; + + + private EditText mATimeValueView; + private Integer mASetTime ; + private EditText mETimeValueView; + private Integer mESetTime ; + + private EditText mDTempValueView; + private Integer mDSetTemp ; + private EditText mATempValueView; + private Button save; + private Integer mASetTemp ; + private EditText mETempValueView; + private Integer mESetTemp ; + private EditText protocol_Name; + + + private EditText mLTempValueView; + private Integer mLSetTemp ; + private EditText mOTempValueView; + private Integer mOSetTemp ; + private long diff=0; + private long diffSeconds=0; + private long diffMinutes=0; + private long diffHours=0; + private long diff1=0; + private long diffSeconds1=0; + private long diffMinutes1=0; + + private long diffHours1=0; + private int FLAG=0; + + + private int count=0; + private int valuw=0; + + int i=0; + + private EditText mNPcrCView; + private Integer mNPcrC ; + private Timer T; + + + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_protocol); + loadingBar = new ProgressDialog(this); + + + setGUI(); + TestID = getIntent().getStringExtra("pid"); + + Log.e("main", "error id "+TestID); + getTestDetails(TestID); + + + + + + } + + private void setGUI() { + mValueView = findViewById(R.id.Temp_Value); + mCycleView = findViewById(R.id.RemTime_Value); +save=findViewById(R.id.action_save); + mFETempValueView=findViewById(R.id.S_Temp_Set); + mFETimeValueView=findViewById(R.id.S_Time_Set); + protocol_Name=findViewById(R.id.protocol_name); + + mDTempValueView = findViewById(R.id.D_Temp_Set); + mDTimeValueView = findViewById(R.id.D_Time_Set); + mATempValueView = findViewById(R.id.A_Temp_Set); + mATimeValueView = findViewById(R.id.A_Time_Set); + mETempValueView = findViewById(R.id.E_Temp_Set); + mETimeValueView = findViewById(R.id.E_Time_Set); + mLTempValueView=findViewById(R.id.L_Temp_Set); + mOTempValueView=findViewById(R.id.O_Temp_Set); + mLTimeValueView = findViewById(R.id.L_Time_Set); + + mOTimeValueView = findViewById(R.id.O_Time_Set); + + + + T=new Timer(); + + + SharedPreferences preferences689 = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + + number = preferences689.getString("Phone", null); + + TestRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + mNPcrCView = findViewById(R.id.N_Pcr_C); + + + mHeatingState = findViewById(R.id.heating_state); + mHeatingStatusView= findViewById(R.id.heating_status_text); + + mHeatingState.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + startCounter(); + + + i=1; + if(date2 !=null && date1 !=null) { + SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + try { + date1 = format.parse(time1); + date2 = format.parse(time2); + diff = (date2.getTime() - date1.getTime()); + diffSeconds = diff / 1000 % 60; + diffMinutes = diff / (60 * 1000) % 60; + diffHours = diff / (60 * 60 * 1000); + + + + } catch (ParseException e) { + e.printStackTrace(); + } + + + } + + Log.e("main", "error data inside " + valuedata); + + getService().heatingSwitch(1); + + mDSetTemp = Integer.parseInt(mDTempValueView.getText().toString()); + getService().sendDTemp(mDSetTemp); + + mDSetTime = Integer.parseInt(mDTimeValueView.getText().toString()); + getService().sendDTime(mDSetTime); + + mLSetTemp = Integer.parseInt(mLTempValueView.getText().toString()); + getService().sendLTemp(mLSetTemp); + mLSetTime = Integer.parseInt(mLTimeValueView.getText().toString()); + getService().sendLTime(mLSetTime); + + mOSetTemp = Integer.parseInt(mOTempValueView.getText().toString()); + getService().sendOTemp(mOSetTemp); + mOSetTime = Integer.parseInt(mOTimeValueView.getText().toString()); + getService().sendOTime(mOSetTime); + + + mASetTemp = Integer.parseInt(mATempValueView.getText().toString()); + getService().sendATemp(mASetTemp); + mASetTime = Integer.parseInt(mATimeValueView.getText().toString()); + getService().sendATime(mASetTime); + + mESetTemp = Integer.parseInt(mETempValueView.getText().toString()); + getService().sendETemp(mESetTemp); + mESetTime = Integer.parseInt(mETimeValueView.getText().toString()); + getService().sendETime(mESetTime); + + mNPcrC = Integer.parseInt(mNPcrCView.getText().toString()); + getService().sendNPcrN(mNPcrC); + Log.e("main", "error 34" + mDSetTemp); + + Log.e("main", "error 2 " + mDSetTemp); + Log.e("main", "error data box " + valuedata); + + + + + + } + else { + getService().heatingSwitch(0); + } + mHeatingStatusView.setText(isChecked ? R.string.Heating_block_on : R.string.Heating_block_off); + }); + + + + } + + @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() { + mValueView.setText("wait"); + mCycleView.setText("wait"); + + + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.template_feature_title; + } + + + + @Override + protected int getDefaultDeviceName() { + return R.string.template_default_name; + } + + @Override + protected UUID getFilterUUID() { + return CycleManager.SERVICE_UUID; + } + + @Override + protected Class getServiceClass() { + return CycleService.class; + } + + @Override + protected void onServiceBound(final CycleService.TemplateBinder binder) { + } + + @Override + protected void onServiceUnbound() { + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + } + + @SuppressWarnings("unused") + private void setValueOnView(@NonNull final BluetoothDevice device, int value) { + } + + + + + + + + + + + + + + + + + + @SuppressWarnings("unused") + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int value) { + + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_DEVICE); + + if (no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT.equals(action)) { + int value = intent.getIntExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_DATA, 0); + setValueOnView(device, value); + valuw=value; + if(value==0) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time1 = df.format(Calendar.getInstance().getTime()); + + + Log.e("main", "error 403 " +time1); + + + + + + } + + else if(value ==1 ) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time2 = df.format(Calendar.getInstance().getTime()); + + + Log.e("main", "error 404 " +time2); + LocalDateTime date = LocalDateTime.now(); + seconds1 = date.toLocalTime().toSecondOfDay(); + + + } + else if(value ==2 ) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time3 = df.format(Calendar.getInstance().getTime()); + + try { + date1 = df.parse(time1); + date2 = df.parse(time2); + date3=df.parse(time3); + + } catch (ParseException e) { + e.printStackTrace(); + } + Log.e("main", "date 1 " + date2.getTime()); + Log.e("main", "date 2 " + date1.getTime()); + + + diff1 = date3.getTime() - date2.getTime(); + Log.e("main", "difference minute " + diffMinutes); + + + Log.e("main", "difference minute " + diffMinutes); + + diffSeconds1 = diff1 / 1000 % 60; + diffMinutes1 = diff1 / (60 * 1000) % 60; + diffHours1 = diff1/ (60 * 60 * 1000); + Log.e("main", "date difference " + diffMinutes1); + + + + Log.e("main", "error 404 " +time2); + + + + } + + if(time1 !=null && time2 !=null &&diffSeconds1==1 ) { + + SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + try { + date1 = format.parse(time1); + date2 = format.parse(time2); + Log.e("main", "date 1 " + date2.getTime()); + Log.e("main", "date 2 " + date1.getTime()); + + + diff = date2.getTime() - date1.getTime(); + Log.e("main", "difference minute " + diffMinutes); + + diffSeconds = diff / 1000 % 60; + diffMinutes = diff / (60 * 1000) % 60; + diffHours = diff / (60 * 60 * 1000); + Log.e("main", "date difference " + diffMinutes); + FLAG=1; + + + + } catch (ParseException e) { + e.printStackTrace(); + } + + + } + else + { + } + + + } else if (no.spca.android.iisc.SPCA.CycleService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_BATTERY_LEVEL, 0); + onBatteryLevelChanged(device, batteryLevel); + } + + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT); + intentFilter.addAction(no.spca.android.iisc.SPCA.CycleService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } + private void startCounter1() + { + T.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + + count++; + Log.e("main", "Currnet " + count); + + } + }); + } + }, 10000, 10000); + + + } + + private void startCounter() + + { + + + + T.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + if(FLAG==1) + { + mNPcrC=mNPcrC-1; + long cycle=mNPcrC.longValue(); + countdown(diff *cycle); + + T.cancel(); + } + + + + } + }); + } + }, 1000, 1000); + + + + + } + private void countdown(long second) + { + new CountDownTimer(second, 1000) { + + public void onTick(long millisUntilFinished) { + + long diffSecondsl = millisUntilFinished / 1000 % 60; + long diffMinutesl = millisUntilFinished / (60 * 1000) % 60; + long diffhourl = millisUntilFinished / (60 *60 * 1000) % 60; + mValueView.setText(diffhourl+"h"+diffMinutesl+"m"+diffSecondsl+"s"); + int cyclecurrent=(mNPcrC-valuw)+1; + if(cyclecurrent<0) + { + mCycleView.setText("Finish"); + + } + else { + + mCycleView.setText(String.valueOf(cyclecurrent)); + } + } + + public void onFinish() { + mValueView.setText("Finish"); + mCycleView.setText("Finish"); + } + }.start(); + + } + + + @Override + public void onPointerCaptureChanged(boolean hasCapture) { + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } + + + + + +private void getTestDetails(String TestID) + { + DatabaseReference productsRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + + productsRef.child(TestID).addValueEventListener(new ValueEventListener() { +@Override +public void onDataChange(DataSnapshot dataSnapshot) + { + if (dataSnapshot.exists()) + { + + + Tests products = dataSnapshot.getValue(Tests.class); + + + mLTempValueView.setText(products.getRev_trans_temp()); + + mLTimeValueView.setText(products.getRev_trans_time()); + + mOTempValueView.setText(products.getIntial_den_temp()); + + mOTimeValueView.setText(products.getIntial_den_time()); + + mDTempValueView.setText(products.getDen_temp()); + + + mDTimeValueView.setText(products.getDen_time()); + + + mATempValueView.setText(products.getAnn_temp()); +protocol_Name.setText(products.getName_protocol()); + + + + mATimeValueView.setText(products.getAnn_time()); + + + + mETempValueView.setText(products.getExt_temp()); + + mETimeValueView.setText(products.getExt_time()); + + mFETempValueView.setText(products.getFext_temp()); + + mFETimeValueView.setText(products.getFext_time()); + + + mNPcrCView.setText(products.getNo_of_pcr_cycle()); + + + + + + + + + + + + mLTempValueView.setText(products.getRev_trans_temp()); + + mLTimeValueView.setText(products.getRev_trans_time()); + mATempValueView.setText(products.getAnn_temp()); + mATimeValueView.setText(products.getAnn_time()); + mDTempValueView.setText(products.getDen_temp()); + mDTimeValueView.setText(products.getDen_time()); + + + } + } + +@Override +public void onCancelled(DatabaseError databaseError) { + + } + }); + } + + } + + + + + + + diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/FontAwesome.java b/app/src/main/java/no/spca/android/iisc/SPCA/FontAwesome.java new file mode 100644 index 0000000..d618508 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/FontAwesome.java @@ -0,0 +1,35 @@ +package no.spca.android.iisc.SPCA; + + +import android.content.Context; +import android.graphics.Typeface; +import android.util.AttributeSet; + +import androidx.appcompat.widget.AppCompatTextView; + +public class FontAwesome extends AppCompatTextView { + + + public FontAwesome(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + init(); + } + + public FontAwesome(Context context, AttributeSet attrs) { + super(context, attrs); + init(); + } + + public FontAwesome(Context context) { + super(context); + init(); + } + + private void init() { + + Typeface tf = Typeface.createFromAsset(getContext().getAssets(), + "fa-solid-900.ttf"); + setTypeface(tf); + } + +} \ No newline at end of file diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/ForgetPassword.java b/app/src/main/java/no/spca/android/iisc/SPCA/ForgetPassword.java new file mode 100644 index 0000000..637240c --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/ForgetPassword.java @@ -0,0 +1,242 @@ +package no.spca.android.iisc.SPCA; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ProgressBar; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import com.chaos.view.PinView; +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.Task; +import com.google.android.gms.tasks.TaskExecutors; +import com.google.firebase.FirebaseException; +import com.google.firebase.auth.AuthResult; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.auth.PhoneAuthCredential; +import com.google.firebase.auth.PhoneAuthProvider; +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.Query; +import com.google.firebase.database.ValueEventListener; +import com.hbb20.CountryCodePicker; + +import java.util.concurrent.TimeUnit; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.VerifyOTP.VerifyOtpForgetPassword; + + +public class ForgetPassword extends AppCompatActivity { + + private String verificationid; + private FirebaseAuth mAuth; + private final int code = 91; + private Button nextactivity; + private ProgressBar progressBar; + CountryCodePicker ccp; + PinView pinFromUser; + String mobile; + private EditText editTextnumber; + boolean exists; + String phonenum; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_forget__password); + editTextnumber=findViewById(R.id.editTextMobile); + ccp=findViewById(R.id.ccp); + ccp.registerCarrierNumberEditText(editTextnumber); + mAuth = FirebaseAuth.getInstance(); + + + findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (!isOnline()) { + //Create an alertdialog + AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(ForgetPassword.this); + Checkbuilder.setTitle("No Internet Connection !"); + Checkbuilder.setMessage("Check Your Internet Connection."); + //Builder Retry Button + + Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + dialog.cancel(); + } + }); + + Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + + AlertDialog alert = Checkbuilder.create(); + alert.show(); + + } else { + + mobile = editTextnumber.getText().toString().trim(); + mobile = mobile.replaceAll("[^0-9]", ""); + + + phonenum = ccp.getFullNumberWithPlus(); + if(mobile.equals("")) + { + editTextnumber.setError("Enter the contact number"); + } + + + Query chekuser = FirebaseDatabase.getInstance().getReference("USERS").orderByChild("number").equalTo(mobile); + chekuser.addListenerForSingleValueEvent(new ValueEventListener() { + @Override + public void onDataChange(@NonNull DataSnapshot dataSnapshot) { + if (dataSnapshot.exists()) { + Intent intent = new Intent(ForgetPassword.this, VerifyOtpForgetPassword.class); + Toast.makeText(ForgetPassword.this, "We Have Sent the OTP to your mentioned Number", Toast.LENGTH_SHORT).show(); + intent.putExtra("mobilecode", phonenum); + intent.putExtra("mobile", mobile); + + startActivity(intent); + + + } else { + editTextnumber.setError("No Such User Exists"); + + } + + } + + @Override + public void onCancelled(@NonNull DatabaseError databaseError) { + Log.e("Raman", "Received an exception check chexk " + databaseError.getMessage()); + + } + }); + + + } + } + + }); + + } + private void verifyCode(String code){ + PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationid, code); + signInWithCredential(credential); + } + + private void signInWithCredential(PhoneAuthCredential credential) { + mAuth.signInWithCredential(credential) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + + Intent intent = new Intent(ForgetPassword.this, ForgetPasswordReset.class); + intent.putExtra("mobile", mobile); + + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + + + startActivity(intent); + + } else { + Toast.makeText(ForgetPassword.this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); + } + } + + }); + } + + private void sendVerificationCode(String number){ + + PhoneAuthProvider.getInstance().verifyPhoneNumber( + number, + 60, + TimeUnit.SECONDS, + (Activity) TaskExecutors.MAIN_THREAD, + mCallBack + ); + } + + private final PhoneAuthProvider.OnVerificationStateChangedCallbacks + mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { + + @Override + public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { + super.onCodeSent(s, forceResendingToken); + verificationid = s; + } + + @Override + public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { + String code = phoneAuthCredential.getSmsCode(); + if (code != null){ + progressBar.setVisibility(View.VISIBLE); + pinFromUser.setText(code); + verifyCode(code); + } + } + + @Override + public void onVerificationFailed(FirebaseException e) { + Toast.makeText(ForgetPassword.this, e.getMessage(), Toast.LENGTH_LONG).show(); + + } + }; + + + + + private void checkuserexist(String number) + { + Query chekuser= FirebaseDatabase.getInstance().getReference("USERS").orderByChild("number").equalTo(number); + chekuser.addListenerForSingleValueEvent(new ValueEventListener() { + @Override + public void onDataChange(@NonNull DataSnapshot dataSnapshot) { + exists= dataSnapshot.exists(); + + + } + + @Override + public void onCancelled(@NonNull DatabaseError databaseError) { + Toast.makeText(ForgetPassword.this,databaseError.getMessage(), Toast.LENGTH_SHORT).show(); + + } + }); + + + + + + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } + +} \ No newline at end of file diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/ForgetPasswordReset.java b/app/src/main/java/no/spca/android/iisc/SPCA/ForgetPasswordReset.java new file mode 100644 index 0000000..976f8cb --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/ForgetPasswordReset.java @@ -0,0 +1,69 @@ +package no.spca.android.iisc.SPCA; + + +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; + +import androidx.appcompat.app.AppCompatActivity; + +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; + +import no.spca.android.iisc.R; + +public class ForgetPasswordReset extends AppCompatActivity { + private Button next; + + String phonenumber,num1,num2; + private EditText passworddata; + private EditText ConfirmPassword; + + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_create__password); + passworddata=findViewById(R.id.password); + ConfirmPassword=findViewById(R.id.confirmpassword); + next=findViewById(R.id.next); + + + + next.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + num1 = ConfirmPassword.getText().toString(); + num2=passworddata.getText().toString(); + if(num1.equals(num2)) { + + Intent intent = new Intent(ForgetPasswordReset.this, LoginScreen.class); + + String phonenumberk = getIntent().getStringExtra("mobile"); + phonenumber = phonenumberk; + + FirebaseDatabase rootNode = FirebaseDatabase.getInstance(); + DatabaseReference reference = rootNode.getReference("USERS"); + + + reference.child(phonenumber).child("password").setValue(num1); + Toast.makeText(ForgetPasswordReset.this, "Password Reset Successfully ", Toast.LENGTH_SHORT).show(); + startActivity(intent); + + } + else + { + ConfirmPassword.setError("Password does not match"); + } + } + }); + + + } +} + diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/GraphActivity.java b/app/src/main/java/no/spca/android/iisc/SPCA/GraphActivity.java new file mode 100644 index 0000000..08a4757 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/GraphActivity.java @@ -0,0 +1,488 @@ + +package no.spca.android.iisc.SPCA; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.hardware.Sensor; +import android.hardware.SensorManager; +import android.media.MediaPlayer; +import android.os.Bundle; + +import com.github.mikephil.charting.charts.LineChart; + + +import android.graphics.Color; +import android.util.Log; + + +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.os.CountDownTimer; +import android.os.Handler; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import com.github.mikephil.charting.components.Legend; +import com.github.mikephil.charting.components.XAxis; +import com.github.mikephil.charting.components.YAxis; +import com.github.mikephil.charting.data.Entry; +import com.github.mikephil.charting.data.LineData; +import com.github.mikephil.charting.data.LineDataSet; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.profile.BleProfileService; +import no.spca.android.iisc.profile.BleProfileServiceReadyActivity; + + + +public class GraphActivity extends BleProfileServiceReadyActivity { + @SuppressWarnings("unused") + private final String TAG = "AddTest"; + + private TextView mValueView; + private TextView mCycleView; + private ProgressDialog loadingBar; + + private Button save; + private String TestRandomKey, saveCurrentDate, saveCurrentTime,number; + + + + private LineChart mChart; + private Thread thread; + private final boolean plotData = true; + File filePath3 = null; + private DatabaseReference TestRef; + + + + + private TextView mHeatingStatusView; + private int seconds1 ,seconds2; + private Switch mHeatingState ; + + + + + private final Handler handler = new Handler(); + private Runnable runnable; + + + + + MediaPlayer msound; + + long l; + + + private int count=0; + private final int valuw=0; + + int i=0; + + private EditText mNPcrCView; + private Integer mNPcrC ; + private Timer T; + private Button connect ; + private Date currentf,currentTime; +String tim; + + + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_graph); + String value1 = getIntent().getExtras().getString("key6"); + Log.e("time", "time " + value1); + Toast.makeText(GraphActivity.this, "Please Connect to Bluetooth to check Temp Graph", Toast.LENGTH_SHORT).show(); + + msound= MediaPlayer.create(GraphActivity.this,R.raw.notification); + + + + connect = findViewById(R.id.action_connect); + + loadingBar = new ProgressDialog(this); + + setGUI(); + Log.e("time", "time " + tim); + + l=Long.parseLong(String.valueOf(value1)); + Log.e("time", "time " + l); + + startCounter(); + + + + + + mChart = (LineChart) findViewById(R.id.chart1); + + mChart.setDescription(""); + mChart.setNoDataText("No data for the moment "); + + mChart.setTouchEnabled(true); + mChart.setDefaultFocusHighlightEnabled(true); + mChart.setHighlightEnabled(true); + mChart.setDragEnabled(true); + mChart.setScaleEnabled(true); + mChart.setDrawGridBackground(false); + + mChart.setPinchZoom(true); + + mChart.setBackgroundColor(Color.WHITE); + + LineData data = new LineData(); + data.setValueTextColor(Color.BLACK); + + mChart.setData(data); + + Legend l = mChart.getLegend(); + + l.setForm(Legend.LegendForm.LINE); + l.setTextColor(Color.BLACK); + + XAxis xl = mChart.getXAxis(); + xl.setTextColor(Color.BLACK); + xl.setDrawGridLines(false); + xl.setAvoidFirstLastClipping(true); + YAxis yl = mChart.getAxisLeft(); + yl.setTextColor(Color.BLACK); + yl.setDrawGridLines(true); + yl.setAxisMaxValue(100f); + + YAxis yl2 = mChart.getAxisRight(); + yl2.setEnabled(false); + + + + + + + + + + + + + + + + + + + + + } + + private void setGUI() { + mValueView = findViewById(R.id.Temp_Value); + mCycleView = findViewById(R.id.RemTime_Value); + + T=new Timer(); + + + SharedPreferences preferences689 = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + + number = preferences689.getString("Phone", null); + TestRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + mNPcrCView = findViewById(R.id.N_Pcr_C); + mHeatingState = findViewById(R.id.heating_state); + mHeatingStatusView= findViewById(R.id.heating_status_text); + //mValueView.setText("fff"); + + } + + @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() { + mValueView.setText("wait"); + mCycleView.setText("wait"); + + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.template_feature_title; + } + + + + @Override + protected int getDefaultDeviceName() { + return R.string.template_default_name; + } + + @Override + protected UUID getFilterUUID() { + return TemperatureManager.SERVICE_UUID; + } + + @Override + protected Class getServiceClass() { + return TemperatureService.class; + } + + @Override + protected void onServiceBound(final TemperatureService.TemplateBinder binder) { + } + + @Override + protected void onServiceUnbound() { + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + } + + @SuppressWarnings("unused") + private void setValueOnView(@NonNull final BluetoothDevice device, int value) { + } + + + + @SuppressWarnings("unused") + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int value) { + + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(TemperatureService.EXTRA_DEVICE); + + if (TemperatureService.BROADCAST_TEMPLATE_MEASUREMENT1.equals(action)) { + int value = intent.getIntExtra(TemperatureService.EXTRA_DATA1, 0); + addEntry(Float.parseFloat(String.valueOf(value))); + mCycleView.setText(String.valueOf(value)); + + + + + } else if (TemperatureService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(TemperatureService.EXTRA_BATTERY_LEVEL, 0); + onBatteryLevelChanged(device, batteryLevel); + } + + } + }; + + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(TemperatureService.BROADCAST_TEMPLATE_MEASUREMENT1); + intentFilter.addAction(TemperatureService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } + private static IntentFilter makeIntentFilter1() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(TemperatureService.BROADCAST_TEMPLATE_MEASUREMENT1); + intentFilter.addAction(TemperatureService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } + + + + + private void startCounter() + + { + + + + T.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + + + countdown(l); + + T.cancel(); + + + + + } + }); + } + }, 1000, 1000); + + + + + } + private void countdown(long second) + { + new CountDownTimer(second, 1000) { + + public void onTick(long millisUntilFinished) { + //Log.d("LOGGER", "sec: " + millisUntilFinished / 1000); + //Log.d("LOGGER", "sec: " + millisUntilFinished / 1000); + long diffSecondsl = millisUntilFinished / 1000 % 60; + long diffMinutesl = millisUntilFinished / (60 * 1000) % 60; + long diffhourl = millisUntilFinished / (60 *60 * 1000) % 60; + + mValueView.setText(diffhourl+"h"+diffMinutesl+"m"+diffSecondsl+"s"); + + + + } + + public void onFinish() { + msound.start(); + msound.setLooping(true); + + mValueView.setText("Finish"); + mCycleView.setText("Finish"); + } + }.start(); + + } + + + @Override + public void onPointerCaptureChanged(boolean hasCapture) { + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } + + + + + private void addEntry(float value) + + { + LineData data=mChart.getData(); + if(data!=null) + { + LineDataSet set=data.getDataSetByIndex(0); + if (set == null) { + set = createSet(); + data.addDataSet(set); + } + data.addXValue(""); + data.addEntry(new Entry((float) value , + set.getEntryCount()), + 0); + mChart.notifyDataSetChanged(); + mChart.setVisibleXRange(6); + mChart.moveViewToX(data.getXValCount()-7); + } + + } + + + + private LineDataSet createSet() { + + LineDataSet set = new LineDataSet(null, "SPL Db"); + set.setDrawCubic(true); + set.setCubicIntensity(0.2f); + + set.setAxisDependency(YAxis.AxisDependency.LEFT); + set.setLineWidth(2f); + set.setColor(Color.BLUE); + set.setCircleColor(Color.BLUE); + set.setCircleSize(4f); + set.setFillAlpha(100); + set.setFillColor(Color.BLUE); + set.setHighLightColor(Color.rgb(244,117,177)); + set.setValueTextColor(Color.BLACK); + set.setValueTextSize(10f); + + + return set; + } + + + + @Override + public void onBackPressed() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setCancelable(false); + builder.setMessage("Do you want to Exit ?"); + + builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + Intent intent = new Intent(GraphActivity.this, MainActivity.class); + connect.performClick(); + finish(); + startActivity(intent); + + + + + } + }); + builder.setNegativeButton("No", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } + @Override + protected void onPause() { + super.onPause(); + msound.release(); + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/Interface/ItemClickListner.java b/app/src/main/java/no/spca/android/iisc/SPCA/Interface/ItemClickListner.java new file mode 100644 index 0000000..66abb07 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/Interface/ItemClickListner.java @@ -0,0 +1,9 @@ +package no.spca.android.iisc.SPCA.Interface; + + +import android.view.View; + +public interface ItemClickListner +{ + void onClick(View view, int position, boolean isLongClick); +} \ No newline at end of file diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/LoginScreen.java b/app/src/main/java/no/spca/android/iisc/SPCA/LoginScreen.java new file mode 100644 index 0000000..54d34f8 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/LoginScreen.java @@ -0,0 +1,215 @@ +package no.spca.android.iisc.SPCA; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.text.method.HideReturnsTransformationMethod; +import android.text.method.PasswordTransformationMethod; +import android.util.Patterns; +import android.view.View; +import android.view.animation.Animation; +import android.widget.Button; +import android.widget.CompoundButton; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.AppCompatCheckBox; + +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.Query; +import com.google.firebase.database.ValueEventListener; + +import no.spca.android.iisc.R; + + +public class LoginScreen extends AppCompatActivity { + + private TextView createaccount, forgetpassword; + private Button login; + private DatabaseReference databaseReference; + private EditText phonenumber, password; + String passworddata, phonenum, phonenumbers, name; + private ProgressDialog loadingBar; + public static final String Name = "nameKey"; + public static final String Phone = "phoneKey"; + + private AppCompatCheckBox checkbox; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_login__screen); + createaccount = findViewById(R.id.createaccount); + phonenumber = findViewById(R.id.contactnumber); + checkbox = (AppCompatCheckBox) findViewById(R.id.showpassword); + + password = findViewById(R.id.password); + checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { + if (isChecked) { + password.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); + } else { + password.setTransformationMethod(PasswordTransformationMethod.getInstance()); + } + } + }); + + loadingBar = new ProgressDialog(this); + + login = findViewById(R.id.login); + forgetpassword = findViewById(R.id.forgetpassword); + forgetpassword.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(LoginScreen.this, ForgetPassword.class); + startActivity(intent); + + } + }); + login.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (!isOnline()) { + //Create an alertdialog + AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(LoginScreen.this); + Checkbuilder.setTitle("No Internet Connection !"); + Checkbuilder.setMessage("Check Your Internet Connection."); + //Builder Retry Button + + Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + dialog.cancel(); + } + }); + + Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + + AlertDialog alert = Checkbuilder.create(); + alert.show(); + + } else { + String mobile = phonenumber.getText().toString().trim(); + phonenum = mobile; + final String passwordj = password.getText().toString().trim(); + + + if (mobile.equals("") || passwordj.equals("")) { + Toast.makeText(LoginScreen.this, "Please enter all the required fields", Toast.LENGTH_SHORT).show(); + + } else if (!Patterns.PHONE.matcher(mobile).matches()) { + + phonenumber.setError("Enter a valid number"); + + } else { + loadingBar.setTitle("Login Account"); + loadingBar.setMessage("Please wait, while we are checking the credentials."); + loadingBar.setCanceledOnTouchOutside(false); + loadingBar.show(); + + Query chekuser = FirebaseDatabase.getInstance().getReference("USERS").orderByChild("number").equalTo(phonenum); + chekuser.addListenerForSingleValueEvent(new ValueEventListener() { + @Override + public void onDataChange(@NonNull DataSnapshot dataSnapshot) { + if (dataSnapshot.exists()) { + String systempassword = dataSnapshot.child(phonenum).child("password").getValue(String.class); + + if (systempassword.equals(passwordj)) { + + Toast.makeText(LoginScreen.this, "logged in Successfully...", Toast.LENGTH_SHORT).show(); + loadingBar.dismiss(); + String name = dataSnapshot.child(phonenum).child("name").getValue(String.class); + + + SharedPreferences preferences = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + + editor.putString("Phone", phonenum); + editor.putString("Name", name); + + + editor.commit(); + + + Intent intent = new Intent(LoginScreen.this, MainActivity.class); + + + intent.putExtra("mobile", phonenum); + + startActivity(intent); + + } else { + loadingBar.dismiss(); + + Toast.makeText(LoginScreen.this, "Wrong Password", Toast.LENGTH_SHORT).show(); + } + } else { + loadingBar.dismiss(); + + Toast.makeText(LoginScreen.this, "No such user exists", Toast.LENGTH_SHORT).show(); + } + + } + + @Override + public void onCancelled(@NonNull DatabaseError databaseError) { + Toast.makeText(LoginScreen.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show(); + + } + }); + + + } + } + } + }); + createaccount.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(LoginScreen.this, Register.class); + startActivity(intent); + } + }); + } + + + @Override + public void onBackPressed() { + + finishAffinity(); + finish(); + } + + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } + + + + + +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/MainActivity.java b/app/src/main/java/no/spca/android/iisc/SPCA/MainActivity.java new file mode 100644 index 0000000..e745b14 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/MainActivity.java @@ -0,0 +1,220 @@ +package no.spca.android.iisc.SPCA; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.SearchView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.firebase.ui.database.FirebaseRecyclerAdapter; +import com.firebase.ui.database.FirebaseRecyclerOptions; +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.Query; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.Model.Tests; + + +public class MainActivity extends NavigationTop { + private DatabaseReference TestRef; + private RecyclerView recyclerView; + + private TextView info; + FloatingActionButton fasbs; + + String number; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + LayoutInflater inflater = (LayoutInflater) this + .getSystemService(LAYOUT_INFLATER_SERVICE); + View contentView = inflater.inflate(R.layout.activity_main, null, false); + draw.addView(contentView, 0); + + SharedPreferences preferences6 = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + + number = preferences6.getString("Phone", null); + fasbs=findViewById(R.id.fab); +info=findViewById(R.id.info); + Log.e("main", "error "+number); + TestRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + recyclerView = findViewById(R.id.recycler_view); + fasbs.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent=new Intent(MainActivity.this, AddTest.class); + startActivity(intent); + + } + }); + + LinearLayoutManager layoutManager1=new LinearLayoutManager(this); + + recyclerView.setLayoutManager(new GridLayoutManager(this, 1)); + + DisplayMetrics displayMetrics = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); + int height = displayMetrics.heightPixels / 8; + int spaceInPixel = 4; + recyclerView.addItemDecoration(new SpaceDecoration(spaceInPixel)); + + } + @Override + protected void onStart() + { + super.onStart(); + + + FirebaseRecyclerOptions options = + new FirebaseRecyclerOptions.Builder() + .setQuery(TestRef, Tests.class) + .build(); + + + FirebaseRecyclerAdapter adapter = + new FirebaseRecyclerAdapter(options) { + @Override + protected void onBindViewHolder(@NonNull TestViewHolder holder, int position, @NonNull final Tests model) + { + + holder.ProtocolName.setText(""+model.getName_protocol()); + holder.cycleNumber.setText("Number of Cycles : "+model.getNo_of_pcr_cycle()); +holder.txttimestamp.setText(model.getDate_protocol()); + + + //holder.txtProductDescription.setText(model.getSample()); + + holder.itemView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent=new Intent(MainActivity.this, TempDataShow.class); + Log.e("main", "error id"+model.getDen_temp()); + Log.e("main", "TestID"+model.getAnn_time()); + + intent.putExtra("pid",model.getRandom_key()); + startActivity(intent); + + } + }); + } + + @NonNull + @Override + public TestViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) + { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); + TestViewHolder holder = new TestViewHolder(view); + return holder; + } + }; + recyclerView.setAdapter(adapter); + adapter.startListening(); + } + private void firebasesearch(String data) + { + { + Query firebaseSearchQuery = TestRef.orderByChild("name_protocol").startAt(data).endAt(data + "\uf8ff"); + FirebaseRecyclerOptions options = + new FirebaseRecyclerOptions.Builder() + .setQuery(firebaseSearchQuery, Tests.class) + .build(); + + + FirebaseRecyclerAdapter adapter = + new FirebaseRecyclerAdapter(options) { + @Override + protected void onBindViewHolder(@NonNull final TestViewHolder holder, int position, @NonNull final Tests model) + { + holder.ProtocolName.setText(""+model.getName_protocol()); + holder.cycleNumber.setText("Number of Cycles : "+model.getNo_of_pcr_cycle()); + holder.txttimestamp.setText(model.getDate_protocol()); + //holder.txtProductDescription.setText(model.getSample()); + + holder.itemView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent=new Intent(MainActivity.this, Datashow.class); + Log.e("main", "error id"+model.getDen_temp()); + Log.e("main", "TestID"+model.getAnn_time()); + + intent.putExtra("pid",model.getIntial_den_temp()); + startActivity(intent); + + + + } + + }); + } + + @NonNull + @Override + public TestViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) + { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); + TestViewHolder holder = new TestViewHolder(view); + return holder; + } + }; + recyclerView.setAdapter(adapter); + adapter.startListening(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater=getMenuInflater(); + inflater.inflate(R.menu.searchmenu,menu); + MenuItem item = menu.findItem(R.id.search); + SearchView searchView = (SearchView) item.getActionView(); + //searchView.setIconified(false); + //searchView.setIconifiedByDefault(false); + searchView.setQueryHint("Search Protocol"); + + + searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit(String query) { + query=query.toLowerCase(); + + firebasesearch(query); + return false; + } + + @Override + public boolean onQueryTextChange(String newText) { + newText=newText.toLowerCase(); + + firebasesearch(newText); + + return false; + } + }); + return super.onCreateOptionsMenu(menu); + } + @Override + public void onBackPressed() { + + finishAffinity(); + finish(); + } +} + + diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/Model/RegisterHelper.java b/app/src/main/java/no/spca/android/iisc/SPCA/Model/RegisterHelper.java new file mode 100644 index 0000000..7ec9900 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/Model/RegisterHelper.java @@ -0,0 +1,41 @@ +package no.spca.android.iisc.SPCA.Model; + +import java.io.Serializable; + +public class RegisterHelper implements Serializable { + + public String name, number, password; + + public RegisterHelper(String name, String number, String password) { + this.name = name; + this.number = number; + this.password = password; + } + public RegisterHelper() { + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/Model/Tests.java b/app/src/main/java/no/spca/android/iisc/SPCA/Model/Tests.java new file mode 100644 index 0000000..d307992 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/Model/Tests.java @@ -0,0 +1,167 @@ +package no.spca.android.iisc.SPCA.Model; + +public class Tests { + + private String Time, rev_trans_temp, rev_trans_time, intial_den_temp, intial_den_time,den_temp,den_time,ann_temp,ann_time,ext_temp,ext_time,fext_temp,fext_time,no_of_pcr_cycle,random_key,name_protocol,date_protocol; + + public Tests() { + + + } + + public Tests(String time, String rev_trans_temp, String rev_trans_time, String intial_den_temp, String intial_den_time, String den_temp, String den_time, String ann_temp, String ann_time, String ext_temp, String ext_time, String fext_temp, String fext_time, String no_of_pcr_cycle, String random_key, String name_protocol, String date_protocol) { + Time = time; + this.rev_trans_temp = rev_trans_temp; + this.rev_trans_time = rev_trans_time; + this.intial_den_temp = intial_den_temp; + this.intial_den_time = intial_den_time; + this.den_temp = den_temp; + this.den_time = den_time; + this.ann_temp = ann_temp; + this.ann_time = ann_time; + this.ext_temp = ext_temp; + this.ext_time = ext_time; + this.fext_temp = fext_temp; + this.fext_time = fext_time; + this.no_of_pcr_cycle = no_of_pcr_cycle; + this.random_key = random_key; + this.name_protocol = name_protocol; + this.date_protocol = date_protocol; + } + + public String getTime() { + return Time; + } + + public void setTime(String time) { + Time = time; + } + + public String getRev_trans_temp() { + return rev_trans_temp; + } + + public void setRev_trans_temp(String rev_trans_temp) { + this.rev_trans_temp = rev_trans_temp; + } + + public String getRev_trans_time() { + return rev_trans_time; + } + + public void setRev_trans_time(String rev_trans_time) { + this.rev_trans_time = rev_trans_time; + } + + public String getIntial_den_temp() { + return intial_den_temp; + } + + public void setIntial_den_temp(String intial_den_temp) { + this.intial_den_temp = intial_den_temp; + } + + public String getIntial_den_time() { + return intial_den_time; + } + + public void setIntial_den_time(String intial_den_time) { + this.intial_den_time = intial_den_time; + } + + public String getDen_temp() { + return den_temp; + } + + public void setDen_temp(String den_temp) { + this.den_temp = den_temp; + } + + public String getDen_time() { + return den_time; + } + + public void setDen_time(String den_time) { + this.den_time = den_time; + } + + public String getAnn_temp() { + return ann_temp; + } + + public void setAnn_temp(String ann_temp) { + this.ann_temp = ann_temp; + } + + public String getAnn_time() { + return ann_time; + } + + public void setAnn_time(String ann_time) { + this.ann_time = ann_time; + } + + public String getExt_temp() { + return ext_temp; + } + + public void setExt_temp(String ext_temp) { + this.ext_temp = ext_temp; + } + + public String getExt_time() { + return ext_time; + } + + public void setExt_time(String ext_time) { + this.ext_time = ext_time; + } + + public String getFext_temp() { + return fext_temp; + } + + public void setFext_temp(String fext_temp) { + this.fext_temp = fext_temp; + } + + public String getFext_time() { + return fext_time; + } + + public void setFext_time(String fext_time) { + this.fext_time = fext_time; + } + + public String getNo_of_pcr_cycle() { + return no_of_pcr_cycle; + } + + public void setNo_of_pcr_cycle(String no_of_pcr_cycle) { + this.no_of_pcr_cycle = no_of_pcr_cycle; + } + + public String getRandom_key() { + return random_key; + } + + public void setRandom_key(String random_key) { + this.random_key = random_key; + } + + public String getName_protocol() { + return name_protocol; + } + + public void setName_protocol(String name_protocol) { + this.name_protocol = name_protocol; + } + + public String getDate_protocol() { + return date_protocol; + } + + public void setDate_protocol(String date_protocol) { + this.date_protocol = date_protocol; + } +} \ No newline at end of file diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/NavigationTop.java b/app/src/main/java/no/spca/android/iisc/SPCA/NavigationTop.java new file mode 100644 index 0000000..b3d8f01 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/NavigationTop.java @@ -0,0 +1,109 @@ +package no.spca.android.iisc.SPCA; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.ActionBarDrawerToggle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.drawerlayout.widget.DrawerLayout; + +import com.google.android.material.navigation.NavigationView; + +import no.spca.android.iisc.R; + + +public class NavigationTop extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { + + protected DrawerLayout draw; + private LinearLayout line; + private Toolbar tool; + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { + switch (menuItem.getItemId()) + { + + case R.id.nav_contact_us: + Intent intent1=new Intent(this,About.class); + startActivity(intent1); + break; + case R.id.nav_result: + Intent intent2=new Intent(this, MainActivity.class); + startActivity(intent2); + break; + case R.id.nav_add_Test: + Intent intent3=new Intent(this, AddTest.class); + startActivity(intent3); + break; + case R.id.nav_logout: + Intent intent8=new Intent(this, LoginScreen.class); + SharedPreferences preferences = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + SharedPreferences.Editor editor = preferences.edit(); + + editor.putString("Phone", null); + editor.putString("Name",null); + + + editor.commit(); + + startActivity(intent8); + break; + + } + return true; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); + + setContentView(R.layout.activity_navigation__top); + + + draw = findViewById(R.id.Drawer); + line = findViewById(R.id.line); + tool = findViewById(R.id.tollbar); + NavigationView navigationView = findViewById(R.id.navigation); + navigationView.setNavigationItemSelectedListener(this); + + setSupportActionBar(tool); + + Window window = getWindow(); + window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); + + + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, draw, tool, R.string.open_navigation_drawer, R.string.close_navigation_drawer) { + @Override + public void onDrawerSlide(View drawerView, float slideOffset) { + super.onDrawerSlide(drawerView, slideOffset); + float sidebar = drawerView.getWidth() * slideOffset; + line.setTranslationX(sidebar); + } + }; + + draw.addDrawerListener(toggle); + toggle.syncState(); + View headerView = navigationView.getHeaderView(0); + TextView textView=headerView.findViewById(R.id.text); + TextView textView1=headerView.findViewById(R.id.not_sign_in); + + SharedPreferences preferences=getSharedPreferences("PhoneBook_number",MODE_PRIVATE); + + String string1 = preferences.getString("Phone", null); + String string2 = preferences.getString("Name", null); + textView.setText(string2); + textView1.setText(string1); + + } +} + diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/Register.java b/app/src/main/java/no/spca/android/iisc/SPCA/Register.java new file mode 100644 index 0000000..129b853 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/Register.java @@ -0,0 +1,190 @@ +package no.spca.android.iisc.SPCA; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.util.Log; +import android.util.Patterns; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.Query; +import com.google.firebase.database.ValueEventListener; +import com.hbb20.CountryCodePicker; +import no.spca.android.iisc.R; + +import no.spca.android.iisc.SPCA.VerifyOTP.VerifyOtp; + + +public class Register extends AppCompatActivity { +String numberwithcode; + private Button next; + private EditText editTextMobile; + private ProgressDialog loadingBar; + + private TextView login; + CountryCodePicker ccp; + String mobile,name; + + private EditText editTextname; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_register); + next=findViewById(R.id.buttonContinue); + editTextMobile = findViewById(R.id.editTextMobile); + + ccp=findViewById(R.id.ccp); + + ccp.registerCarrierNumberEditText(editTextMobile); + loadingBar = new ProgressDialog(this); + login=findViewById(R.id.login_account); + login.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Intent intent = new Intent(Register.this, LoginScreen.class); + startActivity(intent); + + } + }); + + editTextname=findViewById(R.id.editTextName); + + next.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + mobile = editTextMobile.getText().toString().trim(); + mobile = mobile.replaceAll("[^0-9]", ""); + + name = editTextname.getText().toString().trim(); + + + if (!isOnline()) { + //Create an alertdialog + AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(Register.this); + Checkbuilder.setTitle("No Internet Connection !"); + Checkbuilder.setMessage("Check Your Internet Connection."); + + Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + + dialog.cancel(); + } + }); + + Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + finish(); + } + }); + + AlertDialog alert = Checkbuilder.create(); + alert.show(); + + } + + else { + if (mobile.equals("") || name.equals("")) { + Toast.makeText(Register.this, "please enter all the required fields", Toast.LENGTH_SHORT).show(); + + } else if (!Patterns.PHONE.matcher(mobile).matches()) { + editTextMobile.setError("Enter a valid Phone "); + + } + else if (mobile.length() <9 ) { + Toast.makeText(Register.this, "Enter a valid Phone", Toast.LENGTH_SHORT).show(); + + } + else if (mobile.length() >=11 ) { + Toast.makeText(Register.this, "Enter a valid Phone", Toast.LENGTH_SHORT).show(); + + }else { + + Query chekuser = FirebaseDatabase.getInstance().getReference("USERS").orderByChild("number").equalTo(mobile); + chekuser.addListenerForSingleValueEvent(new ValueEventListener() { + @Override + public void onDataChange(@NonNull DataSnapshot dataSnapshot) { + if (dataSnapshot.exists()) { + Toast.makeText(Register.this, "User Already Exist", Toast.LENGTH_SHORT).show(); + + } else { + Intent intent = new Intent(Register.this, VerifyOtp.class); + Log.e("main", "error " + mobile); + + numberwithcode = ccp.getFullNumberWithPlus(); + Log.e("main", "error " + numberwithcode); + + if (mobile.equals("") || name.equals("")) { + Toast.makeText(Register.this, "please enter all the required fields", Toast.LENGTH_SHORT).show(); + + } else if (!Patterns.PHONE.matcher(mobile).matches()) { + editTextMobile.setError("Enter a valid Phone "); + } else { + loadingBar.setTitle("Create Account"); + loadingBar.setMessage("Please wait "); + loadingBar.setCanceledOnTouchOutside(false); + loadingBar.show(); + + + intent.putExtra("numberwithcode", numberwithcode); + + intent.putExtra("mobile", mobile); + intent.putExtra("username", name); + + startActivity(intent); + } + + + } + + } + + @Override + public void onCancelled(@NonNull DatabaseError databaseError) { + Log.e("Raman", "Received an exception check chexk " + databaseError.getMessage()); + + } + }); + } + } + + } + }); + + + + + } + @Override + public void onBackPressed() { + + Intent intent = new Intent(Register.this, LoginScreen.class); + startActivity(intent); + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/SPCAManagerCallbacks.java b/app/src/main/java/no/spca/android/iisc/SPCA/SPCAManagerCallbacks.java new file mode 100644 index 0000000..a0181d0 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/SPCAManagerCallbacks.java @@ -0,0 +1,10 @@ + +package no.spca.android.iisc.SPCA; + +import no.spca.android.iisc.SPCA.callback.CycleCharacteristicCallback; +import no.spca.android.iisc.battery.BatteryManagerCallbacks; + + +interface SPCAManagerCallbacks extends BatteryManagerCallbacks, CycleCharacteristicCallback { + +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/SpaceDecoration.java b/app/src/main/java/no/spca/android/iisc/SPCA/SpaceDecoration.java new file mode 100644 index 0000000..e06c770 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/SpaceDecoration.java @@ -0,0 +1,20 @@ +package no.spca.android.iisc.SPCA; + +import android.graphics.Rect; +import android.view.View; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +public class SpaceDecoration extends RecyclerView.ItemDecoration { + private final int space; + + public SpaceDecoration(int space) { + this.space = space; + } + + @Override + public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { + outRect.left=outRect.bottom=outRect.right=outRect.top=space; + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/TempDataShow.java b/app/src/main/java/no/spca/android/iisc/SPCA/TempDataShow.java new file mode 100644 index 0000000..6144237 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/TempDataShow.java @@ -0,0 +1,650 @@ +package no.spca.android.iisc.SPCA; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.bluetooth.BluetoothDevice; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Build; +import android.os.Bundle; +import android.os.CountDownTimer; +import android.os.Handler; +import android.text.TextWatcher; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.Task; +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.ValueEventListener; + +import java.io.File; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.Model.Tests; +import no.spca.android.iisc.profile.BleProfileService; +import no.spca.android.iisc.profile.BleProfileServiceReadyActivity; + + + +public class TempDataShow extends BleProfileServiceReadyActivity { + @SuppressWarnings("unused") + private final String TAG = "AddTest"; + + private TextView mValueView; + private TextView mCycleView; + private EditText mFETempValueView; + private EditText mFETimeValueView; + + String acttime; + + private TextView mHeatingStatusView; + private int seconds1 ,seconds2; + private Switch mHeatingState ; +private EditText prtocol; + + private EditText mDTimeValueView; + private Integer mDSetTime ; + private EditText mLTimeValueView; + private Integer mLSetTime ; + private EditText mOTimeValueView; + private Integer mOSetTime ; + private String time1,time2,time3; + private Date date1,date2,date3; + + + private final int valuedata=0; + private final int j=0; + private final Handler handler = new Handler(); + private Runnable runnable; + + + private EditText mATimeValueView; + private Integer mASetTime ; + private EditText mETimeValueView; + private Integer mESetTime ; + private TextWatcher txtwt; + + private Button next; + Button connect; + + + + + + private EditText mDTempValueView; + private Integer mDSetTemp ; + private EditText mATempValueView; + private Integer mASetTemp ; + private EditText mETempValueView; + private Integer mESetTemp ; + + private EditText mLTempValueView; + private Integer mLSetTemp ; + private EditText mOTempValueView; + private Integer mOSetTemp ; + private long diff=0; + private long diffSeconds=0; + private long diffMinutes=0; + private long diffHours=0; + private long diff1=0; + private long diffSeconds1=0; + private long diffMinutes1=0; + + private long diffHours1=0; + private Integer mSSetTemp ; + private Integer mSSetTime; + + private int FLAG=0; + + + private int count=0; + private int valuw=0; + + int i=0; + File filePath3 = null; + private DatabaseReference TestRef; + private ProgressDialog loadingBar; + private Button save; + private String TestRandomKey, downloadImageUrl1,saveCurrentDate, saveCurrentTime,number; + + + + private EditText mNPcrCView; + private Integer mNPcrC ; + private Timer T; + + private String TestID = ""; + + + @Override + protected void onCreateView(final Bundle savedInstanceState) { + setContentView(R.layout.activity_protocol); + loadingBar = new ProgressDialog(this); + + setGUI(); + TestID = getIntent().getStringExtra("pid"); + + Log.e("main", "error id "+TestID); + getTestDetails(TestID); + + next = findViewById(R.id.action_next); + connect = findViewById(R.id.action_connect); + next.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + connect.performClick(); + + + Intent intent = new Intent(TempDataShow.this, GraphActivity.class); + + + intent.putExtra("key6",acttime); + + startActivity(intent); + + } + }); + + + + + } + + private void setGUI() { + mValueView = findViewById(R.id.Temp_Value); + mCycleView = findViewById(R.id.RemTime_Value); + + mDTempValueView = findViewById(R.id.D_Temp_Set); + mDTimeValueView = findViewById(R.id.D_Time_Set); + mATempValueView = findViewById(R.id.A_Temp_Set); + mATimeValueView = findViewById(R.id.A_Time_Set); + mETempValueView = findViewById(R.id.E_Temp_Set); + mETimeValueView = findViewById(R.id.E_Time_Set); + mLTempValueView=findViewById(R.id.L_Temp_Set); + mOTempValueView=findViewById(R.id.O_Temp_Set); + mLTimeValueView = findViewById(R.id.L_Time_Set); + + mOTimeValueView = findViewById(R.id.O_Time_Set); + mFETimeValueView=findViewById(R.id.S_Time_Set); + mFETempValueView=findViewById(R.id.S_Temp_Set); + + T=new Timer(); + + + SharedPreferences preferences689 = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + + number = preferences689.getString("Phone", null); + + + TestRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + + mNPcrCView = findViewById(R.id.N_Pcr_C); +prtocol=findViewById(R.id.protocol_name); + + mHeatingState = findViewById(R.id.heating_state); + mHeatingStatusView= findViewById(R.id.heating_status_text); + //mValueView.setText("fff"); + + + + mHeatingState.setOnCheckedChangeListener((buttonView, isChecked) -> { + if (isChecked) { + startCounter(); + + + i=1; + if(date2 !=null && date1 !=null) { + SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + try { + date1 = format.parse(time1); + date2 = format.parse(time2); + diff = (date2.getTime() - date1.getTime()); + diffSeconds = diff / 1000 % 60; + diffMinutes = diff / (60 * 1000) % 60; + diffHours = diff / (60 * 60 * 1000); + + + + } catch (ParseException e) { + e.printStackTrace(); + } + + + + + + } + + Log.e("main", "error data inside " + valuedata); + + getService().heatingSwitch(1); + + mDSetTemp = Integer.parseInt(mDTempValueView.getText().toString()); + getService().sendDTemp(mDSetTemp); + + + mDSetTime = Integer.parseInt(mDTimeValueView.getText().toString()); + getService().sendDTime(mDSetTime); + + mLSetTemp = Integer.parseInt(mLTempValueView.getText().toString()); + getService().sendLTemp(mLSetTemp); + mLSetTime = Integer.parseInt(mLTimeValueView.getText().toString()); + getService().sendLTime(mLSetTime); + + mOSetTemp = Integer.parseInt(mOTempValueView.getText().toString()); + getService().sendOTemp(mOSetTemp); + mOSetTime = Integer.parseInt(mOTimeValueView.getText().toString()); + getService().sendOTime(mOSetTime); + + + mASetTemp = Integer.parseInt(mATempValueView.getText().toString()); + getService().sendATemp(mASetTemp); + mASetTime = Integer.parseInt(mATimeValueView.getText().toString()); + getService().sendATime(mASetTime); + + mESetTemp = Integer.parseInt(mETempValueView.getText().toString()); + getService().sendETemp(mESetTemp); + mESetTime = Integer.parseInt(mETimeValueView.getText().toString()); + getService().sendETime(mESetTime); + + + mSSetTemp = Integer.parseInt(mFETempValueView.getText().toString()); + getService().sendLTemp(mSSetTemp); + mSSetTime = Integer.parseInt(mFETimeValueView.getText().toString()); + getService().sendLTime(mSSetTime); + + + mNPcrC = Integer.parseInt(mNPcrCView.getText().toString()); + getService().sendNPcrN(mNPcrC); + Log.e("main", "error 34" + mDSetTemp); + + Log.e("main", "error 2 " + mDSetTemp); + Log.e("main", "error data box " + valuedata); + + } + else { + getService().heatingSwitch(0); + } + mHeatingStatusView.setText(isChecked ? R.string.Heating_block_on : R.string.Heating_block_off); + }); + + + + } + + @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() { + mValueView.setText("wait"); + mCycleView.setText("wait"); + + } + + @Override + protected int getLoggerProfileTitle() { + return R.string.template_feature_title; + } + + + + + @Override + protected int getDefaultDeviceName() { + return R.string.template_default_name; + } + + @Override + protected UUID getFilterUUID() { + return CycleManager.SERVICE_UUID; + } + + @Override + protected Class getServiceClass() { + return CycleService.class; + } + + @Override + protected void onServiceBound(final CycleService.TemplateBinder binder) { + } + + @Override + protected void onServiceUnbound() { + } + + @Override + public void onServicesDiscovered(final BluetoothDevice device, final boolean optionalServicesFound) { + } + + @Override + public void onDeviceDisconnected(final BluetoothDevice device) { + super.onDeviceDisconnected(device); + } + + @SuppressWarnings("unused") + private void setValueOnView(@NonNull final BluetoothDevice device, int value) { + } + + + + @SuppressWarnings("unused") + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int value) { + + } + + private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @RequiresApi(api = Build.VERSION_CODES.O) + @Override + public void onReceive(final Context context, final Intent intent) { + final String action = intent.getAction(); + final BluetoothDevice device = intent.getParcelableExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_DEVICE); + + if (no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT.equals(action)) { + int value = intent.getIntExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_DATA, 0); + setValueOnView(device, value); + valuw=value; + if(value==0) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time1 = df.format(Calendar.getInstance().getTime()); + + + Log.e("main", "error 403 " +time1); + + + + //cycle 1 start + + + } + + else if(value ==1 ) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time2 = df.format(Calendar.getInstance().getTime()); + + Log.e("main", "error 404 " +time2); + LocalDateTime date = LocalDateTime.now(); + seconds1 = date.toLocalTime().toSecondOfDay(); + + + + } + else if(value ==2 ) + { + DateFormat df = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + time3 = df.format(Calendar.getInstance().getTime()); + + try { + date1 = df.parse(time1); + date2 = df.parse(time2); + date3=df.parse(time3); + + } catch (ParseException e) { + e.printStackTrace(); + } + Log.e("main", "date 1 " + date2.getTime()); + Log.e("main", "date 2 " + date1.getTime()); + + + diff1 = date3.getTime() - date2.getTime(); + Log.e("main", "difference minute " + diffMinutes); + + + Log.e("main", "difference minute " + diffMinutes); + + diffSeconds1 = diff1 / 1000 % 60; + diffMinutes1 = diff1 / (60 * 1000) % 60; + diffHours1 = diff1/ (60 * 60 * 1000); + Log.e("main", "date difference " + diffMinutes1); + + + + Log.e("main", "error 404 " +time2); + + + + + } + + if(time1 !=null && time2 !=null &&diffSeconds1==1 ) { + + SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); + try { + date1 = format.parse(time1); + date2 = format.parse(time2); + Log.e("main", "date 1 " + date2.getTime()); + Log.e("main", "date 2 " + date1.getTime()); + + + diff = date2.getTime() - date1.getTime(); + Log.e("main", "difference minute " + diffMinutes); + + diffSeconds = diff / 1000 % 60; + diffMinutes = diff / (60 * 1000) % 60; + diffHours = diff / (60 * 60 * 1000); + Log.e("main", "date difference " + diffMinutes); + FLAG=1; + + + + } catch (ParseException e) { + e.printStackTrace(); + } + + + } + else + { + } + + } else if (no.spca.android.iisc.SPCA.CycleService.BROADCAST_BATTERY_LEVEL.equals(action)) { + final int batteryLevel = intent.getIntExtra(no.spca.android.iisc.SPCA.CycleService.EXTRA_BATTERY_LEVEL, 0); + onBatteryLevelChanged(device, batteryLevel); + } + + } + }; + + private static IntentFilter makeIntentFilter() { + final IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT); + intentFilter.addAction(no.spca.android.iisc.SPCA.CycleService.BROADCAST_BATTERY_LEVEL); + return intentFilter; + } + + + private void startCounter() + + { + + + + T.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + runOnUiThread(new Runnable() { + @Override + public void run() { + + if(FLAG==1) + { + mNPcrC=mNPcrC-1; + long cycle=mNPcrC.longValue(); + acttime=String.valueOf(diff*cycle); + //acttime="20444444" + connect.performClick(); + + + Intent intent = new Intent(TempDataShow.this, GraphActivity.class); + + + intent.putExtra("key6",acttime); + + startActivity(intent); + //acttime="20444444"; + // countdown(diff *cycle); + + T.cancel(); + } + + + + } + }); + } + }, 1000, 1000); + + + + + } + + + + @Override + public void onPointerCaptureChanged(boolean hasCapture) { + + } + public boolean isOnline() { + ConnectivityManager connMgr = (ConnectivityManager) + getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); + return (networkInfo != null && networkInfo.isConnected()); + + } + private void getTestDetails(String TestID) + { + DatabaseReference productsRef = FirebaseDatabase.getInstance().getReference().child("Test_Data").child(number); + + productsRef.child(TestID).addValueEventListener(new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) + { + if (dataSnapshot.exists()) + { + + + Tests products = dataSnapshot.getValue(Tests.class); + + + mLTempValueView.setText(products.getRev_trans_temp()); + + mLTimeValueView.setText(products.getRev_trans_time()); + + mOTempValueView.setText(products.getIntial_den_temp()); + + mOTimeValueView.setText(products.getIntial_den_time()); + + mDTempValueView.setText(products.getDen_temp()); + + + mDTimeValueView.setText(products.getDen_time()); + + + mATempValueView.setText(products.getAnn_temp()); + prtocol.setText(products.getName_protocol()); + + + + mATimeValueView.setText(products.getAnn_time()); + + + + mETempValueView.setText(products.getExt_temp()); + + mETimeValueView.setText(products.getExt_time()); + + mFETempValueView.setText(products.getFext_temp()); + + mFETimeValueView.setText(products.getFext_time()); + + + mNPcrCView.setText(products.getNo_of_pcr_cycle()); + + mLTempValueView.setText(products.getRev_trans_temp()); + + mLTimeValueView.setText(products.getRev_trans_time()); + mATempValueView.setText(products.getAnn_temp()); + mATimeValueView.setText(products.getAnn_time()); + mDTempValueView.setText(products.getDen_temp()); + mDTimeValueView.setText(products.getDen_time()); + + + } + } + + @Override + public void onCancelled(DatabaseError databaseError) { + + } + }); + } + @Override + public void onBackPressed() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setCancelable(false); + builder.setMessage("Do you want to Exit ?"); + + builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + Intent intent = new Intent(TempDataShow.this, MainActivity.class); + finish(); + startActivity(intent); + + + + + } + }); + builder.setNegativeButton("No", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + + dialog.cancel(); + } + }); + AlertDialog alert = builder.create(); + alert.show(); + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/TemperatureManager.java b/app/src/main/java/no/spca/android/iisc/SPCA/TemperatureManager.java new file mode 100644 index 0000000..562f591 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/TemperatureManager.java @@ -0,0 +1,156 @@ + +package no.spca.android.iisc.SPCA; + +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.content.Context; +import android.util.Log; + +import androidx.annotation.NonNull; + +import java.util.UUID; + +import no.nordicsemi.android.ble.data.Data; +import no.nordicsemi.android.log.LogContract; +import no.spca.android.iisc.SPCA.callback.CycleDataCallback; +import no.spca.android.iisc.battery.BatteryManager; +import no.spca.android.iisc.parser.TemperatureParser; + + +public class TemperatureManager extends BatteryManager { + + + static final UUID SERVICE_UUID = UUID.fromString("00001500-1212-efde-1523-785feabcd123"); private static final UUID TEMP_READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001501-1212-efde-1523-785feabcd123"); private static final UUID OTHER_SERVICE_UUID = UUID.fromString("00001800-0000-1000-8000-00805f9b34fb"); private static final UUID READABLE_CHARACTERISTIC_UUID = UUID.fromString("00001801-0000-1000-8000-00805f9b34fb"); private BluetoothGattCharacteristic mReadBlockTempCharacteristic, mDeviceNameCharacteristic, mRequiredCharacteristic, mOptionalCharacteristic ; + + public TemperatureManager(final Context context) { + super(context); + } + + @NonNull + @Override + protected BatteryManagerGattCallback getGattCallback() { + return mGattCallback; + } + + + private final BatteryManagerGattCallback mGattCallback = new BatteryManagerGattCallback() { + + @Override + protected void initialize() { + + super.initialize(); + + + requestMtu(43)//requestMtu(43) + .with((device, mtu) -> log(LogContract.Log.Level.APPLICATION, "MTU changed to " + mtu)) + .done(device -> { + + }) + .fail((device, status) -> log(Log.WARN, "MTU change not supported")) + .enqueue(); + + setNotificationCallback(mReadBlockTempCharacteristic) + .with(new CycleDataCallback() { + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(LogContract.Log.Level.APPLICATION, TemperatureParser.parse(data)); + super.onDataReceived(device, data); + } + + @Override + public void onSampleValueReceived(@NonNull final BluetoothDevice device, final int value) { + mCallbacks.onSampleValueReceived(device, value); + } + + @Override + public void onInvalidDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + log(Log.WARN, "Invalid data received: " + data); + } + }); + + enableNotifications(mReadBlockTempCharacteristic) + .with((device, data) -> log(Log.DEBUG, "Data sent: " + data)) + .done(device -> log(LogContract.Log.Level.APPLICATION, "Notifications enabled successfully")) + .fail((device, status) -> log(Log.WARN, "Failed to enable notifications")) + .enqueue(); + } + + @Override + protected boolean isRequiredServiceSupported(@NonNull final BluetoothGatt gatt) { + final BluetoothGattService service = gatt.getService(SERVICE_UUID); + if (service != null) { + mReadBlockTempCharacteristic = service.getCharacteristic(TEMP_READABLE_CHARACTERISTIC_UUID); + + } + final BluetoothGattService otherService = gatt.getService(OTHER_SERVICE_UUID); + if (otherService != null) { + mDeviceNameCharacteristic = otherService.getCharacteristic(READABLE_CHARACTERISTIC_UUID); + } + + return mReadBlockTempCharacteristic != null ; + } + + @Override + protected boolean isOptionalServiceSupported(@NonNull final BluetoothGatt gatt) { + super.isOptionalServiceSupported(gatt); + + final BluetoothGattService service = gatt.getService(SERVICE_UUID); + if (service != null) { + mOptionalCharacteristic = service.getCharacteristic(READABLE_CHARACTERISTIC_UUID); + } + return mOptionalCharacteristic != null; + } + + @Override + protected void onDeviceDisconnected() { + super.onDeviceDisconnected(); + + mRequiredCharacteristic = null; + mDeviceNameCharacteristic = null; + mOptionalCharacteristic = null; + } + + @Override + protected void onDeviceReady() { + super.onDeviceReady(); + + readCharacteristic(mReadBlockTempCharacteristic) + .with((device, data) -> { + 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(); + } + }; + + + + + + + + + + + + + + + + + + + + + + + + + +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/TemperatureService.java b/app/src/main/java/no/spca/android/iisc/SPCA/TemperatureService.java new file mode 100644 index 0000000..288233c --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/TemperatureService.java @@ -0,0 +1,142 @@ + + +package no.spca.android.iisc.SPCA; + +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.spca.android.iisc.FeaturesActivity; +import no.spca.android.iisc.NotificationData; +import no.spca.android.iisc.R; +import no.spca.android.iisc.profile.BleProfileService; +import no.spca.android.iisc.profile.LoggableBleManager; + +import static no.spca.android.iisc.SPCA.CycleService.BROADCAST_TEMPLATE_MEASUREMENT; + +public class TemperatureService extends BleProfileService implements SPCAManagerCallbacks { + public static final String BROADCAST_TEMPLATE_MEASUREMENT1 = "no.spca.android.iisc.template.BROADCAST_MEASUREMENT"; + + public static final String EXTRA_DATA1 = "no.spca.android.iisc.template.EXTRA_DATA1"; + + public static final String BROADCAST_BATTERY_LEVEL = "no.spca.android.iisc.BROADCAST_BATTERY_LEVEL"; + public static final String EXTRA_BATTERY_LEVEL = "no.spca.android.iisc.EXTRA_BATTERY_LEVEL"; + + private final static String ACTION_DISCONNECT = "no.spca.android.iisc.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 TemperatureManager mManager; + + + private final LocalBinder mBinder = new TemplateBinder(); + + + class TemplateBinder extends LocalBinder { + } + + @Override + protected LocalBinder getBinder() { + return mBinder; + } + + @Override + protected LoggableBleManager initializeManager() { + return mManager = new TemperatureManager(this); + } + + @Override + public void onCreate() { + super.onCreate(); + + final IntentFilter filter = new IntentFilter(); + filter.addAction(ACTION_DISCONNECT); + registerReceiver(mDisconnectActionBroadcastReceiver, filter); + } + + @Override + public void onDestroy() { + cancelNotification(); + unregisterReceiver(mDisconnectActionBroadcastReceiver); + + super.onDestroy(); + } + + @Override + protected void onRebind() { + cancelNotification(); + } + + @Override + protected void onUnbind() { + 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_DATA1, value); + LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); + + if (!mBound) { + } + } + + @Override + public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { + + } + + + 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, AddTest.class); + + final Intent disconnect = new Intent(ACTION_DISCONNECT); + final PendingIntent disconnectAction = PendingIntent.getBroadcast(this, DISCONNECT_REQ, disconnect, PendingIntent.FLAG_UPDATE_CURRENT); + + 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, NotificationData.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); + } + + + private void cancelNotification() { + final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + nm.cancel(NOTIFICATION_ID); + } + + + 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/spca/android/iisc/SPCA/TestViewHolder.java b/app/src/main/java/no/spca/android/iisc/SPCA/TestViewHolder.java new file mode 100644 index 0000000..8977924 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/TestViewHolder.java @@ -0,0 +1,47 @@ +package no.spca.android.iisc.SPCA; + +import android.view.View; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.recyclerview.widget.RecyclerView; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.Interface.ItemClickListner; + + +public class TestViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener +{ + public TextView ProtocolName, txttimestamp, cycleNumber,iconfinder,txtsampletype; + public ImageView imageView; + public ItemClickListner listner; + + + public TestViewHolder(View itemView) + { + super(itemView); + + + + + imageView = (ImageView) itemView.findViewById(R.id.icon_profile); + iconfinder=(TextView) itemView.findViewById(R.id.icon_text); + + ProtocolName = (TextView) itemView.findViewById(R.id.protocol_id); + txtsampletype = (TextView) itemView.findViewById(R.id.sample_type); + txttimestamp=itemView.findViewById(R.id.timestamp); + cycleNumber =itemView.findViewById(R.id.pro_data); + + } + + public void setItemClickListner(ItemClickListner listner) + { + this.listner = listner; + } + + @Override + public void onClick(View view) + { + listner.onClick(view, getAdapterPosition(), false); + } +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/VerifyOTP/VerifyOtp.java b/app/src/main/java/no/spca/android/iisc/SPCA/VerifyOTP/VerifyOtp.java new file mode 100644 index 0000000..b69ba01 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/VerifyOTP/VerifyOtp.java @@ -0,0 +1,150 @@ +package no.spca.android.iisc.SPCA.VerifyOTP; + +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ProgressBar; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import com.chaos.view.PinView; +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.Task; +import com.google.firebase.FirebaseException; +import com.google.firebase.auth.AuthResult; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.auth.PhoneAuthCredential; +import com.google.firebase.auth.PhoneAuthOptions; +import com.google.firebase.auth.PhoneAuthProvider; + +import java.util.concurrent.TimeUnit; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.CreatePassword; + + +public class VerifyOtp extends AppCompatActivity { + + private String verificationid; + private FirebaseAuth mAuth; + private Button nextactivity; + private ProgressBar progressBar; + PinView pinFromUser; + private EditText editText; + String name; + String phonenumber; + String phonenumberke; + + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_verify__o_t_p); + pinFromUser = findViewById(R.id.firstPinView); + nextactivity = findViewById(R.id.buttonSignIn); + + mAuth = FirebaseAuth.getInstance(); + + + String phonenumberk = getIntent().getStringExtra("numberwithcode"); + phonenumberke = getIntent().getStringExtra("mobile"); + + phonenumber = phonenumberk; + + name = getIntent().getStringExtra("username"); + + + + sendVerificationCode(phonenumber); + findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + String code = pinFromUser.getText().toString().trim(); + + if ((code.isEmpty() || code.length() < 6)) { + + editText.setError("Enter code..."); + editText.requestFocus(); + return; + } + verifyCode(code); + + } + }); + + } + private void verifyCode(String code){ + PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationid, code); + signInWithCredential(credential); + } + + private void signInWithCredential(PhoneAuthCredential credential) { + mAuth.signInWithCredential(credential) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + + Intent intent = new Intent(VerifyOtp.this, CreatePassword.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + intent.putExtra("mobile", phonenumberke); + intent.putExtra("username", name); + + + startActivity(intent); + + } else { + } + } + + }); + } + + private void sendVerificationCode(String number){ + + PhoneAuthOptions options = + PhoneAuthOptions.newBuilder(mAuth) + .setPhoneNumber(number) .setTimeout(60L, TimeUnit.SECONDS) .setActivity(this) .setCallbacks(mCallBack) .build(); + PhoneAuthProvider.verifyPhoneNumber(options); + + } + + private final PhoneAuthProvider.OnVerificationStateChangedCallbacks + mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { + + @Override + public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { + super.onCodeSent(s, forceResendingToken); + verificationid = s; + } + + @Override + public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { + String code = phoneAuthCredential.getSmsCode(); + if (code != null){ + pinFromUser.setText(code); + verifyCode(code); + } + } + + @Override + public void onVerificationFailed(FirebaseException e) { + Toast.makeText(VerifyOtp.this, e.getMessage(),Toast.LENGTH_LONG).show(); + + } + }; + + + + + + + + +} \ No newline at end of file diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/VerifyOTP/VerifyOtpForgetPassword.java b/app/src/main/java/no/spca/android/iisc/SPCA/VerifyOTP/VerifyOtpForgetPassword.java new file mode 100644 index 0000000..20931a6 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/VerifyOTP/VerifyOtpForgetPassword.java @@ -0,0 +1,149 @@ +package no.spca.android.iisc.SPCA.VerifyOTP; + +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ProgressBar; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import com.chaos.view.PinView; +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.Task; +import com.google.firebase.FirebaseException; +import com.google.firebase.auth.AuthResult; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.auth.PhoneAuthCredential; +import com.google.firebase.auth.PhoneAuthOptions; +import com.google.firebase.auth.PhoneAuthProvider; + +import java.util.concurrent.TimeUnit; + +import no.spca.android.iisc.R; +import no.spca.android.iisc.SPCA.ForgetPassword; +import no.spca.android.iisc.SPCA.ForgetPasswordReset; + + +public class VerifyOtpForgetPassword extends AppCompatActivity { + + private String verificationid; + private FirebaseAuth mAuth; + private Button nextactivity; + private ProgressBar progressBar; + PinView pinFromUser; + private EditText editText; + String codeBySystem; + String phonenumber,mobile; + + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_verify__o_t_p); + pinFromUser = findViewById(R.id.firstPinView); + nextactivity = findViewById(R.id.buttonSignIn); + + mAuth = FirebaseAuth.getInstance(); + + + String phonenumberk = getIntent().getStringExtra("mobilecode"); + phonenumber = phonenumberk; + mobile= getIntent().getStringExtra("mobile"); + + + + + sendVerificationCode(phonenumber); + findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + String code = pinFromUser.getText().toString().trim(); + + if ((code.isEmpty() || code.length() < 6)) { + + editText.setError("Enter code..."); + editText.requestFocus(); + return; + } + verifyCode(code); + + } + }); + + } + private void verifyCode(String code){ + PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationid, code); + signInWithCredential(credential); + } + + private void signInWithCredential(PhoneAuthCredential credential) { + mAuth.signInWithCredential(credential) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + + Intent intent = new Intent(VerifyOtpForgetPassword.this, ForgetPasswordReset.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + intent.putExtra("mobile", mobile); + + + startActivity(intent); + + } else { + Toast.makeText(VerifyOtpForgetPassword.this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); + } + } + + }); + } + + private void sendVerificationCode(String number){ + PhoneAuthOptions options = + PhoneAuthOptions.newBuilder(mAuth) + .setPhoneNumber(number) .setTimeout(60L, TimeUnit.SECONDS) .setActivity(this) .setCallbacks(mCallBack) .build(); + PhoneAuthProvider.verifyPhoneNumber(options); + + + } + + private final PhoneAuthProvider.OnVerificationStateChangedCallbacks + mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { + + @Override + public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) { + super.onCodeSent(s, forceResendingToken); + verificationid = s; + } + + @Override + public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { + String code = phoneAuthCredential.getSmsCode(); + if (code != null){ + pinFromUser.setText(code); + verifyCode(code); + } + } + + @Override + public void onVerificationFailed(FirebaseException e) { + Toast.makeText(VerifyOtpForgetPassword.this, e.getMessage(),Toast.LENGTH_LONG).show(); + + } + }; + @Override + public void onBackPressed() { + + Intent intent = new Intent(VerifyOtpForgetPassword.this, ForgetPassword.class); + startActivity(intent); + + } + + +} \ No newline at end of file diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/callback/CycleCharacteristicCallback.java b/app/src/main/java/no/spca/android/iisc/SPCA/callback/CycleCharacteristicCallback.java new file mode 100644 index 0000000..30a6557 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/callback/CycleCharacteristicCallback.java @@ -0,0 +1,12 @@ +package no.spca.android.iisc.SPCA.callback; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.NonNull; + + +public interface CycleCharacteristicCallback { + + + 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/spca/android/iisc/SPCA/callback/CycleDataCallback.java similarity index 54% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateDataCallback.java rename to app/src/main/java/no/spca/android/iisc/SPCA/callback/CycleDataCallback.java index 1ec05f9..2667bbf 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/template/callback/TemplateDataCallback.java +++ b/app/src/main/java/no/spca/android/iisc/SPCA/callback/CycleDataCallback.java @@ -1,4 +1,4 @@ -package no.nordicsemi.android.nrftoolbox.template.callback; +package no.spca.android.iisc.SPCA.callback; import android.bluetooth.BluetoothDevice; import androidx.annotation.NonNull; @@ -6,16 +6,9 @@ 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 { +public abstract class CycleDataCallback implements ProfileDataCallback, CycleCharacteristicCallback { @Override public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { @@ -24,24 +17,17 @@ public abstract class TemplateDataCallback implements ProfileDataCallback, Templ 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/spca/android/iisc/SPCA/callback/TemperatureCharacteristicCallback.java b/app/src/main/java/no/spca/android/iisc/SPCA/callback/TemperatureCharacteristicCallback.java new file mode 100644 index 0000000..ceddcde --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/callback/TemperatureCharacteristicCallback.java @@ -0,0 +1,12 @@ +package no.spca.android.iisc.SPCA.callback; + +import android.bluetooth.BluetoothDevice; + +import androidx.annotation.NonNull; + + +public interface TemperatureCharacteristicCallback { + + + void onSampleValueReceived1(@NonNull final BluetoothDevice device, int value); +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/callback/TemperatureDataCallback.java b/app/src/main/java/no/spca/android/iisc/SPCA/callback/TemperatureDataCallback.java new file mode 100644 index 0000000..eedee0c --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/callback/TemperatureDataCallback.java @@ -0,0 +1,36 @@ +package no.spca.android.iisc.SPCA.callback; + +import android.bluetooth.BluetoothDevice; + +import androidx.annotation.NonNull; + +import no.nordicsemi.android.ble.callback.profile.ProfileDataCallback; +import no.nordicsemi.android.ble.data.Data; + + +@SuppressWarnings("ConstantConditions") +public abstract class TemperatureDataCallback implements ProfileDataCallback, TemperatureCharacteristicCallback { + + @Override + public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { + if (data.size() < 2) { + onInvalidDataReceived(device, data); + return; + } + + 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; + + if (data.size() < 1 + (hearRateType & 0x0F)) { + onInvalidDataReceived(device, data); + return; + } + + final int value = data.getIntValue(hearRateType, offset); + onSampleValueReceived1(device, value); + } + + public abstract void onDataReceived1(@NonNull BluetoothDevice device, @NonNull Data data); +} diff --git a/app/src/main/java/no/spca/android/iisc/SPCA/settings/SettingsActivity.java b/app/src/main/java/no/spca/android/iisc/SPCA/settings/SettingsActivity.java new file mode 100644 index 0000000..e26e211 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/settings/SettingsActivity.java @@ -0,0 +1,35 @@ + + +package no.spca.android.iisc.SPCA.settings; + +import android.os.Bundle; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuItem; + +import no.spca.android.iisc.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); + + 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/spca/android/iisc/SPCA/settings/SettingsFragment.java b/app/src/main/java/no/spca/android/iisc/SPCA/settings/SettingsFragment.java new file mode 100644 index 0000000..34396e9 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SPCA/settings/SettingsFragment.java @@ -0,0 +1,19 @@ + + +package no.spca.android.iisc.SPCA.settings; + +import android.os.Bundle; + +import androidx.preference.PreferenceFragmentCompat; +import no.spca.android.iisc.R; + +public class SettingsFragment extends PreferenceFragmentCompat { + public static final String SETTINGS_DATA = "settings_template_data"; 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/spca/android/iisc/SplashscreenActivity.java b/app/src/main/java/no/spca/android/iisc/SplashscreenActivity.java new file mode 100644 index 0000000..33262e7 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/SplashscreenActivity.java @@ -0,0 +1,104 @@ + +package no.spca.android.iisc; + +import android.app.Activity; +import android.content.Intent; +import android.content.SharedPreferences; +import android.nfc.NdefMessage; +import android.nfc.NdefRecord; +import android.nfc.NfcAdapter; +import android.os.Bundle; +import android.os.Parcelable; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.Button; + +import no.spca.android.iisc.SPCA.LoginScreen; +import no.spca.android.iisc.SPCA.MainActivity; + +public class SplashscreenActivity extends Activity { + + private static final int DELAY = 1000; + Animation btnAnim ; + Button btnGetStarted; + private static final int SPLASH_TIME_OUT=3000; + String number; + + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_splashscreen); + SharedPreferences preferences6 = getSharedPreferences("PhoneBook_number", MODE_PRIVATE); + + number = preferences6.getString("Phone", null); + + btnGetStarted=findViewById(R.id.started); + btnGetStarted.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + + if (number == null ) { + + + Intent home = new Intent(SplashscreenActivity.this, LoginScreen.class); + startActivity(home); + finish(); + } + else { + final Intent newIntent = new Intent(SplashscreenActivity.this, MainActivity.class); + newIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); + // btnGetStarted.setAnimation(btnAnim); + + + 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(); + + } + } + }); + btnAnim = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.button_animation); + // btnGetStarted.setAnimation(btnAnim); + + + } + + @Override + public void onBackPressed() { + } + + + 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/adapter/AppAdapter.java b/app/src/main/java/no/spca/android/iisc/adapter/AppAdapter.java similarity index 58% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/adapter/AppAdapter.java rename to app/src/main/java/no/spca/android/iisc/adapter/AppAdapter.java index d9116d0..60582c9 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/adapter/AppAdapter.java +++ b/app/src/main/java/no/spca/android/iisc/adapter/AppAdapter.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.adapter; import android.content.ComponentName; import android.content.Context; @@ -37,10 +17,11 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import no.nordicsemi.android.nrftoolbox.R; +import no.spca.android.iisc.R; + public class AppAdapter extends BaseAdapter { - private static final String CATEGORY = "no.nordicsemi.android.nrftoolbox.LAUNCHER"; + private static final String CATEGORY = "no.spca.android.iisc.LAUNCHER"; private static final String NRF_CONNECT_PACKAGE = "no.nordicsemi.android.mcp"; private final Context mContext; @@ -52,13 +33,11 @@ public class AppAdapter extends BaseAdapter { 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); diff --git a/app/src/main/java/no/spca/android/iisc/app/ExpandableListActivity.java b/app/src/main/java/no/spca/android/iisc/app/ExpandableListActivity.java new file mode 100644 index 0000000..71b08f2 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/app/ExpandableListActivity.java @@ -0,0 +1,132 @@ + + +package no.spca.android.iisc.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.spca.android.iisc.R; + + + +public class ExpandableListActivity extends AppCompatActivity implements + OnCreateContextMenuListener, + ExpandableListView.OnChildClickListener, ExpandableListView.OnGroupCollapseListener, + ExpandableListView.OnGroupExpandListener { + ExpandableListAdapter mAdapter; + ExpandableListView mList; + boolean mFinishedStart = false; + + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + } + + + @Override + public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, + int childPosition, long id) { + return false; + } + + + @Override + public void onGroupCollapse(int groupPosition) { + } + + + @Override + public void onGroupExpand(int groupPosition) { + } + + + @Override + protected void onRestoreInstanceState(@NonNull Bundle state) { + ensureList(); + super.onRestoreInstanceState(state); + } + + + @Override + public void onContentChanged() { + super.onContentChanged(); + View emptyView ; + mList = findViewById(R.id.list); + if (mList == null) { + throw new RuntimeException( + "Your content must have a ExpandableListView whose id attribute is " + + "'R.id.list'"); + } + + mList.setOnChildClickListener(this); + mList.setOnGroupExpandListener(this); + mList.setOnGroupCollapseListener(this); + + if (mFinishedStart) { + setListAdapter(mAdapter); + } + mFinishedStart = true; + } + + + public void setListAdapter(ExpandableListAdapter adapter) { + synchronized (this) { + ensureList(); + mAdapter = adapter; + mList.setAdapter(adapter); + } + } + + + public ExpandableListView getExpandableListView() { + ensureList(); + return mList; + } + + + public ExpandableListAdapter getExpandableListAdapter() { + return mAdapter; + } + + private void ensureList() { + if (mList != null) { + return; + } + setContentView(R.layout.expandable_list_content); + } + + + public long getSelectedId() { + return mList.getSelectedId(); + } + + + public long getSelectedPosition() { + return mList.getSelectedPosition(); + } + + + public boolean setSelectedChild(int groupPosition, int childPosition, boolean shouldExpandGroup) { + return mList.setSelectedChild(groupPosition, childPosition, shouldExpandGroup); + } + + + 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/spca/android/iisc/battery/BatteryManager.java similarity index 80% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java rename to app/src/main/java/no/spca/android/iisc/battery/BatteryManager.java index 5d5d6e6..2599eb1 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManager.java +++ b/app/src/main/java/no/spca/android/iisc/battery/BatteryManager.java @@ -1,4 +1,4 @@ -package no.nordicsemi.android.nrftoolbox.battery; +package no.spca.android.iisc.battery; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; @@ -15,35 +15,26 @@ 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; +import no.spca.android.iisc.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() { + private final DataReceivedCallback mBatteryLevelDataCallback = new BatteryLevelDataCallback() { @Override public void onBatteryLevelChanged(@NonNull final BluetoothDevice device, final int batteryLevel) { log(LogContract.Log.Level.APPLICATION,"Battery Level received: " + batteryLevel + "%"); @@ -68,7 +59,6 @@ public abstract class BatteryManager extends public void enableBatteryLevelCharacteristicNotifications() { if (isConnected()) { - // If the Battery Level characteristic is null, the request will be ignored setNotificationCallback(mBatteryLevelCharacteristic) .with(mBatteryLevelDataCallback); enableNotifications(mBatteryLevelCharacteristic) @@ -78,9 +68,7 @@ public abstract class BatteryManager extends } } - /** - * Disables Battery Level notifications on the Server. - */ + public void disableBatteryLevelCharacteristicNotifications() { if (isConnected()) { disableNotifications(mBatteryLevelCharacteristic) @@ -89,11 +77,7 @@ public abstract class BatteryManager extends } } - /** - * 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; } diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManagerCallbacks.java b/app/src/main/java/no/spca/android/iisc/battery/BatteryManagerCallbacks.java similarity index 82% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManagerCallbacks.java rename to app/src/main/java/no/spca/android/iisc/battery/BatteryManagerCallbacks.java index 26a2905..a0478e3 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/battery/BatteryManagerCallbacks.java +++ b/app/src/main/java/no/spca/android/iisc/battery/BatteryManagerCallbacks.java @@ -1,4 +1,4 @@ -package no.nordicsemi.android.nrftoolbox.battery; +package no.spca.android.iisc.battery; import no.nordicsemi.android.ble.BleManagerCallbacks; import no.nordicsemi.android.ble.common.profile.battery.BatteryLevelCallback; diff --git a/app/src/main/java/no/spca/android/iisc/parser/CycleParser.java b/app/src/main/java/no/spca/android/iisc/parser/CycleParser.java new file mode 100644 index 0000000..281c748 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/parser/CycleParser.java @@ -0,0 +1,19 @@ +package no.spca.android.iisc.parser; + +import no.nordicsemi.android.ble.data.Data; + +public class CycleParser { + private static final byte HEART_RATE_VALUE_FORMAT = 0x01; @SuppressWarnings("UnusedAssignment") + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + + final boolean value16bit = (flags & HEART_RATE_VALUE_FORMAT) > 0; + + int value = data.getIntValue(value16bit ? Data.FORMAT_UINT16 : Data.FORMAT_UINT8, offset++); if (value16bit) + offset++; + + return "Cycle: " + value + " bpm"; + } +} diff --git a/app/src/main/java/no/spca/android/iisc/parser/TemperatureParser.java b/app/src/main/java/no/spca/android/iisc/parser/TemperatureParser.java new file mode 100644 index 0000000..f3f0bde --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/parser/TemperatureParser.java @@ -0,0 +1,23 @@ + +package no.spca.android.iisc.parser; + +import no.nordicsemi.android.ble.data.Data; + + + +@SuppressWarnings("ConstantConditions") +public class TemperatureParser { + private static final byte HEART_RATE_VALUE_FORMAT = 0x01; @SuppressWarnings("UnusedAssignment") + public static String parse(final Data data) { + int offset = 0; + final int flags = data.getIntValue(Data.FORMAT_UINT8, offset++); + + + final boolean value16bit = (flags & HEART_RATE_VALUE_FORMAT) > 0; + + int value = data.getIntValue(value16bit ? Data.FORMAT_UINT16 : Data.FORMAT_UINT8, offset++); if (value16bit) + offset++; + + return "Temprature: " + value + " bpm"; + } +} diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileActivity.java b/app/src/main/java/no/spca/android/iisc/profile/BleProfileActivity.java similarity index 51% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileActivity.java rename to app/src/main/java/no/spca/android/iisc/profile/BleProfileActivity.java index e9ea7ee..3661f42 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileActivity.java +++ b/app/src/main/java/no/spca/android/iisc/profile/BleProfileActivity.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.profile; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; @@ -32,8 +12,7 @@ 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; @@ -45,10 +24,9 @@ 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; +import no.spca.android.iisc.R; +import no.spca.android.iisc.scanner.ScannerFragment; +import no.spca.android.iisc.DebugLogger; @SuppressWarnings("unused") public abstract class BleProfileActivity extends AppCompatActivity implements BleManagerCallbacks, ScannerFragment.OnDeviceSelectedListener { @@ -76,59 +54,32 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl 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 void onInitialize(final Bundle savedInstanceState) { + } + + 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 void onViewCreated(final Bundle savedInstanceState) { + } + + protected final void setUpView() { - // set GUI getSupportActionBar().setDisplayHomeAsUpEnabled(true); mConnectButton = findViewById(R.id.action_connect); mDeviceNameView = findViewById(R.id.device_name); @@ -136,8 +87,7 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl @Override public void onBackPressed() { - mBleManager.disconnect().enqueue(); - super.onBackPressed(); + } @Override @@ -160,43 +110,16 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl } } - @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) { @@ -210,29 +133,17 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl } } - /** - * 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; } @@ -242,7 +153,6 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl 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); } @@ -257,8 +167,7 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl @Override public void onDialogCanceled() { - // do nothing - } + } @Override public void onDeviceConnecting(@NonNull final BluetoothDevice device) { @@ -296,13 +205,11 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl @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) { @@ -330,80 +237,42 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl 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); @@ -411,11 +280,7 @@ public abstract class BleProfileActivity extends AppCompatActivity implements Bl }); } - /** - * 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; } diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileExpandableListActivity.java b/app/src/main/java/no/spca/android/iisc/profile/BleProfileExpandableListActivity.java similarity index 52% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileExpandableListActivity.java rename to app/src/main/java/no/spca/android/iisc/profile/BleProfileExpandableListActivity.java index a7058bc..010f9ce 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileExpandableListActivity.java +++ b/app/src/main/java/no/spca/android/iisc/profile/BleProfileExpandableListActivity.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.profile; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; @@ -31,8 +11,7 @@ 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; @@ -44,11 +23,10 @@ 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; +import no.spca.android.iisc.R; +import no.spca.android.iisc.app.ExpandableListActivity; +import no.spca.android.iisc.scanner.ScannerFragment; +import no.spca.android.iisc.DebugLogger; @SuppressWarnings("unused") public abstract class BleProfileExpandableListActivity extends ExpandableListActivity implements BleManagerCallbacks, ScannerFragment.OnDeviceSelectedListener { @@ -76,61 +54,34 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct 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); @@ -138,8 +89,7 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct @Override public void onBackPressed() { - mBleManager.disconnect().enqueue(); - super.onBackPressed(); + } @Override @@ -162,44 +112,17 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct } } - @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) { @@ -213,29 +136,17 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct } } - /** - * 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; } @@ -245,7 +156,6 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct 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); } @@ -260,8 +170,7 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct @Override public void onDialogCanceled() { - // do nothing - } + } @Override public void onDeviceConnecting(@NonNull final BluetoothDevice device) { @@ -299,13 +208,11 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct @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) { @@ -333,80 +240,42 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct 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); @@ -414,11 +283,7 @@ public abstract class BleProfileExpandableListActivity extends ExpandableListAct }); } - /** - * 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; } diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileService.java b/app/src/main/java/no/spca/android/iisc/profile/BleProfileService.java similarity index 56% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileService.java rename to app/src/main/java/no/spca/android/iisc/profile/BleProfileService.java index e63c377..0490b2d 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileService.java +++ b/app/src/main/java/no/spca/android/iisc/profile/BleProfileService.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.profile; import android.app.Service; import android.bluetooth.BluetoothAdapter; @@ -50,28 +30,28 @@ public abstract class BleProfileService extends Service implements BleManagerCal @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"; + public static final String BROADCAST_CONNECTION_STATE = "no.spca.android.iisc.BROADCAST_CONNECTION_STATE"; + public static final String BROADCAST_SERVICES_DISCOVERED = "no.spca.android.iisc.BROADCAST_SERVICES_DISCOVERED"; + public static final String BROADCAST_DEVICE_READY = "no.spca.android.iisc.DEVICE_READY"; + public static final String BROADCAST_BOND_STATE = "no.spca.android.iisc.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 BROADCAST_BATTERY_LEVEL = "no.spca.android.iisc.BROADCAST_BATTERY_LEVEL"; + public static final String BROADCAST_ERROR = "no.spca.android.iisc.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"; + + public static final String EXTRA_DEVICE_ADDRESS = "no.spca.android.iisc.EXTRA_DEVICE_ADDRESS"; + + public static final String EXTRA_DEVICE_NAME = "no.spca.android.iisc.EXTRA_DEVICE_NAME"; + public static final String EXTRA_DEVICE = "no.spca.android.iisc.EXTRA_DEVICE"; + public static final String EXTRA_LOG_URI = "no.spca.android.iisc.EXTRA_LOG_URI"; + public static final String EXTRA_CONNECTION_STATE = "no.spca.android.iisc.EXTRA_CONNECTION_STATE"; + public static final String EXTRA_BOND_STATE = "no.spca.android.iisc.EXTRA_BOND_STATE"; + public static final String EXTRA_SERVICE_PRIMARY = "no.spca.android.iisc.EXTRA_SERVICE_PRIMARY"; + public static final String EXTRA_SERVICE_SECONDARY = "no.spca.android.iisc.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 String EXTRA_BATTERY_LEVEL = "no.spca.android.iisc.EXTRA_BATTERY_LEVEL"; + public static final String EXTRA_ERROR_MESSAGE = "no.spca.android.iisc.EXTRA_ERROR_MESSAGE"; + public static final String EXTRA_ERROR_CODE = "no.spca.android.iisc.EXTRA_ERROR_CODE"; public static final int STATE_LINK_LOSS = -1; public static final int STATE_DISCONNECTED = 0; @@ -125,9 +105,7 @@ public abstract class BleProfileService extends Service implements BleManagerCal }; 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) { @@ -139,67 +117,38 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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; } @@ -215,21 +164,13 @@ public abstract class BleProfileService extends Service implements BleManagerCal } } - /** - * 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(); } @@ -247,14 +188,9 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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) { @@ -263,17 +199,12 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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 @@ -282,42 +213,28 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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 - */ + protected void onServiceCreated() { + } + + @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; } @@ -346,30 +263,21 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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; @@ -379,21 +287,13 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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 onBluetoothDisabled() { + } + + protected void onBluetoothEnabled() { - // empty default implementation - } + } @Override public void onDeviceConnecting(@NonNull final BluetoothDevice device) { @@ -414,30 +314,19 @@ public abstract class BleProfileService extends Service implements BleManagerCal @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); @@ -448,7 +337,6 @@ public abstract class BleProfileService extends Service implements BleManagerCal } protected void stopService() { - // user requested disconnection. We must stop the service Logger.v(mLogSession, "Stopping service..."); stopSelf(); } @@ -485,8 +373,7 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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) { @@ -498,7 +385,7 @@ public abstract class BleProfileService extends Service implements BleManagerCal @Override public void onBondingRequired(@NonNull final BluetoothDevice device) { - showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding); + showToast(no.spca.android.iisc.R.string.bonding); final Intent broadcast = new Intent(BROADCAST_BOND_STATE); broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); @@ -508,7 +395,7 @@ public abstract class BleProfileService extends Service implements BleManagerCal @Override public void onBonded(@NonNull final BluetoothDevice device) { - showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonded); + showToast(no.spca.android.iisc.R.string.bonding); final Intent broadcast = new Intent(BROADCAST_BOND_STATE); broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); @@ -518,7 +405,7 @@ public abstract class BleProfileService extends Service implements BleManagerCal @Override public void onBondingFailed(@NonNull final BluetoothDevice device) { - showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding_failed); + showToast(no.spca.android.iisc.R.string.bonding_failed); final Intent broadcast = new Intent(BROADCAST_BOND_STATE); broadcast.putExtra(EXTRA_DEVICE, mBluetoothDevice); @@ -535,68 +422,37 @@ public abstract class BleProfileService extends Service implements BleManagerCal 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/spca/android/iisc/profile/BleProfileServiceReadyActivity.java similarity index 55% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileServiceReadyActivity.java rename to app/src/main/java/no/spca/android/iisc/profile/BleProfileServiceReadyActivity.java index ce2069b..1823d72 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleProfileServiceReadyActivity.java +++ b/app/src/main/java/no/spca/android/iisc/profile/BleProfileServiceReadyActivity.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.profile; import android.app.Service; import android.bluetooth.BluetoothAdapter; @@ -38,9 +18,7 @@ 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; @@ -52,25 +30,13 @@ 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; +import no.spca.android.iisc.R; +import no.spca.android.iisc.scanner.ScannerFragment; +import no.spca.android.iisc.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 +public abstract class BleProfileServiceReadyActivity extends AppCompatActivity implements ScannerFragment.OnDeviceSelectedListener, BleManagerCallbacks { private static final String TAG = "BleProfileServiceReadyActivity"; @@ -91,7 +57,6 @@ public abstract class BleProfileServiceReadyActivity 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 void onInitialize(final Bundle savedInstanceState) { + } + + 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 void onViewCreated(final Bundle savedInstanceState) { + } + + protected final void setUpView() { - // set GUI - getSupportActionBar().setDisplayHomeAsUpEnabled(true); mConnectButton = findViewById(R.id.action_connect); mDeviceNameView = findViewById(R.id.device_name); } @@ -384,43 +285,15 @@ public abstract class BleProfileServiceReadyActivitytrue 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) { @@ -434,20 +307,12 @@ public abstract class BleProfileServiceReadyActivity 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); } @@ -465,7 +329,6 @@ public abstract class BleProfileServiceReadyActivity 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; } diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/LoggableBleManager.java b/app/src/main/java/no/spca/android/iisc/profile/LoggableBleManager.java similarity index 62% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/LoggableBleManager.java rename to app/src/main/java/no/spca/android/iisc/profile/LoggableBleManager.java index 1b4685c..91a628e 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/LoggableBleManager.java +++ b/app/src/main/java/no/spca/android/iisc/profile/LoggableBleManager.java @@ -1,4 +1,4 @@ -package no.nordicsemi.android.nrftoolbox.profile; +package no.spca.android.iisc.profile; import android.content.Context; import androidx.annotation.NonNull; @@ -11,31 +11,16 @@ 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; } diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileService.java b/app/src/main/java/no/spca/android/iisc/profile/multiconnect/BleMulticonnectProfileService.java similarity index 54% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileService.java rename to app/src/main/java/no/spca/android/iisc/profile/multiconnect/BleMulticonnectProfileService.java index 9d651f8..bb83817 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileService.java +++ b/app/src/main/java/no/spca/android/iisc/profile/multiconnect/BleMulticonnectProfileService.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.profile.multiconnect; import android.app.Service; import android.bluetooth.BluetoothAdapter; @@ -47,29 +27,30 @@ 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; +import no.spca.android.iisc.R; +import no.spca.android.iisc.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"; + public static final String BROADCAST_CONNECTION_STATE = "no.spca.android.iisc.BROADCAST_CONNECTION_STATE"; + public static final String BROADCAST_SERVICES_DISCOVERED = "no.spca.android.iisc.BROADCAST_SERVICES_DISCOVERED"; + public static final String BROADCAST_DEVICE_READY = "no.spca.android.iisc.DEVICE_READY"; + public static final String BROADCAST_BOND_STATE = "no.spca.android.iisc.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 BROADCAST_BATTERY_LEVEL = "no.spca.android.iisc.BROADCAST_BATTERY_LEVEL"; + public static final String BROADCAST_ERROR = "no.spca.android.iisc.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"; + public static final String EXTRA_DEVICE = "no.spca.android.iisc.EXTRA_DEVICE"; + public static final String EXTRA_CONNECTION_STATE = "no.spca.android.iisc.EXTRA_CONNECTION_STATE"; + public static final String EXTRA_BOND_STATE = "no.spca.android.iisc.EXTRA_BOND_STATE"; + public static final String EXTRA_SERVICE_PRIMARY = "no.spca.android.iisc.EXTRA_SERVICE_PRIMARY"; + public static final String EXTRA_SERVICE_SECONDARY = "no.spca.android.iisc.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 String EXTRA_BATTERY_LEVEL = "no.spca.android.iisc.EXTRA_BATTERY_LEVEL"; + public static final String EXTRA_ERROR_MESSAGE = "no.spca.android.iisc.EXTRA_ERROR_MESSAGE"; + public static final String EXTRA_ERROR_CODE = "no.spca.android.iisc.EXTRA_ERROR_CODE"; public static final int STATE_LINK_LOSS = -1; public static final int STATE_DISCONNECTED = 0; @@ -92,9 +73,6 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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: @@ -107,33 +85,19 @@ public abstract class BleMulticonnectProfileService extends Service implements B }; 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); @@ -156,12 +120,7 @@ public abstract class BleMulticonnectProfileService extends Service implements B } } - /** - * 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()) { @@ -170,54 +129,32 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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; } @@ -249,21 +186,13 @@ public abstract class BleMulticonnectProfileService extends Service implements B } } - /** - * 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(); } @@ -282,14 +211,9 @@ public abstract class BleMulticonnectProfileService extends Service implements B } } - /** - * 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) { @@ -299,22 +223,16 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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() { @@ -322,58 +240,40 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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 - */ + protected void onServiceCreated() { + } + + @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(); } @@ -384,16 +284,11 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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"); } @@ -403,20 +298,11 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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 onBluetoothDisabled() { + } + + protected void onBluetoothEnabled() { for (final BluetoothDevice device : mManagedDevices) { final BleManager manager = mBleManagers.get(device); @@ -451,22 +337,12 @@ public abstract class BleMulticonnectProfileService extends Service implements B @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(); } @@ -498,7 +374,6 @@ public abstract class BleMulticonnectProfileService extends Service implements B @Override public void onDeviceNotSupported(final BluetoothDevice device) { - // We don't like this device, remove it from both collections mManagedDevices.remove(device); mBleManagers.remove(device); @@ -508,8 +383,7 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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) { @@ -521,7 +395,7 @@ public abstract class BleMulticonnectProfileService extends Service implements B @Override public void onBondingRequired(final BluetoothDevice device) { - showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding); + showToast(no.spca.android.iisc.R.string.bonding); final Intent broadcast = new Intent(BROADCAST_BOND_STATE); broadcast.putExtra(EXTRA_DEVICE, device); @@ -531,7 +405,7 @@ public abstract class BleMulticonnectProfileService extends Service implements B @Override public void onBonded(final BluetoothDevice device) { - showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonded); + showToast(R.string.bonded); final Intent broadcast = new Intent(BROADCAST_BOND_STATE); broadcast.putExtra(EXTRA_DEVICE, device); @@ -541,7 +415,7 @@ public abstract class BleMulticonnectProfileService extends Service implements B @Override public void onBondingFailed(final BluetoothDevice device) { - showToast(no.nordicsemi.android.nrftoolbox.common.R.string.bonding_failed); + showToast(R.string.bonding_failed); final Intent broadcast = new Intent(BROADCAST_BOND_STATE); broadcast.putExtra(EXTRA_DEVICE, device); @@ -558,48 +432,27 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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) { @@ -609,11 +462,7 @@ public abstract class BleMulticonnectProfileService extends Service implements B 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/spca/android/iisc/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java similarity index 54% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java rename to app/src/main/java/no/spca/android/iisc/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java index d3bad57..e03b331 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java +++ b/app/src/main/java/no/spca/android/iisc/profile/multiconnect/BleMulticonnectProfileServiceReadyActivity.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.profile.multiconnect; import android.app.Service; import android.bluetooth.BluetoothAdapter; @@ -39,8 +19,6 @@ 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; @@ -53,26 +31,13 @@ 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; +import no.spca.android.iisc.R; +import no.spca.android.iisc.scanner.ScannerFragment; +import no.spca.android.iisc.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 { + ScannerFragment.OnDeviceSelectedListener, BleManagerCallbacks { private static final String TAG = "BleMulticonnectProfileServiceReadyActivity"; protected static final int REQUEST_ENABLE_BT = 2; @@ -111,7 +76,6 @@ public abstract class BleMulticonnectProfileServiceReadyActivity 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 void onInitialize(final Bundle savedInstanceState) { + } + + 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 void onViewCreated(final Bundle savedInstanceState) { + } + + 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()); @@ -366,20 +255,12 @@ public abstract class BleMulticonnectProfileServiceReadyActivity 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); } @@ -401,48 +281,39 @@ public abstract class BleMulticonnectProfileServiceReadyActivity 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"); diff --git a/app/src/main/java/no/spca/android/iisc/profile/multiconnect/IDeviceLogger.java b/app/src/main/java/no/spca/android/iisc/profile/multiconnect/IDeviceLogger.java new file mode 100644 index 0000000..5a20c59 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/profile/multiconnect/IDeviceLogger.java @@ -0,0 +1,14 @@ + + +package no.spca.android.iisc.profile.multiconnect; + +import android.bluetooth.BluetoothDevice; +import androidx.annotation.StringRes; + +public interface IDeviceLogger { + + void log(final BluetoothDevice device, final int level, final String 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/scanner/DeviceListAdapter.java b/app/src/main/java/no/spca/android/iisc/scanner/DeviceListAdapter.java similarity index 67% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/DeviceListAdapter.java rename to app/src/main/java/no/spca/android/iisc/scanner/DeviceListAdapter.java index cae8572..785726f 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/DeviceListAdapter.java +++ b/app/src/main/java/no/spca/android/iisc/scanner/DeviceListAdapter.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.scanner; import android.bluetooth.BluetoothDevice; import android.content.Context; @@ -34,12 +14,10 @@ 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; +import no.spca.android.iisc.R; + -/** - * 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; @@ -53,10 +31,7 @@ public class DeviceListAdapter extends BaseAdapter { 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) { @@ -65,10 +40,7 @@ public class DeviceListAdapter extends BaseAdapter { 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); @@ -99,17 +71,14 @@ public class DeviceListAdapter extends BaseAdapter { @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) + final int bondedCount = mListBondedValues.size() + 1; final int availableCount = mListValues.isEmpty() ? 2 : mListValues.size() + 1; 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()) { + final int bondedCount = mListBondedValues.size() + 1; if (mListBondedValues.isEmpty()) { if (position == 0) return R.string.scanner_subtitle_not_bonded; else diff --git a/app/src/main/java/no/spca/android/iisc/scanner/ExtendedBluetoothDevice.java b/app/src/main/java/no/spca/android/iisc/scanner/ExtendedBluetoothDevice.java new file mode 100644 index 0000000..0f9f082 --- /dev/null +++ b/app/src/main/java/no/spca/android/iisc/scanner/ExtendedBluetoothDevice.java @@ -0,0 +1,33 @@ + +package no.spca.android.iisc.scanner; + +import android.bluetooth.BluetoothDevice; + +import no.nordicsemi.android.support.v18.scanner.ScanResult; + +public class ExtendedBluetoothDevice { + static final int NO_RSSI = -1000; + public final BluetoothDevice device; + + 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/spca/android/iisc/scanner/ScannerFragment.java similarity index 60% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ScannerFragment.java rename to app/src/main/java/no/spca/android/iisc/scanner/ScannerFragment.java index 65727d2..8bb87cc 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/scanner/ScannerFragment.java +++ b/app/src/main/java/no/spca/android/iisc/scanner/ScannerFragment.java @@ -1,25 +1,5 @@ -/* - * 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; + +package no.spca.android.iisc.scanner; import android.Manifest; import android.app.Dialog; @@ -48,29 +28,21 @@ 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; +import no.spca.android.iisc.R; + -/** - * 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 final static int REQUEST_PERMISSION_REQ_CODE = 34; private BluetoothAdapter mBluetoothAdapter; private OnDeviceSelectedListener mListener; private DeviceListAdapter mAdapter; private final Handler mHandler = new Handler(); @@ -92,31 +64,16 @@ public class ScannerFragment extends DialogFragment { 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); @@ -167,9 +124,7 @@ public class ScannerFragment extends DialogFragment { 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); + mPermissionRationale = dialogView.findViewById(R.id.permission_rationale); mScanButton = dialogView.findViewById(R.id.action_cancel); mScanButton.setOnClickListener(v -> { if (v.getId() == R.id.action_cancel) { if (mIsScanning) { @@ -198,7 +153,6 @@ public class ScannerFragment extends DialogFragment { 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); @@ -209,27 +163,18 @@ public class ScannerFragment extends DialogFragment { } } - /** - * 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 (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 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); + requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_REQ_CODE); return; } - // Hide the rationale message, we don't need it anymore. if (mPermissionRationale != null) mPermissionRationale.setVisibility(View.GONE); @@ -243,7 +188,6 @@ public class ScannerFragment extends DialogFragment { final List filters = new ArrayList<>(); filters.add(new ScanFilter.Builder().setServiceUuid(mUuid).build()); scanner.startScan(filters, settings, scanCallback); - mIsScanning = true; mHandler.postDelayed(() -> { if (mIsScanning) { @@ -252,9 +196,7 @@ public class ScannerFragment extends DialogFragment { }, SCAN_DURATION); } - /** - * Stop scan if user tap Cancel button - */ + private void stopScan() { if (mIsScanning) { mScanButton.setText(R.string.scanner_action_scan); @@ -266,11 +208,10 @@ public class ScannerFragment extends DialogFragment { } } - private ScanCallback scanCallback = new ScanCallback() { + private final ScanCallback scanCallback = new ScanCallback() { @Override public void onScanResult(final int callbackType, final ScanResult result) { - // do nothing - } + } @Override public void onBatchScanResults(final List results) { @@ -279,8 +220,7 @@ public class ScannerFragment extends DialogFragment { @Override public void onScanFailed(final int errorCode) { - // should never be called - } + } }; private void addBoundDevices() { diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundRelativeLayout.java b/app/src/main/java/no/spca/android/iisc/widget/ForegroundRelativeLayout.java similarity index 62% rename from app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundRelativeLayout.java rename to app/src/main/java/no/spca/android/iisc/widget/ForegroundRelativeLayout.java index c3aa280..cb9fd0f 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/widget/ForegroundRelativeLayout.java +++ b/app/src/main/java/no/spca/android/iisc/widget/ForegroundRelativeLayout.java @@ -1,26 +1,6 @@ -/************************************************************************************************************************************************* - * 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; + +package no.spca.android.iisc.widget; import android.annotation.TargetApi; import android.content.Context; @@ -34,7 +14,8 @@ import androidx.annotation.NonNull; import android.util.AttributeSet; import android.widget.RelativeLayout; -import no.nordicsemi.android.nrftoolbox.R; +import no.spca.android.iisc.R; + public class ForegroundRelativeLayout extends RelativeLayout { diff --git a/app/src/main/res/anim/button_animation.xml b/app/src/main/res/anim/button_animation.xml new file mode 100644 index 0000000..9eed840 --- /dev/null +++ b/app/src/main/res/anim/button_animation.xml @@ -0,0 +1,16 @@ + + + + + + + + + + \ 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 deleted file mode 100644 index 7b316a4..0000000 --- a/app/src/main/res/animator/click_animator.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index 2c87a8e..0000000 --- a/app/src/main/res/color/button_color.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ 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 deleted file mode 100644 index c6d777f..0000000 --- a/app/src/main/res/color/menu_text.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - diff --git a/app/src/main/res/drawable-hdpi/battery.png b/app/src/main/res/drawable-hdpi/battery.png deleted file mode 100644 index dd83f9b..0000000 Binary files a/app/src/main/res/drawable-hdpi/battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/dst_logo.png b/app/src/main/res/drawable-hdpi/dst_logo.png new file mode 100644 index 0000000..a37fed2 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/dst_logo.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 deleted file mode 100644 index e64801e..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_action_disconnect.png and /dev/null 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 deleted file mode 100644 index 875f8a2..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_bpm_feature.png and /dev/null 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 deleted file mode 100644 index 6e05b92..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_cgms_feature.png and /dev/null 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 deleted file mode 100644 index 8a105bd..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_csc_feature.png and /dev/null 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 deleted file mode 100644 index db59fae..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_dfu_feature.png and /dev/null 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 deleted file mode 100644 index 9ea9243..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_glucose_feature.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_help.png b/app/src/main/res/drawable-hdpi/ic_help.png deleted file mode 100644 index 459bed7..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_help.png and /dev/null 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 deleted file mode 100644 index 650a4da..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_hrs_feature.png and /dev/null 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 deleted file mode 100644 index de2f119..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_hts_feature.png and /dev/null 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 deleted file mode 100644 index 5b80a88..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_proximity_feature.png and /dev/null 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 deleted file mode 100644 index 8e45929..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_rsc_feature.png and /dev/null 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 deleted file mode 100644 index 2b783a8..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_stat_notify_cgms.png and /dev/null 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 deleted file mode 100644 index ddc2e25..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_stat_notify_csc.png and /dev/null 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 deleted file mode 100644 index 4fed093..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_stat_notify_hts.png and /dev/null 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 deleted file mode 100644 index af0b454..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_stat_notify_proximity.png and /dev/null 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 deleted file mode 100644 index 14ed163..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_stat_notify_rsc.png and /dev/null 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 deleted file mode 100644 index a081193..0000000 Binary files a/app/src/main/res/drawable-hdpi/ic_stat_notify_uart.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/iisc_logo.png b/app/src/main/res/drawable-hdpi/iisc_logo.png new file mode 100644 index 0000000..84e56a3 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/iisc_logo.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 deleted file mode 100644 index e2c0f28..0000000 Binary files a/app/src/main/res/drawable-hdpi/proximity_lock_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/shadow_l.png b/app/src/main/res/drawable-hdpi/shadow_l.png deleted file mode 100644 index b007003..0000000 Binary files a/app/src/main/res/drawable-hdpi/shadow_l.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/shadow_r.png b/app/src/main/res/drawable-hdpi/shadow_r.png deleted file mode 100644 index ae07b59..0000000 Binary files a/app/src/main/res/drawable-hdpi/shadow_r.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/dst_logo.png b/app/src/main/res/drawable-mdpi/dst_logo.png new file mode 100644 index 0000000..60691db Binary files /dev/null and b/app/src/main/res/drawable-mdpi/dst_logo.png differ diff --git a/app/src/main/res/drawable-mdpi/iisc_logo.png b/app/src/main/res/drawable-mdpi/iisc_logo.png new file mode 100644 index 0000000..1975345 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/iisc_logo.png differ diff --git a/app/src/main/res/drawable-v21/button.xml b/app/src/main/res/drawable-v21/button.xml index 4ce2cf2..7b66b15 100644 --- a/app/src/main/res/drawable-v21/button.xml +++ b/app/src/main/res/drawable-v21/button.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable-v21/ic_feature_bg.xml b/app/src/main/res/drawable-v21/ic_feature_bg.xml index 28a32b0..d70912c 100644 --- a/app/src/main/res/drawable-v21/ic_feature_bg.xml +++ b/app/src/main/res/drawable-v21/ic_feature_bg.xml @@ -1,25 +1,5 @@ - + 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 deleted file mode 100644 index 6b1e883..0000000 --- a/app/src/main/res/drawable-v21/ic_icon_button_background.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - diff --git a/app/src/main/res/drawable-v21/uart_button_activated.xml b/app/src/main/res/drawable-v21/uart_button_activated.xml deleted file mode 100644 index e00d0b7..0000000 --- a/app/src/main/res/drawable-v21/uart_button_activated.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - diff --git a/app/src/main/res/drawable-v21/uart_button_background.xml b/app/src/main/res/drawable-v21/uart_button_background.xml deleted file mode 100644 index c2a1769..0000000 --- a/app/src/main/res/drawable-v21/uart_button_background.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - \ 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 deleted file mode 100644 index e754af7..0000000 --- a/app/src/main/res/drawable-v21/uart_button_normal.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - diff --git a/app/src/main/res/drawable-xhdpi/app_drive.png b/app/src/main/res/drawable-xhdpi/app_drive.png deleted file mode 100644 index e640551..0000000 Binary files a/app/src/main/res/drawable-xhdpi/app_drive.png and /dev/null 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 deleted file mode 100644 index 1f3c55b..0000000 Binary files a/app/src/main/res/drawable-xhdpi/app_file_manager.png and /dev/null 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 deleted file mode 100644 index 14e0258..0000000 Binary files a/app/src/main/res/drawable-xhdpi/app_google_play.png and /dev/null 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 deleted file mode 100644 index 406c6cc..0000000 Binary files a/app/src/main/res/drawable-xhdpi/app_total_commander.png and /dev/null 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 deleted file mode 100644 index 73488f3..0000000 Binary files a/app/src/main/res/drawable-xhdpi/btn_default_focused_holo_light.9.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/dst_logo.png b/app/src/main/res/drawable-xhdpi/dst_logo.png new file mode 100644 index 0000000..36895d2 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/dst_logo.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 deleted file mode 100644 index 44d6145..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_action_disconnect.png and /dev/null 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 deleted file mode 100644 index 681e261..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_bpm_feature.png and /dev/null 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 deleted file mode 100644 index c18519d..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_cgms_feature.png and /dev/null 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 deleted file mode 100644 index ba5e624..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_csc_feature.png and /dev/null 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 deleted file mode 100644 index d7065e0..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_dfu_feature.png and /dev/null 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 deleted file mode 100644 index 99ab2f5..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_glucose_feature.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_help.png b/app/src/main/res/drawable-xhdpi/ic_help.png deleted file mode 100644 index 0e67d7c..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_help.png and /dev/null 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 deleted file mode 100644 index d28b50d..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_hrs_feature.png and /dev/null 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 deleted file mode 100644 index c86d709..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_hts_feature.png and /dev/null 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 deleted file mode 100644 index e4351f6..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_hts_feature_black.png and /dev/null 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 deleted file mode 100644 index e13cf3b..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_nrf_connect_feature_fg.png and /dev/null 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 deleted file mode 100644 index d0e7de1..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_proximity_feature.png and /dev/null 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 deleted file mode 100644 index 3f81e0b..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_rsc_feature.png and /dev/null 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 deleted file mode 100644 index 4ff0268..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_stat_notify_cgms.png and /dev/null 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 deleted file mode 100644 index d0f3466..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_stat_notify_csc.png and /dev/null 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 deleted file mode 100644 index a335593..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_stat_notify_hts.png and /dev/null 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 deleted file mode 100644 index a43b04f..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_stat_notify_proximity.png and /dev/null 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 deleted file mode 100644 index 2ab1689..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_stat_notify_rsc.png and /dev/null 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 deleted file mode 100644 index 4255d2b..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_stat_notify_uart.png and /dev/null 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 deleted file mode 100644 index d737be5..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_1.png and /dev/null 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 deleted file mode 100644 index cf8880f..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_1_small.png and /dev/null 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 deleted file mode 100644 index db2432c..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_2.png and /dev/null 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 deleted file mode 100644 index 855a88c..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_2_small.png and /dev/null 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 deleted file mode 100644 index 7664f4f..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_3.png and /dev/null 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 deleted file mode 100644 index 6c40e48..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_3_small.png and /dev/null 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 deleted file mode 100644 index 1f00c16..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_4.png and /dev/null 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 deleted file mode 100644 index 68b32fd..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_4_small.png and /dev/null 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 deleted file mode 100644 index 190332e..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_5.png and /dev/null 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 deleted file mode 100644 index 192fde1..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_5_small.png and /dev/null 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 deleted file mode 100644 index 7b8879c..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_6.png and /dev/null 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 deleted file mode 100644 index 1aa1c47..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_6_small.png and /dev/null 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 deleted file mode 100644 index 3e12930..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_7.png and /dev/null 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 deleted file mode 100644 index 03293e5..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_7_small.png and /dev/null 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 deleted file mode 100644 index 80d2911..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_8.png and /dev/null 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 deleted file mode 100644 index 3a25ec4..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_8_small.png and /dev/null 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 deleted file mode 100644 index 3bf4196..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_9.png and /dev/null 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 deleted file mode 100644 index d2290c5..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_9_small.png and /dev/null 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 deleted file mode 100644 index a7bdf34..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_about.png and /dev/null 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 deleted file mode 100644 index 3be3152..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_about_small.png and /dev/null 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 deleted file mode 100644 index 5107082..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_down.png and /dev/null 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 deleted file mode 100644 index 76937f5..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_down_small.png and /dev/null 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 deleted file mode 100644 index f173944..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_feature.png and /dev/null 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 deleted file mode 100644 index cd5040e..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_forward.png and /dev/null 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 deleted file mode 100644 index fec2018..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_forward_small.png and /dev/null 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 deleted file mode 100644 index c8c63a9..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_left.png and /dev/null 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 deleted file mode 100644 index ed8ac91..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_left_small.png and /dev/null 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 deleted file mode 100644 index 293f712..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_pause.png and /dev/null 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 deleted file mode 100644 index 504389a..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_pause_small.png and /dev/null 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 deleted file mode 100644 index 97ff9b0..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_play.png and /dev/null 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 deleted file mode 100644 index 7f709bb..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_play_small.png and /dev/null 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 deleted file mode 100644 index 3e66f69..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_rewind.png and /dev/null 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 deleted file mode 100644 index 27a2b9e..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_rewind_small.png and /dev/null 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 deleted file mode 100644 index 4ac16d0..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_right.png and /dev/null 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 deleted file mode 100644 index 5f30474..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_right_small.png and /dev/null 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 deleted file mode 100644 index fe5fec4..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_settings.png and /dev/null 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 deleted file mode 100644 index 999d0f0..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_settings_small.png and /dev/null 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 deleted file mode 100644 index c86dbb1..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_stop.png and /dev/null 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 deleted file mode 100644 index 2b07de4..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_stop_small.png and /dev/null 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 deleted file mode 100644 index 5411d8c..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_up.png and /dev/null 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 deleted file mode 100644 index 60ac6b0..0000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_uart_up_small.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/iisc_logo.png b/app/src/main/res/drawable-xhdpi/iisc_logo.png new file mode 100644 index 0000000..c01a84a Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/iisc_logo.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 deleted file mode 100644 index d400031..0000000 Binary files a/app/src/main/res/drawable-xhdpi/proximity_lock_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/shadow_l.png b/app/src/main/res/drawable-xhdpi/shadow_l.png deleted file mode 100644 index b007003..0000000 Binary files a/app/src/main/res/drawable-xhdpi/shadow_l.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/shadow_r.png b/app/src/main/res/drawable-xhdpi/shadow_r.png deleted file mode 100644 index ae07b59..0000000 Binary files a/app/src/main/res/drawable-xhdpi/shadow_r.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/zip.png b/app/src/main/res/drawable-xhdpi/zip.png deleted file mode 100644 index eb96135..0000000 Binary files a/app/src/main/res/drawable-xhdpi/zip.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/dst_logo.png b/app/src/main/res/drawable-xxhdpi/dst_logo.png new file mode 100644 index 0000000..ea6e42d Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/dst_logo.png differ diff --git a/app/src/main/res/drawable-xxhdpi/gradient.xml b/app/src/main/res/drawable-xxhdpi/gradient.xml new file mode 100644 index 0000000..b859849 --- /dev/null +++ b/app/src/main/res/drawable-xxhdpi/gradient.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + 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 deleted file mode 100644 index 9e16b1f..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_add_normal.png and /dev/null 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 deleted file mode 100644 index e4b6217..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_add_pressed.png and /dev/null 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 deleted file mode 100644 index c03cb87..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_clear_normal.png and /dev/null 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 deleted file mode 100644 index ed70b4e..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_clear_pressed.png and /dev/null 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 deleted file mode 100644 index 035ff88..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_disconnect.png and /dev/null 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 deleted file mode 100644 index bde2379..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_download_normal.png and /dev/null 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 deleted file mode 100644 index 2d91bc3..0000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_action_download_pressed.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/iisc_logo.png b/app/src/main/res/drawable-xxhdpi/iisc_logo.png new file mode 100644 index 0000000..2626870 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/iisc_logo.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/dst_logo.png b/app/src/main/res/drawable-xxxhdpi/dst_logo.png new file mode 100644 index 0000000..a7e0369 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/dst_logo.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 deleted file mode 100644 index b650848..0000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_action_disconnect.png and /dev/null 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 deleted file mode 100644 index 6dfdb8f..0000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_battery_alert.png and /dev/null 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 deleted file mode 100644 index 3503f6f..0000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_battery_full.png and /dev/null 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 deleted file mode 100644 index 501500e..0000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_proximity_tag.png and /dev/null 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 deleted file mode 100644 index e676b17..0000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_find.png and /dev/null 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 deleted file mode 100644 index 419d1ef..0000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_stat_notify_proximity_silent.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/iisc_logo.png b/app/src/main/res/drawable-xxxhdpi/iisc_logo.png new file mode 100644 index 0000000..93cb815 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/iisc_logo.png differ diff --git a/app/src/main/res/drawable/app_file_browser.xml b/app/src/main/res/drawable/app_file_browser.xml deleted file mode 100644 index 09b9238..0000000 --- a/app/src/main/res/drawable/app_file_browser.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/bg_circle.xml b/app/src/main/res/drawable/bg_circle.xml new file mode 100644 index 0000000..0235a9b --- /dev/null +++ b/app/src/main/res/drawable/bg_circle.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/button.xml b/app/src/main/res/drawable/button.xml index fe22380..47df4d7 100644 --- a/app/src/main/res/drawable/button.xml +++ b/app/src/main/res/drawable/button.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/button_n.xml b/app/src/main/res/drawable/button_n.xml index 0b90321..44c7bbd 100644 --- a/app/src/main/res/drawable/button_n.xml +++ b/app/src/main/res/drawable/button_n.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/button_p.xml b/app/src/main/res/drawable/button_p.xml index d79ca8a..2ab24c8 100644 --- a/app/src/main/res/drawable/button_p.xml +++ b/app/src/main/res/drawable/button_p.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/buttonshape.xml b/app/src/main/res/drawable/buttonshape.xml new file mode 100644 index 0000000..85525c7 --- /dev/null +++ b/app/src/main/res/drawable/buttonshape.xml @@ -0,0 +1,20 @@ + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_action_add.xml b/app/src/main/res/drawable/ic_action_add.xml deleted file mode 100644 index b5f0f25..0000000 --- a/app/src/main/res/drawable/ic_action_add.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/ic_action_clear.xml b/app/src/main/res/drawable/ic_action_clear.xml index 88047bc..c0332bb 100644 --- a/app/src/main/res/drawable/ic_action_clear.xml +++ b/app/src/main/res/drawable/ic_action_clear.xml @@ -15,14 +15,9 @@ ~ ~ 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/app/src/main/res/drawable/ic_action_download.xml b/app/src/main/res/drawable/ic_action_download.xml deleted file mode 100644 index e0953c2..0000000 --- a/app/src/main/res/drawable/ic_action_download.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - diff --git a/app/src/main/res/drawable/ic_battery.xml b/app/src/main/res/drawable/ic_battery.xml deleted file mode 100644 index afde310..0000000 --- a/app/src/main/res/drawable/ic_battery.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - \ 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 index b06fc4d..de2611e 100644 --- a/app/src/main/res/drawable/ic_feature_bg.xml +++ b/app/src/main/res/drawable/ic_feature_bg.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/ic_feature_bg_n.xml b/app/src/main/res/drawable/ic_feature_bg_n.xml index 35242a5..b6164ee 100644 --- a/app/src/main/res/drawable/ic_feature_bg_n.xml +++ b/app/src/main/res/drawable/ic_feature_bg_n.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/ic_feature_bg_p.xml b/app/src/main/res/drawable/ic_feature_bg_p.xml index 9a567f4..5167d4e 100644 --- a/app/src/main/res/drawable/ic_feature_bg_p.xml +++ b/app/src/main/res/drawable/ic_feature_bg_p.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/ic_feature_small_bg.xml b/app/src/main/res/drawable/ic_feature_small_bg.xml deleted file mode 100644 index 8134d3d..0000000 --- a/app/src/main/res/drawable/ic_feature_small_bg.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - 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 deleted file mode 100644 index 6137705..0000000 --- a/app/src/main/res/drawable/ic_feature_small_bg_n.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - 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 deleted file mode 100644 index 3361815..0000000 --- a/app/src/main/res/drawable/ic_feature_small_bg_p.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - 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 deleted file mode 100644 index 60e5eed..0000000 --- a/app/src/main/res/drawable/ic_nrf_connect_feature_small.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - \ 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 index e37a8b7..3c9b1a3 100644 --- a/app/src/main/res/drawable/ic_rssi_bar.xml +++ b/app/src/main/res/drawable/ic_rssi_bar.xml @@ -1,25 +1,5 @@ - + diff --git a/app/src/main/res/drawable/nordic_logo.xml b/app/src/main/res/drawable/nordic_logo.xml deleted file mode 100644 index 14679a6..0000000 --- a/app/src/main/res/drawable/nordic_logo.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/nordic_logo_horiz_white.xml b/app/src/main/res/drawable/nordic_logo_horiz_white.xml deleted file mode 100644 index af91623..0000000 --- a/app/src/main/res/drawable/nordic_logo_horiz_white.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/start_edit_mode.xml b/app/src/main/res/drawable/start_edit_mode.xml deleted file mode 100644 index de9d619..0000000 --- a/app/src/main/res/drawable/start_edit_mode.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - \ 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 deleted file mode 100644 index d5491ef..0000000 --- a/app/src/main/res/drawable/stop_edit_mode.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/text_back.xml b/app/src/main/res/drawable/text_back.xml new file mode 100644 index 0000000..b155c77 --- /dev/null +++ b/app/src/main/res/drawable/text_back.xml @@ -0,0 +1,7 @@ + + + + + + \ 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 deleted file mode 100644 index 0abfeb5..0000000 --- a/app/src/main/res/drawable/uart_button.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/uart_button_background.xml b/app/src/main/res/drawable/uart_button_background.xml deleted file mode 100644 index 3c1580e..0000000 --- a/app/src/main/res/drawable/uart_button_background.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - \ 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 deleted file mode 100644 index fb981d2..0000000 --- a/app/src/main/res/drawable/uart_button_small.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/drawable/uart_dialog_button_background.xml b/app/src/main/res/drawable/uart_dialog_button_background.xml deleted file mode 100644 index fd4991f..0000000 --- a/app/src/main/res/drawable/uart_dialog_button_background.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/font/fontstyle.ttf b/app/src/main/res/font/fontstyle.ttf new file mode 100644 index 0000000..0ac5e51 Binary files /dev/null and b/app/src/main/res/font/fontstyle.ttf differ diff --git a/app/src/main/res/layout-land/activity_feature_bpm.xml b/app/src/main/res/layout-land/activity_feature_bpm.xml deleted file mode 100644 index b03b233..0000000 --- a/app/src/main/res/layout-land/activity_feature_bpm.xml +++ /dev/null @@ -1,298 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/res/layout-land/activity_feature_cgms.xml b/app/src/main/res/layout-land/activity_feature_cgms.xml deleted file mode 100644 index 45dfc77..0000000 --- a/app/src/main/res/layout-land/activity_feature_cgms.xml +++ /dev/null @@ -1,220 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -