Skip to content

Instantly share code, notes, and snippets.

@Arunshaik2001
Last active October 26, 2022 16:23
Show Gist options
  • Save Arunshaik2001/6060106ace68ef3a65bec09b3ec524fa to your computer and use it in GitHub Desktop.
Save Arunshaik2001/6060106ace68ef3a65bec09b3ec524fa to your computer and use it in GitHub Desktop.
private fun setupGattServer(app: Application) {
gattServerCallback = GattServerCallback()
gattServer = bluetoothManager.openGattServer(
app,
gattServerCallback
).apply {
addService(setupGattService())
}
}
private fun setupGattService(): BluetoothGattService {
val service = BluetoothGattService(SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY)
val messageCharacteristic = BluetoothGattCharacteristic(
MESSAGE_UUID,
BluetoothGattCharacteristic.PROPERTY_WRITE,
BluetoothGattCharacteristic.PERMISSION_WRITE
)
service.addCharacteristic(messageCharacteristic)
return service
}
private class GattServerCallback : BluetoothGattServerCallback() {
override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
super.onConnectionStateChange(device, status, newState)
val isSuccess = status == BluetoothGatt.GATT_SUCCESS
val isConnected = newState == BluetoothProfile.STATE_CONNECTED
if (isSuccess && isConnected) {
setCurrentChatConnection(device)
} else {
_deviceConnection.postValue(DeviceConnectionState.Disconnected)
}
}
override fun onCharacteristicWriteRequest(
device: BluetoothDevice,
requestId: Int,
characteristic: BluetoothGattCharacteristic,
preparedWrite: Boolean,
responseNeeded: Boolean,
offset: Int,
value: ByteArray?
) {
super.onCharacteristicWriteRequest(
device,
requestId,
characteristic,
preparedWrite,
responseNeeded,
offset,
value
)
if (characteristic.uuid == MESSAGE_UUID) {
gattServer?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null)
val message = value?.toString(Charsets.UTF_8)
message?.let {
_messages.postValue(Message.RemoteMessage(it))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment