write method

Future<Null> write(
  1. List<int> value, {
  2. bool withoutResponse = false,
})

Writes the value of a characteristic. CharacteristicWriteType.withoutResponse: the write is not guaranteed and will return immediately with success. CharacteristicWriteType.withResponse: the method will return after the write operation has either passed or failed.

Implementation

Future<Null> write(List<int> value, {bool withoutResponse = false}) async {
  final type = withoutResponse
      ? CharacteristicWriteType.withoutResponse
      : CharacteristicWriteType.withResponse;

  var request = protos.WriteCharacteristicRequest.create()
    ..remoteId = deviceId.toString()
    ..characteristicUuid = uuid.toString()
    ..serviceUuid = serviceUuid.toString()
    ..writeType =
        protos.WriteCharacteristicRequest_WriteType.valueOf(type.index)!
    ..value = value;

  var result = await FlutterBlue.instance._channel
      .invokeMethod('writeCharacteristic', request.writeToBuffer());

  if (type == CharacteristicWriteType.withoutResponse) {
    return result;
  }

  return FlutterBlue.instance._methodStream
      .where((m) => m.method == "WriteCharacteristicResponse")
      .map((m) => m.arguments)
      .map((buffer) =>
          new protos.WriteCharacteristicResponse.fromBuffer(buffer))
      .where((p) =>
          (p.request.remoteId == request.remoteId) &&
          (p.request.characteristicUuid == request.characteristicUuid) &&
          (p.request.serviceUuid == request.serviceUuid))
      .first
      .then((w) => w.success)
      .then((success) => (!success)
          ? throw new Exception('Failed to write the characteristic')
          : null)
      .then((_) => null);
}