@robdobsn/raftjs 1.7.2 → 1.7.3

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 (188) hide show
  1. package/dist/web/RaftAttributeHandler.js +5 -5
  2. package/dist/web/RaftAttributeHandler.js.map +1 -1
  3. package/package.json +5 -2
  4. package/.editorconfig +0 -14
  5. package/.gitattributes +0 -11
  6. package/.nvmrc +0 -1
  7. package/TODO.md +0 -1
  8. package/dist/react-native/RaftAttributeHandler.d.ts +0 -12
  9. package/dist/react-native/RaftAttributeHandler.js +0 -249
  10. package/dist/react-native/RaftAttributeHandler.js.map +0 -1
  11. package/dist/react-native/RaftChannel.d.ts +0 -20
  12. package/dist/react-native/RaftChannel.js +0 -12
  13. package/dist/react-native/RaftChannel.js.map +0 -1
  14. package/dist/react-native/RaftChannelBLE.native.d.ts +0 -95
  15. package/dist/react-native/RaftChannelBLE.native.js +0 -482
  16. package/dist/react-native/RaftChannelBLE.native.js.map +0 -1
  17. package/dist/react-native/RaftChannelBLE.web.d.ts +0 -40
  18. package/dist/react-native/RaftChannelBLE.web.js +0 -300
  19. package/dist/react-native/RaftChannelBLE.web.js.map +0 -1
  20. package/dist/react-native/RaftChannelBLEFactory.d.ts +0 -10
  21. package/dist/react-native/RaftChannelBLEFactory.js +0 -17
  22. package/dist/react-native/RaftChannelBLEFactory.js.map +0 -1
  23. package/dist/react-native/RaftChannelBLEScanner.native.d.ts +0 -18
  24. package/dist/react-native/RaftChannelBLEScanner.native.js +0 -138
  25. package/dist/react-native/RaftChannelBLEScanner.native.js.map +0 -1
  26. package/dist/react-native/RaftChannelSimulated.d.ts +0 -32
  27. package/dist/react-native/RaftChannelSimulated.js +0 -418
  28. package/dist/react-native/RaftChannelSimulated.js.map +0 -1
  29. package/dist/react-native/RaftChannelWebSerial.d.ts +0 -39
  30. package/dist/react-native/RaftChannelWebSerial.js +0 -329
  31. package/dist/react-native/RaftChannelWebSerial.js.map +0 -1
  32. package/dist/react-native/RaftChannelWebSocket.d.ts +0 -30
  33. package/dist/react-native/RaftChannelWebSocket.js +0 -207
  34. package/dist/react-native/RaftChannelWebSocket.js.map +0 -1
  35. package/dist/react-native/RaftCommsStats.d.ts +0 -39
  36. package/dist/react-native/RaftCommsStats.js +0 -128
  37. package/dist/react-native/RaftCommsStats.js.map +0 -1
  38. package/dist/react-native/RaftConnEvents.d.ts +0 -39
  39. package/dist/react-native/RaftConnEvents.js +0 -54
  40. package/dist/react-native/RaftConnEvents.js.map +0 -1
  41. package/dist/react-native/RaftConnector.d.ts +0 -245
  42. package/dist/react-native/RaftConnector.js +0 -621
  43. package/dist/react-native/RaftConnector.js.map +0 -1
  44. package/dist/react-native/RaftCustomAttrHandler.d.ts +0 -4
  45. package/dist/react-native/RaftCustomAttrHandler.js +0 -50
  46. package/dist/react-native/RaftCustomAttrHandler.js.map +0 -1
  47. package/dist/react-native/RaftDeviceInfo.d.ts +0 -63
  48. package/dist/react-native/RaftDeviceInfo.js +0 -36
  49. package/dist/react-native/RaftDeviceInfo.js.map +0 -1
  50. package/dist/react-native/RaftDeviceManager.d.ts +0 -40
  51. package/dist/react-native/RaftDeviceManager.js +0 -499
  52. package/dist/react-native/RaftDeviceManager.js.map +0 -1
  53. package/dist/react-native/RaftDeviceMgrIF.d.ts +0 -15
  54. package/dist/react-native/RaftDeviceMgrIF.js +0 -11
  55. package/dist/react-native/RaftDeviceMgrIF.js.map +0 -1
  56. package/dist/react-native/RaftDeviceMsg.d.ts +0 -9
  57. package/dist/react-native/RaftDeviceMsg.js +0 -11
  58. package/dist/react-native/RaftDeviceMsg.js.map +0 -1
  59. package/dist/react-native/RaftDeviceStates.d.ts +0 -37
  60. package/dist/react-native/RaftDeviceStates.js +0 -60
  61. package/dist/react-native/RaftDeviceStates.js.map +0 -1
  62. package/dist/react-native/RaftFileHandler.d.ts +0 -52
  63. package/dist/react-native/RaftFileHandler.js +0 -502
  64. package/dist/react-native/RaftFileHandler.js.map +0 -1
  65. package/dist/react-native/RaftLog.d.ts +0 -22
  66. package/dist/react-native/RaftLog.js +0 -63
  67. package/dist/react-native/RaftLog.js.map +0 -1
  68. package/dist/react-native/RaftMiniHDLC.d.ts +0 -18
  69. package/dist/react-native/RaftMiniHDLC.js +0 -383
  70. package/dist/react-native/RaftMiniHDLC.js.map +0 -1
  71. package/dist/react-native/RaftMsgHandler.d.ts +0 -62
  72. package/dist/react-native/RaftMsgHandler.js +0 -511
  73. package/dist/react-native/RaftMsgHandler.js.map +0 -1
  74. package/dist/react-native/RaftMsgTrackInfo.d.ts +0 -17
  75. package/dist/react-native/RaftMsgTrackInfo.js +0 -42
  76. package/dist/react-native/RaftMsgTrackInfo.js.map +0 -1
  77. package/dist/react-native/RaftProtocolDefs.d.ts +0 -30
  78. package/dist/react-native/RaftProtocolDefs.js +0 -48
  79. package/dist/react-native/RaftProtocolDefs.js.map +0 -1
  80. package/dist/react-native/RaftStreamHandler.d.ts +0 -38
  81. package/dist/react-native/RaftStreamHandler.js +0 -257
  82. package/dist/react-native/RaftStreamHandler.js.map +0 -1
  83. package/dist/react-native/RaftStruct.d.ts +0 -3
  84. package/dist/react-native/RaftStruct.js +0 -208
  85. package/dist/react-native/RaftStruct.js.map +0 -1
  86. package/dist/react-native/RaftSysTypeManager.d.ts +0 -14
  87. package/dist/react-native/RaftSysTypeManager.js +0 -53
  88. package/dist/react-native/RaftSysTypeManager.js.map +0 -1
  89. package/dist/react-native/RaftSystemType.d.ts +0 -28
  90. package/dist/react-native/RaftSystemType.js +0 -3
  91. package/dist/react-native/RaftSystemType.js.map +0 -1
  92. package/dist/react-native/RaftSystemUtils.d.ts +0 -136
  93. package/dist/react-native/RaftSystemUtils.js +0 -410
  94. package/dist/react-native/RaftSystemUtils.js.map +0 -1
  95. package/dist/react-native/RaftTypes.d.ts +0 -194
  96. package/dist/react-native/RaftTypes.js +0 -153
  97. package/dist/react-native/RaftTypes.js.map +0 -1
  98. package/dist/react-native/RaftUpdateEvents.d.ts +0 -33
  99. package/dist/react-native/RaftUpdateEvents.js +0 -46
  100. package/dist/react-native/RaftUpdateEvents.js.map +0 -1
  101. package/dist/react-native/RaftUpdateManager.d.ts +0 -61
  102. package/dist/react-native/RaftUpdateManager.js +0 -621
  103. package/dist/react-native/RaftUpdateManager.js.map +0 -1
  104. package/dist/react-native/RaftUtils.d.ts +0 -126
  105. package/dist/react-native/RaftUtils.js +0 -467
  106. package/dist/react-native/RaftUtils.js.map +0 -1
  107. package/dist/react-native/RaftWifiTypes.d.ts +0 -23
  108. package/dist/react-native/RaftWifiTypes.js +0 -43
  109. package/dist/react-native/RaftWifiTypes.js.map +0 -1
  110. package/dist/react-native/main.d.ts +0 -25
  111. package/dist/react-native/main.js +0 -51
  112. package/dist/react-native/main.js.map +0 -1
  113. package/eslint.config.mjs +0 -33
  114. package/examples/dashboard/package.json +0 -36
  115. package/examples/dashboard/src/CommandPanel.tsx +0 -147
  116. package/examples/dashboard/src/ConnManager.ts +0 -164
  117. package/examples/dashboard/src/DeviceActionsForm.tsx +0 -133
  118. package/examples/dashboard/src/DeviceAttrsForm.tsx +0 -49
  119. package/examples/dashboard/src/DeviceLineChart.tsx +0 -163
  120. package/examples/dashboard/src/DevicePanel.tsx +0 -166
  121. package/examples/dashboard/src/DevicesPanel.tsx +0 -58
  122. package/examples/dashboard/src/DispLedGrid.tsx +0 -110
  123. package/examples/dashboard/src/DispOneLed.tsx +0 -20
  124. package/examples/dashboard/src/LatencyTest.ts +0 -130
  125. package/examples/dashboard/src/LatencyTestPanel.tsx +0 -92
  126. package/examples/dashboard/src/Main.tsx +0 -234
  127. package/examples/dashboard/src/SettingsManager.ts +0 -67
  128. package/examples/dashboard/src/SettingsScreen.tsx +0 -174
  129. package/examples/dashboard/src/StatusPanel.tsx +0 -71
  130. package/examples/dashboard/src/SystemTypeCog/CogStateInfo.ts +0 -163
  131. package/examples/dashboard/src/SystemTypeCog/SystemTypeCog.ts +0 -91
  132. package/examples/dashboard/src/SystemTypeGeneric/StateInfoGeneric.ts +0 -30
  133. package/examples/dashboard/src/SystemTypeGeneric/SystemTypeGeneric.ts +0 -91
  134. package/examples/dashboard/src/SystemTypeMarty/RICAddOn.ts +0 -70
  135. package/examples/dashboard/src/SystemTypeMarty/RICAddOnBase.ts +0 -33
  136. package/examples/dashboard/src/SystemTypeMarty/RICAddOnManager.ts +0 -342
  137. package/examples/dashboard/src/SystemTypeMarty/RICCommsStats.ts +0 -170
  138. package/examples/dashboard/src/SystemTypeMarty/RICHWElem.ts +0 -123
  139. package/examples/dashboard/src/SystemTypeMarty/RICLEDPatternChecker.ts +0 -207
  140. package/examples/dashboard/src/SystemTypeMarty/RICROSSerial.ts +0 -464
  141. package/examples/dashboard/src/SystemTypeMarty/RICServoFaultDetector.ts +0 -146
  142. package/examples/dashboard/src/SystemTypeMarty/RICStateInfo.ts +0 -97
  143. package/examples/dashboard/src/SystemTypeMarty/RICSystemUtils.ts +0 -371
  144. package/examples/dashboard/src/SystemTypeMarty/RICTypes.ts +0 -20
  145. package/examples/dashboard/src/SystemTypeMarty/SystemTypeMarty.ts +0 -119
  146. package/examples/dashboard/src/index.html +0 -15
  147. package/examples/dashboard/src/index.tsx +0 -13
  148. package/examples/dashboard/src/styles.css +0 -408
  149. package/examples/dashboard/tsconfig.json +0 -18
  150. package/jest.config.js +0 -11
  151. package/src/RaftAttributeHandler.ts +0 -298
  152. package/src/RaftChannel.ts +0 -32
  153. package/src/RaftChannelBLE.native.ts +0 -616
  154. package/src/RaftChannelBLE.web.ts +0 -372
  155. package/src/RaftChannelBLEFactory.ts +0 -13
  156. package/src/RaftChannelBLEScanner.native.ts +0 -184
  157. package/src/RaftChannelSimulated.ts +0 -482
  158. package/src/RaftChannelWebSerial.ts +0 -420
  159. package/src/RaftChannelWebSocket.ts +0 -258
  160. package/src/RaftCommsStats.ts +0 -142
  161. package/src/RaftConnEvents.ts +0 -58
  162. package/src/RaftConnector.ts +0 -743
  163. package/src/RaftCustomAttrHandler.ts +0 -54
  164. package/src/RaftDeviceInfo.ts +0 -102
  165. package/src/RaftDeviceManager.ts +0 -607
  166. package/src/RaftDeviceMgrIF.ts +0 -33
  167. package/src/RaftDeviceMsg.ts +0 -20
  168. package/src/RaftDeviceStates.ts +0 -92
  169. package/src/RaftFileHandler.ts +0 -668
  170. package/src/RaftLog.ts +0 -70
  171. package/src/RaftMiniHDLC.ts +0 -396
  172. package/src/RaftMsgHandler.ts +0 -813
  173. package/src/RaftMsgTrackInfo.ts +0 -51
  174. package/src/RaftProtocolDefs.ts +0 -46
  175. package/src/RaftStreamHandler.ts +0 -328
  176. package/src/RaftStruct.ts +0 -209
  177. package/src/RaftSysTypeManager.ts +0 -60
  178. package/src/RaftSystemType.ts +0 -32
  179. package/src/RaftSystemUtils.ts +0 -487
  180. package/src/RaftTypes.ts +0 -278
  181. package/src/RaftUpdateEvents.ts +0 -48
  182. package/src/RaftUpdateManager.ts +0 -781
  183. package/src/RaftUtils.ts +0 -494
  184. package/src/RaftWifiTypes.ts +0 -36
  185. package/src/main.ts +0 -38
  186. package/testdata/TestDeviceTypeRecs.json +0 -492
  187. package/tsconfig.json +0 -30
  188. package/tsconfig.react-native.json +0 -29
@@ -1,616 +0,0 @@
1
- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2
- //
3
- // RaftChannelPhoneBLE
4
- // Part of RaftJS
5
- //
6
- // Rob Dobson & Chris Greening 2020-2024
7
- // (C) 2020-2024 All rights reserved
8
- //
9
- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
10
-
11
- import { BleError, BleManager, Characteristic, ConnectionPriority, Device, State, Subscription } from "react-native-ble-plx";
12
- import RaftChannel from "./RaftChannel";
13
- import { RaftConnEvent, RaftConnEventFn } from "./RaftConnEvents";
14
- import RaftLog from "./RaftLog";
15
- import RaftMsgHandler from "./RaftMsgHandler";
16
- import RaftUtils from "./RaftUtils";
17
- import RaftChannelBLEScanner from "./RaftChannelBLEScanner.native";
18
- import { DiscoveredDevice } from "./RaftTypes";
19
-
20
- const _bleManager = new BleManager();
21
-
22
- export default class RaftChannelPhoneBLE implements RaftChannel {
23
-
24
- // Conn event fn
25
- private _onConnEvent: RaftConnEventFn | null = null;
26
-
27
- // Default command and response UUIDs
28
- _cmdUUID = 'aa76677e-9cfd-4626-a510-0d305be57c8e';
29
- _respUUID = 'aa76677e-9cfd-4626-a510-0d305be57c8f';
30
- _serviceUUIDs = ['aa76677e-9cfd-4626-a510-0d305be57c8d', 'da903f65-d5c2-4f4d-a065-d1aade7af874'];
31
-
32
- // BLE Scanner
33
- _bleScanner: RaftChannelBLEScanner;
34
-
35
- // Device to connect to using BLE
36
- _deviceToConnectTo: DiscoveredDevice | null = null;
37
-
38
- // Handle BLE disconnection through retry
39
- // May be set after connection checking (e.g. using LEDs)
40
- _retryConnectionIfLost: boolean = false;
41
- RECONNECT_ATTEMPTS_AFTER_CONN_LOST = 20;
42
-
43
- // BLE connection
44
- _bleSubscrOnRx: Subscription | null = null;
45
- _bleSubscrOnDisconnect: Subscription | null = null;
46
- _bleSubscrOnStateChange: Subscription | null = null;
47
- _bleDevice: Device | null = null;
48
-
49
- // MTU (Maximum Transmission Unit) size to request
50
- MTU_SIZE_TO_REQUEST = 512;
51
-
52
- // Message handler
53
- _raftMsgHandler: RaftMsgHandler | null = null;
54
-
55
- // Last message tx time
56
- private _msgTxTimeLast = Date.now();
57
- private _msgTxMinTimeBetweenMs = 1;
58
- private readonly maxRetries = 1;
59
-
60
- // File Handler parameters
61
- private _requestedBatchAckSize = 10;
62
- private _requestedFileBlockSize = 500;
63
-
64
- // Connected device UUID
65
- private _connectedDeviceServiceUUID?: string;
66
-
67
- constructor() {
68
- RaftLog.debug('BLEChannel constructor');
69
-
70
- // _bleManager.setLogLevel(LogLevel.Verbose);
71
-
72
- // Scanner
73
- this._bleScanner = new RaftChannelBLEScanner(
74
- _bleManager,
75
- this._serviceUUIDs,
76
- this.scanningEvent.bind(this),
77
- );
78
-
79
- // Listen for BLE state changes
80
- this._bleSubscrOnStateChange = _bleManager.onStateChange(state => {
81
- this._onBLEStateChange(state);
82
- }, true);
83
- }
84
-
85
- setConnectedDeviceUUID(serviceUUID: string) {
86
- this._connectedDeviceServiceUUID = serviceUUID;
87
- }
88
-
89
- getBleManager(): BleManager {
90
- return _bleManager;
91
- }
92
-
93
-
94
- fhBatchAckSize(): number { return this._requestedBatchAckSize; }
95
- fhFileBlockSize(): number { return this._requestedFileBlockSize; }
96
-
97
- pauseConnection(pause: boolean): void { RaftLog.verbose(`pauseConnection ${pause} - no effect for this channel type`); return; }
98
-
99
- // isConnected
100
- isConnected(): boolean {
101
- return this._bleDevice !== null;
102
- }
103
-
104
- setOnConnEvent(connEventFn: RaftConnEventFn): void {
105
- this._onConnEvent = connEventFn;
106
- }
107
-
108
- requiresSubscription(): boolean {
109
- return true;
110
- }
111
-
112
- isEnabled() {
113
- return true;
114
- }
115
-
116
- // Set message handler
117
- setMsgHandler(raftMsgHandler: RaftMsgHandler): void {
118
- this._raftMsgHandler = raftMsgHandler;
119
- }
120
-
121
- setRetryConnectionIfLost(retry: boolean): void {
122
- RaftLog.debug(`BLEChannel setRetryConnectionIfLost ${retry}`);
123
- this._retryConnectionIfLost = retry;
124
- }
125
-
126
- async discoveryStart(uuids: string[], tries = 10): Promise<boolean> {
127
- if (tries <= 0) {
128
- RaftLog.debug(`BLEChannel discoveryStart failed`);
129
- return false;
130
- }
131
- // Disconnect any existing connection
132
- // await this.disconnect();
133
-
134
- // wait until the bt is powered on
135
- const state = await _bleManager.state();
136
- if (state !== State.PoweredOn) {
137
- RaftLog.debug(`BLEChannel discoveryStart waiting for BLE powered on`);
138
- await new Promise(resolve => setTimeout(resolve, 500));
139
- return this.discoveryStart(uuids, tries - 1);
140
- }
141
- // Start scanning
142
- await this._bleScanner.scanningStart(uuids);
143
-
144
- // Event
145
- RaftLog.debug(`BLEChannel discoveryStart emitting BLE_SCANNING_STARTED`);
146
- this.emit(RaftConnEvent.BLE_SCANNING_STARTED);
147
- return true;
148
- }
149
-
150
- discoveryCancel(): void {
151
- // Stop scanning
152
- this._bleScanner.scanningStop();
153
- }
154
-
155
- _onBLEStateChange(state: State) {
156
- RaftLog.debug('BLEChannel state change ' + state);
157
- if (state === State.PoweredOn) {
158
- this.emit(RaftConnEvent.BLE_BLUETOOTH_STATE, {
159
- btEnabled: true,
160
- });
161
- RaftLog.debug('BLEChannel BLE powered on');
162
- } else if (state === State.PoweredOff) {
163
- this.emit(RaftConnEvent.BLE_BLUETOOTH_STATE, {
164
- btEnabled: false,
165
- });
166
- }
167
- }
168
-
169
- // Get connected locator
170
- getConnectedLocator(): string | Device {
171
- return this._bleDevice || '';
172
- }
173
-
174
- /**
175
- * Get RIC connection status
176
- *
177
- * @returns boolean (true if connected)
178
- *
179
- */
180
- async getIsConnected(forceCheck: boolean = false): Promise<boolean> {
181
- if (this._bleDevice === null) {
182
- return false;
183
- }
184
- if (!forceCheck) {
185
- return true;
186
- }
187
- return await this._bleDevice?.isConnected();
188
- }
189
-
190
- /**
191
- * Get the RSSI of the currently connected device
192
- *
193
- * @return number (or null if not connected)
194
- *
195
- */
196
- async readRSSI(): Promise<number> {
197
- if (this._bleDevice) {
198
- const updatedDevice = await this._bleDevice.readRSSI();
199
- if (updatedDevice.rssi !== null) {
200
- return updatedDevice.rssi;
201
- }
202
- }
203
- // is this a sensible default? should show up as a very weak signal
204
- return -200;
205
- }
206
-
207
- /**
208
- * Connect to a RIC
209
- *
210
- * @returns boolean (true if connected)
211
- *
212
- */
213
- async connect(discoveredDevice: DiscoveredDevice): Promise<boolean> {
214
- RaftLog.debug('BLEChannel requested connection ' + JSON.stringify(discoveredDevice));
215
- this._connectedDeviceServiceUUID = discoveredDevice.serviceUUIDs ? discoveredDevice.serviceUUIDs[0] : undefined;
216
-
217
- this._retryConnectionIfLost = false;
218
- this._bleScanner.scanningStop();
219
-
220
- // Now connecting
221
- this.emit(RaftConnEvent.CONN_CONNECTING, { deviceId: discoveredDevice.id });
222
-
223
- // Connect
224
- this._deviceToConnectTo = discoveredDevice;
225
- const connOk = await this._configDeviceConnection();
226
-
227
- // Check if ok
228
- if (!connOk) {
229
- // Emit failure
230
- this.emit(RaftConnEvent.CONN_CONNECTION_FAILED);
231
- return false;
232
- }
233
-
234
- // Emit success
235
- this.emit(RaftConnEvent.CONN_CONNECTED, {
236
- deviceId: this._deviceToConnectTo.id,
237
- name: this._deviceToConnectTo.name,
238
- });
239
- return true;
240
- }
241
-
242
- /**
243
- * Disconnect from RIC
244
- *
245
- * @returns None
246
- *
247
- */
248
- async disconnect(): Promise<void> {
249
- RaftLog.debug('BLEChannel disconnect requested');
250
- this._retryConnectionIfLost = false;
251
- RaftLog.debug(`this._ricToConnectTo ${this._deviceToConnectTo}`);
252
- const connectedRIC = this._deviceToConnectTo;
253
- this._deviceToConnectTo = null;
254
-
255
- // this._invalidateConnectionInfo(); // //
256
-
257
- // Remove disconnect subscription so it doesn't try to reconnect
258
- if (this._bleSubscrOnDisconnect) {
259
- this._bleSubscrOnDisconnect.remove();
260
- this._bleSubscrOnDisconnect = null;
261
- }
262
- // Disconnect from the connected device
263
- const connMarties = await _bleManager.connectedDevices(
264
- this._serviceUUIDs
265
- );
266
- if (connMarties.length == 0) {
267
- RaftLog.debug('BLEChannel disconnect - no devices connected');
268
- } else {
269
- for (const connRIC of connMarties) {
270
- RaftLog.debug(`Found connected device ${connRIC.id}`);
271
- RaftLog.debug(`ID to disconnect ${connectedRIC?.id}`);
272
- if (connectedRIC?.id === connRIC.id) {
273
- await _bleManager.cancelDeviceConnection(connRIC.id);
274
- }
275
- }
276
- }
277
-
278
- // Emit disconnected event
279
- this.emit(RaftConnEvent.CONN_DISCONNECTED);
280
- RaftLog.debug('BLEChannel disconnect clearing connected device');
281
- this._bleDevice = null;
282
- }
283
-
284
- /**
285
- * Configure device connection
286
- *
287
- * @returns None
288
- *
289
- */
290
- async _configDeviceConnection(): Promise<boolean> {
291
- // Check there is a RIC to connect to
292
- if (this._deviceToConnectTo === null) {
293
- return false;
294
- }
295
-
296
- let deviceConnected: Device | null = null;
297
- for (let connRetry = 0; connRetry < 5; connRetry++) {
298
- try {
299
- deviceConnected = await _bleManager.connectToDevice(
300
- this._deviceToConnectTo.id,
301
- {
302
- timeout: 3000,
303
- },
304
- );
305
- // this.handleLostDevice(); // //
306
- break;
307
- } catch (error) {
308
- RaftLog.debug(
309
- `BLEChannel configDeviceConnection failed at attempt ${connRetry + 1
310
- } error ${error}`,
311
- );
312
- deviceConnected = null;
313
- }
314
- }
315
- if (deviceConnected === null) {
316
- return false;
317
- }
318
-
319
- // Increase MTU size
320
- try {
321
- if (deviceConnected) {
322
- const updatedDevice = await deviceConnected.requestMTU(this.MTU_SIZE_TO_REQUEST);
323
- RaftLog.debug(
324
- `BLEChannel configDeviceConnection requestMTU ${this.MTU_SIZE_TO_REQUEST}, actualMTU ${updatedDevice.mtu}`,
325
- );
326
- }
327
- } catch (error) {
328
- RaftLog.debug(
329
- `BLEChannel configDeviceConnection requestMTU failed error ${error}`,
330
- );
331
- return false;
332
- }
333
-
334
- // Request high-priority connection
335
- try {
336
- await _bleManager.requestConnectionPriorityForDevice(
337
- this._deviceToConnectTo.id,
338
- ConnectionPriority.High,
339
- );
340
- RaftLog.debug(
341
- `BLEChannel configDeviceConnection request ConnPriority.High`,
342
- );
343
- } catch (error) {
344
- RaftLog.debug(
345
- `BLEChannel configDeviceConnection requestConnectionPriorityForDevice failed ${error}`,
346
- );
347
- return false;
348
- }
349
-
350
- // Discover services and characteristics
351
- try {
352
- if (deviceConnected) {
353
- this._bleDevice =
354
- await deviceConnected.discoverAllServicesAndCharacteristics();
355
- }
356
- } catch (error) {
357
- RaftLog.debug(
358
- `BLEChannel configDeviceConnection discoverAllServicesAndCharacteristics failed error ${error}`,
359
- );
360
- return false;
361
- }
362
- // Monitor the inbound characteristic
363
- try {
364
- if (this._bleDevice) {
365
- if (!this._connectedDeviceServiceUUID) {
366
- RaftLog.error('BLEChannel _configDeviceConnection - no connected device service UUID');
367
- return false;
368
- }
369
- this._bleSubscrOnRx = this._bleDevice.monitorCharacteristicForService(
370
- this._connectedDeviceServiceUUID,
371
- this._respUUID,
372
- (error: BleError | null, characteristic: Characteristic | null) => {
373
- this._onMsgRx(error, characteristic);
374
- },
375
- );
376
- }
377
- } catch (error) {
378
- RaftLog.debug(
379
- `BLEChannel configDeviceConnection monitorCharacteristicForService failed ${error}`,
380
- );
381
- return false;
382
- }
383
-
384
- // Deal with future disconnections
385
- this._handleLostConnections();
386
-
387
- return true;
388
- }
389
-
390
- /**
391
- * Handle lost connections
392
- *
393
- * @returns None
394
- *
395
- */
396
- _handleLostConnections(): void {
397
- // Check device ok
398
- if (this._bleDevice === null) {
399
- return;
400
- }
401
-
402
- // Attach a disconnected listener
403
- this._bleSubscrOnDisconnect = _bleManager.onDeviceDisconnected(
404
- this._bleDevice.id,
405
- async () => {
406
- // this._storeConnectionInfo(); // //
407
- // this._invalidateConnectionInfo(); // //
408
- RaftLog.warn(`onDeviceDisconnected BLEManager says device disconnected`);
409
- // this.emit(RaftConnEvent.BLE_CONNECTION_ISSUE_DETECTED);
410
- try {
411
- if (this._bleSubscrOnRx) {
412
- this._bleSubscrOnRx.remove();
413
- this._bleSubscrOnRx = null;
414
- }
415
-
416
- if (this._bleSubscrOnDisconnect) {
417
- this._bleSubscrOnDisconnect.remove();
418
- this._bleSubscrOnDisconnect = null;
419
- }
420
-
421
- // Debug
422
- RaftLog.debug(`connection subscriptions removed`);
423
-
424
- // Device now null
425
- RaftLog.debug(`onDisconnect clearing connected device`);
426
- // this._ghostBleDevice = this._bleDevice; // //
427
- this._bleDevice = null;
428
- } catch (error) {
429
- RaftLog.debug(`Error in onDisconnected ${error}`);
430
- }
431
-
432
- // Attempt reconnection
433
- for (
434
- let reconnAttempt = 0;
435
- reconnAttempt < this.RECONNECT_ATTEMPTS_AFTER_CONN_LOST;
436
- reconnAttempt++
437
- ) {
438
- // Check if scan in progress - and stop reconn attempts if so
439
- const scanInProgress = this._bleScanner.isScanInProgress();
440
- RaftLog.debug(
441
- `onDeviceDisconnected considering reconnection RICToConnectTo ${this._deviceToConnectTo?.name} scanInProgress ${scanInProgress} retryConnectionIfLost ${this._retryConnectionIfLost}`,
442
- );
443
- if (
444
- !this._retryConnectionIfLost ||
445
- scanInProgress ||
446
- !this._deviceToConnectTo
447
- ) {
448
- RaftLog.debug(
449
- `onDeviceDisconnected DISCONNECTED_RIC RICToConnectTo ${this._deviceToConnectTo?.name} scanInProgress ${scanInProgress} retryConnectionIfLost ${this._retryConnectionIfLost}`,
450
- );
451
- if (this._retryConnectionIfLost) {
452
- // this.emit(RaftConnEvent.BLE_DISCONNECTED_RIC);
453
- } else {
454
- // this.emit(RaftConnEvent.BLE_CONNECTING_RIC_FAIL);
455
- }
456
- break;
457
- }
458
- if (await this._configDeviceConnection()) {
459
- RaftLog.debug(
460
- `onDeviceDisconnected successful reconn RICToConnectTo ${this._deviceToConnectTo?.name}`,
461
- );
462
-
463
- // Indicate connection issue resolved
464
- // this.emit(RaftConnEvent.BLE_CONNECTION_ISSUE_RESOLVED);
465
-
466
- // await this.ricConnector.retrieveMartySystemInfo();
467
- return;
468
- }
469
- RaftLog.debug(
470
- `onDeviceDisconnected retrying reconn RICToConnectTo ${this._deviceToConnectTo?.name}`,
471
- );
472
- }
473
- },
474
- );
475
- }
476
-
477
-
478
- getMTU() {
479
- return this._bleDevice?.mtu;
480
- }
481
-
482
- emit(event: RaftConnEvent, data?: any): void {
483
- if (this._onConnEvent) {
484
- this._onConnEvent(event, data);
485
- }
486
- }
487
-
488
- _onMsgRx(error: BleError | null, characteristic: Characteristic | null) {
489
- if (error) {
490
- // this.emit(maybe dont want to emit here - just add to comms stats?);
491
- // this.reportError(error.message);
492
- return;
493
- }
494
-
495
- // Extract message
496
- const msgFrameBase64 = characteristic!.value;
497
-
498
- const rxFrame = RaftUtils.atob(msgFrameBase64!);
499
-
500
- // Debug
501
- // RaftLog.debug('_onMsgRx from BLE ' + RaftUtils.bufferToHex(rxFrame));
502
-
503
- // Send
504
- if (rxFrame !== null && this._raftMsgHandler) {
505
- this._raftMsgHandler.handleNewRxMsg(rxFrame);
506
- }
507
- }
508
-
509
- async scanningEvent(event: RaftConnEvent, data?: any): Promise<void> {
510
- if (this._onConnEvent) {
511
- this._onConnEvent(event, data);
512
- }
513
- }
514
-
515
- async sendTxMsg(
516
- msg: Uint8Array,
517
- // sendWithResponse: boolean,
518
- ): Promise<boolean> {
519
- // Check valid
520
- if (this._bleDevice === null) {
521
- return false;
522
- }
523
-
524
- for (let retryIdx = 0; retryIdx < this.maxRetries; retryIdx++) {
525
-
526
- // Check for min time between messages
527
- while (Date.now() - this._msgTxTimeLast < this._msgTxMinTimeBetweenMs) {
528
- await new Promise(resolve => setTimeout(resolve, 5));
529
- }
530
- this._msgTxTimeLast = Date.now();
531
-
532
- // Convert to Base64
533
- const msgFrameBase64 = RaftUtils.btoa(msg);
534
-
535
- try {
536
- if (!this._connectedDeviceServiceUUID) {
537
- RaftLog.error('BLEChannel sendTxMsg - no connected device service UUID');
538
- return false;
539
- }
540
- await this._bleDevice!.writeCharacteristicWithoutResponseForService(
541
- this._connectedDeviceServiceUUID,
542
- this._cmdUUID,
543
- msgFrameBase64!,
544
- );
545
- return true;
546
- } catch {
547
- if (retryIdx === this.maxRetries - 1) {
548
- RaftLog.debug(`sendTxMsg failed after ${this.maxRetries} attempts`);
549
- return false;
550
- }
551
- RaftLog.debug(`sendTxMsg failed, retrying`);
552
- }
553
- }
554
- return false;
555
- }
556
-
557
- async sendTxMsgNoAwait(
558
- msg: Uint8Array,
559
- // sendWithResponse: boolean,
560
- ): Promise<boolean> {
561
- // Check valid
562
- if (this._bleDevice === null) {
563
- return false;
564
- }
565
-
566
- // Retry upto maxRetries
567
- for (let retryIdx = 0; retryIdx < this.maxRetries; retryIdx++) {
568
-
569
- // Check for min time between messages
570
- while (Date.now() - this._msgTxTimeLast < this._msgTxMinTimeBetweenMs) {
571
- await new Promise(resolve => setTimeout(resolve, 5));
572
- }
573
- this._msgTxTimeLast = Date.now();
574
-
575
- // Convert to Base64
576
- const msgFrameBase64 = RaftUtils.btoa(msg);
577
-
578
- try {
579
- if (!this._connectedDeviceServiceUUID) {
580
- RaftLog.error('BLEChannel sendTxMsgNoAwait - no connected device service UUID');
581
- return false;
582
- }
583
- this._bleDevice!.writeCharacteristicWithoutResponseForService(
584
- this._connectedDeviceServiceUUID,
585
- this._cmdUUID,
586
- msgFrameBase64!,
587
- );
588
- return true;
589
- } catch {
590
- if (retryIdx === this.maxRetries - 1) {
591
- RaftLog.debug(`sendTxMsgNoAwait failed after ${this.maxRetries} attempts`);
592
- return false;
593
- }
594
- RaftLog.debug(`sendTxMsgNoAwait failed, retrying`);
595
- }
596
- }
597
- return false;
598
- }
599
-
600
- // RICREST command before disconnect
601
- ricRestCmdBeforeDisconnect(): string | null {
602
- return "bledisconnect";
603
- }
604
-
605
- // Method used for testing and simulation should never be called
606
- sendTxMsgRaw(): boolean {
607
- RaftLog.debug(`sendTxMsgRaw - not implemented`);
608
- return false;
609
- }
610
-
611
- // Method used for testing and simulation should never be called
612
- sendTxMsgRawAndWaitForReply<T>(): T {
613
- RaftLog.debug(`sendTxMsgRawAndWaitForReply - not implemented`);
614
- return null as T;
615
- }
616
- }