sendString method

Future<String?> sendString(
  1. String string, {
  2. bool awaitResponse = true,
  3. bool log = true,
  4. Duration timeout = const Duration(seconds: 10),
})

Implementation

Future<String?> sendString(
  String string, {
  bool awaitResponse = true,
  bool log = true,
  Duration timeout = const Duration(seconds: 10),
}) async {
  try {
    if (log) {
      _log.info(() => "Sending string: $string");
    }

    if (state != BrilliantConnectionState.connected) {
      throw BrilliantBluetoothException("Device is not connected");
    }

    final data = utf8.encode(string);
    final maxLength = maxStringLength;
    if (maxLength == null || data.length > maxLength) {
      throw BrilliantBluetoothException("Payload exceeds allowed length of ${maxLength ?? 'unknown'}");
    }

    final tx = txChannel;
    final rx = rxChannel;
    if (tx == null || (awaitResponse && rx == null)) {
      throw BrilliantBluetoothException("Required channels not available");
    }

    // Set up the response listener before writing
    Future<String>? responseFuture;
    if (awaitResponse) {
      responseFuture = rx!.onValueReceived
          .timeout(timeout, onTimeout: (event) {
              throw const BrilliantBluetoothException("Timeout waiting for string response");
          })
          .first
          .then((response) => utf8.decode(response));
    }

    // Now perform the write
    await tx.write(data, withoutResponse: false, allowLongWrite: true);

    // Wait for the response if needed
    if (awaitResponse && responseFuture != null) {
      return await responseFuture;
    }

    return null;
  } catch (error) {
    _log.warning("Couldn't send string. $error");
    rethrow;
  }
}