zigbee-herdsman 0.33.9 → 0.34.2

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 (122) hide show
  1. package/.github/workflows/ci.yml +2 -2
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/dist/adapter/adapter.d.ts.map +1 -1
  5. package/dist/adapter/adapter.js +2 -1
  6. package/dist/adapter/adapter.js.map +1 -1
  7. package/dist/adapter/ember/adapter/emberAdapter.d.ts +818 -0
  8. package/dist/adapter/ember/adapter/emberAdapter.d.ts.map +1 -0
  9. package/dist/adapter/ember/adapter/emberAdapter.js +2991 -0
  10. package/dist/adapter/ember/adapter/emberAdapter.js.map +1 -0
  11. package/dist/adapter/ember/adapter/endpoints.d.ts +25 -0
  12. package/dist/adapter/ember/adapter/endpoints.d.ts.map +1 -0
  13. package/dist/adapter/ember/adapter/endpoints.js +66 -0
  14. package/dist/adapter/ember/adapter/endpoints.js.map +1 -0
  15. package/dist/adapter/ember/adapter/index.d.ts +3 -0
  16. package/dist/adapter/ember/adapter/index.d.ts.map +1 -0
  17. package/dist/adapter/ember/adapter/index.js +6 -0
  18. package/dist/adapter/ember/adapter/index.js.map +1 -0
  19. package/dist/adapter/ember/adapter/oneWaitress.d.ts +97 -0
  20. package/dist/adapter/ember/adapter/oneWaitress.d.ts.map +1 -0
  21. package/dist/adapter/ember/adapter/oneWaitress.js +226 -0
  22. package/dist/adapter/ember/adapter/oneWaitress.js.map +1 -0
  23. package/dist/adapter/ember/adapter/requestQueue.d.ts +59 -0
  24. package/dist/adapter/ember/adapter/requestQueue.d.ts.map +1 -0
  25. package/dist/adapter/ember/adapter/requestQueue.js +144 -0
  26. package/dist/adapter/ember/adapter/requestQueue.js.map +1 -0
  27. package/dist/adapter/ember/adapter/tokensManager.d.ts +69 -0
  28. package/dist/adapter/ember/adapter/tokensManager.d.ts.map +1 -0
  29. package/dist/adapter/ember/adapter/tokensManager.js +685 -0
  30. package/dist/adapter/ember/adapter/tokensManager.js.map +1 -0
  31. package/dist/adapter/ember/consts.d.ts +198 -0
  32. package/dist/adapter/ember/consts.d.ts.map +1 -0
  33. package/dist/adapter/ember/consts.js +253 -0
  34. package/dist/adapter/ember/consts.js.map +1 -0
  35. package/dist/adapter/ember/enums.d.ts +2184 -0
  36. package/dist/adapter/ember/enums.d.ts.map +1 -0
  37. package/dist/adapter/ember/enums.js +2391 -0
  38. package/dist/adapter/ember/enums.js.map +1 -0
  39. package/dist/adapter/ember/ezsp/buffalo.d.ts +156 -0
  40. package/dist/adapter/ember/ezsp/buffalo.d.ts.map +1 -0
  41. package/dist/adapter/ember/ezsp/buffalo.js +1033 -0
  42. package/dist/adapter/ember/ezsp/buffalo.js.map +1 -0
  43. package/dist/adapter/ember/ezsp/consts.d.ts +116 -0
  44. package/dist/adapter/ember/ezsp/consts.d.ts.map +1 -0
  45. package/dist/adapter/ember/ezsp/consts.js +128 -0
  46. package/dist/adapter/ember/ezsp/consts.js.map +1 -0
  47. package/dist/adapter/ember/ezsp/enums.d.ts +879 -0
  48. package/dist/adapter/ember/ezsp/enums.d.ts.map +1 -0
  49. package/dist/adapter/ember/ezsp/enums.js +948 -0
  50. package/dist/adapter/ember/ezsp/enums.js.map +1 -0
  51. package/dist/adapter/ember/ezsp/ezsp.d.ts +2664 -0
  52. package/dist/adapter/ember/ezsp/ezsp.d.ts.map +1 -0
  53. package/dist/adapter/ember/ezsp/ezsp.js +6449 -0
  54. package/dist/adapter/ember/ezsp/ezsp.js.map +1 -0
  55. package/dist/adapter/ember/types.d.ts +733 -0
  56. package/dist/adapter/ember/types.d.ts.map +1 -0
  57. package/dist/adapter/ember/types.js +3 -0
  58. package/dist/adapter/ember/types.js.map +1 -0
  59. package/dist/adapter/ember/uart/ash.d.ts +443 -0
  60. package/dist/adapter/ember/uart/ash.d.ts.map +1 -0
  61. package/dist/adapter/ember/uart/ash.js +1567 -0
  62. package/dist/adapter/ember/uart/ash.js.map +1 -0
  63. package/dist/adapter/ember/uart/consts.d.ts +91 -0
  64. package/dist/adapter/ember/uart/consts.d.ts.map +1 -0
  65. package/dist/adapter/ember/uart/consts.js +100 -0
  66. package/dist/adapter/ember/uart/consts.js.map +1 -0
  67. package/dist/adapter/ember/uart/enums.d.ts +191 -0
  68. package/dist/adapter/ember/uart/enums.d.ts.map +1 -0
  69. package/dist/adapter/ember/uart/enums.js +197 -0
  70. package/dist/adapter/ember/uart/enums.js.map +1 -0
  71. package/dist/adapter/ember/uart/parser.d.ts +10 -0
  72. package/dist/adapter/ember/uart/parser.d.ts.map +1 -0
  73. package/dist/adapter/ember/uart/parser.js +41 -0
  74. package/dist/adapter/ember/uart/parser.js.map +1 -0
  75. package/dist/adapter/ember/uart/queues.d.ts +85 -0
  76. package/dist/adapter/ember/uart/queues.d.ts.map +1 -0
  77. package/dist/adapter/ember/uart/queues.js +212 -0
  78. package/dist/adapter/ember/uart/queues.js.map +1 -0
  79. package/dist/adapter/ember/uart/writer.d.ts +15 -0
  80. package/dist/adapter/ember/uart/writer.d.ts.map +1 -0
  81. package/dist/adapter/ember/uart/writer.js +48 -0
  82. package/dist/adapter/ember/uart/writer.js.map +1 -0
  83. package/dist/adapter/ember/utils/initters.d.ts +20 -0
  84. package/dist/adapter/ember/utils/initters.d.ts.map +1 -0
  85. package/dist/adapter/ember/utils/initters.js +58 -0
  86. package/dist/adapter/ember/utils/initters.js.map +1 -0
  87. package/dist/adapter/ember/utils/math.d.ts +51 -0
  88. package/dist/adapter/ember/utils/math.d.ts.map +1 -0
  89. package/dist/adapter/ember/utils/math.js +102 -0
  90. package/dist/adapter/ember/utils/math.js.map +1 -0
  91. package/dist/adapter/ember/zdo.d.ts +921 -0
  92. package/dist/adapter/ember/zdo.d.ts.map +1 -0
  93. package/dist/adapter/ember/zdo.js +723 -0
  94. package/dist/adapter/ember/zdo.js.map +1 -0
  95. package/dist/adapter/ezsp/adapter/ezspAdapter.d.ts.map +1 -1
  96. package/dist/adapter/ezsp/adapter/ezspAdapter.js +28 -22
  97. package/dist/adapter/ezsp/adapter/ezspAdapter.js.map +1 -1
  98. package/dist/adapter/ezsp/driver/driver.d.ts +1 -2
  99. package/dist/adapter/ezsp/driver/driver.d.ts.map +1 -1
  100. package/dist/adapter/ezsp/driver/driver.js +21 -21
  101. package/dist/adapter/ezsp/driver/driver.js.map +1 -1
  102. package/dist/adapter/ezsp/driver/ezsp.d.ts +2 -0
  103. package/dist/adapter/ezsp/driver/ezsp.d.ts.map +1 -1
  104. package/dist/adapter/ezsp/driver/ezsp.js +24 -5
  105. package/dist/adapter/ezsp/driver/ezsp.js.map +1 -1
  106. package/dist/adapter/ezsp/driver/parser.d.ts +1 -2
  107. package/dist/adapter/ezsp/driver/parser.d.ts.map +1 -1
  108. package/dist/adapter/ezsp/driver/parser.js +29 -40
  109. package/dist/adapter/ezsp/driver/parser.js.map +1 -1
  110. package/dist/adapter/ezsp/driver/uart.d.ts +1 -0
  111. package/dist/adapter/ezsp/driver/uart.d.ts.map +1 -1
  112. package/dist/adapter/ezsp/driver/uart.js +38 -13
  113. package/dist/adapter/ezsp/driver/uart.js.map +1 -1
  114. package/dist/adapter/ezsp/driver/writer.d.ts.map +1 -1
  115. package/dist/adapter/ezsp/driver/writer.js +10 -13
  116. package/dist/adapter/ezsp/driver/writer.js.map +1 -1
  117. package/dist/adapter/tstype.d.ts +1 -1
  118. package/dist/adapter/tstype.d.ts.map +1 -1
  119. package/dist/utils/backup.d.ts.map +1 -1
  120. package/dist/utils/backup.js +4 -0
  121. package/dist/utils/backup.js.map +1 -1
  122. package/package.json +1 -1
@@ -0,0 +1,1567 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.UartAsh = exports.AshEvents = void 0;
7
+ /* istanbul ignore file */
8
+ const debug_1 = __importDefault(require("debug"));
9
+ const stream_1 = require("stream");
10
+ const net_1 = require("net");
11
+ const socketPortUtils_1 = __importDefault(require("../../socketPortUtils"));
12
+ const serialPort_1 = require("../../serialPort");
13
+ const consts_1 = require("./consts");
14
+ const math_1 = require("../utils/math");
15
+ const enums_1 = require("../enums");
16
+ const enums_2 = require("./enums");
17
+ const queues_1 = require("./queues");
18
+ const writer_1 = require("./writer");
19
+ const parser_1 = require("./parser");
20
+ const utils_1 = require("../../../utils");
21
+ const debug = (0, debug_1.default)('zigbee-herdsman:adapter:ember:uart:ash');
22
+ /** ASH get rflag in control byte */
23
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
24
+ const ashGetRFlag = (ctrl) => ((ctrl & consts_1.ASH_RFLAG_MASK) >> consts_1.ASH_RFLAG_BIT);
25
+ /** ASH get nflag in control byte */
26
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
27
+ const ashGetNFlag = (ctrl) => ((ctrl & consts_1.ASH_NFLAG_MASK) >> consts_1.ASH_NFLAG_BIT);
28
+ /** ASH get frmnum in control byte */
29
+ const ashGetFrmNum = (ctrl) => ((ctrl & consts_1.ASH_FRMNUM_MASK) >> consts_1.ASH_FRMNUM_BIT);
30
+ /** ASH get acknum in control byte */
31
+ const ashGetACKNum = (ctrl) => ((ctrl & consts_1.ASH_ACKNUM_MASK) >> consts_1.ASH_ACKNUM_BIT);
32
+ var AshEvents;
33
+ (function (AshEvents) {
34
+ /** When the host detects a fatal error */
35
+ AshEvents["hostError"] = "hostError";
36
+ /** When the NCP reports a fatal error */
37
+ AshEvents["ncpError"] = "ncpError";
38
+ /** When a frame has been parsed and queued in the rxQueue. */
39
+ AshEvents["frame"] = "frame";
40
+ })(AshEvents || (exports.AshEvents = AshEvents = {}));
41
+ var SendState;
42
+ (function (SendState) {
43
+ SendState[SendState["IDLE"] = 0] = "IDLE";
44
+ SendState[SendState["SHFRAME"] = 1] = "SHFRAME";
45
+ SendState[SendState["TX_DATA"] = 2] = "TX_DATA";
46
+ SendState[SendState["RETX_DATA"] = 3] = "RETX_DATA";
47
+ })(SendState || (SendState = {}));
48
+ // Bits in ashFlags
49
+ var Flag;
50
+ (function (Flag) {
51
+ /** Reject Condition */
52
+ Flag[Flag["REJ"] = 1] = "REJ";
53
+ /** Retransmit Condition */
54
+ Flag[Flag["RETX"] = 2] = "RETX";
55
+ /** send NAK */
56
+ Flag[Flag["NAK"] = 4] = "NAK";
57
+ /** send ACK */
58
+ Flag[Flag["ACK"] = 8] = "ACK";
59
+ /** send RST */
60
+ Flag[Flag["RST"] = 16] = "RST";
61
+ /** send immediate CAN */
62
+ Flag[Flag["CAN"] = 32] = "CAN";
63
+ /** in CONNECTED state, else ERROR */
64
+ Flag[Flag["CONNECTED"] = 64] = "CONNECTED";
65
+ /** not ready to receive DATA frames */
66
+ Flag[Flag["NR"] = 256] = "NR";
67
+ /** last transmitted NR status */
68
+ Flag[Flag["NRTX"] = 512] = "NRTX";
69
+ })(Flag || (Flag = {}));
70
+ /** max frames sent without being ACKed (1-7) */
71
+ const CONFIG_TX_K = 3;
72
+ /** enables randomizing DATA frame payloads */
73
+ const CONFIG_RANDOMIZE = true;
74
+ /** adaptive rec'd ACK timeout initial value */
75
+ const CONFIG_ACK_TIME_INIT = 800;
76
+ /** " " " " " minimum value */
77
+ const CONFIG_ACK_TIME_MIN = 400;
78
+ /** " " " " " maximum value */
79
+ const CONFIG_ACK_TIME_MAX = 2400;
80
+ /** time allowed to receive RSTACK after ncp is reset */
81
+ const CONFIG_TIME_RST = 2500;
82
+ /** time between checks for received RSTACK (CONNECTED status) */
83
+ const CONFIG_TIME_RST_CHECK = 100;
84
+ /** if free buffers < limit, host receiver isn't ready, will hold off the ncp from sending normal priority frames */
85
+ const CONFIG_NR_LOW_LIMIT = 8; // RX_FREE_LW
86
+ /** if free buffers > limit, host receiver is ready */
87
+ const CONFIG_NR_HIGH_LIMIT = 12; // RX_FREE_HW
88
+ /** time until a set nFlag must be resent (max 2032) */
89
+ const CONFIG_NR_TIME = 480;
90
+ /** Read/write max bytes count at stream level */
91
+ const CONFIG_HIGHWATER_MARK = 256;
92
+ /**
93
+ * ASH Protocol handler.
94
+ */
95
+ class UartAsh extends stream_1.EventEmitter {
96
+ portOptions;
97
+ serialPort;
98
+ socketPort;
99
+ writer;
100
+ parser;
101
+ /** True when serial/socket is currently closing. */
102
+ closing;
103
+ /** time ackTimer started: 0 means not ready uint16_t */
104
+ ackTimer;
105
+ /** time used to check ackTimer expiry (msecs) uint16_t */
106
+ ackPeriod;
107
+ /** not ready timer (16 msec units). Set to (now + config.nrTime) when started. uint8_t */
108
+ nrTimer;
109
+ /** frame decode in progress */
110
+ decodeInProgress;
111
+ // Variables used in encoding frames
112
+ /** true when preceding byte was escaped */
113
+ encodeEscFlag;
114
+ /** byte to send after ASH_ESC uint8_t */
115
+ encodeFlip;
116
+ /** uint16_t */
117
+ encodeCrc;
118
+ /** encoder state: 0 = control/data bytes, 1 = crc low byte, 2 = crc high byte, 3 = flag. uint8_t */
119
+ encodeState;
120
+ /** bytes remaining to encode. uint8_t */
121
+ encodeCount;
122
+ // Variables used in decoding frames
123
+ /** bytes in frame, plus CRC, clamped to limit +1: high values also used to record certain errors. uint8_t */
124
+ decodeLen;
125
+ /** ASH_FLIP if previous byte was ASH_ESC. uint8_t */
126
+ decodeFlip;
127
+ /** a 2 byte queue to avoid outputting crc bytes. uint8_t */
128
+ decodeByte1;
129
+ /** at frame end, they contain the received crc. uint8_t */
130
+ decodeByte2;
131
+ /** uint16_t */
132
+ decodeCrc;
133
+ /** outgoing short frames */
134
+ txSHBuffer;
135
+ /** incoming short frames */
136
+ rxSHBuffer;
137
+ /** bit flags for top-level logic. uint16_t */
138
+ flags;
139
+ /** frame ack'ed from remote peer. uint8_t */
140
+ ackRx;
141
+ /** frame ack'ed to remote peer. uint8_t */
142
+ ackTx;
143
+ /** next frame to be transmitted. uint8_t */
144
+ frmTx;
145
+ /** next frame to be retransmitted. uint8_t */
146
+ frmReTx;
147
+ /** next frame expected to be rec'd. uint8_t */
148
+ frmRx;
149
+ /** frame at retx queue's head. uint8_t */
150
+ frmReTxHead;
151
+ /** consecutive timeout counter. uint8_t */
152
+ timeouts;
153
+ /** rec'd DATA frame buffer. uint8_t */
154
+ rxDataBuffer;
155
+ /** rec'd frame length. uint8_t */
156
+ rxLen;
157
+ /** tx frame offset. uint8_t */
158
+ txOffset;
159
+ counters;
160
+ ncpError;
161
+ hostError;
162
+ /** sendExec() state variable */
163
+ sendState;
164
+ /** NCP is enabled to sleep, set by EZSP, not supported atm, always false */
165
+ ncpSleepEnabled;
166
+ /**
167
+ * Set when the ncp has indicated it has a pending callback by seting the callback flag in the frame control byte
168
+ * or (uart version only) by sending an an ASH_WAKE byte between frames.
169
+ */
170
+ ncpHasCallbacks;
171
+ /** Transmit buffers */
172
+ txPool;
173
+ txQueue;
174
+ reTxQueue;
175
+ txFree;
176
+ /** Receive buffers */
177
+ rxPool;
178
+ rxQueue;
179
+ rxFree;
180
+ constructor(options) {
181
+ super();
182
+ this.portOptions = options;
183
+ this.serialPort = null;
184
+ this.socketPort = null;
185
+ this.writer = null;
186
+ this.parser = null;
187
+ this.txPool = new Array(consts_1.TX_POOL_BUFFERS);
188
+ this.txQueue = new queues_1.EzspQueue();
189
+ this.reTxQueue = new queues_1.EzspQueue();
190
+ this.txFree = new queues_1.EzspFreeList();
191
+ this.rxPool = new Array(consts_1.EZSP_HOST_RX_POOL_SIZE);
192
+ this.rxQueue = new queues_1.EzspQueue();
193
+ this.rxFree = new queues_1.EzspFreeList();
194
+ }
195
+ /**
196
+ * Check if port is valid, open, and not closing.
197
+ */
198
+ get portOpen() {
199
+ if (this.closing) {
200
+ return false;
201
+ }
202
+ return this.serialPort != null ? this.serialPort.isOpen : !this.socketPort?.closed;
203
+ }
204
+ /**
205
+ * Get max wait time before response is considered timed out.
206
+ */
207
+ get responseTimeout() {
208
+ return consts_1.ASH_MAX_TIMEOUTS * CONFIG_ACK_TIME_MAX;
209
+ }
210
+ /**
211
+ * Indicates if the host is in the Connected state.
212
+ * If not, the host and NCP cannot exchange DATA frames.
213
+ * Note that this function does not actively confirm that communication with NCP is healthy, but simply returns its last known status.
214
+ *
215
+ * @returns
216
+ * - true - host and NCP can exchange DATA frames
217
+ * - false - host and NCP cannot now exchange DATA frames
218
+ */
219
+ get connected() {
220
+ return ((this.flags & Flag.CONNECTED) !== 0);
221
+ }
222
+ /**
223
+ * Has nothing to do...
224
+ */
225
+ get idle() {
226
+ return (!this.decodeInProgress // don't have a partial frame
227
+ // && (this.serial.readAvailable() === EzspStatus.NO_RX_DATA) // no rx data
228
+ && this.rxQueue.empty // no rx frames to process
229
+ && !this.ncpHasCallbacks // no pending callbacks
230
+ && (this.flags === Flag.CONNECTED) // no pending ACKs, NAKs, etc.
231
+ && (this.ackTx === this.frmRx) // do not need to send an ACK
232
+ && (this.ackRx === this.frmTx) // not waiting to receive an ACK
233
+ && (this.sendState === SendState.IDLE) // nothing being transmitted now
234
+ && this.txQueue.empty // nothing waiting to transmit
235
+ // && this.serial.outputIsIdle() // nothing in OS buffers or UART FIFO
236
+ );
237
+ }
238
+ /**
239
+ * Initialize ASH variables, timers and queues, but not the serial port
240
+ */
241
+ initVariables() {
242
+ this.closing = false;
243
+ this.serialPort = null;
244
+ this.socketPort = null;
245
+ this.writer = null;
246
+ this.parser = null;
247
+ this.txSHBuffer = Buffer.alloc(consts_1.SH_TX_BUFFER_LEN);
248
+ this.rxSHBuffer = Buffer.alloc(consts_1.SH_RX_BUFFER_LEN);
249
+ this.ackTimer = 0;
250
+ this.ackPeriod = 0;
251
+ this.nrTimer = 0;
252
+ this.flags = 0;
253
+ this.decodeInProgress = false;
254
+ this.ackRx = 0;
255
+ this.ackTx = 0;
256
+ this.frmTx = 0;
257
+ this.frmReTx = 0;
258
+ this.frmRx = 0;
259
+ this.frmReTxHead = 0;
260
+ this.timeouts = 0;
261
+ this.rxDataBuffer = null;
262
+ this.rxLen = 0;
263
+ // init to "start of frame" default
264
+ this.encodeCount = 0;
265
+ this.encodeState = 0;
266
+ this.encodeEscFlag = false;
267
+ this.encodeCrc = 0xFFFF;
268
+ this.txOffset = 0;
269
+ // init to "start of frame" default
270
+ this.decodeLen = 0;
271
+ this.decodeByte1 = 0;
272
+ this.decodeByte2 = 0;
273
+ this.decodeFlip = 0;
274
+ this.decodeCrc = 0xFFFF;
275
+ this.ncpError = enums_1.EzspStatus.NO_ERROR;
276
+ this.hostError = enums_1.EzspStatus.NO_ERROR;
277
+ this.sendState = SendState.IDLE;
278
+ this.ncpSleepEnabled = false;
279
+ this.ncpHasCallbacks = false;
280
+ this.stopAckTimer();
281
+ this.stopNrTimer();
282
+ this.initQueues();
283
+ this.counters = {
284
+ txData: 0,
285
+ txAllFrames: 0,
286
+ txDataFrames: 0,
287
+ txAckFrames: 0,
288
+ txNakFrames: 0,
289
+ txReDataFrames: 0,
290
+ // txN0Frames: 0,
291
+ txN1Frames: 0,
292
+ txCancelled: 0,
293
+ rxData: 0,
294
+ rxAllFrames: 0,
295
+ rxDataFrames: 0,
296
+ rxAckFrames: 0,
297
+ rxNakFrames: 0,
298
+ rxReDataFrames: 0,
299
+ // rxN0Frames: 0,
300
+ rxN1Frames: 0,
301
+ rxCancelled: 0,
302
+ rxCrcErrors: 0,
303
+ rxCommErrors: 0,
304
+ rxTooShort: 0,
305
+ rxTooLong: 0,
306
+ rxBadControl: 0,
307
+ rxBadLength: 0,
308
+ rxBadAckNumber: 0,
309
+ rxNoBuffer: 0,
310
+ rxDuplicates: 0,
311
+ rxOutOfSequence: 0,
312
+ rxAckTimeouts: 0,
313
+ };
314
+ }
315
+ /**
316
+ * Initializes all queues and free lists.
317
+ * All receive buffers are put into rxFree, and rxQueue is empty.
318
+ * All transmit buffers are put into txFree, and txQueue and reTxQueue are empty.
319
+ */
320
+ initQueues() {
321
+ this.txQueue.tail = null;
322
+ this.reTxQueue.tail = null;
323
+ this.txFree.link = null;
324
+ for (let i = 0; i < consts_1.TX_POOL_BUFFERS; i++) {
325
+ this.txFree.freeBuffer(this.txPool[i] = new queues_1.EzspBuffer());
326
+ }
327
+ this.rxQueue.tail = null;
328
+ this.rxFree.link = null;
329
+ for (let i = 0; i < consts_1.EZSP_HOST_RX_POOL_SIZE; i++) {
330
+ this.rxFree.freeBuffer(this.rxPool[i] = new queues_1.EzspBuffer());
331
+ }
332
+ }
333
+ async initPort() {
334
+ if (!socketPortUtils_1.default.isTcpPath(this.portOptions.path)) {
335
+ if (this.serialPort != null) {
336
+ this.serialPort.close();
337
+ }
338
+ const serialOpts = {
339
+ path: this.portOptions.path,
340
+ baudRate: typeof this.portOptions.baudRate === 'number' ? this.portOptions.baudRate : 115200,
341
+ rtscts: typeof this.portOptions.rtscts === 'boolean' ? this.portOptions.rtscts : false,
342
+ autoOpen: false,
343
+ parity: 'none',
344
+ stopBits: 1,
345
+ xon: false,
346
+ xoff: false,
347
+ };
348
+ // enable software flow control if RTS/CTS not enabled in config
349
+ if (!serialOpts.rtscts) {
350
+ debug(`RTS/CTS config is off, enabling software flow control.`);
351
+ serialOpts.xon = true;
352
+ serialOpts.xoff = true;
353
+ }
354
+ //@ts-expect-error Jest testing
355
+ if (this.portOptions.binding != null) {
356
+ //@ts-expect-error Jest testing
357
+ serialOpts.binding = this.portOptions.binding;
358
+ }
359
+ debug(`Opening SerialPort with ${JSON.stringify(serialOpts)}`);
360
+ this.serialPort = new serialPort_1.SerialPort(serialOpts);
361
+ this.writer = new writer_1.AshWriter({ highWaterMark: CONFIG_HIGHWATER_MARK });
362
+ this.writer.pipe(this.serialPort);
363
+ this.parser = new parser_1.AshParser({ readableHighWaterMark: CONFIG_HIGHWATER_MARK });
364
+ this.serialPort.pipe(this.parser);
365
+ this.parser.on('data', this.onFrame.bind(this));
366
+ try {
367
+ await this.serialPort.asyncOpen();
368
+ debug('Serialport opened');
369
+ this.serialPort.once('close', this.onPortClose.bind(this));
370
+ this.serialPort.on('error', this.onPortError.bind(this));
371
+ }
372
+ catch (error) {
373
+ await this.stop();
374
+ throw error;
375
+ }
376
+ }
377
+ else {
378
+ if (this.socketPort != null) {
379
+ this.socketPort.destroy();
380
+ }
381
+ const info = socketPortUtils_1.default.parseTcpPath(this.portOptions.path);
382
+ debug(`Opening TCP socket with ${info.host}:${info.port}`);
383
+ this.socketPort = new net_1.Socket();
384
+ this.socketPort.setNoDelay(true);
385
+ this.socketPort.setKeepAlive(true, 15000);
386
+ this.writer = new writer_1.AshWriter({ highWaterMark: CONFIG_HIGHWATER_MARK });
387
+ this.writer.pipe(this.socketPort);
388
+ this.parser = new parser_1.AshParser({ readableHighWaterMark: CONFIG_HIGHWATER_MARK });
389
+ this.socketPort.pipe(this.parser);
390
+ this.parser.on('data', this.onFrame.bind(this));
391
+ return new Promise((resolve, reject) => {
392
+ const openError = async (err) => {
393
+ await this.stop();
394
+ reject(err);
395
+ };
396
+ this.socketPort.on('connect', () => {
397
+ debug('Socket connected');
398
+ });
399
+ this.socketPort.on('ready', async () => {
400
+ debug('Socket ready');
401
+ this.socketPort.removeListener('error', openError);
402
+ this.socketPort.once('close', this.onPortClose.bind(this));
403
+ this.socketPort.on('error', this.onPortError.bind(this));
404
+ resolve();
405
+ });
406
+ this.socketPort.once('error', openError);
407
+ this.socketPort.connect(info.port, info.host);
408
+ });
409
+ }
410
+ }
411
+ /**
412
+ * Handle port closing
413
+ * @param err A boolean for Socket, an Error for serialport
414
+ */
415
+ async onPortClose(err) {
416
+ console.log(`Port closed. Error? ${err ?? 'no'}`);
417
+ }
418
+ /**
419
+ * Handle port error
420
+ * @param error
421
+ */
422
+ async onPortError(error) {
423
+ console.log(`Port error: ${error}`);
424
+ this.hostDisconnect(enums_1.EzspStatus.ERROR_SERIAL_INIT);
425
+ await this.stop();
426
+ }
427
+ /**
428
+ * Handle received frame from AshParser.
429
+ * @param buf
430
+ */
431
+ onFrame(buffer) {
432
+ const iCAN = buffer.lastIndexOf(enums_2.AshReservedByte.CANCEL); // should only be one, but just in case...
433
+ if (iCAN !== -1) {
434
+ // ignore the cancel before RSTACK
435
+ if (this.flags & Flag.CONNECTED) {
436
+ this.counters.rxCancelled += 1;
437
+ console.warn(`Frame(s) in progress cancelled. ${buffer.subarray(0, iCAN).toString('hex')}`);
438
+ }
439
+ // get rid of everything up to the CAN flag and start reading frame from there, no need to loop through bytes in vain
440
+ buffer = buffer.subarray(iCAN + 1);
441
+ }
442
+ const status = this.receiveFrame(buffer);
443
+ if (status === enums_1.EzspStatus.SUCCESS) {
444
+ // ?
445
+ }
446
+ else if ((status !== enums_1.EzspStatus.ASH_IN_PROGRESS) && (status !== enums_1.EzspStatus.NO_RX_DATA)) {
447
+ throw new Error(enums_1.EzspStatus[status]);
448
+ }
449
+ }
450
+ /**
451
+ * Initializes the ASH protocol, and waits until the NCP finishes rebooting, or a non-recoverable error occurs.
452
+ *
453
+ * @returns
454
+ * - EzspStatus.SUCCESS
455
+ * - EzspStatus.HOST_FATAL_ERROR
456
+ * - EzspStatus.ASH_NCP_FATAL_ERROR)
457
+ */
458
+ async start() {
459
+ if (this.closing || (this.flags & Flag.CONNECTED)) {
460
+ return enums_1.EzspStatus.ERROR_INVALID_CALL;
461
+ }
462
+ console.log(`======== ASH starting ========`);
463
+ if (this.serialPort != null) {
464
+ this.serialPort.flush(); // clear read/write buffers
465
+ }
466
+ else {
467
+ // XXX: Socket equiv?
468
+ }
469
+ this.sendExec();
470
+ // block til RSTACK or timeout
471
+ for (let i = 0; i < CONFIG_TIME_RST; i += CONFIG_TIME_RST_CHECK) {
472
+ if ((this.flags & Flag.CONNECTED)) {
473
+ console.log(`======== ASH started ========`);
474
+ return enums_1.EzspStatus.SUCCESS;
475
+ }
476
+ debug(`Waiting for RSTACK... ${i}/${CONFIG_TIME_RST}`);
477
+ await (0, utils_1.Wait)(CONFIG_TIME_RST_CHECK);
478
+ }
479
+ return enums_1.EzspStatus.HOST_FATAL_ERROR;
480
+ }
481
+ /**
482
+ * Stops the ASH protocol - flushes and closes the serial port, clears all queues, stops timers, etc.
483
+ */
484
+ async stop() {
485
+ this.closing = true;
486
+ this.printCounters();
487
+ if (this.serialPort?.isOpen) {
488
+ try {
489
+ await this.serialPort.asyncFlushAndClose();
490
+ debug(`Serial port closed.`);
491
+ }
492
+ catch (err) {
493
+ debug(`Failed to close serial port ${err}.`);
494
+ }
495
+ this.serialPort.removeAllListeners();
496
+ }
497
+ else if (this.socketPort != null && !this.socketPort.closed) {
498
+ this.socketPort.destroy();
499
+ this.socketPort.removeAllListeners();
500
+ debug(`Socket port closed.`);
501
+ }
502
+ this.initVariables();
503
+ console.log(`======== ASH stopped ========`);
504
+ }
505
+ /**
506
+ * Initializes the ASH serial port and (if enabled) resets the NCP.
507
+ * The method used to do the reset is specified by the the host configuration parameter resetMethod.
508
+ *
509
+ * When the reset method is sending a RST frame, the caller should retry NCP resets a few times if it fails.
510
+ *
511
+ * @returns
512
+ * - EzspStatus.SUCCESS
513
+ * - EzspStatus.HOST_FATAL_ERROR
514
+ */
515
+ async resetNcp() {
516
+ if (this.closing) {
517
+ return enums_1.EzspStatus.ERROR_INVALID_CALL;
518
+ }
519
+ console.log(`======== ASH NCP reset ========`);
520
+ this.initVariables();
521
+ let status;
522
+ // ask ncp to reset itself using RST frame
523
+ try {
524
+ await this.initPort();
525
+ this.flags = Flag.RST | Flag.CAN;
526
+ return enums_1.EzspStatus.SUCCESS;
527
+ }
528
+ catch (err) {
529
+ this.hostError = status;
530
+ return enums_1.EzspStatus.HOST_FATAL_ERROR;
531
+ }
532
+ }
533
+ /**
534
+ * Adds a DATA frame to the transmit queue to send to the NCP.
535
+ * Frames that are too long or too short will not be sent, and frames will not be added to the queue
536
+ * if the host is not in the Connected state, or the NCP is not ready to receive a DATA frame or if there
537
+ * is no room in the queue;
538
+ *
539
+ * @param len length of data field
540
+ * @param inBuf array containing the data to be sent
541
+ *
542
+ * @returns
543
+ * - EzspStatus.SUCCESS
544
+ * - EzspStatus.NO_TX_SPACE
545
+ * - EzspStatus.DATA_FRAME_TOO_SHORT
546
+ * - EzspStatus.DATA_FRAME_TOO_LONG
547
+ * - EzspStatus.NOT_CONNECTED
548
+ */
549
+ send(len, inBuf) {
550
+ // Check for errors that might have been detected
551
+ if (this.hostError !== enums_1.EzspStatus.NO_ERROR) {
552
+ return enums_1.EzspStatus.HOST_FATAL_ERROR;
553
+ }
554
+ if (this.ncpError !== enums_1.EzspStatus.NO_ERROR) {
555
+ return enums_1.EzspStatus.ASH_NCP_FATAL_ERROR;
556
+ }
557
+ // After verifying that the data field length is within bounds,
558
+ // copies data frame to a buffer and appends it to the transmit queue.
559
+ if (len < consts_1.ASH_MIN_DATA_FIELD_LEN) {
560
+ return enums_1.EzspStatus.DATA_FRAME_TOO_SHORT;
561
+ }
562
+ else if (len > consts_1.ASH_MAX_DATA_FIELD_LEN) {
563
+ return enums_1.EzspStatus.DATA_FRAME_TOO_LONG;
564
+ }
565
+ if (!(this.flags & Flag.CONNECTED)) {
566
+ return enums_1.EzspStatus.NOT_CONNECTED;
567
+ }
568
+ const buffer = this.txFree.allocBuffer();
569
+ if (buffer == null) {
570
+ return enums_1.EzspStatus.NO_TX_SPACE;
571
+ }
572
+ inBuf.copy(buffer.data, 0, 0, len);
573
+ buffer.len = len;
574
+ this.randomizeBuffer(buffer.data, buffer.len); // IN/OUT data
575
+ this.txQueue.addTail(buffer);
576
+ this.sendExec();
577
+ return enums_1.EzspStatus.SUCCESS;
578
+ }
579
+ /**
580
+ * Manages outgoing communication to the NCP, including DATA frames as well as the frames used for
581
+ * initialization and error detection and recovery.
582
+ */
583
+ sendExec() {
584
+ let outByte = 0x00;
585
+ let inByte = 0x00;
586
+ let len = 0;
587
+ let buffer = null;
588
+ // Check for received acknowledgement timer expiry
589
+ if (this.ackTimerHasExpired()) {
590
+ if (this.flags & Flag.CONNECTED) {
591
+ const expectedFrm = ((this.flags & Flag.RETX) ? this.frmReTx : this.frmTx);
592
+ if (this.ackRx !== expectedFrm) {
593
+ this.counters.rxAckTimeouts += 1;
594
+ this.adjustAckPeriod(true);
595
+ debug(`Timer expired waiting for ACK for ${expectedFrm}, current=${this.ackRx}`);
596
+ if (++this.timeouts >= consts_1.ASH_MAX_TIMEOUTS) {
597
+ this.hostDisconnect(enums_1.EzspStatus.ASH_ERROR_TIMEOUTS);
598
+ return;
599
+ }
600
+ this.startRetransmission();
601
+ }
602
+ else {
603
+ this.stopAckTimer();
604
+ }
605
+ }
606
+ else {
607
+ this.hostDisconnect(enums_1.EzspStatus.ASH_ERROR_RESET_FAIL);
608
+ }
609
+ }
610
+ while (this.writer.writeAvailable()) {
611
+ // Send ASH_CAN character immediately, ahead of any other transmit data
612
+ if (this.flags & Flag.CAN) {
613
+ if (this.sendState === SendState.IDLE) {
614
+ // sending RST or just woke NCP
615
+ this.writer.writeByte(enums_2.AshReservedByte.CANCEL);
616
+ }
617
+ else if (this.sendState === SendState.TX_DATA) {
618
+ // cancel frame in progress
619
+ this.counters.txCancelled += 1;
620
+ this.writer.writeByte(enums_2.AshReservedByte.CANCEL);
621
+ this.stopAckTimer();
622
+ this.sendState = SendState.IDLE;
623
+ }
624
+ this.flags &= ~Flag.CAN;
625
+ continue;
626
+ }
627
+ switch (this.sendState) {
628
+ case SendState.IDLE:
629
+ // In between frames - do some housekeeping and decide what to send next
630
+ // If retransmitting, set the next frame to send to the last ackNum
631
+ // received, then check to see if retransmission is now complete.
632
+ if (this.flags & Flag.RETX) {
633
+ if ((0, math_1.withinRange)(this.frmReTx, this.ackRx, this.frmTx)) {
634
+ this.frmReTx = this.ackRx;
635
+ }
636
+ if (this.frmReTx === this.frmTx) {
637
+ this.flags &= ~Flag.RETX;
638
+ this.scrubReTxQueue();
639
+ }
640
+ }
641
+ // restrain ncp if needed
642
+ this.dataFrameFlowControl();
643
+ // See if a short frame is flagged to be sent
644
+ // The order of the tests below - RST, NAK and ACK -
645
+ // sets the relative priority of sending these frame types.
646
+ if (this.flags & Flag.RST) {
647
+ this.txSHBuffer[0] = enums_2.AshFrameType.RST;
648
+ this.setAndStartAckTimer(CONFIG_TIME_RST);
649
+ len = 1;
650
+ this.flags &= ~(Flag.RST | Flag.NAK | Flag.ACK);
651
+ this.sendState = SendState.SHFRAME;
652
+ debug(`---> [FRAME type=RST]`);
653
+ }
654
+ else if (this.flags & (Flag.NAK | Flag.ACK)) {
655
+ if (this.flags & Flag.NAK) {
656
+ this.txSHBuffer[0] = enums_2.AshFrameType.NAK + (this.frmRx << consts_1.ASH_ACKNUM_BIT);
657
+ this.flags &= ~(Flag.NRTX | Flag.NAK | Flag.ACK);
658
+ debug(`---> [FRAME type=NAK frmRx=${this.frmRx}]`);
659
+ }
660
+ else {
661
+ this.txSHBuffer[0] = enums_2.AshFrameType.ACK + (this.frmRx << consts_1.ASH_ACKNUM_BIT);
662
+ this.flags &= ~(Flag.NRTX | Flag.ACK);
663
+ debug(`---> [FRAME type=ACK frmRx=${this.frmRx}]`);
664
+ }
665
+ if (this.flags & Flag.NR) {
666
+ this.txSHBuffer[0] |= consts_1.ASH_NFLAG_MASK;
667
+ this.flags |= Flag.NRTX;
668
+ this.startNrTimer();
669
+ }
670
+ this.ackTx = this.frmRx;
671
+ len = 1;
672
+ this.sendState = SendState.SHFRAME;
673
+ }
674
+ else if (this.flags & Flag.RETX) {
675
+ // Retransmitting DATA frames for error recovery
676
+ buffer = this.reTxQueue.getNthEntry((0, math_1.mod8)(this.frmTx - this.frmReTx));
677
+ len = buffer.len + 1;
678
+ this.txSHBuffer[0] = enums_2.AshFrameType.DATA | (this.frmReTx << consts_1.ASH_FRMNUM_BIT) | (this.frmRx << consts_1.ASH_ACKNUM_BIT) | consts_1.ASH_RFLAG_MASK;
679
+ this.sendState = SendState.RETX_DATA;
680
+ debug(`---> [FRAME type=DATA_RETX frmReTx=${this.frmReTx} frmRx=${this.frmRx}]`);
681
+ }
682
+ else if (this.ackTx != this.frmRx) {
683
+ // An ACK should be generated
684
+ this.flags |= Flag.ACK;
685
+ break;
686
+ }
687
+ else if (!this.txQueue.empty && (0, math_1.withinRange)(this.ackRx, this.frmTx, (this.ackRx + CONFIG_TX_K - 1))) {
688
+ // Send a DATA frame if ready
689
+ buffer = this.txQueue.head;
690
+ len = buffer.len + 1;
691
+ this.counters.txData += (len - 1);
692
+ this.txSHBuffer[0] = enums_2.AshFrameType.DATA | (this.frmTx << consts_1.ASH_FRMNUM_BIT) | (this.frmRx << consts_1.ASH_ACKNUM_BIT);
693
+ this.sendState = SendState.TX_DATA;
694
+ debug(`---> [FRAME type=DATA frmTx=${this.frmTx} frmRx=${this.frmRx}]`);
695
+ }
696
+ else {
697
+ // Otherwise there's nothing to send
698
+ this.writer.writeFlush();
699
+ return;
700
+ }
701
+ this.countFrame(true);
702
+ // Start frame - encodeByte() is inited by a non-zero length argument
703
+ outByte = this.encodeByte(len, this.txSHBuffer[0]);
704
+ this.writer.writeByte(outByte);
705
+ break;
706
+ case SendState.SHFRAME:
707
+ // sending short frame
708
+ if (this.txOffset !== 0xFF) {
709
+ inByte = this.txSHBuffer[this.txOffset];
710
+ outByte = this.encodeByte(0, inByte);
711
+ this.writer.writeByte(outByte);
712
+ }
713
+ else {
714
+ this.sendState = SendState.IDLE;
715
+ }
716
+ break;
717
+ case SendState.TX_DATA:
718
+ case SendState.RETX_DATA:
719
+ // sending OR resending data frame
720
+ if (this.txOffset !== 0xFF) {
721
+ inByte = this.txOffset ? buffer.data[this.txOffset - 1] : this.txSHBuffer[0];
722
+ outByte = this.encodeByte(0, inByte);
723
+ this.writer.writeByte(outByte);
724
+ }
725
+ else {
726
+ if (this.sendState === SendState.TX_DATA) {
727
+ this.frmTx = (0, math_1.inc8)(this.frmTx);
728
+ buffer = this.txQueue.removeHead();
729
+ this.reTxQueue.addTail(buffer);
730
+ }
731
+ else {
732
+ this.frmReTx = (0, math_1.inc8)(this.frmReTx);
733
+ }
734
+ if (this.ackTimerIsNotRunning()) {
735
+ this.startAckTimer();
736
+ }
737
+ this.ackTx = this.frmRx;
738
+ this.sendState = SendState.IDLE;
739
+ }
740
+ break;
741
+ }
742
+ }
743
+ this.writer.writeFlush();
744
+ }
745
+ /**
746
+ * Retrieve a frame and accept, reTx, reject, fail based on type & validity in current state.
747
+ * @returns
748
+ * - EzspStatus.SUCCESS On valid RSTACK or valid DATA frame.
749
+ * - EzspStatus.ASH_IN_PROGRESS
750
+ * - EzspStatus.NO_RX_DATA
751
+ * - EzspStatus.NO_RX_SPACE
752
+ * - EzspStatus.HOST_FATAL_ERROR
753
+ * - EzspStatus.ASH_NCP_FATAL_ERROR
754
+ */
755
+ receiveFrame(buffer) {
756
+ // Check for errors that might have been detected
757
+ if (this.hostError !== enums_1.EzspStatus.NO_ERROR) {
758
+ return enums_1.EzspStatus.HOST_FATAL_ERROR;
759
+ }
760
+ if (this.ncpError !== enums_1.EzspStatus.NO_ERROR) {
761
+ return enums_1.EzspStatus.ASH_NCP_FATAL_ERROR;
762
+ }
763
+ let ackNum = 0;
764
+ let frmNum = 0;
765
+ let frameType = enums_2.AshFrameType.INVALID;
766
+ // Read data from serial port and assemble a frame until complete, aborted
767
+ // due to an error, cancelled, or there is no more serial data available.
768
+ const status = this.readFrame(buffer);
769
+ switch (status) {
770
+ case enums_1.EzspStatus.SUCCESS:
771
+ break;
772
+ case enums_1.EzspStatus.ASH_IN_PROGRESS:
773
+ // should have a complete frame by now, if not, don't process further
774
+ return enums_1.EzspStatus.NO_RX_DATA;
775
+ case enums_1.EzspStatus.ASH_CANCELLED:
776
+ // should have been taken out in onFrame
777
+ return this.hostDisconnect(status);
778
+ case enums_1.EzspStatus.ASH_BAD_CRC:
779
+ this.counters.rxCrcErrors += 1;
780
+ this.rejectFrame();
781
+ console.error(`Received frame with CRC error`);
782
+ return enums_1.EzspStatus.NO_RX_DATA;
783
+ case enums_1.EzspStatus.ASH_COMM_ERROR:
784
+ this.counters.rxCommErrors += 1;
785
+ this.rejectFrame();
786
+ console.error(`Received frame with comm error`);
787
+ return enums_1.EzspStatus.NO_RX_DATA;
788
+ case enums_1.EzspStatus.ASH_TOO_SHORT:
789
+ this.counters.rxTooShort += 1;
790
+ this.rejectFrame();
791
+ console.error(`Received frame shorter than minimum`);
792
+ return enums_1.EzspStatus.NO_RX_DATA;
793
+ case enums_1.EzspStatus.ASH_TOO_LONG:
794
+ this.counters.rxTooLong += 1;
795
+ this.rejectFrame();
796
+ console.error(`Received frame longer than maximum`);
797
+ return enums_1.EzspStatus.NO_RX_DATA;
798
+ case enums_1.EzspStatus.ASH_ERROR_XON_XOFF:
799
+ return this.hostDisconnect(status);
800
+ default:
801
+ throw new Error(`Unhandled error while receiving frame.`);
802
+ }
803
+ // Got a complete frame - validate its control and length.
804
+ // On an error the type returned will be TYPE_INVALID.
805
+ frameType = this.getFrameType(this.rxSHBuffer[0], this.rxLen);
806
+ // Free buffer allocated for a received frame if:
807
+ // DATA frame, and out of order
808
+ // DATA frame, and not in the CONNECTED state
809
+ // not a DATA frame
810
+ if (frameType === enums_2.AshFrameType.DATA) {
811
+ if (!(this.flags & Flag.CONNECTED) || (ashGetFrmNum(this.rxSHBuffer[0]) !== this.frmRx)) {
812
+ this.freeNonNullRxBuffer();
813
+ }
814
+ }
815
+ else {
816
+ this.freeNonNullRxBuffer();
817
+ }
818
+ const frameTypeStr = enums_2.AshFrameType[frameType];
819
+ debug(`<--- [FRAME type=${frameTypeStr}]`);
820
+ this.countFrame(false);
821
+ // Process frames received while not in the connected state -
822
+ // ignore everything except RSTACK and ERROR frames
823
+ if (!(this.flags & Flag.CONNECTED)) {
824
+ if (frameType === enums_2.AshFrameType.RSTACK) {
825
+ // RSTACK frames have the ncp ASH version in the first data field byte,
826
+ // and the reset reason in the second byte
827
+ if (this.rxSHBuffer[1] !== consts_1.ASH_VERSION) {
828
+ return this.hostDisconnect(enums_1.EzspStatus.ASH_ERROR_VERSION);
829
+ }
830
+ // Ignore a RSTACK if the reset reason doesn't match our reset method
831
+ if (this.rxSHBuffer[2] !== enums_2.NcpFailedCode.RESET_SOFTWARE) {
832
+ return enums_1.EzspStatus.ASH_IN_PROGRESS;
833
+ }
834
+ this.ncpError = enums_1.EzspStatus.NO_ERROR;
835
+ this.stopAckTimer();
836
+ this.timeouts = 0;
837
+ this.setAckPeriod(CONFIG_ACK_TIME_INIT);
838
+ this.flags = Flag.CONNECTED | Flag.ACK;
839
+ console.log(`======== ASH connected ========`);
840
+ return enums_1.EzspStatus.SUCCESS;
841
+ }
842
+ else if (frameType === enums_2.AshFrameType.ERROR) {
843
+ return this.ncpDisconnect(this.rxSHBuffer[2]);
844
+ }
845
+ return enums_1.EzspStatus.ASH_IN_PROGRESS;
846
+ }
847
+ // Connected - process the ackNum in ACK, NAK and DATA frames
848
+ if ((frameType === enums_2.AshFrameType.DATA) || (frameType === enums_2.AshFrameType.ACK) || (frameType === enums_2.AshFrameType.NAK)) {
849
+ ackNum = ashGetACKNum(this.rxSHBuffer[0]);
850
+ debug(`<--- [FRAME type=${frameTypeStr} ackNum=${ackNum}]`);
851
+ if (!(0, math_1.withinRange)(this.ackRx, ackNum, this.frmTx)) {
852
+ this.counters.rxBadAckNumber += 1;
853
+ debug(`<-x- [FRAME type=${frameTypeStr} ackNum=${ackNum}] Invalid ACK num; not within <${this.ackRx}-${this.frmTx}>`);
854
+ frameType = enums_2.AshFrameType.INVALID;
855
+ }
856
+ else if (ackNum !== this.ackRx) {
857
+ // new frame(s) ACK'ed?
858
+ this.ackRx = ackNum;
859
+ this.timeouts = 0;
860
+ if (this.flags & Flag.RETX) {
861
+ // start timer if unACK'ed frames
862
+ this.stopAckTimer();
863
+ if (ackNum !== this.frmReTx) {
864
+ this.startAckTimer();
865
+ }
866
+ }
867
+ else {
868
+ this.adjustAckPeriod(false); // factor ACK time into period
869
+ if (ackNum !== this.frmTx) {
870
+ // if more unACK'ed frames,
871
+ this.startAckTimer(); // then restart ACK timer
872
+ }
873
+ this.scrubReTxQueue(); // free buffer(s) in ReTx queue
874
+ }
875
+ }
876
+ }
877
+ // Process frames received while connected
878
+ switch (frameType) {
879
+ case enums_2.AshFrameType.DATA:
880
+ frmNum = ashGetFrmNum(this.rxSHBuffer[0]);
881
+ const frameStr = `[FRAME type=${frameTypeStr} ackNum=${ackNum} frmNum=${frmNum}]`;
882
+ if (frmNum === this.frmRx) {
883
+ // is frame in sequence?
884
+ if (this.rxDataBuffer == null) {
885
+ // valid frame but no memory?
886
+ this.counters.rxNoBuffer += 1;
887
+ debug(`<-x- ${frameStr} No buffer available`);
888
+ this.rejectFrame();
889
+ return enums_1.EzspStatus.NO_RX_SPACE;
890
+ }
891
+ if (this.rxSHBuffer[0] & consts_1.ASH_RFLAG_MASK) {
892
+ // if retransmitted, force ACK
893
+ this.flags |= Flag.ACK;
894
+ }
895
+ this.flags &= ~(Flag.REJ | Flag.NAK); // clear the REJ condition
896
+ this.frmRx = (0, math_1.inc8)(this.frmRx);
897
+ this.randomizeBuffer(this.rxDataBuffer.data, this.rxDataBuffer.len); // IN/OUT data
898
+ this.rxQueue.addTail(this.rxDataBuffer); // add frame to receive queue
899
+ debug(`<--- ${frameStr} Added to rxQueue`);
900
+ this.counters.rxData += this.rxDataBuffer.len;
901
+ setImmediate(() => {
902
+ this.emit(AshEvents.frame);
903
+ });
904
+ return enums_1.EzspStatus.SUCCESS;
905
+ }
906
+ else {
907
+ // frame is out of sequence
908
+ if (this.rxSHBuffer[0] & consts_1.ASH_RFLAG_MASK) {
909
+ // if retransmitted, force ACK
910
+ this.counters.rxDuplicates += 1;
911
+ this.flags |= Flag.ACK;
912
+ }
913
+ else {
914
+ // 1st OOS? then set REJ, send NAK
915
+ if ((this.flags & Flag.REJ) === 0) {
916
+ this.counters.rxOutOfSequence += 1;
917
+ debug(`<-x- ${frameStr} Out of sequence: expected ${this.frmRx}; got ${frmNum}.`);
918
+ }
919
+ this.rejectFrame();
920
+ }
921
+ }
922
+ break;
923
+ case enums_2.AshFrameType.ACK:
924
+ // already fully processed
925
+ break;
926
+ case enums_2.AshFrameType.NAK:
927
+ // start retransmission if needed
928
+ this.startRetransmission();
929
+ break;
930
+ case enums_2.AshFrameType.RSTACK:
931
+ // unexpected ncp reset
932
+ this.ncpError = this.rxSHBuffer[2];
933
+ return this.hostDisconnect(enums_1.EzspStatus.ASH_ERROR_NCP_RESET);
934
+ case enums_2.AshFrameType.ERROR:
935
+ // ncp error
936
+ return this.ncpDisconnect(this.rxSHBuffer[2]);
937
+ case enums_2.AshFrameType.INVALID:
938
+ // reject invalid frames
939
+ debug(`<-x- [FRAME type=${frameTypeStr}] Rejecting. ${this.rxSHBuffer.toString('hex')}`);
940
+ this.rejectFrame();
941
+ break;
942
+ }
943
+ return enums_1.EzspStatus.ASH_IN_PROGRESS;
944
+ }
945
+ /**
946
+ * If the last control byte received was a DATA control, and we are connected and not already in the reject condition,
947
+ * then send a NAK and set the reject condition.
948
+ */
949
+ rejectFrame() {
950
+ if (((this.rxSHBuffer[0] & consts_1.ASH_DFRAME_MASK) === enums_2.AshFrameType.DATA)
951
+ && ((this.flags & (Flag.REJ | Flag.CONNECTED)) === Flag.CONNECTED)) {
952
+ this.flags |= (Flag.REJ | Flag.NAK);
953
+ }
954
+ }
955
+ /**
956
+ * Retrieve and process serial bytes.
957
+ * @returns
958
+ */
959
+ readFrame(buffer) {
960
+ let status;
961
+ let index = 0;
962
+ // let inByte: number = 0x00;
963
+ let outByte = 0x00;
964
+ if (!this.decodeInProgress) {
965
+ this.rxLen = 0;
966
+ this.rxDataBuffer = null;
967
+ }
968
+ for (const inByte of buffer) {
969
+ // 0xFF byte signals a callback is pending when between frames in synchronous (polled) callback mode.
970
+ if (!this.decodeInProgress && (inByte === consts_1.ASH_WAKE)) {
971
+ if (this.ncpSleepEnabled) {
972
+ this.ncpHasCallbacks = true;
973
+ }
974
+ status = enums_1.EzspStatus.ASH_IN_PROGRESS;
975
+ continue;
976
+ }
977
+ // Decode next input byte - note that many input bytes do not produce
978
+ // an output byte. Return on any error in decoding.
979
+ index = this.rxLen;
980
+ [status, outByte, this.rxLen] = this.decodeByte(inByte, outByte, this.rxLen);
981
+ // discard an invalid frame
982
+ if ((status !== enums_1.EzspStatus.ASH_IN_PROGRESS) && (status !== enums_1.EzspStatus.SUCCESS)) {
983
+ this.freeNonNullRxBuffer();
984
+ break;
985
+ }
986
+ // if input byte produced an output byte
987
+ if (this.rxLen !== index) {
988
+ if (this.rxLen <= consts_1.SH_RX_BUFFER_LEN) {
989
+ // if a short frame, return in rxBuffer
990
+ this.rxSHBuffer[index] = outByte;
991
+ }
992
+ else {
993
+ // if a longer DATA frame, allocate an EzspBuffer for it.
994
+ // (Note the control byte is always returned in shRxBuffer[0].
995
+ // Even if no buffer can be allocated, the control's ackNum must be processed.)
996
+ if (this.rxLen === (consts_1.SH_RX_BUFFER_LEN + 1)) {
997
+ // alloc buffer, copy prior data
998
+ this.rxDataBuffer = this.rxFree.allocBuffer();
999
+ if (this.rxDataBuffer !== null) {
1000
+ // const len = SH_RX_BUFFER_LEN - 1;
1001
+ // (void) memcpy(this.rxDataBuffer.data, this.shRxBuffer + 1, SH_RX_BUFFER_LEN - 1);
1002
+ this.rxSHBuffer.copy(this.rxDataBuffer.data, 0, 1, consts_1.SH_RX_BUFFER_LEN);
1003
+ this.rxDataBuffer.len = consts_1.SH_RX_BUFFER_LEN - 1;
1004
+ }
1005
+ }
1006
+ if (this.rxDataBuffer !== null) {
1007
+ // copy next byte to buffer
1008
+ this.rxDataBuffer.data[index - 1] = outByte; // -1 since control is omitted
1009
+ this.rxDataBuffer.len = index;
1010
+ }
1011
+ }
1012
+ }
1013
+ if (status !== enums_1.EzspStatus.ASH_IN_PROGRESS) {
1014
+ break;
1015
+ }
1016
+ }
1017
+ return status;
1018
+ }
1019
+ /**
1020
+ *
1021
+ */
1022
+ freeNonNullRxBuffer() {
1023
+ if (this.rxDataBuffer !== null) {
1024
+ this.rxFree.freeBuffer(this.rxDataBuffer);
1025
+ this.rxDataBuffer = null;
1026
+ }
1027
+ }
1028
+ /**
1029
+ *
1030
+ */
1031
+ scrubReTxQueue() {
1032
+ let buffer;
1033
+ while (this.ackRx !== this.frmReTxHead) {
1034
+ buffer = this.reTxQueue.removeHead();
1035
+ this.txFree.freeBuffer(buffer);
1036
+ this.frmReTxHead = (0, math_1.inc8)(this.frmReTxHead);
1037
+ }
1038
+ }
1039
+ /**
1040
+ * If not already retransmitting, and there are unacked frames, start retransmitting after the last frame that was acked.
1041
+ */
1042
+ startRetransmission() {
1043
+ if (!(this.flags & Flag.RETX) && (this.ackRx != this.frmTx)) {
1044
+ this.stopAckTimer();
1045
+ this.frmReTx = this.ackRx;
1046
+ this.flags |= (Flag.RETX | Flag.CAN);
1047
+ }
1048
+ }
1049
+ /**
1050
+ * Check free rx buffers to see whether able to receive DATA frames: set or clear NR flag appropriately.
1051
+ * Inform ncp of our status using the nFlag in ACKs and NAKs.
1052
+ * Note that not ready status must be refreshed if it persists beyond a maximum time limit.
1053
+ */
1054
+ dataFrameFlowControl() {
1055
+ if (this.flags & Flag.CONNECTED) {
1056
+ // Set/clear NR flag based on the number of buffers free
1057
+ if (this.rxFree.length < CONFIG_NR_LOW_LIMIT) {
1058
+ this.flags |= Flag.NR;
1059
+ debug(`NOT READY - Signaling NCP`);
1060
+ }
1061
+ else if (this.rxFree.length > CONFIG_NR_HIGH_LIMIT) {
1062
+ this.flags &= ~Flag.NR;
1063
+ this.stopNrTimer(); // needed??
1064
+ // debug(`READY - Signaling NCP`);// spams-a-lot
1065
+ }
1066
+ // Force an ACK (or possibly NAK) if we need to send an updated nFlag
1067
+ // due to either a changed NR status or to refresh a set nFlag
1068
+ if (this.flags & Flag.NR) {
1069
+ if (!(this.flags & Flag.NRTX) || this.nrTimerHasExpired()) {
1070
+ this.flags |= Flag.ACK;
1071
+ this.startNrTimer();
1072
+ }
1073
+ }
1074
+ else {
1075
+ this.nrTimerHasExpired(); // ensure timer checked often
1076
+ if (this.flags & Flag.NRTX) {
1077
+ this.flags |= Flag.ACK;
1078
+ this.stopNrTimer(); // needed???
1079
+ }
1080
+ }
1081
+ }
1082
+ else {
1083
+ this.stopNrTimer();
1084
+ this.flags &= ~(Flag.NRTX | Flag.NR);
1085
+ }
1086
+ }
1087
+ /**
1088
+ * Sets a fatal error state at the Host level.
1089
+ * @param error
1090
+ * @returns EzspStatus.HOST_FATAL_ERROR
1091
+ */
1092
+ hostDisconnect(error) {
1093
+ this.flags = 0;
1094
+ this.hostError = error;
1095
+ console.error(`ASH disconnected: ${enums_1.EzspStatus[error]} | NCP status: ${enums_1.EzspStatus[this.ncpError]}`);
1096
+ this.emit(AshEvents.hostError, error);
1097
+ return enums_1.EzspStatus.HOST_FATAL_ERROR;
1098
+ }
1099
+ /**
1100
+ * Sets a fatal error state at the NCP level. Will require a reset.
1101
+ * @param error
1102
+ * @returns EzspStatus.ASH_NCP_FATAL_ERROR
1103
+ */
1104
+ ncpDisconnect(error) {
1105
+ this.flags = 0;
1106
+ this.ncpError = error;
1107
+ console.error(`ASH disconnected: ${enums_1.EzspStatus[error]} | NCP status: ${enums_1.EzspStatus[this.ncpError]}`);
1108
+ this.emit(AshEvents.ncpError, error);
1109
+ return enums_1.EzspStatus.ASH_NCP_FATAL_ERROR;
1110
+ }
1111
+ /**
1112
+ * Same as randomizeArray(0, buffer, len).
1113
+ * Returns buffer as-is if randomize is OFF.
1114
+ * @param buffer IN/OUT
1115
+ * @param len
1116
+ */
1117
+ randomizeBuffer(buffer, len) {
1118
+ // If enabled, exclusive-OR buffer data with a pseudo-random sequence
1119
+ if (CONFIG_RANDOMIZE) {
1120
+ this.randomizeArray(0, buffer, len); // zero inits the random sequence
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Randomizes array contents by XORing with an 8-bit pseudo random sequence.
1125
+ * This reduces the likelihood that byte-stuffing will greatly increase the size of the payload.
1126
+ * (This could happen if a DATA frame contained repeated instances of the same reserved byte value.)
1127
+ *
1128
+ * @param seed zero initializes the random sequence a non-zero value continues from a previous invocation
1129
+ * @param buf IN/OUT pointer to the array whose contents will be randomized
1130
+ * @param len number of bytes in the array to modify
1131
+ * @returns last value of the sequence.
1132
+ * If a buffer is processed in two or more chunks, as with linked buffers,
1133
+ * this value should be passed back as the value of the seed argument
1134
+ */
1135
+ randomizeArray(seed, buf, len) {
1136
+ let outIdx = 0;
1137
+ if (seed === 0) {
1138
+ seed = consts_1.LFSR_SEED;
1139
+ }
1140
+ while (len--) {
1141
+ // *buf++ ^= seed;
1142
+ buf[outIdx++] ^= seed;
1143
+ seed = (seed & 1) ? ((seed >> 1) ^ consts_1.LFSR_POLY) : (seed >> 1);
1144
+ }
1145
+ return seed;
1146
+ }
1147
+ /**
1148
+ * Get the frame type from the control byte and validate it against the frame length.
1149
+ * @param control
1150
+ * @param len Frame length
1151
+ * @returns AshFrameType.INVALID if bad control/length otherwise the frame type.
1152
+ */
1153
+ getFrameType(control, len) {
1154
+ if (control === enums_2.AshFrameType.RSTACK) {
1155
+ if (len === consts_1.ASH_FRAME_LEN_RSTACK) {
1156
+ return enums_2.AshFrameType.RSTACK;
1157
+ }
1158
+ }
1159
+ else if (control === enums_2.AshFrameType.ERROR) {
1160
+ if (len === consts_1.ASH_FRAME_LEN_ERROR) {
1161
+ return enums_2.AshFrameType.ERROR;
1162
+ }
1163
+ }
1164
+ else if ((control & consts_1.ASH_DFRAME_MASK) === enums_2.AshFrameType.DATA) {
1165
+ if (len >= consts_1.ASH_FRAME_LEN_DATA_MIN) {
1166
+ return enums_2.AshFrameType.DATA;
1167
+ }
1168
+ }
1169
+ else if ((control & consts_1.ASH_SHFRAME_MASK) === enums_2.AshFrameType.ACK) {
1170
+ if (len === consts_1.ASH_FRAME_LEN_ACK) {
1171
+ return enums_2.AshFrameType.ACK;
1172
+ }
1173
+ }
1174
+ else if ((control & consts_1.ASH_SHFRAME_MASK) === enums_2.AshFrameType.NAK) {
1175
+ if (len === consts_1.ASH_FRAME_LEN_NAK) {
1176
+ return enums_2.AshFrameType.NAK;
1177
+ }
1178
+ }
1179
+ else {
1180
+ this.counters.rxBadControl += 1;
1181
+ debug(`Frame illegal control ${control}.`); // EzspStatus.ASH_BAD_CONTROL
1182
+ return enums_2.AshFrameType.INVALID;
1183
+ }
1184
+ this.counters.rxBadLength += 1;
1185
+ debug(`Frame illegal length ${len} for control ${control}.`); // EzspStatus.ASH_BAD_LENGTH
1186
+ return enums_2.AshFrameType.INVALID;
1187
+ }
1188
+ /**
1189
+ * Encode byte for sending.
1190
+ * @param len Start a new frame if non-zero
1191
+ * @param byte
1192
+ * @returns outByte
1193
+ */
1194
+ encodeByte(len, byte) {
1195
+ // start a new frame if len is non-zero
1196
+ if (len) {
1197
+ this.encodeCount = len;
1198
+ this.txOffset = 0;
1199
+ this.encodeState = 0;
1200
+ this.encodeEscFlag = false;
1201
+ this.encodeCrc = 0xFFFF;
1202
+ }
1203
+ // was an escape last time?
1204
+ if (this.encodeEscFlag) {
1205
+ this.encodeEscFlag = false;
1206
+ // send data byte with bit flipped
1207
+ return this.encodeFlip;
1208
+ }
1209
+ // control and data field bytes
1210
+ if (this.encodeState === 0) {
1211
+ this.encodeCrc = (0, math_1.halCommonCrc16)(byte, this.encodeCrc);
1212
+ if (--this.encodeCount === 0) {
1213
+ this.encodeState = 1;
1214
+ }
1215
+ else {
1216
+ ++this.txOffset;
1217
+ }
1218
+ return this.encodeStuffByte(byte);
1219
+ }
1220
+ else if (this.encodeState === 1) {
1221
+ // CRC high byte
1222
+ this.encodeState = 2;
1223
+ return this.encodeStuffByte(this.encodeCrc >> 8);
1224
+ }
1225
+ else if (this.encodeState === 2) {
1226
+ // CRC low byte
1227
+ this.encodeState = 3;
1228
+ return this.encodeStuffByte(this.encodeCrc & 0xFF);
1229
+ }
1230
+ this.txOffset = 0xFF;
1231
+ return enums_2.AshReservedByte.FLAG;
1232
+ }
1233
+ /**
1234
+ * Stuff byte as defined by ASH protocol.
1235
+ * @param byte
1236
+ * @returns
1237
+ */
1238
+ encodeStuffByte(byte) {
1239
+ if (enums_2.AshReservedByte[byte] != null) {
1240
+ // is special byte
1241
+ this.encodeEscFlag = true;
1242
+ this.encodeFlip = byte ^ consts_1.ASH_FLIP;
1243
+ return enums_2.AshReservedByte.ESCAPE;
1244
+ }
1245
+ else {
1246
+ return byte;
1247
+ }
1248
+ }
1249
+ /**
1250
+ * Decode received byte.
1251
+ * @param byte
1252
+ * @param inByte IN/OUT
1253
+ * @param inLen IN/OUT
1254
+ * @returns [EzspStatus, outByte, outLen]
1255
+ * - EzspStatus.ASH_IN_PROGRESS
1256
+ * - EzspStatus.ASH_COMM_ERROR
1257
+ * - EzspStatus.ASH_BAD_CRC
1258
+ * - EzspStatus.ASH_TOO_SHORT
1259
+ * - EzspStatus.ASH_TOO_LONG
1260
+ * - EzspStatus.SUCCESS
1261
+ * - EzspStatus.ASH_CANCELLED
1262
+ * - EzspStatus.ASH_ERROR_XON_XOFF
1263
+ */
1264
+ decodeByte(byte, inByte, inLen) {
1265
+ let status = enums_1.EzspStatus.ASH_IN_PROGRESS;
1266
+ if (!this.decodeInProgress) {
1267
+ this.decodeLen = 0;
1268
+ this.decodeByte1 = 0;
1269
+ this.decodeByte2 = 0;
1270
+ this.decodeFlip = 0;
1271
+ this.decodeCrc = 0xFFFF;
1272
+ }
1273
+ switch (byte) {
1274
+ case enums_2.AshReservedByte.FLAG:
1275
+ // flag byte (frame delimiter)
1276
+ if (this.decodeLen === 0) {
1277
+ // if no frame data, not end flag, so ignore it
1278
+ this.decodeFlip = 0; // ignore isolated data escape between flags
1279
+ break;
1280
+ }
1281
+ else if (this.decodeLen === 0xFF) {
1282
+ status = enums_1.EzspStatus.ASH_COMM_ERROR;
1283
+ }
1284
+ else if (this.decodeCrc !== ((this.decodeByte2 << 8) + this.decodeByte1)) {
1285
+ status = enums_1.EzspStatus.ASH_BAD_CRC;
1286
+ }
1287
+ else if (this.decodeLen < consts_1.ASH_MIN_FRAME_WITH_CRC_LEN) {
1288
+ status = enums_1.EzspStatus.ASH_TOO_SHORT;
1289
+ }
1290
+ else if (this.decodeLen > consts_1.ASH_MAX_FRAME_WITH_CRC_LEN) {
1291
+ status = enums_1.EzspStatus.ASH_TOO_LONG;
1292
+ }
1293
+ else {
1294
+ status = enums_1.EzspStatus.SUCCESS;
1295
+ }
1296
+ break;
1297
+ case enums_2.AshReservedByte.ESCAPE:
1298
+ // byte stuffing escape byte
1299
+ this.decodeFlip = consts_1.ASH_FLIP;
1300
+ break;
1301
+ case enums_2.AshReservedByte.CANCEL:
1302
+ // cancel frame without an error
1303
+ status = enums_1.EzspStatus.ASH_CANCELLED;
1304
+ break;
1305
+ case enums_2.AshReservedByte.SUBSTITUTE:
1306
+ // discard remainder of frame
1307
+ this.decodeLen = 0xFF; // special value flags low level comm error
1308
+ break;
1309
+ case enums_2.AshReservedByte.XON:
1310
+ case enums_2.AshReservedByte.XOFF:
1311
+ // If host is using RTS/CTS, ignore any XON/XOFFs received from the NCP.
1312
+ // If using XON/XOFF, the host driver must remove them from the input stream.
1313
+ // If it doesn't, it probably means the driver isn't setup for XON/XOFF,
1314
+ // so issue an error to flag the serial port driver problem.
1315
+ if (this.serialPort != null && !this.serialPort.settings.rtscts) {
1316
+ status = enums_1.EzspStatus.ASH_ERROR_XON_XOFF;
1317
+ }
1318
+ break;
1319
+ default:
1320
+ // a normal byte
1321
+ byte ^= this.decodeFlip;
1322
+ this.decodeFlip = 0;
1323
+ if (this.decodeLen <= consts_1.ASH_MAX_FRAME_WITH_CRC_LEN) {
1324
+ // limit length to max + 1
1325
+ ++this.decodeLen;
1326
+ }
1327
+ if (this.decodeLen > consts_1.ASH_CRC_LEN) {
1328
+ // compute frame CRC even if too long
1329
+ this.decodeCrc = (0, math_1.halCommonCrc16)(this.decodeByte2, this.decodeCrc);
1330
+ if (this.decodeLen <= consts_1.ASH_MAX_FRAME_WITH_CRC_LEN) {
1331
+ // store to only max len
1332
+ inByte = this.decodeByte2;
1333
+ inLen = this.decodeLen - consts_1.ASH_CRC_LEN; // CRC is not output, reduce length
1334
+ }
1335
+ }
1336
+ this.decodeByte2 = this.decodeByte1;
1337
+ this.decodeByte1 = byte;
1338
+ break;
1339
+ }
1340
+ this.decodeInProgress = (status === enums_1.EzspStatus.ASH_IN_PROGRESS);
1341
+ return [status, inByte, inLen];
1342
+ }
1343
+ /**
1344
+ * Starts the Not Ready timer
1345
+ *
1346
+ * On the host, this times nFlag refreshing when the host doesn't have room for callbacks for a prolonged period.
1347
+ *
1348
+ * On the NCP, if this times out the NCP resumes sending callbacks.
1349
+ */
1350
+ startNrTimer() {
1351
+ this.nrTimer = (Date.now() + CONFIG_NR_TIME);
1352
+ }
1353
+ /**
1354
+ * Stop Not Ready timer (set to 0).
1355
+ */
1356
+ stopNrTimer() {
1357
+ this.nrTimer = 0;
1358
+ }
1359
+ /**
1360
+ * Tests whether the Not Ready timer has expired or has stopped. If expired, it is stopped.
1361
+ *
1362
+ * @returns true if the Not Ready timer has expired or stopped
1363
+ */
1364
+ nrTimerHasExpired() {
1365
+ if (this.nrTimer) {
1366
+ if ((Date.now() - this.nrTimer) >= 0) {
1367
+ this.nrTimer = 0;
1368
+ }
1369
+ }
1370
+ return (!this.nrTimer);
1371
+ }
1372
+ /**
1373
+ * Indicates whether or not Not Ready timer is currently running.
1374
+ *
1375
+ * @return True if nrTime == 0
1376
+ */
1377
+ nrTimerIsNotRunning() {
1378
+ return this.nrTimer === 0;
1379
+ }
1380
+ /**
1381
+ * Sets the acknowledgement timer period (in msec) and stops the timer.
1382
+ */
1383
+ setAckPeriod(msec) {
1384
+ this.ackPeriod = msec;
1385
+ this.ackTimer = 0;
1386
+ }
1387
+ /**
1388
+ * Sets the acknowledgement timer period (in msec), and starts the timer running.
1389
+ */
1390
+ setAndStartAckTimer(msec) {
1391
+ this.setAckPeriod(msec);
1392
+ this.startAckTimer();
1393
+ }
1394
+ /**
1395
+ * Adapts the acknowledgement timer period to the observed ACK delay.
1396
+ * If the timer is not running, it does nothing.
1397
+ * If the timer has expired, the timeout period is doubled.
1398
+ * If the timer has not expired, the elapsed time is fed into simple
1399
+ *
1400
+ * IIR filter:
1401
+ * T[n+1] = (7*T[n] + elapsedTime) / 8
1402
+ *
1403
+ * The timeout period, ackPeriod, is limited such that:
1404
+ * config.ackTimeMin <= ackPeriod <= config.ackTimeMax.
1405
+ *
1406
+ * The acknowledgement timer is always stopped by this function.
1407
+ *
1408
+ * @param expired true if timer has expired
1409
+ */
1410
+ adjustAckPeriod(expired) {
1411
+ if (expired) {
1412
+ // if expired, double the period
1413
+ this.ackPeriod += this.ackPeriod;
1414
+ }
1415
+ else if (this.ackTimer) {
1416
+ // adjust period only if running
1417
+ // time elapsed since timer was started
1418
+ let temp = this.ackPeriod;
1419
+ // compute time to receive acknowledgement, then stop timer
1420
+ const lastAckTime = Date.now() - this.ackTimer;
1421
+ temp = (temp << 3) - temp;
1422
+ temp += lastAckTime << 2;
1423
+ temp >>= 3;
1424
+ this.ackPeriod = (temp & 0xFFFF);
1425
+ }
1426
+ // keep ackPeriod within limits
1427
+ if (this.ackPeriod > CONFIG_ACK_TIME_MAX) {
1428
+ this.ackPeriod = CONFIG_ACK_TIME_MAX;
1429
+ }
1430
+ else if (this.ackPeriod < CONFIG_ACK_TIME_MIN) {
1431
+ this.ackPeriod = CONFIG_ACK_TIME_MIN;
1432
+ }
1433
+ this.ackTimer = 0; // always stop the timer
1434
+ }
1435
+ /**
1436
+ * Sets ACK Timer to the specified period and starts it running.
1437
+ */
1438
+ startAckTimer() {
1439
+ this.ackTimer = Date.now();
1440
+ }
1441
+ /**
1442
+ * Stops and clears ACK Timer.
1443
+ */
1444
+ stopAckTimer() {
1445
+ this.ackTimer = 0;
1446
+ }
1447
+ /**
1448
+ * Indicates whether or not ACK Timer has expired.
1449
+ * If the timer is stopped (0) then it is not expired.
1450
+ *
1451
+ * @returns
1452
+ */
1453
+ ackTimerHasExpired() {
1454
+ if (this.ackTimer === 0) {
1455
+ // if timer is not running, return false
1456
+ return false;
1457
+ }
1458
+ // return ((halCommonGetInt16uMillisecondTick() - this.ackTimer) >= this.ackPeriod);
1459
+ return ((Date.now() - this.ackTimer) >= this.ackPeriod);
1460
+ }
1461
+ /**
1462
+ * Indicates whether or not ACK Timer is currently running (!= 0).
1463
+ * The timer may be running even if expired.
1464
+ */
1465
+ ackTimerIsNotRunning() {
1466
+ return this.ackTimer === 0;
1467
+ }
1468
+ /**
1469
+ * Increase counters based on frame type and direction.
1470
+ * @param sent True if frame being sent, false if being received.
1471
+ */
1472
+ countFrame(sent) {
1473
+ let control;
1474
+ if (sent) {
1475
+ control = this.txSHBuffer[0];
1476
+ this.counters.txAllFrames += 1;
1477
+ }
1478
+ else {
1479
+ control = this.rxSHBuffer[0];
1480
+ this.counters.rxAllFrames += 1;
1481
+ }
1482
+ if ((control & consts_1.ASH_DFRAME_MASK) === enums_2.AshFrameType.DATA) {
1483
+ if (sent) {
1484
+ if (control & consts_1.ASH_RFLAG_MASK) {
1485
+ this.counters.txReDataFrames += 1;
1486
+ }
1487
+ else {
1488
+ this.counters.txDataFrames += 1;
1489
+ }
1490
+ }
1491
+ else {
1492
+ if (control & consts_1.ASH_RFLAG_MASK) {
1493
+ this.counters.rxReDataFrames += 1;
1494
+ }
1495
+ else {
1496
+ this.counters.rxDataFrames += 1;
1497
+ }
1498
+ }
1499
+ }
1500
+ else if ((control & consts_1.ASH_SHFRAME_MASK) === enums_2.AshFrameType.ACK) {
1501
+ if (sent) {
1502
+ this.counters.txAckFrames += 1;
1503
+ if (control & consts_1.ASH_NFLAG_MASK) {
1504
+ this.counters.txN1Frames += 1;
1505
+ } /* else {
1506
+ this.counters.txN0Frames += 1;
1507
+ }*/
1508
+ }
1509
+ else {
1510
+ this.counters.rxAckFrames += 1;
1511
+ if (control & consts_1.ASH_NFLAG_MASK) {
1512
+ this.counters.rxN1Frames += 1;
1513
+ } /* else {
1514
+ this.counters.rxN0Frames += 1;
1515
+ }*/
1516
+ }
1517
+ }
1518
+ else if ((control & consts_1.ASH_SHFRAME_MASK) === enums_2.AshFrameType.NAK) {
1519
+ if (sent) {
1520
+ this.counters.txNakFrames += 1;
1521
+ if (control & consts_1.ASH_NFLAG_MASK) {
1522
+ this.counters.txN1Frames += 1;
1523
+ } /* else {
1524
+ this.counters.txN0Frames += 1;
1525
+ }*/
1526
+ }
1527
+ else {
1528
+ this.counters.rxNakFrames += 1;
1529
+ if (control & consts_1.ASH_NFLAG_MASK) {
1530
+ this.counters.rxN1Frames += 1;
1531
+ } /* else {
1532
+ this.counters.rxN0Frames += 1;
1533
+ }*/
1534
+ }
1535
+ }
1536
+ }
1537
+ /**
1538
+ * Prints counters in a nicely formatted table.
1539
+ */
1540
+ printCounters() {
1541
+ console.table({
1542
+ "Total frames": { "Received": this.counters.rxAllFrames, "Transmitted": this.counters.txAllFrames },
1543
+ "Cancelled": { "Received": this.counters.rxCancelled, "Transmitted": this.counters.txCancelled },
1544
+ "DATA frames": { "Received": this.counters.rxDataFrames, "Transmitted": this.counters.txDataFrames },
1545
+ "DATA bytes": { "Received": this.counters.rxData, "Transmitted": this.counters.txData },
1546
+ "Retry frames": { "Received": this.counters.rxReDataFrames, "Transmitted": this.counters.txReDataFrames },
1547
+ "ACK frames": { "Received": this.counters.rxAckFrames, "Transmitted": this.counters.txAckFrames },
1548
+ "NAK frames": { "Received": this.counters.rxNakFrames, "Transmitted": this.counters.txNakFrames },
1549
+ "nRdy frames": { "Received": this.counters.rxN1Frames, "Transmitted": this.counters.txN1Frames },
1550
+ });
1551
+ console.table({
1552
+ "CRC errors": { "Received": this.counters.rxCrcErrors },
1553
+ "Comm errors": { "Received": this.counters.rxCommErrors },
1554
+ "Length < minimum": { "Received": this.counters.rxTooShort },
1555
+ "Length > maximum": { "Received": this.counters.rxTooLong },
1556
+ "Bad controls": { "Received": this.counters.rxBadControl },
1557
+ "Bad lengths": { "Received": this.counters.rxBadLength },
1558
+ "Bad ACK numbers": { "Received": this.counters.rxBadAckNumber },
1559
+ "Out of buffers": { "Received": this.counters.rxNoBuffer },
1560
+ "Retry dupes": { "Received": this.counters.rxDuplicates },
1561
+ "Out of sequence": { "Received": this.counters.rxOutOfSequence },
1562
+ "ACK timeouts": { "Received": this.counters.rxAckTimeouts },
1563
+ });
1564
+ }
1565
+ }
1566
+ exports.UartAsh = UartAsh;
1567
+ //# sourceMappingURL=ash.js.map