@onekeyfe/hd-transport-lowlevel 1.1.27-alpha.35 → 1.1.27-alpha.4

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.
package/dist/index.d.ts CHANGED
@@ -1,46 +1,26 @@
1
- import * as transport from '@onekeyfe/hd-transport';
2
- import transport__default, { ProtocolType, LowlevelTransportSharedPlugin, LowLevelDevice, TransportCallOptions } from '@onekeyfe/hd-transport';
1
+ import * as _onekeyfe_hd_transport from '@onekeyfe/hd-transport';
2
+ import _onekeyfe_hd_transport__default, { LowlevelTransportSharedPlugin } from '@onekeyfe/hd-transport';
3
3
  import EventEmitter from 'events';
4
4
 
5
5
  type LowLevelAcquireInput = {
6
6
  uuid: string;
7
- expectedProtocol?: ProtocolType;
8
7
  };
9
8
 
10
9
  declare class LowlevelTransport {
11
- _messages: ReturnType<typeof transport__default.parseConfigure> | undefined;
12
- _messagesV2: ReturnType<typeof transport__default.parseConfigure> | undefined;
10
+ _messages: ReturnType<typeof _onekeyfe_hd_transport__default.parseConfigure> | undefined;
13
11
  configured: boolean;
14
12
  Log?: any;
15
13
  emitter?: EventEmitter;
16
14
  plugin: LowlevelTransportSharedPlugin;
17
- private deviceProtocol;
18
- private deviceProtocolHints;
19
- private protocolV2Assemblers;
20
- getProtocolType(path: string): ProtocolType;
21
15
  init(logger: any, emitter: EventEmitter, plugin: LowlevelTransportSharedPlugin): void;
22
16
  configure(signedData: any): void;
23
- configureProtocolV2(signedData: any): void;
24
17
  listen(): void;
25
- enumerate(): Promise<LowLevelDevice[]>;
18
+ enumerate(): Promise<_onekeyfe_hd_transport.LowLevelDevice[]>;
26
19
  acquire(input: LowLevelAcquireInput): Promise<{
27
20
  uuid: string;
28
- protocolType: ProtocolType;
29
21
  }>;
30
22
  release(uuid: string): Promise<boolean>;
31
- call(uuid: string, name: string, data: Record<string, unknown>, options?: TransportCallOptions): Promise<transport.MessageFromOneKey>;
32
- private callProtocolV1;
33
- private createProtocolTimeoutError;
34
- private createProtocolMismatchError;
35
- private detectProtocol;
36
- private resetConnectionAfterProbe;
37
- private probeProtocolV1;
38
- private probeProtocolV2;
39
- private receiveHex;
40
- private readProtocolV1Message;
41
- private readProtocolV2Frame;
42
- private writeProtocolV2Frame;
43
- private callProtocolV2;
23
+ call(uuid: string, name: string, data: Record<string, unknown>): Promise<_onekeyfe_hd_transport.MessageFromOneKey>;
44
24
  cancel(): void;
45
25
  }
46
26
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,SAWN,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,YAAY,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,EACV,cAAc,EACd,6BAA6B,EAC7B,YAAY,EACZ,oBAAoB,EACrB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAqBpD,MAAM,CAAC,OAAO,OAAO,iBAAiB;IACpC,SAAS,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAEnE,WAAW,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAErE,UAAU,UAAS;IAEnB,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV,OAAO,CAAC,EAAE,YAAY,CAAC;IAEvB,MAAM,EAAE,6BAA6B,CAAuC;IAE5E,OAAO,CAAC,cAAc,CAAwC;IAE9D,OAAO,CAAC,mBAAmB,CAAwC;IAEnE,OAAO,CAAC,oBAAoB,CAAoD;IAEhF,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY;IAI3C,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,6BAA6B;IAO9E,SAAS,CAAC,UAAU,EAAE,GAAG;IAMzB,mBAAmB,CAAC,UAAU,EAAE,GAAG;IAInC,MAAM;IAIA,SAAS;IAWT,OAAO,CAAC,KAAK,EAAE,oBAAoB;;;;IAuBnC,OAAO,CAAC,IAAI,EAAE,MAAM;IAapB,IAAI,CACR,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,oBAAoB;YA6BlB,cAAc;IAuC5B,OAAO,CAAC,0BAA0B;IAOlC,OAAO,CAAC,2BAA2B;YAOrB,cAAc;YAiDd,yBAAyB;YA0BzB,eAAe;YAef,eAAe;YAoBf,UAAU;YAUV,qBAAqB;YAmBrB,mBAAmB;YAqBnB,oBAAoB;YAOpB,cAAc;IAsC5B,MAAM;CAGP"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,SAA8B,MAAM,wBAAwB,CAAC;AAEpE,OAAO,KAAK,YAAY,MAAM,QAAQ,CAAC;AACvC,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAIpD,MAAM,CAAC,OAAO,OAAO,iBAAiB;IACpC,SAAS,EAAE,UAAU,CAAC,OAAO,SAAS,CAAC,cAAc,CAAC,GAAG,SAAS,CAAC;IAEnE,UAAU,UAAS;IAEnB,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV,OAAO,CAAC,EAAE,YAAY,CAAC;IAEvB,MAAM,EAAE,6BAA6B,CAAuC;IAE5E,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,6BAA6B;IAO9E,SAAS,CAAC,UAAU,EAAE,GAAG;IAMzB,MAAM;IAIN,SAAS;IAIH,OAAO,CAAC,KAAK,EAAE,oBAAoB;;;IAanC,OAAO,CAAC,IAAI,EAAE,MAAM;IAUpB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAuCpE,MAAM;CAGP"}
package/dist/index.js CHANGED
@@ -37,31 +37,11 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
37
37
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
38
  };
39
39
 
40
- const { check, ProtocolV1, parseConfigure } = transport__default["default"];
41
- const PROTOCOL_PROBE_TIMEOUT_MS = 1000;
42
- const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
43
- const LOWLEVEL_PROTOCOL_TIMEOUT_MS = 30000;
44
- const LOWLEVEL_PROTOCOL_V2_PACKET_LENGTH = 64;
45
- function inferProtocolHintFromDeviceName(name) {
46
- return /\bpro\s*2\b/i.test(name !== null && name !== void 0 ? name : '') ? 'V2' : undefined;
47
- }
48
- function isProtocolV1TransportChunk(data) {
49
- return data.length >= 9 && data[0] === 0x3f && data[1] === 0x23 && data[2] === 0x23;
50
- }
51
- function readProtocolV1PayloadLength(data) {
52
- return data[5] * 0x1000000 + data[6] * 0x10000 + data[7] * 0x100 + data[8];
53
- }
40
+ const { check, buildBuffers, receiveOne, parseConfigure } = transport__default["default"];
54
41
  class LowlevelTransport {
55
42
  constructor() {
56
43
  this.configured = false;
57
44
  this.plugin = {};
58
- this.deviceProtocol = new Map();
59
- this.deviceProtocolHints = new Map();
60
- this.protocolV2Assemblers = new Map();
61
- }
62
- getProtocolType(path) {
63
- var _a;
64
- return (_a = this.deviceProtocol.get(path)) !== null && _a !== void 0 ? _a : 'V1';
65
45
  }
66
46
  init(logger, emitter, plugin) {
67
47
  this.Log = logger;
@@ -74,48 +54,28 @@ class LowlevelTransport {
74
54
  this.configured = true;
75
55
  this._messages = messages;
76
56
  }
77
- configureProtocolV2(signedData) {
78
- this._messagesV2 = parseConfigure(signedData);
79
- }
80
57
  listen() {
81
58
  }
82
59
  enumerate() {
83
- return __awaiter(this, void 0, void 0, function* () {
84
- const devices = yield this.plugin.enumerate();
85
- return devices.map((device) => {
86
- const protocolHint = inferProtocolHintFromDeviceName(device.name);
87
- if (protocolHint) {
88
- this.deviceProtocolHints.set(device.id, protocolHint);
89
- }
90
- return device;
91
- });
92
- });
60
+ return this.plugin.enumerate();
93
61
  }
94
62
  acquire(input) {
95
63
  var _a;
96
64
  return __awaiter(this, void 0, void 0, function* () {
97
65
  try {
98
66
  yield this.plugin.connect(input.uuid);
67
+ return { uuid: input.uuid };
99
68
  }
100
69
  catch (error) {
101
70
  this.Log.debug('lowlelvel transport connect error: ', error);
102
71
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.LowlevelTrasnportConnectError, (_a = error.message) !== null && _a !== void 0 ? _a : error);
103
72
  }
104
- this.protocolV2Assemblers.set(input.uuid, new transport.ProtocolV2FrameAssembler());
105
- const protocolHint = input.expectedProtocol
106
- ? undefined
107
- : this.deviceProtocolHints.get(input.uuid);
108
- const protocolType = yield this.detectProtocol(input.uuid, input.expectedProtocol, protocolHint);
109
- return { uuid: input.uuid, protocolType };
110
73
  });
111
74
  }
112
75
  release(uuid) {
113
76
  return __awaiter(this, void 0, void 0, function* () {
114
77
  try {
115
78
  yield this.plugin.disconnect(uuid);
116
- this.deviceProtocol.delete(uuid);
117
- this.deviceProtocolHints.delete(uuid);
118
- this.protocolV2Assemblers.delete(uuid);
119
79
  return true;
120
80
  }
121
81
  catch (error) {
@@ -124,31 +84,19 @@ class LowlevelTransport {
124
84
  }
125
85
  });
126
86
  }
127
- call(uuid, name, data, options) {
87
+ call(uuid, name, data) {
128
88
  return __awaiter(this, void 0, void 0, function* () {
129
89
  if (this._messages === null || !this._messages) {
130
90
  throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
131
91
  }
132
- const protocol = this.getProtocolType(uuid);
92
+ const messages = this._messages;
133
93
  if (transport.LogBlockCommand.has(name)) {
134
- this.Log.debug('lowlevel-transport', 'call-', ' name: ', name, ' protocol: ', protocol);
94
+ this.Log.debug('lowlevel-transport', 'call-', ' name: ', name);
135
95
  }
136
96
  else {
137
- this.Log.debug('lowlevel-transport', 'call-', ' name: ', name, ' data: ', data, ' protocol: ', protocol);
138
- }
139
- if (protocol === 'V2') {
140
- return this.callProtocolV2(uuid, name, data, options);
97
+ this.Log.debug('lowlevel-transport', 'call-', ' name: ', name, ' data: ', data);
141
98
  }
142
- return this.callProtocolV1(uuid, name, data, options);
143
- });
144
- }
145
- callProtocolV1(uuid, name, data, options) {
146
- return __awaiter(this, void 0, void 0, function* () {
147
- if (!this._messages) {
148
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
149
- }
150
- const messages = this._messages;
151
- const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
99
+ const buffers = buildBuffers(messages, name, data);
152
100
  for (const o of buffers) {
153
101
  const outData = o.toString('hex');
154
102
  this.Log.debug('send hex strting: ', outData);
@@ -161,209 +109,16 @@ class LowlevelTransport {
161
109
  }
162
110
  }
163
111
  try {
164
- const response = yield this.readProtocolV1Message(options === null || options === void 0 ? void 0 : options.timeoutMs);
112
+ const response = yield this.plugin.receive();
113
+ if (typeof response !== 'string') {
114
+ throw new Error('Returning data is not string');
115
+ }
165
116
  this.Log.debug('receive data: ', response);
166
- const jsonData = ProtocolV1.decodeMessage(messages, response);
117
+ const jsonData = receiveOne(messages, response);
167
118
  return check.call(jsonData);
168
119
  }
169
120
  catch (e) {
170
- if (name === 'Initialize' && (options === null || options === void 0 ? void 0 : options.timeoutMs) === PROTOCOL_PROBE_TIMEOUT_MS) {
171
- this.Log.debug('[LowlevelTransport] Protocol V1 Initialize probe call failed:', e);
172
- }
173
- else {
174
- this.Log.error('lowlevel call error: ', e);
175
- }
176
- throw e;
177
- }
178
- });
179
- }
180
- createProtocolTimeoutError(name, timeout) {
181
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.BleTimeoutError, `Lowlevel response timeout after ${timeout}ms for ${name}`);
182
- }
183
- createProtocolMismatchError(expected) {
184
- return hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.RuntimeError, `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`);
185
- }
186
- detectProtocol(uuid, expectedProtocol, protocolHint) {
187
- var _a, _b, _c, _d, _e;
188
- return __awaiter(this, void 0, void 0, function* () {
189
- if (expectedProtocol === 'V2') {
190
- if (yield this.probeProtocolV2(uuid)) {
191
- this.deviceProtocol.set(uuid, 'V2');
192
- (_a = this.Log) === null || _a === void 0 ? void 0 : _a.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V2 (expected)`);
193
- return 'V2';
194
- }
195
- throw this.createProtocolMismatchError(expectedProtocol);
196
- }
197
- if (expectedProtocol === 'V1') {
198
- if (yield this.probeProtocolV1(uuid)) {
199
- this.deviceProtocol.set(uuid, 'V1');
200
- (_b = this.Log) === null || _b === void 0 ? void 0 : _b.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V1 (expected)`);
201
- return 'V1';
202
- }
203
- throw this.createProtocolMismatchError(expectedProtocol);
204
- }
205
- if (protocolHint === 'V2' && (yield this.probeProtocolV2(uuid))) {
206
- this.deviceProtocol.set(uuid, 'V2');
207
- (_c = this.Log) === null || _c === void 0 ? void 0 : _c.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V2 (hint)`);
208
- return 'V2';
209
- }
210
- const cachedProtocol = this.deviceProtocol.get(uuid);
211
- if (cachedProtocol === 'V2' && (yield this.probeProtocolV2(uuid))) {
212
- this.deviceProtocol.set(uuid, 'V2');
213
- (_d = this.Log) === null || _d === void 0 ? void 0 : _d.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V2 (cached)`);
214
- return 'V2';
215
- }
216
- let protocol = 'V1';
217
- const protocolV1Detected = yield this.probeProtocolV1(uuid);
218
- if (!protocolV1Detected) {
219
- yield this.resetConnectionAfterProbe(uuid, 'V1');
220
- if (yield this.probeProtocolV2(uuid)) {
221
- protocol = 'V2';
222
- }
223
- }
224
- this.deviceProtocol.set(uuid, protocol);
225
- (_e = this.Log) === null || _e === void 0 ? void 0 : _e.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> ${protocol}`);
226
- return protocol;
227
- });
228
- }
229
- resetConnectionAfterProbe(uuid, protocol) {
230
- var _a, _b, _c, _d;
231
- return __awaiter(this, void 0, void 0, function* () {
232
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
233
- try {
234
- yield this.plugin.disconnect(uuid);
235
- }
236
- catch (error) {
237
- (_b = this.Log) === null || _b === void 0 ? void 0 : _b.debug(`[LowlevelTransport] disconnect after Protocol ${protocol} probe failed:`, error);
238
- }
239
- try {
240
- yield this.plugin.connect(uuid);
241
- }
242
- catch (error) {
243
- (_c = this.Log) === null || _c === void 0 ? void 0 : _c.debug(`[LowlevelTransport] reconnect after Protocol ${protocol} probe failed:`, error);
244
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.LowlevelTrasnportConnectError, (_d = error.message) !== null && _d !== void 0 ? _d : error);
245
- }
246
- });
247
- }
248
- probeProtocolV1(uuid) {
249
- var _a;
250
- return __awaiter(this, void 0, void 0, function* () {
251
- if (!this._messages) {
252
- return false;
253
- }
254
- try {
255
- this.deviceProtocol.set(uuid, 'V1');
256
- yield this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
257
- return true;
258
- }
259
- catch (error) {
260
- (_a = this.Log) === null || _a === void 0 ? void 0 : _a.debug('[LowlevelTransport] Protocol V1 Initialize probe failed:', error);
261
- return false;
262
- }
263
- });
264
- }
265
- probeProtocolV2(uuid) {
266
- var _a;
267
- return __awaiter(this, void 0, void 0, function* () {
268
- if (!this._messages || !this._messagesV2) {
269
- return false;
270
- }
271
- this.deviceProtocol.set(uuid, 'V2');
272
- (_a = this.protocolV2Assemblers.get(uuid)) === null || _a === void 0 ? void 0 : _a.reset();
273
- return transport.probeProtocolV2({
274
- call: (name, data, options) => this.callProtocolV2(uuid, name, data, options),
275
- timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
276
- logger: this.Log,
277
- logPrefix: 'ProtocolV2 Lowlevel-BLE',
278
- onProbeFailed: () => __awaiter(this, void 0, void 0, function* () {
279
- var _b;
280
- (_b = this.protocolV2Assemblers.get(uuid)) === null || _b === void 0 ? void 0 : _b.reset();
281
- yield this.resetConnectionAfterProbe(uuid, 'V2');
282
- }),
283
- });
284
- });
285
- }
286
- receiveHex(timeoutMs, commandName) {
287
- return __awaiter(this, void 0, void 0, function* () {
288
- const response = yield transport.withProtocolTimeout(this.plugin.receive(), timeoutMs, () => this.createProtocolTimeoutError(commandName, timeoutMs !== null && timeoutMs !== void 0 ? timeoutMs : 0));
289
- if (typeof response !== 'string') {
290
- throw new Error('Returning data is not string');
291
- }
292
- return response;
293
- });
294
- }
295
- readProtocolV1Message(timeoutMs) {
296
- return __awaiter(this, void 0, void 0, function* () {
297
- const first = yield this.receiveHex(timeoutMs, 'ProtocolV1');
298
- const firstData = transport.hexToBytes(first);
299
- if (!isProtocolV1TransportChunk(firstData)) {
300
- return first;
301
- }
302
- const payloadLength = readProtocolV1PayloadLength(firstData);
303
- let buffer = firstData.slice(3);
304
- const expectedLength = transport.PROTOCOL_V1_MESSAGE_HEADER_SIZE + payloadLength;
305
- while (buffer.length < expectedLength) {
306
- const next = yield this.receiveHex(timeoutMs, 'ProtocolV1');
307
- buffer = transport.concatUint8Arrays([buffer, transport.hexToBytes(next)]);
308
- }
309
- return transport.bytesToHex(buffer.slice(0, expectedLength));
310
- });
311
- }
312
- readProtocolV2Frame(uuid, timeoutMs) {
313
- return __awaiter(this, void 0, void 0, function* () {
314
- let assembler = this.protocolV2Assemblers.get(uuid);
315
- if (!assembler) {
316
- assembler = new transport.ProtocolV2FrameAssembler();
317
- this.protocolV2Assemblers.set(uuid, assembler);
318
- }
319
- const queuedFrame = assembler.push(new Uint8Array(0));
320
- if (queuedFrame)
321
- return queuedFrame;
322
- let frame;
323
- while (!frame) {
324
- const response = yield this.receiveHex(timeoutMs, 'ProtocolV2');
325
- const chunk = transport.hexToBytes(response);
326
- if (chunk.length > 0) {
327
- frame = assembler.push(chunk);
328
- }
329
- }
330
- return frame;
331
- });
332
- }
333
- writeProtocolV2Frame(uuid, frame) {
334
- return __awaiter(this, void 0, void 0, function* () {
335
- for (let offset = 0; offset < frame.length; offset += LOWLEVEL_PROTOCOL_V2_PACKET_LENGTH) {
336
- const chunk = frame.slice(offset, offset + LOWLEVEL_PROTOCOL_V2_PACKET_LENGTH);
337
- yield this.plugin.send(uuid, transport.bytesToHex(chunk));
338
- }
339
- });
340
- }
341
- callProtocolV2(uuid, name, data, options) {
342
- var _a, _b, _c;
343
- return __awaiter(this, void 0, void 0, function* () {
344
- if (!this._messages || !this._messagesV2) {
345
- throw hdShared.ERRORS.TypedError(hdShared.HardwareErrorCode.TransportNotConfigured);
346
- }
347
- const timeoutMs = (_a = options === null || options === void 0 ? void 0 : options.timeoutMs) !== null && _a !== void 0 ? _a : LOWLEVEL_PROTOCOL_TIMEOUT_MS;
348
- (_b = this.protocolV2Assemblers.get(uuid)) === null || _b === void 0 ? void 0 : _b.reset();
349
- const session = new transport.ProtocolV2Session({
350
- schemas: {
351
- protocolV1: this._messages,
352
- protocolV2: this._messagesV2,
353
- },
354
- router: transport.PROTOCOL_V2_CHANNEL_BLE_UART,
355
- writeFrame: (frame) => this.writeProtocolV2Frame(uuid, frame),
356
- readFrame: () => this.readProtocolV2Frame(uuid, timeoutMs),
357
- logger: this.Log,
358
- logPrefix: 'ProtocolV2 Lowlevel-BLE',
359
- createTimeoutError: (_messageName, timeout) => this.createProtocolTimeoutError(name, timeout),
360
- });
361
- try {
362
- return yield session.call(name, data, Object.assign(Object.assign({}, options), { timeoutMs }));
363
- }
364
- catch (e) {
365
- (_c = this.protocolV2Assemblers.get(uuid)) === null || _c === void 0 ? void 0 : _c.reset();
366
- this.Log.error('lowlevel Protocol V2 call error: ', e);
121
+ this.Log.error('lowlevel call error: ', e);
367
122
  throw e;
368
123
  }
369
124
  });
package/dist/types.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import type { ProtocolType } from '@onekeyfe/hd-transport';
2
1
  export type LowLevelAcquireInput = {
3
2
  uuid: string;
4
- expectedProtocol?: ProtocolType;
5
3
  };
6
4
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE3D,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,CAAC,EAAE,YAAY,CAAC;CACjC,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,oBAAoB,GAAG;IACjC,IAAI,EAAE,MAAM,CAAC;CACd,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/hd-transport-lowlevel",
3
- "version": "1.1.27-alpha.35",
3
+ "version": "1.1.27-alpha.4",
4
4
  "homepage": "https://github.com/OneKeyHQ/hardware-js-sdk#readme",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
@@ -15,13 +15,12 @@
15
15
  "scripts": {
16
16
  "dev": "rimraf dist && rollup -c ../../build/rollup.config.js -w",
17
17
  "build": "rimraf dist && rollup -c ../../build/rollup.config.js",
18
- "test": "jest",
19
18
  "lint": "eslint .",
20
19
  "lint:fix": "eslint . --fix"
21
20
  },
22
21
  "dependencies": {
23
- "@onekeyfe/hd-shared": "1.1.27-alpha.35",
24
- "@onekeyfe/hd-transport": "1.1.27-alpha.35"
22
+ "@onekeyfe/hd-shared": "1.1.27-alpha.4",
23
+ "@onekeyfe/hd-transport": "1.1.27-alpha.4"
25
24
  },
26
- "gitHead": "3a5eb264b57a6cc2338d1f9534be0ba265c2db35"
25
+ "gitHead": "93d0e7734f8c3a6380be10f74de203f0ba785bb8"
27
26
  }
package/src/index.ts CHANGED
@@ -1,50 +1,15 @@
1
1
  import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
2
- import transport, {
3
- LogBlockCommand,
4
- PROTOCOL_V1_MESSAGE_HEADER_SIZE,
5
- PROTOCOL_V2_CHANNEL_BLE_UART,
6
- ProtocolV2FrameAssembler,
7
- ProtocolV2Session,
8
- bytesToHex,
9
- concatUint8Arrays,
10
- hexToBytes,
11
- probeProtocolV2 as probeProtocolV2Helper,
12
- withProtocolTimeout,
13
- } from '@onekeyfe/hd-transport';
2
+ import transport, { LogBlockCommand } from '@onekeyfe/hd-transport';
14
3
 
15
4
  import type EventEmitter from 'events';
16
- import type {
17
- LowLevelDevice,
18
- LowlevelTransportSharedPlugin,
19
- ProtocolType,
20
- TransportCallOptions,
21
- } from '@onekeyfe/hd-transport';
5
+ import type { LowlevelTransportSharedPlugin } from '@onekeyfe/hd-transport';
22
6
  import type { LowLevelAcquireInput } from './types';
23
7
 
24
- const { check, ProtocolV1, parseConfigure } = transport;
25
-
26
- const PROTOCOL_PROBE_TIMEOUT_MS = 1000;
27
- const PROTOCOL_V2_PROBE_TIMEOUT_MS = 5000;
28
- const LOWLEVEL_PROTOCOL_TIMEOUT_MS = 30_000;
29
- const LOWLEVEL_PROTOCOL_V2_PACKET_LENGTH = 64;
30
-
31
- function inferProtocolHintFromDeviceName(name?: string | null): ProtocolType | undefined {
32
- return /\bpro\s*2\b/i.test(name ?? '') ? 'V2' : undefined;
33
- }
34
-
35
- function isProtocolV1TransportChunk(data: Uint8Array) {
36
- return data.length >= 9 && data[0] === 0x3f && data[1] === 0x23 && data[2] === 0x23;
37
- }
38
-
39
- function readProtocolV1PayloadLength(data: Uint8Array) {
40
- return data[5] * 0x1000000 + data[6] * 0x10000 + data[7] * 0x100 + data[8];
41
- }
8
+ const { check, buildBuffers, receiveOne, parseConfigure } = transport;
42
9
 
43
10
  export default class LowlevelTransport {
44
11
  _messages: ReturnType<typeof transport.parseConfigure> | undefined;
45
12
 
46
- _messagesV2: ReturnType<typeof transport.parseConfigure> | undefined;
47
-
48
13
  configured = false;
49
14
 
50
15
  Log?: any;
@@ -53,16 +18,6 @@ export default class LowlevelTransport {
53
18
 
54
19
  plugin: LowlevelTransportSharedPlugin = {} as LowlevelTransportSharedPlugin;
55
20
 
56
- private deviceProtocol: Map<string, ProtocolType> = new Map();
57
-
58
- private deviceProtocolHints: Map<string, ProtocolType> = new Map();
59
-
60
- private protocolV2Assemblers: Map<string, ProtocolV2FrameAssembler> = new Map();
61
-
62
- getProtocolType(path: string): ProtocolType {
63
- return this.deviceProtocol.get(path) ?? 'V1';
64
- }
65
-
66
21
  init(logger: any, emitter: EventEmitter, plugin: LowlevelTransportSharedPlugin) {
67
22
  this.Log = logger;
68
23
  this.emitter = emitter;
@@ -76,28 +31,18 @@ export default class LowlevelTransport {
76
31
  this._messages = messages;
77
32
  }
78
33
 
79
- configureProtocolV2(signedData: any) {
80
- this._messagesV2 = parseConfigure(signedData);
81
- }
82
-
83
34
  listen() {
84
35
  // empty
85
36
  }
86
37
 
87
- async enumerate() {
88
- const devices = await this.plugin.enumerate();
89
- return devices.map((device: LowLevelDevice) => {
90
- const protocolHint = inferProtocolHintFromDeviceName(device.name);
91
- if (protocolHint) {
92
- this.deviceProtocolHints.set(device.id, protocolHint);
93
- }
94
- return device;
95
- });
38
+ enumerate() {
39
+ return this.plugin.enumerate();
96
40
  }
97
41
 
98
42
  async acquire(input: LowLevelAcquireInput) {
99
43
  try {
100
44
  await this.plugin.connect(input.uuid);
45
+ return { uuid: input.uuid };
101
46
  } catch (error) {
102
47
  this.Log.debug('lowlelvel transport connect error: ', error);
103
48
  throw ERRORS.TypedError(
@@ -105,25 +50,11 @@ export default class LowlevelTransport {
105
50
  error.message ?? error
106
51
  );
107
52
  }
108
-
109
- this.protocolV2Assemblers.set(input.uuid, new ProtocolV2FrameAssembler());
110
- const protocolHint = input.expectedProtocol
111
- ? undefined
112
- : this.deviceProtocolHints.get(input.uuid);
113
- const protocolType = await this.detectProtocol(
114
- input.uuid,
115
- input.expectedProtocol,
116
- protocolHint
117
- );
118
- return { uuid: input.uuid, protocolType };
119
53
  }
120
54
 
121
55
  async release(uuid: string) {
122
56
  try {
123
57
  await this.plugin.disconnect(uuid);
124
- this.deviceProtocol.delete(uuid);
125
- this.deviceProtocolHints.delete(uuid);
126
- this.protocolV2Assemblers.delete(uuid);
127
58
  return true;
128
59
  } catch (error) {
129
60
  this.Log.debug('lowlelvel transport disconnect error: ', error);
@@ -131,51 +62,19 @@ export default class LowlevelTransport {
131
62
  }
132
63
  }
133
64
 
134
- async call(
135
- uuid: string,
136
- name: string,
137
- data: Record<string, unknown>,
138
- options?: TransportCallOptions
139
- ) {
65
+ async call(uuid: string, name: string, data: Record<string, unknown>) {
140
66
  if (this._messages === null || !this._messages) {
141
67
  throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
142
68
  }
143
69
 
144
- const protocol = this.getProtocolType(uuid);
70
+ const messages = this._messages;
145
71
  if (LogBlockCommand.has(name)) {
146
- this.Log.debug('lowlevel-transport', 'call-', ' name: ', name, ' protocol: ', protocol);
72
+ this.Log.debug('lowlevel-transport', 'call-', ' name: ', name);
147
73
  } else {
148
- this.Log.debug(
149
- 'lowlevel-transport',
150
- 'call-',
151
- ' name: ',
152
- name,
153
- ' data: ',
154
- data,
155
- ' protocol: ',
156
- protocol
157
- );
158
- }
159
-
160
- if (protocol === 'V2') {
161
- return this.callProtocolV2(uuid, name, data, options);
74
+ this.Log.debug('lowlevel-transport', 'call-', ' name: ', name, ' data: ', data);
162
75
  }
163
76
 
164
- return this.callProtocolV1(uuid, name, data, options);
165
- }
166
-
167
- private async callProtocolV1(
168
- uuid: string,
169
- name: string,
170
- data: Record<string, unknown>,
171
- options?: TransportCallOptions
172
- ) {
173
- if (!this._messages) {
174
- throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
175
- }
176
-
177
- const messages = this._messages;
178
- const buffers = ProtocolV1.encodeTransportPackets(messages, name, data);
77
+ const buffers = buildBuffers(messages, name, data);
179
78
  for (const o of buffers) {
180
79
  const outData = o.toString('hex');
181
80
  // Upload resources on low-end phones may OOM
@@ -189,235 +88,15 @@ export default class LowlevelTransport {
189
88
  }
190
89
 
191
90
  try {
192
- const response = await this.readProtocolV1Message(options?.timeoutMs);
91
+ const response = await this.plugin.receive();
92
+ if (typeof response !== 'string') {
93
+ throw new Error('Returning data is not string');
94
+ }
193
95
  this.Log.debug('receive data: ', response);
194
- const jsonData = ProtocolV1.decodeMessage(messages, response);
96
+ const jsonData = receiveOne(messages, response);
195
97
  return check.call(jsonData);
196
98
  } catch (e) {
197
- if (name === 'Initialize' && options?.timeoutMs === PROTOCOL_PROBE_TIMEOUT_MS) {
198
- this.Log.debug('[LowlevelTransport] Protocol V1 Initialize probe call failed:', e);
199
- } else {
200
- this.Log.error('lowlevel call error: ', e);
201
- }
202
- throw e;
203
- }
204
- }
205
-
206
- private createProtocolTimeoutError(name: string, timeout: number) {
207
- return ERRORS.TypedError(
208
- HardwareErrorCode.BleTimeoutError,
209
- `Lowlevel response timeout after ${timeout}ms for ${name}`
210
- );
211
- }
212
-
213
- private createProtocolMismatchError(expected: ProtocolType) {
214
- return ERRORS.TypedError(
215
- HardwareErrorCode.RuntimeError,
216
- `Device protocol mismatch: expected ${expected}, but device did not respond to expected protocol`
217
- );
218
- }
219
-
220
- private async detectProtocol(
221
- uuid: string,
222
- expectedProtocol?: ProtocolType,
223
- protocolHint?: ProtocolType
224
- ): Promise<ProtocolType> {
225
- if (expectedProtocol === 'V2') {
226
- if (await this.probeProtocolV2(uuid)) {
227
- this.deviceProtocol.set(uuid, 'V2');
228
- this.Log?.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V2 (expected)`);
229
- return 'V2';
230
- }
231
- throw this.createProtocolMismatchError(expectedProtocol);
232
- }
233
-
234
- if (expectedProtocol === 'V1') {
235
- if (await this.probeProtocolV1(uuid)) {
236
- this.deviceProtocol.set(uuid, 'V1');
237
- this.Log?.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V1 (expected)`);
238
- return 'V1';
239
- }
240
- throw this.createProtocolMismatchError(expectedProtocol);
241
- }
242
-
243
- if (protocolHint === 'V2' && (await this.probeProtocolV2(uuid))) {
244
- this.deviceProtocol.set(uuid, 'V2');
245
- this.Log?.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V2 (hint)`);
246
- return 'V2';
247
- }
248
-
249
- const cachedProtocol = this.deviceProtocol.get(uuid);
250
- if (cachedProtocol === 'V2' && (await this.probeProtocolV2(uuid))) {
251
- this.deviceProtocol.set(uuid, 'V2');
252
- this.Log?.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> V2 (cached)`);
253
- return 'V2';
254
- }
255
-
256
- let protocol: ProtocolType = 'V1';
257
- const protocolV1Detected = await this.probeProtocolV1(uuid);
258
- if (!protocolV1Detected) {
259
- await this.resetConnectionAfterProbe(uuid, 'V1');
260
- if (await this.probeProtocolV2(uuid)) {
261
- protocol = 'V2';
262
- }
263
- }
264
- this.deviceProtocol.set(uuid, protocol);
265
- this.Log?.debug(`[LowlevelTransport] detectProtocol: uuid=${uuid} -> ${protocol}`);
266
- return protocol;
267
- }
268
-
269
- private async resetConnectionAfterProbe(uuid: string, protocol: ProtocolType) {
270
- this.protocolV2Assemblers.get(uuid)?.reset();
271
-
272
- try {
273
- await this.plugin.disconnect(uuid);
274
- } catch (error) {
275
- this.Log?.debug(
276
- `[LowlevelTransport] disconnect after Protocol ${protocol} probe failed:`,
277
- error
278
- );
279
- }
280
-
281
- try {
282
- await this.plugin.connect(uuid);
283
- } catch (error) {
284
- this.Log?.debug(
285
- `[LowlevelTransport] reconnect after Protocol ${protocol} probe failed:`,
286
- error
287
- );
288
- throw ERRORS.TypedError(
289
- HardwareErrorCode.LowlevelTrasnportConnectError,
290
- error.message ?? error
291
- );
292
- }
293
- }
294
-
295
- private async probeProtocolV1(uuid: string) {
296
- if (!this._messages) {
297
- return false;
298
- }
299
-
300
- try {
301
- this.deviceProtocol.set(uuid, 'V1');
302
- await this.callProtocolV1(uuid, 'Initialize', {}, { timeoutMs: PROTOCOL_PROBE_TIMEOUT_MS });
303
- return true;
304
- } catch (error) {
305
- this.Log?.debug('[LowlevelTransport] Protocol V1 Initialize probe failed:', error);
306
- return false;
307
- }
308
- }
309
-
310
- private async probeProtocolV2(uuid: string) {
311
- if (!this._messages || !this._messagesV2) {
312
- return false;
313
- }
314
-
315
- this.deviceProtocol.set(uuid, 'V2');
316
- this.protocolV2Assemblers.get(uuid)?.reset();
317
- return probeProtocolV2Helper({
318
- call: (name: string, data: Record<string, unknown>, options?: TransportCallOptions) =>
319
- this.callProtocolV2(uuid, name, data, options),
320
- timeoutMs: PROTOCOL_V2_PROBE_TIMEOUT_MS,
321
- logger: this.Log,
322
- logPrefix: 'ProtocolV2 Lowlevel-BLE',
323
- onProbeFailed: async () => {
324
- this.protocolV2Assemblers.get(uuid)?.reset();
325
- await this.resetConnectionAfterProbe(uuid, 'V2');
326
- },
327
- });
328
- }
329
-
330
- private async receiveHex(timeoutMs: number | undefined, commandName: string) {
331
- const response = await withProtocolTimeout(this.plugin.receive(), timeoutMs, () =>
332
- this.createProtocolTimeoutError(commandName, timeoutMs ?? 0)
333
- );
334
- if (typeof response !== 'string') {
335
- throw new Error('Returning data is not string');
336
- }
337
- return response;
338
- }
339
-
340
- private async readProtocolV1Message(timeoutMs?: number) {
341
- const first = await this.receiveHex(timeoutMs, 'ProtocolV1');
342
- const firstData = hexToBytes(first);
343
- if (!isProtocolV1TransportChunk(firstData)) {
344
- return first;
345
- }
346
-
347
- const payloadLength = readProtocolV1PayloadLength(firstData);
348
- let buffer = firstData.slice(3);
349
- const expectedLength = PROTOCOL_V1_MESSAGE_HEADER_SIZE + payloadLength;
350
-
351
- while (buffer.length < expectedLength) {
352
- const next = await this.receiveHex(timeoutMs, 'ProtocolV1');
353
- buffer = concatUint8Arrays([buffer, hexToBytes(next)]);
354
- }
355
-
356
- return bytesToHex(buffer.slice(0, expectedLength));
357
- }
358
-
359
- private async readProtocolV2Frame(uuid: string, timeoutMs?: number) {
360
- let assembler = this.protocolV2Assemblers.get(uuid);
361
- if (!assembler) {
362
- assembler = new ProtocolV2FrameAssembler();
363
- this.protocolV2Assemblers.set(uuid, assembler);
364
- }
365
-
366
- const queuedFrame = assembler.push(new Uint8Array(0));
367
- if (queuedFrame) return queuedFrame;
368
-
369
- let frame: Uint8Array | undefined;
370
- while (!frame) {
371
- const response = await this.receiveHex(timeoutMs, 'ProtocolV2');
372
- const chunk = hexToBytes(response);
373
- if (chunk.length > 0) {
374
- frame = assembler.push(chunk);
375
- }
376
- }
377
- return frame;
378
- }
379
-
380
- private async writeProtocolV2Frame(uuid: string, frame: Uint8Array) {
381
- for (let offset = 0; offset < frame.length; offset += LOWLEVEL_PROTOCOL_V2_PACKET_LENGTH) {
382
- const chunk = frame.slice(offset, offset + LOWLEVEL_PROTOCOL_V2_PACKET_LENGTH);
383
- await this.plugin.send(uuid, bytesToHex(chunk));
384
- }
385
- }
386
-
387
- private async callProtocolV2(
388
- uuid: string,
389
- name: string,
390
- data: Record<string, unknown>,
391
- options?: TransportCallOptions
392
- ) {
393
- if (!this._messages || !this._messagesV2) {
394
- throw ERRORS.TypedError(HardwareErrorCode.TransportNotConfigured);
395
- }
396
-
397
- const timeoutMs = options?.timeoutMs ?? LOWLEVEL_PROTOCOL_TIMEOUT_MS;
398
- this.protocolV2Assemblers.get(uuid)?.reset();
399
- const session = new ProtocolV2Session({
400
- schemas: {
401
- protocolV1: this._messages,
402
- protocolV2: this._messagesV2,
403
- },
404
- router: PROTOCOL_V2_CHANNEL_BLE_UART,
405
- writeFrame: (frame: Uint8Array) => this.writeProtocolV2Frame(uuid, frame),
406
- readFrame: () => this.readProtocolV2Frame(uuid, timeoutMs),
407
- logger: this.Log,
408
- logPrefix: 'ProtocolV2 Lowlevel-BLE',
409
- createTimeoutError: (_messageName: string, timeout: number) =>
410
- this.createProtocolTimeoutError(name, timeout),
411
- });
412
-
413
- try {
414
- return await session.call(name, data, {
415
- ...options,
416
- timeoutMs,
417
- });
418
- } catch (e) {
419
- this.protocolV2Assemblers.get(uuid)?.reset();
420
- this.Log.error('lowlevel Protocol V2 call error: ', e);
99
+ this.Log.error('lowlevel call error: ', e);
421
100
  throw e;
422
101
  }
423
102
  }
package/src/types.ts CHANGED
@@ -1,6 +1,3 @@
1
- import type { ProtocolType } from '@onekeyfe/hd-transport';
2
-
3
1
  export type LowLevelAcquireInput = {
4
2
  uuid: string;
5
- expectedProtocol?: ProtocolType;
6
3
  };
package/.eslintignore DELETED
@@ -1,4 +0,0 @@
1
- coverage/
2
- dist/
3
- __tests__/
4
- jest.config.js
@@ -1,253 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-var-requires */
2
- const LowlevelTransport = require('../src').default;
3
- const { parseConfigure } = require('../../hd-transport/src/serialization/protobuf/messages');
4
- const { ProtocolV1, ProtocolV2 } = require('../../hd-transport/src/protocols');
5
- const { bytesToHex } = require('../../hd-transport/src/protocols/v2/session');
6
- const { PROTOCOL_V2_CHANNEL_BLE_UART } = require('../../hd-transport/src/constants');
7
-
8
- const protocolV1Schema = {
9
- nested: {
10
- Initialize: {
11
- fields: {},
12
- },
13
- Success: {
14
- fields: {
15
- message: {
16
- type: 'string',
17
- id: 1,
18
- },
19
- },
20
- },
21
- MessageType: {
22
- values: {
23
- MessageType_Initialize: 1,
24
- MessageType_Success: 2,
25
- },
26
- },
27
- },
28
- };
29
-
30
- const protocolV2Schema = {
31
- nested: {
32
- GetProtoVersion: {
33
- fields: {},
34
- },
35
- ProtoVersion: {
36
- fields: {
37
- major_version: {
38
- type: 'uint32',
39
- id: 1,
40
- },
41
- minor_version: {
42
- type: 'uint32',
43
- id: 2,
44
- },
45
- patch_version: {
46
- type: 'uint32',
47
- id: 3,
48
- },
49
- },
50
- },
51
- Ping: {
52
- fields: {
53
- message: {
54
- type: 'string',
55
- id: 1,
56
- },
57
- },
58
- },
59
- Success: {
60
- fields: {
61
- message: {
62
- type: 'string',
63
- id: 1,
64
- },
65
- },
66
- },
67
- MessageType: {
68
- values: {
69
- MessageType_GetProtoVersion: 60200,
70
- MessageType_ProtoVersion: 60201,
71
- MessageType_Ping: 60206,
72
- MessageType_Success: 60207,
73
- },
74
- },
75
- },
76
- };
77
-
78
- const schemas = {
79
- protocolV1: parseConfigure(protocolV1Schema),
80
- protocolV2: parseConfigure(protocolV2Schema),
81
- };
82
-
83
- const createLogger = () => ({
84
- debug: jest.fn(),
85
- error: jest.fn(),
86
- });
87
-
88
- const createPlugin = ({ devices, responses }) => ({
89
- enumerate: jest.fn(() => Promise.resolve(devices)),
90
- connect: jest.fn(() => Promise.resolve()),
91
- disconnect: jest.fn(() => Promise.resolve()),
92
- init: jest.fn(() => Promise.resolve()),
93
- send: jest.fn(() => Promise.resolve()),
94
- receive: jest.fn(() => {
95
- const next = responses.shift();
96
- if (next instanceof Error) {
97
- return Promise.reject(next);
98
- }
99
- if (!next) {
100
- return Promise.reject(new Error('No queued response'));
101
- }
102
- return Promise.resolve(next);
103
- }),
104
- version: 'test-plugin',
105
- });
106
-
107
- const configureTransport = plugin => {
108
- const lowlevel = new LowlevelTransport();
109
- lowlevel.init(createLogger(), undefined, plugin);
110
- lowlevel.configure(protocolV1Schema);
111
- lowlevel.configureProtocolV2(protocolV2Schema);
112
- return lowlevel;
113
- };
114
-
115
- const splitFrame = (frame, index) => [
116
- bytesToHex(frame.slice(0, index)),
117
- bytesToHex(frame.slice(index)),
118
- ];
119
-
120
- describe('LowlevelTransport protocol framing', () => {
121
- test('keeps Protocol V1 raw notification chunks compatible', async () => {
122
- const responseChunks = ProtocolV1.encodeTransportPackets(schemas.protocolV1, 'Success', {
123
- message: 'ok',
124
- }).map(chunk => chunk.toString('hex'));
125
- const plugin = createPlugin({
126
- devices: [{ id: 'classic-id', name: 'OneKey Classic', commType: 'ble' }],
127
- responses: responseChunks,
128
- });
129
- const lowlevel = configureTransport(plugin);
130
-
131
- await expect(lowlevel.call('classic-id', 'Initialize', {})).resolves.toEqual({
132
- type: 'Success',
133
- message: { message: 'ok' },
134
- });
135
- });
136
-
137
- test('detects Protocol V2 devices and reassembles split Protocol V2 notifications', async () => {
138
- const probeResponse = ProtocolV2.encodeFrame(
139
- schemas,
140
- 'Success',
141
- {
142
- message: 'probe',
143
- },
144
- { router: PROTOCOL_V2_CHANNEL_BLE_UART }
145
- );
146
- const callResponse = ProtocolV2.encodeFrame(
147
- schemas,
148
- 'ProtoVersion',
149
- {
150
- major_version: 2,
151
- minor_version: 1,
152
- patch_version: 3,
153
- },
154
- { router: PROTOCOL_V2_CHANNEL_BLE_UART }
155
- );
156
- const plugin = createPlugin({
157
- devices: [{ id: 'pro2-id', name: 'OneKey Pro 2', commType: 'ble' }],
158
- responses: [...splitFrame(probeResponse, 4), ...splitFrame(callResponse, 5)],
159
- });
160
- const lowlevel = configureTransport(plugin);
161
-
162
- await expect(lowlevel.enumerate()).resolves.toEqual([
163
- { id: 'pro2-id', name: 'OneKey Pro 2', commType: 'ble' },
164
- ]);
165
- await expect(lowlevel.acquire({ uuid: 'pro2-id' })).resolves.toEqual({
166
- uuid: 'pro2-id',
167
- protocolType: 'V2',
168
- });
169
- await expect(lowlevel.call('pro2-id', 'GetProtoVersion', {})).resolves.toEqual({
170
- type: 'ProtoVersion',
171
- message: {
172
- major_version: 2,
173
- minor_version: 1,
174
- patch_version: 3,
175
- },
176
- });
177
- expect(plugin.send).toHaveBeenCalled();
178
- });
179
-
180
- test('falls back to Protocol V2 probe for unnamed Protocol V2 devices', async () => {
181
- const probeResponse = ProtocolV2.encodeFrame(
182
- schemas,
183
- 'Success',
184
- {
185
- message: 'probe',
186
- },
187
- { router: PROTOCOL_V2_CHANNEL_BLE_UART }
188
- );
189
- const plugin = createPlugin({
190
- devices: [{ id: 'unknown-pro2-id', name: 'Unknown BLE Device', commType: 'ble' }],
191
- responses: [new Error('Protocol V1 probe timed out'), bytesToHex(probeResponse)],
192
- });
193
- const lowlevel = configureTransport(plugin);
194
-
195
- await expect(lowlevel.acquire({ uuid: 'unknown-pro2-id' })).resolves.toEqual({
196
- uuid: 'unknown-pro2-id',
197
- protocolType: 'V2',
198
- });
199
- expect(lowlevel.getProtocolType('unknown-pro2-id')).toBe('V2');
200
- });
201
-
202
- test('resets the lowlevel connection before probing Protocol V2 after a V1 timeout', async () => {
203
- const probeResponse = ProtocolV2.encodeFrame(
204
- schemas,
205
- 'Success',
206
- {
207
- message: 'probe',
208
- },
209
- { router: PROTOCOL_V2_CHANNEL_BLE_UART }
210
- );
211
- let staleReceivePending = false;
212
- let resetAfterTimeout = false;
213
- const plugin = createPlugin({
214
- devices: [{ id: 'slow-v2-id', name: 'Unknown BLE Device', commType: 'ble' }],
215
- responses: [],
216
- });
217
- plugin.disconnect.mockImplementation(() => {
218
- staleReceivePending = false;
219
- resetAfterTimeout = true;
220
- return Promise.resolve();
221
- });
222
- plugin.receive.mockImplementation(() => {
223
- if (!staleReceivePending && !resetAfterTimeout) {
224
- staleReceivePending = true;
225
- return new Promise(() => {});
226
- }
227
- if (staleReceivePending) {
228
- return Promise.reject(new Error('stale receive still pending'));
229
- }
230
- return Promise.resolve(bytesToHex(probeResponse));
231
- });
232
- const lowlevel = configureTransport(plugin);
233
-
234
- await expect(lowlevel.acquire({ uuid: 'slow-v2-id' })).resolves.toEqual({
235
- uuid: 'slow-v2-id',
236
- protocolType: 'V2',
237
- });
238
- expect(plugin.disconnect).toHaveBeenCalledWith('slow-v2-id');
239
- expect(plugin.connect).toHaveBeenCalledTimes(2);
240
- });
241
-
242
- test('verifies expected Protocol V1 instead of trusting the requested protocol', async () => {
243
- const plugin = createPlugin({
244
- devices: [{ id: 'v2-id', name: 'Unknown BLE Device', commType: 'ble' }],
245
- responses: [new Error('Protocol V1 probe timed out')],
246
- });
247
- const lowlevel = configureTransport(plugin);
248
-
249
- await expect(lowlevel.acquire({ uuid: 'v2-id', expectedProtocol: 'V1' })).rejects.toThrow(
250
- 'Device protocol mismatch: expected V1'
251
- );
252
- });
253
- });
package/jest.config.js DELETED
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- preset: '../../jest.config.js',
3
- testEnvironment: 'node',
4
- modulePathIgnorePatterns: ['node_modules', '<rootDir>/lib', '<rootDir>/libDev'],
5
- collectCoverage: true,
6
- };