fix(ble): match Onelap Key faces and discover it on Android (#440)

* fix(ble): match Onelap Key faces and strip firmware padding

The settings page drew the firmware revision's trailing padding as tofu after 0.105. Device Information strings now stop at the first NUL and drop 0xFF or non-UTF-8 tails. The controller diagram uses the molded cross: circle, triangle, square, dot pad, and ONELAP.

* fix(ble): show legacy Onelap Key advertisements on Android

universal_ble's default Android scan asks only for BLE 5 extended advertisements, so a BLE 4.x Onelap Key never appears. Request legacy advertisements at low latency, and accept a later packet that is the first one to carry the controller name.

* style: keep the Onelap scan change to the discovery lines

The previous commit reformatted connection.dart. Restore the surrounding file and leave the legacy-scan and name-arrival checks.

* fix(ble): preserve valid UTF-8 prefixes

Keep the valid device-information prefix before malformed UTF-8.
Discard printable bytes after the error and cover truncated sequences
and valid replacement characters with regression tests.

* fix(ble): retain extended advertisements

Allow both legacy and extended Android advertisements while keeping
low-latency scanning. Verify the configuration at the BLE platform
boundary and remove the incorrect extended-only explanation.

* style: use English comments and test descriptions

---------

Co-authored-by: haoxiang.yang <haoxiang.yang@megatronix.co>
This commit is contained in:
skyiea314
2026-11-06 15:38:36 +08:00
committed by GitHub
parent 4b41f4bdaf
commit fa56e76a9b
11 changed files with 277 additions and 11 deletions

View File

@@ -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

View File

@@ -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<int> 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<int> 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);
}
}

View File

@@ -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) {

View File

@@ -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;
}

View File

@@ -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];

View File

@@ -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<BleDevice> 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;
}

View File

@@ -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,

View File

@@ -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);
});
}

View File

@@ -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<String> 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,
);
});
}

View File

@@ -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<void> 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);
});
}

View File

@@ -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<void> 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,