@onekeyfe/hardware-cli 1.2.0-alpha.2 → 1.2.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ import { getCanonicalDeviceState, getCompatibleFeatures } from '../deviceStateCommands';
2
+
3
+ const createSdkMock = () => ({
4
+ searchDevices: jest.fn(),
5
+ getDeviceState: jest.fn(),
6
+ getFeatures: jest.fn(),
7
+ });
8
+
9
+ describe('设备状态 CLI 兼容层', () => {
10
+ test('Protocol V2 直接返回 SDK 搜索结果中的兼容 features', async () => {
11
+ const sdk = createSdkMock();
12
+ const features = {
13
+ protocol: 'V2',
14
+ deviceType: 'pro2',
15
+ deviceId: 'device-id',
16
+ };
17
+ sdk.searchDevices.mockResolvedValue({
18
+ success: true,
19
+ payload: [
20
+ {
21
+ connectId: 'pro2-connect-id',
22
+ state: { protocol: 'V2' },
23
+ features,
24
+ },
25
+ ],
26
+ });
27
+
28
+ await expect(getCompatibleFeatures(sdk as never, 'pro2-connect-id')).resolves.toEqual({
29
+ success: true,
30
+ payload: features,
31
+ });
32
+ expect(sdk.getFeatures).not.toHaveBeenCalled();
33
+ });
34
+
35
+ test('Protocol V1 继续调用公共 getFeatures 保持旧行为', async () => {
36
+ const sdk = createSdkMock();
37
+ const response = {
38
+ success: true,
39
+ payload: { protocol: 'V1', label: 'Classic' },
40
+ };
41
+ sdk.searchDevices.mockResolvedValue({
42
+ success: true,
43
+ payload: [
44
+ {
45
+ connectId: 'classic-connect-id',
46
+ state: { protocol: 'V1' },
47
+ },
48
+ ],
49
+ });
50
+ sdk.getFeatures.mockResolvedValue(response);
51
+
52
+ await expect(getCompatibleFeatures(sdk as never, 'classic-connect-id')).resolves.toBe(response);
53
+ expect(sdk.getFeatures).toHaveBeenCalledWith('classic-connect-id');
54
+ });
55
+
56
+ test('未显式指定设备时选择搜索结果中的第一台设备', async () => {
57
+ const sdk = createSdkMock();
58
+ const response = { success: true, payload: { protocol: 'V1' } };
59
+ sdk.searchDevices.mockResolvedValue({
60
+ success: true,
61
+ payload: [{ connectId: 'first-device', state: { protocol: 'V1' } }],
62
+ });
63
+ sdk.getFeatures.mockResolvedValue(response);
64
+
65
+ await expect(getCompatibleFeatures(sdk as never)).resolves.toBe(response);
66
+ expect(sdk.getFeatures).toHaveBeenCalledWith('first-device');
67
+ });
68
+
69
+ test('显式 connectId 不在搜索结果时返回结构化错误', async () => {
70
+ const sdk = createSdkMock();
71
+ sdk.searchDevices.mockResolvedValue({
72
+ success: true,
73
+ payload: [{ connectId: 'another-device', state: { protocol: 'V1' } }],
74
+ });
75
+
76
+ await expect(getCompatibleFeatures(sdk as never, 'missing-device')).resolves.toEqual({
77
+ success: false,
78
+ payload: {
79
+ code: 'DEVICE_NOT_FOUND',
80
+ error: 'Device not found: missing-device',
81
+ },
82
+ });
83
+ expect(sdk.getFeatures).not.toHaveBeenCalled();
84
+ });
85
+
86
+ test('get-state 将 firmware scope 传给 SDK', async () => {
87
+ const sdk = createSdkMock();
88
+ const response = { success: true, payload: { protocol: 'V2' } };
89
+ sdk.searchDevices.mockResolvedValue({
90
+ success: true,
91
+ payload: [{ connectId: 'pro2-connect-id', state: { protocol: 'V2' } }],
92
+ });
93
+ sdk.getDeviceState.mockResolvedValue(response);
94
+
95
+ await expect(
96
+ getCanonicalDeviceState(sdk as never, 'pro2-connect-id', 'firmware')
97
+ ).resolves.toBe(response);
98
+ expect(sdk.getDeviceState).toHaveBeenCalledWith('pro2-connect-id', {
99
+ scope: 'firmware',
100
+ });
101
+ expect(sdk.searchDevices).toHaveBeenCalledTimes(1);
102
+ });
103
+
104
+ test('get-state 未指定 connectId 时搜索并选择第一台设备', async () => {
105
+ const sdk = createSdkMock();
106
+ const state = { protocol: 'V2', revision: 2 };
107
+ sdk.searchDevices.mockResolvedValue({
108
+ success: true,
109
+ payload: [{ connectId: 'pro2-connect-id', state }],
110
+ });
111
+
112
+ await expect(getCanonicalDeviceState(sdk as never, undefined, 'runtime')).resolves.toEqual({
113
+ success: true,
114
+ payload: state,
115
+ });
116
+ expect(sdk.getDeviceState).not.toHaveBeenCalled();
117
+ });
118
+ });
@@ -0,0 +1,20 @@
1
+ import { getLegacyFirmwareConnectTimeout, program } from '../cli';
2
+
3
+ describe('firmware-update-legacy CLI command', () => {
4
+ test('提供 Classic/Pure 的本地固件升级命令', () => {
5
+ const command = program.commands.find(item => item.name() === 'firmware-update-legacy');
6
+
7
+ expect(command).toBeDefined();
8
+ expect(command?.description()).toBe(
9
+ 'Update Classic/Pure firmware through the legacy protocol'
10
+ );
11
+ expect(command?.options.find(option => option.long === '--binary')?.mandatory).toBe(true);
12
+ expect(command?.options.some(option => option.long === '--device-name')).toBe(true);
13
+ expect(command?.options.some(option => option.long === '--update-type')).toBe(true);
14
+ });
15
+
16
+ test('USB Classic 固件升级使用足够的设备探测超时', () => {
17
+ expect(getLegacyFirmwareConnectTimeout('usb')).toBe(90_000);
18
+ expect(getLegacyFirmwareConnectTimeout('ble')).toBeUndefined();
19
+ });
20
+ });
@@ -0,0 +1,19 @@
1
+ import { program } from '../cli';
2
+
3
+ describe('firmware-update-v4 CLI command', () => {
4
+ test('exposes firmware-update-v4 as the formal command', () => {
5
+ const command = program.commands.find(item => item.name() === 'firmware-update-v4');
6
+
7
+ expect(command).toBeDefined();
8
+ expect(command?.description()).toBe(
9
+ 'Run Protocol V2 firmware update through sdk.firmwareUpdateV4'
10
+ );
11
+ });
12
+
13
+ test('does not expose the pre-release firmware-update-v4-debug command', () => {
14
+ expect(program.commands.some(item => item.name() === 'firmware-update-v4-debug')).toBe(false);
15
+ expect(program.commands.some(item => item.aliases().includes('firmware-update-v4-debug'))).toBe(
16
+ false
17
+ );
18
+ });
19
+ });
@@ -0,0 +1,225 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ type MockCharacteristic = EventEmitter & {
4
+ uuid: string;
5
+ unsubscribe: jest.Mock;
6
+ subscribe: jest.Mock;
7
+ write: jest.Mock;
8
+ removeAllListeners: jest.Mock;
9
+ };
10
+
11
+ const createCharacteristic = (uuid: string): MockCharacteristic => {
12
+ const characteristic = new EventEmitter() as MockCharacteristic;
13
+ characteristic.uuid = uuid;
14
+ characteristic.unsubscribe = jest.fn(callback => callback());
15
+ characteristic.subscribe = jest.fn(callback => callback());
16
+ characteristic.write = jest.fn((_buffer, _withoutResponse, callback) => callback());
17
+ characteristic.removeAllListeners = jest.fn(
18
+ characteristic.removeAllListeners.bind(characteristic)
19
+ );
20
+ return characteristic;
21
+ };
22
+
23
+ const createPeripheral = (id: string) => {
24
+ const write = createCharacteristic('0002');
25
+ const notify = createCharacteristic('0003');
26
+ const service = {
27
+ uuid: '0001',
28
+ discoverCharacteristics: jest.fn((_uuids, callback) => callback(null, [write, notify])),
29
+ };
30
+ return {
31
+ peripheral: {
32
+ id,
33
+ state: 'connected',
34
+ advertisement: {
35
+ localName: `OneKey Pro 2 ${id}`,
36
+ serviceUuids: ['fffd'],
37
+ },
38
+ discoverServices: jest.fn((_uuids, callback) => callback(null, [service])),
39
+ connect: jest.fn(callback => callback()),
40
+ disconnect: jest.fn(callback => callback()),
41
+ },
42
+ write,
43
+ notify,
44
+ };
45
+ };
46
+
47
+ describe('Noble BLE plugin notification routing', () => {
48
+ afterEach(() => {
49
+ jest.resetModules();
50
+ jest.clearAllMocks();
51
+ });
52
+
53
+ test('routes notifications to the receiver waiting for the same device', async () => {
54
+ const deviceA = createPeripheral('device-a');
55
+ const deviceB = createPeripheral('device-b');
56
+ const noble = new EventEmitter() as EventEmitter & {
57
+ state: string;
58
+ startScanning: jest.Mock;
59
+ stopScanning: jest.Mock;
60
+ };
61
+ noble.state = 'poweredOn';
62
+ noble.startScanning = jest.fn((_services, _duplicates, callback) => {
63
+ callback?.();
64
+ noble.emit('discover', deviceA.peripheral);
65
+ noble.emit('discover', deviceB.peripheral);
66
+ });
67
+ noble.stopScanning = jest.fn(callback => callback?.());
68
+ jest.doMock('@stoprocent/noble', () => noble);
69
+
70
+ const { createNobleBlePlugin } = await import('../transports/nobleBlePlugin');
71
+ const plugin = createNobleBlePlugin();
72
+ await plugin.init();
73
+ await plugin.connect('device-a');
74
+ await plugin.connect('device-b');
75
+
76
+ const receiveA = plugin.receive('device-a');
77
+ const receiveB = plugin.receive('device-b');
78
+ deviceB.notify.emit('data', Buffer.from('bb', 'hex'));
79
+ deviceA.notify.emit('data', Buffer.from('aa', 'hex'));
80
+
81
+ await expect(Promise.all([receiveA, receiveB])).resolves.toEqual(['aa', 'bb']);
82
+ });
83
+
84
+ test('finishes disconnect cleanup when Noble never calls unsubscribe back', async () => {
85
+ const device = createPeripheral('device-a');
86
+ const noble = new EventEmitter() as EventEmitter & {
87
+ state: string;
88
+ startScanning: jest.Mock;
89
+ stopScanning: jest.Mock;
90
+ };
91
+ noble.state = 'poweredOn';
92
+ noble.startScanning = jest.fn((_services, _duplicates, callback) => {
93
+ callback?.();
94
+ noble.emit('discover', device.peripheral);
95
+ });
96
+ noble.stopScanning = jest.fn(callback => callback?.());
97
+ jest.doMock('@stoprocent/noble', () => noble);
98
+
99
+ const { createNobleBlePlugin } = await import('../transports/nobleBlePlugin');
100
+ const plugin = createNobleBlePlugin();
101
+ await plugin.init();
102
+ await plugin.connect('device-a');
103
+ device.notify.unsubscribe.mockImplementation(() => undefined);
104
+
105
+ const result = await Promise.race([
106
+ plugin.disconnect('device-a').then(() => 'completed'),
107
+ new Promise(resolve => {
108
+ setTimeout(() => resolve('blocked'), 300);
109
+ }),
110
+ ]);
111
+
112
+ expect(result).toBe('completed');
113
+ });
114
+
115
+ test('uses withoutResponse for normal and high-volume writes', async () => {
116
+ const device = createPeripheral('device-a');
117
+ const noble = new EventEmitter() as EventEmitter & {
118
+ state: string;
119
+ startScanning: jest.Mock;
120
+ stopScanning: jest.Mock;
121
+ };
122
+ noble.state = 'poweredOn';
123
+ noble.startScanning = jest.fn((_services, _duplicates, callback) => {
124
+ callback?.();
125
+ noble.emit('discover', device.peripheral);
126
+ });
127
+ noble.stopScanning = jest.fn(callback => callback?.());
128
+ jest.doMock('@stoprocent/noble', () => noble);
129
+
130
+ const { createNobleBlePlugin } = await import('../transports/nobleBlePlugin');
131
+ const plugin = createNobleBlePlugin();
132
+ await plugin.init();
133
+ await plugin.connect('device-a');
134
+
135
+ await plugin.send('device-a', 'aa');
136
+ await plugin.send('device-a', 'bb');
137
+
138
+ expect(device.write.write.mock.calls.map(([, withoutResponse]) => withoutResponse)).toEqual([
139
+ true,
140
+ true,
141
+ ]);
142
+ });
143
+
144
+ test('uses acknowledged writes when requested by firmware upload', async () => {
145
+ const device = createPeripheral('device-a');
146
+ const noble = new EventEmitter() as EventEmitter & {
147
+ state: string;
148
+ startScanning: jest.Mock;
149
+ stopScanning: jest.Mock;
150
+ };
151
+ noble.state = 'poweredOn';
152
+ noble.startScanning = jest.fn((_services, _duplicates, callback) => {
153
+ callback?.();
154
+ noble.emit('discover', device.peripheral);
155
+ });
156
+ noble.stopScanning = jest.fn(callback => callback?.());
157
+ jest.doMock('@stoprocent/noble', () => noble);
158
+
159
+ const { createNobleBlePlugin } = await import('../transports/nobleBlePlugin');
160
+ const plugin = createNobleBlePlugin();
161
+ await plugin.init();
162
+ await plugin.connect('device-a');
163
+
164
+ await (plugin.send as any)('device-a', 'aa', { withoutResponse: false });
165
+
166
+ expect(device.write.write).toHaveBeenCalledWith(expect.any(Buffer), false, expect.any(Function));
167
+ });
168
+
169
+ test('does not add a fixed delay between 192-byte writes', async () => {
170
+ const device = createPeripheral('device-a');
171
+ const noble = new EventEmitter() as EventEmitter & {
172
+ state: string;
173
+ startScanning: jest.Mock;
174
+ stopScanning: jest.Mock;
175
+ };
176
+ const wait = jest.fn(() => Promise.resolve());
177
+ noble.state = 'poweredOn';
178
+ noble.startScanning = jest.fn((_services, _duplicates, callback) => {
179
+ callback?.();
180
+ noble.emit('discover', device.peripheral);
181
+ });
182
+ noble.stopScanning = jest.fn(callback => callback?.());
183
+ jest.doMock('@stoprocent/noble', () => noble);
184
+ jest.doMock('@onekeyfe/hd-shared', () => ({
185
+ ...jest.requireActual('@onekeyfe/hd-shared'),
186
+ wait,
187
+ }));
188
+
189
+ const { createNobleBlePlugin } = await import('../transports/nobleBlePlugin');
190
+ const plugin = createNobleBlePlugin();
191
+ await plugin.init();
192
+ await plugin.connect('device-a');
193
+
194
+ await plugin.send('device-a', 'aa'.repeat(193));
195
+
196
+ expect(device.write.write).toHaveBeenCalledTimes(2);
197
+ expect(wait).not.toHaveBeenCalled();
198
+ });
199
+
200
+ test('preserves a short final BLE packet without padding', async () => {
201
+ const device = createPeripheral('device-a');
202
+ const noble = new EventEmitter() as EventEmitter & {
203
+ state: string;
204
+ startScanning: jest.Mock;
205
+ stopScanning: jest.Mock;
206
+ };
207
+ noble.state = 'poweredOn';
208
+ noble.startScanning = jest.fn((_services, _duplicates, callback) => {
209
+ callback?.();
210
+ noble.emit('discover', device.peripheral);
211
+ });
212
+ noble.stopScanning = jest.fn(callback => callback?.());
213
+ jest.doMock('@stoprocent/noble', () => noble);
214
+
215
+ const { createNobleBlePlugin } = await import('../transports/nobleBlePlugin');
216
+ const plugin = createNobleBlePlugin();
217
+ await plugin.init();
218
+ await plugin.connect('device-a');
219
+
220
+ await plugin.send('device-a', 'aabb');
221
+
222
+ const packet = device.write.write.mock.calls[0][0] as Buffer;
223
+ expect(packet).toEqual(Buffer.from('aabb', 'hex'));
224
+ });
225
+ });
@@ -0,0 +1,46 @@
1
+ import { buildWallpaperUploadMetrics, program } from '../cli';
2
+
3
+ describe('upload-wallpaper CLI command', () => {
4
+ test('exposes a command backed by the SDK wallpaper API', () => {
5
+ const command = program.commands.find(item => item.name() === 'upload-wallpaper');
6
+
7
+ expect(command).toBeDefined();
8
+ expect(command?.description()).toBe('Upload and activate a Pro2 wallpaper');
9
+ });
10
+
11
+ test('reports effective transfer speed from encoded bytes and elapsed time', () => {
12
+ expect(
13
+ buildWallpaperUploadMetrics({
14
+ totalBytes: 2_473_984,
15
+ transferredBytes: 2_473_984,
16
+ startedAt: 1_000,
17
+ endedAt: 2_000,
18
+ lastProgress: 100,
19
+ })
20
+ ).toEqual({
21
+ totalBytes: 2_473_984,
22
+ transferredBytes: 2_473_984,
23
+ totalSeconds: 1,
24
+ transferKiBPerSecond: 2416,
25
+ lastProgress: 100,
26
+ });
27
+ });
28
+
29
+ test('uses confirmed bytes for an interrupted transfer rate', () => {
30
+ expect(
31
+ buildWallpaperUploadMetrics({
32
+ totalBytes: 1_855_500,
33
+ transferredBytes: 631_800,
34
+ startedAt: 1_000,
35
+ endedAt: 101_000,
36
+ lastProgress: 34,
37
+ })
38
+ ).toEqual({
39
+ totalBytes: 1_855_500,
40
+ transferredBytes: 631_800,
41
+ totalSeconds: 100,
42
+ transferKiBPerSecond: 6.17,
43
+ lastProgress: 34,
44
+ });
45
+ });
46
+ });