Skip to content

Commit

Permalink
fix ver & reduce logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Codel1417 committed May 14, 2024
1 parent 4bf0366 commit e1cabe4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 30 deletions.
40 changes: 21 additions & 19 deletions lib/Backend/Bluetooth/bluetooth_manager_plus.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {
}
_didInitFlutterBluePlus = true;

await FlutterBluePlus.setLogLevel(LogLevel.verbose, color: false);
await FlutterBluePlus.setLogLevel(LogLevel.warning, color: false);
// first, check if bluetooth is supported by your hardware
// Note: The platform is initialized on the first call to any FlutterBluePlus method.
if (await FlutterBluePlus.isSupported == false) {
Expand All @@ -56,7 +56,7 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {

// listen to *any device* connection state changes
_onConnectionStateChangedStreamSubscription = FlutterBluePlus.events.onConnectionStateChanged.listen((event) async {
_bluetoothPlusLogger.info('${event.device} ${event.connectionState}');
_bluetoothPlusLogger.info('${event.device.advName} ${event.connectionState}');
Map<String, BaseStatefulDevice> knownDevices = ref.read(knownDevicesProvider);
BluetoothDevice bluetoothDevice = event.device;
BluetoothConnectionState bluetoothConnectionState = event.connectionState;
Expand Down Expand Up @@ -158,17 +158,17 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {
}
});
_onReadRssiStreamSubscription = FlutterBluePlus.events.onReadRssi.listen((event) {
_bluetoothPlusLogger.info('${event.device} RSSI:${event.rssi}');
_bluetoothPlusLogger.info('${event.device.advName} RSSI:${event.rssi}');
BaseStatefulDevice? statefulDevice = ref.read(knownDevicesProvider)[event.device.remoteId.str];
statefulDevice?.rssi.value = event.rssi;
});
_onMtuChanged = FlutterBluePlus.events.onMtuChanged.listen((event) {
_bluetoothPlusLogger.info('${event.device} MTU:${event.mtu}');
_bluetoothPlusLogger.info('${event.device.advName} MTU:${event.mtu}');
BaseStatefulDevice? statefulDevice = ref.read(knownDevicesProvider)[event.device.remoteId.str];
statefulDevice?.mtu.value = event.mtu;
});
_onDiscoveredServicesStreamSubscription = FlutterBluePlus.events.onDiscoveredServices.listen((event) async {
_bluetoothPlusLogger.info('${event.device} ${event.services}');
//_bluetoothPlusLogger.info('${event.device} ${event.services}');
//Subscribes to all characteristics
for (BluetoothService service in event.services) {
for (BluetoothCharacteristic characteristic in service.characteristics) {
Expand All @@ -177,44 +177,46 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {
}
});
_onCharacteristicReceivedStreamSubscription = FlutterBluePlus.events.onCharacteristicReceived.listen((event) {
_bluetoothPlusLogger.info('${event.device} ${event.value}');
_bluetoothPlusLogger.info('onCharacteristicReceived ${event.device.advName} ${event.characteristic.uuid.str} ${event.value}');

BluetoothDevice bluetoothDevice = event.device;
BluetoothCharacteristic bluetoothCharacteristic = event.characteristic;
List<int> values = event.value;
BaseStatefulDevice? statefulDevice = ref.read(knownDevicesProvider)[bluetoothDevice.remoteId.str];
// get Device object
// set value
if (statefulDevice == null) {
return;
}
if (bluetoothCharacteristic.characteristicUuid == Guid("2a19")) {
statefulDevice?.batteryLevel.value = values.first.toDouble();
statefulDevice.batteryLevel.value = values.first.toDouble();
} else if (bluetoothCharacteristic.characteristicUuid == Guid("5073792e-4fc0-45a0-b0a5-78b6c1756c91")) {
String value = const Utf8Decoder().convert(values);
statefulDevice?.messageHistory.add(MessageHistoryEntry(type: MessageHistoryType.receive, message: value));
statefulDevice?.batteryCharging.value = value == "CHARGE ON";
}
if (bluetoothCharacteristic.characteristicUuid.str == statefulDevice?.baseDeviceDefinition.bleRxCharacteristic) {
statefulDevice.messageHistory.add(MessageHistoryEntry(type: MessageHistoryType.receive, message: value));
statefulDevice.batteryCharging.value = value == "CHARGE ON";
} else if (bluetoothCharacteristic.characteristicUuid == Guid(statefulDevice.baseDeviceDefinition.bleRxCharacteristic)) {
String value = const Utf8Decoder().convert(values);
statefulDevice?.messageHistory.add(MessageHistoryEntry(type: MessageHistoryType.receive, message: value));
statefulDevice.messageHistory.add(MessageHistoryEntry(type: MessageHistoryType.receive, message: value));
// Firmware Version
if (value.startsWith("VER")) {
statefulDevice?.fwVersion.value = value.substring(value.indexOf(" "));
statefulDevice.fwVersion.value = value.substring(value.indexOf(" "));
// Sent after VER message
} else if (value.startsWith("GLOWTIP")) {
statefulDevice?.hasGlowtip.value = "TRUE" == value.substring(value.indexOf(" "));
statefulDevice.hasGlowtip.value = "TRUE" == value.substring(value.indexOf(" "));
} else if (value.contains("BUSY")) {
//statefulDevice.deviceState.value = DeviceState.busy;
} else if (value.contains("LOWBATT")) {
statefulDevice?.batteryLow.value = true;
statefulDevice.batteryLow.value = true;
} else if (value.contains("ERR")) {
statefulDevice?.gearReturnedError.value = true;
statefulDevice.gearReturnedError.value = true;
} else if (value.contains("HWVER")) {
// Hardware Version
statefulDevice?.hwVersion.value = value.substring(value.indexOf(" "));
statefulDevice.hwVersion.value = value.substring(value.indexOf(" "));
}
}
});
_onServicesResetStreamSubscription = FlutterBluePlus.events.onServicesReset.listen((event) async {
_bluetoothPlusLogger.info("${event.device} onServicesReset");
_bluetoothPlusLogger.info("${event.device.advName} onServicesReset");
await event.device.discoverServices();
});
// handle bluetooth on & off
Expand Down Expand Up @@ -277,7 +279,7 @@ Future<void> sendMessage(BaseStatefulDevice device, List<int> message, {bool wit
BluetoothDevice? bluetoothDevice = FlutterBluePlus.connectedDevices.firstWhereOrNull((element) => element.remoteId.str == device.baseStoredDevice.btMACAddress);
if (bluetoothDevice != null) {
BluetoothCharacteristic? bluetoothCharacteristic =
bluetoothDevice.servicesList.firstWhereOrNull((element) => element.uuid.str == device.baseDeviceDefinition.bleDeviceService)?.characteristics.firstWhereOrNull((element) => element.characteristicUuid.str == device.baseDeviceDefinition.bleTxCharacteristic);
bluetoothDevice.servicesList.firstWhereOrNull((element) => element.uuid == Guid(device.baseDeviceDefinition.bleDeviceService))?.characteristics.firstWhereOrNull((element) => element.characteristicUuid == Guid(device.baseDeviceDefinition.bleTxCharacteristic));
await bluetoothCharacteristic?.write(message, withoutResponse: withoutResponse, allowLongWrite: allowLongWrite);
}
}
21 changes: 10 additions & 11 deletions lib/Backend/Definitions/Device/device_definition.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,13 @@ class BaseStatefulDevice extends ChangeNotifier {
reset();
} else if (deviceConnectionState.value == ConnectivityState.connected) {
// Add initial commands to the queue
commandQueue.addCommand(BluetoothMessage(message: "VER", device: this, priority: Priority.low, type: Type.system));
commandQueue.addCommand(BluetoothMessage(message: "HWVER", device: this, priority: Priority.low, type: Type.system));
if (baseStoredDevice.autoMove) {
changeAutoMove(this);
}
Future.delayed(const Duration(seconds: 5), () {
commandQueue.addCommand(BluetoothMessage(message: "VER", device: this, priority: Priority.low, type: Type.system, responseMSG: "VER "));
commandQueue.addCommand(BluetoothMessage(message: "HWVER", device: this, priority: Priority.low, type: Type.system, responseMSG: "HWVER "));
if (baseStoredDevice.autoMove) {
changeAutoMove(this);
}
});
}
});
batteryLevel.addListener(() {
Expand Down Expand Up @@ -292,11 +294,6 @@ class CommandQueue {

void addCommand(BluetoothMessage bluetoothMessage) {
messageQueueStreamSubscription ??= messageQueueStream().listen((message) async {
//Check if the device is still known and connected;
if (device.deviceConnectionState.value != ConnectivityState.connected) {
device.deviceState.value = DeviceState.standby;
return;
}
//TODO: Resend on busy
if (bluetoothMessage.delay == null) {
try {
Expand All @@ -316,7 +313,7 @@ class CommandQueue {
// We use a timeout as sometimes a response isn't sent by the gear
Future<String> response = message.device.rxCharacteristicStream.timeout(timeoutDuration, onTimeout: (sink) => sink.close()).where((event) {
bluetoothLog.info('Response:$event');
return event == message.responseMSG!;
return event.contains(message.responseMSG!);
}).first;
// Handles response value
response.then((value) {
Expand All @@ -341,6 +338,8 @@ class CommandQueue {
await Future.delayed(const Duration(milliseconds: 50)); // Prevent the loop from consuming too many resources
}
bluetoothLog.fine("Finished waiting for response from ${device.baseStoredDevice.name}:${message.responseMSG}");
} else {
await Future.delayed(const Duration(milliseconds: 200));
}
} catch (e, s) {
bluetoothLog.warning('Command timed out or threw error: $e', e, s);
Expand Down

0 comments on commit e1cabe4

Please sign in to comment.