zigbee-herdsman 6.0.2 → 6.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/package.json +9 -3
  3. package/.github/ISSUE_TEMPLATE/config.yml +0 -5
  4. package/.github/dependabot.yml +0 -22
  5. package/.github/workflows/ci.yml +0 -69
  6. package/.github/workflows/release-please.yml +0 -18
  7. package/.github/workflows/stale.yml +0 -20
  8. package/.github/workflows/typedoc.yaml +0 -47
  9. package/.release-please-manifest.json +0 -3
  10. package/.vscode/extensions.json +0 -3
  11. package/.vscode/settings.json +0 -11
  12. package/biome.json +0 -98
  13. package/examples/join-and-log.js +0 -24
  14. package/release-please-config.json +0 -9
  15. package/src/adapter/adapter.ts +0 -189
  16. package/src/adapter/adapterDiscovery.ts +0 -666
  17. package/src/adapter/const.ts +0 -12
  18. package/src/adapter/deconz/adapter/deconzAdapter.ts +0 -877
  19. package/src/adapter/deconz/driver/constants.ts +0 -246
  20. package/src/adapter/deconz/driver/driver.ts +0 -1540
  21. package/src/adapter/deconz/driver/frame.ts +0 -11
  22. package/src/adapter/deconz/driver/frameParser.ts +0 -753
  23. package/src/adapter/deconz/driver/parser.ts +0 -45
  24. package/src/adapter/deconz/driver/writer.ts +0 -22
  25. package/src/adapter/deconz/types.d.ts +0 -13
  26. package/src/adapter/ember/adapter/emberAdapter.ts +0 -2265
  27. package/src/adapter/ember/adapter/endpoints.ts +0 -86
  28. package/src/adapter/ember/adapter/oneWaitress.ts +0 -324
  29. package/src/adapter/ember/adapter/tokensManager.ts +0 -782
  30. package/src/adapter/ember/consts.ts +0 -178
  31. package/src/adapter/ember/enums.ts +0 -1746
  32. package/src/adapter/ember/ezsp/buffalo.ts +0 -1392
  33. package/src/adapter/ember/ezsp/consts.ts +0 -148
  34. package/src/adapter/ember/ezsp/enums.ts +0 -1114
  35. package/src/adapter/ember/ezsp/ezsp.ts +0 -9061
  36. package/src/adapter/ember/ezspError.ts +0 -10
  37. package/src/adapter/ember/types.ts +0 -866
  38. package/src/adapter/ember/uart/ash.ts +0 -1960
  39. package/src/adapter/ember/uart/consts.ts +0 -109
  40. package/src/adapter/ember/uart/enums.ts +0 -192
  41. package/src/adapter/ember/uart/parser.ts +0 -48
  42. package/src/adapter/ember/uart/queues.ts +0 -247
  43. package/src/adapter/ember/uart/writer.ts +0 -53
  44. package/src/adapter/ember/utils/initters.ts +0 -58
  45. package/src/adapter/ember/utils/math.ts +0 -73
  46. package/src/adapter/events.ts +0 -21
  47. package/src/adapter/ezsp/adapter/backup.ts +0 -109
  48. package/src/adapter/ezsp/adapter/ezspAdapter.ts +0 -614
  49. package/src/adapter/ezsp/driver/commands.ts +0 -2497
  50. package/src/adapter/ezsp/driver/consts.ts +0 -11
  51. package/src/adapter/ezsp/driver/driver.ts +0 -1002
  52. package/src/adapter/ezsp/driver/ezsp.ts +0 -802
  53. package/src/adapter/ezsp/driver/frame.ts +0 -101
  54. package/src/adapter/ezsp/driver/index.ts +0 -4
  55. package/src/adapter/ezsp/driver/multicast.ts +0 -78
  56. package/src/adapter/ezsp/driver/parser.ts +0 -81
  57. package/src/adapter/ezsp/driver/types/basic.ts +0 -201
  58. package/src/adapter/ezsp/driver/types/index.ts +0 -239
  59. package/src/adapter/ezsp/driver/types/named.ts +0 -2330
  60. package/src/adapter/ezsp/driver/types/struct.ts +0 -844
  61. package/src/adapter/ezsp/driver/uart.ts +0 -460
  62. package/src/adapter/ezsp/driver/utils/crc16ccitt.ts +0 -44
  63. package/src/adapter/ezsp/driver/utils/index.ts +0 -32
  64. package/src/adapter/ezsp/driver/writer.ts +0 -64
  65. package/src/adapter/index.ts +0 -3
  66. package/src/adapter/serialPort.ts +0 -58
  67. package/src/adapter/socketPortUtils.ts +0 -16
  68. package/src/adapter/tstype.ts +0 -78
  69. package/src/adapter/z-stack/adapter/adapter-backup.ts +0 -519
  70. package/src/adapter/z-stack/adapter/adapter-nv-memory.ts +0 -457
  71. package/src/adapter/z-stack/adapter/endpoints.ts +0 -57
  72. package/src/adapter/z-stack/adapter/manager.ts +0 -543
  73. package/src/adapter/z-stack/adapter/tstype.ts +0 -6
  74. package/src/adapter/z-stack/adapter/zStackAdapter.ts +0 -1190
  75. package/src/adapter/z-stack/constants/af.ts +0 -27
  76. package/src/adapter/z-stack/constants/common.ts +0 -285
  77. package/src/adapter/z-stack/constants/dbg.ts +0 -23
  78. package/src/adapter/z-stack/constants/index.ts +0 -11
  79. package/src/adapter/z-stack/constants/mac.ts +0 -128
  80. package/src/adapter/z-stack/constants/sapi.ts +0 -25
  81. package/src/adapter/z-stack/constants/sys.ts +0 -72
  82. package/src/adapter/z-stack/constants/util.ts +0 -82
  83. package/src/adapter/z-stack/constants/utils.ts +0 -14
  84. package/src/adapter/z-stack/constants/zdo.ts +0 -103
  85. package/src/adapter/z-stack/models/startup-options.ts +0 -13
  86. package/src/adapter/z-stack/structs/entries/address-manager-entry.ts +0 -44
  87. package/src/adapter/z-stack/structs/entries/address-manager-table.ts +0 -19
  88. package/src/adapter/z-stack/structs/entries/aps-link-key-data-entry.ts +0 -12
  89. package/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts +0 -21
  90. package/src/adapter/z-stack/structs/entries/aps-tc-link-key-entry.ts +0 -19
  91. package/src/adapter/z-stack/structs/entries/aps-tc-link-key-table.ts +0 -21
  92. package/src/adapter/z-stack/structs/entries/channel-list.ts +0 -8
  93. package/src/adapter/z-stack/structs/entries/has-configured.ts +0 -16
  94. package/src/adapter/z-stack/structs/entries/index.ts +0 -16
  95. package/src/adapter/z-stack/structs/entries/nib.ts +0 -66
  96. package/src/adapter/z-stack/structs/entries/nwk-key-descriptor.ts +0 -15
  97. package/src/adapter/z-stack/structs/entries/nwk-key.ts +0 -13
  98. package/src/adapter/z-stack/structs/entries/nwk-pan-id.ts +0 -8
  99. package/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-entry.ts +0 -20
  100. package/src/adapter/z-stack/structs/entries/nwk-sec-material-descriptor-table.ts +0 -19
  101. package/src/adapter/z-stack/structs/entries/security-manager-entry.ts +0 -33
  102. package/src/adapter/z-stack/structs/entries/security-manager-table.ts +0 -22
  103. package/src/adapter/z-stack/structs/index.ts +0 -4
  104. package/src/adapter/z-stack/structs/serializable-memory-object.ts +0 -14
  105. package/src/adapter/z-stack/structs/struct.ts +0 -367
  106. package/src/adapter/z-stack/structs/table.ts +0 -198
  107. package/src/adapter/z-stack/unpi/constants.ts +0 -33
  108. package/src/adapter/z-stack/unpi/frame.ts +0 -62
  109. package/src/adapter/z-stack/unpi/index.ts +0 -4
  110. package/src/adapter/z-stack/unpi/parser.ts +0 -56
  111. package/src/adapter/z-stack/unpi/writer.ts +0 -21
  112. package/src/adapter/z-stack/utils/channel-list.ts +0 -40
  113. package/src/adapter/z-stack/utils/index.ts +0 -2
  114. package/src/adapter/z-stack/utils/network-options.ts +0 -26
  115. package/src/adapter/z-stack/znp/buffaloZnp.ts +0 -175
  116. package/src/adapter/z-stack/znp/definition.ts +0 -2713
  117. package/src/adapter/z-stack/znp/index.ts +0 -2
  118. package/src/adapter/z-stack/znp/parameterType.ts +0 -22
  119. package/src/adapter/z-stack/znp/tstype.ts +0 -44
  120. package/src/adapter/z-stack/znp/utils.ts +0 -10
  121. package/src/adapter/z-stack/znp/znp.ts +0 -342
  122. package/src/adapter/z-stack/znp/zpiObject.ts +0 -148
  123. package/src/adapter/zboss/adapter/zbossAdapter.ts +0 -526
  124. package/src/adapter/zboss/commands.ts +0 -1184
  125. package/src/adapter/zboss/consts.ts +0 -9
  126. package/src/adapter/zboss/driver.ts +0 -422
  127. package/src/adapter/zboss/enums.ts +0 -360
  128. package/src/adapter/zboss/frame.ts +0 -227
  129. package/src/adapter/zboss/reader.ts +0 -65
  130. package/src/adapter/zboss/types.ts +0 -0
  131. package/src/adapter/zboss/uart.ts +0 -428
  132. package/src/adapter/zboss/utils.ts +0 -58
  133. package/src/adapter/zboss/writer.ts +0 -49
  134. package/src/adapter/zigate/adapter/patchZdoBuffaloBE.ts +0 -27
  135. package/src/adapter/zigate/adapter/zigateAdapter.ts +0 -618
  136. package/src/adapter/zigate/driver/LICENSE +0 -17
  137. package/src/adapter/zigate/driver/buffaloZiGate.ts +0 -212
  138. package/src/adapter/zigate/driver/commandType.ts +0 -418
  139. package/src/adapter/zigate/driver/constants.ts +0 -150
  140. package/src/adapter/zigate/driver/frame.ts +0 -197
  141. package/src/adapter/zigate/driver/messageType.ts +0 -287
  142. package/src/adapter/zigate/driver/parameterType.ts +0 -32
  143. package/src/adapter/zigate/driver/ziGateObject.ts +0 -146
  144. package/src/adapter/zigate/driver/zigate.ts +0 -423
  145. package/src/adapter/zoh/adapter/utils.ts +0 -27
  146. package/src/adapter/zoh/adapter/zohAdapter.ts +0 -838
  147. package/src/buffalo/buffalo.ts +0 -342
  148. package/src/buffalo/index.ts +0 -1
  149. package/src/controller/controller.ts +0 -1022
  150. package/src/controller/database.ts +0 -124
  151. package/src/controller/events.ts +0 -52
  152. package/src/controller/greenPower.ts +0 -603
  153. package/src/controller/helpers/index.ts +0 -1
  154. package/src/controller/helpers/installCodes.ts +0 -107
  155. package/src/controller/helpers/request.ts +0 -96
  156. package/src/controller/helpers/requestQueue.ts +0 -125
  157. package/src/controller/helpers/zclFrameConverter.ts +0 -47
  158. package/src/controller/helpers/zclTransactionSequenceNumber.ts +0 -19
  159. package/src/controller/index.ts +0 -6
  160. package/src/controller/model/device.ts +0 -1249
  161. package/src/controller/model/endpoint.ts +0 -1105
  162. package/src/controller/model/entity.ts +0 -23
  163. package/src/controller/model/group.ts +0 -424
  164. package/src/controller/model/index.ts +0 -5
  165. package/src/controller/model/zigbeeEntity.ts +0 -30
  166. package/src/controller/touchlink.ts +0 -189
  167. package/src/controller/tstype.ts +0 -274
  168. package/src/index.ts +0 -12
  169. package/src/models/backup-storage-legacy.ts +0 -48
  170. package/src/models/backup-storage-unified.ts +0 -47
  171. package/src/models/backup.ts +0 -37
  172. package/src/models/index.ts +0 -5
  173. package/src/models/network-options.ts +0 -11
  174. package/src/utils/backup.ts +0 -152
  175. package/src/utils/index.ts +0 -5
  176. package/src/utils/logger.ts +0 -20
  177. package/src/utils/patchBigIntSerialization.ts +0 -8
  178. package/src/utils/queue.ts +0 -76
  179. package/src/utils/types.d.ts +0 -3
  180. package/src/utils/utils.ts +0 -19
  181. package/src/utils/wait.ts +0 -5
  182. package/src/utils/waitress.ts +0 -96
  183. package/src/zspec/consts.ts +0 -84
  184. package/src/zspec/enums.ts +0 -22
  185. package/src/zspec/index.ts +0 -3
  186. package/src/zspec/tstypes.ts +0 -18
  187. package/src/zspec/utils.ts +0 -247
  188. package/src/zspec/zcl/buffaloZcl.ts +0 -1220
  189. package/src/zspec/zcl/definition/cluster.ts +0 -5915
  190. package/src/zspec/zcl/definition/clusters-typegen.ts +0 -588
  191. package/src/zspec/zcl/definition/clusters-types.ts +0 -7331
  192. package/src/zspec/zcl/definition/consts.ts +0 -24
  193. package/src/zspec/zcl/definition/enums.ts +0 -203
  194. package/src/zspec/zcl/definition/foundation.ts +0 -329
  195. package/src/zspec/zcl/definition/manufacturerCode.ts +0 -729
  196. package/src/zspec/zcl/definition/status.ts +0 -69
  197. package/src/zspec/zcl/definition/tstype.ts +0 -377
  198. package/src/zspec/zcl/index.ts +0 -11
  199. package/src/zspec/zcl/utils.ts +0 -321
  200. package/src/zspec/zcl/zclFrame.ts +0 -356
  201. package/src/zspec/zcl/zclHeader.ts +0 -102
  202. package/src/zspec/zcl/zclStatusError.ts +0 -10
  203. package/src/zspec/zdo/buffaloZdo.ts +0 -2336
  204. package/src/zspec/zdo/definition/clusters.ts +0 -722
  205. package/src/zspec/zdo/definition/consts.ts +0 -16
  206. package/src/zspec/zdo/definition/enums.ts +0 -99
  207. package/src/zspec/zdo/definition/status.ts +0 -105
  208. package/src/zspec/zdo/definition/tstypes.ts +0 -1062
  209. package/src/zspec/zdo/index.ts +0 -7
  210. package/src/zspec/zdo/utils.ts +0 -76
  211. package/src/zspec/zdo/zdoStatusError.ts +0 -10
  212. package/test/adapter/adapter.test.ts +0 -1062
  213. package/test/adapter/ember/ash.test.ts +0 -337
  214. package/test/adapter/ember/consts.ts +0 -131
  215. package/test/adapter/ember/emberAdapter.test.ts +0 -3449
  216. package/test/adapter/ember/ezsp.test.ts +0 -385
  217. package/test/adapter/ember/ezspBuffalo.test.ts +0 -93
  218. package/test/adapter/ember/ezspError.test.ts +0 -12
  219. package/test/adapter/ember/math.test.ts +0 -206
  220. package/test/adapter/ezsp/frame.test.ts +0 -30
  221. package/test/adapter/ezsp/uart.test.ts +0 -181
  222. package/test/adapter/z-stack/adapter.test.ts +0 -3984
  223. package/test/adapter/z-stack/constants.test.ts +0 -33
  224. package/test/adapter/z-stack/structs.test.ts +0 -115
  225. package/test/adapter/z-stack/unpi.test.ts +0 -213
  226. package/test/adapter/z-stack/znp.test.ts +0 -1284
  227. package/test/adapter/zboss/fixZdoResponse.test.ts +0 -179
  228. package/test/adapter/zigate/patchZdoBuffaloBE.test.ts +0 -81
  229. package/test/adapter/zigate/zdo.test.ts +0 -187
  230. package/test/adapter/zoh/utils.test.ts +0 -36
  231. package/test/adapter/zoh/zohAdapter.test.ts +0 -1307
  232. package/test/benchOptions.ts +0 -14
  233. package/test/buffalo.test.ts +0 -431
  234. package/test/controller.bench.ts +0 -214
  235. package/test/controller.test.ts +0 -8702
  236. package/test/greenpower.test.ts +0 -1408
  237. package/test/mockAdapters.ts +0 -65
  238. package/test/mockDevices.ts +0 -598
  239. package/test/requests.bench.ts +0 -229
  240. package/test/testUtils.ts +0 -20
  241. package/test/tsconfig.json +0 -9
  242. package/test/utils/math.ts +0 -19
  243. package/test/utils.test.ts +0 -279
  244. package/test/vitest.config.mts +0 -26
  245. package/test/zcl.test.ts +0 -2831
  246. package/test/zspec/utils.test.ts +0 -68
  247. package/test/zspec/zcl/buffalo.test.ts +0 -1374
  248. package/test/zspec/zcl/frame.test.ts +0 -960
  249. package/test/zspec/zcl/utils.test.ts +0 -273
  250. package/test/zspec/zdo/buffalo.test.ts +0 -1850
  251. package/test/zspec/zdo/utils.test.ts +0 -241
  252. package/tsconfig.json +0 -24
@@ -1,1960 +0,0 @@
1
- /* v8 ignore start */
2
-
3
- import {EventEmitter} from "node:events";
4
- import {Socket} from "node:net";
5
-
6
- import {wait} from "../../../utils";
7
- import {logger} from "../../../utils/logger";
8
- import {SerialPort} from "../../serialPort";
9
- import SocketPortUtils from "../../socketPortUtils";
10
- import type {SerialPortOptions} from "../../tstype";
11
- import {EzspStatus} from "../enums";
12
- import {halCommonCrc16, inc8, mod8, withinRange} from "../utils/math";
13
- import {
14
- ASH_ACKNUM_BIT,
15
- ASH_ACKNUM_MASK,
16
- ASH_CRC_LEN,
17
- ASH_DFRAME_MASK,
18
- ASH_FLIP,
19
- ASH_FRAME_LEN_ACK,
20
- ASH_FRAME_LEN_DATA_MIN,
21
- ASH_FRAME_LEN_ERROR,
22
- ASH_FRAME_LEN_NAK,
23
- ASH_FRAME_LEN_RSTACK,
24
- ASH_FRMNUM_BIT,
25
- ASH_FRMNUM_MASK,
26
- ASH_MAX_DATA_FIELD_LEN,
27
- ASH_MAX_FRAME_WITH_CRC_LEN,
28
- ASH_MAX_TIMEOUTS,
29
- ASH_MIN_DATA_FIELD_LEN,
30
- ASH_MIN_FRAME_WITH_CRC_LEN,
31
- ASH_NFLAG_MASK,
32
- ASH_RFLAG_MASK,
33
- ASH_SHFRAME_MASK,
34
- ASH_VERSION,
35
- ASH_WAKE,
36
- EZSP_HOST_RX_POOL_SIZE,
37
- LFSR_POLY,
38
- LFSR_SEED,
39
- SH_RX_BUFFER_LEN,
40
- SH_TX_BUFFER_LEN,
41
- TX_POOL_BUFFERS,
42
- } from "./consts";
43
- import {AshFrameType, AshReservedByte, NcpFailedCode} from "./enums";
44
- import {AshParser} from "./parser";
45
- import {EzspBuffer, EzspFreeList, EzspQueue} from "./queues";
46
- import {AshWriter} from "./writer";
47
-
48
- const NS = "zh:ember:uart:ash";
49
-
50
- /** ASH get rflag in control byte */
51
- // const ashGetRFlag = (ctrl: number): number => (ctrl & ASH_RFLAG_MASK) >> ASH_RFLAG_BIT;
52
- /** ASH get nflag in control byte */
53
- // const ashGetNFlag = (ctrl: number): number => (ctrl & ASH_NFLAG_MASK) >> ASH_NFLAG_BIT;
54
- /** ASH get frmnum in control byte */
55
- const ashGetFrmNum = (ctrl: number): number => (ctrl & ASH_FRMNUM_MASK) >> ASH_FRMNUM_BIT;
56
- /** ASH get acknum in control byte */
57
- const ashGetACKNum = (ctrl: number): number => (ctrl & ASH_ACKNUM_MASK) >> ASH_ACKNUM_BIT;
58
-
59
- type UartAshCounters = {
60
- /** DATA frame data fields bytes transmitted */
61
- txData: number;
62
- /** frames of all types transmitted */
63
- txAllFrames: number;
64
- /** DATA frames transmitted */
65
- txDataFrames: number;
66
- /** ACK frames transmitted */
67
- txAckFrames: number;
68
- /** NAK frames transmitted */
69
- txNakFrames: number;
70
- /** DATA frames retransmitted */
71
- txReDataFrames: number;
72
- /** ACK and NAK frames with nFlag 0 transmitted */
73
- // txN0Frames: number,
74
- /** ACK and NAK frames with nFlag 1 transmitted */
75
- txN1Frames: number;
76
- /** frames cancelled (with ASH_CAN byte) */
77
- txCancelled: number;
78
-
79
- /** DATA frame data fields bytes received */
80
- rxData: number;
81
- /** frames of all types received */
82
- rxAllFrames: number;
83
- /** DATA frames received */
84
- rxDataFrames: number;
85
- /** ACK frames received */
86
- rxAckFrames: number;
87
- /** NAK frames received */
88
- rxNakFrames: number;
89
- /** retransmitted DATA frames received */
90
- rxReDataFrames: number;
91
- /** ACK and NAK frames with nFlag 0 received */
92
- // rxN0Frames: number,
93
- /** ACK and NAK frames with nFlag 1 received */
94
- rxN1Frames: number;
95
- /** frames cancelled (with ASH_CAN byte) */
96
- rxCancelled: number;
97
-
98
- /** frames with CRC errors */
99
- rxCrcErrors: number;
100
- /** frames with comm errors (with ASH_SUB byte) */
101
- rxCommErrors: number;
102
- /** frames shorter than minimum */
103
- rxTooShort: number;
104
- /** frames longer than maximum */
105
- rxTooLong: number;
106
- /** frames with illegal control byte */
107
- rxBadControl: number;
108
- /** frames with illegal length for type of frame */
109
- rxBadLength: number;
110
- /** frames with bad ACK numbers */
111
- rxBadAckNumber: number;
112
- /** DATA frames discarded due to lack of buffers */
113
- rxNoBuffer: number;
114
- /** duplicate retransmitted DATA frames */
115
- rxDuplicates: number;
116
- /** DATA frames received out of sequence */
117
- rxOutOfSequence: number;
118
- /** received ACK timeouts */
119
- rxAckTimeouts: number;
120
- };
121
-
122
- enum SendState {
123
- IDLE = 0,
124
- SHFRAME = 1,
125
- TX_DATA = 2,
126
- RETX_DATA = 3,
127
- }
128
-
129
- // Bits in ashFlags
130
- enum Flag {
131
- /** Reject Condition */
132
- REJ = 0x01,
133
- /** Retransmit Condition */
134
- RETX = 0x02,
135
- /** send NAK */
136
- NAK = 0x04,
137
- /** send ACK */
138
- ACK = 0x08,
139
- /** send RST */
140
- RST = 0x10,
141
- /** send immediate CAN */
142
- CAN = 0x20,
143
- /** in CONNECTED state, else ERROR */
144
- CONNECTED = 0x40,
145
- /** not ready to receive DATA frames */
146
- NR = 0x100,
147
- /** last transmitted NR status */
148
- NRTX = 0x200,
149
- }
150
-
151
- /** max frames sent without being ACKed (1-7) */
152
- export const CONFIG_TX_K = 3;
153
- /** enables randomizing DATA frame payloads */
154
- const CONFIG_RANDOMIZE = true;
155
- /** adaptive rec'd ACK timeout initial value */
156
- const CONFIG_ACK_TIME_INIT = 800;
157
- /** " " " " " minimum value */
158
- const CONFIG_ACK_TIME_MIN = 400;
159
- /** " " " " " maximum value */
160
- const CONFIG_ACK_TIME_MAX = 2400;
161
- /** time allowed to receive RSTACK after ncp is reset */
162
- const CONFIG_TIME_RST = 5000;
163
- /** time between checks for received RSTACK (CONNECTED status) */
164
- const CONFIG_TIME_RST_CHECK = 100;
165
- /** if free buffers < limit, host receiver isn't ready, will hold off the ncp from sending normal priority frames */
166
- const CONFIG_NR_LOW_LIMIT = 8; // RX_FREE_LW
167
- /** if free buffers > limit, host receiver is ready */
168
- const CONFIG_NR_HIGH_LIMIT = 12; // RX_FREE_HW
169
- /** time until a set nFlag must be resent (max 2032) */
170
- const CONFIG_NR_TIME = 480;
171
- /** Read/write max bytes count at stream level */
172
- const CONFIG_HIGHWATER_MARK = 256;
173
-
174
- interface UartAshEventMap {
175
- fatalError: [status: EzspStatus];
176
- frame: [];
177
- }
178
-
179
- /**
180
- * ASH Protocol handler.
181
- */
182
- export class UartAsh extends EventEmitter<UartAshEventMap> {
183
- private readonly portOptions: SerialPortOptions;
184
- private serialPort?: SerialPort;
185
- private socketPort?: Socket;
186
- private writer: AshWriter;
187
- private parser: AshParser;
188
-
189
- /** True when serial/socket is currently closing. */
190
- private closing: boolean;
191
-
192
- /** time ackTimer started: 0 means not ready uint16_t */
193
- private ackTimer: number;
194
- /** time used to check ackTimer expiry (msecs) uint16_t */
195
- private ackPeriod: number;
196
- /** not ready timer (16 msec units). Set to (now + config.nrTime) when started. uint8_t */
197
- private nrTimer: number;
198
- /** frame decode in progress */
199
- private decodeInProgress: boolean;
200
-
201
- // Variables used in encoding frames
202
- /** true when preceding byte was escaped */
203
- private encodeEscFlag: boolean;
204
- /** byte to send after ASH_ESC uint8_t */
205
- private encodeFlip: number;
206
- /** uint16_t */
207
- private encodeCrc: number;
208
- /** encoder state: 0 = control/data bytes, 1 = crc low byte, 2 = crc high byte, 3 = flag. uint8_t */
209
- private encodeState: number;
210
- /** bytes remaining to encode. uint8_t */
211
- private encodeCount: number;
212
-
213
- // Variables used in decoding frames
214
- /** bytes in frame, plus CRC, clamped to limit +1: high values also used to record certain errors. uint8_t */
215
- private decodeLen: number;
216
- /** ASH_FLIP if previous byte was ASH_ESC. uint8_t */
217
- private decodeFlip: number;
218
- /** a 2 byte queue to avoid outputting crc bytes. uint8_t */
219
- private decodeByte1: number;
220
- /** at frame end, they contain the received crc. uint8_t */
221
- private decodeByte2: number;
222
- /** uint16_t */
223
- private decodeCrc: number;
224
-
225
- /** outgoing short frames */
226
- private txSHBuffer: Buffer;
227
- /** incoming short frames */
228
- private rxSHBuffer: Buffer;
229
-
230
- /** bit flags for top-level logic. uint16_t */
231
- private flags: number;
232
- /** frame ack'ed from remote peer. uint8_t */
233
- private ackRx: number;
234
- /** frame ack'ed to remote peer. uint8_t */
235
- private ackTx: number;
236
- /** next frame to be transmitted. uint8_t */
237
- private frmTx: number;
238
- /** next frame to be retransmitted. uint8_t */
239
- private frmReTx: number;
240
- /** next frame expected to be rec'd. uint8_t */
241
- private frmRx: number;
242
- /** frame at retx queue's head. uint8_t */
243
- private frmReTxHead: number;
244
- /** consecutive timeout counter. uint8_t */
245
- private timeouts: number;
246
- /** rec'd DATA frame buffer. uint8_t */
247
- private rxDataBuffer?: EzspBuffer;
248
- /** rec'd frame length. uint8_t */
249
- private rxLen: number;
250
- /** tx frame offset. uint8_t */
251
- private txOffset: number;
252
-
253
- public counters: UartAshCounters;
254
-
255
- /**
256
- * Errors reported by the NCP.
257
- * The `NcpFailedCode` from the frame reporting this is logged before this is set to make it clear where it failed:
258
- * - The NCP sent an ERROR frame during the initial reset sequence (before CONNECTED state)
259
- * - The NCP sent an ERROR frame
260
- * - The NCP sent an unexpected RSTACK
261
- */
262
- private ncpError: EzspStatus;
263
- /** Errors reported by the Host. */
264
- private hostError: EzspStatus;
265
- /** sendExec() state variable */
266
- private sendState: SendState;
267
-
268
- /** NCP is enabled to sleep, set by EZSP, not supported atm, always false */
269
- public ncpSleepEnabled: boolean;
270
- /**
271
- * Set when the ncp has indicated it has a pending callback by seting the callback flag in the frame control byte
272
- * or (uart version only) by sending an an ASH_WAKE byte between frames.
273
- */
274
- public ncpHasCallbacks: boolean;
275
-
276
- /** Transmit buffers */
277
- private readonly txPool: EzspBuffer[];
278
- public readonly txQueue: EzspQueue;
279
- public readonly reTxQueue: EzspQueue;
280
- public readonly txFree: EzspFreeList;
281
-
282
- /** Receive buffers */
283
- private readonly rxPool: EzspBuffer[];
284
- public readonly rxQueue: EzspQueue;
285
- public readonly rxFree: EzspFreeList;
286
-
287
- constructor(options: SerialPortOptions) {
288
- super();
289
-
290
- this.portOptions = options;
291
- this.serialPort = undefined;
292
- this.socketPort = undefined;
293
- this.writer = new AshWriter({highWaterMark: CONFIG_HIGHWATER_MARK});
294
- this.parser = new AshParser({readableHighWaterMark: CONFIG_HIGHWATER_MARK});
295
-
296
- this.txPool = new Array<EzspBuffer>(TX_POOL_BUFFERS);
297
- this.txQueue = new EzspQueue();
298
- this.reTxQueue = new EzspQueue();
299
- this.txFree = new EzspFreeList();
300
-
301
- this.rxPool = new Array<EzspBuffer>(EZSP_HOST_RX_POOL_SIZE);
302
- this.rxQueue = new EzspQueue();
303
- this.rxFree = new EzspFreeList();
304
-
305
- this.closing = false;
306
-
307
- this.txSHBuffer = Buffer.alloc(SH_TX_BUFFER_LEN);
308
- this.rxSHBuffer = Buffer.alloc(SH_RX_BUFFER_LEN);
309
- this.ackTimer = 0;
310
- this.ackPeriod = 0;
311
- this.nrTimer = 0;
312
-
313
- this.flags = 0;
314
- this.decodeInProgress = false;
315
- this.ackRx = 0;
316
- this.ackTx = 0;
317
- this.frmTx = 0;
318
- this.frmReTx = 0;
319
- this.frmRx = 0;
320
- this.frmReTxHead = 0;
321
- this.timeouts = 0;
322
- this.rxDataBuffer = undefined;
323
- this.rxLen = 0;
324
-
325
- // init to "start of frame" default
326
- this.encodeCount = 0;
327
- this.encodeState = 0;
328
- this.encodeEscFlag = false;
329
- this.encodeFlip = 0;
330
- this.encodeCrc = 0xffff;
331
- this.txOffset = 0;
332
-
333
- // init to "start of frame" default
334
- this.decodeLen = 0;
335
- this.decodeByte1 = 0;
336
- this.decodeByte2 = 0;
337
- this.decodeFlip = 0;
338
- this.decodeCrc = 0xffff;
339
-
340
- this.ncpError = EzspStatus.NO_ERROR;
341
- this.hostError = EzspStatus.NO_ERROR;
342
- this.sendState = SendState.IDLE;
343
-
344
- this.ncpSleepEnabled = false;
345
- this.ncpHasCallbacks = false;
346
-
347
- this.stopAckTimer();
348
- this.stopNrTimer();
349
-
350
- this.counters = {
351
- txData: 0,
352
- txAllFrames: 0,
353
- txDataFrames: 0,
354
- txAckFrames: 0,
355
- txNakFrames: 0,
356
- txReDataFrames: 0,
357
- // txN0Frames: 0,
358
- txN1Frames: 0,
359
- txCancelled: 0,
360
-
361
- rxData: 0,
362
- rxAllFrames: 0,
363
- rxDataFrames: 0,
364
- rxAckFrames: 0,
365
- rxNakFrames: 0,
366
- rxReDataFrames: 0,
367
- // rxN0Frames: 0,
368
- rxN1Frames: 0,
369
- rxCancelled: 0,
370
-
371
- rxCrcErrors: 0,
372
- rxCommErrors: 0,
373
- rxTooShort: 0,
374
- rxTooLong: 0,
375
- rxBadControl: 0,
376
- rxBadLength: 0,
377
- rxBadAckNumber: 0,
378
- rxNoBuffer: 0,
379
- rxDuplicates: 0,
380
- rxOutOfSequence: 0,
381
- rxAckTimeouts: 0,
382
- };
383
-
384
- // All transmit buffers are put into txFree, and txQueue and reTxQueue are empty.
385
- this.txQueue.tail = undefined;
386
- this.reTxQueue.tail = undefined;
387
- this.txFree.link = undefined;
388
-
389
- for (let i = 0; i < TX_POOL_BUFFERS; i++) {
390
- this.txPool[i] = new EzspBuffer();
391
- this.txFree.freeBuffer(this.txPool[i]);
392
- }
393
-
394
- // All receive buffers are put into rxFree, and rxQueue is empty.
395
- this.rxQueue.tail = undefined;
396
- this.rxFree.link = undefined;
397
-
398
- for (let i = 0; i < EZSP_HOST_RX_POOL_SIZE; i++) {
399
- this.rxPool[i] = new EzspBuffer();
400
- this.rxFree.freeBuffer(this.rxPool[i]);
401
- }
402
- }
403
-
404
- /**
405
- * Check if port is valid, open, and not closing.
406
- */
407
- get portOpen(): boolean {
408
- if (this.closing) {
409
- return false;
410
- }
411
-
412
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
413
- if (SocketPortUtils.isTcpPath(this.portOptions.path!)) {
414
- return this.socketPort ? !this.socketPort.closed : false;
415
- }
416
-
417
- return this.serialPort ? this.serialPort.isOpen : false;
418
- }
419
-
420
- /**
421
- * Get max wait time before response is considered timed out.
422
- */
423
- get responseTimeout(): number {
424
- return ASH_MAX_TIMEOUTS * CONFIG_ACK_TIME_MAX;
425
- }
426
-
427
- /**
428
- * Indicates if the host is in the Connected state.
429
- * If not, the host and NCP cannot exchange DATA frames.
430
- * Note that this function does not actively confirm that communication with NCP is healthy, but simply returns its last known status.
431
- *
432
- * @returns
433
- * - true - host and NCP can exchange DATA frames
434
- * - false - host and NCP cannot now exchange DATA frames
435
- */
436
- get connected(): boolean {
437
- return (this.flags & Flag.CONNECTED) !== 0;
438
- }
439
-
440
- /**
441
- * Has nothing to do...
442
- */
443
- get idle(): boolean {
444
- return (
445
- !this.decodeInProgress && // don't have a partial frame
446
- // && (this.serial.readAvailable() === EzspStatus.NO_RX_DATA) // no rx data
447
- this.rxQueue.empty && // no rx frames to process
448
- !this.ncpHasCallbacks && // no pending callbacks
449
- this.flags === Flag.CONNECTED && // no pending ACKs, NAKs, etc.
450
- this.ackTx === this.frmRx && // do not need to send an ACK
451
- this.ackRx === this.frmTx && // not waiting to receive an ACK
452
- this.sendState === SendState.IDLE && // nothing being transmitted now
453
- this.txQueue.empty // nothing waiting to transmit
454
- // && this.serial.outputIsIdle() // nothing in OS buffers or UART FIFO
455
- );
456
- }
457
-
458
- /**
459
- * Init the serial or socket port and hook parser/writer.
460
- * NOTE: This is the only function that throws/rejects in the ASH layer (caught by resetNcp and turned into an EzspStatus).
461
- */
462
- private async initPort(): Promise<void> {
463
- await this.closePort(); // will do nothing if nothing's open
464
-
465
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
466
- if (!SocketPortUtils.isTcpPath(this.portOptions.path!)) {
467
- const serialOpts = {
468
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
469
- path: this.portOptions.path!,
470
- baudRate: typeof this.portOptions.baudRate === "number" ? this.portOptions.baudRate : 115200,
471
- rtscts: typeof this.portOptions.rtscts === "boolean" ? this.portOptions.rtscts : false,
472
- autoOpen: false,
473
- parity: "none" as const,
474
- stopBits: 1 as const,
475
- xon: false,
476
- xoff: false,
477
- };
478
-
479
- // enable software flow control if RTS/CTS not enabled in config
480
- if (!serialOpts.rtscts) {
481
- logger.info("RTS/CTS config is off, enabling software flow control.", NS);
482
- serialOpts.xon = true;
483
- serialOpts.xoff = true;
484
- }
485
-
486
- // @ts-expect-error Jest testing
487
- if (this.portOptions.binding !== undefined) {
488
- // @ts-expect-error Jest testing
489
- serialOpts.binding = this.portOptions.binding;
490
- }
491
-
492
- logger.debug(() => `Opening serial port with ${JSON.stringify(serialOpts)}`, NS);
493
- this.serialPort = new SerialPort(serialOpts);
494
-
495
- this.writer.pipe(this.serialPort);
496
- this.serialPort.pipe(this.parser);
497
- this.parser.on("data", this.onFrame.bind(this));
498
-
499
- try {
500
- await this.serialPort.asyncOpen();
501
- logger.info("Serial port opened", NS);
502
-
503
- this.serialPort.once("close", this.onPortClose.bind(this));
504
- this.serialPort.on("error", this.onPortError.bind(this));
505
- } catch (error) {
506
- await this.stop();
507
-
508
- throw error;
509
- }
510
- } else {
511
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
512
- const info = SocketPortUtils.parseTcpPath(this.portOptions.path!);
513
- logger.debug(`Opening TCP socket with ${info.host}:${info.port}`, NS);
514
-
515
- this.socketPort = new Socket();
516
-
517
- this.socketPort.setNoDelay(true);
518
- this.socketPort.setKeepAlive(true, 15000);
519
- this.writer.pipe(this.socketPort);
520
- this.socketPort.pipe(this.parser);
521
- this.parser.on("data", this.onFrame.bind(this));
522
-
523
- return await new Promise((resolve, reject): void => {
524
- const openError = async (err: Error): Promise<void> => {
525
- await this.stop();
526
-
527
- reject(err);
528
- };
529
-
530
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
531
- this.socketPort!.on("connect", () => {
532
- logger.debug("Socket connected", NS);
533
- });
534
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
535
- this.socketPort!.on("ready", (): void => {
536
- logger.info("Socket ready", NS);
537
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
538
- this.socketPort!.removeListener("error", openError);
539
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
540
- this.socketPort!.once("close", this.onPortClose.bind(this));
541
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
542
- this.socketPort!.on("error", this.onPortError.bind(this));
543
-
544
- resolve();
545
- });
546
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
547
- this.socketPort!.once("error", openError);
548
-
549
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
550
- this.socketPort!.connect(info.port, info.host);
551
- });
552
- }
553
- }
554
-
555
- /**
556
- * Handle port closing
557
- * @param err A boolean for Socket, an Error for serialport
558
- */
559
- private onPortClose(error: boolean | Error): void {
560
- logger.info("Port closed.", NS);
561
-
562
- if (error && this.flags !== 0) {
563
- logger.info(`Port close ${error}`, NS);
564
- this.flags = 0;
565
- this.emit("fatalError", EzspStatus.ERROR_SERIAL_INIT);
566
- }
567
- }
568
-
569
- /**
570
- * Handle port error
571
- * @param error
572
- */
573
- private onPortError(error: Error): void {
574
- logger.error(`Port ${error}`, NS);
575
- this.flags = 0;
576
- this.emit("fatalError", EzspStatus.ERROR_SERIAL_INIT);
577
- }
578
-
579
- /**
580
- * Handle received frame from AshParser.
581
- * @param buf
582
- */
583
- private onFrame(buffer: Buffer): void {
584
- const iCAN = buffer.lastIndexOf(AshReservedByte.CANCEL); // should only be one, but just in case...
585
-
586
- if (iCAN !== -1) {
587
- // ignore the cancel before RSTACK
588
- if (this.flags & Flag.CONNECTED) {
589
- this.counters.rxCancelled += 1;
590
-
591
- logger.warning(`Frame(s) in progress cancelled in [${buffer.toString("hex")}]`, NS);
592
- }
593
-
594
- // get rid of everything up to the CAN flag and start reading frame from there, no need to loop through bytes in vain
595
- buffer = buffer.subarray(iCAN + 1);
596
- }
597
-
598
- if (!buffer.length) {
599
- // skip any CANCEL that results in empty frame (have yet to see one, but just in case...)
600
- // shouldn't happen for any other reason, unless receiving bad stuff from port?
601
- logger.debug("Received empty frame. Skipping.", NS);
602
- return;
603
- }
604
-
605
- const status = this.receiveFrame(buffer);
606
-
607
- this.sendExec(); // always trigger to cover all cases
608
-
609
- if (status !== EzspStatus.SUCCESS && status !== EzspStatus.ASH_IN_PROGRESS && status !== EzspStatus.NO_RX_DATA) {
610
- logger.error(`Error while parsing received frame, status=${EzspStatus[status]}.`, NS);
611
- this.emit("fatalError", EzspStatus.HOST_FATAL_ERROR);
612
- return;
613
- }
614
- }
615
-
616
- /**
617
- * Initializes the ASH protocol, and waits until the NCP finishes rebooting, or a non-recoverable error occurs.
618
- *
619
- * @returns
620
- * - EzspStatus.SUCCESS
621
- * - EzspStatus.HOST_FATAL_ERROR
622
- * - EzspStatus.ASH_NCP_FATAL_ERROR)
623
- */
624
- public async start(): Promise<EzspStatus> {
625
- if (!this.portOpen || this.flags & Flag.CONNECTED) {
626
- return EzspStatus.ERROR_INVALID_CALL;
627
- }
628
-
629
- logger.info("======== ASH starting ========", NS);
630
-
631
- try {
632
- if (this.serialPort) {
633
- await this.serialPort.asyncFlush(); // clear read/write buffers
634
- } else {
635
- // XXX: Socket equiv?
636
- }
637
- } catch (err) {
638
- logger.error(`Error while flushing before start: ${err}`, NS);
639
- }
640
-
641
- // block til RSTACK, fatal error or timeout
642
- // NOTE: on average, this seems to take around 1000ms when successful
643
- for (let i = 0; i < CONFIG_TIME_RST; i += CONFIG_TIME_RST_CHECK) {
644
- this.sendExec();
645
-
646
- if (this.flags & Flag.CONNECTED) {
647
- logger.info("======== ASH started ========", NS);
648
-
649
- return EzspStatus.SUCCESS;
650
- }
651
-
652
- if (this.hostError !== EzspStatus.NO_ERROR || this.ncpError !== EzspStatus.NO_ERROR) {
653
- // don't wait for inevitable fail, bail early, let retry logic in EZSP layer do its thing
654
- break;
655
- }
656
-
657
- logger.debug(`Waiting for RSTACK... ${i}/${CONFIG_TIME_RST}`, NS);
658
- await wait(CONFIG_TIME_RST_CHECK);
659
- }
660
-
661
- return EzspStatus.HOST_FATAL_ERROR;
662
- }
663
-
664
- /**
665
- * Stops the ASH protocol - flushes and closes the serial port, clears all queues, stops timers, etc.
666
- */
667
- public async stop(): Promise<void> {
668
- this.closing = true;
669
-
670
- this.logCounters();
671
- await this.closePort();
672
-
673
- logger.info("======== ASH stopped ========", NS);
674
- }
675
-
676
- /**
677
- * Close port and remove listeners.
678
- * Does nothing if port not defined/open.
679
- */
680
- public async closePort(): Promise<void> {
681
- this.flags = 0;
682
-
683
- if (this.serialPort?.isOpen) {
684
- try {
685
- await this.serialPort.asyncFlushAndClose();
686
- } catch (err) {
687
- logger.error(`Failed to close serial port ${err}.`, NS);
688
- }
689
-
690
- this.serialPort.removeAllListeners();
691
- } else if (this.socketPort != null && !this.socketPort.closed) {
692
- this.socketPort.destroy();
693
- this.socketPort.removeAllListeners();
694
- }
695
- }
696
-
697
- /**
698
- * Initializes the ASH serial port and (if enabled) resets the NCP.
699
- * The method used to do the reset is specified by the the host configuration parameter resetMethod.
700
- *
701
- * When the reset method is sending a RST frame, the caller should retry NCP resets a few times if it fails.
702
- *
703
- * @returns
704
- * - EzspStatus.SUCCESS
705
- * - EzspStatus.HOST_FATAL_ERROR
706
- */
707
- public async resetNcp(): Promise<EzspStatus> {
708
- if (this.closing) {
709
- return EzspStatus.ERROR_INVALID_CALL;
710
- }
711
-
712
- logger.info("======== ASH Adapter reset ========", NS);
713
-
714
- // ask ncp to reset itself using RST frame
715
- try {
716
- if (!this.portOpen) {
717
- await this.initPort();
718
- }
719
-
720
- this.flags = Flag.RST | Flag.CAN;
721
-
722
- return EzspStatus.SUCCESS;
723
- } catch (err) {
724
- logger.error(`Failed to init port with error ${err}`, NS);
725
-
726
- this.hostError = EzspStatus.HOST_FATAL_ERROR;
727
-
728
- return this.hostError;
729
- }
730
- }
731
-
732
- /**
733
- * Adds a DATA frame to the transmit queue to send to the NCP.
734
- * Frames that are too long or too short will not be sent, and frames will not be added to the queue
735
- * if the host is not in the Connected state, or the NCP is not ready to receive a DATA frame or if there
736
- * is no room in the queue;
737
- *
738
- * @param len length of data field
739
- * @param inBuf array containing the data to be sent
740
- *
741
- * @returns
742
- * - EzspStatus.SUCCESS
743
- * - EzspStatus.NO_TX_SPACE
744
- * - EzspStatus.DATA_FRAME_TOO_SHORT
745
- * - EzspStatus.DATA_FRAME_TOO_LONG
746
- * - EzspStatus.NOT_CONNECTED
747
- */
748
- public send(len: number, inBuf: Buffer): EzspStatus {
749
- // Check for errors that might have been detected
750
- if (this.hostError !== EzspStatus.NO_ERROR) {
751
- return EzspStatus.HOST_FATAL_ERROR;
752
- }
753
-
754
- if (this.ncpError !== EzspStatus.NO_ERROR) {
755
- return EzspStatus.ASH_NCP_FATAL_ERROR;
756
- }
757
-
758
- // After verifying that the data field length is within bounds,
759
- // copies data frame to a buffer and appends it to the transmit queue.
760
- if (len < ASH_MIN_DATA_FIELD_LEN) {
761
- return EzspStatus.DATA_FRAME_TOO_SHORT;
762
- }
763
-
764
- if (len > ASH_MAX_DATA_FIELD_LEN) {
765
- return EzspStatus.DATA_FRAME_TOO_LONG;
766
- }
767
-
768
- if (!(this.flags & Flag.CONNECTED)) {
769
- return EzspStatus.NOT_CONNECTED;
770
- }
771
-
772
- const buffer = this.txFree.allocBuffer();
773
-
774
- if (buffer === undefined) {
775
- return EzspStatus.NO_TX_SPACE;
776
- }
777
-
778
- inBuf.copy(buffer.data, 0, 0, len);
779
-
780
- buffer.len = len;
781
-
782
- this.randomizeBuffer(buffer.data, buffer.len); // IN/OUT data
783
- this.txQueue.addTail(buffer);
784
- this.sendExec();
785
-
786
- return EzspStatus.SUCCESS;
787
- }
788
-
789
- /**
790
- * Manages outgoing communication to the NCP, including DATA frames as well as the frames used for
791
- * initialization and error detection and recovery.
792
- */
793
- public sendExec(): void {
794
- let outByte = 0x00;
795
- let inByte = 0x00;
796
- let len = 0;
797
- let buffer: EzspBuffer | undefined;
798
-
799
- // Check for received acknowledgement timer expiry
800
- if (this.ackTimerHasExpired()) {
801
- if (this.flags & Flag.CONNECTED) {
802
- const reTx = this.flags & Flag.RETX;
803
- const expectedFrm = reTx ? this.frmReTx : this.frmTx;
804
-
805
- if (this.ackRx !== expectedFrm) {
806
- this.counters.rxAckTimeouts += 1;
807
-
808
- this.adjustAckPeriod(true);
809
-
810
- logger.debug(`Timer expired waiting for ACK for ${reTx ? "frmReTx" : "frmTx"}=${expectedFrm}, ackRx=${this.ackRx}`, NS);
811
-
812
- if (++this.timeouts >= ASH_MAX_TIMEOUTS) {
813
- this.hostDisconnect(EzspStatus.ASH_ERROR_TIMEOUTS);
814
-
815
- return;
816
- }
817
-
818
- this.startRetransmission();
819
- } else {
820
- this.stopAckTimer();
821
- }
822
- } /* else {
823
- this.hostDisconnect(EzspStatus.ASH_ERROR_RESET_FAIL);
824
- }*/
825
- // let Ezsp layer retry logic handle timeout
826
- }
827
-
828
- while (this.writer.writeAvailable()) {
829
- // Send ASH_CAN character immediately, ahead of any other transmit data
830
- if (this.flags & Flag.CAN) {
831
- if (this.sendState === SendState.IDLE) {
832
- // sending RST or just woke NCP
833
- this.writer.writeByte(AshReservedByte.CANCEL);
834
- } else if (this.sendState === SendState.TX_DATA) {
835
- // cancel frame in progress
836
- this.counters.txCancelled += 1;
837
-
838
- this.writer.writeByte(AshReservedByte.CANCEL);
839
-
840
- this.stopAckTimer();
841
-
842
- this.sendState = SendState.IDLE;
843
- }
844
-
845
- this.flags &= ~Flag.CAN;
846
-
847
- continue;
848
- }
849
-
850
- switch (this.sendState) {
851
- case SendState.IDLE: {
852
- // In between frames - do some housekeeping and decide what to send next
853
- // If retransmitting, set the next frame to send to the last ackNum
854
- // received, then check to see if retransmission is now complete.
855
- if (this.flags & Flag.RETX) {
856
- if (withinRange(this.frmReTx, this.ackRx, this.frmTx)) {
857
- this.frmReTx = this.ackRx;
858
- }
859
-
860
- if (this.frmReTx === this.frmTx) {
861
- this.flags &= ~Flag.RETX;
862
-
863
- this.scrubReTxQueue();
864
- }
865
- }
866
-
867
- // restrain ncp if needed
868
- this.dataFrameFlowControl();
869
-
870
- // See if a short frame is flagged to be sent
871
- // The order of the tests below - RST, NAK and ACK -
872
- // sets the relative priority of sending these frame types.
873
- if (this.flags & Flag.RST) {
874
- this.txSHBuffer[0] = AshFrameType.RST;
875
-
876
- this.setAndStartAckTimer(CONFIG_TIME_RST);
877
-
878
- len = 1;
879
- this.flags &= ~(Flag.RST | Flag.NAK | Flag.ACK);
880
- this.sendState = SendState.SHFRAME;
881
- logger.debug("---> [FRAME type=RST]", NS);
882
- } else if (this.flags & (Flag.NAK | Flag.ACK)) {
883
- if (this.flags & Flag.NAK) {
884
- this.txSHBuffer[0] = AshFrameType.NAK + (this.frmRx << ASH_ACKNUM_BIT);
885
- this.flags &= ~(Flag.NRTX | Flag.NAK | Flag.ACK);
886
- logger.debug(`---> [FRAME type=NAK frmRx=${this.frmRx}](ackRx=${this.ackRx})`, NS);
887
- } else {
888
- this.txSHBuffer[0] = AshFrameType.ACK + (this.frmRx << ASH_ACKNUM_BIT);
889
- this.flags &= ~(Flag.NRTX | Flag.ACK);
890
- logger.debug(`---> [FRAME type=ACK frmRx=${this.frmRx}](ackRx=${this.ackRx})`, NS);
891
- }
892
-
893
- if (this.flags & Flag.NR) {
894
- this.txSHBuffer[0] |= ASH_NFLAG_MASK;
895
- this.flags |= Flag.NRTX;
896
-
897
- this.startNrTimer();
898
- }
899
-
900
- this.ackTx = this.frmRx;
901
- len = 1;
902
- this.sendState = SendState.SHFRAME;
903
- } else if (this.flags & Flag.RETX) {
904
- // Retransmitting DATA frames for error recovery
905
- // buffer assumed valid from loop logic
906
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
907
- buffer = this.reTxQueue.getNthEntry(mod8(this.frmTx - this.frmReTx))!;
908
- len = buffer.len + 1;
909
- this.txSHBuffer[0] = AshFrameType.DATA | (this.frmReTx << ASH_FRMNUM_BIT) | (this.frmRx << ASH_ACKNUM_BIT) | ASH_RFLAG_MASK;
910
- this.sendState = SendState.RETX_DATA;
911
- logger.debug(
912
- `---> [FRAME type=DATA_RETX frmReTx=${this.frmReTx} frmRx=${this.frmRx}](ackRx=${this.ackRx} frmTx=${this.frmTx})`,
913
- NS,
914
- );
915
- } else if (this.ackTx !== this.frmRx) {
916
- // An ACK should be generated
917
- this.flags |= Flag.ACK;
918
- break;
919
- } else if (!this.txQueue.empty && withinRange(this.ackRx, this.frmTx, this.ackRx + CONFIG_TX_K - 1)) {
920
- // Send a DATA frame if ready
921
- buffer = this.txQueue.head;
922
- len = buffer.len + 1;
923
-
924
- this.counters.txData += len - 1;
925
-
926
- this.txSHBuffer[0] = AshFrameType.DATA | (this.frmTx << ASH_FRMNUM_BIT) | (this.frmRx << ASH_ACKNUM_BIT);
927
- this.sendState = SendState.TX_DATA;
928
- logger.debug(`---> [FRAME type=DATA frmTx=${this.frmTx} frmRx=${this.frmRx}](ackRx=${this.ackRx})`, NS);
929
- } else {
930
- // Otherwise there's nothing to send
931
- this.writer.writeFlush();
932
-
933
- return;
934
- }
935
-
936
- this.countFrame(true);
937
-
938
- // Start frame - encodeByte() is inited by a non-zero length argument
939
- outByte = this.encodeByte(len, this.txSHBuffer[0]);
940
-
941
- this.writer.writeByte(outByte);
942
- break;
943
- }
944
-
945
- case SendState.SHFRAME: {
946
- // sending short frame
947
- if (this.txOffset !== 0xff) {
948
- inByte = this.txSHBuffer[this.txOffset];
949
- outByte = this.encodeByte(0, inByte);
950
-
951
- this.writer.writeByte(outByte);
952
- } else {
953
- this.sendState = SendState.IDLE;
954
- }
955
- break;
956
- }
957
-
958
- case SendState.TX_DATA:
959
- case SendState.RETX_DATA: {
960
- // sending OR resending data frame
961
- if (this.txOffset !== 0xff) {
962
- // buffer assumed valid from loop logic
963
- // biome-ignore lint/style/noNonNullAssertion: ignored using `--suppress`
964
- inByte = this.txOffset ? buffer!.data[this.txOffset - 1] : this.txSHBuffer[0];
965
- outByte = this.encodeByte(0, inByte);
966
-
967
- this.writer.writeByte(outByte);
968
- } else {
969
- if (this.sendState === SendState.TX_DATA) {
970
- this.frmTx = inc8(this.frmTx);
971
- buffer = this.txQueue.removeHead();
972
-
973
- this.reTxQueue.addTail(buffer);
974
- } else {
975
- this.frmReTx = inc8(this.frmReTx);
976
- }
977
-
978
- if (this.ackTimerIsNotRunning()) {
979
- this.startAckTimer();
980
- }
981
-
982
- this.ackTx = this.frmRx;
983
- this.sendState = SendState.IDLE;
984
- }
985
- break;
986
- }
987
- }
988
- }
989
-
990
- this.writer.writeFlush();
991
- }
992
-
993
- /**
994
- * Retrieve a frame and accept, reTx, reject, fail based on type & validity in current state.
995
- * @returns
996
- * - EzspStatus.SUCCESS On valid RSTACK or valid DATA frame.
997
- * - EzspStatus.ASH_IN_PROGRESS
998
- * - EzspStatus.NO_RX_DATA
999
- * - EzspStatus.NO_RX_SPACE
1000
- * - EzspStatus.HOST_FATAL_ERROR
1001
- * - EzspStatus.ASH_NCP_FATAL_ERROR
1002
- */
1003
- private receiveFrame(buffer: Buffer): EzspStatus {
1004
- // Check for errors that might have been detected
1005
- if (this.hostError !== EzspStatus.NO_ERROR) {
1006
- return EzspStatus.HOST_FATAL_ERROR;
1007
- }
1008
-
1009
- if (this.ncpError !== EzspStatus.NO_ERROR) {
1010
- return EzspStatus.ASH_NCP_FATAL_ERROR;
1011
- }
1012
-
1013
- let ackNum = 0;
1014
- let frmNum = 0;
1015
- let frameType: AshFrameType = AshFrameType.INVALID;
1016
-
1017
- // Read data from serial port and assemble a frame until complete, aborted
1018
- // due to an error, cancelled, or there is no more serial data available.
1019
- const status = this.readFrame(buffer);
1020
-
1021
- switch (status) {
1022
- case EzspStatus.SUCCESS:
1023
- break;
1024
- case EzspStatus.ASH_IN_PROGRESS:
1025
- // should have a complete frame by now, if not, don't process further
1026
- return EzspStatus.NO_RX_DATA;
1027
- case EzspStatus.ASH_CANCELLED:
1028
- // should have been taken out in onFrame
1029
- return this.hostDisconnect(status);
1030
- case EzspStatus.ASH_BAD_CRC:
1031
- this.counters.rxCrcErrors += 1;
1032
-
1033
- this.rejectFrame();
1034
- logger.error("Received frame with CRC error", NS);
1035
- return EzspStatus.NO_RX_DATA;
1036
- case EzspStatus.ASH_COMM_ERROR:
1037
- this.counters.rxCommErrors += 1;
1038
-
1039
- this.rejectFrame();
1040
- logger.error("Received frame with comm error", NS);
1041
- return EzspStatus.NO_RX_DATA;
1042
- case EzspStatus.ASH_TOO_SHORT:
1043
- this.counters.rxTooShort += 1;
1044
-
1045
- this.rejectFrame();
1046
- logger.error("Received frame shorter than minimum", NS);
1047
- return EzspStatus.NO_RX_DATA;
1048
- case EzspStatus.ASH_TOO_LONG:
1049
- this.counters.rxTooLong += 1;
1050
-
1051
- this.rejectFrame();
1052
- logger.error("Received frame longer than maximum", NS);
1053
- return EzspStatus.NO_RX_DATA;
1054
- case EzspStatus.ASH_ERROR_XON_XOFF:
1055
- return this.hostDisconnect(status);
1056
- default:
1057
- logger.error(`Unhandled error while receiving frame, status=${EzspStatus[status]}.`, NS);
1058
- return this.hostDisconnect(EzspStatus.HOST_FATAL_ERROR);
1059
- }
1060
-
1061
- // Got a complete frame - validate its control and length.
1062
- // On an error the type returned will be TYPE_INVALID.
1063
- frameType = this.getFrameType(this.rxSHBuffer[0], this.rxLen);
1064
-
1065
- // Free buffer allocated for a received frame if:
1066
- // DATA frame, and out of order
1067
- // DATA frame, and not in the CONNECTED state
1068
- // not a DATA frame
1069
- if (frameType === AshFrameType.DATA) {
1070
- if (!(this.flags & Flag.CONNECTED) || ashGetFrmNum(this.rxSHBuffer[0]) !== this.frmRx) {
1071
- this.freeAllocatedRxBuffer();
1072
- }
1073
- } else {
1074
- this.freeAllocatedRxBuffer();
1075
- }
1076
-
1077
- const frameTypeStr = AshFrameType[frameType];
1078
-
1079
- logger.debug(`<--- [FRAME type=${frameTypeStr}]`, NS);
1080
- this.countFrame(false);
1081
-
1082
- // Process frames received while not in the connected state -
1083
- // ignore everything except RSTACK and ERROR frames
1084
- if (!(this.flags & Flag.CONNECTED)) {
1085
- if (frameType === AshFrameType.RSTACK) {
1086
- // RSTACK frames have the ncp ASH version in the first data field byte,
1087
- // and the reset reason in the second byte
1088
- if (this.rxSHBuffer[1] !== ASH_VERSION) {
1089
- return this.hostDisconnect(EzspStatus.ASH_ERROR_VERSION);
1090
- }
1091
-
1092
- // Ignore a RSTACK if the reset reason doesn't match our reset method
1093
- if (this.rxSHBuffer[2] !== NcpFailedCode.RESET_SOFTWARE) {
1094
- return EzspStatus.ASH_IN_PROGRESS;
1095
- }
1096
-
1097
- this.ncpError = EzspStatus.NO_ERROR;
1098
-
1099
- this.stopAckTimer();
1100
-
1101
- this.timeouts = 0;
1102
-
1103
- this.setAckPeriod(CONFIG_ACK_TIME_INIT);
1104
-
1105
- this.flags = Flag.CONNECTED | Flag.ACK;
1106
-
1107
- logger.info("======== ASH connected ========", NS);
1108
-
1109
- return EzspStatus.SUCCESS;
1110
- }
1111
-
1112
- if (frameType === AshFrameType.ERROR) {
1113
- logger.error(`Received ERROR from adapter while connecting, with code=${NcpFailedCode[this.rxSHBuffer[2]]}.`, NS);
1114
- // let Ezsp retry logic handle error
1115
- // return this.ncpDisconnect(EzspStatus.ASH_NCP_FATAL_ERROR);
1116
- }
1117
-
1118
- return EzspStatus.ASH_IN_PROGRESS;
1119
- }
1120
-
1121
- // Connected - process the ackNum in ACK, NAK and DATA frames
1122
- if (frameType === AshFrameType.DATA || frameType === AshFrameType.ACK || frameType === AshFrameType.NAK) {
1123
- ackNum = ashGetACKNum(this.rxSHBuffer[0]);
1124
-
1125
- logger.debug(`<--- [FRAME type=${frameTypeStr} ackNum=${ackNum}](ackRx=${this.ackRx} frmTx=${this.frmTx})`, NS);
1126
-
1127
- if (!withinRange(this.ackRx, ackNum, this.frmTx)) {
1128
- this.counters.rxBadAckNumber += 1;
1129
-
1130
- logger.debug(`<-x- [FRAME type=${frameTypeStr} ackNum=${ackNum}] Invalid ACK num; not within <${this.ackRx}-${this.frmTx}>`, NS);
1131
-
1132
- frameType = AshFrameType.INVALID;
1133
- } else if (ackNum !== this.ackRx) {
1134
- // new frame(s) ACK'ed?
1135
- this.ackRx = ackNum;
1136
- this.timeouts = 0;
1137
-
1138
- if (this.flags & Flag.RETX) {
1139
- // start timer if unACK'ed frames
1140
- this.stopAckTimer();
1141
-
1142
- if (ackNum !== this.frmReTx) {
1143
- this.startAckTimer();
1144
- }
1145
- } else {
1146
- this.adjustAckPeriod(false); // factor ACK time into period
1147
-
1148
- if (ackNum !== this.frmTx) {
1149
- // if more unACK'ed frames,
1150
- this.startAckTimer(); // then restart ACK timer
1151
- }
1152
-
1153
- this.scrubReTxQueue(); // free buffer(s) in ReTx queue
1154
- }
1155
- }
1156
- }
1157
-
1158
- // Process frames received while connected
1159
- switch (frameType) {
1160
- case AshFrameType.DATA: {
1161
- frmNum = ashGetFrmNum(this.rxSHBuffer[0]);
1162
- const frameStr = `[FRAME type=${frameTypeStr} ackNum=${ackNum} frmNum=${frmNum}](frmRx=${this.frmRx})`;
1163
-
1164
- if (frmNum === this.frmRx) {
1165
- // is frame in sequence?
1166
- if (this.rxDataBuffer == null) {
1167
- // valid frame but no memory?
1168
- this.counters.rxNoBuffer += 1;
1169
-
1170
- logger.debug(`<-x- ${frameStr} No buffer available`, NS);
1171
-
1172
- this.rejectFrame();
1173
-
1174
- return EzspStatus.NO_RX_SPACE;
1175
- }
1176
-
1177
- if (this.rxSHBuffer[0] & ASH_RFLAG_MASK) {
1178
- // if retransmitted, force ACK
1179
- this.flags |= Flag.ACK;
1180
- }
1181
-
1182
- this.flags &= ~(Flag.REJ | Flag.NAK); // clear the REJ condition
1183
- this.frmRx = inc8(this.frmRx);
1184
-
1185
- this.randomizeBuffer(this.rxDataBuffer.data, this.rxDataBuffer.len); // IN/OUT data
1186
- this.rxQueue.addTail(this.rxDataBuffer); // add frame to receive queue
1187
-
1188
- logger.debug(`<--- ${frameStr} Added to rxQueue`, NS);
1189
-
1190
- this.counters.rxData += this.rxDataBuffer.len;
1191
-
1192
- setImmediate(() => this.emit("frame"));
1193
- return EzspStatus.SUCCESS;
1194
- }
1195
-
1196
- // frame is out of sequence
1197
- if (this.rxSHBuffer[0] & ASH_RFLAG_MASK) {
1198
- // if retransmitted, force ACK
1199
- this.counters.rxDuplicates += 1;
1200
- this.flags |= Flag.ACK;
1201
- } else {
1202
- // 1st OOS? then set REJ, send NAK
1203
- if ((this.flags & Flag.REJ) === 0) {
1204
- this.counters.rxOutOfSequence += 1;
1205
-
1206
- logger.debug(`<-x- ${frameStr} Out of sequence: expected ${this.frmRx}; got ${frmNum}.`, NS);
1207
- }
1208
-
1209
- this.rejectFrame();
1210
- }
1211
- break;
1212
- }
1213
- case AshFrameType.ACK:
1214
- // already fully processed
1215
- break;
1216
- case AshFrameType.NAK:
1217
- // start retransmission if needed
1218
- this.startRetransmission();
1219
-
1220
- break;
1221
- case AshFrameType.RSTACK:
1222
- // unexpected ncp reset
1223
- logger.error(`Received unexpected reset from adapter, with reason=${NcpFailedCode[this.rxSHBuffer[2]]}.`, NS);
1224
- this.ncpError = EzspStatus.ASH_NCP_FATAL_ERROR;
1225
-
1226
- return this.hostDisconnect(EzspStatus.ASH_ERROR_NCP_RESET);
1227
- case AshFrameType.ERROR:
1228
- // ncp error
1229
- logger.error(`Received ERROR from adapter, with code=${NcpFailedCode[this.rxSHBuffer[2]]}.`, NS);
1230
- return this.ncpDisconnect(EzspStatus.ASH_NCP_FATAL_ERROR);
1231
- case AshFrameType.INVALID:
1232
- // reject invalid frames
1233
- logger.debug(`<-x- [FRAME type=${frameTypeStr}] Rejecting. ${this.rxSHBuffer.toString("hex")}`, NS);
1234
-
1235
- this.rejectFrame();
1236
- break;
1237
- }
1238
-
1239
- return EzspStatus.ASH_IN_PROGRESS;
1240
- }
1241
-
1242
- /**
1243
- * If the last control byte received was a DATA control, and we are connected and not already in the reject condition,
1244
- * then send a NAK and set the reject condition.
1245
- */
1246
- private rejectFrame(): void {
1247
- if ((this.rxSHBuffer[0] & ASH_DFRAME_MASK) === AshFrameType.DATA && (this.flags & (Flag.REJ | Flag.CONNECTED)) === Flag.CONNECTED) {
1248
- this.flags |= Flag.REJ | Flag.NAK;
1249
- }
1250
- }
1251
-
1252
- /**
1253
- * Retrieve and process serial bytes.
1254
- * @returns
1255
- */
1256
- private readFrame(buffer: Buffer): EzspStatus {
1257
- let status: EzspStatus = EzspStatus.ERROR_INVALID_CALL; // no actual data to read, something's very wrong
1258
- let index = 0;
1259
- // let inByte: number = 0x00;
1260
- let outByte = 0x00;
1261
-
1262
- if (!this.decodeInProgress) {
1263
- this.rxLen = 0;
1264
- this.rxDataBuffer = undefined;
1265
- }
1266
-
1267
- for (const inByte of buffer) {
1268
- // 0xFF byte signals a callback is pending when between frames in synchronous (polled) callback mode.
1269
- if (!this.decodeInProgress && inByte === ASH_WAKE) {
1270
- if (this.ncpSleepEnabled) {
1271
- this.ncpHasCallbacks = true;
1272
- }
1273
-
1274
- status = EzspStatus.ASH_IN_PROGRESS;
1275
- continue;
1276
- }
1277
-
1278
- // Decode next input byte - note that many input bytes do not produce
1279
- // an output byte. Return on any error in decoding.
1280
- index = this.rxLen;
1281
- [status, outByte, this.rxLen] = this.decodeByte(inByte, outByte, this.rxLen);
1282
-
1283
- // discard an invalid frame
1284
- if (status !== EzspStatus.ASH_IN_PROGRESS && status !== EzspStatus.SUCCESS) {
1285
- this.freeAllocatedRxBuffer();
1286
-
1287
- break;
1288
- }
1289
-
1290
- // if input byte produced an output byte
1291
- if (this.rxLen !== index) {
1292
- if (this.rxLen <= SH_RX_BUFFER_LEN) {
1293
- // if a short frame, return in rxBuffer
1294
- this.rxSHBuffer[index] = outByte;
1295
- } else {
1296
- // if a longer DATA frame, allocate an EzspBuffer for it.
1297
- // (Note the control byte is always returned in shRxBuffer[0].
1298
- // Even if no buffer can be allocated, the control's ackNum must be processed.)
1299
- if (this.rxLen === SH_RX_BUFFER_LEN + 1) {
1300
- // alloc buffer, copy prior data
1301
- this.rxDataBuffer = this.rxFree.allocBuffer();
1302
-
1303
- if (this.rxDataBuffer !== undefined) {
1304
- // const len = SH_RX_BUFFER_LEN - 1;
1305
-
1306
- // (void) memcpy(this.rxDataBuffer.data, this.shRxBuffer + 1, SH_RX_BUFFER_LEN - 1);
1307
- this.rxSHBuffer.copy(this.rxDataBuffer.data, 0, 1, SH_RX_BUFFER_LEN);
1308
-
1309
- this.rxDataBuffer.len = SH_RX_BUFFER_LEN - 1;
1310
- }
1311
- }
1312
-
1313
- if (this.rxDataBuffer !== undefined) {
1314
- // copy next byte to buffer
1315
- this.rxDataBuffer.data[index - 1] = outByte; // -1 since control is omitted
1316
- this.rxDataBuffer.len = index;
1317
- }
1318
- }
1319
- }
1320
-
1321
- if (status !== EzspStatus.ASH_IN_PROGRESS) {
1322
- break;
1323
- }
1324
- }
1325
-
1326
- return status;
1327
- }
1328
-
1329
- /**
1330
- *
1331
- */
1332
- private freeAllocatedRxBuffer(): void {
1333
- if (this.rxDataBuffer !== undefined) {
1334
- this.rxFree.freeBuffer(this.rxDataBuffer);
1335
-
1336
- this.rxDataBuffer = undefined;
1337
- }
1338
- }
1339
-
1340
- /**
1341
- *
1342
- */
1343
- private scrubReTxQueue(): void {
1344
- let buffer: EzspBuffer;
1345
-
1346
- while (this.ackRx !== this.frmReTxHead) {
1347
- buffer = this.reTxQueue.removeHead();
1348
-
1349
- this.txFree.freeBuffer(buffer);
1350
-
1351
- this.frmReTxHead = inc8(this.frmReTxHead);
1352
- }
1353
- }
1354
-
1355
- /**
1356
- * If not already retransmitting, and there are unacked frames, start retransmitting after the last frame that was acked.
1357
- */
1358
- private startRetransmission(): void {
1359
- if (!(this.flags & Flag.RETX) && this.ackRx !== this.frmTx) {
1360
- this.stopAckTimer();
1361
-
1362
- this.frmReTx = this.ackRx;
1363
- this.flags |= Flag.RETX | Flag.CAN;
1364
- }
1365
- }
1366
-
1367
- /**
1368
- * Check free rx buffers to see whether able to receive DATA frames: set or clear NR flag appropriately.
1369
- * Inform ncp of our status using the nFlag in ACKs and NAKs.
1370
- * Note that not ready status must be refreshed if it persists beyond a maximum time limit.
1371
- */
1372
- private dataFrameFlowControl(): void {
1373
- if (this.flags & Flag.CONNECTED) {
1374
- // Set/clear NR flag based on the number of buffers free
1375
- if (this.rxFree.length < CONFIG_NR_LOW_LIMIT) {
1376
- this.flags |= Flag.NR;
1377
-
1378
- logger.warning("NOT READY - Signaling adapter", NS);
1379
- } else if (this.rxFree.length > CONFIG_NR_HIGH_LIMIT) {
1380
- this.flags &= ~Flag.NR;
1381
-
1382
- this.stopNrTimer(); // needed??
1383
- }
1384
-
1385
- // Force an ACK (or possibly NAK) if we need to send an updated nFlag
1386
- // due to either a changed NR status or to refresh a set nFlag
1387
- if (this.flags & Flag.NR) {
1388
- if (!(this.flags & Flag.NRTX) || this.nrTimerHasExpired()) {
1389
- this.flags |= Flag.ACK;
1390
-
1391
- this.startNrTimer();
1392
- }
1393
- } else {
1394
- this.nrTimerHasExpired(); // ensure timer checked often
1395
-
1396
- if (this.flags & Flag.NRTX) {
1397
- this.flags |= Flag.ACK;
1398
-
1399
- this.stopNrTimer(); // needed???
1400
- }
1401
- }
1402
- } else {
1403
- this.stopNrTimer();
1404
-
1405
- this.flags &= ~(Flag.NRTX | Flag.NR);
1406
- }
1407
- }
1408
-
1409
- /**
1410
- * Sets a fatal error state at the Host level.
1411
- * @param error
1412
- * @returns EzspStatus.HOST_FATAL_ERROR
1413
- */
1414
- private hostDisconnect(error: EzspStatus): EzspStatus {
1415
- this.flags = 0;
1416
- this.hostError = error;
1417
-
1418
- logger.error(`ASH disconnected: ${EzspStatus[error]} | Adapter status: ${EzspStatus[this.ncpError]}`, NS);
1419
-
1420
- return EzspStatus.HOST_FATAL_ERROR;
1421
- }
1422
-
1423
- /**
1424
- * Sets a fatal error state at the NCP level. Will require a reset.
1425
- * @param error
1426
- * @returns EzspStatus.ASH_NCP_FATAL_ERROR
1427
- */
1428
- private ncpDisconnect(error: EzspStatus): EzspStatus {
1429
- this.flags = 0;
1430
- this.ncpError = error;
1431
-
1432
- logger.error(`ASH disconnected | Adapter status: ${EzspStatus[this.ncpError]}`, NS);
1433
-
1434
- return EzspStatus.ASH_NCP_FATAL_ERROR;
1435
- }
1436
-
1437
- /**
1438
- * Same as randomizeArray(0, buffer, len).
1439
- * Returns buffer as-is if randomize is OFF.
1440
- * @param buffer IN/OUT
1441
- * @param len
1442
- */
1443
- public randomizeBuffer(buffer: Buffer, len: number): void {
1444
- // If enabled, exclusive-OR buffer data with a pseudo-random sequence
1445
- if (CONFIG_RANDOMIZE) {
1446
- this.randomizeArray(0, buffer, len); // zero inits the random sequence
1447
- }
1448
- }
1449
-
1450
- /**
1451
- * Randomizes array contents by XORing with an 8-bit pseudo random sequence.
1452
- * This reduces the likelihood that byte-stuffing will greatly increase the size of the payload.
1453
- * (This could happen if a DATA frame contained repeated instances of the same reserved byte value.)
1454
- *
1455
- * @param seed zero initializes the random sequence a non-zero value continues from a previous invocation
1456
- * @param buf IN/OUT pointer to the array whose contents will be randomized
1457
- * @param len number of bytes in the array to modify
1458
- * @returns last value of the sequence.
1459
- * If a buffer is processed in two or more chunks, as with linked buffers,
1460
- * this value should be passed back as the value of the seed argument
1461
- */
1462
- public randomizeArray(seed: number, buf: Buffer, len: number): number {
1463
- let outIdx = 0;
1464
-
1465
- if (seed === 0) {
1466
- seed = LFSR_SEED;
1467
- }
1468
-
1469
- while (len--) {
1470
- // *buf++ ^= seed;
1471
- buf[outIdx++] ^= seed;
1472
-
1473
- seed = seed & 1 ? (seed >> 1) ^ LFSR_POLY : seed >> 1;
1474
- }
1475
-
1476
- return seed;
1477
- }
1478
-
1479
- /**
1480
- * Get the frame type from the control byte and validate it against the frame length.
1481
- * @param control
1482
- * @param len Frame length
1483
- * @returns AshFrameType.INVALID if bad control/length otherwise the frame type.
1484
- */
1485
- public getFrameType(control: number, len: number): AshFrameType {
1486
- if (control === AshFrameType.RSTACK) {
1487
- if (len === ASH_FRAME_LEN_RSTACK) {
1488
- return AshFrameType.RSTACK;
1489
- }
1490
- } else if (control === AshFrameType.ERROR) {
1491
- if (len === ASH_FRAME_LEN_ERROR) {
1492
- return AshFrameType.ERROR;
1493
- }
1494
- } else if ((control & ASH_DFRAME_MASK) === AshFrameType.DATA) {
1495
- if (len >= ASH_FRAME_LEN_DATA_MIN) {
1496
- return AshFrameType.DATA;
1497
- }
1498
- } else if ((control & ASH_SHFRAME_MASK) === AshFrameType.ACK) {
1499
- if (len === ASH_FRAME_LEN_ACK) {
1500
- return AshFrameType.ACK;
1501
- }
1502
- } else if ((control & ASH_SHFRAME_MASK) === AshFrameType.NAK) {
1503
- if (len === ASH_FRAME_LEN_NAK) {
1504
- return AshFrameType.NAK;
1505
- }
1506
- } else {
1507
- this.counters.rxBadControl += 1;
1508
- logger.debug(`Frame illegal control ${control}.`, NS); // EzspStatus.ASH_BAD_CONTROL
1509
-
1510
- return AshFrameType.INVALID;
1511
- }
1512
-
1513
- this.counters.rxBadLength += 1;
1514
- logger.debug(`Frame illegal length ${len} for control ${control}.`, NS); // EzspStatus.ASH_BAD_LENGTH
1515
-
1516
- return AshFrameType.INVALID;
1517
- }
1518
-
1519
- /**
1520
- * Encode byte for sending.
1521
- * @param len Start a new frame if non-zero
1522
- * @param byte
1523
- * @returns outByte
1524
- */
1525
- private encodeByte(len: number, byte: number): number {
1526
- // start a new frame if len is non-zero
1527
- if (len) {
1528
- this.encodeCount = len;
1529
- this.txOffset = 0;
1530
- this.encodeState = 0;
1531
- this.encodeEscFlag = false;
1532
- this.encodeCrc = 0xffff;
1533
- }
1534
-
1535
- // was an escape last time?
1536
- if (this.encodeEscFlag) {
1537
- this.encodeEscFlag = false;
1538
-
1539
- // send data byte with bit flipped
1540
- return this.encodeFlip;
1541
- }
1542
-
1543
- // control and data field bytes
1544
- if (this.encodeState === 0) {
1545
- this.encodeCrc = halCommonCrc16(byte, this.encodeCrc);
1546
-
1547
- if (--this.encodeCount === 0) {
1548
- this.encodeState = 1;
1549
- } else {
1550
- ++this.txOffset;
1551
- }
1552
-
1553
- return this.encodeStuffByte(byte);
1554
- }
1555
-
1556
- if (this.encodeState === 1) {
1557
- // CRC high byte
1558
- this.encodeState = 2;
1559
-
1560
- return this.encodeStuffByte(this.encodeCrc >> 8);
1561
- }
1562
-
1563
- if (this.encodeState === 2) {
1564
- // CRC low byte
1565
- this.encodeState = 3;
1566
-
1567
- return this.encodeStuffByte(this.encodeCrc & 0xff);
1568
- }
1569
-
1570
- this.txOffset = 0xff;
1571
-
1572
- return AshReservedByte.FLAG;
1573
- }
1574
-
1575
- /**
1576
- * Stuff byte as defined by ASH protocol.
1577
- * @param byte
1578
- * @returns
1579
- */
1580
- private encodeStuffByte(byte: number): number {
1581
- if (AshReservedByte[byte] != null) {
1582
- // is special byte
1583
- this.encodeEscFlag = true;
1584
- this.encodeFlip = byte ^ ASH_FLIP;
1585
-
1586
- return AshReservedByte.ESCAPE;
1587
- }
1588
-
1589
- return byte;
1590
- }
1591
-
1592
- /**
1593
- * Decode received byte.
1594
- * @param byte
1595
- * @param inByte IN/OUT
1596
- * @param inLen IN/OUT
1597
- * @returns [EzspStatus, outByte, outLen]
1598
- * - EzspStatus.ASH_IN_PROGRESS
1599
- * - EzspStatus.ASH_COMM_ERROR
1600
- * - EzspStatus.ASH_BAD_CRC
1601
- * - EzspStatus.ASH_TOO_SHORT
1602
- * - EzspStatus.ASH_TOO_LONG
1603
- * - EzspStatus.SUCCESS
1604
- * - EzspStatus.ASH_CANCELLED
1605
- * - EzspStatus.ASH_ERROR_XON_XOFF
1606
- */
1607
- private decodeByte(byte: number, inByte: number, inLen: number): [EzspStatus, outByte: number, outLen: number] {
1608
- let status: EzspStatus = EzspStatus.ASH_IN_PROGRESS;
1609
-
1610
- if (!this.decodeInProgress) {
1611
- this.decodeLen = 0;
1612
- this.decodeByte1 = 0;
1613
- this.decodeByte2 = 0;
1614
- this.decodeFlip = 0;
1615
- this.decodeCrc = 0xffff;
1616
- }
1617
-
1618
- switch (byte) {
1619
- case AshReservedByte.FLAG:
1620
- // flag byte (frame delimiter)
1621
- if (this.decodeLen === 0) {
1622
- // if no frame data, not end flag, so ignore it
1623
- this.decodeFlip = 0; // ignore isolated data escape between flags
1624
- break;
1625
- }
1626
-
1627
- if (this.decodeLen === 0xff) {
1628
- status = EzspStatus.ASH_COMM_ERROR;
1629
- } else if (this.decodeCrc !== (this.decodeByte2 << 8) + this.decodeByte1) {
1630
- status = EzspStatus.ASH_BAD_CRC;
1631
- } else if (this.decodeLen < ASH_MIN_FRAME_WITH_CRC_LEN) {
1632
- status = EzspStatus.ASH_TOO_SHORT;
1633
- } else if (this.decodeLen > ASH_MAX_FRAME_WITH_CRC_LEN) {
1634
- status = EzspStatus.ASH_TOO_LONG;
1635
- } else {
1636
- status = EzspStatus.SUCCESS;
1637
- }
1638
- break;
1639
- case AshReservedByte.ESCAPE:
1640
- // byte stuffing escape byte
1641
- this.decodeFlip = ASH_FLIP;
1642
- break;
1643
- case AshReservedByte.CANCEL:
1644
- // cancel frame without an error
1645
- status = EzspStatus.ASH_CANCELLED;
1646
- break;
1647
- case AshReservedByte.SUBSTITUTE:
1648
- // discard remainder of frame
1649
- this.decodeLen = 0xff; // special value flags low level comm error
1650
- break;
1651
- case AshReservedByte.XON:
1652
- case AshReservedByte.XOFF:
1653
- // If host is using RTS/CTS, ignore any XON/XOFFs received from the NCP.
1654
- // If using XON/XOFF, the host driver must remove them from the input stream.
1655
- // If it doesn't, it probably means the driver isn't setup for XON/XOFF,
1656
- // so issue an error to flag the serial port driver problem.
1657
- if (this.serialPort != null && !this.serialPort.settings.rtscts) {
1658
- status = EzspStatus.ASH_ERROR_XON_XOFF;
1659
- }
1660
- break;
1661
- default:
1662
- // a normal byte
1663
- byte ^= this.decodeFlip;
1664
- this.decodeFlip = 0;
1665
-
1666
- if (this.decodeLen <= ASH_MAX_FRAME_WITH_CRC_LEN) {
1667
- // limit length to max + 1
1668
- ++this.decodeLen;
1669
- }
1670
-
1671
- if (this.decodeLen > ASH_CRC_LEN) {
1672
- // compute frame CRC even if too long
1673
- this.decodeCrc = halCommonCrc16(this.decodeByte2, this.decodeCrc);
1674
-
1675
- if (this.decodeLen <= ASH_MAX_FRAME_WITH_CRC_LEN) {
1676
- // store to only max len
1677
- inByte = this.decodeByte2;
1678
- inLen = this.decodeLen - ASH_CRC_LEN; // CRC is not output, reduce length
1679
- }
1680
- }
1681
-
1682
- this.decodeByte2 = this.decodeByte1;
1683
- this.decodeByte1 = byte;
1684
- break;
1685
- }
1686
-
1687
- this.decodeInProgress = status === EzspStatus.ASH_IN_PROGRESS;
1688
-
1689
- return [status, inByte, inLen];
1690
- }
1691
-
1692
- /**
1693
- * Starts the Not Ready timer
1694
- *
1695
- * On the host, this times nFlag refreshing when the host doesn't have room for callbacks for a prolonged period.
1696
- *
1697
- * On the NCP, if this times out the NCP resumes sending callbacks.
1698
- */
1699
- private startNrTimer(): void {
1700
- this.nrTimer = Date.now() + CONFIG_NR_TIME;
1701
- }
1702
-
1703
- /**
1704
- * Stop Not Ready timer (set to 0).
1705
- */
1706
- private stopNrTimer(): void {
1707
- this.nrTimer = 0;
1708
- }
1709
-
1710
- /**
1711
- * Tests whether the Not Ready timer has expired or has stopped. If expired, it is stopped.
1712
- *
1713
- * @returns true if the Not Ready timer has expired or stopped
1714
- */
1715
- private nrTimerHasExpired(): boolean {
1716
- if (this.nrTimer) {
1717
- if (Date.now() - this.nrTimer >= 0) {
1718
- this.nrTimer = 0;
1719
- }
1720
- }
1721
-
1722
- return !this.nrTimer;
1723
- }
1724
-
1725
- /**
1726
- * Sets the acknowledgement timer period (in msec) and stops the timer.
1727
- */
1728
- private setAckPeriod(msec: number): void {
1729
- this.ackPeriod = msec;
1730
- this.ackTimer = 0;
1731
- }
1732
-
1733
- /**
1734
- * Sets the acknowledgement timer period (in msec), and starts the timer running.
1735
- */
1736
- private setAndStartAckTimer(msec: number): void {
1737
- this.setAckPeriod(msec);
1738
- this.startAckTimer();
1739
- }
1740
-
1741
- /**
1742
- * Adapts the acknowledgement timer period to the observed ACK delay.
1743
- * If the timer is not running, it does nothing.
1744
- * If the timer has expired, the timeout period is doubled.
1745
- * If the timer has not expired, the elapsed time is fed into simple
1746
- *
1747
- * IIR filter:
1748
- * T[n+1] = (7*T[n] + elapsedTime) / 8
1749
- *
1750
- * The timeout period, ackPeriod, is limited such that:
1751
- * config.ackTimeMin <= ackPeriod <= config.ackTimeMax.
1752
- *
1753
- * The acknowledgement timer is always stopped by this function.
1754
- *
1755
- * @param expired true if timer has expired
1756
- */
1757
- private adjustAckPeriod(expired: boolean): void {
1758
- if (expired) {
1759
- // if expired, double the period
1760
- this.ackPeriod += this.ackPeriod;
1761
- } else if (this.ackTimer) {
1762
- // adjust period only if running
1763
- // time elapsed since timer was started
1764
- let temp: number = this.ackPeriod;
1765
- // compute time to receive acknowledgement, then stop timer
1766
- const lastAckTime: number = Date.now() - this.ackTimer;
1767
- temp = (temp << 3) - temp;
1768
- temp += lastAckTime << 2;
1769
- temp >>= 3;
1770
- this.ackPeriod = temp & 0xffff;
1771
- }
1772
-
1773
- // keep ackPeriod within limits
1774
- if (this.ackPeriod > CONFIG_ACK_TIME_MAX) {
1775
- this.ackPeriod = CONFIG_ACK_TIME_MAX;
1776
- } else if (this.ackPeriod < CONFIG_ACK_TIME_MIN) {
1777
- this.ackPeriod = CONFIG_ACK_TIME_MIN;
1778
- }
1779
-
1780
- this.ackTimer = 0; // always stop the timer
1781
- }
1782
-
1783
- /**
1784
- * Sets ACK Timer to the specified period and starts it running.
1785
- */
1786
- private startAckTimer(): void {
1787
- this.ackTimer = Date.now();
1788
- }
1789
-
1790
- /**
1791
- * Stops and clears ACK Timer.
1792
- */
1793
- private stopAckTimer(): void {
1794
- this.ackTimer = 0;
1795
- }
1796
-
1797
- /**
1798
- * Indicates whether or not ACK Timer has expired.
1799
- * If the timer is stopped (0) then it is not expired.
1800
- *
1801
- * @returns
1802
- */
1803
- private ackTimerHasExpired(): boolean {
1804
- if (this.ackTimer === 0) {
1805
- // if timer is not running, return false
1806
- return false;
1807
- }
1808
-
1809
- // return ((halCommonGetInt16uMillisecondTick() - this.ackTimer) >= this.ackPeriod);
1810
- return Date.now() - this.ackTimer >= this.ackPeriod;
1811
- }
1812
-
1813
- /**
1814
- * Indicates whether or not ACK Timer is currently running (!= 0).
1815
- * The timer may be running even if expired.
1816
- */
1817
- private ackTimerIsNotRunning(): boolean {
1818
- return this.ackTimer === 0;
1819
- }
1820
-
1821
- /**
1822
- * Increase counters based on frame type and direction.
1823
- * @param sent True if frame being sent, false if being received.
1824
- */
1825
- private countFrame(sent: boolean): void {
1826
- let control: number;
1827
-
1828
- if (sent) {
1829
- control = this.txSHBuffer[0];
1830
- this.counters.txAllFrames += 1;
1831
- } else {
1832
- control = this.rxSHBuffer[0];
1833
- this.counters.rxAllFrames += 1;
1834
- }
1835
-
1836
- if ((control & ASH_DFRAME_MASK) === AshFrameType.DATA) {
1837
- if (sent) {
1838
- if (control & ASH_RFLAG_MASK) {
1839
- this.counters.txReDataFrames += 1;
1840
- } else {
1841
- this.counters.txDataFrames += 1;
1842
- }
1843
- } else {
1844
- if (control & ASH_RFLAG_MASK) {
1845
- this.counters.rxReDataFrames += 1;
1846
- } else {
1847
- this.counters.rxDataFrames += 1;
1848
- }
1849
- }
1850
- } else if ((control & ASH_SHFRAME_MASK) === AshFrameType.ACK) {
1851
- if (sent) {
1852
- this.counters.txAckFrames += 1;
1853
-
1854
- if (control & ASH_NFLAG_MASK) {
1855
- this.counters.txN1Frames += 1;
1856
- } /* else {
1857
- this.counters.txN0Frames += 1;
1858
- }*/
1859
- } else {
1860
- this.counters.rxAckFrames += 1;
1861
-
1862
- if (control & ASH_NFLAG_MASK) {
1863
- this.counters.rxN1Frames += 1;
1864
- } /* else {
1865
- this.counters.rxN0Frames += 1;
1866
- }*/
1867
- }
1868
- } else if ((control & ASH_SHFRAME_MASK) === AshFrameType.NAK) {
1869
- if (sent) {
1870
- this.counters.txNakFrames += 1;
1871
-
1872
- if (control & ASH_NFLAG_MASK) {
1873
- this.counters.txN1Frames += 1;
1874
- } /* else {
1875
- this.counters.txN0Frames += 1;
1876
- }*/
1877
- } else {
1878
- this.counters.rxNakFrames += 1;
1879
-
1880
- if (control & ASH_NFLAG_MASK) {
1881
- this.counters.rxN1Frames += 1;
1882
- } /* else {
1883
- this.counters.rxN0Frames += 1;
1884
- }*/
1885
- }
1886
- }
1887
- }
1888
-
1889
- /**
1890
- * Read and clear ASH layer counters in the same manner as the NCP ones.
1891
- * @returns
1892
- */
1893
- public readAndClearCounters(): number[] {
1894
- const counters = [
1895
- this.counters.txData,
1896
- this.counters.txAllFrames,
1897
- this.counters.txDataFrames,
1898
- this.counters.txAckFrames,
1899
- this.counters.txNakFrames,
1900
- this.counters.txReDataFrames,
1901
- this.counters.txN1Frames,
1902
- this.counters.txCancelled,
1903
-
1904
- this.counters.rxData,
1905
- this.counters.rxAllFrames,
1906
- this.counters.rxDataFrames,
1907
- this.counters.rxAckFrames,
1908
- this.counters.rxNakFrames,
1909
- this.counters.rxReDataFrames,
1910
- this.counters.rxN1Frames,
1911
- this.counters.rxCancelled,
1912
-
1913
- this.counters.rxCrcErrors,
1914
- this.counters.rxCommErrors,
1915
- this.counters.rxTooShort,
1916
- this.counters.rxTooLong,
1917
- this.counters.rxBadControl,
1918
- this.counters.rxBadLength,
1919
- this.counters.rxBadAckNumber,
1920
- this.counters.rxNoBuffer,
1921
- this.counters.rxDuplicates,
1922
- this.counters.rxOutOfSequence,
1923
- this.counters.rxAckTimeouts,
1924
- ];
1925
-
1926
- for (const c in this.counters) {
1927
- this.counters[c as keyof UartAshCounters] = 0;
1928
- }
1929
-
1930
- return counters;
1931
- }
1932
-
1933
- /**
1934
- * Log counters (pretty-formatted) as they are since last time they were cleared.
1935
- * Used on ASH layer stop to get 'pre-stop state'.
1936
- */
1937
- private logCounters(): void {
1938
- logger.info("ASH COUNTERS since last clear:", NS);
1939
- logger.info(` Total frames: RX=${this.counters.rxAllFrames}, TX=${this.counters.txAllFrames}`, NS);
1940
- logger.info(` Cancelled : RX=${this.counters.rxCancelled}, TX=${this.counters.txCancelled}`, NS);
1941
- logger.info(` DATA frames : RX=${this.counters.rxDataFrames}, TX=${this.counters.txDataFrames}`, NS);
1942
- logger.info(` DATA bytes : RX=${this.counters.rxData}, TX=${this.counters.txData}`, NS);
1943
- logger.info(` Retry frames: RX=${this.counters.rxReDataFrames}, TX=${this.counters.txReDataFrames}`, NS);
1944
- logger.info(` ACK frames : RX=${this.counters.rxAckFrames}, TX=${this.counters.txAckFrames}`, NS);
1945
- logger.info(` NAK frames : RX=${this.counters.rxNakFrames}, TX=${this.counters.txNakFrames}`, NS);
1946
- logger.info(` nRdy frames : RX=${this.counters.rxN1Frames}, TX=${this.counters.txN1Frames}`, NS);
1947
-
1948
- logger.info(` CRC errors : RX=${this.counters.rxCrcErrors}`, NS);
1949
- logger.info(` Comm errors : RX=${this.counters.rxCommErrors}`, NS);
1950
- logger.info(` Length < minimum: RX=${this.counters.rxTooShort}`, NS);
1951
- logger.info(` Length > maximum: RX=${this.counters.rxTooLong}`, NS);
1952
- logger.info(` Bad controls : RX=${this.counters.rxBadControl}`, NS);
1953
- logger.info(` Bad lengths : RX=${this.counters.rxBadLength}`, NS);
1954
- logger.info(` Bad ACK numbers : RX=${this.counters.rxBadAckNumber}`, NS);
1955
- logger.info(` Out of buffers : RX=${this.counters.rxNoBuffer}`, NS);
1956
- logger.info(` Retry dupes : RX=${this.counters.rxDuplicates}`, NS);
1957
- logger.info(` Out of sequence : RX=${this.counters.rxOutOfSequence}`, NS);
1958
- logger.info(` ACK timeouts : RX=${this.counters.rxAckTimeouts}`, NS);
1959
- }
1960
- }