sendString method

Future<String?> sendString(
  1. String string, {
  2. bool awaitResponse = false,
  3. Duration? timeout,
})

Sends a string to the device.

Implementation

Future<String?> sendString(
  String string, {
  bool awaitResponse = false,
  Duration? timeout,
}) async {
  try {
    final controlChar = string.length == 1 && string.codeUnitAt(0) < 10
        ? string.codeUnitAt(0)
        : null;
    if (controlChar != null && !awaitResponse) {
      _log.info("Sending control character: $controlChar");
      await _txChannel!
          .write(Uint8List.fromList([controlChar]), withoutResponse: true);
      _log.finer("Sent control character: $controlChar");
      return null;
    } else {
      _log.info("Sending string: $string");
    }

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

    if (string.length > maxStringLength!) {
      throw ("Payload exceeds allowed length of $maxStringLength");
    }

    await _txChannel!.write(utf8.encode(string));

    _log.finer("Sent string: $string");

    if (!awaitResponse) {
      return null;
    }

    final response =
        await stringResponse.timeout(timeout ?? defaultTimeout).first;

    return response;
  } catch (error) {
    _log.warning("Couldn't send string. $error");
    return Future.error(BrilliantBluetoothException(error.toString()));
  }
}