-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathsagas.ts
More file actions
707 lines (611 loc) · 23.1 KB
/
sagas.ts
File metadata and controls
707 lines (611 loc) · 23.1 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// SPDX-License-Identifier: MIT
// Copyright (c) 2025 The Pybricks Authors
import { firmwareVersion } from '@pybricks/firmware';
import { AnyAction } from 'redux';
import { eventChannel } from 'redux-saga';
import semver from 'semver';
import {
actionChannel,
call,
delay,
fork,
put,
race,
select,
spawn,
take,
takeEvery,
} from 'typed-redux-saga/macro';
import { alertsDidShowAlert, alertsShowAlert } from '../alerts/actions';
import { BleConnectionState } from '../ble/reducers';
import { supportedPybricksProfileVersion } from '../ble/sagas';
import {
PnpIdVendorIdSource,
deviceNameUUID,
firmwareRevisionStringUUID,
softwareRevisionStringUUID,
} from '../ble-device-info-service/protocol';
import {
blePybricksServiceDidReceiveHubCapabilities,
didFailToWriteCommand,
didNotifyEvent,
didWriteCommand,
writeCommand,
} from '../ble-pybricks-service/actions';
import { pybricksHubCapabilitiesCharacteristicUUID } from '../ble-pybricks-service/protocol';
import { firmwareInstallPybricks } from '../firmware/actions';
import { RootState } from '../reducers';
import { assert, defined, ensureError, maybe } from '../utils';
import { pythonVersionToSemver } from '../utils/version';
import {
usbConnectPybricks,
usbDidConnectPybricks,
usbDidDisconnectPybricks,
usbDidFailToConnectPybricks,
usbDidReceiveDeviceName,
usbDidReceiveFirmwareRevision,
usbDidReceivePybricksMessageResponse,
usbDidReceiveSoftwareRevision,
usbDisconnectPybricks,
usbHotPlugConnectPybricks,
usbPybricksDidFailToSubscribe,
usbPybricksDidFailToUnsubscribe,
usbPybricksDidSubscribe,
usbPybricksDidUnsubscribe,
usbPybricksSubscribe,
usbPybricksUnsubscribe,
usbToggle,
} from './actions';
import { UsbConnectionState } from './reducers';
import {
PybricksUsbInEndpointMessageType,
PybricksUsbInterfaceRequest,
PybricksUsbOutEndpointMessageType,
pybricksUsbClass,
pybricksUsbProtocol,
pybricksUsbRequestMaxLength,
pybricksUsbSubclass,
uuid16,
} from '.';
const textDecoder = new TextDecoder('utf-8');
function* handleUsbConnectPybricks(hotPlugDevice?: USBDevice): Generator {
// Normally, this would be triggered by usbConnectPybricks(), but on hotplug
// events, this doens't happen, so we need a different action to trigger
// so that reducers still work correctly.
if (hotPlugDevice !== undefined) {
yield* put(usbHotPlugConnectPybricks());
}
if (navigator.usb === undefined) {
yield* put(alertsShowAlert('usb', 'noWebUsb'));
yield* put(usbDidFailToConnectPybricks());
return;
}
const exitStack: Array<() => Promise<void>> = [];
function* cleanup() {
for (const func of exitStack.reverse()) {
yield* call(() => func());
}
}
const disconnectChannel = eventChannel<USBConnectionEvent>((emitter) => {
navigator.usb.addEventListener('disconnect', emitter);
return () => {
navigator.usb.removeEventListener('disconnect', emitter);
};
});
exitStack.push(async () => disconnectChannel.close());
let usbDevice: USBDevice;
// if we are not responding to a hotplug event, we need to request the device
if (hotPlugDevice === undefined) {
const [reqDevice, reqDeviceErr] = yield* call(() =>
maybe(
navigator.usb.requestDevice({
filters: [
{
classCode: pybricksUsbClass,
subclassCode: pybricksUsbSubclass,
protocolCode: pybricksUsbProtocol,
},
],
}),
),
);
if (reqDeviceErr) {
if (reqDeviceErr.name === 'NotFoundError') {
// This means the user canceled the device selection dialog.
// REVISIT: should we show noHub message like BLE?
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
console.error('Failed to request USB device:', reqDeviceErr);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
defined(reqDevice);
usbDevice = reqDevice;
} else {
usbDevice = hotPlugDevice;
}
const [, openErr] = yield* call(() => maybe(usbDevice.open()));
if (openErr) {
// TODO: show error message to user here
console.error('Failed to open USB device:', openErr);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
exitStack.push(() => usbDevice.close().catch(console.debug));
const [, selectErr] = yield* call(() => maybe(usbDevice.selectConfiguration(1)));
if (selectErr) {
// TODO: show error message to user here
console.error('Failed to select USB device configuration:', selectErr);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
assert(usbDevice.configuration !== null, 'USB device configuration is null');
const iface = usbDevice.configuration.interfaces.find(
(iface) =>
iface.alternate.interfaceClass === pybricksUsbClass &&
iface.alternate.interfaceSubclass === pybricksUsbSubclass &&
iface.alternate.interfaceProtocol === pybricksUsbProtocol,
);
assert(iface !== undefined, 'USB device does not have a Pybricks interface');
const inEndpoint = iface.alternate.endpoints.find(
(ep) => ep.direction === 'in' && ep.type === 'bulk',
);
assert(
inEndpoint !== undefined,
'USB device does not have a bulk IN endpoint for Pybricks interface',
);
const outEndpoint = iface.alternate.endpoints.find(
(ep) => ep.direction === 'out' && ep.type === 'bulk',
);
assert(
outEndpoint !== undefined,
'USB device does not have a bulk OUT endpoint for Pybricks interface',
);
const [, claimErr] = yield* call(() =>
maybe(usbDevice.claimInterface(iface.interfaceNumber)),
);
if (claimErr) {
// TODO: show error message to user here
console.error('Failed to claim USB interface:', claimErr);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
exitStack.push(() => usbDevice.releaseInterface(0).catch(console.debug));
const [fwVerResult, fwVerError] = yield* call(() =>
maybe(
usbDevice.controlTransferIn(
{
requestType: 'class',
recipient: 'interface',
request: PybricksUsbInterfaceRequest.Gatt,
value: firmwareRevisionStringUUID,
index: 0x00,
},
pybricksUsbRequestMaxLength,
),
),
);
if (fwVerError || fwVerResult?.status !== 'ok') {
// TODO: show error message to user here
console.error('Failed to get firmware version:', fwVerError);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
defined(fwVerResult);
const firmwareRevision = textDecoder.decode(fwVerResult.data);
yield* put(usbDidReceiveFirmwareRevision(firmwareRevision));
// notify user if old firmware
if (
semver.lt(
pythonVersionToSemver(firmwareRevision),
pythonVersionToSemver(firmwareVersion),
)
) {
yield* put(alertsShowAlert('usb', 'oldFirmware'));
// initiate flashing firmware if user requested
const flashIfRequested = function* () {
const { action } = yield* take<
ReturnType<typeof alertsDidShowAlert<'usb', 'oldFirmware'>>
>(
alertsDidShowAlert.when(
(a) => a.domain === 'usb' && 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 [nameResult, nameError] = yield* call(() =>
maybe(
usbDevice.controlTransferIn(
{
requestType: 'class',
recipient: 'interface',
request: PybricksUsbInterfaceRequest.Gatt,
value: deviceNameUUID,
index: 0x00,
},
pybricksUsbRequestMaxLength,
),
),
);
if (nameError || nameResult?.status !== 'ok') {
// TODO: show error message to user here
console.error('Failed to get device name:', nameError);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
defined(nameResult);
const deviceName = textDecoder.decode(nameResult.data);
yield* put(usbDidReceiveDeviceName(deviceName));
const [swVerResult, swVerError] = yield* call(() =>
maybe(
usbDevice.controlTransferIn(
{
requestType: 'class',
recipient: 'interface',
request: PybricksUsbInterfaceRequest.Gatt,
value: softwareRevisionStringUUID,
index: 0x00,
},
pybricksUsbRequestMaxLength,
),
),
);
if (swVerError || swVerResult?.status !== 'ok') {
// TODO: show error message to user here
console.error('Failed to get software version:', swVerError);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
defined(swVerResult);
const softwareRevision = textDecoder.decode(swVerResult.data);
yield* put(usbDidReceiveSoftwareRevision(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 [hubCapResult, hubCapErr] = yield* call(() =>
maybe(
usbDevice.controlTransferIn(
{
requestType: 'class',
recipient: 'interface',
request: PybricksUsbInterfaceRequest.Pybricks,
value: uuid16(pybricksHubCapabilitiesCharacteristicUUID),
index: 0x00,
},
pybricksUsbRequestMaxLength,
),
),
);
if (hubCapErr || hubCapResult?.status !== 'ok') {
// TODO: show error message to user here
console.error('Failed to get hub capabilities:', hubCapErr);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
defined(hubCapResult);
assert(hubCapResult.data !== undefined, 'Hub capabilities data is undefined');
const hubCapabilitiesValue = new DataView(hubCapResult.data.buffer);
const maxWriteSize = hubCapabilitiesValue.getUint16(0, true);
const flags = hubCapabilitiesValue.getUint32(2, true);
const maxUserProgramSize = hubCapabilitiesValue.getUint32(6, true);
const numOfSlots = hubCapabilitiesValue.getUint8(10);
yield* put(
blePybricksServiceDidReceiveHubCapabilities(
maxWriteSize,
flags,
maxUserProgramSize,
numOfSlots,
),
);
// This services the Pybricks interface IN endpoint and pipes messages
// to the correct place depending on the message type. We need to get this
// up and running before subscribing to events or sending commands so that
// we can receive responses.
function* receiveMessages(): Generator {
defined(usbDevice);
defined(inEndpoint);
defined(outEndpoint);
for (;;) {
const [result, err] = yield* call(() =>
maybe(
usbDevice.transferIn(
inEndpoint.endpointNumber,
inEndpoint.packetSize,
),
),
);
if (err) {
// TODO: notify user that USB is broken (if not disconnected)
console.error('Failed to receive USB message:', err);
return;
}
if (result?.status !== 'ok') {
console.warn('USB message transfer failed:', result);
continue;
}
assert(result.data !== undefined, 'USB message data is undefined');
if (result.data.byteLength < 1) {
// empty messages are normal, just ignore them
continue;
}
console.debug('Received USB message:', result.data);
switch (result.data.getInt8(0)) {
case PybricksUsbInEndpointMessageType.Response:
yield* put(
usbDidReceivePybricksMessageResponse(
result.data.getUint32(1, true),
),
);
break;
case PybricksUsbInEndpointMessageType.Event:
yield* put(
didNotifyEvent(new DataView(result.data.buffer.slice(1))),
);
break;
default:
console.warn('Unknown USB message type:', result.data.getInt8(0));
break;
}
}
}
const receiveMessagesTask = yield* fork(receiveMessages);
exitStack.push(async () => receiveMessagesTask.cancel());
// This is used to serialize requests to the Pybricks interface OUT endpoint.
// It makes sure that we wait for a response for each command before sending
// the next one.
function* sendMessages(): Generator {
defined(usbDevice);
defined(outEndpoint);
const chan = yield* actionChannel<AnyAction>(
(a: AnyAction) =>
usbPybricksSubscribe.matches(a) ||
usbPybricksUnsubscribe.matches(a) ||
writeCommand.matches(a),
);
for (;;) {
const action = yield* take(chan);
console.debug('Processing USB action:', action);
if (usbPybricksSubscribe.matches(action)) {
const message = new DataView(new ArrayBuffer(2));
message.setUint8(0, PybricksUsbOutEndpointMessageType.Subscribe);
message.setUint8(1, 1); // subscribe to events
const [result, err] = yield* call(() =>
maybe(usbDevice.transferOut(outEndpoint.endpointNumber, message)),
);
if (err || result?.status !== 'ok') {
yield* put(usbPybricksDidFailToSubscribe());
console.error('Failed to send USB subscribe message:', err, result);
continue;
}
yield* put(usbPybricksDidSubscribe());
continue;
}
if (usbPybricksUnsubscribe.matches(action)) {
const message = new DataView(new ArrayBuffer(2));
message.setUint8(0, PybricksUsbOutEndpointMessageType.Subscribe);
message.setUint8(1, 0); // unsubscribe from events
const [result, err] = yield* call(() =>
maybe(usbDevice.transferOut(outEndpoint.endpointNumber, message)),
);
if (err || result?.status !== 'ok') {
yield* put(usbPybricksDidFailToUnsubscribe());
console.error(
'Failed to send USB unsubscribe message:',
err,
result,
);
continue;
}
yield* put(usbPybricksDidUnsubscribe());
continue;
}
if (writeCommand.matches(action)) {
const payload = new Uint8Array(1 + action.value.length);
payload[0] = PybricksUsbOutEndpointMessageType.Command;
payload.set(action.value, 1);
const message = new DataView(payload.buffer);
const [result, err] = yield* call(() =>
maybe(usbDevice.transferOut(outEndpoint.endpointNumber, message)),
);
if (err) {
yield* put(didFailToWriteCommand(action.id, ensureError(err)));
console.error('Failed to send USB command:', err, result);
continue;
}
if (result?.status !== 'ok') {
yield* put(
didFailToWriteCommand(action.id, ensureError(result?.status)),
);
console.error('Failed to send USB command:', result);
continue;
}
const { response, timeout } = yield* race({
response: take(usbDidReceivePybricksMessageResponse),
timeout: delay(1000),
});
if (timeout) {
yield* put(
didFailToWriteCommand(
action.id,
new Error('Timed out waiting for response'),
),
);
console.error('Timed out waiting for USB command response');
continue;
}
defined(response);
if (response.statusCode !== 0) {
yield* put(
didFailToWriteCommand(
action.id,
new Error(
`USB command failed with status code ${response.statusCode}`,
),
),
);
console.error('USB command failed:', response);
continue;
}
yield* put(didWriteCommand(action.id));
continue;
}
console.error(`Unknown USB action type: ${action.type}`);
}
}
const sendMessagesTask = yield* fork(sendMessages);
exitStack.push(async () => sendMessagesTask.cancel());
yield* put(usbPybricksSubscribe());
const { didFailToSub } = yield* race({
didSub: take(usbPybricksDidSubscribe),
didFailToSub: take(usbPybricksDidFailToSubscribe),
});
if (didFailToSub) {
console.error('Failed to subscribe to USB Pybricks messages:', didFailToSub);
yield* put(usbDidFailToConnectPybricks());
yield* cleanup();
return;
}
// TODO: how to push put(usbPybricksUnsubscribe()) on exit stack?
yield* put(
usbDidConnectPybricks({
vendorIdSource: PnpIdVendorIdSource.UsbImpForum,
vendorId: usbDevice.vendorId,
productId: usbDevice.productId,
productVersion: 0,
}),
);
// wait for the user to request disconnecting the USB device or for the
// USB device to be physically disconnected
for (;;) {
const { disconnectRequest, disconnectEvent } = yield* race({
disconnectRequest: take(usbDisconnectPybricks),
disconnectEvent: take(disconnectChannel),
});
console.debug('USB disconnect request or event received:', {
disconnectRequest,
disconnectEvent,
});
if (disconnectRequest || disconnectEvent?.device === usbDevice) {
break;
}
}
yield* put(usbPybricksUnsubscribe());
yield* race({
didUnsub: take(usbPybricksDidUnsubscribe),
didFailToUnsub: take(usbPybricksDidFailToUnsubscribe),
});
yield* cleanup();
yield* put(usbDidDisconnectPybricks());
}
function* handleUsbToggle(): Generator {
const connectionState = (yield select(
(s: RootState) => s.usb.connection,
)) as UsbConnectionState;
console.debug('Handling USB toggle action, current state:', connectionState);
switch (connectionState) {
case UsbConnectionState.Connected:
yield* put(usbDisconnectPybricks());
break;
case UsbConnectionState.Disconnected:
yield* put(usbConnectPybricks());
break;
}
}
function* handleUsbConnectEvent(): Generator {
if (navigator.usb === undefined) {
return;
}
const [devices, devicesError] = yield* call(() =>
maybe(navigator.usb.getDevices()),
);
if (devicesError) {
console.error('Failed to get USB devices:', devicesError);
} else {
defined(devices);
const pybricksDevices = devices.filter(
(d) =>
d.deviceClass === pybricksUsbClass &&
d.deviceSubclass === pybricksUsbSubclass &&
d.deviceProtocol === pybricksUsbProtocol,
);
// if there is exactly one Pybricks device connected, we can connect to
// it, otherwise we should let the user choose which one to connect to
if (pybricksDevices.length === 1) {
yield* spawn(handleUsbConnectPybricks, pybricksDevices[0]);
}
}
const channel = eventChannel<USBConnectionEvent>((emitter) => {
navigator.usb.addEventListener('connect', emitter);
return () => {
navigator.usb.removeEventListener('connect', emitter);
};
});
for (;;) {
const event = yield* take(channel);
console.log('USB device connected:', event);
if (
event.device.deviceClass !== pybricksUsbClass ||
event.device.deviceSubclass !== pybricksUsbSubclass ||
event.device.deviceProtocol !== pybricksUsbProtocol
) {
continue;
}
const state = yield* select((s: RootState) => s);
// If we are not already connected, we can connect to the hub that
// was just connected.
if (
state.ble.connection === BleConnectionState.Disconnected &&
state.usb.connection === UsbConnectionState.Disconnected
) {
yield* spawn(handleUsbConnectPybricks, event.device);
}
}
}
function* handleUsbDisconnectEvent(): Generator {
if (navigator.usb === undefined) {
return;
}
const channel = eventChannel<USBConnectionEvent>((emitter) => {
navigator.usb.addEventListener('disconnect', emitter);
return () => {
navigator.usb.removeEventListener('disconnect', emitter);
};
});
for (;;) {
const event = yield* take(channel);
console.log('USB device disconnected:', event);
}
}
export default function* (): Generator {
yield* takeEvery(usbConnectPybricks, handleUsbConnectPybricks, undefined);
yield* takeEvery(usbToggle, handleUsbToggle);
yield* spawn(handleUsbConnectEvent);
yield* spawn(handleUsbDisconnectEvent);
}