Skip to content

Instantly share code, notes, and snippets.

@twyatt
Last active April 8, 2019 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twyatt/b1542406777251365f323e9da1caa31a to your computer and use it in GitHub Desktop.
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
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