diff --git a/INSTRUCTIONS_ONELAP_KEY.md b/INSTRUCTIONS_ONELAP_KEY.md index 22d9ac23..c04320b6 100644 --- a/INSTRUCTIONS_ONELAP_KEY.md +++ b/INSTRUCTIONS_ONELAP_KEY.md @@ -6,7 +6,7 @@ This beta driver supports the legacy `Onelap Key` five-button BLE controller. Ph Wake the controller, stop other applications from holding its BLE connection, and let BikeControl scan. The controller may advertise only the Battery Service, so the driver uses the device name for discovery. After connecting, it finds service `8ce5cc01-0a4d-11e9-ab14-d663bd873d93` and subscribes to characteristic `8ce5cc02-0a4d-11e9-ab14-d663bd873d93`. The driver does not send an initialization command. -The default single-click mapping is: Up = Shift Up, Down = Shift Down, Left/Right = menu navigation, Center = Select. All five buttons are registered through the existing keymap system, so BikeControl's custom mappings and output transports remain available. Hardware-reported long presses use the shared long-press dispatch path; the driver releases them when a follow-up valid frame or a disconnect arrives. It does not replace the hardware gesture with a software timer. +The default single-click mapping is: Up = Shift Up, Down = Shift Down, Left/Right = menu navigation, Center = Select. The diagram uses the molded faces, not those actions: circle on Up, triangle on Left, square on Right, a dot pad on Down, and ONELAP on the center hub. All five buttons are registered through the existing keymap system, so BikeControl's custom mappings and output transports remain available. Hardware-reported long presses use the shared long-press dispatch path; the driver releases them when a follow-up valid frame or a disconnect arrives. It does not replace the hardware gesture with a software timer. ## Notification layout diff --git a/lib/bluetooth/ble_string.dart b/lib/bluetooth/ble_string.dart new file mode 100644 index 00000000..aee150a9 --- /dev/null +++ b/lib/bluetooth/ble_string.dart @@ -0,0 +1,32 @@ +import 'dart:convert'; + +/// Device Information strings are C strings, often in a fixed buffer. +/// Bytes after the NUL, 0xFF fill, or a non-UTF-8 tail render as tofu boxes +/// after an otherwise readable version such as `0.105`. +String? decodeBleDeviceInfoString(List data) { + if (data.isEmpty) return null; + var end = data.length; + final nul = data.indexOf(0); + if (nul != -1) end = nul; + while (end > 0 && data[end - 1] == 0xFF) { + end--; + } + if (end == 0) return null; + + final bytes = data.sublist(0, end); + final decoded = _decode(bytes); + final cleaned = decoded.replaceAll(_unprintable, '').trim(); + return cleaned.isEmpty ? null : cleaned; +} + +final _unprintable = RegExp(r'[\u0000-\u001F\u007F-\u009F\uE000-\uF8FF\uFFFD-\uFFFF]'); + +String _decode(List bytes) { + try { + return utf8.decode(bytes); + } on FormatException catch (error) { + // An incomplete multibyte character may precede the error offset. + // The caller removes any resulting replacement characters during cleanup. + return utf8.decode(bytes.sublist(0, error.offset ?? 0), allowMalformed: true); + } +} diff --git a/lib/bluetooth/connection.dart b/lib/bluetooth/connection.dart index d4e91cb9..6b342e10 100644 --- a/lib/bluetooth/connection.dart +++ b/lib/bluetooth/connection.dart @@ -16,6 +16,7 @@ import 'package:bike_control/bluetooth/inactivity_disconnector.dart'; import 'package:bike_control/bluetooth/incline/incline_controller.dart'; import 'package:bike_control/bluetooth/incline/incline_sink.dart'; import 'package:bike_control/bluetooth/incline/manual_incline_device.dart'; +import 'package:bike_control/bluetooth/scan_identity.dart'; import 'package:bike_control/bluetooth/support_log_buffer.dart'; import 'package:bike_control/bluetooth/wifi_trainer_scanner.dart'; import 'package:bike_control/gen/l10n.dart'; @@ -1169,7 +1170,10 @@ class Connection { _rssiConnectionStreams.add(existingDevice); // Notify UI of update } - if (_lastScanResult.none((e) => e.deviceId == result.deviceId && e.services.contentEquals(result.services))) { + if (scanResultAddsIdentity(_lastScanResult, result)) { + _lastScanResult.removeWhere( + (device) => device.deviceId == result.deviceId && device.services.contentEquals(result.services), + ); _lastScanResult.add(result); // A left puck coming into range is what brings the right one's LEDs @@ -1346,7 +1350,15 @@ class Connection { await UniversalBle.startScan( // allow all to enable Wahoo Kickr Bike Shift detection //scanFilter: kIsWeb ? ScanFilter(withServices: BluetoothDevice.servicesToScan) : null, - platformConfig: PlatformConfig(web: WebOptions(optionalServices: BluetoothDevice.servicesToScan)), + platformConfig: PlatformConfig( + web: WebOptions(optionalServices: BluetoothDevice.servicesToScan), + android: AndroidOptions( + scanMode: AndroidScanMode.lowLatency, + // false accepts both legacy and extended advertisements, + // keeping other devices discoverable. + legacy: false, + ), + ), ); if (kIsWeb) { diff --git a/lib/bluetooth/devices/bluetooth_device.dart b/lib/bluetooth/devices/bluetooth_device.dart index 03d2c743..b7c9c273 100644 --- a/lib/bluetooth/devices/bluetooth_device.dart +++ b/lib/bluetooth/devices/bluetooth_device.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:bike_control/bluetooth/ble.dart'; +import 'package:bike_control/bluetooth/ble_string.dart'; import 'package:bike_control/bluetooth/devices/base_device.dart'; import 'package:bike_control/bluetooth/devices/openbikecontrol/openbikecontrol_device.dart'; import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart'; @@ -560,8 +561,7 @@ abstract class BluetoothDevice extends BaseDevice { if (characteristic == null) return null; try { final data = await readUpstream(service!.uuid, characteristic.uuid); - final decoded = String.fromCharCodes(data).trim(); - return decoded.isEmpty ? null : decoded; + return decodeBleDeviceInfoString(data); } catch (_) { return null; } diff --git a/lib/bluetooth/devices/magene/onelap_key.dart b/lib/bluetooth/devices/magene/onelap_key.dart index 65881f65..f5f44010 100644 --- a/lib/bluetooth/devices/magene/onelap_key.dart +++ b/lib/bluetooth/devices/magene/onelap_key.dart @@ -113,41 +113,44 @@ class OnelapKeyConstants { } } +/// Faces match the molded cross, not the default actions. Up is a circle, +/// left a triangle, right a square, down a dot pad, and the hub reads ONELAP. +/// The action badge still shows the mapping. class OnelapKeyButtons { static const center = ControllerButton( 'onelapCenter', identifier: 1, action: InGameAction.select, color: Colors.black, - icon: LucideIcons.circle, + label: 'ONELAP', ); static const left = ControllerButton( 'onelapLeft', identifier: 2, action: InGameAction.navigateLeft, color: Colors.black, - icon: LucideIcons.chevronLeft, + icon: LucideIcons.triangle, ); static const up = ControllerButton( 'onelapUp', identifier: 3, action: InGameAction.shiftUp, color: Colors.black, - icon: LucideIcons.plus, + icon: LucideIcons.circle, ); static const right = ControllerButton( 'onelapRight', identifier: 4, action: InGameAction.navigateRight, color: Colors.black, - icon: LucideIcons.chevronRight, + icon: LucideIcons.square, ); static const down = ControllerButton( 'onelapDown', identifier: 5, action: InGameAction.shiftDown, color: Colors.black, - icon: LucideIcons.minus, + icon: LucideIcons.grip, ); static const values = [center, left, up, right, down]; diff --git a/lib/bluetooth/scan_identity.dart b/lib/bluetooth/scan_identity.dart new file mode 100644 index 00000000..9f9e1f98 --- /dev/null +++ b/lib/bluetooth/scan_identity.dart @@ -0,0 +1,24 @@ +import 'package:dartx/dartx.dart'; +import 'package:universal_ble/universal_ble.dart'; + +/// Whether [result] should be classified. +/// +/// The first advertisement of a controller often carries only the Battery +/// Service. The local name, which is how an Onelap Key is recognised, can +/// arrive in a later packet with the same service list. Treating that packet +/// as a duplicate drops the controller before it can be named. +bool scanResultAddsIdentity(Iterable seen, BleDevice result) { + final prior = seen.where( + (device) => + device.deviceId == result.deviceId && + device.services.contentEquals(result.services), + ); + if (prior.isEmpty) return true; + if (!_hasName(result.name)) return false; + return prior.every((device) => !_hasName(device.name)); +} + +bool _hasName(String? name) { + final trimmed = name?.trim(); + return trimmed != null && trimmed.isNotEmpty; +} diff --git a/lib/widgets/ui/button_widget.dart b/lib/widgets/ui/button_widget.dart index 7dcdcc2d..393ce249 100644 --- a/lib/widgets/ui/button_widget.dart +++ b/lib/widgets/ui/button_widget.dart @@ -73,7 +73,7 @@ class ButtonWidget extends StatelessWidget { ), if (button.icon != null) Icon(button.icon, size: size * 0.42, color: onBg) - else + else if (button.shortLabel.length <= 2) Text( button.shortLabel, style: TextStyle( @@ -82,6 +82,25 @@ class ButtonWidget extends StatelessWidget { letterSpacing: -0.2, color: onBg, ), + ) + else + Positioned.fill( + child: Padding( + padding: EdgeInsets.all(size * 0.14), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + button.shortLabel, + maxLines: 1, + style: TextStyle( + fontSize: size * 0.26, + fontWeight: FontWeight.w700, + letterSpacing: -0.2, + color: onBg, + ), + ), + ), + ), ), Positioned( top: -badgeSize * 0.15, diff --git a/test/bluetooth/ble_string_test.dart b/test/bluetooth/ble_string_test.dart new file mode 100644 index 00000000..30a5983f --- /dev/null +++ b/test/bluetooth/ble_string_test.dart @@ -0,0 +1,76 @@ +import 'dart:convert'; + +import 'package:bike_control/bluetooth/ble_string.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('keeps a plain firmware version', () { + expect(decodeBleDeviceInfoString('1.2.0'.codeUnits), '1.2.0'); + expect(decodeBleDeviceInfoString('0.105'.codeUnits), '0.105'); + }); + + test('drops NUL padding that would render as tofu', () { + expect( + decodeBleDeviceInfoString([...'0.105'.codeUnits, 0, 0, 0, 0, 0xFF, 0xFF]), + '0.105', + ); + }); + + test('drops 0xFF fill and non-UTF-8 tails after the version', () { + expect(decodeBleDeviceInfoString([...'0.105'.codeUnits, 0xFF, 0xFF, 0xFF]), '0.105'); + expect( + decodeBleDeviceInfoString([...'0.105'.codeUnits, 0x80, 0x81, 0xFE, 0xFD]), + '0.105', + ); + }); + + test('keeps a valid UTF-8 manufacturer name', () { + final name = utf8.encode('迈金'); + expect(decodeBleDeviceInfoString(name), '迈金'); + expect(decodeBleDeviceInfoString([...name, 0, 0xFF]), '迈金'); + }); + + test('malformed UTF-8 tails preserve the valid Chinese prefix', () { + expect(decodeBleDeviceInfoString([...utf8.encode('迈金'), 0x80, 0xFF]), '迈金'); + }); + + test('ASCII after the first malformed sequence is not appended to the firmware version', () { + for (final tail in [ + [0x80, 0x41], + [0xE2, 0x41], + [0xE2, 0x82, 0x41], + [0xC0, 0xAF, 0x41], + [0xED, 0xA0, 0x80, 0x41], + [0xF4, 0x90, 0x80, 0x80, 0x41], + [0xFF, 0x41], + ]) { + expect(decodeBleDeviceInfoString([...'0.105'.codeUnits, ...tail]), '0.105', reason: '$tail'); + } + }); + + test('incomplete multibyte tails preserve the valid Unicode prefix', () { + for (final tail in [ + [0xC2], + [0xE2, 0x82], + [0xF0, 0x9F, 0x92], + ]) { + expect(decodeBleDeviceInfoString([...utf8.encode('迈金🚴'), ...tail]), '迈金🚴', reason: '$tail'); + } + }); + + test('valid replacement characters do not truncate subsequent device information', () { + final name = utf8.encode('迈\uFFFD金'); + expect(decodeBleDeviceInfoString(name), '迈金'); + expect(decodeBleDeviceInfoString([...name, 0x80]), '迈金'); + }); + + test('malformed leading bytes do not expose subsequent ASCII as device information', () { + expect(decodeBleDeviceInfoString([0x80, ...'0.105'.codeUnits]), isNull); + }); + + test('returns null for an empty or padding-only buffer', () { + expect(decodeBleDeviceInfoString(const []), isNull); + expect(decodeBleDeviceInfoString([0, 0, 0xFF]), isNull); + expect(decodeBleDeviceInfoString([0xFF, 0xFF]), isNull); + }); +} diff --git a/test/bluetooth/scan_identity_test.dart b/test/bluetooth/scan_identity_test.dart new file mode 100644 index 00000000..175756b5 --- /dev/null +++ b/test/bluetooth/scan_identity_test.dart @@ -0,0 +1,46 @@ +import 'package:bike_control/bluetooth/scan_identity.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:universal_ble/universal_ble.dart'; + +BleDevice _device({String? name, List services = const ['180f']}) => + BleDevice(deviceId: 'onelap', name: name, services: services); + +void main() { + test('accepts the first sighting and a later packet that adds the name', () { + final unnamed = _device(); + expect(scanResultAddsIdentity(const [], unnamed), isTrue); + expect( + scanResultAddsIdentity([unnamed], _device(name: 'Onelap Key_12224')), + isTrue, + ); + }); + + test('ignores a repeat once the name is known', () { + final named = _device(name: 'Onelap Key_12224'); + expect( + scanResultAddsIdentity([named], _device(name: 'Onelap Key_12224')), + isFalse, + ); + expect(scanResultAddsIdentity([named], _device()), isFalse); + expect( + scanResultAddsIdentity([ + _device(), + named, + ], _device(name: 'Onelap Key_12224')), + isFalse, + ); + }); + + test('a different service list is a new sighting', () { + expect( + scanResultAddsIdentity( + [_device(name: 'Onelap Key_12224')], + _device( + name: 'Onelap Key_12224', + services: const ['180f', '8ce5cc01-0a4d-11e9-ab14-d663bd873d93'], + ), + ), + isTrue, + ); + }); +} diff --git a/test/integration/ble_scan_config_test.dart b/test/integration/ble_scan_config_test.dart new file mode 100644 index 00000000..e877fe89 --- /dev/null +++ b/test/integration/ble_scan_config_test.dart @@ -0,0 +1,39 @@ +import 'package:bike_control/bluetooth/emulation/emulated_ble_platform.dart'; +import 'package:bike_control/utils/core.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:universal_ble/universal_ble.dart'; + +import 'harness/test_env.dart'; + +class _RecordingBlePlatform extends FakeUniversalBlePlatform { + PlatformConfig? scanConfig; + + @override + Future startScan({ScanFilter? scanFilter, PlatformConfig? platformConfig}) async { + scanConfig = platformConfig; + await super.startScan(scanFilter: scanFilter, platformConfig: platformConfig); + } +} + +void main() async { + final env = await IntegrationEnv.setUp(); + late _RecordingBlePlatform ble; + + setUp(() async { + await env.resetState(); + ble = _RecordingBlePlatform(); + UniversalBle.setInstance(ble); + }); + + tearDown(() async { + await env.resetConnection(); + UniversalBle.setInstance(env.ble); + }); + + test('Android low-latency scanning accepts both legacy and extended advertisements', () async { + await core.connection.performScanning(); + + expect(ble.scanConfig?.android?.legacy, isFalse); + expect(ble.scanConfig?.android?.scanMode, AndroidScanMode.lowLatency); + }); +} diff --git a/test/onelap_key_test.dart b/test/onelap_key_test.dart index c305517d..434f3c2c 100644 --- a/test/onelap_key_test.dart +++ b/test/onelap_key_test.dart @@ -15,6 +15,7 @@ import 'package:bike_control/utils/keymap/buttons.dart'; import 'package:bike_control/utils/keymap/keymap.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shadcn_flutter/shadcn_flutter.dart' show LucideIcons; import 'package:shared_preferences/shared_preferences.dart'; import 'package:universal_ble/universal_ble.dart'; @@ -239,6 +240,20 @@ Future main() async { }); } + test('diagram faces match the molded cross', () { + expect(OnelapKeyButtons.up.icon, LucideIcons.circle); + expect(OnelapKeyButtons.left.icon, LucideIcons.triangle); + expect(OnelapKeyButtons.right.icon, LucideIcons.square); + expect(OnelapKeyButtons.down.icon, LucideIcons.grip); + expect(OnelapKeyButtons.center.icon, isNull); + expect(OnelapKeyButtons.center.label, 'ONELAP'); + expect(device.controllerLayout.positions[OnelapKeyButtons.up], const Offset(0.5, 0.2)); + expect(device.controllerLayout.positions[OnelapKeyButtons.left], const Offset(0.2, 0.5)); + expect(device.controllerLayout.positions[OnelapKeyButtons.right], const Offset(0.8, 0.5)); + expect(device.controllerLayout.positions[OnelapKeyButtons.down], const Offset(0.5, 0.8)); + expect(device.controllerLayout.positions[OnelapKeyButtons.center], const Offset(0.5, 0.5)); + }); + test('Web exposes CC01 and registers all five buttons', () { expect( BluetoothDevice.servicesToScan,