Last active
April 8, 2019 19:49
-
-
Save twyatt/b1542406777251365f323e9da1caa31a to your computer and use it in GitHub Desktop.
Provides a shorthand for writing to a characteristic using a service and characteristic UUID. https://github.com/JuulLabs-OSS/able
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.myapplication | |
import android.bluetooth.BluetoothGattCharacteristic | |
import android.bluetooth.BluetoothGattService | |
import com.juul.able.experimental.Gatt | |
import com.juul.able.experimental.WriteType | |
import com.juul.able.experimental.throwable.writeCharacteristicOrThrow | |
import java.util.UUID | |
class GattServiceNotFound(uuid: UUID) : Exception("GATT service $uuid not found.") | |
class GattCharacteristicNotFound(uuid: UUID) : Exception("GATT characteristic $uuid not found.") | |
fun Gatt.getServiceOrThrow(uuid: UUID) = | |
getService(uuid) ?: throw GattServiceNotFound(uuid) | |
fun BluetoothGattService.getCharacteristicOrThrow(uuid: UUID) = | |
getCharacteristic(uuid) ?: throw GattCharacteristicNotFound(uuid) | |
suspend fun Gatt.writeCharacteristicOrThrow( | |
serviceUuid: UUID, | |
characteristicUuid: UUID, | |
value: ByteArray, | |
writeType: WriteType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT | |
) { | |
val characteristic = getServiceOrThrow(serviceUuid) | |
.getCharacteristicOrThrow(characteristicUuid) | |
writeCharacteristicOrThrow(characteristic, value, writeType) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment