@zeppos/zeus-cli 1.3.5 → 1.3.7

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.
Files changed (42) hide show
  1. package/bin/main.js +8 -8
  2. package/modules/build.js +5 -3
  3. package/modules/create.js +6 -5
  4. package/package.json +1 -1
  5. package/private-modules/zeppos-app-utils/dist/config/device.js +105 -45
  6. package/private-modules/zeppos-app-utils/dist/modules/create/local-app.js +3 -2
  7. package/private-modules/zeppos-app-utils/dist/modules/fetchDevices.js +87 -0
  8. package/private-modules/zeppos-app-utils/dist/modules/index.js +1 -0
  9. package/private-modules/zeppos-app-utils/dist/public/template/os1.0/app/fetch-api/app-side/index.js +6 -18
  10. package/private-modules/zeppos-app-utils/dist/public/template/os1.0/app/fetch-api/pages/index.js +6 -6
  11. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/app-side/index.js +6 -18
  12. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/pages/index.js +6 -6
  13. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/empty/assets/default.b/icon.png +0 -0
  14. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/empty/assets/default.r/icon.png +0 -0
  15. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/empty/assets/default.s/icon.png +0 -0
  16. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/fetch-api/app-side/index.js +7 -35
  17. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/fetch-api/page/index.js +1 -1
  18. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/fetch-api/page/index.r.layout.js +8 -8
  19. package/private-modules/zeppos-app-utils/dist/public/template/os3.0/app/fetch-api/page/index.s.layout.js +1 -1
  20. package/private-modules/zeppos-app-utils/dist/tools/index.js +2 -1
  21. package/private-modules/zeppos-app-utils/dist/config/device-server.js +0 -116
  22. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/.prettierrc.js +0 -6
  23. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/app-side/index.js +0 -45
  24. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/app.js +0 -25
  25. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/app.json +0 -64
  26. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/assets/gts/icon.png +0 -0
  27. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/page/home/index.page.js +0 -155
  28. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/page/home/index.page.json +0 -1
  29. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/page/home/index.style.js +0 -92
  30. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/page/i18n/en-US.po +0 -9
  31. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/secondary-widget/index.js +0 -160
  32. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/setting/i18n/en-US.po +0 -5
  33. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/setting/index.js +0 -143
  34. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/data.js +0 -67
  35. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/defer.js +0 -35
  36. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/device-polyfill.js +0 -6
  37. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/es6-promise.js +0 -1178
  38. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/event.js +0 -42
  39. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/message-side.js +0 -1190
  40. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/shared/message.js +0 -1196
  41. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/utils/constants.js +0 -1
  42. package/private-modules/zeppos-app-utils/dist/public/template/os2.0/app/fetch-api/todo-list/utils/index.js +0 -38
@@ -1,1196 +0,0 @@
1
- import { EventBus } from '@zos/utils'
2
- import { log as Logger } from '@zos/utils'
3
- import { Deferred, timeout } from './defer'
4
- import { json2buf, buf2json, bin2hex, str2buf, buf2str } from './data'
5
-
6
- let logger
7
-
8
- function initLogger() {
9
- if (typeof __ZEPPOS__ !== 'undefined') {
10
- logger = Logger.getLogger('device-message')
11
- // logger.level = logger.levels.warn
12
- } else {
13
- logger = Logger.getLogger('side-message')
14
- }
15
- }
16
-
17
- const DEBUG = true
18
-
19
- export const MESSAGE_SIZE = 3600
20
- export const MESSAGE_HEADER = 16
21
- export const MESSAGE_PAYLOAD = MESSAGE_SIZE - MESSAGE_HEADER
22
- export const HM_MESSAGE_PROTO_HEADER = 66
23
- export const HM_MESSAGE_PROTO_PAYLOAD = MESSAGE_PAYLOAD - HM_MESSAGE_PROTO_HEADER
24
-
25
- export const MessageFlag = {
26
- Runtime: 0x0,
27
- App: 0x1
28
- }
29
-
30
- export const MessageType = {
31
- Shake: 0x1,
32
- Close: 0x2,
33
- Heart: 0x3,
34
- Data: 0x4,
35
- DataWithSystemTool: 0x5,
36
- Log: 0x6
37
- }
38
-
39
- export const MessageRuntimeType = {
40
- Invoke: 0x1
41
- }
42
- export const MessageVersion = {
43
- Version1: 0x1
44
- }
45
-
46
- export const MessagePayloadType = {
47
- Request: 0x1,
48
- Response: 0x2,
49
- Notify: 0x3
50
- }
51
-
52
- export const DataType = {
53
- empty: 'empty',
54
- json: 'json',
55
- text: 'text',
56
- bin: 'bin'
57
- }
58
-
59
- export const MessagePayloadDataTypeOp = {
60
- EMPTY: 0x0,
61
- TEXT: 0x1,
62
- JSON: 0x2,
63
- BIN: 0x3
64
- }
65
-
66
- export function getDataType(type) {
67
- switch (type.toLowerCase()) {
68
- case DataType.json:
69
- return MessagePayloadDataTypeOp.JSON
70
- case DataType.text:
71
- return MessagePayloadDataTypeOp.TEXT
72
- case DataType.bin:
73
- return MessagePayloadDataTypeOp.BIN
74
- case DataType.empty:
75
- return MessagePayloadDataTypeOp.EMPTY
76
- default:
77
- return MessagePayloadDataTypeOp.TEXT
78
- }
79
- }
80
-
81
- // 中续,结束
82
- export const MessagePayloadOpCode = {
83
- Continued: 0x0,
84
- Finished: 0x1
85
- }
86
-
87
- let traceId = 10000
88
- export function genTraceId() {
89
- return traceId++
90
- }
91
-
92
- let spanId = 1000
93
- export function genSpanId() {
94
- return spanId++
95
- }
96
-
97
- export function getTimestamp(t = Date.now()) {
98
- return t % 10000000
99
- }
100
-
101
- class Session extends EventBus {
102
- constructor(id, type, ctx) {
103
- super()
104
- this.id = id
105
- this.type = type // payloadType
106
- this.ctx = ctx
107
- this.tempBuf = null
108
- this.chunks = []
109
- this.count = 0
110
- this.finishChunk = null
111
- }
112
-
113
- addChunk(payload) {
114
- if (payload.opCode === MessagePayloadOpCode.Finished) {
115
- this.count = payload.seqId
116
- this.finishChunk = payload
117
- }
118
-
119
- if (payload.payloadLength !== payload.payload.byteLength) {
120
- logger.error(
121
- 'receive chunk data length error, expect %d but %d',
122
- payload.payloadLength,
123
- payload.payload.byteLength
124
- )
125
- this.emit(
126
- 'error',
127
- Error(
128
- `receive chunk data length error, expect ${payload.payloadLength} but ${payload.payload.byteLength}`
129
- )
130
- )
131
- return
132
- }
133
-
134
- this.chunks.push(payload)
135
- this.checkIfReceiveAllChunks()
136
- }
137
-
138
- checkIfReceiveAllChunks() {
139
- if (this.count !== this.chunks.length) return
140
-
141
- for (let i = 1; i <= this.count; i++) {
142
- const chunk = this.chunks.find((c) => c.seqId === i)
143
-
144
- if (!chunk) {
145
- this.releaseBuf()
146
- this.emit('error', Error('receive data error'))
147
- return
148
- }
149
-
150
- const buf = chunk.payload
151
- this.tempBuf = this.tempBuf ? Buffer.concat([this.tempBuf, buf]) : buf
152
- }
153
-
154
- if (!this.finishChunk) return
155
-
156
- this.finishChunk.payload = this.tempBuf
157
- this.finishChunk.payloadLength = this.finishChunk.payload.byteLength
158
-
159
- if (this.finishChunk.totalLength !== this.finishChunk.payloadLength) {
160
- logger.error(
161
- 'receive full data length error, expect %d but %d',
162
- this.finishChunk.payloadLength,
163
- this.finishChunk.payload.byteLength
164
- )
165
- this.emit(
166
- 'error',
167
- Error(
168
- `receive full data length error, expect ${this.finishChunk.payloadLength} but ${this.finishChunk.payload.byteLength}`
169
- )
170
- )
171
- return
172
- }
173
-
174
- this.emit('data', this.finishChunk)
175
- }
176
-
177
- getLength() {
178
- return this.tempBufLength
179
- }
180
- releaseBuf() {
181
- this.tempBuf = null
182
- this.chunks = []
183
- this.finishChunk = null
184
- this.count = 0
185
- }
186
- }
187
-
188
- class SessionMgr {
189
- constructor() {
190
- this.sessions = new Map()
191
- }
192
-
193
- key(session) {
194
- return `${session.id}:${session.type}`
195
- }
196
-
197
- newSession(id, type, ctx) {
198
- const newSession = new Session(id, type, ctx)
199
- this.sessions.set(this.key(newSession), newSession)
200
- return newSession
201
- }
202
-
203
- destroy(session) {
204
- session.releaseBuf()
205
- this.sessions.delete(this.key(session))
206
- }
207
-
208
- has(id, type) {
209
- return this.sessions.has(
210
- this.key({
211
- id,
212
- type
213
- })
214
- )
215
- }
216
-
217
- getById(id, type) {
218
- return this.sessions.get(
219
- this.key({
220
- id,
221
- type
222
- })
223
- )
224
- }
225
-
226
- clear() {
227
- this.sessions.clear()
228
- }
229
- }
230
-
231
- export class MessageBuilder extends EventBus {
232
- constructor(
233
- { appId = 0, appDevicePort = 20, appSidePort = 0, ble = undefined } = {
234
- appId: 0,
235
- appDevicePort: 20,
236
- appSidePort: 0,
237
- ble: undefined
238
- }
239
- ) {
240
- super()
241
- initLogger()
242
- this.isDevice = typeof __ZEPPOS__ !== 'undefined'
243
- this.isSide = !this.isDevice
244
-
245
- this.appId = appId
246
- this.appDevicePort = appDevicePort
247
- this.appSidePort = appSidePort
248
- this.ble = ble
249
- this.sendMsg = this.getSafeSend()
250
- this.chunkSize = MESSAGE_PAYLOAD
251
- this.tempBuf = null
252
- this.shakeTask = Deferred()
253
- this.waitingShakePromise = this.shakeTask.promise
254
- this.sessionMgr = new SessionMgr()
255
- }
256
-
257
- getMessageSize() {
258
- return MESSAGE_SIZE
259
- }
260
-
261
- getMessagePayloadSize() {
262
- return MESSAGE_PAYLOAD
263
- }
264
-
265
- getMessageHeaderSize() {
266
- return MESSAGE_HEADER
267
- }
268
-
269
- buf2Json(buf) {
270
- return buf2json(buf)
271
- }
272
-
273
- json2Buf(json) {
274
- return json2buf(json)
275
- }
276
-
277
- now(t = Date.now()) {
278
- return getTimestamp(t)
279
- }
280
-
281
- connect(cb) {
282
- this.on('message', (message) => {
283
- this.onMessage(message)
284
- })
285
-
286
- this.ble &&
287
- this.ble.createConnect((index, data, size) => {
288
- DEBUG &&
289
- logger.warn('[RAW] [R] receive index=>%d size=>%d bin=>%s', index, size, bin2hex(data))
290
- this.onFragmentData(data)
291
- })
292
-
293
- this.sendShake()
294
- cb && cb(this)
295
- }
296
-
297
- disConnect(cb) {
298
- logger.debug('app ble disconnect')
299
- this.sendClose()
300
- this.off('message')
301
- this.ble && this.ble.disConnect()
302
-
303
- cb && cb(this)
304
- }
305
-
306
- listen(cb) {
307
- if (typeof messaging === 'undefined') {
308
- return
309
- }
310
-
311
- messaging &&
312
- messaging.peerSocket.addListener('message', (message) => {
313
- DEBUG &&
314
- logger.warn('[RAW] [R] receive size=>%d bin=>%s', message.byteLength, bin2hex(message))
315
- this.onMessage(message)
316
- })
317
-
318
- this.waitingShakePromise = Promise.resolve()
319
- cb && cb(this)
320
- }
321
-
322
- buildBin(data) {
323
- if (data.payload.byteLength > this.chunkSize) {
324
- throw new Error(`${data.payload.byteLength} greater than max size of ${this.chunkSize}`)
325
- }
326
-
327
- const size = this.getMessageHeaderSize() + data.payload.byteLength
328
- let buf = Buffer.alloc(size)
329
- let offset = 0
330
-
331
- buf.writeUInt8(data.flag, offset)
332
- offset += 1
333
-
334
- buf.writeUInt8(data.version, offset)
335
- offset += 1
336
-
337
- buf.writeUInt16LE(data.type, offset)
338
- offset += 2
339
-
340
- buf.writeUInt16LE(data.port1, offset)
341
- offset += 2
342
-
343
- buf.writeUInt16LE(data.port2, offset)
344
- offset += 2
345
-
346
- buf.writeUInt32LE(data.appId, offset)
347
- offset += 4
348
-
349
- buf.writeUInt32LE(data.extra, offset)
350
- offset += 4
351
-
352
- buf.fill(data.payload, offset, data.payload.byteLength + offset)
353
-
354
- return buf
355
- }
356
-
357
- buildShake() {
358
- return this.buildBin({
359
- flag: MessageFlag.App,
360
- version: MessageVersion.Version1,
361
- type: MessageType.Shake,
362
- port1: this.appDevicePort,
363
- port2: this.appSidePort,
364
- appId: this.appId,
365
- extra: 0,
366
- payload: Buffer.from([this.appId])
367
- })
368
- }
369
-
370
- sendShake() {
371
- if (this.appSidePort === 0) {
372
- const shake = this.buildShake()
373
- this.sendMsg(shake)
374
- }
375
- }
376
-
377
- buildClose() {
378
- return this.buildBin({
379
- flag: MessageFlag.App,
380
- version: MessageVersion.Version1,
381
- type: MessageType.Close,
382
- port1: this.appDevicePort,
383
- port2: this.appSidePort,
384
- appId: this.appId,
385
- extra: 0,
386
- payload: Buffer.from([this.appId])
387
- })
388
- }
389
-
390
- sendClose() {
391
- if (this.appSidePort !== 0) {
392
- const close = this.buildClose()
393
-
394
- this.sendMsg(close)
395
- }
396
- }
397
-
398
- readBin(arrayBuf) {
399
- const buf = Buffer.from(arrayBuf)
400
- let offset = 0
401
-
402
- const flag = buf.readUInt8(offset)
403
- offset += 1
404
-
405
- const version = buf.readUInt8(offset)
406
- offset += 1
407
-
408
- const type = buf.readUInt16LE(offset)
409
- offset += 2
410
-
411
- const port1 = buf.readUInt16LE(offset)
412
- offset += 2
413
-
414
- const port2 = buf.readUInt16LE(offset)
415
- offset += 2
416
-
417
- const appId = buf.readUInt32LE(offset)
418
- offset += 4
419
-
420
- const extra = buf.readUInt32LE(offset)
421
- offset += 4
422
-
423
- const payload = buf.subarray(offset)
424
-
425
- return {
426
- flag,
427
- version,
428
- type,
429
- port1,
430
- port2,
431
- appId,
432
- extra,
433
- payload
434
- }
435
- }
436
-
437
- // opts 覆盖头部选项
438
- buildData(payload, opts = {}) {
439
- return this.buildBin({
440
- flag: MessageFlag.App,
441
- version: MessageVersion.Version1,
442
- type: MessageType.Data,
443
- port1: this.appDevicePort,
444
- port2: this.appSidePort,
445
- appId: this.appId,
446
- extra: 0,
447
- ...opts,
448
- payload
449
- })
450
- }
451
-
452
- sendBin(buf, debug = DEBUG) {
453
- // ble 发送消息
454
- debug && logger.warn('[RAW] [S] send size=%d bin=%s', buf.byteLength, bin2hex(buf.buffer))
455
- const result = this.ble.send(buf.buffer, buf.byteLength)
456
-
457
- if (!result) {
458
- throw Error('send message error')
459
- }
460
- }
461
-
462
- sendBinBySide(buf, debug = DEBUG) {
463
- // side 发送消息
464
- debug && logger.warn('[RAW] [S] send size=%d bin=%s', buf.byteLength, bin2hex(buf.buffer))
465
- messaging.peerSocket.send(buf.buffer)
466
- }
467
-
468
- // 通用获取逻辑
469
- getSafeSend() {
470
- if (this.isDevice) {
471
- return this.sendBin.bind(this)
472
- } else {
473
- return this.sendBinBySide.bind(this)
474
- }
475
- }
476
-
477
- _logSend(buf) {
478
- this.sendMsg(buf, false)
479
- }
480
-
481
- // 大数据的复杂头部分包协议
482
- sendHmProtocol(
483
- { requestId, dataBin, type, contentType, dataType },
484
- { messageType = MessageType.Data } = {}
485
- ) {
486
- const headerSize = 0
487
- const hmDataSize = HM_MESSAGE_PROTO_PAYLOAD
488
- const userDataLength = dataBin.byteLength
489
-
490
- let offset = 0
491
- const _buf = Buffer.alloc(hmDataSize)
492
- const traceId = requestId ? requestId : genTraceId()
493
- const spanId = genSpanId()
494
- let seqId = 1
495
-
496
- const count = Math.ceil(userDataLength / hmDataSize)
497
-
498
- function genSeqId() {
499
- return seqId++
500
- }
501
-
502
- for (let i = 1; i <= count; i++) {
503
- this.errorIfBleDisconnect()
504
- if (i === count) {
505
- // last
506
- const tailSize = userDataLength - offset
507
- const tailBuf = Buffer.alloc(headerSize + tailSize)
508
-
509
- dataBin.copy(tailBuf, headerSize, offset, offset + tailSize)
510
- offset += tailSize
511
- this.sendDataWithSession(
512
- {
513
- traceId,
514
- spanId: spanId,
515
- seqId: genSeqId(),
516
- payload: tailBuf,
517
- type,
518
- opCode: MessagePayloadOpCode.Finished,
519
- totalLength: userDataLength,
520
- contentType,
521
- dataType
522
- },
523
- {
524
- messageType
525
- }
526
- )
527
-
528
- break
529
- }
530
-
531
- dataBin.copy(_buf, headerSize, offset, offset + hmDataSize)
532
- offset += hmDataSize
533
-
534
- this.sendDataWithSession(
535
- {
536
- traceId,
537
- spanId: spanId,
538
- seqId: genSeqId(),
539
- payload: _buf,
540
- type,
541
- opCode: MessagePayloadOpCode.Continued,
542
- totalLength: userDataLength,
543
- contentType,
544
- dataType
545
- },
546
- {
547
- messageType
548
- }
549
- )
550
- }
551
-
552
- if (offset === userDataLength) {
553
- DEBUG && logger.debug('HmProtocol send ok msgSize=> %d dataSize=> %d', offset, userDataLength)
554
- } else {
555
- DEBUG &&
556
- logger.error('HmProtocol send error msgSize=> %d dataSize=> %d', offset, userDataLength)
557
- }
558
- }
559
-
560
- // 大数据的简单分包协议
561
- sendSimpleProtocol({ dataBin }, { messageType = MessageType.Data } = {}) {
562
- const dataSize = this.chunkSize
563
- const headerSize = 0
564
- const userDataLength = dataBin.byteLength
565
-
566
- let offset = 0
567
- const _buf = Buffer.alloc(dataSize)
568
-
569
- const count = Math.ceil(userDataLength / dataSize)
570
-
571
- for (let i = 1; i <= count; i++) {
572
- if (i === count) {
573
- // last
574
- const tailSize = userDataLength - offset
575
- const tailBuf = Buffer.alloc(headerSize + tailSize)
576
-
577
- dataBin.copy(tailBuf, headerSize, offset, offset + tailSize)
578
- offset += tailSize
579
- this.sendSimpleData(
580
- {
581
- payload: tailBuf
582
- },
583
- {
584
- messageType
585
- }
586
- )
587
-
588
- break
589
- }
590
-
591
- dataBin.copy(_buf, headerSize, offset, offset + dataSize)
592
- offset += dataSize
593
-
594
- this.sendSimpleData(
595
- {
596
- payload: _buf
597
- },
598
- {
599
- messageType
600
- }
601
- )
602
- }
603
-
604
- if (offset === userDataLength) {
605
- // logger.debug('SimpleProtocol send ok msgSize=> %d dataSize=> %d', offset, userDataLength)
606
- } else {
607
- // logger.error('SimpleProtocol send error msgSize=> %d dataSize=> %d', offset, userDataLength)
608
- }
609
- }
610
-
611
- sendJson({ requestId = 0, json, type = MessagePayloadType.Request, contentType, dataType }) {
612
- const packageBin = json2buf(json)
613
- const traceId = requestId ? requestId : genTraceId()
614
-
615
- this.sendHmProtocol({
616
- requestId: traceId,
617
- dataBin: packageBin,
618
- type,
619
- contentType,
620
- dataType
621
- })
622
- }
623
-
624
- sendBuf({ requestId = 0, buf, type = MessagePayloadType.Request, contentType, dataType }) {
625
- const traceId = requestId ? requestId : genTraceId()
626
-
627
- return this.sendHmProtocol({
628
- requestId: traceId,
629
- dataBin: buf,
630
- type,
631
- contentType,
632
- dataType
633
- })
634
- }
635
-
636
- sendLog(str) {
637
- const packageBuf = str2buf(str)
638
- this.sendSimpleProtocol(
639
- {
640
- dataBin: packageBuf
641
- },
642
- {
643
- messageType: MessageType.Log
644
- }
645
- )
646
- }
647
-
648
- sendDataWithSession(
649
- { traceId, spanId, seqId, payload, type, opCode, totalLength, contentType, dataType },
650
- { messageType }
651
- ) {
652
- const payloadBin = this.buildPayload({
653
- traceId,
654
- spanId,
655
- seqId,
656
- totalLength,
657
- type,
658
- opCode,
659
- payload,
660
- contentType,
661
- dataType
662
- })
663
-
664
- let data = this.isDevice
665
- ? this.buildData(payloadBin, {
666
- type: messageType
667
- })
668
- : payloadBin
669
-
670
- this.sendMsg(data)
671
- }
672
-
673
- sendSimpleData({ payload }, { messageType }) {
674
- let data = this.isDevice
675
- ? this.buildData(payload, {
676
- type: messageType
677
- })
678
- : payload
679
-
680
- this._logSend(data)
681
- }
682
-
683
- buildPayload(data) {
684
- const size = HM_MESSAGE_PROTO_HEADER + data.payload.byteLength
685
- let buf = Buffer.alloc(size)
686
- let offset = 0
687
-
688
- // header
689
- // traceId
690
- buf.writeUInt32LE(data.traceId, offset)
691
- offset += 4
692
-
693
- // parentId
694
- buf.writeUInt32LE(0, offset)
695
- offset += 4
696
-
697
- // spanId
698
- buf.writeUInt32LE(data.spanId, offset)
699
- offset += 4
700
-
701
- // seqId // 顺序 id,消息部分顺序序列号
702
- buf.writeUInt32LE(data.seqId, offset)
703
- offset += 4
704
-
705
- // message total length
706
- buf.writeUInt32LE(data.totalLength, offset)
707
- offset += 4
708
-
709
- // payload length 当前
710
- buf.writeUInt32LE(data.payload.byteLength, offset)
711
- offset += 4
712
-
713
- // payload type
714
- buf.writeUInt8(data.type, offset)
715
- offset += 1
716
-
717
- // opCode
718
- buf.writeUInt8(data.opCode, offset)
719
- offset += 1
720
-
721
- // timestamp1
722
- buf.writeUInt32LE(this.now(), offset)
723
- offset += 4
724
-
725
- // timestamp2
726
- buf.writeUInt32LE(0, offset)
727
- offset += 4
728
-
729
- // timestamp3
730
- buf.writeUInt32LE(0, offset)
731
- offset += 4
732
-
733
- // timestamp4
734
- buf.writeUInt32LE(0, offset)
735
- offset += 4
736
-
737
- // timestamp5
738
- buf.writeUInt32LE(0, offset)
739
- offset += 4
740
-
741
- // timestamp6
742
- buf.writeUInt32LE(0, offset)
743
- offset += 4
744
-
745
- // timestamp7
746
- buf.writeUInt32LE(0, offset)
747
- offset += 4
748
-
749
- // request content data type
750
- buf.writeUInt8(data.contentType, offset)
751
- offset += 1
752
-
753
- // response data type
754
- buf.writeUInt8(data.dataType, offset)
755
- offset += 1
756
-
757
- buf.writeUInt16LE(0, offset)
758
- offset += 2
759
-
760
- // extra1
761
- buf.writeUInt32LE(0, offset)
762
- offset += 4
763
-
764
- // extra2
765
- buf.writeUInt32LE(0, offset)
766
- offset += 4
767
-
768
- // payload
769
- buf.fill(data.payload, offset, data.payload.byteLength + offset)
770
-
771
- return buf
772
- }
773
-
774
- readPayload(arrayBuf) {
775
- const buf = Buffer.from(arrayBuf)
776
- let offset = 0
777
-
778
- const traceId = buf.readUInt32LE(offset)
779
- offset += 4
780
-
781
- const parentId = buf.readUInt32LE(offset)
782
- offset += 4
783
-
784
- const spanId = buf.readUInt32LE(offset)
785
- offset += 4
786
-
787
- const seqId = buf.readUInt32LE(offset)
788
- offset += 4
789
-
790
- const totalLength = buf.readUInt32LE(offset)
791
- offset += 4
792
-
793
- const payloadLength = buf.readUInt32LE(offset)
794
- offset += 4
795
-
796
- const payloadType = buf.readUInt8(offset)
797
- offset += 1
798
-
799
- const opCode = buf.readUInt8(offset)
800
- offset += 1
801
-
802
- const timestamp1 = buf.readUInt32LE(offset)
803
- offset += 4
804
-
805
- const timestamp2 = buf.readUInt32LE(offset)
806
- offset += 4
807
-
808
- const timestamp3 = buf.readUInt32LE(offset)
809
- offset += 4
810
-
811
- const timestamp4 = buf.readUInt32LE(offset)
812
- offset += 4
813
-
814
- const timestamp5 = buf.readUInt32LE(offset)
815
- offset += 4
816
-
817
- const timestamp6 = buf.readUInt32LE(offset)
818
- offset += 4
819
-
820
- const timestamp7 = buf.readUInt32LE(offset)
821
- offset += 4
822
-
823
- // request data type
824
- const contentType = buf.readUInt8(offset)
825
- offset += 1
826
-
827
- // response data type
828
- const dataType = buf.readUInt8(offset)
829
- offset += 1
830
-
831
- const extra1 = buf.readUInt16LE(offset)
832
- offset += 2
833
-
834
- const extra2 = buf.readUInt32LE(offset)
835
- offset += 4
836
-
837
- const extra3 = buf.readUInt32LE(offset)
838
- offset += 4
839
-
840
- const payload = buf.subarray(offset)
841
-
842
- return {
843
- traceId,
844
- parentId,
845
- spanId,
846
- seqId,
847
- totalLength,
848
- payloadLength,
849
- payloadType,
850
- opCode,
851
- contentType,
852
- dataType,
853
- timestamp1,
854
- timestamp2,
855
- timestamp3,
856
- timestamp4,
857
- timestamp5,
858
- timestamp6,
859
- timestamp7,
860
- extra1,
861
- extra2,
862
- extra3,
863
- payload
864
- }
865
- }
866
-
867
- onFragmentData(bin) {
868
- const data = this.readBin(bin)
869
- this.emit('raw', bin)
870
-
871
- DEBUG && logger.debug('receive data=>', JSON.stringify(data))
872
- if (data.flag === MessageFlag.App && data.type === MessageType.Shake) {
873
- this.appSidePort = data.port2
874
- logger.debug('appSidePort=>', data.port2)
875
- this.shakeTask.resolve()
876
- } else if (
877
- data.flag === MessageFlag.App &&
878
- data.type === MessageType.Data &&
879
- data.port2 === this.appSidePort
880
- ) {
881
- this.emit('message', data.payload)
882
- this.emit('read', data)
883
- } else if (
884
- data.flag === MessageFlag.App &&
885
- data.type === MessageType.DataWithSystemTool &&
886
- data.port2 === this.appSidePort
887
- ) {
888
- this.emit('message', data.payload)
889
- this.emit('read', data)
890
- } else if (
891
- data.flag === MessageFlag.App &&
892
- data.type === MessageType.Log &&
893
- data.port2 === this.appSidePort
894
- ) {
895
- this.emit('log', data.payload)
896
- } else {
897
- logger.error('error appSidePort=>%d data=>%j', this.appSidePort, data)
898
- }
899
- }
900
-
901
- errorIfBleDisconnect() {}
902
-
903
- onMessage(messagePayload) {
904
- const payload = this.readPayload(messagePayload)
905
- let session = this.sessionMgr.getById(payload.traceId, payload.payloadType)
906
-
907
- if (!session) {
908
- session = this.sessionMgr.newSession(payload.traceId, payload.payloadType, this)
909
-
910
- // TODO: 需要考虑缓冲,监听回调要放到启动之前,或者没有增加监听就缓存请求
911
- session.on('data', (fullPayload) => {
912
- if (fullPayload.opCode === MessagePayloadOpCode.Finished) {
913
- if (fullPayload.payloadType === MessagePayloadType.Request) {
914
- this.emit('request', {
915
- request: fullPayload,
916
- response: ({ data }) => {
917
- this.response({
918
- requestId: fullPayload.traceId,
919
- contentType: fullPayload.contentType,
920
- dataType: fullPayload.dataType,
921
- data
922
- })
923
- }
924
- })
925
- } else if (fullPayload.payloadType === MessagePayloadType.Response) {
926
- this.emit('response', fullPayload)
927
- } else if (fullPayload.payloadType === MessagePayloadType.Notify) {
928
- this.emit('call', fullPayload)
929
- }
930
-
931
- this.emit('data', fullPayload)
932
- this.sessionMgr.destroy(session)
933
- }
934
- })
935
-
936
- session.on('error', (error) => {
937
- this.sessionMgr.destroy(session)
938
- this.emit('error', error)
939
- })
940
- }
941
-
942
- session.addChunk(payload)
943
- }
944
-
945
- /**
946
- * 发送请求
947
- * @param {object buffer arraybuffer arraybuffer like} data 传输的数据
948
- * @param {*} opts
949
- * @returns
950
- */
951
- request(data, opts) {
952
- const _request = () => {
953
- const defaultOpts = {
954
- timeout: 60000,
955
- contentType: 'json',
956
- dataType: 'json'
957
- }
958
- const requestId = genTraceId()
959
- const defer = Deferred()
960
- opts = Object.assign(defaultOpts, opts)
961
-
962
- const error = (error) => {
963
- this.off('error', error)
964
- defer.reject(error)
965
- }
966
-
967
- const transact = ({ traceId, payload, dataType }) => {
968
- this.errorIfBleDisconnect()
969
- DEBUG && logger.debug('traceId=>%d payload=>%s', traceId, payload.toString('hex'))
970
- if (traceId === requestId) {
971
- let result
972
- switch (dataType) {
973
- case MessagePayloadDataTypeOp.TEXT:
974
- result = buf2str(payload)
975
- break
976
- case MessagePayloadDataTypeOp.BIN:
977
- result = payload
978
- break
979
- case MessagePayloadDataTypeOp.JSON:
980
- result = buf2json(payload)
981
- break
982
- default: // text
983
- result = buf2str(payload)
984
- break
985
- }
986
- DEBUG && logger.debug('request id=>%d payload=>%j', requestId, data)
987
- DEBUG && logger.debug('response id=>%d payload=>%j', requestId, result)
988
-
989
- this.off('response', transact)
990
- this.off('error', error)
991
- defer.resolve(result)
992
- }
993
- }
994
-
995
- this.on('response', transact)
996
- this.on('error', error)
997
- if (Buffer.isBuffer(data)) {
998
- this.sendBuf({
999
- requestId,
1000
- buf: data,
1001
- type: MessagePayloadType.Request,
1002
- contentType: MessagePayloadDataTypeOp.BIN,
1003
- dataType: getDataType(opts.dataType)
1004
- })
1005
- } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
1006
- this.sendBuf({
1007
- requestId,
1008
- buf: Buffer.from(data),
1009
- type: MessagePayloadType.Request,
1010
- contentType: MessagePayloadDataTypeOp.BIN,
1011
- dataType: getDataType(opts.dataType)
1012
- })
1013
- } else {
1014
- this.sendJson({
1015
- requestId,
1016
- json: data,
1017
- type: MessagePayloadType.Request,
1018
- contentType: MessagePayloadDataTypeOp.JSON,
1019
- dataType: getDataType(opts.dataType)
1020
- })
1021
- }
1022
-
1023
- let hasReturned = false
1024
-
1025
- return Promise.race([
1026
- timeout(opts.timeout, (resolve, reject) => {
1027
- if (hasReturned) {
1028
- return resolve()
1029
- }
1030
-
1031
- DEBUG &&
1032
- logger.error(
1033
- `request timeout in ${opts.timeout}ms error=> %d data=> %j`,
1034
- requestId,
1035
- data
1036
- )
1037
- this.off('response', transact)
1038
-
1039
- reject(Error(`Timed out in ${opts.timeout}ms.`))
1040
- }),
1041
- defer.promise.finally(() => {
1042
- hasReturned = true
1043
- })
1044
- ])
1045
- }
1046
-
1047
- return this.waitingShakePromise.then(_request)
1048
- }
1049
-
1050
- requestCb(data, opts, cb) {
1051
- const _requestCb = () => {
1052
- const defaultOpts = {
1053
- timeout: 60000,
1054
- contentType: 'json',
1055
- dataType: 'json'
1056
- }
1057
-
1058
- if (typeof opts === 'function') {
1059
- cb = opts
1060
- opts = defaultOpts
1061
- } else {
1062
- opts = Object.assign(defaultOpts, opts)
1063
- }
1064
-
1065
- const requestId = genTraceId()
1066
- let timer1 = null
1067
- let hasReturned = false
1068
-
1069
- const transact = ({ traceId, payload, dataType }) => {
1070
- DEBUG && logger.debug('traceId=>%d payload=>%s', traceId, payload.toString('hex'))
1071
- if (traceId === requestId) {
1072
- let result
1073
- switch (dataType) {
1074
- case MessagePayloadDataTypeOp.TEXT:
1075
- result = buf2str(payload)
1076
- break
1077
- case MessagePayloadDataTypeOp.BIN:
1078
- result = payload
1079
- break
1080
- case MessagePayloadDataTypeOp.JSON:
1081
- result = buf2json(payload)
1082
- break
1083
- default: // text
1084
- result = buf2str(payload)
1085
- break
1086
- }
1087
- DEBUG && logger.debug('request id=>%d payload=>%j', requestId, data)
1088
- DEBUG && logger.debug('response id=>%d payload=>%j', requestId, result)
1089
-
1090
- timer1 && clearTimeout(timer1)
1091
- timer1 = null
1092
- this.off('response', transact)
1093
- hasReturned = true
1094
- cb(null, result)
1095
- }
1096
- }
1097
-
1098
- this.on('response', transact)
1099
- if (Buffer.isBuffer(data)) {
1100
- this.sendBuf({
1101
- requestId,
1102
- buf: data,
1103
- type: MessagePayloadType.Request,
1104
- contentType: MessagePayloadDataTypeOp.BIN,
1105
- dataType: getDataType(opts.dataType)
1106
- })
1107
- } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
1108
- this.sendBuf({
1109
- requestId,
1110
- buf: Buffer.from(data),
1111
- type: MessagePayloadType.Request,
1112
- contentType: MessagePayloadDataTypeOp.BIN,
1113
- dataType: getDataType(opts.dataType)
1114
- })
1115
- } else {
1116
- this.sendJson({
1117
- requestId,
1118
- json: data,
1119
- type: MessagePayloadType.Request,
1120
- contentType: MessagePayloadDataTypeOp.JSON,
1121
- dataType: getDataType(opts.dataType)
1122
- })
1123
- }
1124
-
1125
- timer1 = setTimeout(() => {
1126
- timer1 = null
1127
- if (hasReturned) {
1128
- return
1129
- }
1130
-
1131
- DEBUG &&
1132
- logger.error(`request time out in ${opts.timeout}ms error=>%d data=>%j`, requestId, data)
1133
- this.off('response', transact)
1134
- cb(Error(`Timed out in ${opts.timeout}ms.`))
1135
- }, opts.timeout)
1136
- }
1137
-
1138
- return this.waitingShakePromise.then(_requestCb)
1139
- }
1140
-
1141
- /**
1142
- * 相应接口给当前请求
1143
- * @param {obj} param0
1144
- */
1145
- response({ requestId, contentType, dataType, data }) {
1146
- if (MessagePayloadDataTypeOp.BIN === dataType) {
1147
- this.sendBuf({
1148
- requestId,
1149
- buf: data,
1150
- type: MessagePayloadType.Response,
1151
- contentType,
1152
- dataType
1153
- })
1154
- } else {
1155
- this.sendJson({
1156
- requestId,
1157
- json: data,
1158
- type: MessagePayloadType.Response,
1159
- contentType,
1160
- dataType
1161
- })
1162
- }
1163
- }
1164
-
1165
- /**
1166
- * call 模式调用接口到伴生服务
1167
- * @param {json | buffer} data
1168
- * @returns
1169
- */
1170
- call(data) {
1171
- return this.waitingShakePromise.then(() => {
1172
- if (Buffer.isBuffer(data)) {
1173
- return this.sendBuf({
1174
- buf: data,
1175
- type: MessagePayloadType.Notify,
1176
- contentType: MessagePayloadDataTypeOp.BIN,
1177
- dataType: MessagePayloadDataTypeOp.EMPTY
1178
- })
1179
- } else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
1180
- return this.sendBuf({
1181
- buf: Buffer.from(data),
1182
- type: MessagePayloadType.Notify,
1183
- contentType: MessagePayloadDataTypeOp.BIN,
1184
- dataType: MessagePayloadDataTypeOp.EMPTY
1185
- })
1186
- } else {
1187
- return this.sendJson({
1188
- json: data,
1189
- type: MessagePayloadType.Notify,
1190
- contentType: MessagePayloadDataTypeOp.JSON,
1191
- dataType: MessagePayloadDataTypeOp.EMPTY
1192
- })
1193
- }
1194
- })
1195
- }
1196
- }