-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathsagas.ts
More file actions
533 lines (456 loc) · 17.8 KB
/
sagas.ts
File metadata and controls
533 lines (456 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// SPDX-License-Identifier: MIT
// Copyright (c) 2020-2026 The Pybricks Authors
//
// Manages connection to a Bluetooth Low Energy device running Pybricks firmware.
// TODO: this file needs to be combined with the firmware BLE connection management
// to reduce duplicated code
import { firmwareVersion } from '@pybricks/firmware';
import { Task, buffers, eventChannel } from 'redux-saga';
import * as semver from 'semver';
import {
call,
cancel,
delay,
fork,
put,
select,
spawn,
take,
takeEvery,
} from 'typed-redux-saga/macro';
import { alertsDidShowAlert, alertsShowAlert } from '../alerts/actions';
import {
bleDIServiceDidReceiveFirmwareRevision,
bleDIServiceDidReceivePnPId,
bleDIServiceDidReceiveSoftwareRevision,
} from '../ble-device-info-service/actions';
import {
decodePnpId,
deviceInformationServiceUUID,
firmwareRevisionStringUUID,
pnpIdUUID,
softwareRevisionStringUUID,
} from '../ble-device-info-service/protocol';
import {
didFailToWrite as didFailToWriteUart,
didNotify as didNotifyUart,
didWrite as didWriteUart,
write as writeUart,
} from '../ble-nordic-uart-service/actions';
import {
nordicUartRxCharUUID,
nordicUartServiceUUID,
nordicUartTxCharUUID,
} from '../ble-nordic-uart-service/protocol';
import {
blePybricksServiceDidNotReceiveHubCapabilities,
blePybricksServiceDidReceiveHubCapabilities,
didFailToWriteCommand,
didNotifyEvent,
didWriteCommand,
writeCommand,
} from '../ble-pybricks-service/actions';
import {
pybricksControlEventCharacteristicUUID,
pybricksHubCapabilitiesCharacteristicUUID,
pybricksServiceUUID,
} from '../ble-pybricks-service/protocol';
import { firmwareInstallPybricks } from '../firmware/actions';
import { RootState } from '../reducers';
import { ensureError } from '../utils';
import { isLinux } from '../utils/os';
import { pythonVersionToSemver } from '../utils/version';
import {
bleConnectPybricks as bleConnectPybricks,
bleDidConnectPybricks,
bleDidDisconnectPybricks,
bleDidFailToConnectPybricks,
bleDisconnectPybricks,
toggleBluetooth,
} from './actions';
import { BleConnectionState } from './reducers';
/** The version of the Pybricks Profile version currently implemented by this file. */
export const supportedPybricksProfileVersion = '1.5.0';
const decoder = new TextDecoder();
function* handlePybricksControlValueChanged(data: DataView): Generator {
yield* put(didNotifyEvent(data));
}
function* handleWriteCommand(
char: BluetoothRemoteGATTCharacteristic,
action: ReturnType<typeof writeCommand>,
): Generator {
// have to spawn to avoid cancellation
yield* spawn(function* () {
try {
yield* call(() => char.writeValueWithResponse(action.value.buffer));
yield* put(didWriteCommand(action.id));
} catch (err) {
yield* put(didFailToWriteCommand(action.id, ensureError(err)));
}
});
}
function* handleUartValueChanged(data: DataView): Generator {
yield* put(didNotifyUart(data));
}
function* handleWriteUart(
char: BluetoothRemoteGATTCharacteristic,
action: ReturnType<typeof writeUart>,
): Generator {
// have to spawn to avoid cancellation
yield* spawn(function* () {
try {
yield* call(() => char.writeValueWithoutResponse(action.value.buffer));
yield* put(didWriteUart(action.id));
} catch (err) {
yield* put(didFailToWriteUart(action.id, ensureError(err)));
}
});
}
function* handleBleConnectPybricks(): Generator {
if (navigator.bluetooth === undefined) {
yield* put(alertsShowAlert('ble', 'noWebBluetooth'));
yield* put(bleDidFailToConnectPybricks());
return;
}
const available = yield* call(() => navigator.bluetooth.getAvailability());
if (!available) {
yield* put(alertsShowAlert('ble', 'bluetoothNotAvailable'));
yield* put(bleDidFailToConnectPybricks());
return;
}
// spawned tasks that will need to be canceled later
const tasks = new Array<Task>();
const defer = new Array<() => void>();
try {
const device = yield* call(() =>
navigator.bluetooth
.requestDevice({
filters: [{ services: [pybricksServiceUUID] }],
optionalServices: [
pybricksServiceUUID,
deviceInformationServiceUUID,
nordicUartServiceUUID,
],
})
.catch((err) => {
if (err instanceof DOMException && err.name === 'NotFoundError') {
// this means the user clicked the cancel button in the scan dialog
return undefined;
}
throw err;
}),
);
if (!device) {
yield* put(alertsShowAlert('ble', 'noHub'));
yield* put(bleDidFailToConnectPybricks());
const { action } = yield* take<
ReturnType<typeof alertsDidShowAlert<'ble', 'noHub'>>
>(
alertsDidShowAlert.when(
(a) => a.domain === 'ble' && a.specific === 'noHub',
),
);
if (action === 'flashFirmware') {
yield* put(firmwareInstallPybricks());
}
return;
}
const gatt = device.gatt;
if (!gatt) {
yield* put(alertsShowAlert('ble', 'noGatt'));
yield* put(bleDidFailToConnectPybricks());
return;
}
const disconnectChannel = eventChannel<Event>((emit) => {
device.addEventListener('gattserverdisconnected', emit);
return (): void =>
device.removeEventListener('gattserverdisconnected', emit);
}, buffers.sliding(1));
defer.push(() => disconnectChannel.close());
const server = yield* call(() => gatt.connect());
defer.push(() => server.disconnect());
// istanbul ignore if
if (process.env.NODE_ENV !== 'test') {
// give OS Bluetooth stack some time to settle
yield* delay(1000);
}
const deviceInfoService = yield* call(() =>
server.getPrimaryService(deviceInformationServiceUUID).catch((err) => {
if (err instanceof DOMException && err.name === 'NotFoundError') {
return undefined;
}
throw err;
}),
);
if (!deviceInfoService) {
yield* put(
alertsShowAlert('ble', 'missingService', {
serviceName: 'Device Information',
hubName: device.name || 'Pybricks Hub',
}),
);
yield* put(bleDidFailToConnectPybricks());
return;
}
const firmwareVersionChar = yield* call(() =>
deviceInfoService.getCharacteristic(firmwareRevisionStringUUID),
);
const firmwareRevision = decoder.decode(
yield* call(() => firmwareVersionChar.readValue()),
);
yield* put(bleDIServiceDidReceiveFirmwareRevision(firmwareRevision));
// notify user if old firmware
if (
semver.lt(
pythonVersionToSemver(firmwareRevision),
pythonVersionToSemver(firmwareVersion),
)
) {
yield* put(alertsShowAlert('ble', 'oldFirmware'));
// initiate flashing firmware if user requested
const flashIfRequested = function* () {
const { action } = yield* take<
ReturnType<typeof alertsDidShowAlert<'ble', 'oldFirmware'>>
>(
alertsDidShowAlert.when(
(a) => a.domain === 'ble' && a.specific === 'oldFirmware',
),
);
if (action === 'flashFirmware') {
yield* put(firmwareInstallPybricks());
}
};
// have to spawn so that we don't block the task and it still works
// if parent task ends
yield* spawn(flashIfRequested);
}
const softwareVersionChar = yield* call(() =>
deviceInfoService.getCharacteristic(softwareRevisionStringUUID),
);
const softwareRevision = decoder.decode(
yield* call(() => softwareVersionChar.readValue()),
);
yield* put(bleDIServiceDidReceiveSoftwareRevision(softwareRevision));
// notify user if newer Pybricks Profile on hub
if (
semver.gte(
softwareRevision,
new semver.SemVer(supportedPybricksProfileVersion).inc('minor'),
)
) {
yield* put(
alertsShowAlert('ble', 'newPybricksProfile', {
hubVersion: softwareRevision,
supportedVersion: supportedPybricksProfileVersion,
}),
);
}
const pnpIdChar = yield* call(() =>
deviceInfoService.getCharacteristic(pnpIdUUID).catch((err) => {
if (err instanceof DOMException && err.name === 'NotFoundError') {
return undefined;
}
throw err;
}),
);
if (!pnpIdChar) {
// possible with firmware < v3.1.0
throw new Error('missing PnP ID characteristic');
}
const pnpId = decodePnpId(yield* call(() => pnpIdChar.readValue()));
yield* put(bleDIServiceDidReceivePnPId(pnpId));
const pybricksService = yield* call(() =>
server.getPrimaryService(pybricksServiceUUID).catch((err) => {
if (err instanceof DOMException && err.name === 'NotFoundError') {
return undefined;
}
throw err;
}),
);
if (!pybricksService) {
yield* put(
alertsShowAlert('ble', 'missingService', {
serviceName: 'Pybricks',
hubName: device.name || 'Pybricks Hub',
}),
);
yield* put(bleDidFailToConnectPybricks());
return;
}
const pybricksControlChar = yield* call(() =>
pybricksService.getCharacteristic(pybricksControlEventCharacteristicUUID),
);
const pybricksControlChannel = eventChannel<DataView>((emit) => {
const listener = (): void => {
if (!pybricksControlChar.value) {
return;
}
emit(pybricksControlChar.value);
};
pybricksControlChar.addEventListener(
'characteristicvaluechanged',
listener,
);
return (): void =>
pybricksControlChar.removeEventListener(
'characteristicvaluechanged',
listener,
);
});
defer.push(() => pybricksControlChannel.close());
tasks.push(
yield* takeEvery(pybricksControlChannel, handlePybricksControlValueChanged),
);
// REVISIT: possible Pybricks firmware bug (or chromium bug on Linux)
// where 'characteristicvaluechanged' is not called after disconnecting
// and reconnecting unless we stop notifications before we start them
// again. Wireshark shows that no enable notification descriptor write
// is performed but notifications are received.
yield* call(() => pybricksControlChar.stopNotifications());
yield* call(() => pybricksControlChar.startNotifications());
tasks.push(
yield* takeEvery(writeCommand, handleWriteCommand, pybricksControlChar),
);
// hub capabilities characteristic was introduced in Pybricks Profile v1.2.0
if (semver.satisfies(softwareRevision, '^1.2.0')) {
const pybricksHubCapabilitiesChar = yield* call(() =>
pybricksService.getCharacteristic(
pybricksHubCapabilitiesCharacteristicUUID,
),
);
const hubCapabilitiesValue = yield* call(() =>
pybricksHubCapabilitiesChar.readValue(),
);
const maxWriteSize = hubCapabilitiesValue.getUint16(0, true);
const flags = hubCapabilitiesValue.getUint32(2, true);
const maxUserProgramSize = hubCapabilitiesValue.getUint32(6, true);
const numOfSlots = (() => {
if (semver.satisfies(softwareRevision, '^1.5.0')) {
return hubCapabilitiesValue.getUint8(10);
}
return 0;
})();
yield* put(
blePybricksServiceDidReceiveHubCapabilities(
maxWriteSize,
flags,
maxUserProgramSize,
numOfSlots,
),
);
} else {
yield* put(
blePybricksServiceDidNotReceiveHubCapabilities(pnpId, firmwareRevision),
);
}
// Nordic UART service is removed starting with Pybricks Profile v1.5.0
if (!semver.satisfies(softwareRevision, '^1.5.0')) {
const uartService = yield* call(() =>
server.getPrimaryService(nordicUartServiceUUID).catch((err) => {
if (err instanceof DOMException && err.name === 'NotFoundError') {
return undefined;
}
throw err;
}),
);
if (!uartService) {
yield* put(
alertsShowAlert('ble', 'missingService', {
serviceName: 'Nordic UART',
hubName: device.name || 'Pybricks Hub',
}),
);
yield* put(bleDidFailToConnectPybricks());
return;
}
const uartRxChar = yield* call(() =>
uartService.getCharacteristic(nordicUartRxCharUUID),
);
const uartTxChar = yield* call(() =>
uartService.getCharacteristic(nordicUartTxCharUUID),
);
const uartTxChannel = eventChannel<DataView>((emitter) => {
const listener = (): void => {
if (!uartTxChar.value) {
return;
}
emitter(uartTxChar.value);
};
uartTxChar.addEventListener('characteristicvaluechanged', listener);
return (): void =>
uartTxChar.removeEventListener(
'characteristicvaluechanged',
listener,
);
});
defer.push(() => uartTxChannel.close());
tasks.push(yield* takeEvery(uartTxChannel, handleUartValueChanged));
// REVISIT: possible Pybricks firmware bug (or chromium bug on Linux)
// where 'characteristicvaluechanged' is not called after disconnecting
// and reconnecting unless we stop notifications before we start them
// again. Wireshark shows that no enable notification descriptor write
// is performed but notifications are received.
yield* call(() => uartTxChar.stopNotifications());
yield* call(() => uartTxChar.startNotifications());
tasks.push(yield* takeEvery(writeUart, handleWriteUart, uartRxChar));
}
yield* put(bleDidConnectPybricks(device.id, device.name || ''));
const handleDisconnectRequest = function* (): Generator {
yield* take(bleDisconnectPybricks);
server.disconnect();
};
yield* fork(handleDisconnectRequest);
// wait for disconnection
yield* take(disconnectChannel);
// HACK: Disconnection event comes early on Linux when server.disconnect()
// is called, so scanning again can show that the previous connection is
// still "paired" and trying to select it results in an infinite wait.
// To work around this, we need to wait long enough for BlueZ to actually
// disconnect the device.
// https://github.com/pybricks/support/issues/600#issuecomment-1286606624
// istanbul ignore if
if (process.env.NODE_ENV !== 'test' && isLinux()) {
const wasDisconnectRequestedByUser = yield* select(
(s: RootState) => s.ble.connection === BleConnectionState.Disconnecting,
);
if (wasDisconnectRequestedByUser) {
yield* delay(5000);
}
}
yield* put(bleDidDisconnectPybricks());
} catch (err) {
// istanbul ignore if
if (process.env.NODE_ENV !== 'test') {
// log error so it can still be copied even if alert is closed
console.error(err);
}
yield* put(
alertsShowAlert('alerts', 'unexpectedError', {
error: ensureError(err),
}),
);
yield* put(bleDidFailToConnectPybricks());
} finally {
yield* cancel(tasks);
while (defer.length > 0) {
defer.pop()?.();
}
}
}
function* handleToggleBluetooth(): Generator {
const connectionState = (yield select(
(s: RootState) => s.ble.connection,
)) as BleConnectionState;
switch (connectionState) {
case BleConnectionState.Connected:
yield* put(bleDisconnectPybricks());
break;
case BleConnectionState.Disconnected:
yield* put(bleConnectPybricks());
break;
}
}
export default function* (): Generator {
yield* takeEvery(bleConnectPybricks, handleBleConnectPybricks);
yield* takeEvery(toggleBluetooth, handleToggleBluetooth);
}