writeCharacteristic method

  1. @override
Future<bool> writeCharacteristic({
  1. required String serviceUuid,
  2. required String characteristicUuid,
  3. required Uint8List payload,
  4. Duration timeout = const Duration(seconds: 30),
  5. required bool withResponse,
})
override

writeCharacteristic sends a payload to a BLE characteristic.

The return value is true if the payload was sent successfully.

Implementation

@override
Future<bool> writeCharacteristic({
  required String serviceUuid,
  required String characteristicUuid,
  required Uint8List payload,
  Duration timeout = const Duration(seconds: 30),
  required bool withResponse,
}) async {
  if (_connectedDevice == null) {
    log("Not connected to any device");
    return false;
  }

  final service = _connectedDevice!.gattServices.firstWhereOrNull((element) {
    return element.uuid.toString().toLowerCase() == serviceUuid.toLowerCase();
  });
  if (service == null) {
    log("Service not found: $serviceUuid");
    return false;
  }

  final characteristic = service.characteristics.firstWhereOrNull((element) {
    return element.uuid.toString().toLowerCase() == characteristicUuid.toLowerCase();
  });

  if (characteristic == null) {
    log("Characteristic not found: $characteristicUuid");
    return false;
  }

  await characteristic.writeValue(payload);
  return true;
}