handleStringResponsePart method
Handles string response parts from the device.
Implementation
Stream<String> handleStringResponsePart(
Stream<OnCharacteristicReceivedEvent> source) async* {
Uint8List? ongoingPrintResponse;
int? ongoingPrintResponseChunkCount;
await for (final event in source) {
if (event.value[0] == FrameDataTypePrefixes.longText.value) {
// ongoing long text
if (ongoingPrintResponse == null ||
ongoingPrintResponseChunkCount == null) {
ongoingPrintResponse = Uint8List(0);
ongoingPrintResponseChunkCount = 0;
_log.fine("Starting receiving new long printed string");
}
ongoingPrintResponse =
Uint8List.fromList(ongoingPrintResponse + event.value.sublist(1));
ongoingPrintResponseChunkCount++;
final receivedString = utf8.decode(event.value.sublist(1));
_log.finer(
"Received long text chunk #$ongoingPrintResponseChunkCount: $receivedString");
if (ongoingPrintResponse.length > maxReceiveBuffer) {
_log.severe(
"Buffered received long printed string is more than $maxReceiveBuffer bytes: ${ongoingPrintResponse.lengthInBytes} bytes received");
throw BrilliantBluetoothException(
"Buffered received long printed string is more than $maxReceiveBuffer bytes: ${ongoingPrintResponse.lengthInBytes} bytes received");
}
} else if (event.value[0] == FrameDataTypePrefixes.longTextEnd.value) {
final totalExpectedChunkCount =
int.parse(utf8.decode(event.value.sublist(1)));
_log.finer(
"Received final string chunk count: $totalExpectedChunkCount");
if (ongoingPrintResponseChunkCount != totalExpectedChunkCount) {
_log.warning(
"Chunk count mismatch in long received string (expected $totalExpectedChunkCount, got $ongoingPrintResponseChunkCount)");
throw BrilliantBluetoothException(
"Chunk count mismatch in long received string (expected $totalExpectedChunkCount, got $ongoingPrintResponseChunkCount)");
}
final completePrintResponse = utf8.decode(ongoingPrintResponse!);
ongoingPrintResponse = null;
ongoingPrintResponseChunkCount = null;
_log.info("Finished receiving long string: $completePrintResponse");
yield completePrintResponse;
} else {
final receivedString = utf8.decode(event.value);
if (receivedString.startsWith("+") || receivedString.startsWith(">")) {
_log.fine("Received check string: $receivedString");
} else {
_log.info("Received string: $receivedString");
}
yield receivedString;
}
}
}