├── .gitignore
├── .idea
├── .gitignore
├── compiler.xml
├── gradle.xml
├── misc.xml
└── vcs.xml
├── LICENSE.md
├── README.md
├── blex
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── se
│ │ └── hellsoft
│ │ └── blex
│ │ ├── BondingHelper.kt
│ │ ├── ChannelBluetoothGattCallback.kt
│ │ ├── GattCallback.kt
│ │ ├── GattDevice.kt
│ │ ├── GattEvents.kt
│ │ ├── GattTypes.kt
│ │ └── bluetoothDevice.kt
│ └── test
│ └── java
│ └── se
│ └── hellsoft
│ └── blex
│ ├── BluetoothMocks.kt
│ └── GattDeviceTests.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 Erik Hellman
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A wrapper for the Bluetooth GATT system API on Android
2 |
3 | This library wraps the system API for BLE (`BluetoothGatt` etc.) in a more convenient and safer API
4 | for use in apps. It solves the common problems one regularly have with BLE on Android, like race
5 | conditions, queueing commands, and blocking of binder threads.
6 |
--------------------------------------------------------------------------------
/blex/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/blex/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'maven-publish'
5 | }
6 |
7 | android {
8 | namespace 'se.hellsoft.blex'
9 | compileSdk 33
10 |
11 | defaultConfig {
12 | minSdk 26
13 | targetSdk 33
14 | versionCode 1
15 | versionName "1.0"
16 | aarMetadata {
17 | minCompileSdk = 33
18 | }
19 |
20 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
21 | }
22 |
23 | buildTypes {
24 | release {
25 | minifyEnabled false
26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
27 | }
28 | }
29 |
30 | compileOptions {
31 | sourceCompatibility JavaVersion.VERSION_11
32 | targetCompatibility JavaVersion.VERSION_11
33 | }
34 |
35 | kotlinOptions {
36 | jvmTarget = '11'
37 | }
38 |
39 | publishing {
40 | singleVariant('release') {
41 | withSourcesJar()
42 | withJavadocJar()
43 | }
44 | }
45 | }
46 |
47 | afterEvaluate {
48 | publishing {
49 | publications {
50 | release(MavenPublication) {
51 | from components.release
52 | groupId = 'se.hellsoft'
53 | artifactId = 'blex'
54 | version = android.defaultConfig.versionName // or manually '1.0'
55 | }
56 | }
57 | }
58 | }
59 |
60 | dependencies {
61 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
62 | implementation 'androidx.annotation:annotation:1.5.0'
63 |
64 | testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4'
65 | testImplementation 'junit:junit:4.13.2'
66 | testImplementation "io.mockk:mockk:1.13.2"
67 | }
--------------------------------------------------------------------------------
/blex/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
--------------------------------------------------------------------------------
/blex/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/BondingHelper.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("unused")
2 |
3 | package se.hellsoft.blex
4 |
5 | import android.bluetooth.BluetoothDevice
6 | import android.bluetooth.BluetoothDevice.*
7 | import android.content.BroadcastReceiver
8 | import android.content.Context
9 | import android.content.Intent
10 | import android.content.IntentFilter
11 | import android.os.Build
12 | import androidx.annotation.RequiresPermission
13 | import kotlinx.coroutines.channels.awaitClose
14 | import kotlinx.coroutines.channels.trySendBlocking
15 | import kotlinx.coroutines.flow.Flow
16 | import kotlinx.coroutines.flow.callbackFlow
17 | import kotlinx.coroutines.flow.onStart
18 | import java.lang.reflect.Method
19 |
20 | @RequiresPermission(anyOf = ["android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH"])
21 | fun BluetoothDevice.releaseBond() {
22 | val method: Method = this.javaClass.getMethod("removeBond")
23 | method.invoke(this)
24 | }
25 |
26 | data class BondState(val device: BluetoothDevice, val state: Int)
27 |
28 | @RequiresPermission(anyOf = ["android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH"])
29 | fun BluetoothDevice.createBond(context: Context): Flow {
30 | return bondedState(context).onStart { createBond() }
31 | }
32 |
33 | @RequiresPermission(anyOf = ["android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH"])
34 | fun BluetoothDevice.bondedState(context: Context): Flow {
35 | return callbackFlow {
36 | val receiver = object : BroadcastReceiver() {
37 | override fun onReceive(context: Context, data: Intent) {
38 | val bondState = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
39 | BondState(
40 | data.getParcelableExtra(EXTRA_DEVICE, BluetoothDevice::class.java)!!,
41 | data.getIntExtra(EXTRA_BOND_STATE, BOND_NONE)
42 | )
43 |
44 | } else {
45 | @Suppress("DEPRECATION")
46 | BondState(
47 | data.getParcelableExtra(EXTRA_DEVICE)!!,
48 | data.getIntExtra(EXTRA_BOND_STATE, BOND_NONE)
49 | )
50 | }
51 | trySendBlocking(bondState)
52 | }
53 | }
54 | val filter = IntentFilter(ACTION_BOND_STATE_CHANGED)
55 | context.registerReceiver(receiver, filter)
56 | trySendBlocking(
57 | BondState(
58 | this@bondedState,
59 | this@bondedState.bondState
60 | )
61 | )
62 |
63 | awaitClose { context.unregisterReceiver(receiver) }
64 | }
65 | }
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/ChannelBluetoothGattCallback.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.bluetooth.BluetoothGatt
4 | import android.bluetooth.BluetoothGattCallback
5 | import android.bluetooth.BluetoothGattCharacteristic
6 | import android.bluetooth.BluetoothGattDescriptor
7 | import kotlinx.coroutines.channels.Channel
8 | import kotlinx.coroutines.channels.Channel.Factory.BUFFERED
9 | import kotlinx.coroutines.channels.ReceiveChannel
10 | import java.lang.IllegalStateException
11 |
12 | @Suppress("OVERRIDE_DEPRECATION", "DEPRECATION")
13 | class ChannelBluetoothGattCallback : BluetoothGattCallback() {
14 | private val events = Channel(BUFFERED)
15 | val receiveEvents: ReceiveChannel = events
16 |
17 | private fun sendOrThrow(event: GattEvent) {
18 | val result = events.trySend(event)
19 | if (!result.isSuccess) {
20 | throw IllegalStateException("Overflow or closed output: $result")
21 | }
22 | }
23 |
24 | override fun onPhyUpdate(gatt: BluetoothGatt?, txPhy: Int, rxPhy: Int, status: Int) {
25 | val phyUpdate = PhyUpdate(txPhy, rxPhy, status)
26 | sendOrThrow(phyUpdate)
27 | }
28 |
29 | override fun onPhyRead(gatt: BluetoothGatt, txPhy: Int, rxPhy: Int, status: Int) {
30 | val phyRead = PhyRead(txPhy, rxPhy, status)
31 | sendOrThrow(phyRead)
32 | }
33 |
34 | override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
35 | val connectionChanged =
36 | ConnectionChanged(status, ConnectionState.fromState(newState))
37 | sendOrThrow(connectionChanged)
38 | }
39 |
40 | override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
41 | val servicesDiscovered = ServicesDiscovered(status)
42 | sendOrThrow(servicesDiscovered)
43 | }
44 |
45 | override fun onCharacteristicRead(
46 | gatt: BluetoothGatt,
47 | characteristic: BluetoothGattCharacteristic,
48 | value: ByteArray,
49 | status: Int
50 | ) {
51 | val characteristicRead = CharacteristicRead(
52 | GattCharacteristic(characteristic),
53 | value,
54 | status
55 | )
56 | sendOrThrow(characteristicRead)
57 | }
58 |
59 | override fun onCharacteristicWrite(
60 | gatt: BluetoothGatt,
61 | characteristic: BluetoothGattCharacteristic,
62 | status: Int
63 | ) {
64 | val characteristicWritten = CharacteristicWritten(
65 | GattCharacteristic(characteristic),
66 | status
67 | )
68 | sendOrThrow(characteristicWritten)
69 | }
70 |
71 | override fun onCharacteristicChanged(
72 | gatt: BluetoothGatt,
73 | characteristic: BluetoothGattCharacteristic,
74 | value: ByteArray
75 | ) {
76 | val characteristicChanged = CharacteristicChanged(
77 | GattCharacteristic(characteristic),
78 | value
79 | )
80 | sendOrThrow(characteristicChanged)
81 | }
82 |
83 | override fun onDescriptorRead(
84 | gatt: BluetoothGatt,
85 | descriptor: BluetoothGattDescriptor,
86 | status: Int,
87 | value: ByteArray
88 | ) {
89 | val descriptorRead = DescriptorRead(
90 | GattCharacteristic(descriptor.characteristic),
91 | GattDescriptor(descriptor),
92 | value,
93 | status
94 | )
95 | sendOrThrow(descriptorRead)
96 | }
97 |
98 | override fun onDescriptorWrite(
99 | gatt: BluetoothGatt,
100 | descriptor: BluetoothGattDescriptor,
101 | status: Int
102 | ) {
103 | val descriptorWritten = DescriptorWritten(
104 | GattCharacteristic(descriptor.characteristic),
105 | descriptor.uuid,
106 | status
107 | )
108 | sendOrThrow(descriptorWritten)
109 | }
110 |
111 | override fun onCharacteristicRead(
112 | gatt: BluetoothGatt,
113 | characteristic: BluetoothGattCharacteristic,
114 | status: Int
115 | ) {
116 | val characteristicRead = CharacteristicRead(
117 | GattCharacteristic(characteristic),
118 | characteristic.value,
119 | status
120 | )
121 | sendOrThrow(characteristicRead)
122 | }
123 |
124 | override fun onCharacteristicChanged(
125 | gatt: BluetoothGatt,
126 | characteristic: BluetoothGattCharacteristic
127 | ) {
128 | val characteristicChanged = CharacteristicChanged(
129 | GattCharacteristic(characteristic),
130 | characteristic.value
131 | )
132 | sendOrThrow(characteristicChanged)
133 | }
134 |
135 | override fun onDescriptorRead(
136 | gatt: BluetoothGatt,
137 | descriptor: BluetoothGattDescriptor,
138 | status: Int
139 | ) {
140 | val descriptorRead = DescriptorRead(
141 | GattCharacteristic(descriptor.characteristic),
142 | GattDescriptor(descriptor),
143 | descriptor.value,
144 | status
145 | )
146 | sendOrThrow(descriptorRead)
147 | }
148 |
149 | override fun onReliableWriteCompleted(gatt: BluetoothGatt?, status: Int) {
150 | val reliableWriteCompleted = ReliableWriteCompleted(status)
151 | sendOrThrow(reliableWriteCompleted)
152 | }
153 |
154 | override fun onReadRemoteRssi(gatt: BluetoothGatt?, rssi: Int, status: Int) {
155 | val readRemoteRssi = ReadRemoteRssi(rssi, status)
156 | sendOrThrow(readRemoteRssi)
157 | }
158 |
159 | override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
160 | val mtuChanged = MtuChanged(mtu, status)
161 | sendOrThrow(mtuChanged)
162 | }
163 |
164 | override fun onServiceChanged(gatt: BluetoothGatt) {
165 | val serviceChanged = ServiceChanged
166 | sendOrThrow(serviceChanged)
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/GattCallback.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.bluetooth.BluetoothGatt
4 | import android.bluetooth.BluetoothGattCallback
5 | import android.bluetooth.BluetoothGattCharacteristic
6 | import android.bluetooth.BluetoothGattDescriptor
7 | import android.util.Log
8 | import kotlinx.coroutines.flow.Flow
9 | import kotlinx.coroutines.flow.MutableSharedFlow
10 |
11 | @Suppress("OVERRIDE_DEPRECATION", "DEPRECATION")
12 | internal class GattCallback(
13 | bufferCapacity: Int,
14 | private val logger: ((level: Int, message: String, throwable: Throwable?) -> Unit)? = null,
15 | private val servicesChanged: (gatt: BluetoothGatt) -> Unit
16 | ) : BluetoothGattCallback() {
17 | internal val events: Flow = MutableSharedFlow(bufferCapacity)
18 | private val mutableEvents = events as MutableSharedFlow
19 |
20 | override fun onPhyUpdate(gatt: BluetoothGatt?, txPhy: Int, rxPhy: Int, status: Int) {
21 | val phyUpdate = PhyUpdate(txPhy, rxPhy, status)
22 | logger?.invoke(Log.INFO, "onPhyUpdate: $phyUpdate", null)
23 | mutableEvents.tryEmit(phyUpdate)
24 | }
25 |
26 | override fun onPhyRead(gatt: BluetoothGatt, txPhy: Int, rxPhy: Int, status: Int) {
27 | val phyRead = PhyRead(txPhy, rxPhy, status)
28 | logger?.invoke(Log.INFO, "onPhyRead: $phyRead", null)
29 | mutableEvents.tryEmit(phyRead)
30 | }
31 |
32 | override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
33 | val connectionChanged = ConnectionChanged(status, ConnectionState.fromState(newState))
34 | logger?.invoke(Log.INFO, "onConnectionStateChange: $connectionChanged", null)
35 | mutableEvents.tryEmit(connectionChanged)
36 | }
37 |
38 | override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
39 | val servicesDiscovered = ServicesDiscovered(status)
40 | logger?.invoke(Log.INFO, "onServicesDiscovered: $servicesDiscovered", null)
41 | mutableEvents.tryEmit(servicesDiscovered)
42 | servicesChanged(gatt)
43 | }
44 |
45 | override fun onCharacteristicRead(
46 | gatt: BluetoothGatt,
47 | characteristic: BluetoothGattCharacteristic,
48 | value: ByteArray,
49 | status: Int
50 | ) {
51 | val characteristicRead = CharacteristicRead(
52 | GattCharacteristic(characteristic),
53 | value,
54 | status
55 | )
56 | logger?.invoke(Log.INFO, "onCharacteristicRead: $characteristicRead", null)
57 | mutableEvents.tryEmit(characteristicRead)
58 | }
59 |
60 | override fun onCharacteristicWrite(
61 | gatt: BluetoothGatt,
62 | characteristic: BluetoothGattCharacteristic,
63 | status: Int
64 | ) {
65 | val characteristicWritten = CharacteristicWritten(
66 | GattCharacteristic(characteristic),
67 | status
68 | )
69 | logger?.invoke(Log.INFO, "onCharacteristicWrite: $characteristicWritten", null)
70 | mutableEvents.tryEmit(characteristicWritten)
71 | }
72 |
73 | override fun onCharacteristicChanged(
74 | gatt: BluetoothGatt,
75 | characteristic: BluetoothGattCharacteristic,
76 | value: ByteArray
77 | ) {
78 | val characteristicChanged = CharacteristicChanged(
79 | GattCharacteristic(characteristic),
80 | value
81 | )
82 | logger?.invoke(Log.INFO, "onCharacteristicChanged: $characteristicChanged", null)
83 | mutableEvents.tryEmit(characteristicChanged)
84 | }
85 |
86 | override fun onDescriptorRead(
87 | gatt: BluetoothGatt,
88 | descriptor: BluetoothGattDescriptor,
89 | status: Int,
90 | value: ByteArray
91 | ) {
92 | val descriptorRead = DescriptorRead(
93 | GattCharacteristic(descriptor.characteristic),
94 | GattDescriptor(descriptor),
95 | value,
96 | status
97 | )
98 | logger?.invoke(Log.INFO, "onDescriptorRead: $descriptorRead", null)
99 | mutableEvents.tryEmit(descriptorRead)
100 | }
101 |
102 | override fun onDescriptorWrite(
103 | gatt: BluetoothGatt,
104 | descriptor: BluetoothGattDescriptor,
105 | status: Int
106 | ) {
107 | val descriptorWritten = DescriptorWritten(
108 | GattCharacteristic(descriptor.characteristic),
109 | descriptor.uuid,
110 | status
111 | )
112 | logger?.invoke(Log.INFO, "onDescriptorWrite: $descriptorWritten", null)
113 | mutableEvents.tryEmit(descriptorWritten)
114 | }
115 |
116 | override fun onCharacteristicRead(
117 | gatt: BluetoothGatt,
118 | characteristic: BluetoothGattCharacteristic,
119 | status: Int
120 | ) {
121 | val characteristicRead = CharacteristicRead(
122 | GattCharacteristic(characteristic),
123 | characteristic.value,
124 | status
125 | )
126 | logger?.invoke(Log.INFO, "onCharacteristicRead: $characteristicRead", null)
127 | mutableEvents.tryEmit(characteristicRead)
128 | }
129 |
130 | override fun onCharacteristicChanged(
131 | gatt: BluetoothGatt,
132 | characteristic: BluetoothGattCharacteristic
133 | ) {
134 | val characteristicChanged = CharacteristicChanged(
135 | GattCharacteristic(characteristic),
136 | characteristic.value
137 | )
138 | logger?.invoke(Log.INFO, "onCharacteristicChanged: $characteristicChanged", null)
139 | mutableEvents.tryEmit(characteristicChanged)
140 | }
141 |
142 | override fun onDescriptorRead(
143 | gatt: BluetoothGatt,
144 | descriptor: BluetoothGattDescriptor,
145 | status: Int
146 | ) {
147 | val descriptorRead = DescriptorRead(
148 | GattCharacteristic(descriptor.characteristic),
149 | GattDescriptor(descriptor),
150 | descriptor.value,
151 | status
152 | )
153 | logger?.invoke(Log.INFO, "onDescriptorRead: $descriptorRead", null)
154 | mutableEvents.tryEmit(descriptorRead)
155 | }
156 |
157 | override fun onReliableWriteCompleted(gatt: BluetoothGatt?, status: Int) {
158 | val reliableWriteCompleted = ReliableWriteCompleted(status)
159 | logger?.invoke(Log.INFO, "onReliableWriteCompleted: $reliableWriteCompleted", null)
160 | mutableEvents.tryEmit(reliableWriteCompleted)
161 | }
162 |
163 | override fun onReadRemoteRssi(gatt: BluetoothGatt?, rssi: Int, status: Int) {
164 | val readRemoteRssi = ReadRemoteRssi(rssi, status)
165 | logger?.invoke(Log.INFO, "onReadRemoteRssi: $readRemoteRssi", null)
166 | mutableEvents.tryEmit(readRemoteRssi)
167 | }
168 |
169 | override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) {
170 | val mtuChanged = MtuChanged(mtu, status)
171 | logger?.invoke(Log.INFO, "onMtuChanged: $mtuChanged", null)
172 | mutableEvents.tryEmit(mtuChanged)
173 | }
174 |
175 | override fun onServiceChanged(gatt: BluetoothGatt) {
176 | val serviceChanged = ServiceChanged
177 | logger?.invoke(Log.INFO, "onServiceChanged: $serviceChanged", null)
178 | mutableEvents.tryEmit(serviceChanged)
179 | servicesChanged(gatt)
180 | }
181 | }
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/GattDevice.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.Manifest.permission.BLUETOOTH
4 | import android.Manifest.permission.BLUETOOTH_CONNECT
5 | import android.annotation.SuppressLint
6 | import android.bluetooth.BluetoothDevice
7 | import android.bluetooth.BluetoothGatt
8 | import android.bluetooth.BluetoothGattCharacteristic
9 | import android.bluetooth.BluetoothGattDescriptor
10 | import android.content.Context
11 | import android.os.Build
12 | import android.util.Log
13 | import androidx.annotation.RequiresPermission
14 | import kotlinx.coroutines.CoroutineScope
15 | import kotlinx.coroutines.CoroutineStart
16 | import kotlinx.coroutines.channels.ReceiveChannel
17 | import kotlinx.coroutines.flow.MutableSharedFlow
18 | import kotlinx.coroutines.flow.MutableStateFlow
19 | import kotlinx.coroutines.flow.StateFlow
20 | import kotlinx.coroutines.flow.first
21 | import kotlinx.coroutines.flow.mapNotNull
22 | import kotlinx.coroutines.flow.onStart
23 | import kotlinx.coroutines.launch
24 | import kotlinx.coroutines.sync.Mutex
25 | import kotlinx.coroutines.sync.withLock
26 | import kotlinx.coroutines.withTimeoutOrNull
27 | import java.lang.IllegalStateException
28 | import java.util.UUID
29 | import kotlin.time.Duration.Companion.seconds
30 |
31 | val DEFAULT_GATT_TIMEOUT = 5.seconds
32 |
33 | @SuppressLint("InlinedApi")
34 | interface GattDevice {
35 | companion object {
36 | val ClientCharacteristicConfigurationID: UUID =
37 | UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
38 | }
39 |
40 | val connectionState: StateFlow
41 | val services: StateFlow>
42 |
43 | suspend fun discoverServices(): ServicesDiscovered
44 |
45 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
46 | suspend fun registerNotifications(
47 | characteristic: GattCharacteristic,
48 | descriptor: UUID = ClientCharacteristicConfigurationID
49 | ): Boolean
50 |
51 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
52 | suspend fun unregisterNotifications(
53 | characteristic: GattCharacteristic,
54 | descriptor: UUID = ClientCharacteristicConfigurationID
55 | ): Boolean
56 |
57 | /**
58 | * Write a new value to the specified GATT characteristic.
59 | *
60 | * @param characteristic The target for the write operations
61 | * @param value The value to write to the characteristic
62 | * @param writeType The type of write operation
63 | * @return The result of the write operation
64 | */
65 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
66 | suspend fun writeCharacteristic(
67 | characteristic: GattCharacteristic,
68 | value: ByteArray,
69 | writeType: Int = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
70 | ): CharacteristicWritten
71 |
72 | /**
73 | * Read from a characteristic.
74 | *
75 | * @param characteristic The characteristic to read from
76 | * @return The result of the read operation, including the value read if successful.
77 | */
78 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
79 | suspend fun readCharacteristic(characteristic: GattCharacteristic): CharacteristicRead
80 |
81 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
82 | suspend fun writeDescriptor(
83 | characteristic: GattCharacteristic,
84 | descriptor: GattDescriptor,
85 | value: ByteArray
86 | ): DescriptorWritten
87 |
88 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
89 | suspend fun readDescriptor(
90 | characteristic: GattCharacteristic,
91 | descriptor: GattDescriptor,
92 | ): DescriptorRead
93 |
94 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
95 | suspend fun readMtu(mtu: Int): MtuChanged
96 |
97 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
98 | suspend fun readPhy(): PhyRead
99 |
100 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
101 | suspend fun setPreferredPhy(txPhy: Int, rxPhy: Int, phyOptions: Int): PhyUpdate
102 |
103 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
104 | suspend fun readRemoteRssi(): ReadRemoteRssi
105 | }
106 |
107 | @SuppressLint("InlinedApi")
108 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
109 | fun ConnectedGattDevice(
110 | scope: CoroutineScope,
111 | bluetoothDevice: BluetoothDevice,
112 | context: Context,
113 | transport: Int = BluetoothDevice.TRANSPORT_LE,
114 | phy: Int = BluetoothDevice.PHY_LE_1M,
115 | eventBufferCapacity: Int = 10,
116 | logger: ((level: Int, message: String, throwable: Throwable?) -> Unit) =
117 | { _, _, _ -> },
118 | ): GattDevice {
119 | val (bluetoothGatt, gattEvents) = bluetoothDevice.connectGattIn(
120 | context,
121 | scope,
122 | transport,
123 | phy
124 | )
125 |
126 | return GattDeviceImpl(scope, bluetoothGatt, gattEvents, eventBufferCapacity, logger)
127 | }
128 |
129 | @SuppressLint("InlinedApi")
130 | internal class GattDeviceImpl(
131 | scope: CoroutineScope,
132 | private val bluetoothGatt: BluetoothGatt,
133 | gattEvents: ReceiveChannel,
134 | eventBufferCapacity: Int,
135 | private val logger: ((level: Int, message: String, throwable: Throwable?) -> Unit),
136 | ) : GattDevice {
137 | override val connectionState: StateFlow
138 | override val services: StateFlow>
139 |
140 | /* :scream: */
141 | private val eventBus = MutableSharedFlow(extraBufferCapacity = eventBufferCapacity)
142 | private val eventBusMutex = Mutex()
143 |
144 | init {
145 | connectionState = MutableStateFlow(ConnectionState.Disconnected)
146 | services = MutableStateFlow(emptyList())
147 |
148 | scope.launch(start = CoroutineStart.UNDISPATCHED) {
149 | for (gattEvent in gattEvents) {
150 | logEvent(gattEvent, logger)
151 | when (gattEvent) {
152 | is ConnectionChanged -> connectionState.value = gattEvent.newState
153 | is ServicesDiscovered -> services.value =
154 | bluetoothGatt.services.map { GattService(it) }
155 |
156 | else -> {}
157 | }
158 | eventBus.emitOrThrow(gattEvent)
159 | }
160 | }
161 | }
162 |
163 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
164 | override suspend fun discoverServices(): ServicesDiscovered =
165 | callGattDevice("discoverServices", { bluetoothGatt.discoverServices() }) {
166 | it as? ServicesDiscovered
167 | }
168 |
169 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
170 | override suspend fun registerNotifications(
171 | characteristic: GattCharacteristic,
172 | descriptor: UUID
173 | ): Boolean = updateNotifications(characteristic, descriptor, enable = true)
174 |
175 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
176 | override suspend fun unregisterNotifications(
177 | characteristic: GattCharacteristic,
178 | descriptor: UUID
179 | ): Boolean = updateNotifications(characteristic, descriptor, enable = false)
180 |
181 | @Suppress("DEPRECATION")
182 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
183 | private suspend fun updateNotifications(
184 | characteristic: GattCharacteristic,
185 | descriptor: UUID,
186 | enable: Boolean
187 | ): Boolean {
188 | val value =
189 | if (enable) BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE else BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
190 | val targetDesc =
191 | characteristic.descriptors.find { it.id == descriptor }?.bluetoothGattDescriptor
192 | ?: return false
193 | val result = callGattDevice(
194 | "updateNotifications: ${if (enable) "enable" else "disable"}",
195 | {
196 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
197 | bluetoothGatt.writeDescriptor(targetDesc, value)
198 | } else {
199 | targetDesc.value = value
200 | bluetoothGatt.writeDescriptor(targetDesc)
201 | }
202 | }
203 | ) {
204 | it as? DescriptorWritten
205 | }
206 |
207 | return result.status == BluetoothGatt.GATT_SUCCESS
208 | }
209 |
210 | @Suppress("DEPRECATION")
211 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
212 | override suspend fun writeCharacteristic(
213 | characteristic: GattCharacteristic,
214 | value: ByteArray,
215 | writeType: Int
216 | ): CharacteristicWritten =
217 | callGattDevice(
218 | "writeCharacteristic",
219 | {
220 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
221 | bluetoothGatt.writeCharacteristic(
222 | characteristic.bluetoothGattCharacteristic,
223 | value,
224 | writeType
225 | )
226 | } else {
227 | characteristic.bluetoothGattCharacteristic.writeType = writeType
228 | characteristic.bluetoothGattCharacteristic.value = value
229 | bluetoothGatt.writeCharacteristic(characteristic.bluetoothGattCharacteristic)
230 | }
231 | }
232 | ) {
233 | (it as? CharacteristicWritten)?.takeIf {
234 | it.characteristic.instanceId == characteristic.instanceId
235 | }
236 | }
237 |
238 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
239 | override suspend fun readCharacteristic(characteristic: GattCharacteristic): CharacteristicRead =
240 | callGattDevice(
241 | "readCharacteristic",
242 | { bluetoothGatt.readCharacteristic(characteristic.bluetoothGattCharacteristic) }
243 | ) {
244 | (it as? CharacteristicRead)?.takeIf {
245 | it.characteristic.instanceId == characteristic.instanceId
246 | }
247 | }
248 |
249 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
250 | override suspend fun writeDescriptor(
251 | characteristic: GattCharacteristic,
252 | descriptor: GattDescriptor,
253 | value: ByteArray
254 | ): DescriptorWritten =
255 | callGattDevice(
256 | "writeDescriptor",
257 | {
258 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
259 | bluetoothGatt.writeDescriptor(descriptor.bluetoothGattDescriptor, value)
260 | } else {
261 | descriptor.bluetoothGattDescriptor.value = value
262 | bluetoothGatt.writeDescriptor(descriptor.bluetoothGattDescriptor)
263 | }
264 |
265 | }
266 | ) {
267 | (it as? DescriptorWritten)?.takeIf { it.descriptorId == descriptor.id }
268 | }
269 |
270 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
271 | override suspend fun readDescriptor(
272 | characteristic: GattCharacteristic,
273 | descriptor: GattDescriptor
274 | ): DescriptorRead =
275 | callGattDevice("readDescriptor", { bluetoothGatt.readDescriptor(descriptor.bluetoothGattDescriptor) }) {
276 | (it as? DescriptorRead)?.takeIf {
277 | it.descriptor.id == descriptor.id &&
278 | it.characteristic.instanceId == characteristic.instanceId
279 | }
280 | }
281 |
282 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
283 | override suspend fun readMtu(mtu: Int): MtuChanged =
284 | callGattDevice("readMtu", { bluetoothGatt.requestMtu(mtu) }) { it as? MtuChanged }
285 |
286 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
287 | override suspend fun readPhy(): PhyRead =
288 | callGattDevice("readPhy", { bluetoothGatt.readPhy() }) { it as? PhyRead }
289 |
290 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
291 | override suspend fun setPreferredPhy(txPhy: Int, rxPhy: Int, phyOptions: Int): PhyUpdate =
292 | callGattDevice("setPreferredPhy", { bluetoothGatt.setPreferredPhy(txPhy, rxPhy, phyOptions) }) {
293 | it as? PhyUpdate
294 | }
295 |
296 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
297 | override suspend fun readRemoteRssi(): ReadRemoteRssi =
298 | callGattDevice("readRemoteRssi", { bluetoothGatt.readRemoteRssi() }) { it as? ReadRemoteRssi }
299 |
300 | private suspend fun callGattDevice(
301 | action: String,
302 | gattCall: () -> Unit,
303 | filter: (GattEvent) -> T?
304 | ): T = eventBusMutex.withLock {
305 | withTimeoutOrNull(DEFAULT_GATT_TIMEOUT) {
306 | try {
307 | connectionState.first { it == ConnectionState.Connected }
308 | eventBus
309 | .onStart {
310 | logger(Log.DEBUG, "try: $action", null)
311 | gattCall()
312 | }
313 | .mapNotNull { filter(it) }
314 | .first()
315 | } catch (e: Exception) {
316 | logger(Log.ERROR, "error: $action", null)
317 | throw e
318 | }
319 | } ?: throw IllegalStateException("Gatt timeout")
320 | }
321 |
322 | private fun logEvent(
323 | event: GattEvent,
324 | logger: ((level: Int, message: String, throwable: Throwable?) -> Unit)
325 | ) {
326 | val desc = when (event) {
327 | is ServicesDiscovered -> "onServicesDiscovered"
328 | is CharacteristicRead -> "onCharacteristicRead"
329 | is CharacteristicWritten -> "onCharacteristicWritten"
330 | is DescriptorRead -> "onDescriptorRead"
331 | is DescriptorWritten -> "onDescriptorWritten"
332 | is MtuChanged -> "onMtuChanged"
333 | is PhyRead -> "onPhyRead"
334 | is PhyUpdate -> "onPhyUpdate"
335 | is ReadRemoteRssi -> "onReadRemoteRssi"
336 | else -> "onUnknownEvent"
337 | }
338 | logger(Log.INFO, "$desc: $event", null)
339 | }
340 | }
341 |
342 | private fun MutableSharedFlow.emitOrThrow(item: T) {
343 | if (!tryEmit(item)) throw IllegalStateException("Buffer overflow")
344 | }
345 |
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/GattEvents.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.bluetooth.BluetoothProfile
4 | import java.util.UUID
5 |
6 | enum class ConnectionState(val state: Int) {
7 | Connected(BluetoothProfile.STATE_CONNECTED),
8 | Connecting(BluetoothProfile.STATE_CONNECTING),
9 | Disconnected(BluetoothProfile.STATE_DISCONNECTED),
10 | Disconnecting(BluetoothProfile.STATE_DISCONNECTING);
11 |
12 | companion object {
13 | fun fromState(state: Int): ConnectionState {
14 | return when (state) {
15 | BluetoothProfile.STATE_CONNECTED -> Connected
16 | BluetoothProfile.STATE_CONNECTING -> Connecting
17 | BluetoothProfile.STATE_DISCONNECTED -> Disconnected
18 | BluetoothProfile.STATE_DISCONNECTING -> Disconnecting
19 | else -> throw IllegalArgumentException("Illegal connection state $state")
20 | }
21 | }
22 | }
23 | }
24 |
25 | sealed class GattEvent
26 |
27 | data class ConnectionChanged(
28 | val status: Int,
29 | val newState: ConnectionState,
30 | ) : GattEvent()
31 |
32 | data class ServicesDiscovered(val status: Int) : GattEvent()
33 |
34 | data class CharacteristicChanged(
35 | val characteristics: GattCharacteristic,
36 | val value: ByteArray
37 | ) : GattEvent() {
38 | override fun equals(other: Any?): Boolean {
39 | if (this === other) return true
40 | if (javaClass != other?.javaClass) return false
41 |
42 | other as CharacteristicChanged
43 |
44 | if (characteristics != other.characteristics) return false
45 | if (!value.contentEquals(other.value)) return false
46 |
47 | return true
48 | }
49 |
50 | override fun hashCode(): Int {
51 | var result = characteristics.hashCode()
52 | result = 31 * result + value.contentHashCode()
53 | return result
54 | }
55 | }
56 |
57 | data class CharacteristicRead(
58 | val characteristic: GattCharacteristic,
59 | val value: ByteArray,
60 | val status: Int
61 | ) : GattEvent() {
62 | override fun equals(other: Any?): Boolean {
63 | if (this === other) return true
64 | if (javaClass != other?.javaClass) return false
65 |
66 | other as CharacteristicRead
67 |
68 | if (characteristic != other.characteristic) return false
69 | if (!value.contentEquals(other.value)) return false
70 | if (status != other.status) return false
71 |
72 | return true
73 | }
74 |
75 | override fun hashCode(): Int {
76 | var result = characteristic.hashCode()
77 | result = 31 * result + value.contentHashCode()
78 | result = 31 * result + status
79 | return result
80 | }
81 | }
82 |
83 | data class CharacteristicWritten(
84 | val characteristic: GattCharacteristic,
85 | val status: Int
86 | ) : GattEvent()
87 |
88 | data class DescriptorRead(
89 | val characteristic: GattCharacteristic,
90 | val descriptor: GattDescriptor,
91 | val value: ByteArray,
92 | val status: Int
93 | ) : GattEvent() {
94 | override fun equals(other: Any?): Boolean {
95 | if (this === other) return true
96 | if (javaClass != other?.javaClass) return false
97 |
98 | other as DescriptorRead
99 |
100 | if (descriptor != other.descriptor) return false
101 | if (!value.contentEquals(other.value)) return false
102 | if (status != other.status) return false
103 |
104 | return true
105 | }
106 |
107 | override fun hashCode(): Int {
108 | var result = descriptor.hashCode()
109 | result = 31 * result + value.contentHashCode()
110 | result = 31 * result + status
111 | return result
112 | }
113 | }
114 |
115 | data class DescriptorWritten(
116 | val characteristic: GattCharacteristic,
117 | val descriptorId: UUID,
118 | val status: Int
119 | ) : GattEvent()
120 |
121 | data class MtuChanged(val mtu: Int, val status: Int) : GattEvent()
122 | data class PhyRead(val txPhy: Int, val rxPhy: Int, val status: Int) : GattEvent()
123 | data class PhyUpdate(val txPhy: Int, val rxPhy: Int, val status: Int) : GattEvent()
124 | data class ReadRemoteRssi(val rssi: Int, val status: Int) : GattEvent()
125 | data class ReliableWriteCompleted(val status: Int) : GattEvent()
126 | object ServiceChanged : GattEvent()
127 |
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/GattTypes.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.bluetooth.BluetoothGattCharacteristic
4 | import android.bluetooth.BluetoothGattDescriptor
5 | import android.bluetooth.BluetoothGattService
6 | import java.util.*
7 |
8 | @Suppress("unused", "MemberVisibilityCanBePrivate")
9 | class GattService internal constructor(internal val bluetoothGattService: BluetoothGattService) {
10 | val instanceId = bluetoothGattService.instanceId
11 | val id: UUID = bluetoothGattService.uuid
12 | val characteristics: List = bluetoothGattService.characteristics.map { GattCharacteristic(it) }
13 | val serviceType = bluetoothGattService.type
14 | val services = bluetoothGattService.includedServices.map { GattService(it) }
15 | }
16 |
17 | @Suppress("unused")
18 | class GattCharacteristic internal constructor(internal val bluetoothGattCharacteristic: BluetoothGattCharacteristic) {
19 | val instanceId = bluetoothGattCharacteristic.instanceId
20 | val id: UUID = bluetoothGattCharacteristic.uuid
21 | val permissions = bluetoothGattCharacteristic.permissions
22 | val properties = bluetoothGattCharacteristic.properties
23 | val descriptors = bluetoothGattCharacteristic.descriptors.map { GattDescriptor(it) }
24 | }
25 |
26 | @Suppress("unused")
27 | class GattDescriptor internal constructor(internal val bluetoothGattDescriptor: BluetoothGattDescriptor) {
28 | val id: UUID = bluetoothGattDescriptor.uuid
29 | val permissions = bluetoothGattDescriptor.permissions
30 | }
31 |
--------------------------------------------------------------------------------
/blex/src/main/java/se/hellsoft/blex/bluetoothDevice.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.Manifest.permission.BLUETOOTH
4 | import android.Manifest.permission.BLUETOOTH_CONNECT
5 | import android.annotation.SuppressLint
6 | import android.bluetooth.BluetoothDevice
7 | import android.bluetooth.BluetoothGatt
8 | import android.content.Context
9 | import androidx.annotation.RequiresPermission
10 | import kotlinx.coroutines.CoroutineScope
11 | import kotlinx.coroutines.CoroutineStart
12 | import kotlinx.coroutines.Job
13 | import kotlinx.coroutines.cancel
14 | import kotlinx.coroutines.cancelAndJoin
15 | import kotlinx.coroutines.channels.ReceiveChannel
16 | import kotlinx.coroutines.coroutineScope
17 | import kotlinx.coroutines.launch
18 | import kotlinx.coroutines.plus
19 | import kotlinx.coroutines.suspendCancellableCoroutine
20 |
21 | /**
22 | * Connects to a BluetoothGatt in a managed fashion, exposing all events as a [ReceiveChannel]
23 | * to ensure that all events are handled.
24 | *
25 | * The connection to the [BluetoothGatt] is managed within the [CoroutineScope], and will be
26 | * disconnected and closed upon cancellation.
27 | */
28 | @SuppressLint("InlinedApi")
29 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
30 | internal fun BluetoothDevice.connectGattIn(
31 | context: Context,
32 | coroutineScope: CoroutineScope,
33 | transport: Int = BluetoothDevice.TRANSPORT_LE,
34 | phy: Int = BluetoothDevice.PHY_LE_1M,
35 | ): Pair> {
36 | lateinit var bluetoothGatt: BluetoothGatt
37 | val callback = ChannelBluetoothGattCallback()
38 |
39 | coroutineScope.launch(start = CoroutineStart.UNDISPATCHED) {
40 | suspendCancellableCoroutine { continuation ->
41 | bluetoothGatt = this@connectGattIn.connectGatt(
42 | /* context */ context,
43 | /* autoConnect */ true,
44 | /* callback */
45 | callback,
46 | /* transport */ transport,
47 | /* phy */ phy,
48 | /* handler */ null,
49 | )
50 |
51 | continuation.invokeOnCancellation {
52 | bluetoothGatt.disconnect()
53 | bluetoothGatt.close()
54 | }
55 | }
56 | }
57 |
58 | return bluetoothGatt to callback.receiveEvents
59 | }
60 |
61 | /**
62 | * Runs a block of code with a managed GATT connection to this [BluetoothDevice].
63 | *
64 | * A connection will be created to this [BluetoothDevice], and torn down at the end of [block] by
65 | * calling [BluetoothGatt.disconnect] and [BluetoothGatt.close]
66 | */
67 | @SuppressLint("InlinedApi")
68 | @RequiresPermission(anyOf = [BLUETOOTH, BLUETOOTH_CONNECT])
69 | suspend fun BluetoothDevice.withGattConnection(
70 | context: Context,
71 | transport: Int = BluetoothDevice.TRANSPORT_LE,
72 | phy: Int = BluetoothDevice.PHY_LE_1M,
73 | eventBufferCapacity: Int = 10,
74 | logger: ((level: Int, message: String, throwable: Throwable?) -> Unit) =
75 | { _, _, _ -> },
76 | block: suspend GattDevice.() -> Unit,
77 | ) = coroutineScope {
78 | val bluetoothJob = Job(coroutineContext[Job])
79 | val bluetoothScope = this + bluetoothJob
80 |
81 | val gattDevice = ConnectedGattDevice(
82 | bluetoothScope,
83 | this@withGattConnection,
84 | context,
85 | transport,
86 | phy,
87 | eventBufferCapacity,
88 | logger,
89 | )
90 |
91 | gattDevice.block()
92 |
93 | bluetoothJob.cancelAndJoin()
94 | }
--------------------------------------------------------------------------------
/blex/src/test/java/se/hellsoft/blex/BluetoothMocks.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.bluetooth.*
4 | import io.mockk.every
5 | import io.mockk.mockk
6 | import io.mockk.slot
7 | import kotlinx.coroutines.coroutineScope
8 | import kotlinx.coroutines.delay
9 | import kotlinx.coroutines.flow.MutableSharedFlow
10 | import kotlinx.coroutines.launch
11 | import java.util.*
12 |
13 | typealias GattServices = List>>>>
14 |
15 | fun mockDevice(hwAddress: String, gattServices: GattServices): BluetoothDevice {
16 | val uuidSlot = slot()
17 | val callbackSlot = slot()
18 | val byteArraySlot = slot()
19 | val characteristicSlot = slot()
20 |
21 | val gatt = mockk(relaxed = true) {
22 | every { writeCharacteristic(any(), any(), any()) }
23 | every { readCharacteristic(capture(characteristicSlot)) } coAnswers {
24 | val char = characteristicSlot.captured
25 | (callbackSlot.captured.events as MutableSharedFlow).tryEmit(
26 | CharacteristicRead(
27 | GattCharacteristic(char),
28 | ByteArray(20),
29 | BluetoothGatt.GATT_SUCCESS
30 | )
31 | )
32 | }
33 | every { services } returns gattServices.map { mockService(it.first, it.second) }
34 | every { setCharacteristicNotification(any(), any()) } returns true
35 | }
36 |
37 | return mockk(relaxed = true) {
38 | every {
39 | connectGatt(
40 | any(),
41 | any(),
42 | capture(callbackSlot),
43 | any(),
44 | any()
45 | )
46 | } coAnswers {
47 | gatt
48 | }
49 | every { address } returns hwAddress
50 | }
51 | }
52 |
53 | fun mockService(id: UUID, serviceIds: List>>) =
54 | mockk(relaxed = true) {
55 | every { uuid } returns id
56 | every { characteristics } returns serviceIds.map {
57 | mockCharacteristic(
58 | this,
59 | it.first,
60 | it.second
61 | )
62 | }
63 | }
64 |
65 | fun mockCharacteristic(gattService: BluetoothGattService, id: UUID, descriptorIds: List) =
66 | mockk(relaxed = true) {
67 | every { service } returns gattService
68 | every { uuid } returns id
69 | every { descriptors } returns descriptorIds.map { mockDescriptor(this, it) }
70 | }
71 |
72 | fun mockDescriptor(gattCharacteristic: BluetoothGattCharacteristic, id: UUID) =
73 | mockk(relaxed = true) {
74 | every { uuid } returns id
75 | every { characteristic } returns gattCharacteristic
76 | every { value } returns ByteArray(20)
77 | }
--------------------------------------------------------------------------------
/blex/src/test/java/se/hellsoft/blex/GattDeviceTests.kt:
--------------------------------------------------------------------------------
1 | package se.hellsoft.blex
2 |
3 | import android.bluetooth.BluetoothGatt
4 | import io.mockk.mockk
5 | import kotlinx.coroutines.ExperimentalCoroutinesApi
6 | import kotlinx.coroutines.delay
7 | import kotlinx.coroutines.flow.*
8 | import kotlinx.coroutines.test.StandardTestDispatcher
9 | import kotlinx.coroutines.test.advanceUntilIdle
10 | import kotlinx.coroutines.test.runTest
11 | import org.junit.Test
12 |
13 | import org.junit.Assert.*
14 | import java.util.UUID
15 |
16 | @OptIn(ExperimentalCoroutinesApi::class)
17 | class GattDeviceTests {
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id 'com.android.application' version '7.3.0' apply false
4 | id 'com.android.library' version '7.3.0' apply false
5 | id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
6 | }
7 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ErikHellman/android-blex/23e06e7a4cbb3448d34b68cd84cbb21390e09cfd/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Nov 11 09:00:47 CET 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "blex"
16 | include ':blex'
17 |
--------------------------------------------------------------------------------