-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathsimulator.ts
429 lines (378 loc) · 10.1 KB
/
simulator.ts
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
/**
* (c) 2021, Micro:bit Educational Foundation and contributors
*
* SPDX-License-Identifier: MIT
*/
import { TypedEventTarget } from "../common/events";
import { Logging } from "../logging/logging";
import {
BoardVersion,
ConnectionStatus,
DeviceConnection,
DeviceConnectionEventMap,
FlashDataSource,
FlashEvent,
SerialDataEvent,
SerialResetEvent,
ConnectionStatusEvent,
} from "./device";
// Simulator-only events.
export class LogDataEvent extends Event {
constructor(public readonly log: DataLog) {
super("log_data");
}
}
export class RadioDataEvent extends Event {
constructor(public readonly text: string) {
super("radio_data");
}
}
export class RadioGroupEvent extends Event {
constructor(public readonly group: number) {
super("radio_group");
}
}
export class RadioResetEvent extends Event {
constructor() {
super("radio_reset");
}
}
export class StateChangeEvent extends Event {
constructor(public readonly state: SimulatorState) {
super("state_change");
}
}
export class RequestFlashEvent extends Event {
constructor() {
super("request_flash");
}
}
// It'd be nice to publish these types from the simulator project.
export interface RadioState {
type: "radio";
enabled: boolean;
group: number;
}
export interface DataLoggingState {
type: "dataLogging";
logFull: boolean;
}
export interface RangeSensor {
type: "range";
id: string;
value: number;
min: number;
max: number;
unit: number;
lowThreshold?: number;
highThreshold?: number;
}
export interface EnumSensor {
type: "enum";
id: string;
value: string;
choices: string[];
}
export type Sensor = RangeSensor | EnumSensor;
export interface LogEntry {
headings?: string[];
data?: string[];
}
export interface SimulatorState {
radio: RadioState;
dataLogging: DataLoggingState;
accelerometerX: RangeSensor;
accelerometerY: RangeSensor;
accelerometerZ: RangeSensor;
gesture: EnumSensor;
compassX: RangeSensor;
compassY: RangeSensor;
compassZ: RangeSensor;
compassHeading: RangeSensor;
pin0: RangeSensor;
pin1: RangeSensor;
pin2: RangeSensor;
pinLogo: RangeSensor;
temperature: RangeSensor;
lightLevel: RangeSensor;
soundLevel: RangeSensor;
buttonA: RangeSensor;
buttonB: RangeSensor;
}
export type SimulatorStateKey = keyof SimulatorState;
export type SensorStateKey = Extract<
SimulatorStateKey,
| "accelerometerX"
| "accelerometerY"
| "accelerometerZ"
| "compassX"
| "compassY"
| "compassZ"
| "compassHeading"
| "gesture"
| "pin0"
| "pin1"
| "pin2"
| "pinLogo"
| "temperature"
| "lightLevel"
| "soundLevel"
| "buttonA"
| "buttonB"
>;
interface Config {
language: string;
translations: Record<string, string>;
}
export interface DataLog {
headings: string[];
data: DataLogRow[];
}
export interface DataLogRow {
isHeading?: boolean;
data: string[];
}
const initialDataLog = (): DataLog => ({
headings: [],
data: [],
});
class SimulatorEventMap extends DeviceConnectionEventMap {
"log_data": LogDataEvent;
"radio_data": RadioDataEvent;
"radio_group": RadioGroupEvent;
"radio_reset": RadioResetEvent;
"state_change": StateChangeEvent;
"request_flash": RequestFlashEvent;
}
/**
* A simulated device.
*
* This communicates with the iframe that is used to embed the simulator.
*/
export class SimulatorDeviceConnection
extends TypedEventTarget<SimulatorEventMap>
implements DeviceConnection
{
status: ConnectionStatus = ConnectionStatus.NO_AUTHORIZED_DEVICE;
state: SimulatorState | undefined;
log: DataLog = initialDataLog();
private messageListener = (event: MessageEvent) => {
const iframe = this.iframe();
if (!iframe || event.source !== iframe.contentWindow || !event.data.kind) {
// Not an event for us.
return;
}
switch (event.data.kind) {
case "ready": {
const newState = event.data.state;
this.state = newState;
this.dispatchTypedEvent("state_change", new StateChangeEvent(newState));
if (this.status !== ConnectionStatus.CONNECTED) {
this.setStatus(ConnectionStatus.CONNECTED);
}
break;
}
case "request_flash": {
this.dispatchTypedEvent("request_flash", new RequestFlashEvent());
this.logging.event({
type: "sim-user-start",
});
break;
}
case "state_change": {
const updated = {
...this.state,
...event.data.change,
};
this.state = updated;
this.dispatchTypedEvent("state_change", new StateChangeEvent(updated));
break;
}
case "radio_output": {
// So this is a Uint8Array that may be prefixed with 0, 1, 0 bytes to indicate that it's a "string".
// Either way we only display strings for now so convert at this layer.
// If it's really binary data then TextEncoder will put replacement characters in and we'll live with that for now.
const message = event.data.data;
const text = new TextDecoder()
.decode(message)
// eslint-disable-next-line no-control-regex
.replace(/^\x01\x00\x01/, "");
if (message instanceof Uint8Array) {
this.dispatchTypedEvent("radio_data", new RadioDataEvent(text));
}
break;
}
case "log_output": {
const entry: LogEntry = event.data;
const result: DataLog = {
headings: entry.headings ?? this.log.headings,
data: this.log.data,
};
// The first row is all-time headings row so don't show the initial set.
if (entry.headings && this.log.data.length > 0) {
result.data.push({ isHeading: true, data: entry.headings });
}
if (entry.data) {
result.data.push({ data: entry.data });
}
this.log = result;
this.dispatchTypedEvent("log_data", new LogDataEvent(this.log));
break;
}
case "log_delete": {
this.log = initialDataLog();
this.dispatchTypedEvent("log_data", new LogDataEvent(this.log));
break;
}
case "serial_output": {
const text = event.data.data;
if (typeof text === "string") {
this.dispatchTypedEvent("serial_data", new SerialDataEvent(text));
}
break;
}
case "internal_error": {
const error = event.data.error;
this.logging.error(error);
break;
}
default: {
// Ignore unknown message.
}
}
};
constructor(
private logging: Logging,
private iframe: () => HTMLIFrameElement | null,
private sensorsLogged: Record<string, boolean> = {}
) {
super();
}
private logSensor(sensorId: string): void {
if (!this.sensorsLogged[sensorId]) {
this.logging.event({
type: `sim-user-${sensorId}`,
});
this.sensorsLogged[sensorId] = true;
}
}
async initialize(): Promise<void> {
window.addEventListener("message", this.messageListener);
this.setStatus(ConnectionStatus.NOT_CONNECTED);
}
dispose() {
window.removeEventListener("message", this.messageListener);
}
async connect(): Promise<ConnectionStatus> {
this.setStatus(ConnectionStatus.CONNECTED);
return this.status;
}
getBoardVersion(): BoardVersion | null {
return "V2";
}
async flash(
dataSource: FlashDataSource,
options: {
partial: boolean;
progress: (percentage: number | undefined) => void;
}
): Promise<void> {
this.postMessage("flash", {
filesystem: await dataSource.files(),
});
this.notifyResetComms();
options.progress(undefined);
this.dispatchTypedEvent("flash", new FlashEvent());
}
configure(config: Config): void {
this.postMessage("config", config);
}
private notifyResetComms() {
// Might be nice to rework so this was all about connection state changes.
this.dispatchTypedEvent("serial_reset", new SerialResetEvent());
this.dispatchTypedEvent("radio_reset", new RadioResetEvent());
}
async disconnect(): Promise<void> {
window.removeEventListener("message", this.messageListener);
this.setStatus(ConnectionStatus.NOT_CONNECTED);
}
async serialWrite(data: string): Promise<void> {
this.postMessage("serial_input", {
data,
});
}
radioSend(message: string) {
const kind = "radio_input";
const data = new TextEncoder().encode(message);
const prefixed = new Uint8Array(3 + data.length);
prefixed.set([1, 0, 1]);
prefixed.set(data, 3);
this.postMessage(kind, { data: prefixed });
this.logSensor(kind);
}
setSimulatorValue = async (
id: SensorStateKey,
value: number | string
): Promise<void> => {
if (!this.state) {
throw new Error("Simulator not ready");
}
// We don't get notified of our own changes, so update our state and notify.
this.state = {
...this.state,
[id]: {
// Would be good to make this safe.
...(this.state as any)[id],
value,
},
};
this.dispatchTypedEvent("state_change", new StateChangeEvent(this.state));
this.postMessage("set_value", {
id,
value,
});
this.logSensor(id);
};
stop = async (): Promise<void> => {
this.postMessage("stop", {});
};
reset = async (): Promise<void> => {
this.postMessage("reset", {});
this.notifyResetComms();
this.logging.event({
type: "sim-user-reset",
});
};
mute = async (): Promise<void> => {
this.postMessage("mute", {});
this.logging.event({
type: "sim-user-mute",
});
};
unmute = async (): Promise<void> => {
this.postMessage("unmute", {});
this.logging.event({
type: "sim-user-unmute",
});
};
private setStatus(newStatus: ConnectionStatus) {
this.status = newStatus;
this.dispatchTypedEvent("status", new ConnectionStatusEvent(newStatus));
}
clearDevice(): void {
this.setStatus(ConnectionStatus.NO_AUTHORIZED_DEVICE);
}
private postMessage(kind: string, data: any): void {
const iframe = this.iframe();
if (!iframe) {
throw new Error("Missing simulator iframe.");
}
iframe.contentWindow!.postMessage(
{
kind,
...data,
},
"*"
);
}
}