@robdobsn/raftjs 1.7.8 → 1.10.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/.editorconfig +14 -0
  2. package/.gitattributes +11 -0
  3. package/.nvmrc +1 -0
  4. package/TODO.md +1 -0
  5. package/dist/react-native/RaftAttributeHandler.d.ts +14 -0
  6. package/dist/react-native/RaftAttributeHandler.js +375 -0
  7. package/dist/react-native/RaftAttributeHandler.js.map +1 -0
  8. package/dist/react-native/RaftChannel.d.ts +20 -0
  9. package/dist/react-native/RaftChannel.js +12 -0
  10. package/dist/react-native/RaftChannel.js.map +1 -0
  11. package/dist/react-native/RaftChannelBLE.native.d.ts +95 -0
  12. package/dist/react-native/RaftChannelBLE.native.js +483 -0
  13. package/dist/react-native/RaftChannelBLE.native.js.map +1 -0
  14. package/dist/react-native/RaftChannelBLE.web.d.ts +40 -0
  15. package/dist/react-native/RaftChannelBLE.web.js +302 -0
  16. package/dist/react-native/RaftChannelBLE.web.js.map +1 -0
  17. package/dist/react-native/RaftChannelBLEFactory.d.ts +10 -0
  18. package/dist/react-native/RaftChannelBLEFactory.js +17 -0
  19. package/dist/react-native/RaftChannelBLEFactory.js.map +1 -0
  20. package/dist/react-native/RaftChannelBLEScanner.native.d.ts +18 -0
  21. package/dist/react-native/RaftChannelBLEScanner.native.js +138 -0
  22. package/dist/react-native/RaftChannelBLEScanner.native.js.map +1 -0
  23. package/dist/react-native/RaftChannelSimulated.d.ts +42 -0
  24. package/dist/react-native/RaftChannelSimulated.js +1000 -0
  25. package/dist/react-native/RaftChannelSimulated.js.map +1 -0
  26. package/dist/react-native/RaftChannelWebSerial.d.ts +39 -0
  27. package/dist/react-native/RaftChannelWebSerial.js +329 -0
  28. package/dist/react-native/RaftChannelWebSerial.js.map +1 -0
  29. package/dist/react-native/RaftChannelWebSocket.d.ts +30 -0
  30. package/dist/react-native/RaftChannelWebSocket.js +222 -0
  31. package/dist/react-native/RaftChannelWebSocket.js.map +1 -0
  32. package/dist/react-native/RaftCommsStats.d.ts +39 -0
  33. package/dist/react-native/RaftCommsStats.js +128 -0
  34. package/dist/react-native/RaftCommsStats.js.map +1 -0
  35. package/dist/react-native/RaftConnEvents.d.ts +39 -0
  36. package/dist/react-native/RaftConnEvents.js +54 -0
  37. package/dist/react-native/RaftConnEvents.js.map +1 -0
  38. package/dist/react-native/RaftConnector.d.ts +248 -0
  39. package/dist/react-native/RaftConnector.js +658 -0
  40. package/dist/react-native/RaftConnector.js.map +1 -0
  41. package/dist/react-native/RaftCustomAttrHandler.d.ts +6 -0
  42. package/dist/react-native/RaftCustomAttrHandler.js +93 -0
  43. package/dist/react-native/RaftCustomAttrHandler.js.map +1 -0
  44. package/dist/react-native/RaftDeviceInfo.d.ts +71 -0
  45. package/dist/react-native/RaftDeviceInfo.js +50 -0
  46. package/dist/react-native/RaftDeviceInfo.js.map +1 -0
  47. package/dist/react-native/RaftDeviceManager.d.ts +61 -0
  48. package/dist/react-native/RaftDeviceManager.js +665 -0
  49. package/dist/react-native/RaftDeviceManager.js.map +1 -0
  50. package/dist/react-native/RaftDeviceMgrIF.d.ts +15 -0
  51. package/dist/react-native/RaftDeviceMgrIF.js +11 -0
  52. package/dist/react-native/RaftDeviceMgrIF.js.map +1 -0
  53. package/dist/react-native/RaftDeviceMsg.d.ts +9 -0
  54. package/dist/react-native/RaftDeviceMsg.js +11 -0
  55. package/dist/react-native/RaftDeviceMsg.js.map +1 -0
  56. package/dist/react-native/RaftDeviceStates.d.ts +37 -0
  57. package/dist/react-native/RaftDeviceStates.js +60 -0
  58. package/dist/react-native/RaftDeviceStates.js.map +1 -0
  59. package/dist/react-native/RaftFileHandler.d.ts +52 -0
  60. package/dist/react-native/RaftFileHandler.js +502 -0
  61. package/dist/react-native/RaftFileHandler.js.map +1 -0
  62. package/dist/react-native/RaftLog.d.ts +22 -0
  63. package/dist/react-native/RaftLog.js +63 -0
  64. package/dist/react-native/RaftLog.js.map +1 -0
  65. package/dist/react-native/RaftMiniHDLC.d.ts +18 -0
  66. package/dist/react-native/RaftMiniHDLC.js +383 -0
  67. package/dist/react-native/RaftMiniHDLC.js.map +1 -0
  68. package/dist/react-native/RaftMsgHandler.d.ts +62 -0
  69. package/dist/react-native/RaftMsgHandler.js +511 -0
  70. package/dist/react-native/RaftMsgHandler.js.map +1 -0
  71. package/dist/react-native/RaftMsgTrackInfo.d.ts +17 -0
  72. package/dist/react-native/RaftMsgTrackInfo.js +42 -0
  73. package/dist/react-native/RaftMsgTrackInfo.js.map +1 -0
  74. package/dist/react-native/RaftProtocolDefs.d.ts +30 -0
  75. package/dist/react-native/RaftProtocolDefs.js +48 -0
  76. package/dist/react-native/RaftProtocolDefs.js.map +1 -0
  77. package/dist/react-native/RaftStreamHandler.d.ts +38 -0
  78. package/dist/react-native/RaftStreamHandler.js +258 -0
  79. package/dist/react-native/RaftStreamHandler.js.map +1 -0
  80. package/dist/react-native/RaftStruct.d.ts +3 -0
  81. package/dist/react-native/RaftStruct.js +258 -0
  82. package/dist/react-native/RaftStruct.js.map +1 -0
  83. package/dist/react-native/RaftSysTypeManager.d.ts +16 -0
  84. package/dist/react-native/RaftSysTypeManager.js +78 -0
  85. package/dist/react-native/RaftSysTypeManager.js.map +1 -0
  86. package/dist/react-native/RaftSystemType.d.ts +30 -0
  87. package/dist/react-native/RaftSystemType.js +3 -0
  88. package/dist/react-native/RaftSystemType.js.map +1 -0
  89. package/dist/react-native/RaftSystemUtils.d.ts +136 -0
  90. package/dist/react-native/RaftSystemUtils.js +412 -0
  91. package/dist/react-native/RaftSystemUtils.js.map +1 -0
  92. package/dist/react-native/RaftTypes.d.ts +195 -0
  93. package/dist/react-native/RaftTypes.js +153 -0
  94. package/dist/react-native/RaftTypes.js.map +1 -0
  95. package/dist/react-native/RaftUpdateEvents.d.ts +33 -0
  96. package/dist/react-native/RaftUpdateEvents.js +46 -0
  97. package/dist/react-native/RaftUpdateEvents.js.map +1 -0
  98. package/dist/react-native/RaftUpdateManager.d.ts +61 -0
  99. package/dist/react-native/RaftUpdateManager.js +621 -0
  100. package/dist/react-native/RaftUpdateManager.js.map +1 -0
  101. package/dist/react-native/RaftUtils.d.ts +128 -0
  102. package/dist/react-native/RaftUtils.js +487 -0
  103. package/dist/react-native/RaftUtils.js.map +1 -0
  104. package/dist/react-native/RaftWifiTypes.d.ts +23 -0
  105. package/dist/react-native/RaftWifiTypes.js +43 -0
  106. package/dist/react-native/RaftWifiTypes.js.map +1 -0
  107. package/dist/react-native/main.d.ts +26 -0
  108. package/dist/react-native/main.js +51 -0
  109. package/dist/react-native/main.js.map +1 -0
  110. package/dist/web/RaftAttributeHandler.js +9 -6
  111. package/dist/web/RaftAttributeHandler.js.map +1 -1
  112. package/dist/web/RaftChannelBLE.web.js +8 -6
  113. package/dist/web/RaftChannelBLE.web.js.map +1 -1
  114. package/dist/web/RaftChannelSimulated.d.ts +10 -0
  115. package/dist/web/RaftChannelSimulated.js +662 -80
  116. package/dist/web/RaftChannelSimulated.js.map +1 -1
  117. package/dist/web/RaftChannelWebSerial.js +2 -2
  118. package/dist/web/RaftChannelWebSerial.js.map +1 -1
  119. package/dist/web/RaftChannelWebSocket.js +16 -1
  120. package/dist/web/RaftChannelWebSocket.js.map +1 -1
  121. package/dist/web/RaftConnector.d.ts +2 -0
  122. package/dist/web/RaftConnector.js +38 -15
  123. package/dist/web/RaftConnector.js.map +1 -1
  124. package/dist/web/RaftCustomAttrHandler.d.ts +2 -0
  125. package/dist/web/RaftCustomAttrHandler.js +54 -26
  126. package/dist/web/RaftCustomAttrHandler.js.map +1 -1
  127. package/dist/web/RaftDeviceInfo.d.ts +3 -1
  128. package/dist/web/RaftDeviceInfo.js +17 -3
  129. package/dist/web/RaftDeviceInfo.js.map +1 -1
  130. package/dist/web/RaftDeviceManager.d.ts +22 -1
  131. package/dist/web/RaftDeviceManager.js +210 -44
  132. package/dist/web/RaftDeviceManager.js.map +1 -1
  133. package/dist/web/RaftDeviceStates.d.ts +1 -1
  134. package/dist/web/RaftDeviceStates.js +2 -2
  135. package/dist/web/RaftDeviceStates.js.map +1 -1
  136. package/dist/web/RaftMsgHandler.js.map +1 -1
  137. package/dist/web/RaftStreamHandler.js +2 -1
  138. package/dist/web/RaftStreamHandler.js.map +1 -1
  139. package/dist/web/RaftStruct.js +197 -147
  140. package/dist/web/RaftStruct.js.map +1 -1
  141. package/dist/web/RaftUpdateManager.js +1 -1
  142. package/dist/web/RaftUpdateManager.js.map +1 -1
  143. package/dist/web/RaftUtils.d.ts +2 -0
  144. package/dist/web/RaftUtils.js +20 -0
  145. package/dist/web/RaftUtils.js.map +1 -1
  146. package/dist/web/main.d.ts +1 -0
  147. package/dist/web/main.js.map +1 -1
  148. package/eslint.config.mjs +33 -0
  149. package/examples/dashboard/package.json +36 -0
  150. package/examples/dashboard/src/CommandPanel.tsx +147 -0
  151. package/examples/dashboard/src/ConnManager.ts +166 -0
  152. package/examples/dashboard/src/DeviceActionsForm.tsx +133 -0
  153. package/examples/dashboard/src/DeviceAttrsForm.tsx +49 -0
  154. package/examples/dashboard/src/DeviceLineChart.tsx +163 -0
  155. package/examples/dashboard/src/DevicePanel.tsx +171 -0
  156. package/examples/dashboard/src/DevicesPanel.tsx +58 -0
  157. package/examples/dashboard/src/DispLedGrid.tsx +110 -0
  158. package/examples/dashboard/src/DispOneLed.tsx +20 -0
  159. package/examples/dashboard/src/LatencyTest.ts +130 -0
  160. package/examples/dashboard/src/LatencyTestPanel.tsx +92 -0
  161. package/examples/dashboard/src/Main.tsx +234 -0
  162. package/examples/dashboard/src/SettingsManager.ts +67 -0
  163. package/examples/dashboard/src/SettingsScreen.tsx +174 -0
  164. package/examples/dashboard/src/StatusPanel.tsx +71 -0
  165. package/examples/dashboard/src/SystemTypeCog/CogStateInfo.ts +162 -0
  166. package/examples/dashboard/src/SystemTypeCog/SystemTypeCog.ts +91 -0
  167. package/examples/dashboard/src/SystemTypeGeneric/StateInfoGeneric.ts +30 -0
  168. package/examples/dashboard/src/SystemTypeGeneric/SystemTypeGeneric.ts +91 -0
  169. package/examples/dashboard/src/SystemTypeMarty/RICAddOn.ts +70 -0
  170. package/examples/dashboard/src/SystemTypeMarty/RICAddOnBase.ts +33 -0
  171. package/examples/dashboard/src/SystemTypeMarty/RICAddOnManager.ts +342 -0
  172. package/examples/dashboard/src/SystemTypeMarty/RICCommsStats.ts +170 -0
  173. package/examples/dashboard/src/SystemTypeMarty/RICHWElem.ts +123 -0
  174. package/examples/dashboard/src/SystemTypeMarty/RICLEDPatternChecker.ts +207 -0
  175. package/examples/dashboard/src/SystemTypeMarty/RICROSSerial.ts +464 -0
  176. package/examples/dashboard/src/SystemTypeMarty/RICServoFaultDetector.ts +146 -0
  177. package/examples/dashboard/src/SystemTypeMarty/RICStateInfo.ts +97 -0
  178. package/examples/dashboard/src/SystemTypeMarty/RICSystemUtils.ts +371 -0
  179. package/examples/dashboard/src/SystemTypeMarty/RICTypes.ts +20 -0
  180. package/examples/dashboard/src/SystemTypeMarty/SystemTypeMarty.ts +119 -0
  181. package/examples/dashboard/src/index.html +15 -0
  182. package/examples/dashboard/src/index.tsx +13 -0
  183. package/examples/dashboard/src/styles.css +408 -0
  184. package/examples/dashboard/tsconfig.json +18 -0
  185. package/jest.config.js +11 -0
  186. package/package.json +4 -7
  187. package/src/RaftAttributeHandler.ts +450 -0
  188. package/src/RaftChannel.ts +32 -0
  189. package/src/RaftChannelBLE.native.ts +617 -0
  190. package/src/RaftChannelBLE.web.ts +374 -0
  191. package/src/RaftChannelBLEFactory.ts +13 -0
  192. package/src/RaftChannelBLEScanner.native.ts +184 -0
  193. package/src/RaftChannelSimulated.ts +1176 -0
  194. package/src/RaftChannelWebSerial.ts +420 -0
  195. package/src/RaftChannelWebSocket.ts +272 -0
  196. package/src/RaftCommsStats.ts +142 -0
  197. package/src/RaftConnEvents.ts +58 -0
  198. package/src/RaftConnector.ts +785 -0
  199. package/src/RaftCustomAttrHandler.ts +117 -0
  200. package/src/RaftDeviceInfo.ts +125 -0
  201. package/src/RaftDeviceManager.ts +844 -0
  202. package/src/RaftDeviceMgrIF.ts +33 -0
  203. package/src/RaftDeviceMsg.ts +20 -0
  204. package/src/RaftDeviceStates.ts +92 -0
  205. package/src/RaftFileHandler.ts +668 -0
  206. package/src/RaftLog.ts +70 -0
  207. package/src/RaftMiniHDLC.ts +396 -0
  208. package/src/RaftMsgHandler.ts +812 -0
  209. package/src/RaftMsgTrackInfo.ts +51 -0
  210. package/src/RaftProtocolDefs.ts +46 -0
  211. package/src/RaftStreamHandler.ts +329 -0
  212. package/src/RaftStruct.ts +282 -0
  213. package/src/RaftSysTypeManager.ts +87 -0
  214. package/src/RaftSystemType.ts +34 -0
  215. package/src/RaftSystemUtils.ts +489 -0
  216. package/src/RaftTypes.ts +279 -0
  217. package/src/RaftUpdateEvents.ts +48 -0
  218. package/src/RaftUpdateManager.ts +781 -0
  219. package/src/RaftUtils.ts +514 -0
  220. package/src/RaftWifiTypes.ts +36 -0
  221. package/src/main.ts +39 -0
  222. package/testdata/TestDeviceTypeRecs.json +492 -0
  223. package/tsconfig.json +30 -0
  224. package/tsconfig.react-native.json +29 -0
@@ -0,0 +1,658 @@
1
+ "use strict";
2
+ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3
+ //
4
+ // RaftConnector
5
+ // Part of RaftJS
6
+ //
7
+ // Rob Dobson & Chris Greening 2020-2024
8
+ // (C) 2020-2024 All rights reserved
9
+ //
10
+ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const tslib_1 = require("tslib");
13
+ const RaftMsgHandler_1 = tslib_1.__importDefault(require("./RaftMsgHandler"));
14
+ const RaftChannelWebSocket_1 = tslib_1.__importDefault(require("./RaftChannelWebSocket"));
15
+ const RaftChannelWebSerial_1 = tslib_1.__importDefault(require("./RaftChannelWebSerial"));
16
+ const RaftChannelSimulated_1 = tslib_1.__importDefault(require("./RaftChannelSimulated"));
17
+ const RaftCommsStats_1 = tslib_1.__importDefault(require("./RaftCommsStats"));
18
+ const RaftTypes_1 = require("./RaftTypes");
19
+ const RaftSystemUtils_1 = tslib_1.__importDefault(require("./RaftSystemUtils"));
20
+ const RaftFileHandler_1 = tslib_1.__importDefault(require("./RaftFileHandler"));
21
+ const RaftStreamHandler_1 = tslib_1.__importDefault(require("./RaftStreamHandler"));
22
+ const RaftLog_1 = tslib_1.__importDefault(require("./RaftLog"));
23
+ const RaftConnEvents_1 = require("./RaftConnEvents");
24
+ const RaftUpdateEvents_1 = require("./RaftUpdateEvents");
25
+ const RaftUpdateManager_1 = tslib_1.__importDefault(require("./RaftUpdateManager"));
26
+ const RaftChannelBLEFactory_1 = require("./RaftChannelBLEFactory");
27
+ class RaftConnector {
28
+ // get stream handler
29
+ getStreamHandler() {
30
+ return this._raftStreamHandler;
31
+ }
32
+ /**
33
+ * RaftConnector constructor
34
+ * @param getSystemTypeCB - callback to get system type
35
+ */
36
+ constructor(getSystemTypeCB = null) {
37
+ // Get system type callback
38
+ this._getSystemTypeCB = null;
39
+ // System type
40
+ this._systemType = null;
41
+ // Channel
42
+ this._raftChannel = null;
43
+ // Channel connection method and locator
44
+ this._channelConnMethod = "";
45
+ this._channelConnLocator = "";
46
+ // Comms stats
47
+ this._commsStats = new RaftCommsStats_1.default();
48
+ // Message handler
49
+ this._raftMsgHandler = new RaftMsgHandler_1.default(this._commsStats);
50
+ // RaftSystem
51
+ this._raftSystemUtils = new RaftSystemUtils_1.default(this._raftMsgHandler);
52
+ // Connection performance checker
53
+ this._testConnPerfBlockSize = 500;
54
+ this._testConnPerfNumBlocks = 50;
55
+ this._connPerfRsltDelayMs = 4000;
56
+ // Retry connection if lost
57
+ this._retryIfLostEnabled = true;
58
+ this._retryIfLostForSecs = 60;
59
+ this._retryIfLostIsConnected = false;
60
+ this._retryIfLostDisconnectTime = null;
61
+ this._retryIfLostRetryDelayMs = 500;
62
+ // File handler
63
+ this._raftFileHandler = new RaftFileHandler_1.default(this._raftMsgHandler, this._commsStats);
64
+ // Stream handler
65
+ this._raftStreamHandler = new RaftStreamHandler_1.default(this._raftMsgHandler, this._commsStats, this);
66
+ // Event listener
67
+ this._onEventFn = null;
68
+ // Update manager
69
+ this._raftUpdateManager = null;
70
+ // Get system type callback
71
+ this._getSystemTypeCB = getSystemTypeCB;
72
+ // Debug
73
+ RaftLog_1.default.debug('RaftConnector starting up');
74
+ }
75
+ /**
76
+ * Configure the file handler
77
+ * @param fileBlockSize - size of file blocks to send
78
+ * @param batchAckSize - number of blocks to send before waiting for ack
79
+ * @returns void
80
+ */
81
+ configureFileHandler(fileBlockSize, batchAckSize) {
82
+ this._raftFileHandler.setRequestedFileBlockSize(fileBlockSize);
83
+ this._raftFileHandler.setRequestedBatchAckSize(batchAckSize);
84
+ }
85
+ /**
86
+ * Set event listener
87
+ * @param onEventFn - event listener
88
+ * @returns void
89
+ * */
90
+ setEventListener(onEventFn) {
91
+ this._onEventFn = onEventFn;
92
+ }
93
+ /**
94
+ * isConnected
95
+ * @returns boolean - true if connected
96
+ * */
97
+ isConnected() {
98
+ // Check if connected
99
+ const isConnected = this._retryIfLostIsConnected || (this._raftChannel ? this._raftChannel.isConnected() : false);
100
+ return isConnected;
101
+ }
102
+ /**
103
+ * Set try to reconnect if connection lost
104
+ * @param enableRetry - true to enable retry
105
+ * @param retryForSecs - retry for this many seconds
106
+ * @returns void
107
+ * */
108
+ setRetryConnectionIfLost(enableRetry, retryForSecs) {
109
+ this._retryIfLostEnabled = enableRetry;
110
+ this._retryIfLostForSecs = retryForSecs;
111
+ if (!this._retryIfLostEnabled) {
112
+ this._retryIfLostIsConnected = false;
113
+ }
114
+ RaftLog_1.default.debug(`setRetryConnectionIfLost ${enableRetry} retry for ${retryForSecs}`);
115
+ }
116
+ /**
117
+ * Get Raft system type (the type of hardware connected to - determined using the getSystemInfo API)
118
+ * @returns RaftSystemType | null - Raft system type
119
+ * */
120
+ getSystemType() {
121
+ return this._systemType;
122
+ }
123
+ /**
124
+ * Get connection method
125
+ * @returns string - connection method
126
+ * */
127
+ getConnMethod() {
128
+ return this._channelConnMethod;
129
+ }
130
+ /**
131
+ * Get connection locator
132
+ * @returns string | object - connection locator
133
+ * */
134
+ getConnLocator() {
135
+ return this._raftChannel ? this._raftChannel.getConnectedLocator() : null;
136
+ }
137
+ /**
138
+ * Get Raft channel (this is the channel used for commuinications with the Raft application)
139
+ * @returns RaftChannel | null - Raft channel
140
+ * */
141
+ getRaftChannel() {
142
+ return this._raftChannel;
143
+ }
144
+ /**
145
+ * Get Raft system utils (access to system information and control)
146
+ * @returns RaftSystemUtils - Raft system utils
147
+ * */
148
+ getRaftSystemUtils() {
149
+ return this._raftSystemUtils;
150
+ }
151
+ /**
152
+ * Get communication stats
153
+ * @returns RaftCommsStats - communication stats
154
+ * */
155
+ getCommsStats() {
156
+ return this._commsStats;
157
+ }
158
+ /**
159
+ * Get Raft message handler (to allow message sending and receiving)
160
+ * @returns RaftMsgHandler - Raft message handler
161
+ * */
162
+ getRaftMsgHandler() {
163
+ return this._raftMsgHandler;
164
+ }
165
+ /**
166
+ * Pause connection
167
+ * @param pause - true to pause, false to resume
168
+ */
169
+ pauseConnection(pause = true) {
170
+ if (this._raftChannel)
171
+ this._raftChannel.pauseConnection(pause);
172
+ }
173
+ /**
174
+ * Initialize the Raft channel
175
+ */
176
+ async initializeChannel(method) {
177
+ // Disconnect any existing channel first to avoid stale connections
178
+ RaftLog_1.default.verbose(`[RaftConnector.initializeChannel] START method=${method} hasExistingChannel=${!!this._raftChannel}`);
179
+ if (this._raftChannel) {
180
+ RaftLog_1.default.verbose(`[RaftConnector.initializeChannel] Disconnecting existing channel...`);
181
+ try {
182
+ await this._raftChannel.disconnect();
183
+ RaftLog_1.default.verbose(`[RaftConnector.initializeChannel] Existing channel disconnected successfully`);
184
+ }
185
+ catch (e) {
186
+ RaftLog_1.default.warn(`[RaftConnector.initializeChannel] Error disconnecting existing channel: ${e}`);
187
+ }
188
+ this._raftChannel = null;
189
+ RaftLog_1.default.verbose(`[RaftConnector.initializeChannel] Existing channel nulled`);
190
+ }
191
+ // Initialize raft channel
192
+ RaftLog_1.default.verbose(`[RaftConnector.initializeChannel] Creating new channel...`);
193
+ if (method === 'WebBLE' || method === 'PhoneBLE') {
194
+ const RaftChannelBLE = (0, RaftChannelBLEFactory_1.createBLEChannel)();
195
+ this._raftChannel = new RaftChannelBLE();
196
+ this._channelConnMethod = method;
197
+ }
198
+ else if (method === 'WebSocket' || method === 'wifi') {
199
+ this._raftChannel = new RaftChannelWebSocket_1.default();
200
+ this._channelConnMethod = 'WebSocket';
201
+ }
202
+ else if (method === 'WebSerial') {
203
+ this._raftChannel = new RaftChannelWebSerial_1.default();
204
+ this._channelConnMethod = 'WebSerial';
205
+ }
206
+ else if (method === 'Simulated') {
207
+ this._raftChannel = new RaftChannelSimulated_1.default();
208
+ this._channelConnMethod = 'Simulated';
209
+ }
210
+ else {
211
+ RaftLog_1.default.warn('Unknown method: ' + method);
212
+ return false;
213
+ }
214
+ // Check channel established
215
+ if (this._raftChannel !== null) {
216
+ // Set message handler
217
+ this._raftChannel.setMsgHandler(this._raftMsgHandler);
218
+ this._raftChannel.setOnConnEvent(this.onConnEvent.bind(this));
219
+ // Message handling in and out
220
+ this._raftMsgHandler.registerForResults(this);
221
+ this._raftMsgHandler.registerMsgSender(this._raftChannel);
222
+ this._raftMsgHandler.reportMsgCallbacksSet("eventHandler", this.onRxReportMsg.bind(this));
223
+ return true;
224
+ }
225
+ else {
226
+ this._channelConnMethod = "";
227
+ return false;
228
+ }
229
+ }
230
+ /**
231
+ * Connect to a Raft device
232
+ *
233
+ * @param {string | object} locator - either a string (WebSocket URL or serial port) or an object (WebBLE)
234
+ * @returns Promise<boolean>
235
+ *
236
+ */
237
+ async connect(locator) {
238
+ if (!this._raftChannel) {
239
+ RaftLog_1.default.warn('Raft channel is not initialized.');
240
+ return false;
241
+ }
242
+ // Store locator
243
+ this._channelConnLocator = locator;
244
+ // Get system type
245
+ if (this._getSystemTypeCB) {
246
+ // Get system type
247
+ this._systemType = await this._getSystemTypeCB(this._raftSystemUtils);
248
+ // Set defaults
249
+ if (this._systemType && this._systemType.defaultWiFiHostname) {
250
+ this._raftSystemUtils.setDefaultWiFiHostname(this._systemType.defaultWiFiHostname);
251
+ }
252
+ }
253
+ // Connect
254
+ let connOk = false;
255
+ try {
256
+ // Event
257
+ this.onConnEvent(RaftConnEvents_1.RaftConnEvent.CONN_CONNECTING);
258
+ // Connect
259
+ connOk = await this._connectToChannel();
260
+ }
261
+ catch (err) {
262
+ RaftLog_1.default.warn('RaftConnector.connect - error: ' + err);
263
+ }
264
+ if (connOk) {
265
+ // Setup system type
266
+ if (this._systemType) {
267
+ this._systemType.setup(this._raftSystemUtils, this._onEventFn);
268
+ }
269
+ // Check if subscription required
270
+ if (this._systemType &&
271
+ this._systemType.subscribeForUpdates &&
272
+ this._raftChannel.requiresSubscription()) {
273
+ try {
274
+ // Subscription
275
+ await this._systemType.subscribeForUpdates(this._raftSystemUtils, true);
276
+ RaftLog_1.default.info(`connect subscribed for updates`);
277
+ }
278
+ catch (error) {
279
+ RaftLog_1.default.warn(`connect subscribe for updates failed ${error}`);
280
+ }
281
+ }
282
+ // configure file handler
283
+ this.configureFileHandler(this._raftChannel.fhFileBlockSize(), this._raftChannel.fhBatchAckSize());
284
+ // Send connected event
285
+ this.onConnEvent(RaftConnEvents_1.RaftConnEvent.CONN_CONNECTED);
286
+ }
287
+ else {
288
+ // Failed Event
289
+ this.onConnEvent(RaftConnEvents_1.RaftConnEvent.CONN_CONNECTION_FAILED);
290
+ // Clear system type
291
+ this._systemType = null;
292
+ }
293
+ return connOk;
294
+ }
295
+ async disconnect() {
296
+ // Disconnect
297
+ this._retryIfLostIsConnected = false;
298
+ if (this._raftChannel) {
299
+ // Store reference to channel before async operations to avoid race condition
300
+ const channelToDisconnect = this._raftChannel;
301
+ this._raftChannel = null;
302
+ // Check if there is a RICREST command to send before disconnecting
303
+ const ricRestCommand = channelToDisconnect.ricRestCmdBeforeDisconnect();
304
+ if (ricRestCommand) {
305
+ console.log(`sending RICREST command before disconnect: ${ricRestCommand}`);
306
+ await this.sendRICRESTMsg(ricRestCommand, {});
307
+ }
308
+ // Pause a little before disconnecting
309
+ await new Promise(resolve => setTimeout(resolve, 1000));
310
+ // await this.sendRICRESTMsg("bledisc", {});
311
+ await channelToDisconnect.disconnect();
312
+ }
313
+ }
314
+ // Mark: Tx Message handling -----------------------------------------------------------------------------------------
315
+ /**
316
+ *
317
+ * sendRICRESTMsg
318
+ * @param commandName command API string
319
+ * @param params parameters (simple name value pairs only) to parameterize trajectory
320
+ * @returns Promise<RaftOKFail>
321
+ *
322
+ */
323
+ async sendRICRESTMsg(commandName, params, bridgeID = undefined) {
324
+ try {
325
+ // Format the paramList as query string
326
+ const paramEntries = Object.entries(params);
327
+ let paramQueryStr = '';
328
+ for (const param of paramEntries) {
329
+ if (paramQueryStr.length > 0)
330
+ paramQueryStr += '&';
331
+ paramQueryStr += param[0] + '=' + param[1];
332
+ }
333
+ // Format the url to send
334
+ if (paramQueryStr.length > 0)
335
+ commandName += '?' + paramQueryStr;
336
+ return await this._raftMsgHandler.sendRICRESTURL(commandName, bridgeID);
337
+ }
338
+ catch (error) {
339
+ RaftLog_1.default.warn(`sendRICRESTMsg failed ${error}`);
340
+ return { rslt: 'fail' };
341
+ }
342
+ }
343
+ // Mark: Rx Message handling -----------------------------------------------------------------------------------------
344
+ /**
345
+ * onRxReply - handle a reply message
346
+ * @param msgHandle number indicating the message that is being replied to (from the original message)
347
+ * @param msgRsltCode result code
348
+ * @param msgRsltJsonObj result object
349
+ */
350
+ onRxReply(msgHandle, msgRsltCode, msgRsltJsonObj) {
351
+ RaftLog_1.default.verbose(`onRxReply msgHandle ${msgHandle} rsltCode ${msgRsltCode} obj ${JSON.stringify(msgRsltJsonObj)}`);
352
+ }
353
+ /**
354
+ * onRxUnnumberedMsg - handle an unnumbered message
355
+ * @param msgRsltJsonObj result object
356
+ */
357
+ onRxUnnumberedMsg(msgRsltJsonObj) {
358
+ RaftLog_1.default.verbose(`onRxUnnumberedMsg rsltCode obj ${JSON.stringify(msgRsltJsonObj)}`);
359
+ // Inform the file handler
360
+ if ('okto' in msgRsltJsonObj) {
361
+ this._raftFileHandler.onOktoMsg(msgRsltJsonObj.okto);
362
+ }
363
+ else if ('sokto' in msgRsltJsonObj) {
364
+ this._raftStreamHandler.onSoktoMsg(msgRsltJsonObj.sokto);
365
+ }
366
+ }
367
+ /**
368
+ * onRxFileBlock - handle a file block
369
+ * @param filePos file position
370
+ * @param fileBlockData file block data
371
+ */
372
+ onRxFileBlock(filePos, fileBlockData) {
373
+ // RaftLog.info(`onRxFileBlock filePos ${filePos} fileBlockData ${RaftUtils.bufferToHex(fileBlockData)}`);
374
+ this._raftFileHandler.onFileBlock(filePos, fileBlockData);
375
+ }
376
+ // Mark: Handling of other message types -----------------------------------------------------------------------------------------
377
+ /**
378
+ * onRxOtherMsgType - handle other message types
379
+ * @param payload message payload
380
+ * @param frameTimeMs time of frame
381
+ */
382
+ onRxOtherMsgType(payload, _frameTimeMs) {
383
+ // RaftLog.debug(`onRxOtherMsgType payload ${RaftUtils.bufferToHex(payload)}`);
384
+ RaftLog_1.default.verbose(`onRxOtherMsgType payloadLen ${payload.length}`);
385
+ // Handle other messages
386
+ if (this._systemType && this._systemType.rxOtherMsgType) {
387
+ this._systemType.rxOtherMsgType(payload, _frameTimeMs);
388
+ }
389
+ }
390
+ // Mark: File sending --------------------------------------------------------------------------------
391
+ /**
392
+ * sendFile - send a file
393
+ * @param fileName name of file to send
394
+ * @param fileContents file contents
395
+ * @param progressCallback callback to receive progress updates
396
+ * @returns Promise<boolean> - true if file sent successfully
397
+ */
398
+ async sendFile(fileName, fileContents, progressCallback) {
399
+ return this._raftFileHandler.fileSend(fileName, RaftTypes_1.RaftFileSendType.NORMAL_FILE, "fs", fileContents, progressCallback);
400
+ }
401
+ // Mark: Streaming --------------------------------------------------------------------------------
402
+ /**
403
+ * streamAudio - stream audio
404
+ * @param streamContents audio data
405
+ * @param clearExisting true to clear existing audio
406
+ * @param duration duration of audio
407
+ */
408
+ streamAudio(streamContents, clearExisting, duration) {
409
+ if (this._raftStreamHandler && this.isConnected()) {
410
+ this._raftStreamHandler.streamAudio(streamContents, clearExisting, duration);
411
+ }
412
+ }
413
+ /**
414
+ * isStreamStarting - check if stream is starting
415
+ */
416
+ isStreamStarting() {
417
+ return this._raftStreamHandler.isStreamStarting();
418
+ }
419
+ // Mark: File system --------------------------------------------------------------------------------
420
+ /**
421
+ * fsGetContents - get file contents
422
+ * @param fileName name of file to get
423
+ * @param fileSource source of file to get (e.g. "fs" or "bridgeserial1", if omitted defaults to "fs")
424
+ * @param progressCallback callback to receive progress updates
425
+ * @returns Promise<RaftFileDownloadResult>
426
+ */
427
+ async fsGetContents(fileName, fileSource, progressCallback) {
428
+ return await this._raftFileHandler.fileReceive(fileName, fileSource, progressCallback);
429
+ }
430
+ /**
431
+ * setLegacySoktoMode - set legacy sokto mode
432
+ * @param legacyMode true to set legacy mode
433
+ */
434
+ setLegacySoktoMode(legacyMode) {
435
+ return this._raftStreamHandler.setLegacySoktoMode(legacyMode);
436
+ }
437
+ // Mark: Bridge serial --------------------------------------------------------------------------------
438
+ /**
439
+ * createCommsBridge - create a comms bridge
440
+ * @param bridgeSource source of bridge (e.g. "Serial1")
441
+ * @param bridgeName name of bridge
442
+ * @param idleCloseSecs idle close time seconds
443
+ * @returns Promise<RaftBridgeSetupResp>
444
+ */
445
+ async createCommsBridge(bridgeSource, bridgeName, idleCloseSecs = 0) {
446
+ return await this._raftMsgHandler.createCommsBridge(bridgeSource, bridgeName, idleCloseSecs);
447
+ }
448
+ // Mark: Connection performance--------------------------------------------------------------------------
449
+ /**
450
+ * ParkMiller random number generator
451
+ * @param seed
452
+ * @returns number
453
+ */
454
+ parkmiller_next(seed) {
455
+ const hi = Math.round(16807 * (seed & 0xffff));
456
+ let lo = Math.round(16807 * (seed >> 16));
457
+ lo += (hi & 0x7fff) << 16;
458
+ lo += hi >> 15;
459
+ if (lo > 0x7fffffff)
460
+ lo -= 0x7fffffff;
461
+ return lo;
462
+ }
463
+ /**
464
+ * checkConnPerformance - check connection performance
465
+ * @returns Promise<number | undefined> - connection performance
466
+ */
467
+ async checkConnPerformance() {
468
+ // Sends a magic sequence of bytes followed by blocks of random data
469
+ // these will be ignored by the Raft library (as it recognises magic sequence)
470
+ // and is used performance evaluation
471
+ let prbsState = 1;
472
+ const testData = new Uint8Array(this._testConnPerfBlockSize);
473
+ for (let i = 0; i < this._testConnPerfNumBlocks; i++) {
474
+ testData.set([0, (i >> 24) & 0xff, (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff, 0x1f, 0x9d, 0xf4, 0x7a, 0xb5]);
475
+ for (let j = 10; j < this._testConnPerfBlockSize; j++) {
476
+ prbsState = this.parkmiller_next(prbsState);
477
+ testData[j] = prbsState & 0xff;
478
+ }
479
+ if (this._raftChannel) {
480
+ await this._raftChannel.sendTxMsg(testData, false);
481
+ }
482
+ }
483
+ // Wait a little to allow the Raft app to process the data
484
+ await new Promise(resolve => setTimeout(resolve, this._connPerfRsltDelayMs));
485
+ // Get performance
486
+ const blePerf = await this._raftSystemUtils.getSysModInfoBLEMan();
487
+ if (blePerf) {
488
+ console.log(`checkConnPerformance result rate = ${blePerf.tBPS}BytesPS`);
489
+ return blePerf.tBPS;
490
+ }
491
+ else {
492
+ throw new Error('checkConnPerformance: failed to get BLE performance');
493
+ }
494
+ }
495
+ // Mark: Connection event --------------------------------------------------------------------------
496
+ /**
497
+ * onConnEvent - handle connection event
498
+ * @param eventEnum connection event enumeration
499
+ * @param data data associated with event
500
+ * @returns void
501
+ */
502
+ onConnEvent(eventEnum, data = undefined) {
503
+ // Handle information clearing on disconnect
504
+ switch (eventEnum) {
505
+ case RaftConnEvents_1.RaftConnEvent.CONN_DISCONNECTED:
506
+ // Disconnect time
507
+ this._retryIfLostDisconnectTime = Date.now();
508
+ // Check if retry required
509
+ if (this._retryIfLostIsConnected && this._retryIfLostEnabled) {
510
+ // Indicate connection disrupted
511
+ if (this._onEventFn) {
512
+ this._onEventFn("conn", RaftConnEvents_1.RaftConnEvent.CONN_ISSUE_DETECTED, RaftConnEvents_1.RaftConnEventNames[RaftConnEvents_1.RaftConnEvent.CONN_ISSUE_DETECTED]);
513
+ }
514
+ // Retry connection
515
+ this._retryConnection();
516
+ // Don't allow disconnection to propagate until retries have occurred
517
+ return;
518
+ }
519
+ // Invalidate connection details
520
+ this._raftSystemUtils.invalidate();
521
+ // Invalidate system-type info
522
+ if (this._systemType && this._systemType.stateIsInvalid) {
523
+ this._systemType.stateIsInvalid();
524
+ }
525
+ break;
526
+ }
527
+ // Notify
528
+ if (this._onEventFn) {
529
+ this._onEventFn("conn", eventEnum, RaftConnEvents_1.RaftConnEventNames[eventEnum], data);
530
+ }
531
+ }
532
+ /**
533
+ * Retry connection
534
+ */
535
+ _retryConnection() {
536
+ // Check timeout
537
+ if ((this._retryIfLostDisconnectTime !== null) &&
538
+ (Date.now() - this._retryIfLostDisconnectTime < this._retryIfLostForSecs * 1000)) {
539
+ // Set timer to try to reconnect
540
+ setTimeout(async () => {
541
+ // Try to connect
542
+ const isConn = await this._connectToChannel();
543
+ if (!isConn) {
544
+ this._retryConnection();
545
+ }
546
+ else {
547
+ // No longer retrying
548
+ this._retryIfLostDisconnectTime = null;
549
+ // Indicate connection problem resolved
550
+ if (this._onEventFn) {
551
+ this._onEventFn("conn", RaftConnEvents_1.RaftConnEvent.CONN_ISSUE_RESOLVED, RaftConnEvents_1.RaftConnEventNames[RaftConnEvents_1.RaftConnEvent.CONN_ISSUE_RESOLVED]);
552
+ }
553
+ }
554
+ }, this._retryIfLostRetryDelayMs);
555
+ }
556
+ else {
557
+ // No longer connected after retry timeout
558
+ this._retryIfLostIsConnected = false;
559
+ // Indicate disconnection
560
+ if (this._onEventFn) {
561
+ this._onEventFn("conn", RaftConnEvents_1.RaftConnEvent.CONN_DISCONNECTED, RaftConnEvents_1.RaftConnEventNames[RaftConnEvents_1.RaftConnEvent.CONN_DISCONNECTED]);
562
+ }
563
+ // Invalidate connection details
564
+ this._raftSystemUtils.invalidate();
565
+ // Invalidate system-type info
566
+ if (this._systemType && this._systemType.stateIsInvalid) {
567
+ this._systemType.stateIsInvalid();
568
+ }
569
+ }
570
+ }
571
+ /**
572
+ * Connect to channel
573
+ * @returns Promise<boolean> - true if connected
574
+ */
575
+ async _connectToChannel() {
576
+ // Connect
577
+ try {
578
+ if (this._raftChannel) {
579
+ const connected = await this._raftChannel.connect(this._channelConnLocator, this._systemType ? this._systemType.connectorOptions : {});
580
+ if (connected) {
581
+ this._retryIfLostIsConnected = true;
582
+ return true;
583
+ }
584
+ }
585
+ }
586
+ catch (error) {
587
+ RaftLog_1.default.warn(`RaftConnector.connect() error: ${error}`);
588
+ }
589
+ return false;
590
+ }
591
+ // Mark: OTA Update -----------------------------------------------------------------------------------------
592
+ /**
593
+ * onUpdateEvent - handle update event
594
+ * @param eventEnum
595
+ * @param data
596
+ */
597
+ _onUpdateEvent(eventEnum, data = undefined) {
598
+ // Notify
599
+ if (this._onEventFn) {
600
+ this._onEventFn("ota", eventEnum, RaftUpdateEvents_1.RaftUpdateEventNames[eventEnum], data);
601
+ }
602
+ }
603
+ /**
604
+ * otaUpdateCheck - check for OTA update
605
+ * @returns Promise<RaftUpdateEvent> - update event
606
+ * */
607
+ async otaUpdateCheck() {
608
+ if (!this._raftUpdateManager)
609
+ return RaftUpdateEvents_1.RaftUpdateEvent.UPDATE_NOT_CONFIGURED;
610
+ return await this._raftUpdateManager.checkForUpdate(this._raftSystemUtils.getCachedSystemInfo());
611
+ }
612
+ /**
613
+ * otaUpdateStart - start OTA update
614
+ * @returns Promise<RaftUpdateEvent> - update event
615
+ * */
616
+ async otaUpdateStart() {
617
+ if (!this._raftUpdateManager)
618
+ return RaftUpdateEvents_1.RaftUpdateEvent.UPDATE_NOT_CONFIGURED;
619
+ return await this._raftUpdateManager.firmwareUpdate();
620
+ }
621
+ /**
622
+ * otaUpdateCancel - cancel OTA update
623
+ * @returns Promise<void>
624
+ * */
625
+ async otaUpdateCancel() {
626
+ if (!this._raftUpdateManager)
627
+ return;
628
+ return await this._raftUpdateManager.firmwareUpdateCancel();
629
+ }
630
+ /**
631
+ * setupUpdateManager - setup the update manager
632
+ * @param appVersion - app version
633
+ * @param appUpdateURL - app update URL
634
+ * @param firmwareBaseURL - firmware base URL
635
+ * @param fileDownloader - file downloader
636
+ * @returns void
637
+ * */
638
+ setupUpdateManager(appVersion, appUpdateURL, firmwareBaseURL, fileDownloader) {
639
+ // Setup update manager
640
+ const firmwareTypeStrForMainFw = 'main';
641
+ this._raftUpdateManager = new RaftUpdateManager_1.default(this._systemType, this._raftMsgHandler, this._raftFileHandler, this._raftSystemUtils, this._onUpdateEvent.bind(this), firmwareTypeStrForMainFw, appVersion, fileDownloader, appUpdateURL, firmwareBaseURL, this._raftChannel);
642
+ }
643
+ async onRxReportMsg(reportMsg) {
644
+ // console.log(`onRxReportMsg ${JSON.stringify(reportMsg)}`);
645
+ if (reportMsg.msgType && reportMsg.msgType.toLowerCase() === "sysevent") {
646
+ if (reportMsg.msgName && reportMsg.msgName.toLowerCase() === "shutdown") {
647
+ // Indicate disconnection
648
+ if (this._onEventFn) {
649
+ this._onEventFn("conn", RaftConnEvents_1.RaftConnEvent.CONN_DISCONNECTED, RaftConnEvents_1.RaftConnEventNames[RaftConnEvents_1.RaftConnEvent.CONN_DISCONNECTED]);
650
+ }
651
+ // Disconnect
652
+ await this.disconnect();
653
+ }
654
+ }
655
+ }
656
+ }
657
+ exports.default = RaftConnector;
658
+ //# sourceMappingURL=RaftConnector.js.map