forked from microbit-foundation/cctd-ml-machine
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmockUsb.ts
More file actions
89 lines (77 loc) · 2.55 KB
/
mockUsb.ts
File metadata and controls
89 lines (77 loc) · 2.55 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
import {
AfterRequestDevice,
BeforeRequestDevice,
BoardVersion,
ConnectionStatus,
ConnectionStatusEvent,
DeviceConnectionEventMap,
FlashDataSource,
FlashEvent,
FlashOptions,
MicrobitWebUSBConnection,
SerialConnectionEventMap,
TypedEventTarget,
} from "@microbit/microbit-connection";
/**
* A mock USB connection used during end-to-end testing.
*/
export class MockWebUSBConnection
extends TypedEventTarget<DeviceConnectionEventMap & SerialConnectionEventMap>
implements MicrobitWebUSBConnection
{
status: ConnectionStatus = ConnectionStatus.NO_AUTHORIZED_DEVICE;
private fakeDeviceId: number | undefined = 123;
constructor() {
super();
// Make globally available to allow e2e tests to configure interactions.
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
(window as any).mockUsb = this;
this.fakeDeviceId = Math.round(Math.random() * 1000);
}
async initialize(): Promise<void> {}
dispose(): void {}
mockDeviceId(deviceId: number | undefined) {
this.fakeDeviceId = deviceId;
}
private setStatus(newStatus: ConnectionStatus) {
this.status = newStatus;
this.dispatchTypedEvent("status", new ConnectionStatusEvent(newStatus));
}
async connect(): Promise<ConnectionStatus> {
this.dispatchTypedEvent("beforerequestdevice", new BeforeRequestDevice());
await new Promise((resolve) => setTimeout(resolve, 100));
this.dispatchTypedEvent("afterrequestdevice", new AfterRequestDevice());
await new Promise((resolve) => setTimeout(resolve, 100));
this.setStatus(ConnectionStatus.CONNECTED);
return this.status;
}
getDeviceId(): number | undefined {
return this.fakeDeviceId;
}
getBoardVersion(): BoardVersion | undefined {
return "V2";
}
async flash(
_dataSource: FlashDataSource,
options: FlashOptions
): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 100));
options.progress(50, options.partial);
await new Promise((resolve) => setTimeout(resolve, 100));
options.progress(undefined, options.partial);
this.dispatchTypedEvent("flash", new FlashEvent());
}
async disconnect(): Promise<void> {}
async serialWrite(_data: string): Promise<void> {}
clearDevice(): void {
this.fakeDeviceId = undefined;
this.setStatus(ConnectionStatus.NO_AUTHORIZED_DEVICE);
}
setRequestDeviceExclusionFilters(
_exclusionFilters: USBDeviceFilter[]
): void {}
getDevice(): USBDevice | undefined {
return undefined;
}
async softwareReset(): Promise<void> {}
}