feat(ble): add Magene Onelap Key support (#438)

Detect Onelap Key controllers and subscribe to their CC02 notification characteristic. Decode five-button click and long-press masks, register the buttons with the shared keymap, and cover real captured frames with regression tests.

Jira-Id: TT-0

Co-authored-by: haoxiang.yang <haoxiang.yang@megatronix.co>
This commit is contained in:
skyiea314
2026-11-05 16:16:19 +08:00
committed by GitHub
parent 709649ddaf
commit d2d03fee9b
8 changed files with 648 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
# Magene Onelap Key Five-Button Controller
This beta driver supports the legacy `Onelap Key` five-button BLE controller. Physical devices advertise names such as `Onelap Key_12224`; name matching is case-insensitive. Other Magene products, QED/QED2 devices, and unnamed devices that happen to expose the same private service are outside the detection scope.
## Connection and mapping
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.
## Notification layout
A notification must contain at least 11 bytes, with `data[1] == 0xf5` and `data[2] == 0x10`. Indexes are zero-based.
| Byte | Meaning |
| --- | --- |
| `data[5] & 0x1f` | Device type: 0 general, 1 left-hand, 2 right-hand; unknown types are ignored |
| `(data[5] >> 5) & 7` | Device index |
| `data[8]` | Single-click bit mask |
| `data[10]` | Long-press bit mask |
Mask bits `01/02/04/08/10` represent Center, Left, Up, Right, and Down respectively. The upper three bits have no verified five-button meaning. The driver leaves other fields uninterpreted instead of inventing sequence numbers or checksums. Consecutive identical click frames are dispatched independently.
For the verified hardware, `8bf510e503000000000004` reports an Up long press and `8bf510e503000004000000` reports the corresponding release. The release frame does not trigger another Shift Up. The all-zero event mask in the initial hold frame also produces no click.
## Verification
On 2026-11-05, one `Onelap Key_12224` was captured on macOS. All five single-click gestures and all five long-press gestures passed the ten-step physical acceptance check. The real gesture frames and long-press release frames are stored in `test/fixtures/onelap_key_capture.json` and replayed by `test/onelap_key_test.dart`. Tests also cover notification subscription, the absence of initialization writes, native and Web detection paths, device isolation, malformed frames, and long-press cleanup.
The physical capture used a separate BLE diagnostic tool. BikeControl's Dart implementation is validated by replaying those frames and by simulated BLE tests. This does not claim real-device validation on Windows, Android, or iOS, nor in-game validation in MyWhoosh. No extracted application DLLs, firmware, account data, or authentication material are included.

View File

@@ -69,6 +69,7 @@ Best follow our landing page and the "Get Started" button: [bikecontrol.app](htt
- Stages SB20 Smart Bike (beta)
- CYCPLUS BC2 Virtual Shifter
- Thinkrider VS200 Virtual Shifter (beta)
- Magene Onelap Key (five-button controller, beta; [connection and protocol](INSTRUCTIONS_ONELAP_KEY.md))
- Elite Sterzo Smart (for steering support)
- Elite Square Smart Frame (beta)
- Your Phone!

View File

@@ -46,6 +46,7 @@ import 'elite/elite_rizer.dart';
import 'elite/elite_square.dart';
import 'elite/elite_sterzo.dart';
import 'ltwoo/ltwoo_erx.dart';
import 'magene/onelap_key.dart';
import 'sensors/ble_cadence_device.dart';
import 'sensors/ble_heart_rate_device.dart';
import 'sensors/ble_power_device.dart';
@@ -103,6 +104,7 @@ abstract class BluetoothDevice extends BaseDevice {
ShimanoDi2Constants.SERVICE_UUID_ALTERNATIVE,
OpenBikeControlConstants.SERVICE_UUID,
ThinkRiderVs200Constants.SERVICE_UUID,
OnelapKeyConstants.serviceUuid,
// Nordic UART Service — needed so L-TWOO derailleurs show up in filtered
// scans; device matching itself stays name-gated (NUS is far too generic).
LtwooErxConstants.SERVICE_UUID,
@@ -280,6 +282,7 @@ abstract class BluetoothDevice extends BaseDevice {
_ when scanResult.name!.toUpperCase().startsWith('CYCPLUS') && scanResult.name!.toUpperCase().contains('BC2') =>
CycplusBc2(scanResult),
_ when scanResult.name!.toUpperCase().startsWith('THINK VS') => ThinkRiderVs200(scanResult),
_ when OnelapKeyConstants.matchesName(scanResult.name) => OnelapKey(scanResult),
_ when LtwooErxConstants.matchesName(scanResult.name) => LtwooErx(scanResult),
// Windows' universal_ble surfaces the Tacx Neo with an empty
// advertisement (no services/serviceData), so match on name alone.
@@ -368,6 +371,7 @@ abstract class BluetoothDevice extends BaseDevice {
_ when scanResult.name!.toUpperCase().startsWith('CYCPLUS') && scanResult.name!.toUpperCase().contains('BC2') =>
CycplusBc2(scanResult),
_ when scanResult.name!.toUpperCase().startsWith('THINK VS') => ThinkRiderVs200(scanResult),
_ when OnelapKeyConstants.matchesName(scanResult.name) => OnelapKey(scanResult),
_ when LtwooErxConstants.matchesName(scanResult.name) => LtwooErx(scanResult),
// Windows' universal_ble surfaces the Tacx Neo with an empty
// advertisement (no services/serviceData) — only the name is usable, so

View File

@@ -0,0 +1,154 @@
import 'dart:typed_data';
import 'package:bike_control/utils/keymap/buttons.dart';
import 'package:bike_control/widgets/controller/controller_layout.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart' show LucideIcons;
import 'package:universal_ble/universal_ble.dart';
import '../bluetooth_device.dart';
import 'onelap_key_packet.dart';
class OnelapKey extends BluetoothDevice {
OnelapKey(super.scanResult)
: super(
availableButtons: OnelapKeyButtons.values,
allowMultiple: true,
isBeta: true,
);
bool _longPressActive = false;
@override
ControllerLayout get controllerLayout => ControllerLayout(
aspectRatio: 1,
shape: ContourShape.pill,
positions: {
OnelapKeyButtons.center: const Offset(0.5, 0.5),
OnelapKeyButtons.left: const Offset(0.2, 0.5),
OnelapKeyButtons.up: const Offset(0.5, 0.2),
OnelapKeyButtons.right: const Offset(0.8, 0.5),
OnelapKeyButtons.down: const Offset(0.5, 0.8),
},
);
@override
Future<void> handleServices(List<BleService> services) async {
final service = services.firstWhere(
(service) => service.uuid.toLowerCase() == OnelapKeyConstants.serviceUuid,
orElse: () => throw Exception(
'Service not found: ${OnelapKeyConstants.serviceUuid}',
),
);
final characteristic = service.characteristics.firstWhere(
(characteristic) => characteristic.uuid.toLowerCase() == OnelapKeyConstants.characteristicUuid,
orElse: () => throw Exception(
'Characteristic not found: ${OnelapKeyConstants.characteristicUuid}',
),
);
await _releaseLongPress();
await UniversalBle.subscribeNotifications(
device.deviceId,
service.uuid,
characteristic.uuid,
);
}
List<ControllerButton> _buttonsForMask(int mask) => [
for (var index = 0; index < availableButtons.length; index++)
if ((mask & (1 << index)) != 0) availableButtons[index],
];
Future<void> _releaseLongPress() async {
if (!_longPressActive) {
return;
}
_longPressActive = false;
await handleButtonsClicked([]);
}
@override
Future<void> processCharacteristic(
String characteristic,
Uint8List bytes,
) async {
if (characteristic.toLowerCase() != OnelapKeyConstants.characteristicUuid) {
return;
}
final packet = OnelapKeyPacket.parse(bytes);
if (packet == null) {
await _releaseLongPress();
return;
}
// Frames encode gestures; identical consecutive clicks must not be deduplicated.
await _releaseLongPress();
if (packet.clickedButtons != 0) {
await handleButtonsClicked(_buttonsForMask(packet.clickedButtons));
await handleButtonsClicked([]);
}
if (packet.longPressedButtons != 0) {
_longPressActive = true;
await handleButtonsClicked(
_buttonsForMask(packet.longPressedButtons),
longPress: true,
);
}
}
@override
Future<void> disconnect() async {
await _releaseLongPress();
await super.disconnect();
}
}
class OnelapKeyConstants {
static const serviceUuid = '8ce5cc01-0a4d-11e9-ab14-d663bd873d93';
static const characteristicUuid = '8ce5cc02-0a4d-11e9-ab14-d663bd873d93';
static bool matchesName(String? name) {
final normalized = name?.trim().toLowerCase();
return normalized == 'onelap key' || (normalized?.startsWith('onelap key_') ?? false);
}
}
class OnelapKeyButtons {
static const center = ControllerButton(
'onelapCenter',
identifier: 1,
action: InGameAction.select,
color: Colors.black,
icon: LucideIcons.circle,
);
static const left = ControllerButton(
'onelapLeft',
identifier: 2,
action: InGameAction.navigateLeft,
color: Colors.black,
icon: LucideIcons.chevronLeft,
);
static const up = ControllerButton(
'onelapUp',
identifier: 3,
action: InGameAction.shiftUp,
color: Colors.black,
icon: LucideIcons.plus,
);
static const right = ControllerButton(
'onelapRight',
identifier: 4,
action: InGameAction.navigateRight,
color: Colors.black,
icon: LucideIcons.chevronRight,
);
static const down = ControllerButton(
'onelapDown',
identifier: 5,
action: InGameAction.shiftDown,
color: Colors.black,
icon: LucideIcons.minus,
);
static const values = [center, left, up, right, down];
}

View File

@@ -0,0 +1,30 @@
class OnelapKeyPacket {
final int deviceType;
final int deviceIndex;
final int clickedButtons;
final int longPressedButtons;
const OnelapKeyPacket({
required this.deviceType,
required this.deviceIndex,
required this.clickedButtons,
required this.longPressedButtons,
});
static OnelapKeyPacket? parse(List<int> bytes) {
if (bytes.length < 11 || bytes[1] != 0xf5 || bytes[2] != 0x10) {
return null;
}
final deviceType = bytes[5] & 0x1f;
if (deviceType > 2) {
return null;
}
return OnelapKeyPacket(
deviceType: deviceType,
deviceIndex: (bytes[5] >> 5) & 0x07,
clickedButtons: bytes[8] & 0x1f,
longPressedButtons: bytes[10] & 0x1f,
);
}
}

View File

@@ -2,6 +2,7 @@ import 'package:bike_control/bluetooth/devices/cycplus/cycplus_bc2.dart';
import 'package:bike_control/bluetooth/devices/elite/elite_square.dart';
import 'package:bike_control/bluetooth/devices/elite/elite_sterzo.dart';
import 'package:bike_control/bluetooth/devices/gyroscope/gyroscope_steering.dart';
import 'package:bike_control/bluetooth/devices/magene/onelap_key.dart';
import 'package:bike_control/bluetooth/devices/openbikecontrol/protocol_parser.dart';
import 'package:bike_control/bluetooth/devices/shimano/shimano_di2.dart';
import 'package:bike_control/bluetooth/devices/stages/stages_smart_bike.dart';
@@ -328,6 +329,7 @@ class ControllerButton {
...WahooKickrShiftButtons.values,
...StagesSmartBikeButtons.values,
...CycplusBc2Buttons.values,
...OnelapKeyButtons.values,
...WheeltopEdsButtons.values,
...ShimanoDi2Buttons.values,
...OpenBikeProtocolParser.BUTTON_NAMES.values,

80
test/fixtures/onelap_key_capture.json vendored Normal file
View File

@@ -0,0 +1,80 @@
{
"description": "Real Onelap Key_12224 single-click and long-press capture from the macOS diagnostic run on 2026-11-05.",
"cases": [
{
"button": "onelapCenter",
"trigger": "singleClick",
"packets": [
"8bf510e503000001010000"
]
},
{
"button": "onelapLeft",
"trigger": "singleClick",
"packets": [
"8bf510e503000002020000"
]
},
{
"button": "onelapUp",
"trigger": "singleClick",
"packets": [
"8bf510e503000004040000"
]
},
{
"button": "onelapRight",
"trigger": "singleClick",
"packets": [
"8bf510e503000008080000"
]
},
{
"button": "onelapDown",
"trigger": "singleClick",
"packets": [
"8bf510e503000010100000"
]
},
{
"button": "onelapCenter",
"trigger": "longPress",
"packets": [
"8bf510e503000000000001",
"8bf510e503000001000000"
]
},
{
"button": "onelapLeft",
"trigger": "longPress",
"packets": [
"8bf510e503000000000002",
"8bf510e503000002000000"
]
},
{
"button": "onelapUp",
"trigger": "longPress",
"packets": [
"8bf510e503000000000004",
"8bf510e503000004000000"
]
},
{
"button": "onelapRight",
"trigger": "longPress",
"packets": [
"8bf510e503000000000008",
"8bf510e503000008000000"
]
},
{
"button": "onelapDown",
"trigger": "longPress",
"packets": [
"8bf510e503000000000010",
"8bf510e503000010000000"
]
}
]
}

347
test/onelap_key_test.dart Normal file
View File

@@ -0,0 +1,347 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:bike_control/bluetooth/devices/bluetooth_device.dart';
import 'package:bike_control/bluetooth/devices/magene/onelap_key.dart';
import 'package:bike_control/bluetooth/devices/magene/onelap_key_packet.dart';
import 'package:bike_control/bluetooth/emulation/emulated_ble_platform.dart';
import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/utils/actions/base_actions.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/keymap/apps/custom_app.dart';
import 'package:bike_control/utils/keymap/apps/my_whoosh.dart';
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:shared_preferences/shared_preferences.dart';
import 'package:universal_ble/universal_ble.dart';
Uint8List _hex(String value) => Uint8List.fromList([
for (var offset = 0; offset < value.length; offset += 2) int.parse(value.substring(offset, offset + 2), radix: 16),
]);
class _TestOnelapKey extends OnelapKey {
_TestOnelapKey(super.scanResult);
bool repeatEnabled = false;
@override
bool get isProEnabledForRepeat => repeatEnabled;
@override
Future<void> disconnectUpstream() async {}
}
Future<void> main() async {
TestWidgetsFlutterBinding.ensureInitialized();
await AppLocalizations.load(const Locale('en'));
final fixture =
jsonDecode(
File('test/fixtures/onelap_key_capture.json').readAsStringSync(),
)
as Map<String, dynamic>;
final cases = fixture['cases'] as List<dynamic>;
late _TestOnelapKey device;
late StubActions actions;
setUp(() {
actions = StubActions();
core.actionHandler = actions;
device = _TestOnelapKey(
BleDevice(deviceId: 'onelap-1', name: 'Onelap Key_12224'),
);
});
tearDown(() async {
BluetoothDevice.debugIsWeb = null;
await device.disconnect();
await device.actionStreamInternal.close();
});
Future<void> send(String hex, {String? characteristic}) => device.processCharacteristic(
characteristic ?? OnelapKeyConstants.characteristicUuid,
_hex(hex),
);
group('Onelap Key hardware frames', () {
for (final value in cases) {
final sample = value as Map<String, dynamic>;
final name = sample['button'] as String;
final longPress = sample['trigger'] == 'longPress';
test('$name ${sample['trigger']}', () async {
for (final value in sample['packets'] as List<dynamic>) {
await send(value as String);
}
final button = OnelapKeyButtons.values.singleWhere(
(button) => button.name == name,
);
if (longPress) {
expect(actions.performedActions, [
PerformedAction(
button,
isDown: true,
isUp: false,
trigger: ButtonTrigger.longPress,
),
PerformedAction(
button,
isDown: false,
isUp: true,
trigger: ButtonTrigger.longPress,
),
]);
} else {
expect(actions.performedActions, [
PerformedAction(button, isDown: true, isUp: true),
]);
}
});
}
test('preserves consecutive identical clicks', () async {
await send('8bf510e503000004040000');
await send('8bf510e503000004040000');
expect(actions.performedActions, [
PerformedAction(OnelapKeyButtons.up, isDown: true, isUp: true),
PerformedAction(OnelapKeyButtons.up, isDown: true, isUp: true),
]);
});
test('dispatches all known buttons in a multi-bit mask', () async {
await send('8bf510e5030000000a0000');
expect(actions.performedActions.map((action) => action.button.name), [
'onelapLeft',
'onelapRight',
]);
});
test('ignores CC03 and other messages', () async {
await send(
'8bf510e503000004040000',
characteristic: '8ce5cc03-0a4d-11e9-ab14-d663bd873d93',
);
await send('8b0010e503000004040000');
await send('8bf500e503000004040000');
expect(actions.performedActions, isEmpty);
});
test('ignores short frames and unknown high bits', () async {
for (var length = 0; length < 11; length++) {
await device.processCharacteristic(
OnelapKeyConstants.characteristicUuid,
Uint8List(length),
);
}
await send('8bf510e503000000e000e0');
expect(actions.performedActions, isEmpty);
});
test('invalid frames release an active long press', () async {
await send('8bf510e503000000000004');
await send('00');
expect(actions.performedActions, [
PerformedAction(
OnelapKeyButtons.up,
isDown: true,
isUp: false,
trigger: ButtonTrigger.longPress,
),
PerformedAction(
OnelapKeyButtons.up,
isDown: false,
isUp: true,
trigger: ButtonTrigger.longPress,
),
]);
});
test('disconnect releases long press and the next click starts clean', () async {
await send('8bf510e503000000000001');
await device.disconnect();
await send('8bf510e503000004040000');
expect(actions.performedActions, [
PerformedAction(
OnelapKeyButtons.center,
isDown: true,
isUp: false,
trigger: ButtonTrigger.longPress,
),
PerformedAction(
OnelapKeyButtons.center,
isDown: false,
isUp: true,
trigger: ButtonTrigger.longPress,
),
PerformedAction(OnelapKeyButtons.up, isDown: true, isUp: true),
]);
});
test('releases the previous long press before a new gesture', () async {
await send('8bf510e503000000000001');
await send('8bf510e503000004040000');
expect(actions.performedActions.last.trigger, ButtonTrigger.singleClick);
expect(actions.performedActions[1].isUp, isTrue);
expect(actions.performedActions, hasLength(3));
});
test('characteristic UUID matching is case-insensitive', () async {
await send(
'8bf510e503000004040000',
characteristic: OnelapKeyConstants.characteristicUuid.toUpperCase(),
);
expect(actions.performedActions, hasLength(1));
});
});
group('Onelap Key detection and registration', () {
for (final web in [false, true]) {
test('${web ? 'Web' : 'native'} detects a battery-only advertisement by name', () {
BluetoothDevice.debugIsWeb = () => web;
for (final name in [
'Onelap Key_12224',
'ONELAP KEY_12224',
'Onelap Key',
]) {
final result = BluetoothDevice.fromScanResult(
BleDevice(
deviceId: 'scan',
name: name,
services: ['0000180f-0000-1000-8000-00805f9b34fb'],
),
);
expect(result, isA<OnelapKey>());
}
});
test('${web ? 'Web' : 'native'} ignores other Magene devices and unnamed devices', () {
BluetoothDevice.debugIsWeb = () => web;
for (final name in ['Onelap Keyboard', 'Magene', 'Onelap']) {
expect(
BluetoothDevice.fromScanResult(
BleDevice(deviceId: 'other', name: name),
),
isNull,
);
}
expect(
BluetoothDevice.fromScanResult(
BleDevice(
deviceId: 'unnamed',
name: null,
services: [OnelapKeyConstants.serviceUuid],
),
),
isNull,
);
});
}
test('Web exposes CC01 and registers all five buttons', () {
expect(
BluetoothDevice.servicesToScan,
contains(OnelapKeyConstants.serviceUuid),
);
expect(ControllerButton.values, containsAll(OnelapKeyButtons.values));
expect(device.controllerLayout.positions, hasLength(5));
expect(device.supportsLongPress, isTrue);
});
test('MyWhoosh mapping includes all five buttons after registration', () async {
SharedPreferences.setMockInitialValues({'trainer_app': 'MyWhoosh'});
core.settings.prefs = await SharedPreferences.getInstance();
final keymap = MyWhoosh().keymap;
keymap.addNewButtons(device.availableButtons);
for (final button in device.availableButtons) {
expect(keymap.getKeyPair(button)?.inGameAction, button.action);
}
});
test('hardware release stops Pro implicit repeat', () async {
final app = CustomApp(profileName: 'Onelap repeat');
final button = device.availableButtons[2];
app.keymap.addKeyPair(
KeyPair(
buttons: [button],
physicalKey: null,
logicalKey: null,
inGameAction: InGameAction.shiftUp,
),
);
actions.supportedApp = app;
device.repeatEnabled = true;
await send('8bf510e503000000000004');
await Future<void>.delayed(Duration.zero);
expect(actions.performedActions, hasLength(1));
await send('8bf510e503000004000000');
final afterRelease = actions.performedActions.length;
await Future<void>.delayed(const Duration(milliseconds: 350));
expect(actions.performedActions, hasLength(afterRelease));
});
test('multiple controllers keep independent device identifiers', () {
final other = OnelapKey(
BleDevice(deviceId: 'onelap-2', name: 'Onelap Key_2'),
);
expect(
device.availableButtons.every(
(button) => button.sourceDeviceId == 'onelap-1',
),
isTrue,
);
expect(
other.availableButtons.every(
(button) => button.sourceDeviceId == 'onelap-2',
),
isTrue,
);
expect(
other.availableButtons.first,
isNot(equals(device.availableButtons.first)),
);
});
test('subscribes only to CC02 and sends no initialization write', () async {
final peripheral = FakePeripheral(
deviceId: device.uniqueId,
name: device.name,
services: [
BleService(OnelapKeyConstants.serviceUuid, [
BleCharacteristic(OnelapKeyConstants.characteristicUuid, [
CharacteristicProperty.notify,
], []),
]),
],
);
final ble = FakeUniversalBlePlatform()..addPeripheral(peripheral);
UniversalBle.setInstance(ble);
await device.handleServices(peripheral.services);
expect(peripheral.subscriptions, [
OnelapKeyConstants.characteristicUuid,
]);
expect(peripheral.writes, isEmpty);
});
test('missing CC01 or CC02 fails clearly', () async {
await expectLater(device.handleServices([]), throwsException);
await expectLater(
device.handleServices([
BleService(OnelapKeyConstants.serviceUuid, []),
]),
throwsException,
);
});
});
test('protocol preserves device type and index and rejects unknown types', () {
final bytes = _hex('8bf510e503e20000040000');
final packet = OnelapKeyPacket.parse(bytes)!;
expect(packet.deviceType, 2);
expect(packet.deviceIndex, 7);
expect(packet.clickedButtons, 4);
bytes[5] = 3;
expect(OnelapKeyPacket.parse(bytes), isNull);
});
}