├── .gitignore ├── LICENSE ├── README.md ├── ble ├── .gitignore ├── ble-proguard-rules.pro ├── build.gradle └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── no │ │ └── nordicsemi │ │ └── android │ │ └── ble │ │ ├── BleManager.java │ │ ├── BleManagerCallbacks.java │ │ ├── ConnectRequest.java │ │ ├── ConnectionPriorityRequest.java │ │ ├── DisconnectRequest.java │ │ ├── MtuRequest.java │ │ ├── Operation.java │ │ ├── PhyRequest.java │ │ ├── ReadRequest.java │ │ ├── ReadRssiRequest.java │ │ ├── ReliableWriteRequest.java │ │ ├── Request.java │ │ ├── RequestQueue.java │ │ ├── SimpleRequest.java │ │ ├── SimpleValueRequest.java │ │ ├── SleepRequest.java │ │ ├── TimeoutHandler.java │ │ ├── TimeoutableRequest.java │ │ ├── TimeoutableValueRequest.java │ │ ├── ValueChangedCallback.java │ │ ├── WaitForValueChangedRequest.java │ │ ├── WriteRequest.java │ │ ├── annotation │ │ ├── ConnectionPriority.java │ │ ├── ConnectionState.java │ │ ├── PhyMask.java │ │ ├── PhyOption.java │ │ ├── PhyValue.java │ │ └── WriteType.java │ │ ├── callback │ │ ├── BeforeCallback.java │ │ ├── ConnectionPriorityCallback.java │ │ ├── DataReceivedCallback.java │ │ ├── DataSentCallback.java │ │ ├── FailCallback.java │ │ ├── InvalidRequestCallback.java │ │ ├── MtuCallback.java │ │ ├── PhyCallback.java │ │ ├── ReadProgressCallback.java │ │ ├── RssiCallback.java │ │ ├── SuccessCallback.java │ │ ├── WriteProgressCallback.java │ │ └── profile │ │ │ ├── ProfileDataCallback.java │ │ │ └── ProfileReadResponse.java │ │ ├── data │ │ ├── Data.java │ │ ├── DataFilter.java │ │ ├── DataMerger.java │ │ ├── DataSplitter.java │ │ ├── DataStream.java │ │ ├── DefaultMtuSplitter.java │ │ └── MutableData.java │ │ ├── error │ │ └── GattError.java │ │ ├── exception │ │ ├── BluetoothDisabledException.java │ │ ├── ConnectionException.java │ │ ├── DeviceDisconnectedException.java │ │ ├── InvalidDataException.java │ │ ├── InvalidRequestException.java │ │ └── RequestFailedException.java │ │ ├── response │ │ ├── ConnectionPriorityResponse.java │ │ ├── MtuResult.java │ │ ├── PhyResult.java │ │ ├── ReadResponse.java │ │ ├── RssiResult.java │ │ └── WriteResponse.java │ │ └── utils │ │ ├── ILogger.java │ │ └── ParserUtils.java │ └── test │ └── java │ └── no │ └── nordicsemi │ └── android │ └── ble │ ├── RequestTest.java │ └── data │ ├── DataStreamTest.java │ ├── DataTest.java │ └── DefaultMtuSplitterTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea 4 | .DS_Store 5 | /build 6 | *.iml 7 | ble/local.properties 8 | ble/.idea/vcs.xml 9 | ble/.idea/misc.xml 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Nordic Semiconductor 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of Nordic Semiconductor ASA nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android BLE Library 2 | 3 | [ ![Download](https://api.bintray.com/packages/nordic/android/ble-library/images/download.svg) ](https://bintray.com/nordic/android/ble-library/_latestVersion) 4 | 5 | An Android library that solves a lot of Android's Bluetooth Low Energy problems. 6 | The [BleManager](https://github.com/NordicSemiconductor/Android-BLE-Library/blob/master/ble/src/main/java/no/nordicsemi/android/ble/BleManager.java) 7 | class exposes high level API for connecting and communicating with Bluetooth LE peripherals. 8 | The API is clean and easy to read. 9 | 10 | ## Features 11 | 12 | **BleManager** class provides the following features: 13 | 14 | 1. Connection, with automatic retries 15 | 2. Service discovery 16 | 3. Bonding (optional) and removing bond information (using reflections) 17 | 4. Automatic handling of Service Changed indications 18 | 5. Device initialization 19 | 6. Asynchronous and synchronous BLE operations using queue 20 | 7. Splitting and merging long packets when writing and reading characteristics and descriptors 21 | 8. Requesting MTU and connection priority (on Android Lollipop or newer) 22 | 9. Reading and setting preferred PHY (on Android Oreo or newer) 23 | 10. Reading RSSI 24 | 11. Refreshing device cache (using reflections) 25 | 12. Reliable Write support 26 | 13. Operation timeouts (for *connect*, *disconnect* and *wait for notification* requests) 27 | 14. Error handling 28 | 15. Logging 29 | 30 | The library **does not provide support for scanning** for Bluetooth LE devices. 31 | For scanning, we recommend using 32 | [Android Scanner Compat Library](https://github.com/NordicSemiconductor/Android-Scanner-Compat-Library) 33 | which brings almost all recent features, introduced in Lollipop and later, to the older platforms. 34 | 35 | ## Importing 36 | 37 | #### Maven Central or jcenter 38 | 39 | The library may be found on jcenter and Maven Central repository. 40 | Add it to your project by adding the following dependency: 41 | 42 | ```grovy 43 | implementation 'no.nordicsemi.android:ble:2.1.1' 44 | ``` 45 | 46 | The last version not migrated to AndroidX is 2.0.5. 47 | 48 | #### As a library module 49 | 50 | Clone this project and add *ble* module as a dependency to your project: 51 | 52 | 1. In *settings.gradle* file add the following lines: 53 | ```groovy 54 | include ':ble' 55 | project(':ble').projectDir = file('../Android-BLE-Library/ble') 56 | ``` 57 | 2. In *app/build.gradle* file add `implementation project(':ble')` inside dependencies. 58 | 3. Sync project and build it. 59 | 60 | ## Usage 61 | 62 | `BleManager` may be used for a single connection 63 | (see [nRF Toolbox](https://github.com/NordicSemiconductor/Android-nRF-Toolbox) -> RSC profile) 64 | or when multiple connections are required (see nRF Toolbox -> Proximity profile), 65 | from a Service (see nRF Toolbox -> RSC profile), ViewModel's repo 66 | (see [Architecture Components](https://developer.android.com/topic/libraries/architecture/index.html) 67 | and [nRF Blinky](https://github.com/NordicSemiconductor/Android-nRF-Blinky)), 68 | or as a singleton (not recommended, see nRF Toolbox -> HRM). 69 | 70 | A single `BleManager` instance is responsible for connecting and communicating with a single peripheral. 71 | Multiple manager instances are allowed. Extend `BleManager` with you manager where you define the 72 | high level device's API. 73 | 74 | ### Changes in version 2.0: 75 | 76 | 1. BLE operation methods (i.e. `writeCharacteristic(...)`, etc.) return the `Request` class now, 77 | instead of boolean. 78 | 2. `onLinklossOccur` callback has been renamed to `onLinkLossOccurred`. 79 | 3. GATT callbacks (for example: `onCharacteristicRead`, `onCharacteristicNotified`, etc.) inside 80 | `BleManagerGattCallback` has been deprecated. Use `Request` callbacks instead. 81 | 4. Build-in Battery Level support has been deprecated. Request Battery Level as any other value. 82 | 5. A new callbacks method: `onBondingFailed` has been added to `BleManagerCallbacks`. 83 | 6. `shouldAutoConnect()` has ben deprecated, use `useAutoConnect(boolean)` in `ConnectRequest` instead. 84 | 7. Timeout is supported for *connect*, *disconnect* and *wait for notification/indication*. 85 | Most BLE operations do not support setting timeout, as receiving the `BluetoothGattCallback` is required 86 | in order to perform the next operation. 87 | 8. Atomic `RequestQueue` and `ReliableWriteRequest` are supported. 88 | 9. BLE Library 2.0 uses Java 8. There's no good reason for this except to push the ecosystem to 89 | having this be a default. As of AGP 3.2 there is no reason not to do this 90 | (via [butterknife](https://github.com/JakeWharton/butterknife)). 91 | 92 | #### Migration guide: 93 | 94 | 1. Replace `initGatt(BluetoothGatt)` with `initialize()`: 95 | 96 | Old code: 97 | ```java 98 | @Override 99 | protected Deque initGatt(final BluetoothGatt gatt) { 100 | final LinkedList requests = new LinkedList<>(); 101 | requests.add(Request.newEnableNotificationsRequest(characteristic)); 102 | return requests; 103 | } 104 | ``` 105 | New code: 106 | ```java 107 | @Override 108 | protected void initialize() { 109 | setNotificationCallback(characteristic) 110 | .with(new DataReceivedCallback() { 111 | @Override 112 | public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { 113 | ... 114 | } 115 | }); 116 | enableNotifications(characteristic) 117 | .enqueue(); 118 | } 119 | ``` 120 | See changes in [Android nRF Toolbox](https://github.com/NordicSemiconductor/Android-nRF-Toolbox/) 121 | and [Android nRF Blinky](https://github.com/NordicSemiconductor/Android-nRF-Blinky/) for more examples. 122 | 123 | Remember to call `.enqueue()` method for initialization requests! 124 | 125 | Connect's completion callback is called after the initialization is done (without or with errors). 126 | 127 | 2. Move your callback implementation from `BleManagerGattCallback` to request callbacks. 128 | 3. To split logic from parsing, we recommend to extend `DataReceivedCallback` interface in a class 129 | where your parse your data, and return higher-level values. For a sample, check out nRF Toolbox 130 | and [Android BLE Common Library](https://github.com/NordicSemiconductor/Android-BLE-Common-Library/). 131 | If you are depending on a SIG adopted profile, like Heart Rate Monitor, Proximity, etc., 132 | feel free to include the **BLE Common Library** in your project. 133 | It has all the parsers implemented. If your profile isn't there, we are happy to accept PRs. 134 | 4. `connect()` and `disconnect()` methods also require calling `.enqueue()` in asynchronous use. 135 | 5. Replace the `shouldAutoConnect()` method in the manager with `connect(device).useAutConnect(true).enqueue()/await()`. 136 | 137 | #### How to test it: 138 | 139 | The new version is compatible with [nRF Toolbox](https://github.com/NordicSemiconductor/Android-nRF-Toolbox) 140 | and [BLE Common Library](https://github.com/NordicSemiconductor/Android-BLE-Common-Library). 141 | The latter one is a set of useful parsers and callbacks for common Bluetooth SIG adopted profiles. 142 | 143 | The libraries are available on jcenter, but if you need to make some changes, clone all 3 projects, 144 | ensure the path to *:ble* and *:ble-common* modules are correct in *settings.gradle* file, and sync the project. 145 | 146 | ## How to use it 147 | 148 | Find the simple example here [Android nRF Blinky](https://github.com/NordicSemiconductor/Android-nRF-Blinky). 149 | 150 | For an example how to use it from an Activity or a Service, check the base Activity and Service 151 | classes in [nRF Toolbox](https://github.com/NordicSemiconductor/Android-nRF-Toolbox/tree/master/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile). 152 | 153 | 1. Define your device API by extending `BleManagerCallbacks`: 154 | [example](https://github.com/NordicSemiconductor/Android-nRF-Blinky/blob/master/app/src/main/java/no/nordicsemi/android/blinky/profile/BlinkyManagerCallbacks.java) 155 | 2. Extend `BleManager` class and implement required methods: 156 | [example](https://github.com/NordicSemiconductor/Android-nRF-Blinky/blob/master/app/src/main/java/no/nordicsemi/android/blinky/profile/BlinkyManager.java) 157 | 158 | ## Version 1.x 159 | 160 | The BLE library v 1.x is no longer supported. Please migrate to 2.x for bug fixing releases. 161 | Find it on [version/1x branch](https://github.com/NordicSemiconductor/Android-BLE-Library/tree/version/1x). -------------------------------------------------------------------------------- /ble/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /.idea -------------------------------------------------------------------------------- /ble/ble-proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /ble/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | /* 3 | apply plugin: 'com.github.dcendents.android-maven' 4 | apply plugin: 'com.jfrog.bintray' 5 | 6 | ext { 7 | PUBLISH_GROUP_ID = 'no.nordicsemi.android' 8 | PUBLISH_ARTIFACT_ID = 'ble' 9 | PUBLISH_VERSION = '2.1.1' 10 | 11 | bintrayRepo = 'android' 12 | bintrayName = 'ble-library' 13 | 14 | publishedGroupId = PUBLISH_GROUP_ID 15 | artifact = PUBLISH_ARTIFACT_ID 16 | libraryVersion = PUBLISH_VERSION 17 | libraryName = 'BLE Library' 18 | libraryDescription = 'Bluetooth Low Energy library for Android' 19 | 20 | issuesUrl = 'https://github.com/NordicSemiconductor/Android-BLE-Library/issues' 21 | siteUrl = 'https://github.com/NordicSemiconductor/Android-BLE-Library' 22 | gitUrl = 'https://github.com/NordicSemiconductor/Android-BLE-Library.git' 23 | 24 | developerId = 'philips77' 25 | developerName = 'Aleksander Nowakowski' 26 | developerEmail = 'aleksander.nowakowski@nordicsemi.no' 27 | 28 | licenseName = 'The BSD 3-Clause License' 29 | licenseUrl = 'http://opensource.org/licenses/BSD-3-Clause' 30 | allLicenses = ["BSD 3-Clause"] 31 | } 32 | */ 33 | android { 34 | compileSdkVersion 34 35 | 36 | namespace 'no.nordicsemi.android.ble' 37 | 38 | 39 | defaultConfig { 40 | minSdkVersion 18 41 | targetSdkVersion 34 42 | versionCode 27 43 | versionName "2.1.1" 44 | 45 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 46 | } 47 | 48 | buildTypes { 49 | release { 50 | minifyEnabled false 51 | consumerProguardFiles 'ble-proguard-rules.pro' 52 | } 53 | } 54 | 55 | compileOptions { 56 | targetCompatibility JavaVersion.VERSION_1_8 57 | sourceCompatibility JavaVersion.VERSION_1_8 58 | } 59 | } 60 | 61 | dependencies { 62 | //noinspection GradleDependency 63 | api 'androidx.annotation:annotation:1.1.0' 64 | implementation 'androidx.appcompat:appcompat:1.6.1' 65 | 66 | testImplementation 'junit:junit:4.13.2' 67 | androidTestImplementation 'androidx.test:runner:1.5.2' 68 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' 69 | } 70 | 71 | /* 72 | // The following script creates a POM file required to publish on Maven Central 73 | apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle' 74 | 75 | // This script creates sources and javadocs. Both are required to publish a library on jcenter and MC. 76 | apply from: 'https://raw.githubusercontent.com/ArthurHub/release-android-library/master/android-release-aar.gradle' 77 | 78 | // The following link publishes the library to jcenter. It does not handle the userOrg, so it has been copied and modified below. 79 | //apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle' 80 | 81 | // Copied from https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle 82 | version = libraryVersion 83 | 84 | // Bintray 85 | Properties properties = new Properties() 86 | properties.load(project.rootProject.file('local.properties').newDataInputStream()) 87 | 88 | bintray { 89 | user = properties.getProperty("bintray.user") 90 | key = properties.getProperty("bintray.apikey") 91 | 92 | configurations = ['archives'] 93 | pkg { 94 | repo = bintrayRepo 95 | name = bintrayName 96 | userOrg = properties.getProperty("bintray.userOrg") 97 | desc = libraryDescription 98 | websiteUrl = siteUrl 99 | issueTrackerUrl = issuesUrl 100 | vcsUrl = gitUrl 101 | licenses = allLicenses 102 | publish = true 103 | publicDownloadNumbers = true 104 | version { 105 | desc = libraryDescription 106 | gpg { 107 | sign = true //Determines whether to GPG sign the files. The default is false 108 | passphrase = properties.getProperty("bintray.gpg.password") 109 | //Optional. The passphrase for GPG signing' 110 | } 111 | } 112 | } 113 | } 114 | 115 | if (JavaVersion.current().isJava8Compatible()) { 116 | allprojects { 117 | tasks.withType(Javadoc) { 118 | options.addStringOption('Xdoclint:none', '-quiet') 119 | } 120 | } 121 | } 122 | */ -------------------------------------------------------------------------------- /ble/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/ConnectionPriorityRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Build; 27 | 28 | import androidx.annotation.IntRange; 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.RequiresApi; 31 | import no.nordicsemi.android.ble.annotation.ConnectionPriority; 32 | import no.nordicsemi.android.ble.callback.BeforeCallback; 33 | import no.nordicsemi.android.ble.callback.ConnectionPriorityCallback; 34 | import no.nordicsemi.android.ble.callback.FailCallback; 35 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 36 | import no.nordicsemi.android.ble.callback.SuccessCallback; 37 | import no.nordicsemi.android.ble.exception.BluetoothDisabledException; 38 | import no.nordicsemi.android.ble.exception.DeviceDisconnectedException; 39 | import no.nordicsemi.android.ble.exception.InvalidRequestException; 40 | import no.nordicsemi.android.ble.exception.RequestFailedException; 41 | 42 | @SuppressWarnings({"unused"}) 43 | public final class ConnectionPriorityRequest extends SimpleValueRequest 44 | implements Operation { 45 | 46 | /** 47 | * Connection parameter update - Use the connection parameters recommended by the 48 | * Bluetooth SIG. This is the default value if no connection parameter update 49 | * is requested. 50 | *

51 | * Interval: 30 - 50 ms, latency: 0, supervision timeout: 20 sec. 52 | */ 53 | public static final int CONNECTION_PRIORITY_BALANCED = 0; 54 | 55 | /** 56 | * Connection parameter update - Request a high priority, low latency connection. 57 | * An application should only request high priority connection parameters to transfer 58 | * large amounts of data over LE quickly. Once the transfer is complete, the application 59 | * should request {@link #CONNECTION_PRIORITY_BALANCED} connection parameters 60 | * to reduce energy use. 61 | *

62 | * Interval: 11.25 - 15 ms (Android 6+) or 7.5 - 10 ms (Android 4.3 - 5.1), 63 | * latency: 0, supervision timeout: 20 sec. 64 | */ 65 | public static final int CONNECTION_PRIORITY_HIGH = 1; 66 | 67 | /** 68 | * Connection parameter update - Request low power, reduced data rate connection parameters. 69 | *

70 | * Interval: 100 - 125 ms, latency: 2, supervision timeout: 20 sec. 71 | */ 72 | public static final int CONNECTION_PRIORITY_LOW_POWER = 2; 73 | 74 | private final int value; 75 | 76 | ConnectionPriorityRequest(@NonNull final Type type, @ConnectionPriority int priority) { 77 | super(type); 78 | if (priority < 0 || priority > 2) 79 | priority = CONNECTION_PRIORITY_BALANCED; 80 | this.value = priority; 81 | } 82 | 83 | @NonNull 84 | @Override 85 | ConnectionPriorityRequest setManager(@NonNull final BleManager manager) { 86 | super.setManager(manager); 87 | return this; 88 | } 89 | 90 | @Override 91 | @NonNull 92 | public ConnectionPriorityRequest done(@NonNull final SuccessCallback callback) { 93 | super.done(callback); 94 | return this; 95 | } 96 | 97 | @Override 98 | @NonNull 99 | public ConnectionPriorityRequest fail(@NonNull final FailCallback callback) { 100 | super.fail(callback); 101 | return this; 102 | } 103 | 104 | @NonNull 105 | @Override 106 | public ConnectionPriorityRequest invalid(@NonNull final InvalidRequestCallback callback) { 107 | super.invalid(callback); 108 | return this; 109 | } 110 | 111 | @Override 112 | @NonNull 113 | public ConnectionPriorityRequest before(@NonNull final BeforeCallback callback) { 114 | super.before(callback); 115 | return this; 116 | } 117 | 118 | @RequiresApi(value = Build.VERSION_CODES.O) 119 | @Override 120 | @NonNull 121 | public ConnectionPriorityRequest with(@NonNull final ConnectionPriorityCallback callback) { 122 | // The BluetoothGattCallback#onConnectionUpdated callback was introduced in Android Oreo. 123 | super.with(callback); 124 | return this; 125 | } 126 | 127 | @RequiresApi(value = Build.VERSION_CODES.O) 128 | @NonNull 129 | @Override 130 | public E await(@NonNull final Class responseClass) 131 | throws RequestFailedException, DeviceDisconnectedException, BluetoothDisabledException, 132 | InvalidRequestException { 133 | // The BluetoothGattCallback#onConnectionUpdated callback was introduced in Android Oreo. 134 | return super.await(responseClass); 135 | } 136 | 137 | @RequiresApi(value = Build.VERSION_CODES.O) 138 | @NonNull 139 | @Override 140 | public E await(@NonNull final E response) 141 | throws RequestFailedException, DeviceDisconnectedException, BluetoothDisabledException, 142 | InvalidRequestException { 143 | // The BluetoothGattCallback#onConnectionUpdated callback was introduced in Android Oreo. 144 | return super.await(response); 145 | } 146 | 147 | @RequiresApi(api = Build.VERSION_CODES.O) 148 | void notifyConnectionPriorityChanged(@NonNull final BluetoothDevice device, 149 | @IntRange(from = 6, to = 3200) final int interval, 150 | @IntRange(from = 0, to = 499) final int latency, 151 | @IntRange(from = 10, to = 3200) final int timeout) { 152 | if (valueCallback != null) 153 | valueCallback.onConnectionUpdated(device, interval, latency, timeout); 154 | } 155 | 156 | @ConnectionPriority 157 | int getRequiredPriority() { 158 | return value; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/DisconnectRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import androidx.annotation.IntRange; 26 | import androidx.annotation.NonNull; 27 | import no.nordicsemi.android.ble.callback.BeforeCallback; 28 | import no.nordicsemi.android.ble.callback.FailCallback; 29 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 30 | import no.nordicsemi.android.ble.callback.SuccessCallback; 31 | 32 | @SuppressWarnings({"unused"}) 33 | public class DisconnectRequest extends TimeoutableRequest { 34 | 35 | DisconnectRequest(@NonNull final Type type) { 36 | super(type); 37 | } 38 | 39 | @NonNull 40 | @Override 41 | DisconnectRequest setManager(@NonNull final BleManager manager) { 42 | super.setManager(manager); 43 | return this; 44 | } 45 | 46 | @NonNull 47 | @Override 48 | public DisconnectRequest timeout(@IntRange(from = 0) final long timeout) { 49 | super.timeout(timeout); 50 | return this; 51 | } 52 | 53 | @NonNull 54 | @Override 55 | public DisconnectRequest done(@NonNull final SuccessCallback callback) { 56 | super.done(callback); 57 | return this; 58 | } 59 | 60 | @NonNull 61 | @Override 62 | public DisconnectRequest fail(@NonNull final FailCallback callback) { 63 | super.fail(callback); 64 | return this; 65 | } 66 | 67 | @NonNull 68 | @Override 69 | public DisconnectRequest invalid(@NonNull final InvalidRequestCallback callback) { 70 | super.invalid(callback); 71 | return this; 72 | } 73 | 74 | @Override 75 | @NonNull 76 | public DisconnectRequest before(@NonNull final BeforeCallback callback) { 77 | super.before(callback); 78 | return this; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/MtuRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | import no.nordicsemi.android.ble.callback.BeforeCallback; 30 | import no.nordicsemi.android.ble.callback.FailCallback; 31 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 32 | import no.nordicsemi.android.ble.callback.MtuCallback; 33 | import no.nordicsemi.android.ble.callback.SuccessCallback; 34 | 35 | public final class MtuRequest extends SimpleValueRequestimplements Operation { 36 | private final int value; 37 | 38 | MtuRequest(@NonNull final Type type, @IntRange(from = 23, to = 517) int mtu) { 39 | super(type); 40 | if (mtu < 23) 41 | mtu = 23; 42 | if (mtu > 517) 43 | mtu = 517; 44 | this.value = mtu; 45 | } 46 | 47 | @NonNull 48 | @Override 49 | MtuRequest setManager(@NonNull final BleManager manager) { 50 | super.setManager(manager); 51 | return this; 52 | } 53 | 54 | @Override 55 | @NonNull 56 | public MtuRequest done(@NonNull final SuccessCallback callback) { 57 | super.done(callback); 58 | return this; 59 | } 60 | 61 | @Override 62 | @NonNull 63 | public MtuRequest fail(@NonNull final FailCallback callback) { 64 | super.fail(callback); 65 | return this; 66 | } 67 | 68 | @NonNull 69 | @Override 70 | public MtuRequest invalid(@NonNull final InvalidRequestCallback callback) { 71 | super.invalid(callback); 72 | return this; 73 | } 74 | 75 | @Override 76 | @NonNull 77 | public MtuRequest before(@NonNull final BeforeCallback callback) { 78 | super.before(callback); 79 | return this; 80 | } 81 | 82 | @Override 83 | @NonNull 84 | public MtuRequest with(@NonNull final MtuCallback callback) { 85 | super.with(callback); 86 | return this; 87 | } 88 | 89 | void notifyMtuChanged(@NonNull final BluetoothDevice device, 90 | @IntRange(from = 23, to = 517) final int mtu) { 91 | handler.post(() -> { 92 | if (valueCallback != null) 93 | valueCallback.onMtuChanged(device, mtu); 94 | }); 95 | } 96 | 97 | int getRequiredMtu() { 98 | return value; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/Operation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | /** 26 | * An operation is a request that can be executed during a pending connection without 27 | * changing connection state. Such requests may be added to {@link RequestQueue}. 28 | */ 29 | public interface Operation { 30 | // empty 31 | } 32 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/PhyRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | import no.nordicsemi.android.ble.annotation.PhyMask; 29 | import no.nordicsemi.android.ble.annotation.PhyOption; 30 | import no.nordicsemi.android.ble.annotation.PhyValue; 31 | import no.nordicsemi.android.ble.callback.BeforeCallback; 32 | import no.nordicsemi.android.ble.callback.FailCallback; 33 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 34 | import no.nordicsemi.android.ble.callback.PhyCallback; 35 | import no.nordicsemi.android.ble.callback.SuccessCallback; 36 | 37 | @SuppressWarnings({"unused"}) 38 | public final class PhyRequest extends SimpleValueRequest implements Operation { 39 | 40 | /** 41 | * Bluetooth LE 1M PHY mask. Used to specify LE 1M Physical Channel as one of many available 42 | * options in a bitmask. 43 | */ 44 | public static final int PHY_LE_1M_MASK = 1; 45 | 46 | /** 47 | * Bluetooth LE 2M PHY mask. Used to specify LE 2M Physical Channel as one of many available 48 | * options in a bitmask. 49 | */ 50 | public static final int PHY_LE_2M_MASK = 2; 51 | 52 | /** 53 | * Bluetooth LE Coded PHY mask. Used to specify LE Coded Physical Channel as one of many 54 | * available options in a bitmask. 55 | */ 56 | public static final int PHY_LE_CODED_MASK = 4; 57 | 58 | /** 59 | * No preferred coding when transmitting on the LE Coded PHY. 60 | */ 61 | public static final int PHY_OPTION_NO_PREFERRED = 0; 62 | 63 | /** 64 | * Prefer the S=2 coding to be used when transmitting on the LE Coded PHY. 65 | */ 66 | public static final int PHY_OPTION_S2 = 1; 67 | 68 | /** 69 | * Prefer the S=8 coding to be used when transmitting on the LE Coded PHY. 70 | */ 71 | public static final int PHY_OPTION_S8 = 2; 72 | 73 | private final int txPhy; 74 | private final int rxPhy; 75 | private final int phyOptions; 76 | 77 | PhyRequest(@NonNull final Type type) { 78 | super(type); 79 | this.txPhy = 0; 80 | this.rxPhy = 0; 81 | this.phyOptions = 0; 82 | } 83 | 84 | PhyRequest(@NonNull final Type type, 85 | @PhyMask int txPhy, @PhyMask int rxPhy, @PhyOption int phyOptions) { 86 | super(type); 87 | if ((txPhy & ~(PHY_LE_1M_MASK | PHY_LE_2M_MASK | PHY_LE_CODED_MASK)) > 0) 88 | txPhy = PHY_LE_1M_MASK; 89 | if ((rxPhy & ~(PHY_LE_1M_MASK | PHY_LE_2M_MASK | PHY_LE_CODED_MASK)) > 0) 90 | rxPhy = PHY_LE_1M_MASK; 91 | if (phyOptions < PHY_OPTION_NO_PREFERRED || phyOptions > PHY_OPTION_S8) 92 | phyOptions = PHY_OPTION_NO_PREFERRED; 93 | this.txPhy = txPhy; 94 | this.rxPhy = rxPhy; 95 | this.phyOptions = phyOptions; 96 | } 97 | 98 | @NonNull 99 | @Override 100 | PhyRequest setManager(@NonNull final BleManager manager) { 101 | super.setManager(manager); 102 | return this; 103 | } 104 | 105 | @Override 106 | @NonNull 107 | public PhyRequest done(@NonNull final SuccessCallback callback) { 108 | super.done(callback); 109 | return this; 110 | } 111 | 112 | @Override 113 | @NonNull 114 | public PhyRequest fail(@NonNull final FailCallback callback) { 115 | super.fail(callback); 116 | return this; 117 | } 118 | 119 | @NonNull 120 | @Override 121 | public PhyRequest invalid(@NonNull final InvalidRequestCallback callback) { 122 | super.invalid(callback); 123 | return this; 124 | } 125 | 126 | @Override 127 | @NonNull 128 | public PhyRequest before(@NonNull final BeforeCallback callback) { 129 | super.before(callback); 130 | return this; 131 | } 132 | 133 | @Override 134 | @NonNull 135 | public PhyRequest with(@NonNull final PhyCallback callback) { 136 | super.with(callback); 137 | return this; 138 | } 139 | 140 | void notifyPhyChanged(@NonNull final BluetoothDevice device, 141 | @PhyValue final int txPhy, @PhyValue final int rxPhy) { 142 | handler.post(() -> { 143 | if (valueCallback != null) 144 | valueCallback.onPhyChanged(device, txPhy, rxPhy); 145 | }); 146 | } 147 | 148 | void notifyLegacyPhy(@NonNull final BluetoothDevice device) { 149 | handler.post(() -> { 150 | if (valueCallback != null) 151 | valueCallback.onPhyChanged(device, PhyCallback.PHY_LE_1M, PhyCallback.PHY_LE_1M); 152 | }); 153 | } 154 | 155 | @PhyMask 156 | int getPreferredTxPhy() { 157 | return txPhy; 158 | } 159 | 160 | @PhyMask 161 | int getPreferredRxPhy() { 162 | return rxPhy; 163 | } 164 | 165 | @PhyOption 166 | int getPreferredPhyOptions() { 167 | return phyOptions; 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/ReadRssiRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | import no.nordicsemi.android.ble.callback.BeforeCallback; 30 | import no.nordicsemi.android.ble.callback.FailCallback; 31 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 32 | import no.nordicsemi.android.ble.callback.RssiCallback; 33 | import no.nordicsemi.android.ble.callback.SuccessCallback; 34 | 35 | public final class ReadRssiRequest extends SimpleValueRequest implements Operation { 36 | 37 | ReadRssiRequest(@NonNull final Type type) { 38 | super(type); 39 | } 40 | 41 | @NonNull 42 | @Override 43 | ReadRssiRequest setManager(@NonNull final BleManager manager) { 44 | super.setManager(manager); 45 | return this; 46 | } 47 | 48 | @Override 49 | @NonNull 50 | public ReadRssiRequest done(@NonNull final SuccessCallback callback) { 51 | super.done(callback); 52 | return this; 53 | } 54 | 55 | @Override 56 | @NonNull 57 | public ReadRssiRequest fail(@NonNull final FailCallback callback) { 58 | super.fail(callback); 59 | return this; 60 | } 61 | 62 | @NonNull 63 | @Override 64 | public ReadRssiRequest invalid(@NonNull final InvalidRequestCallback callback) { 65 | super.invalid(callback); 66 | return this; 67 | } 68 | 69 | @Override 70 | @NonNull 71 | public ReadRssiRequest before(@NonNull final BeforeCallback callback) { 72 | super.before(callback); 73 | return this; 74 | } 75 | 76 | @Override 77 | @NonNull 78 | public ReadRssiRequest with(@NonNull final RssiCallback callback) { 79 | super.with(callback); 80 | return this; 81 | } 82 | 83 | void notifyRssiRead(@NonNull final BluetoothDevice device, 84 | @IntRange(from = -128, to = 20) final int rssi) { 85 | handler.post(() -> { 86 | if (valueCallback != null) 87 | valueCallback.onRssiRead(device, rssi); 88 | }); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/ReliableWriteRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import androidx.annotation.NonNull; 26 | import no.nordicsemi.android.ble.callback.BeforeCallback; 27 | import no.nordicsemi.android.ble.callback.FailCallback; 28 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 29 | import no.nordicsemi.android.ble.callback.SuccessCallback; 30 | 31 | @SuppressWarnings("unused") 32 | public final class ReliableWriteRequest extends RequestQueue { 33 | private boolean initialized; 34 | private boolean closed; 35 | private boolean cancelled; 36 | 37 | @NonNull 38 | @Override 39 | ReliableWriteRequest setManager(@NonNull final BleManager manager) { 40 | super.setManager(manager); 41 | return this; 42 | } 43 | 44 | @Override 45 | @NonNull 46 | public ReliableWriteRequest done(@NonNull final SuccessCallback callback) { 47 | super.done(callback); 48 | return this; 49 | } 50 | 51 | @Override 52 | @NonNull 53 | public ReliableWriteRequest fail(@NonNull final FailCallback callback) { 54 | super.fail(callback); 55 | return this; 56 | } 57 | 58 | @NonNull 59 | @Override 60 | public ReliableWriteRequest invalid(@NonNull final InvalidRequestCallback callback) { 61 | super.invalid(callback); 62 | return this; 63 | } 64 | 65 | @Override 66 | @NonNull 67 | public ReliableWriteRequest before(@NonNull final BeforeCallback callback) { 68 | super.before(callback); 69 | return this; 70 | } 71 | 72 | @NonNull 73 | @Override 74 | public ReliableWriteRequest add(@NonNull final Operation operation) { 75 | super.add(operation); 76 | // Make sure the write request uses splitting, as Long Write is not supported 77 | // in Reliable Write sub-procedure. 78 | if (operation instanceof WriteRequest) { 79 | ((WriteRequest) operation).forceSplit(); 80 | } 81 | return this; 82 | } 83 | 84 | @Override 85 | public void cancelQueue() { 86 | cancelled = true; 87 | super.cancelQueue(); 88 | } 89 | 90 | /** 91 | * Alias for {@link #cancelQueue()}. 92 | */ 93 | public void abort() { 94 | cancelQueue(); 95 | } 96 | 97 | @Override 98 | public int size() { 99 | int size = super.size(); 100 | 101 | // Add Begin Reliable Write 102 | if (!initialized) 103 | size += 1; 104 | 105 | // Add Execute or Abort Reliable Write 106 | if (!closed) 107 | size += 1; 108 | return size; 109 | } 110 | 111 | @Override 112 | Request getNext() { 113 | if (!initialized) { 114 | initialized = true; 115 | return newBeginReliableWriteRequest(); 116 | } 117 | if (super.isEmpty()) { 118 | closed = true; 119 | 120 | if (cancelled) 121 | return newAbortReliableWriteRequest(); 122 | return newExecuteReliableWriteRequest(); 123 | } 124 | return super.getNext(); 125 | } 126 | 127 | @Override 128 | boolean hasMore() { 129 | // If no operations were added, consider the RW request empty, no requests will be executed. 130 | if (!initialized) 131 | return super.hasMore(); 132 | return !closed; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/RequestQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import java.util.LinkedList; 26 | import java.util.Queue; 27 | 28 | import androidx.annotation.IntRange; 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.Nullable; 31 | import no.nordicsemi.android.ble.callback.BeforeCallback; 32 | import no.nordicsemi.android.ble.callback.FailCallback; 33 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 34 | import no.nordicsemi.android.ble.callback.SuccessCallback; 35 | 36 | @SuppressWarnings("WeakerAccess") 37 | public class RequestQueue extends SimpleRequest { 38 | /** 39 | * A list of operations that will be executed together. 40 | */ 41 | @NonNull 42 | private final Queue requests; 43 | 44 | RequestQueue() { 45 | super(Type.SET); 46 | requests = new LinkedList<>(); 47 | } 48 | 49 | @NonNull 50 | @Override 51 | RequestQueue setManager(@NonNull final BleManager manager) { 52 | super.setManager(manager); 53 | return this; 54 | } 55 | 56 | @Override 57 | @NonNull 58 | public RequestQueue done(@NonNull final SuccessCallback callback) { 59 | super.done(callback); 60 | return this; 61 | } 62 | 63 | @Override 64 | @NonNull 65 | public RequestQueue fail(@NonNull final FailCallback callback) { 66 | super.fail(callback); 67 | return this; 68 | } 69 | 70 | @NonNull 71 | @Override 72 | public RequestQueue invalid(@NonNull final InvalidRequestCallback callback) { 73 | super.invalid(callback); 74 | return this; 75 | } 76 | 77 | @Override 78 | @NonNull 79 | public RequestQueue before(@NonNull final BeforeCallback callback) { 80 | super.before(callback); 81 | return this; 82 | } 83 | 84 | /** 85 | * Enqueues a new operation. All operations will be executed sequentially in order they were 86 | * added. 87 | * 88 | * @param operation the new operation to be enqueued. 89 | * @throws IllegalStateException if the operation was enqueued before. 90 | * @throws IllegalArgumentException if the operation is not a {@link Request}. 91 | */ 92 | @NonNull 93 | public RequestQueue add(@NonNull final Operation operation) { 94 | if (operation instanceof Request) { 95 | final Request request = (Request) operation; 96 | // Validate 97 | if (request.enqueued) 98 | throw new IllegalStateException("Request already enqueued"); 99 | // Add 100 | requests.add(request); 101 | // Mark 102 | request.enqueued = true; 103 | return this; 104 | } else { 105 | throw new IllegalArgumentException("Operation does not extend Request"); 106 | } 107 | } 108 | 109 | /** 110 | * Returns number of enqueued operations. 111 | * 112 | * @return the size of the internal operations list. 113 | */ 114 | @IntRange(from = 0) 115 | public int size() { 116 | return requests.size(); 117 | } 118 | 119 | /** 120 | * Returns whether the set is empty, or not. 121 | * 122 | * @return true if the set is empty. Set gets emptied while it all enqueued operations 123 | * are being executed. 124 | */ 125 | public boolean isEmpty() { 126 | return requests.isEmpty(); 127 | } 128 | 129 | /** 130 | * Cancels all the enqueued operations that were not executed yet. 131 | * The one currently executed will be finished. 132 | *

133 | * It is safe to call this method in {@link Request#done(SuccessCallback)} or 134 | * {@link Request#fail(FailCallback)} callback; 135 | */ 136 | public void cancelQueue() { 137 | requests.clear(); 138 | } 139 | 140 | /** 141 | * Returns the next {@link Request} to be enqueued. 142 | * 143 | * @return the next request. 144 | */ 145 | @Nullable 146 | Request getNext() { 147 | try { 148 | return requests.remove(); 149 | // poll() may also throw an exception 150 | // See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/37 151 | } catch (final Exception e) { 152 | return null; 153 | } 154 | } 155 | 156 | /** 157 | * Returns whether there are more operations to be executed. 158 | * 159 | * @return true, if not all operations were completed. 160 | */ 161 | boolean hasMore() { 162 | return !requests.isEmpty(); 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/SimpleRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothGatt; 26 | import android.bluetooth.BluetoothGattCharacteristic; 27 | import android.bluetooth.BluetoothGattDescriptor; 28 | 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.Nullable; 31 | import no.nordicsemi.android.ble.callback.FailCallback; 32 | import no.nordicsemi.android.ble.callback.SuccessCallback; 33 | import no.nordicsemi.android.ble.exception.BluetoothDisabledException; 34 | import no.nordicsemi.android.ble.exception.DeviceDisconnectedException; 35 | import no.nordicsemi.android.ble.exception.InvalidRequestException; 36 | import no.nordicsemi.android.ble.exception.RequestFailedException; 37 | 38 | /** 39 | * A request that requires a {@link android.bluetooth.BluetoothGattCallback callback} or can't 40 | * have timeout for any other reason. This class defines the {@link #await()} method. 41 | */ 42 | @SuppressWarnings({"WeakerAccess", "unused"}) 43 | public class SimpleRequest extends Request { 44 | 45 | SimpleRequest(@NonNull final Type type) { 46 | super(type); 47 | } 48 | 49 | SimpleRequest(@NonNull final Type type, 50 | @Nullable final BluetoothGattCharacteristic characteristic) { 51 | super(type, characteristic); 52 | } 53 | 54 | SimpleRequest(@NonNull final Type type, 55 | @Nullable final BluetoothGattDescriptor descriptor) { 56 | super(type, descriptor); 57 | } 58 | 59 | /** 60 | * Synchronously waits until the request is done. 61 | *

62 | * Callbacks set using {@link #done(SuccessCallback)} and {@link #fail(FailCallback)} 63 | * will be ignored. 64 | *

65 | * This method may not be called from the main (UI) thread. 66 | * 67 | * @throws RequestFailedException thrown when the BLE request finished with status other 68 | * than {@link BluetoothGatt#GATT_SUCCESS}. 69 | * @throws IllegalStateException thrown when you try to call this method from the main 70 | * (UI) thread. 71 | * @throws DeviceDisconnectedException thrown when the device disconnected before the request 72 | * was completed. 73 | * @throws BluetoothDisabledException thrown when the Bluetooth adapter has been disabled. 74 | * @throws InvalidRequestException thrown when the request was called before the device was 75 | * connected at least once (unknown device). 76 | */ 77 | public final void await() throws RequestFailedException, DeviceDisconnectedException, 78 | BluetoothDisabledException, InvalidRequestException { 79 | assertNotMainThread(); 80 | 81 | final SuccessCallback sc = successCallback; 82 | final FailCallback fc = failCallback; 83 | try { 84 | syncLock.close(); 85 | final RequestCallback callback = new RequestCallback(); 86 | done(callback).fail(callback).invalid(callback).enqueue(); 87 | 88 | syncLock.block(); 89 | if (!callback.isSuccess()) { 90 | if (callback.status == FailCallback.REASON_DEVICE_DISCONNECTED) { 91 | throw new DeviceDisconnectedException(); 92 | } 93 | if (callback.status == FailCallback.REASON_BLUETOOTH_DISABLED) { 94 | throw new BluetoothDisabledException(); 95 | } 96 | if (callback.status == RequestCallback.REASON_REQUEST_INVALID) { 97 | throw new InvalidRequestException(this); 98 | } 99 | throw new RequestFailedException(this, callback.status); 100 | } 101 | } finally { 102 | successCallback = sc; 103 | failCallback = fc; 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/SimpleValueRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothGattCharacteristic; 26 | import android.bluetooth.BluetoothGattDescriptor; 27 | 28 | import androidx.annotation.NonNull; 29 | import androidx.annotation.Nullable; 30 | import no.nordicsemi.android.ble.callback.FailCallback; 31 | import no.nordicsemi.android.ble.callback.SuccessCallback; 32 | import no.nordicsemi.android.ble.exception.BluetoothDisabledException; 33 | import no.nordicsemi.android.ble.exception.DeviceDisconnectedException; 34 | import no.nordicsemi.android.ble.exception.InvalidRequestException; 35 | import no.nordicsemi.android.ble.exception.RequestFailedException; 36 | 37 | /** 38 | * A value request that requires a {@link android.bluetooth.BluetoothGattCallback callback} or 39 | * can't have timeout for any other reason. This class defines the {@link #await()} methods. 40 | */ 41 | @SuppressWarnings({"WeakerAccess", "unused"}) 42 | public abstract class SimpleValueRequest extends SimpleRequest { 43 | T valueCallback; 44 | 45 | SimpleValueRequest(@NonNull final Type type) { 46 | super(type); 47 | } 48 | 49 | SimpleValueRequest(@NonNull final Type type, 50 | @Nullable final BluetoothGattCharacteristic characteristic) { 51 | super(type, characteristic); 52 | } 53 | 54 | SimpleValueRequest(@NonNull final Type type, 55 | @Nullable final BluetoothGattDescriptor descriptor) { 56 | super(type, descriptor); 57 | } 58 | 59 | /** 60 | * Sets the value callback. When the request is invoked synchronously, this callback will 61 | * be ignored and the received value will be returned by the await(...) method; 62 | * 63 | * @param callback the callback. 64 | * @return The request. 65 | */ 66 | @NonNull 67 | public SimpleValueRequest with(@NonNull final T callback) { 68 | this.valueCallback = callback; 69 | return this; 70 | } 71 | 72 | /** 73 | * Synchronously waits until the request is done. The given response object will be filled 74 | * with the request response. 75 | *

76 | * Callbacks set using {@link #done(SuccessCallback)} and {@link #fail(FailCallback)} and 77 | * {@link #with(T)} will be ignored. 78 | *

79 | * This method may not be called from the main (UI) thread. 80 | * 81 | * @param response the response object. 82 | * @param a response class. 83 | * @return The response with a response. 84 | * @throws RequestFailedException thrown when the BLE request finished with status other 85 | * than {@link android.bluetooth.BluetoothGatt#GATT_SUCCESS}. 86 | * @throws IllegalStateException thrown when you try to call this method from the main 87 | * (UI) thread. 88 | * @throws DeviceDisconnectedException thrown when the device disconnected before the request 89 | * was completed. 90 | * @throws BluetoothDisabledException thrown when the Bluetooth adapter is disabled. 91 | * @throws InvalidRequestException thrown when the request was called before the device was 92 | * connected at least once (unknown device). 93 | * @see #await(Class) 94 | */ 95 | @NonNull 96 | public E await(@NonNull final E response) 97 | throws RequestFailedException, DeviceDisconnectedException, BluetoothDisabledException, 98 | InvalidRequestException { 99 | assertNotMainThread(); 100 | 101 | final T vc = valueCallback; 102 | try { 103 | with(response).await(); 104 | return response; 105 | } finally { 106 | valueCallback = vc; 107 | } 108 | } 109 | 110 | /** 111 | * Synchronously waits until the request is done. 112 | *

113 | * Callbacks set using {@link #done(SuccessCallback)} and {@link #fail(FailCallback)} and 114 | * {@link #with(T)} will be ignored. 115 | *

116 | * This method may not be called from the main (UI) thread. 117 | * 118 | * @param responseClass the response class. This class will be instantiate, therefore it has 119 | * to have a default constructor. 120 | * @return The response with a response. 121 | * @throws RequestFailedException thrown when the BLE request finished with status other 122 | * than {@link android.bluetooth.BluetoothGatt#GATT_SUCCESS}. 123 | * @throws IllegalStateException thrown when you try to call this method from the main 124 | * (UI) thread. 125 | * @throws IllegalArgumentException thrown when the response class could not be instantiated. 126 | * @throws DeviceDisconnectedException thrown when the device disconnected before the request 127 | * was completed. 128 | * @throws BluetoothDisabledException thrown when the Bluetooth adapter is disabled. 129 | * @throws InvalidRequestException thrown when the request was called before the device was 130 | * connected at least once (unknown device). 131 | * @see #await(Object) 132 | */ 133 | @NonNull 134 | public E await(@NonNull final Class responseClass) 135 | throws RequestFailedException, DeviceDisconnectedException, BluetoothDisabledException, 136 | InvalidRequestException { 137 | assertNotMainThread(); 138 | 139 | try { 140 | final E response = responseClass.newInstance(); 141 | return await(response); 142 | } catch (IllegalAccessException e) { 143 | throw new IllegalArgumentException("Couldn't instantiate " 144 | + responseClass.getCanonicalName() 145 | + " class. Is the default constructor accessible?"); 146 | } catch (InstantiationException e) { 147 | throw new IllegalArgumentException("Couldn't instantiate " 148 | + responseClass.getCanonicalName() 149 | + " class. Does it have a default constructor with no arguments?"); 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/SleepRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import androidx.annotation.IntRange; 26 | import androidx.annotation.NonNull; 27 | import no.nordicsemi.android.ble.callback.BeforeCallback; 28 | import no.nordicsemi.android.ble.callback.FailCallback; 29 | import no.nordicsemi.android.ble.callback.InvalidRequestCallback; 30 | import no.nordicsemi.android.ble.callback.SuccessCallback; 31 | 32 | @SuppressWarnings({"unused", "WeakerAccess"}) 33 | public final class SleepRequest extends SimpleRequest implements Operation { 34 | private long delay; 35 | 36 | SleepRequest(@NonNull final Type type, @IntRange(from = 0) final long delay) { 37 | super(type); 38 | this.delay = delay; 39 | } 40 | 41 | @NonNull 42 | @Override 43 | SleepRequest setManager(@NonNull final BleManager manager) { 44 | super.setManager(manager); 45 | return this; 46 | } 47 | 48 | @NonNull 49 | @Override 50 | public SleepRequest done(@NonNull final SuccessCallback callback) { 51 | super.done(callback); 52 | return this; 53 | } 54 | 55 | @NonNull 56 | @Override 57 | public SleepRequest fail(@NonNull final FailCallback callback) { 58 | super.fail(callback); 59 | return this; 60 | } 61 | 62 | @NonNull 63 | @Override 64 | public SleepRequest invalid(@NonNull final InvalidRequestCallback callback) { 65 | super.invalid(callback); 66 | return this; 67 | } 68 | 69 | @NonNull 70 | @Override 71 | public SleepRequest before(@NonNull final BeforeCallback callback) { 72 | super.before(callback); 73 | return this; 74 | } 75 | 76 | long getDelay() { 77 | return delay; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/TimeoutHandler.java: -------------------------------------------------------------------------------- 1 | package no.nordicsemi.android.ble; 2 | 3 | import androidx.annotation.NonNull; 4 | 5 | abstract class TimeoutHandler { 6 | 7 | /** 8 | * Method called when the request timed out. 9 | * 10 | * @param request the request that timed out. 11 | */ 12 | abstract void onRequestTimeout(@NonNull final TimeoutableRequest request); 13 | } 14 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/TimeoutableRequest.java: -------------------------------------------------------------------------------- 1 | package no.nordicsemi.android.ble; 2 | 3 | import android.bluetooth.BluetoothDevice; 4 | import android.bluetooth.BluetoothGatt; 5 | import android.bluetooth.BluetoothGattCharacteristic; 6 | import android.bluetooth.BluetoothGattDescriptor; 7 | 8 | import androidx.annotation.IntRange; 9 | import androidx.annotation.NonNull; 10 | import androidx.annotation.Nullable; 11 | import no.nordicsemi.android.ble.callback.FailCallback; 12 | import no.nordicsemi.android.ble.callback.SuccessCallback; 13 | import no.nordicsemi.android.ble.exception.BluetoothDisabledException; 14 | import no.nordicsemi.android.ble.exception.DeviceDisconnectedException; 15 | import no.nordicsemi.android.ble.exception.InvalidRequestException; 16 | import no.nordicsemi.android.ble.exception.RequestFailedException; 17 | 18 | @SuppressWarnings("WeakerAccess") 19 | public abstract class TimeoutableRequest extends Request { 20 | private TimeoutHandler timeoutHandler; 21 | private Runnable timeoutCallback; 22 | protected long timeout; 23 | 24 | TimeoutableRequest(@NonNull final Type type) { 25 | super(type); 26 | } 27 | 28 | TimeoutableRequest(@NonNull final Type type, @Nullable final BluetoothGattCharacteristic characteristic) { 29 | super(type, characteristic); 30 | } 31 | 32 | TimeoutableRequest(@NonNull final Type type, @Nullable final BluetoothGattDescriptor descriptor) { 33 | super(type, descriptor); 34 | } 35 | 36 | @NonNull 37 | @Override 38 | TimeoutableRequest setManager(@NonNull final BleManager manager) { 39 | super.setManager(manager); 40 | this.timeoutHandler = manager; 41 | return this; 42 | } 43 | 44 | /** 45 | * Sets the operation timeout. 46 | * When the timeout occurs, the request will fail with {@link FailCallback#REASON_TIMEOUT}. 47 | * 48 | * @param timeout the request timeout in milliseconds, 0 to disable timeout. 49 | * @return the callback. 50 | * @throws IllegalStateException thrown when the request has already been started. 51 | * @throws UnsupportedOperationException thrown when the timeout is not allowed for this request, 52 | * as the callback from the system is required. 53 | */ 54 | @NonNull 55 | public TimeoutableRequest timeout(@IntRange(from = 0) final long timeout) { 56 | if (timeoutCallback != null) 57 | throw new IllegalStateException("Request already started"); 58 | this.timeout = timeout; 59 | return this; 60 | } 61 | 62 | /** 63 | * Enqueues the request for asynchronous execution. 64 | *

65 | * Use {@link #timeout(long)} to set the maximum time the manager should wait until the device 66 | * is ready. When the timeout occurs, the request will fail with 67 | * {@link FailCallback#REASON_TIMEOUT} and the device will get disconnected. 68 | */ 69 | @Override 70 | public final void enqueue() { 71 | super.enqueue(); 72 | } 73 | 74 | /** 75 | * Enqueues the request for asynchronous execution. 76 | *

77 | * When the timeout occurs, the request will fail with {@link FailCallback#REASON_TIMEOUT} 78 | * and the device will get disconnected. 79 | * 80 | * @param timeout the request timeout in milliseconds, 0 to disable timeout. This value will 81 | * override one set in {@link #timeout(long)}. 82 | * @deprecated Use {@link #timeout(long)} and {@link #enqueue()} instead. 83 | */ 84 | @Deprecated 85 | public final void enqueue(@IntRange(from = 0) final long timeout) { 86 | timeout(timeout).enqueue(); 87 | } 88 | 89 | /** 90 | * Synchronously waits until the request is done. 91 | *

92 | * Use {@link #timeout(long)} to set the maximum time the manager should wait until the request 93 | * is ready. When the timeout occurs, the {@link InterruptedException} will be thrown. 94 | *

95 | * Callbacks set using {@link #done(SuccessCallback)} and {@link #fail(FailCallback)} 96 | * will be ignored. 97 | *

98 | * This method may not be called from the main (UI) thread. 99 | * 100 | * @throws RequestFailedException thrown when the BLE request finished with status other 101 | * than {@link BluetoothGatt#GATT_SUCCESS}. 102 | * @throws InterruptedException thrown if the timeout occurred before the request has 103 | * finished. 104 | * @throws IllegalStateException thrown when you try to call this method from the main 105 | * (UI) thread. 106 | * @throws DeviceDisconnectedException thrown when the device disconnected before the request 107 | * was completed. 108 | * @throws BluetoothDisabledException thrown when the Bluetooth adapter has been disabled. 109 | * @throws InvalidRequestException thrown when the request was called before the device was 110 | * connected at least once (unknown device). 111 | * @see #enqueue() 112 | */ 113 | public final void await() throws RequestFailedException, DeviceDisconnectedException, 114 | BluetoothDisabledException, InvalidRequestException, InterruptedException { 115 | assertNotMainThread(); 116 | 117 | final SuccessCallback sc = successCallback; 118 | final FailCallback fc = failCallback; 119 | try { 120 | syncLock.close(); 121 | final RequestCallback callback = new RequestCallback(); 122 | done(callback).fail(callback).invalid(callback).enqueue(); 123 | 124 | if (!syncLock.block(timeout)) { 125 | throw new InterruptedException(); 126 | } 127 | if (!callback.isSuccess()) { 128 | if (callback.status == FailCallback.REASON_DEVICE_DISCONNECTED) { 129 | throw new DeviceDisconnectedException(); 130 | } 131 | if (callback.status == FailCallback.REASON_BLUETOOTH_DISABLED) { 132 | throw new BluetoothDisabledException(); 133 | } 134 | if (callback.status == RequestCallback.REASON_REQUEST_INVALID) { 135 | throw new InvalidRequestException(this); 136 | } 137 | throw new RequestFailedException(this, callback.status); 138 | } 139 | } finally { 140 | successCallback = sc; 141 | failCallback = fc; 142 | } 143 | } 144 | 145 | /** 146 | * Synchronously waits, for as most as the given number of milliseconds, until the request 147 | * is ready. 148 | *

149 | * When the timeout occurs, the {@link InterruptedException} will be thrown. 150 | *

151 | * Callbacks set using {@link #done(SuccessCallback)} and {@link #fail(FailCallback)} 152 | * will be ignored. 153 | *

154 | * This method may not be called from the main (UI) thread. 155 | * 156 | * @param timeout optional timeout in milliseconds, 0 to disable timeout. This will 157 | * override the timeout set using {@link #timeout(long)}. 158 | * @throws RequestFailedException thrown when the BLE request finished with status other 159 | * than {@link BluetoothGatt#GATT_SUCCESS}. 160 | * @throws InterruptedException thrown if the timeout occurred before the request has 161 | * finished. 162 | * @throws IllegalStateException thrown when you try to call this method from the main 163 | * (UI) thread. 164 | * @throws DeviceDisconnectedException thrown when the device disconnected before the request 165 | * was completed. 166 | * @throws BluetoothDisabledException thrown when the Bluetooth adapter has been disabled. 167 | * @throws InvalidRequestException thrown when the request was called before the device was 168 | * connected at least once (unknown device). 169 | * @deprecated Use {@link #timeout(long)} and {@link #await()} instead. 170 | */ 171 | @Deprecated 172 | public final void await(@IntRange(from = 0) final long timeout) throws RequestFailedException, 173 | InterruptedException, DeviceDisconnectedException, BluetoothDisabledException, 174 | InvalidRequestException { 175 | timeout(timeout).await(); 176 | } 177 | 178 | @Override 179 | void notifyStarted(@NonNull final BluetoothDevice device) { 180 | if (timeout > 0L) { 181 | timeoutCallback = () -> { 182 | timeoutCallback = null; 183 | if (!finished) { 184 | notifyFail(device, FailCallback.REASON_TIMEOUT); 185 | timeoutHandler.onRequestTimeout(this); 186 | } 187 | }; 188 | handler.postDelayed(timeoutCallback, timeout); 189 | } 190 | super.notifyStarted(device); 191 | } 192 | 193 | @Override 194 | void notifySuccess(@NonNull final BluetoothDevice device) { 195 | if (!finished) { 196 | handler.removeCallbacks(timeoutCallback); 197 | timeoutCallback = null; 198 | } 199 | super.notifySuccess(device); 200 | } 201 | 202 | @Override 203 | void notifyFail(@NonNull final BluetoothDevice device, final int status) { 204 | if (!finished) { 205 | handler.removeCallbacks(timeoutCallback); 206 | timeoutCallback = null; 207 | } 208 | super.notifyFail(device, status); 209 | } 210 | 211 | @Override 212 | void notifyInvalidRequest() { 213 | if (!finished) { 214 | handler.removeCallbacks(timeoutCallback); 215 | timeoutCallback = null; 216 | } 217 | super.notifyInvalidRequest(); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/ValueChangedCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Handler; 27 | 28 | import androidx.annotation.NonNull; 29 | import androidx.annotation.Nullable; 30 | import no.nordicsemi.android.ble.callback.DataReceivedCallback; 31 | import no.nordicsemi.android.ble.callback.ReadProgressCallback; 32 | import no.nordicsemi.android.ble.data.Data; 33 | import no.nordicsemi.android.ble.data.DataFilter; 34 | import no.nordicsemi.android.ble.data.DataMerger; 35 | import no.nordicsemi.android.ble.data.DataStream; 36 | 37 | @SuppressWarnings({"unused", "WeakerAccess", "UnusedReturnValue"}) 38 | public class ValueChangedCallback { 39 | private ReadProgressCallback progressCallback; 40 | private DataReceivedCallback valueCallback; 41 | private DataMerger dataMerger; 42 | private DataStream buffer; 43 | private DataFilter filter; 44 | private final Handler handler; 45 | private int count = 0; 46 | 47 | ValueChangedCallback(final Handler handler) { 48 | this.handler = handler; 49 | } 50 | 51 | /** 52 | * Sets the asynchronous data callback that will be called whenever a notification or 53 | * an indication is received on given characteristic. 54 | * 55 | * @param callback the data callback. 56 | * @return The request. 57 | */ 58 | @NonNull 59 | public ValueChangedCallback with(@NonNull final DataReceivedCallback callback) { 60 | this.valueCallback = callback; 61 | return this; 62 | } 63 | 64 | /** 65 | * Sets a filter which allows to skip some incoming data. 66 | * 67 | * @param filter the data filter. 68 | * @return The request. 69 | */ 70 | @NonNull 71 | public ValueChangedCallback filter(@NonNull final DataFilter filter) { 72 | this.filter = filter; 73 | return this; 74 | } 75 | 76 | /** 77 | * Adds a merger that will be used to merge multiple packets into a single Data. 78 | * The merger may modify each packet if necessary. 79 | * 80 | * @return The request. 81 | */ 82 | @NonNull 83 | public ValueChangedCallback merge(@NonNull final DataMerger merger) { 84 | this.dataMerger = merger; 85 | this.progressCallback = null; 86 | return this; 87 | } 88 | 89 | /** 90 | * Adds a merger that will be used to merge multiple packets into a single Data. 91 | * The merger may modify each packet if necessary. 92 | * 93 | * @return The request. 94 | */ 95 | @NonNull 96 | public ValueChangedCallback merge(@NonNull final DataMerger merger, 97 | @NonNull final ReadProgressCallback callback) { 98 | this.dataMerger = merger; 99 | this.progressCallback = callback; 100 | return this; 101 | } 102 | 103 | ValueChangedCallback free() { 104 | valueCallback = null; 105 | dataMerger = null; 106 | progressCallback = null; 107 | buffer = null; 108 | return this; 109 | } 110 | 111 | boolean matches(final byte[] packet) { 112 | return filter == null || filter.filter(packet); 113 | } 114 | 115 | void notifyValueChanged(@NonNull final BluetoothDevice device, @Nullable final byte[] value) { 116 | // Keep a reference to the value callback, as it may change during execution 117 | final DataReceivedCallback valueCallback = this.valueCallback; 118 | 119 | // With no value callback there is no need for any merging 120 | if (valueCallback == null) { 121 | return; 122 | } 123 | 124 | if (dataMerger == null) { 125 | final Data data = new Data(value); 126 | handler.post(() -> valueCallback.onDataReceived(device, data)); 127 | } else { 128 | handler.post(() -> { 129 | if (progressCallback != null) 130 | progressCallback.onPacketReceived(device, value, count); 131 | }); 132 | if (buffer == null) 133 | buffer = new DataStream(); 134 | if (dataMerger.merge(buffer, value, count++)) { 135 | final Data data = buffer.toData(); 136 | handler.post(() -> valueCallback.onDataReceived(device, data)); 137 | buffer = null; 138 | count = 0; 139 | } // else 140 | // wait for more packets to be merged 141 | } 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/annotation/ConnectionPriority.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.annotation; 24 | 25 | import java.lang.annotation.Retention; 26 | import java.lang.annotation.RetentionPolicy; 27 | 28 | import androidx.annotation.IntDef; 29 | import no.nordicsemi.android.ble.ConnectionPriorityRequest; 30 | 31 | @Retention(RetentionPolicy.SOURCE) 32 | @IntDef(value = { 33 | ConnectionPriorityRequest.CONNECTION_PRIORITY_BALANCED, 34 | ConnectionPriorityRequest.CONNECTION_PRIORITY_HIGH, 35 | ConnectionPriorityRequest.CONNECTION_PRIORITY_LOW_POWER 36 | }) 37 | public @interface ConnectionPriority {} -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/annotation/ConnectionState.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.annotation; 24 | 25 | import android.bluetooth.BluetoothProfile; 26 | 27 | import java.lang.annotation.Retention; 28 | import java.lang.annotation.RetentionPolicy; 29 | 30 | import androidx.annotation.IntDef; 31 | 32 | @Retention(RetentionPolicy.SOURCE) 33 | @IntDef(value = { 34 | BluetoothProfile.STATE_DISCONNECTED, 35 | BluetoothProfile.STATE_CONNECTING, 36 | BluetoothProfile.STATE_CONNECTED, 37 | BluetoothProfile.STATE_DISCONNECTING, 38 | }) 39 | public @interface ConnectionState {} -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/annotation/PhyMask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.annotation; 24 | 25 | import java.lang.annotation.Retention; 26 | import java.lang.annotation.RetentionPolicy; 27 | 28 | import androidx.annotation.IntDef; 29 | import no.nordicsemi.android.ble.PhyRequest; 30 | 31 | @Retention(RetentionPolicy.SOURCE) 32 | @IntDef(flag = true, value = { 33 | PhyRequest.PHY_LE_1M_MASK, 34 | PhyRequest.PHY_LE_2M_MASK, 35 | PhyRequest.PHY_LE_CODED_MASK 36 | }) 37 | public @interface PhyMask {} 38 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/annotation/PhyOption.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.annotation; 24 | 25 | import java.lang.annotation.Retention; 26 | import java.lang.annotation.RetentionPolicy; 27 | 28 | import androidx.annotation.IntDef; 29 | import no.nordicsemi.android.ble.PhyRequest; 30 | 31 | @Retention(RetentionPolicy.SOURCE) 32 | @IntDef(value = { 33 | PhyRequest.PHY_OPTION_NO_PREFERRED, 34 | PhyRequest.PHY_OPTION_S2, 35 | PhyRequest.PHY_OPTION_S8 36 | }) 37 | public @interface PhyOption {} -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/annotation/PhyValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.annotation; 24 | 25 | import java.lang.annotation.Retention; 26 | import java.lang.annotation.RetentionPolicy; 27 | 28 | import androidx.annotation.IntDef; 29 | import no.nordicsemi.android.ble.callback.PhyCallback; 30 | 31 | @Retention(RetentionPolicy.SOURCE) 32 | @IntDef(value = { 33 | PhyCallback.PHY_LE_1M, 34 | PhyCallback.PHY_LE_2M, 35 | PhyCallback.PHY_LE_CODED 36 | }) 37 | public @interface PhyValue {} 38 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/annotation/WriteType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.annotation; 24 | 25 | import android.bluetooth.BluetoothGattCharacteristic; 26 | 27 | import java.lang.annotation.Retention; 28 | import java.lang.annotation.RetentionPolicy; 29 | 30 | import androidx.annotation.IntDef; 31 | 32 | @Retention(RetentionPolicy.SOURCE) 33 | @IntDef(value = { 34 | BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, 35 | BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE, 36 | BluetoothGattCharacteristic.WRITE_TYPE_SIGNED, 37 | }) 38 | public @interface WriteType {} -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/BeforeCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | 29 | public interface BeforeCallback { 30 | 31 | /** 32 | * A callback invoked when the request is about to start. 33 | * 34 | * @param device the target device. 35 | */ 36 | void onRequestStarted(@NonNull final BluetoothDevice device); 37 | } 38 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/ConnectionPriorityCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | 30 | /** 31 | * The connection parameters for a Bluetooth LE connection is a set of parameters that determine 32 | * when and how the Central and a Peripheral in a link transmits data. 33 | * It is always the Central that actually sets the connection parameters used, but the Peripheral 34 | * can send a so-called Connection Parameter Update Request, that the Central can then accept or reject. 35 | *

36 | * On Android, requesting connection parameters is available since Android Lollipop using 37 | * {@link android.bluetooth.BluetoothGatt#requestConnectionPriority(int)}. There are 3 options 38 | * available: {@link android.bluetooth.BluetoothGatt#CONNECTION_PRIORITY_LOW_POWER}, 39 | * {@link android.bluetooth.BluetoothGatt#CONNECTION_PRIORITY_BALANCED} and 40 | * {@link android.bluetooth.BluetoothGatt#CONNECTION_PRIORITY_HIGH}. See 41 | * {@link no.nordicsemi.android.ble.Request#newConnectionPriorityRequest(int)} for details. 42 | *

43 | * Until Android 8.0 Oreo, there was no callback indicating whether the change has succeeded, 44 | * or not. Also, when a Central or Peripheral requested connection parameters change without 45 | * explicit calling of this method, the application was not aware of it. 46 | * Android Oreo added a hidden callback to {@link android.bluetooth.BluetoothGattCallback} 47 | * notifying about connection parameters change. Those values will be reported with this callback. 48 | */ 49 | public interface ConnectionPriorityCallback { 50 | 51 | /** 52 | * Callback indicating the connection parameters were updated. Works on Android 8.0 Oreo or newer. 53 | * 54 | * @param device the target device. 55 | * @param interval Connection interval used on this connection, 1.25ms unit. Valid range is from 56 | * 6 (7.5ms) to 3200 (4000ms). 57 | * @param latency Slave latency for the connection in number of connection events. Valid range 58 | * is from 0 to 499. 59 | * @param timeout Supervision timeout for this connection, in 10ms unit. Valid range is from 10 60 | * (100 ms = 0.1s) to 3200 (32s). 61 | */ 62 | void onConnectionUpdated(@NonNull final BluetoothDevice device, 63 | @IntRange(from = 6, to = 3200) final int interval, 64 | @IntRange(from = 0, to = 499) final int latency, 65 | @IntRange(from = 10, to = 3200) final int timeout); 66 | } 67 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/DataReceivedCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | import no.nordicsemi.android.ble.data.Data; 29 | import no.nordicsemi.android.ble.data.DataMerger; 30 | 31 | public interface DataReceivedCallback { 32 | 33 | /** 34 | * Callback received each time the value was read or has changed using 35 | * notifications or indications. 36 | * 37 | * @param device the target device. 38 | * @param data the data received. If the {@link DataMerger} was used, 39 | * this contains the merged result. 40 | */ 41 | void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data); 42 | } 43 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/DataSentCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | import no.nordicsemi.android.ble.data.Data; 29 | import no.nordicsemi.android.ble.data.DataSplitter; 30 | 31 | public interface DataSentCallback { 32 | 33 | /** 34 | * Callback received each time the value was written to a characteristic or descriptor. 35 | * 36 | * @param device the target device. 37 | * @param data the data sent. If the {@link DataSplitter} was used, this contains the full data. 38 | */ 39 | void onDataSent(@NonNull final BluetoothDevice device, @NonNull final Data data); 40 | } 41 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/FailCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | 29 | public interface FailCallback { 30 | int REASON_DEVICE_DISCONNECTED = -1; 31 | int REASON_DEVICE_NOT_SUPPORTED = -2; 32 | int REASON_NULL_ATTRIBUTE = -3; 33 | int REASON_REQUEST_FAILED = -4; 34 | int REASON_TIMEOUT = -5; 35 | int REASON_VALIDATION = -6; 36 | int REASON_BLUETOOTH_DISABLED = -100; 37 | 38 | /** 39 | * A callback invoked when the request has failed with status other than 40 | * {@link android.bluetooth.BluetoothGatt#GATT_SUCCESS}. 41 | * 42 | * @param device target device. 43 | * @param status error status code, one of BluetoothGatt#GATT_* constants or 44 | * {@link #REASON_DEVICE_DISCONNECTED}, {@link #REASON_TIMEOUT}, 45 | * {@link #REASON_DEVICE_NOT_SUPPORTED} (only for Connect request), 46 | * {@link #REASON_BLUETOOTH_DISABLED}, {@link #REASON_NULL_ATTRIBUTE}, 47 | * {@link #REASON_VALIDATION} or {@link #REASON_REQUEST_FAILED} (for other reason). 48 | */ 49 | void onRequestFailed(@NonNull final BluetoothDevice device, final int status); 50 | } 51 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/InvalidRequestCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | public interface InvalidRequestCallback { 26 | 27 | /** 28 | * A callback invoked when the request was invalid, for example when was called before the 29 | * device was connected. 30 | */ 31 | void onInvalidRequest(); 32 | } 33 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/MtuCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | 30 | public interface MtuCallback { 31 | 32 | /** 33 | * Method called when the MTU request has finished with success. The MTU value may 34 | * be different than requested one. The maximum packet size is 3 bytes less then MTU. 35 | * 36 | * @param device the target device. 37 | * @param mtu the new MTU (Maximum Transfer Unit). 38 | */ 39 | void onMtuChanged(@NonNull final BluetoothDevice device, 40 | @IntRange(from = 23, to = 517) final int mtu); 41 | } 42 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/PhyCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | import no.nordicsemi.android.ble.annotation.PhyValue; 29 | 30 | @SuppressWarnings("unused") 31 | public interface PhyCallback { 32 | /** 33 | * Bluetooth LE 1M PHY. Used to refer to LE 1M Physical Channel for advertising, scanning or 34 | * connection. 35 | */ 36 | int PHY_LE_1M = 1; 37 | 38 | /** 39 | * Bluetooth LE 2M PHY. Used to refer to LE 2M Physical Channel for advertising, scanning or 40 | * connection. 41 | */ 42 | int PHY_LE_2M = 2; 43 | 44 | /** 45 | * Bluetooth LE Coded PHY. Used to refer to LE Coded Physical Channel for advertising, scanning 46 | * or connection. 47 | */ 48 | int PHY_LE_CODED = 3; 49 | 50 | /** 51 | * Method called when the PHY value has changed or was read. 52 | * 53 | * @param device the target device. 54 | * @param txPhy the transmitter PHY in use. One of {@link #PHY_LE_1M}, 55 | * {@link #PHY_LE_2M}, and {@link #PHY_LE_CODED}. 56 | * @param rxPhy the receiver PHY in use. One of {@link #PHY_LE_1M}, 57 | * {@link #PHY_LE_2M}, and {@link #PHY_LE_CODED}. 58 | */ 59 | void onPhyChanged(@NonNull final BluetoothDevice device, 60 | @PhyValue final int txPhy, @PhyValue final int rxPhy); 61 | } 62 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/ReadProgressCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | import androidx.annotation.Nullable; 30 | import no.nordicsemi.android.ble.data.DataMerger; 31 | 32 | public interface ReadProgressCallback { 33 | 34 | /** 35 | * Callback received each time the value was read or has changed using notifications or 36 | * indications when {@link DataMerger} was used. 37 | * 38 | * @param device the target device. 39 | * @param data the last packet received. 40 | * @param index the index of a packet that will be merged into a single Data. 41 | */ 42 | void onPacketReceived(@NonNull final BluetoothDevice device, 43 | @Nullable final byte[] data, @IntRange(from = 0) final int index); 44 | } 45 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/RssiCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | 30 | public interface RssiCallback { 31 | 32 | /** 33 | * Method called when the RSSI value has been read. 34 | * 35 | * @param device the target device. 36 | * @param rssi the current RSSI value, in dBm. 37 | */ 38 | void onRssiRead(@NonNull final BluetoothDevice device, 39 | @IntRange(from = -128, to = 20) final int rssi); 40 | } 41 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/SuccessCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | 29 | public interface SuccessCallback { 30 | 31 | /** 32 | * A callback invoked when the request completed successfully. 33 | * 34 | * @param device the target device. 35 | */ 36 | void onRequestCompleted(@NonNull final BluetoothDevice device); 37 | } 38 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/WriteProgressCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | import androidx.annotation.Nullable; 30 | import no.nordicsemi.android.ble.data.DataSplitter; 31 | 32 | public interface WriteProgressCallback { 33 | 34 | /** 35 | * Callback called each time a packet has been sent when {@link DataSplitter} was used. 36 | * 37 | * @param device the target device. 38 | * @param data the last packet sent. 39 | * @param index the index of a packet that the initial Data was cut into. 40 | */ 41 | void onPacketSent(@NonNull final BluetoothDevice device, 42 | @Nullable final byte[] data, @IntRange(from = 0) final int index); 43 | } 44 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/profile/ProfileDataCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback.profile; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | 27 | import androidx.annotation.NonNull; 28 | import no.nordicsemi.android.ble.callback.DataReceivedCallback; 29 | import no.nordicsemi.android.ble.data.Data; 30 | import no.nordicsemi.android.ble.data.DataMerger; 31 | 32 | @SuppressWarnings("unused") 33 | public interface ProfileDataCallback extends DataReceivedCallback { 34 | 35 | /** 36 | * Callback called when the data received do not conform to required scheme. 37 | * @param device the target device. 38 | * @param data the data received. If the {@link DataMerger} was used, this contains the 39 | * merged result. 40 | */ 41 | default void onInvalidDataReceived(@NonNull final BluetoothDevice device, 42 | @NonNull final Data data) { 43 | // ignore 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/callback/profile/ProfileReadResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.callback.profile; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.NonNull; 30 | import no.nordicsemi.android.ble.data.Data; 31 | import no.nordicsemi.android.ble.response.ReadResponse; 32 | 33 | /** 34 | * A response type for read requests with basic validation check. 35 | * When read was requested as a synchronous call the {@link #isValid()} can be used to 36 | * check if data were parsed successfully. Parsing method must call super methods on 37 | * both {@link #onDataReceived(BluetoothDevice, Data)} and 38 | * {@link #onInvalidDataReceived(BluetoothDevice, Data)} in order to make getters working properly. 39 | *

40 | * Check out profile data callbacks in the Android BLE Common Library for example of usage. 41 | */ 42 | @SuppressWarnings({"unused", "WeakerAccess"}) 43 | public class ProfileReadResponse extends ReadResponse implements ProfileDataCallback, Parcelable { 44 | private boolean valid = true; 45 | 46 | public ProfileReadResponse() { 47 | // empty 48 | } 49 | 50 | @Override 51 | public void onInvalidDataReceived(@NonNull final BluetoothDevice device, 52 | @NonNull final Data data) { 53 | this.valid = false; 54 | } 55 | 56 | /** 57 | * Returns true if {@link #onInvalidDataReceived(BluetoothDevice, Data)} wasn't called. 58 | * 59 | * @return True, if profile data were valid, false if parsing error occurred. 60 | */ 61 | public boolean isValid() { 62 | return valid; 63 | } 64 | 65 | // Parcelable 66 | protected ProfileReadResponse(final Parcel in) { 67 | super(in); 68 | valid = in.readByte() != 0; 69 | } 70 | 71 | @Override 72 | public void writeToParcel(final Parcel dest, final int flags) { 73 | super.writeToParcel(dest, flags); 74 | dest.writeByte((byte) (valid ? 1 : 0)); 75 | } 76 | 77 | public static final Creator CREATOR = new Creator() { 78 | @Override 79 | public ProfileReadResponse createFromParcel(final Parcel in) { 80 | return new ProfileReadResponse(in); 81 | } 82 | 83 | @Override 84 | public ProfileReadResponse[] newArray(final int size) { 85 | return new ProfileReadResponse[size]; 86 | } 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/data/DataFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import androidx.annotation.Nullable; 26 | 27 | public interface DataFilter { 28 | 29 | /** 30 | * This method should return true if the packet matches the filter and should be processed 31 | * by the request. 32 | * 33 | * @param lastPacket the packet received. 34 | * @return True, if packet should be processed, false if it should be ignored. 35 | */ 36 | boolean filter(@Nullable final byte[] lastPacket); 37 | } 38 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/data/DataMerger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import androidx.annotation.IntRange; 26 | import androidx.annotation.NonNull; 27 | import androidx.annotation.Nullable; 28 | 29 | public interface DataMerger { 30 | 31 | /** 32 | * This method should merge the last packet into the output message. 33 | * 34 | * @param output the stream for the output message, initially empty. 35 | * @param lastPacket the data received in the last read/notify/indicate operation. 36 | * @param index an index of the packet, 0-based (if you expect 3 packets, they will be 37 | * called with indexes 0, 1, 2). 38 | * @return True, if the message is complete, false if more data are expected. 39 | */ 40 | boolean merge(@NonNull final DataStream output, 41 | @Nullable final byte[] lastPacket, @IntRange(from = 0) final int index); 42 | } 43 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/data/DataSplitter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import androidx.annotation.IntRange; 26 | import androidx.annotation.NonNull; 27 | import androidx.annotation.Nullable; 28 | 29 | public interface DataSplitter { 30 | 31 | /** 32 | * The implementation should return a index'th byte array from given message, 33 | * with at most maxLength size, or null if no bytes are left to be sent. 34 | * 35 | * @param message the full message to be chunk. 36 | * @param index index of a packet, 0-based. 37 | * @param maxLength maximum length of the returned packet. Equals to MTU-3. 38 | * Use {@link no.nordicsemi.android.ble.BleManager#requestMtu(int)} to request 39 | * higher MTU, or {@link no.nordicsemi.android.ble.BleManager#overrideMtu(int)} 40 | * If the MTU change was initiated by the target device. 41 | * @return The packet to be sent, or null, if the whole message was already split. 42 | */ 43 | @Nullable 44 | byte[] chunk(@NonNull final byte[] message, 45 | @IntRange(from = 0) final int index, @IntRange(from = 20) final int maxLength); 46 | } 47 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/data/DataStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import java.io.ByteArrayOutputStream; 26 | 27 | import androidx.annotation.IntRange; 28 | import androidx.annotation.NonNull; 29 | import androidx.annotation.Nullable; 30 | 31 | @SuppressWarnings("WeakerAccess") 32 | public class DataStream { 33 | private final ByteArrayOutputStream buffer; 34 | 35 | public DataStream() { 36 | buffer = new ByteArrayOutputStream(); 37 | } 38 | 39 | @SuppressWarnings("SimplifiableIfStatement") 40 | public boolean write(@Nullable final byte[] data) { 41 | if (data == null) 42 | return false; 43 | 44 | return write(data, 0, data.length); 45 | } 46 | 47 | public boolean write(@Nullable final byte[] data, 48 | @IntRange(from = 0) final int offset, @IntRange(from = 0) final int length) { 49 | if (data == null || data.length < offset) 50 | return false; 51 | 52 | final int len = Math.min(data.length - offset, length); 53 | buffer.write(data, offset, len); 54 | return true; 55 | } 56 | 57 | public boolean write(@Nullable final Data data) { 58 | return data != null && write(data.getValue()); 59 | } 60 | 61 | @IntRange(from = 0) 62 | public int size() { 63 | return buffer.size(); 64 | } 65 | 66 | @NonNull 67 | public byte[] toByteArray() { 68 | return buffer.toByteArray(); 69 | } 70 | 71 | @NonNull 72 | public Data toData() { 73 | return new Data(buffer.toByteArray()); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/data/DefaultMtuSplitter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import androidx.annotation.IntRange; 26 | import androidx.annotation.NonNull; 27 | import androidx.annotation.Nullable; 28 | 29 | /** 30 | * Splits the message into at-most MTU-3 size packets. 31 | */ 32 | public final class DefaultMtuSplitter implements DataSplitter { 33 | 34 | @Nullable 35 | @Override 36 | public byte[] chunk(@NonNull final byte[] message, 37 | @IntRange(from = 0) final int index, 38 | @IntRange(from = 20) final int maxLength) { 39 | final int offset = index * maxLength; 40 | final int length = Math.min(maxLength, message.length - offset); 41 | 42 | if (length <= 0) 43 | return null; 44 | 45 | final byte[] data = new byte[length]; 46 | System.arraycopy(message, offset, data, 0, length); 47 | return data; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/error/GattError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | package no.nordicsemi.android.ble.error; 23 | 24 | import android.bluetooth.BluetoothGatt; 25 | 26 | /** 27 | * Parses the GATT and HCI errors to human readable strings. 28 | *

29 | * See: gatt_api.h for details.
30 | * See also: hcidefs.h for other possible HCI errors. 31 | */ 32 | @SuppressWarnings("WeakerAccess") 33 | public class GattError { 34 | public static final int GATT_SUCCESS = BluetoothGatt.GATT_SUCCESS; 35 | public static final int GATT_CONN_L2C_FAILURE = 0x01; 36 | public static final int GATT_CONN_TIMEOUT = 0x08; 37 | public static final int GATT_CONN_TERMINATE_PEER_USER = 0x13; 38 | public static final int GATT_CONN_TERMINATE_LOCAL_HOST = 0x16; 39 | public static final int GATT_CONN_FAIL_ESTABLISH = 0x3E; 40 | public static final int GATT_CONN_LMP_TIMEOUT = 0x22; 41 | public static final int GATT_CONN_CANCEL = 0x0100; 42 | public static final int GATT_ERROR = 0x0085; // Device not reachable 43 | 44 | public static final int GATT_INVALID_HANDLE = 0x0001; 45 | public static final int GATT_READ_NOT_PERMIT = 0x0002; 46 | public static final int GATT_WRITE_NOT_PERMIT = 0x0003; 47 | public static final int GATT_INVALID_PDU = 0x0004; 48 | public static final int GATT_INSUF_AUTHENTICATION = 0x0005; 49 | public static final int GATT_REQ_NOT_SUPPORTED = 0x0006; 50 | public static final int GATT_INVALID_OFFSET = 0x0007; 51 | public static final int GATT_INSUF_AUTHORIZATION = 0x0008; 52 | public static final int GATT_PREPARE_Q_FULL = 0x0009; 53 | public static final int GATT_NOT_FOUND = 0x000a; 54 | public static final int GATT_NOT_LONG = 0x000b; 55 | public static final int GATT_INSUF_KEY_SIZE = 0x000c; 56 | public static final int GATT_INVALID_ATTR_LEN = 0x000d; 57 | public static final int GATT_ERR_UNLIKELY = 0x000e; 58 | public static final int GATT_INSUF_ENCRYPTION = 0x000f; 59 | public static final int GATT_UNSUPPORT_GRP_TYPE = 0x0010; 60 | public static final int GATT_INSUF_RESOURCE = 0x0011; 61 | public static final int GATT_CONTROLLER_BUSY = 0x003A; 62 | public static final int GATT_UNACCEPT_CONN_INTERVAL = 0x003B; 63 | public static final int GATT_ILLEGAL_PARAMETER = 0x0087; 64 | public static final int GATT_NO_RESOURCES = 0x0080; 65 | public static final int GATT_INTERNAL_ERROR = 0x0081; 66 | public static final int GATT_WRONG_STATE = 0x0082; 67 | public static final int GATT_DB_FULL = 0x0083; 68 | public static final int GATT_BUSY = 0x0084; 69 | public static final int GATT_CMD_STARTED = 0x0086; 70 | public static final int GATT_PENDING = 0x0088; 71 | public static final int GATT_AUTH_FAIL = 0x0089; 72 | public static final int GATT_MORE = 0x008a; 73 | public static final int GATT_INVALID_CFG = 0x008b; 74 | public static final int GATT_SERVICE_STARTED = 0x008c; 75 | public static final int GATT_ENCRYPTED_NO_MITM = 0x008d; 76 | public static final int GATT_NOT_ENCRYPTED = 0x008e; 77 | public static final int GATT_CONGESTED = 0x008f; 78 | public static final int GATT_CCCD_CFG_ERROR = 0x00FD; 79 | public static final int GATT_PROCEDURE_IN_PROGRESS = 0x00FE; 80 | public static final int GATT_VALUE_OUT_OF_RANGE = 0x00FF; 81 | public static final int TOO_MANY_OPEN_CONNECTIONS = 0x0101; 82 | 83 | /** 84 | * Converts the connection status given by the 85 | * {@link android.bluetooth.BluetoothGattCallback#onConnectionStateChange(BluetoothGatt, int, int)} 86 | * to error name. 87 | * 88 | * @param error the status number. 89 | * @return The error name as stated in the links in {@link GattError} documentation. 90 | */ 91 | public static String parseConnectionError(final int error) { 92 | switch (error) { 93 | case GATT_SUCCESS: 94 | return "SUCCESS"; 95 | case GATT_CONN_L2C_FAILURE: 96 | return "GATT CONN L2C FAILURE"; 97 | case GATT_CONN_TIMEOUT: 98 | return "GATT CONN TIMEOUT"; 99 | case GATT_CONN_TERMINATE_PEER_USER: 100 | return "GATT CONN TERMINATE PEER USER"; 101 | case GATT_CONN_TERMINATE_LOCAL_HOST: 102 | return "GATT CONN TERMINATE LOCAL HOST"; 103 | case GATT_CONN_FAIL_ESTABLISH: 104 | return "GATT CONN FAIL ESTABLISH"; 105 | case GATT_CONN_LMP_TIMEOUT: 106 | return "GATT CONN LMP TIMEOUT"; 107 | case GATT_CONN_CANCEL: 108 | return "GATT CONN CANCEL "; 109 | case GATT_ERROR: 110 | return "GATT ERROR"; // Device not reachable 111 | default: 112 | return "UNKNOWN (" + error + ")"; 113 | } 114 | } 115 | 116 | /** 117 | * Converts the Bluetooth communication status given by other BluetoothGattCallbacks to error 118 | * name. It also parses the DFU errors. 119 | * 120 | * @param error the status number. 121 | * @return The error name as stated in the links in {@link GattError} documentation. 122 | */ 123 | public static String parse(final int error) { 124 | switch (error) { 125 | case GATT_INVALID_HANDLE: 126 | return "GATT INVALID HANDLE"; 127 | case GATT_READ_NOT_PERMIT: 128 | return "GATT READ NOT PERMIT"; 129 | case GATT_WRITE_NOT_PERMIT: 130 | return "GATT WRITE NOT PERMIT"; 131 | case GATT_INVALID_PDU: 132 | return "GATT INVALID PDU"; 133 | case GATT_INSUF_AUTHENTICATION: 134 | return "GATT INSUF AUTHENTICATION"; 135 | case GATT_REQ_NOT_SUPPORTED: 136 | return "GATT REQ NOT SUPPORTED"; 137 | case GATT_INVALID_OFFSET: 138 | return "GATT INVALID OFFSET"; 139 | case GATT_INSUF_AUTHORIZATION: 140 | return "GATT INSUF AUTHORIZATION"; 141 | case GATT_PREPARE_Q_FULL: 142 | return "GATT PREPARE Q FULL"; 143 | case GATT_NOT_FOUND: 144 | return "GATT NOT FOUND"; 145 | case GATT_NOT_LONG: 146 | return "GATT NOT LONG"; 147 | case GATT_INSUF_KEY_SIZE: 148 | return "GATT INSUF KEY SIZE"; 149 | case GATT_INVALID_ATTR_LEN: 150 | return "GATT INVALID ATTR LEN"; 151 | case GATT_ERR_UNLIKELY: 152 | return "GATT ERR UNLIKELY"; 153 | case GATT_INSUF_ENCRYPTION: 154 | return "GATT INSUF ENCRYPTION"; 155 | case GATT_UNSUPPORT_GRP_TYPE: 156 | return "GATT UNSUPPORT GRP TYPE"; 157 | case GATT_INSUF_RESOURCE: 158 | return "GATT INSUF RESOURCE"; 159 | case GATT_CONN_LMP_TIMEOUT: 160 | return "GATT CONN LMP TIMEOUT"; 161 | case GATT_CONTROLLER_BUSY: 162 | return "GATT CONTROLLER BUSY"; 163 | case GATT_UNACCEPT_CONN_INTERVAL: 164 | return "GATT UNACCEPT CONN INTERVAL"; 165 | case GATT_ILLEGAL_PARAMETER: 166 | return "GATT ILLEGAL PARAMETER"; 167 | case GATT_NO_RESOURCES: 168 | return "GATT NO RESOURCES"; 169 | case GATT_INTERNAL_ERROR: 170 | return "GATT INTERNAL ERROR"; 171 | case GATT_WRONG_STATE: 172 | return "GATT WRONG STATE"; 173 | case GATT_DB_FULL: 174 | return "GATT DB FULL"; 175 | case GATT_BUSY: 176 | return "GATT BUSY"; 177 | case GATT_ERROR: 178 | return "GATT ERROR"; 179 | case GATT_CMD_STARTED: 180 | return "GATT CMD STARTED"; 181 | case GATT_PENDING: 182 | return "GATT PENDING"; 183 | case GATT_AUTH_FAIL: 184 | return "GATT AUTH FAIL"; 185 | case GATT_MORE: 186 | return "GATT MORE"; 187 | case GATT_INVALID_CFG: 188 | return "GATT INVALID CFG"; 189 | case GATT_SERVICE_STARTED: 190 | return "GATT SERVICE STARTED"; 191 | case GATT_ENCRYPTED_NO_MITM: 192 | return "GATT ENCRYPTED NO MITM"; 193 | case GATT_NOT_ENCRYPTED: 194 | return "GATT NOT ENCRYPTED"; 195 | case GATT_CONGESTED: 196 | return "GATT CONGESTED"; 197 | case GATT_CCCD_CFG_ERROR: 198 | return "GATT CCCD CFG ERROR"; 199 | case GATT_PROCEDURE_IN_PROGRESS: 200 | return "GATT PROCEDURE IN PROGRESS"; 201 | case GATT_VALUE_OUT_OF_RANGE: 202 | return "GATT VALUE OUT OF RANGE"; 203 | case TOO_MANY_OPEN_CONNECTIONS: 204 | return "TOO MANY OPEN CONNECTIONS"; 205 | default: 206 | return "UNKNOWN (" + error + ")"; 207 | } 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/exception/BluetoothDisabledException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.exception; 24 | 25 | public class BluetoothDisabledException extends ConnectionException { 26 | } 27 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/exception/ConnectionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.exception; 24 | 25 | @SuppressWarnings("WeakerAccess") 26 | public class ConnectionException extends Exception { 27 | } 28 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/exception/DeviceDisconnectedException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.exception; 24 | 25 | public class DeviceDisconnectedException extends ConnectionException { 26 | } 27 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/exception/InvalidDataException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.exception; 24 | 25 | import androidx.annotation.NonNull; 26 | import no.nordicsemi.android.ble.callback.profile.ProfileReadResponse; 27 | 28 | @SuppressWarnings("unused") 29 | public final class InvalidDataException extends Exception { 30 | private final ProfileReadResponse response; 31 | 32 | public InvalidDataException(@NonNull final ProfileReadResponse response) { 33 | this.response = response; 34 | } 35 | 36 | public ProfileReadResponse getResponse() { 37 | return response; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/exception/InvalidRequestException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.exception; 24 | 25 | import no.nordicsemi.android.ble.Request; 26 | 27 | @SuppressWarnings({"WeakerAccess", "unused"}) 28 | public final class InvalidRequestException extends Exception { 29 | private final Request request; 30 | 31 | public InvalidRequestException(final Request request) { 32 | super("Invalid request"); 33 | this.request = request; 34 | } 35 | 36 | /** 37 | * Returns the invalid request. 38 | * @return The invalid request. 39 | */ 40 | public Request getRequest() { 41 | return request; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/exception/RequestFailedException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.exception; 24 | 25 | import no.nordicsemi.android.ble.Request; 26 | 27 | @SuppressWarnings({"WeakerAccess", "unused"}) 28 | public final class RequestFailedException extends Exception { 29 | private final Request request; 30 | private final int status; 31 | 32 | public RequestFailedException(final Request request, final int status) { 33 | super("Request failed with status " + status); 34 | this.request = request; 35 | this.status = status; 36 | } 37 | 38 | /** 39 | * Returns the request status. One of {{@link android.bluetooth.BluetoothGatt}} GATT_* 40 | * or {@link no.nordicsemi.android.ble.callback.FailCallback} REASON_* codes. 41 | * 42 | * @return Error code. 43 | */ 44 | public int getStatus() { 45 | return status; 46 | } 47 | 48 | /** 49 | * Returns the request that failed. 50 | * @return The request that failed. 51 | */ 52 | public Request getRequest() { 53 | return request; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/response/ConnectionPriorityResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.response; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.IntRange; 30 | import androidx.annotation.NonNull; 31 | import androidx.annotation.Nullable; 32 | import no.nordicsemi.android.ble.callback.ConnectionPriorityCallback; 33 | 34 | /** 35 | * The synchronous response type for connection priority requests. 36 | * 37 | * @see ConnectionPriorityCallback 38 | */ 39 | @SuppressWarnings({"unused", "WeakerAccess"}) 40 | public class ConnectionPriorityResponse implements ConnectionPriorityCallback, Parcelable { 41 | private BluetoothDevice device; 42 | 43 | @IntRange(from = 6, to = 3200) 44 | private int interval; 45 | 46 | @IntRange(from = 0, to = 499) 47 | private int latency; 48 | 49 | @IntRange(from = 10, to = 3200) 50 | private int supervisionTimeout; 51 | 52 | @Override 53 | public void onConnectionUpdated(@NonNull final BluetoothDevice device, 54 | @IntRange(from = 6, to = 3200) final int interval, 55 | @IntRange(from = 0, to = 499) final int latency, 56 | @IntRange(from = 10, to = 3200) final int timeout) { 57 | this.device = device; 58 | this.interval = interval; 59 | this.latency = latency; 60 | this.supervisionTimeout = timeout; 61 | } 62 | 63 | @Nullable 64 | public BluetoothDevice getBluetoothDevice() { 65 | return device; 66 | } 67 | 68 | /** 69 | * The connection interval determines how often the Central will ask for data from the Peripheral. 70 | * When the Peripheral requests an update, it supplies a maximum and a minimum wanted interval. 71 | * The connection interval must be between 7.5 ms and 4 s. 72 | * 73 | * @return Connection interval used on this connection, 1.25ms unit. 74 | * Valid range is from 6 (7.5ms) to 3200 (4000ms). 75 | */ 76 | @IntRange(from = 6, to = 3200) 77 | public int getConnectionInterval() { 78 | return interval; 79 | } 80 | 81 | /** 82 | * By setting a non-zero slave latency, the Peripheral can choose to not answer when 83 | * the Central asks for data up to the slave latency number of times. 84 | * However, if the Peripheral has data to send, it can choose to send data at any time. 85 | * This enables a peripheral to stay sleeping for a longer time, if it doesn't have data to send, 86 | * but still send data fast if needed. The text book example of such device is for example 87 | * keyboard and mice, which want to be sleeping for as long as possible when there is 88 | * no data to send, but still have low latency (and for the mouse: low connection interval) 89 | * when needed. 90 | * 91 | * @return Slave latency for the connection in number of connection events. 92 | * Valid range is from 0 to 499. 93 | */ 94 | @IntRange(from = 0, to = 499) 95 | public int getSlaveLatency() { 96 | return latency; 97 | } 98 | 99 | /** 100 | * This timeout determines the timeout from the last data exchange till a link is considered lost. 101 | * A Central will not start trying to reconnect before the timeout has passed, 102 | * so if you have a device which goes in and out of range often, and you need to notice when 103 | * that happens, it might make sense to have a short timeout. 104 | * 105 | * @return Supervision timeout for this connection, in 10ms unit. 106 | * Valid range is from 10 (100 ms = 0.1s) to 3200 (32s). 107 | */ 108 | @IntRange(from = 10, to = 3200) 109 | public int getSupervisionTimeout() { 110 | return supervisionTimeout; 111 | } 112 | 113 | // Parcelable 114 | protected ConnectionPriorityResponse(final Parcel in) { 115 | device = in.readParcelable(BluetoothDevice.class.getClassLoader()); 116 | interval = in.readInt(); 117 | latency = in.readInt(); 118 | supervisionTimeout = in.readInt(); 119 | } 120 | 121 | @Override 122 | public void writeToParcel(final Parcel dest, final int flags) { 123 | dest.writeParcelable(device, flags); 124 | dest.writeInt(interval); 125 | dest.writeInt(latency); 126 | dest.writeInt(supervisionTimeout); 127 | } 128 | 129 | @Override 130 | public int describeContents() { 131 | return 0; 132 | } 133 | 134 | public static final Creator CREATOR = new Creator() { 135 | @Override 136 | public ConnectionPriorityResponse createFromParcel(final Parcel in) { 137 | return new ConnectionPriorityResponse(in); 138 | } 139 | 140 | @Override 141 | public ConnectionPriorityResponse[] newArray(final int size) { 142 | return new ConnectionPriorityResponse[size]; 143 | } 144 | }; 145 | } 146 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/response/MtuResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.response; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.IntRange; 30 | import androidx.annotation.NonNull; 31 | import androidx.annotation.Nullable; 32 | import no.nordicsemi.android.ble.callback.MtuCallback; 33 | 34 | @SuppressWarnings({"unused", "WeakerAccess"}) 35 | public class MtuResult implements MtuCallback, Parcelable { 36 | private BluetoothDevice device; 37 | 38 | @IntRange(from = 23, to = 517) 39 | private int mtu; 40 | 41 | @Override 42 | public void onMtuChanged(@NonNull final BluetoothDevice device, 43 | @IntRange(from = 23, to = 517) final int mtu) { 44 | this.device = device; 45 | this.mtu = mtu; 46 | } 47 | 48 | @Nullable 49 | public BluetoothDevice getBluetoothDevice() { 50 | return device; 51 | } 52 | 53 | /** 54 | * Returns the agreed MTU. The maximum packet size is 3 bytes less then MTU. 55 | * 56 | * @return The MTU. 57 | */ 58 | @IntRange(from = 23, to = 517) 59 | public int getMtu() { 60 | return mtu; 61 | } 62 | 63 | // Parcelable 64 | protected MtuResult(final Parcel in) { 65 | device = in.readParcelable(BluetoothDevice.class.getClassLoader()); 66 | mtu = in.readInt(); 67 | } 68 | 69 | @Override 70 | public void writeToParcel(final Parcel dest, final int flags) { 71 | dest.writeParcelable(device, flags); 72 | dest.writeInt(mtu); 73 | } 74 | 75 | @Override 76 | public int describeContents() { 77 | return 0; 78 | } 79 | 80 | public static final Creator CREATOR = new Creator() { 81 | @Override 82 | public MtuResult createFromParcel(final Parcel in) { 83 | return new MtuResult(in); 84 | } 85 | 86 | @Override 87 | public MtuResult[] newArray(final int size) { 88 | return new MtuResult[size]; 89 | } 90 | }; 91 | } 92 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/response/PhyResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.response; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.Nullable; 31 | import no.nordicsemi.android.ble.annotation.PhyValue; 32 | import no.nordicsemi.android.ble.callback.PhyCallback; 33 | 34 | @SuppressWarnings({"unused", "WeakerAccess"}) 35 | public class PhyResult implements PhyCallback, Parcelable { 36 | private BluetoothDevice device; 37 | 38 | @PhyValue 39 | private int txPhy; 40 | 41 | @PhyValue 42 | private int rxPhy; 43 | 44 | @Override 45 | public void onPhyChanged(@NonNull final BluetoothDevice device, 46 | @PhyValue final int txPhy, @PhyValue final int rxPhy) { 47 | this.device = device; 48 | this.txPhy = txPhy; 49 | this.rxPhy = rxPhy; 50 | } 51 | 52 | @Nullable 53 | public BluetoothDevice getBluetoothDevice() { 54 | return device; 55 | } 56 | 57 | @PhyValue 58 | public int getTxPhy() { 59 | return txPhy; 60 | } 61 | 62 | @PhyValue 63 | public int getRxPhy() { 64 | return rxPhy; 65 | } 66 | 67 | // Parcelable 68 | protected PhyResult(final Parcel in) { 69 | device = in.readParcelable(BluetoothDevice.class.getClassLoader()); 70 | txPhy = in.readInt(); 71 | rxPhy = in.readInt(); 72 | } 73 | 74 | @Override 75 | public void writeToParcel(final Parcel dest, final int flags) { 76 | dest.writeParcelable(device, flags); 77 | dest.writeInt(txPhy); 78 | dest.writeInt(rxPhy); 79 | } 80 | 81 | @Override 82 | public int describeContents() { 83 | return 0; 84 | } 85 | 86 | public static final Creator CREATOR = new Creator() { 87 | @Override 88 | public PhyResult createFromParcel(final Parcel in) { 89 | return new PhyResult(in); 90 | } 91 | 92 | @Override 93 | public PhyResult[] newArray(final int size) { 94 | return new PhyResult[size]; 95 | } 96 | }; 97 | } 98 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/response/ReadResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.response; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.Nullable; 31 | import no.nordicsemi.android.ble.callback.DataReceivedCallback; 32 | import no.nordicsemi.android.ble.data.Data; 33 | 34 | /** 35 | * Generic read response class that returns the data received and the device from which data 36 | * were read. 37 | * Overriding class must call super on {@link #onDataReceived(BluetoothDevice, Data)} in 38 | * order to make getters work properly. 39 | */ 40 | @SuppressWarnings({"unused", "WeakerAccess"}) 41 | public class ReadResponse implements DataReceivedCallback, Parcelable { 42 | private BluetoothDevice device; 43 | private Data data; 44 | 45 | public ReadResponse() { 46 | // empty 47 | } 48 | 49 | @Override 50 | public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) { 51 | this.device = device; 52 | this.data = data; 53 | } 54 | 55 | @Nullable 56 | public BluetoothDevice getBluetoothDevice() { 57 | return device; 58 | } 59 | 60 | @Nullable 61 | public Data getRawData() { 62 | return data; 63 | } 64 | 65 | // Parcelable 66 | protected ReadResponse(final Parcel in) { 67 | device = in.readParcelable(BluetoothDevice.class.getClassLoader()); 68 | data = in.readParcelable(Data.class.getClassLoader()); 69 | } 70 | 71 | @Override 72 | public void writeToParcel(final Parcel dest, final int flags) { 73 | dest.writeParcelable(device, flags); 74 | dest.writeParcelable(data, flags); 75 | } 76 | 77 | @Override 78 | public int describeContents() { 79 | return 0; 80 | } 81 | 82 | public static final Creator CREATOR = new Creator() { 83 | @Override 84 | public ReadResponse createFromParcel(final Parcel in) { 85 | return new ReadResponse(in); 86 | } 87 | 88 | @Override 89 | public ReadResponse[] newArray(final int size) { 90 | return new ReadResponse[size]; 91 | } 92 | }; 93 | } 94 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/response/RssiResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.response; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.IntRange; 30 | import androidx.annotation.NonNull; 31 | import androidx.annotation.Nullable; 32 | import no.nordicsemi.android.ble.callback.RssiCallback; 33 | 34 | @SuppressWarnings({"unused", "WeakerAccess"}) 35 | public class RssiResult implements RssiCallback, Parcelable { 36 | private BluetoothDevice device; 37 | 38 | @IntRange(from = -128, to = 20) 39 | private int rssi; 40 | 41 | @Override 42 | public void onRssiRead(@NonNull final BluetoothDevice device, 43 | @IntRange(from = -128, to = 20) final int rssi) { 44 | this.device = device; 45 | this.rssi = rssi; 46 | } 47 | 48 | @Nullable 49 | public BluetoothDevice getBluetoothDevice() { 50 | return device; 51 | } 52 | 53 | @IntRange(from = -128, to = 20) 54 | public int getRssi() { 55 | return rssi; 56 | } 57 | 58 | // Parcelable 59 | protected RssiResult(final Parcel in) { 60 | device = in.readParcelable(BluetoothDevice.class.getClassLoader()); 61 | rssi = in.readInt(); 62 | } 63 | 64 | @Override 65 | public void writeToParcel(final Parcel dest, final int flags) { 66 | dest.writeParcelable(device, flags); 67 | dest.writeInt(rssi); 68 | } 69 | 70 | @Override 71 | public int describeContents() { 72 | return 0; 73 | } 74 | 75 | public static final Creator CREATOR = new Creator() { 76 | @Override 77 | public RssiResult createFromParcel(final Parcel in) { 78 | return new RssiResult(in); 79 | } 80 | 81 | @Override 82 | public RssiResult[] newArray(final int size) { 83 | return new RssiResult[size]; 84 | } 85 | }; 86 | } 87 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/response/WriteResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.response; 24 | 25 | import android.bluetooth.BluetoothDevice; 26 | import android.os.Parcel; 27 | import android.os.Parcelable; 28 | 29 | import androidx.annotation.NonNull; 30 | import androidx.annotation.Nullable; 31 | import no.nordicsemi.android.ble.callback.DataSentCallback; 32 | import no.nordicsemi.android.ble.data.Data; 33 | 34 | /** 35 | * Generic write response class that returns the target device and the data that were sent. 36 | * Overriding class must call super on {@link #onDataSent(BluetoothDevice, Data)} in 37 | * order to make getters work properly. 38 | */ 39 | @SuppressWarnings({"unused", "WeakerAccess"}) 40 | public class WriteResponse implements DataSentCallback, Parcelable { 41 | private BluetoothDevice device; 42 | private Data data; 43 | 44 | @Override 45 | public void onDataSent(@NonNull final BluetoothDevice device, @NonNull final Data data) { 46 | this.device = device; 47 | this.data = data; 48 | } 49 | 50 | @Nullable 51 | public BluetoothDevice getBluetoothDevice() { 52 | return device; 53 | } 54 | 55 | @Nullable 56 | public Data getRawData() { 57 | return data; 58 | } 59 | 60 | // Parcelable 61 | protected WriteResponse(final Parcel in) { 62 | device = in.readParcelable(BluetoothDevice.class.getClassLoader()); 63 | data = in.readParcelable(Data.class.getClassLoader()); 64 | } 65 | 66 | @Override 67 | public void writeToParcel(final Parcel dest, final int flags) { 68 | dest.writeParcelable(device, flags); 69 | dest.writeParcelable(data, flags); 70 | } 71 | 72 | @Override 73 | public int describeContents() { 74 | return 0; 75 | } 76 | 77 | public static final Creator CREATOR = new Creator() { 78 | @Override 79 | public WriteResponse createFromParcel(final Parcel in) { 80 | return new WriteResponse(in); 81 | } 82 | 83 | @Override 84 | public WriteResponse[] newArray(final int size) { 85 | return new WriteResponse[size]; 86 | } 87 | }; 88 | } 89 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/utils/ILogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | package no.nordicsemi.android.ble.utils; 23 | 24 | import androidx.annotation.NonNull; 25 | import androidx.annotation.Nullable; 26 | import androidx.annotation.StringRes; 27 | 28 | @SuppressWarnings("unused") 29 | public interface ILogger { 30 | 31 | /** 32 | * Logs the given message with given log priority into the all managed devices' log session. 33 | * 34 | * @param priority the log priority. 35 | * @param message the message to be logged. 36 | */ 37 | void log(final int priority, @NonNull final String message); 38 | 39 | /** 40 | * Logs the given message with given log priority into the all managed devices' log session. 41 | * 42 | * @param priority the log priority. 43 | * @param messageRes string resource id. 44 | * @param params additional (optional) parameters used to fill the message. 45 | */ 46 | void log(final int priority, @StringRes final int messageRes, @Nullable final Object... params); 47 | } 48 | -------------------------------------------------------------------------------- /ble/src/main/java/no/nordicsemi/android/ble/utils/ParserUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | package no.nordicsemi.android.ble.utils; 23 | 24 | import android.bluetooth.BluetoothGattCharacteristic; 25 | import android.bluetooth.BluetoothGattDescriptor; 26 | 27 | @SuppressWarnings({"WeakerAccess", "unused"}) 28 | public class ParserUtils { 29 | protected final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); 30 | 31 | public static String parse(final BluetoothGattCharacteristic characteristic) { 32 | return parse(characteristic.getValue()); 33 | } 34 | 35 | public static String parse(final BluetoothGattDescriptor descriptor) { 36 | return parse(descriptor.getValue()); 37 | } 38 | 39 | public static String parse(final byte[] data) { 40 | if (data == null || data.length == 0) 41 | return ""; 42 | 43 | final char[] out = new char[data.length * 3 - 1]; 44 | for (int j = 0; j < data.length; j++) { 45 | int v = data[j] & 0xFF; 46 | out[j * 3] = HEX_ARRAY[v >>> 4]; 47 | out[j * 3 + 1] = HEX_ARRAY[v & 0x0F]; 48 | if (j != data.length - 1) 49 | out[j * 3 + 2] = '-'; 50 | } 51 | return "(0x) " + new String(out); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /ble/src/test/java/no/nordicsemi/android/ble/RequestTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble; 24 | 25 | import android.bluetooth.BluetoothGattCharacteristic; 26 | 27 | import org.junit.Before; 28 | import org.junit.Test; 29 | 30 | import java.util.UUID; 31 | 32 | import static org.junit.Assert.assertArrayEquals; 33 | import static org.junit.Assert.assertEquals; 34 | import static org.junit.Assert.assertFalse; 35 | import static org.junit.Assert.assertNotNull; 36 | import static org.junit.Assert.assertTrue; 37 | 38 | @SuppressWarnings("ConstantConditions") 39 | public class RequestTest { 40 | private final String text = 41 | "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + 42 | "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " + 43 | "nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis " + 44 | "aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat " + 45 | "nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " + 46 | "officia deserunt mollit anim id est laborum."; 47 | private final int MTU = 23; 48 | 49 | private BluetoothGattCharacteristic characteristic; 50 | private byte[] chunk; 51 | private boolean called; 52 | private boolean done; 53 | 54 | @Before 55 | public void init() { 56 | characteristic = new BluetoothGattCharacteristic(UUID.randomUUID(), BluetoothGattCharacteristic.PROPERTY_WRITE, BluetoothGattCharacteristic.PERMISSION_WRITE); 57 | } 58 | 59 | @Test 60 | public void split_basic() { 61 | final WriteRequest request = Request.newWriteRequest(characteristic, text.getBytes(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) 62 | .split(); 63 | chunk = request.getData(MTU); 64 | 65 | // Verify the chunk 66 | assertNotNull(chunk); 67 | assertEquals(MTU - 3, chunk.length); 68 | final String expected = text.substring(0, MTU - 3); 69 | assertArrayEquals(expected.getBytes(), chunk); 70 | } 71 | 72 | @Test 73 | public void split_highMtu() { 74 | final int MTU_HIGH = 276; 75 | 76 | final WriteRequest request = Request.newWriteRequest(characteristic, text.getBytes(), BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE) 77 | .split(); 78 | chunk = request.getData(MTU_HIGH); 79 | // Verify the chunk 80 | assertNotNull(chunk); 81 | assertEquals(MTU_HIGH - 3, chunk.length); 82 | final String expected = text.substring(0, MTU_HIGH - 3); 83 | assertArrayEquals(expected.getBytes(), chunk); 84 | } 85 | 86 | @Test 87 | public void split_callbacks() { 88 | // Create a WriteRequest with the default splitter and custom progress and success callbacks 89 | final WriteRequest request = Request.newWriteRequest(characteristic, text.getBytes(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) 90 | .split((device, data, index) -> { 91 | // Validate the progress callback 92 | called = true; 93 | assertNotNull(data); 94 | assertArrayEquals(chunk, data); 95 | assertTrue(data.length <= MTU - 3); 96 | }).done(device -> done = true); 97 | 98 | done = false; 99 | do { 100 | // Get next packet until null is returned 101 | called = false; 102 | chunk = request.getData(MTU); 103 | if (chunk != null) { 104 | // If there are bytes to send, let's assume they were sent: 105 | // Sending data... 106 | // Data sent 107 | 108 | // Notify request that the packet was sent. This will increment count value 109 | request.notifyPacketSent(null, chunk); 110 | assertTrue(called); 111 | } else { 112 | // Progress callback shouldn't be called without calling notifyPacketSent(...) 113 | assertFalse(called); 114 | } 115 | } while (request.hasMore()); 116 | 117 | // When there is nothing more to be sent notify about success 118 | request.notifySuccess(null); 119 | 120 | // Check if success callback was called 121 | assertTrue(done); 122 | } 123 | 124 | @Test 125 | public void split_merge() { 126 | // The WriteRequest is only to split the text into chunks 127 | final WriteRequest request = Request.newWriteRequest(characteristic, text.getBytes(), BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) 128 | .split(); 129 | 130 | // Create ReadRequest that will merge packets until the complete text is in the stream 131 | final ReadRequest readRequest = Request.newReadRequest(characteristic) 132 | .merge((output, lastPacket, index) -> { 133 | // Simply copy all bytes from the lastPacket to the stream 134 | output.write(lastPacket); 135 | return output.size() == text.length(); 136 | }, (device, data, index) -> { 137 | // Validate the progress callback 138 | called = true; 139 | assertNotNull(data); 140 | assertArrayEquals(chunk, data); 141 | assertTrue(data.length <= MTU - 3); 142 | }) 143 | .with((device, data) -> { 144 | // This should contain the whole data 145 | done = true; 146 | assertArrayEquals(text.getBytes(), data.getValue()); 147 | }) 148 | .done(device -> done = true); 149 | 150 | done = false; 151 | do { 152 | // Get next packet until null is returned 153 | called = false; 154 | chunk = request.getData(MTU); 155 | if (chunk != null) { 156 | // If there are bytes to send, let's assume they were sent: 157 | // Sending data... 158 | // Data sent 159 | 160 | // Notify request that the packet was sent. This will increment count value 161 | request.notifyPacketSent(null, chunk); 162 | 163 | // Having the chunk, let's pretend we just read it 164 | called = false; 165 | readRequest.notifyValueChanged(null, chunk); 166 | // Check if the progress callback was called with correct chunk 167 | assertTrue(called); 168 | } 169 | } while (request.hasMore()); 170 | // Verify that the data callback was called 171 | assertTrue(done); 172 | 173 | // Verify that the success callback is called 174 | called = false; 175 | done = false; 176 | readRequest.notifySuccess(null); 177 | assertTrue(done); 178 | } 179 | } -------------------------------------------------------------------------------- /ble/src/test/java/no/nordicsemi/android/ble/data/DataStreamTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import org.junit.Test; 26 | 27 | import static org.junit.Assert.assertArrayEquals; 28 | import static org.junit.Assert.assertEquals; 29 | 30 | public class DataStreamTest { 31 | 32 | @Test 33 | public void write() { 34 | final DataStream stream = new DataStream(); 35 | stream.write(new byte[] { 0, 1, 2, 3}); 36 | stream.write(new byte[] { 4, 5, 6}); 37 | assertArrayEquals(new byte[] { 0, 1, 2, 3, 4, 5, 6}, stream.toByteArray()); 38 | } 39 | 40 | @Test 41 | public void write_part() { 42 | final DataStream stream = new DataStream(); 43 | stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6}, 1, 2); 44 | assertArrayEquals(new byte[] { 1, 2}, stream.toByteArray()); 45 | } 46 | 47 | @Test 48 | public void write_data() { 49 | final DataStream stream = new DataStream(); 50 | final Data data1 = new Data(new byte[] { 0, 2, 4, 6, 8 }); 51 | final Data data2 = new Data(new byte[] { 1, 3, 5, 7, 9 }); 52 | stream.write(data1); 53 | stream.write(data2); 54 | assertArrayEquals(new byte[] { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9}, stream.toByteArray()); 55 | } 56 | 57 | @Test 58 | public void size() { 59 | final DataStream stream = new DataStream(); 60 | stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6}); 61 | assertEquals(7, stream.size()); 62 | } 63 | 64 | @SuppressWarnings("ConstantConditions") 65 | @Test 66 | public void toData() { 67 | final DataStream stream = new DataStream(); 68 | stream.write(new byte[] { 0, 1, 2, 3, 4, 5, 6}); 69 | final Data data = stream.toData(); 70 | assertEquals(0x100, data.getIntValue(Data.FORMAT_UINT16, 0).intValue()); 71 | } 72 | } -------------------------------------------------------------------------------- /ble/src/test/java/no/nordicsemi/android/ble/data/DefaultMtuSplitterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2018, Nordic Semiconductor 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | * 7 | * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | * 9 | * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * 12 | * 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 13 | * software without specific prior written permission. 14 | * 15 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 17 | * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 18 | * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 20 | * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 21 | */ 22 | 23 | package no.nordicsemi.android.ble.data; 24 | 25 | import org.junit.Test; 26 | 27 | import static org.junit.Assert.assertArrayEquals; 28 | import static org.junit.Assert.assertNull; 29 | 30 | public class DefaultMtuSplitterTest { 31 | private final String text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " + 32 | "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis " + 33 | "nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis " + 34 | "aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat " + 35 | "nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " + 36 | "officia deserunt mollit anim id est laborum."; 37 | 38 | @Test 39 | public void chunk_23() { 40 | final int MTU = 23; 41 | final DefaultMtuSplitter splitter = new DefaultMtuSplitter(); 42 | final byte[] result = splitter.chunk(text.getBytes(), 1, MTU - 3); 43 | assertArrayEquals(text.substring(MTU - 3, 2 * (MTU - 3)).getBytes(), result); 44 | } 45 | 46 | @Test 47 | public void chunk_43() { 48 | final int MTU = 43; 49 | final DefaultMtuSplitter splitter = new DefaultMtuSplitter(); 50 | final byte[] result = splitter.chunk(text.getBytes(), 2, MTU - 3); 51 | assertArrayEquals(text.substring(2 * (MTU - 3), 3 * (MTU - 3)).getBytes(), result); 52 | } 53 | 54 | @Test 55 | public void chunk_end() { 56 | final int MTU = 23; 57 | final DefaultMtuSplitter splitter = new DefaultMtuSplitter(); 58 | final byte[] result = splitter.chunk(text.getBytes(), 200, MTU - 3); 59 | assertNull(result); 60 | } 61 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.3.3' 11 | /* 12 | classpath "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4" 13 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 14 | */ 15 | // NOTE: Do not place your application dependencies here; they belong 16 | // in the individual module build.gradle files 17 | } 18 | } 19 | 20 | allprojects { 21 | repositories { 22 | google() 23 | mavenCentral() 24 | } 25 | } 26 | 27 | task clean(type: Delete) { 28 | delete rootProject.buildDir 29 | } 30 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | android.enableJetifier=true 15 | android.useAndroidX=true 16 | 17 | # When configured, Gradle will run in incubating parallel mode. 18 | # This option should only be used with decoupled projects. More details, visit 19 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 20 | # org.gradle.parallel=true 21 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fbiego/Android-BLE-Library/9b063a3738d372eb9d51c9208f98fa4b5a0025e2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Feb 01 10:44:39 CET 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':ble' --------------------------------------------------------------------------------