Future<BleCommandItemModel> _sendCommandHandler(BleCommandItemModel command) async {
Log.info(tag, "try to send command $command");
if (connectionState == PeripheralConnectionState.connected) {
final currentTime =
DateTime.now().millisecondsSinceEpoch;
BleCommandItemModel finalCommand;
// Add relevant timestamps to the command
if (command.firstSendTime == 0) {
finalCommand = command.copyWith(
firstSendTime: currentTime,
lastAttemptToSendTime: currentTime,
);
} else {
finalCommand = command.copyWith(
lastAttemptToSendTime: currentTime,
);
}
final pck = CommandPacketModel(finalCommand);
final commandPacket = pck.prepare();
Log.info(tag, 'commandPacket $commandPacket');
final chunks = getSplitPacketBytes(commandPacket);
Log.info(tag, 'chunks $chunks');
for (final chunk in chunks) {
Log.info(tag, 'TRY TO WRITE CHUNK $chunk');
await bleService.writeCharacteristic(chunk);
}
} else {
if (command.onError != null) {
command.onError!();
}
if (commonErrorCallback != null) {
commonErrorCallback!();
commonErrorCallback = null;
}
Log.warning(tag, "device disconnected, command not sent ");
}
return command;
}