-
Notifications
You must be signed in to change notification settings - Fork 0
/
pxtextension.ts
281 lines (254 loc) · 7.35 KB
/
pxtextension.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
//% fixedInstances
//% blockNamespace=ml
class MlEvent {
eventValue: number;
eventLabel: string;
lastDuration: number;
onStartHandler: () => void;
onStopHandler: () => void;
onStopDetailedHandler: (duration: number) => void;
constructor(value: number, label: string) {
this.eventValue = value;
this.eventLabel = label;
this.lastDuration = 0;
}
}
//% color=#2b64c3 weight=120 icon="\uf108" block="Machine Learning" advanced=false
namespace ml {
//% blockNamespace=ml
export namespace event {
//% fixedInstance block="unknown"
export const Unknown = new MlEvent(1, "unknown");
}
export let events = [event.Unknown];
let prevEvent: MlEvent | undefined;
let currentEvent: MlEvent = event.Unknown;
let lastEventTimestamp: number = 0;
export function maybeUpdateEventStats(currentEvent: MlEvent) {
const now = input.runningTime();
if (!prevEvent) {
lastEventTimestamp = now;
prevEvent = currentEvent;
return;
}
if (currentEvent !== prevEvent) {
prevEvent.lastDuration = now - lastEventTimestamp;
if (prevEvent.onStopDetailedHandler) {
prevEvent.onStopDetailedHandler(prevEvent.lastDuration);
}
if (prevEvent.onStopHandler) {
prevEvent.onStopHandler();
}
lastEventTimestamp = now;
prevEvent = currentEvent;
}
}
/**
* Do something when an ML event is detected.
* @param event one of the actions the machine learning model was trained on
* @param body code to execute
*/
//% blockId=ml_on_event_start
//% block="on ML $event start"
//% weight=50
//% parts="v2"
//% group="micro:bit (V2)"
//% help=github:machine-learning/docs/ml_on_event_start
export function onStart(event: MlEvent, body: () => void): void {
event.onStartHandler = body;
const wrappedBody = () => {
if (prevEvent !== event) {
maybeUpdateEventStats(event);
body();
}
};
if (!isRunning()) {
startRunning();
}
// The sim probably won't respect the DropIfBusy flag.
control.onEvent(
MlRunnerIds.MlRunnerInference,
event.eventValue,
wrappedBody,
EventFlags.DropIfBusy
);
}
/**
* Do something when an ML event is no longer detected.
* @param event one of the actions the machine learning model was trained on
* @param body code to execute
*/
//% blockId=ml_on_event_stop
//% block="on ML $event stop"
//% weight=40
//% parts="v2"
//% group="micro:bit (V2)"
//% help=github:machine-learning/docs/ml_on_event_stop
export function onStop(event: MlEvent, body: () => void): void {
if (!isRunning()) {
startRunning();
}
event.onStopHandler = body;
}
/**
* Do something when an ML event is no longer detected.
* @param event one of the actions the machine learning model was trained on
* @param body code to execute
*/
//% blockId=ml_on_event_stop_detailed
//% block="on ML $event stop $duration (ms)"
//% weight=30
//% draggableParameters="reporter"
//% parts="v2"
//% group="micro:bit (V2)"
//% help=github:machine-learning/docs/ml_on_event_stop_detailed
export function onStopDetailed(
event: MlEvent,
body: (duration: number) => void
): void {
if (!isRunning()) {
startRunning();
}
event.onStopDetailedHandler = body;
}
/**
* Tests if an ML event is currently detected.
* @param event one of the actions the machine learning model was trained on
*/
//% blockId=ml_is_event_detected
//% block="is ML $event detected"
//% weight=20
//% parts="v2"
//% group="micro:bit (V2)"
//% help=github:machine-learning/docs/ml_is_event_detected
export function isDetected(event: MlEvent): boolean {
if (!isRunning()) {
startRunning();
return false;
}
return event.eventValue == currentEventId();
}
/**
* Get the certainty of an ML event in percent (0 to 100).
* @param event one of the actions the machine learning model was trained on
*/
//% blockId=ml_on_event_certainty
//% block="certainty (\\%) ML $event"
//% weight=10
//% parts="v2"
//% help=github:machine-learning/docs/ml_get_event_certainty
export function getCertainty(event: MlEvent): number {
const eventValue = event.eventValue;
if (eventValue <= 1) {
// `unknown` can't have a certainty.
return 0;
}
return getCertaintyInternal(event.eventValue);
}
//% shim=mlrunner::currentEventCertainty
function getCertaintyInternal(eventValue: number): number {
if (eventValue === currentEvent.eventValue) {
return 100;
}
return 0;
}
export let getModelBlob: () => Buffer;
let simIsRunning = false;
/**
* TS shim for C++ function init(), which initialize the ML model with
* an address to a model blob.
*
* @param modelBlob The model blob to initialize the ML model with.
*/
//% shim=mlrunner::init
function initRunner(modelBlob: Buffer): void {
return;
}
/**
* Configure the ML model, start capturing accelerometer data, and run
* the model in the background.
*/
function startRunning(): void {
let modelBlob = hex``;
// The model blob should be re-generated by the MakeCode extension
if (typeof getModelBlob === "function") {
modelBlob = getModelBlob() || hex``;
}
initRunner(modelBlob);
simIsRunning = true;
}
/**
* Check if the ML model is currently running in the background.
*/
//% shim=mlrunner::isModelRunning
function isRunning(): boolean {
return simIsRunning;
}
//% shim=mlrunner::currentEventId
function currentEventId(): number {
return currentEvent.eventValue;
}
// Start simulator code.
type SimulatorMessageType =
| "register"
| "data"
| "request_data"
| "simulate_event";
interface SimulatorMessage {
type: SimulatorMessageType;
data?: any;
}
const simChannel = "microbit-foundation/pxt-microbit-ml";
//% shim=TD_NOOP
function simulatorRegister(): void {
const msg: SimulatorMessage = {
type: "register",
};
control.simmessages.onReceived(simChannel, handleMessage);
simulatorSendMessage(msg);
}
export function simulatorSendData(): void {
if (!events) {
return;
}
const eventLabels = events.map((event) => ({
name: event.eventLabel,
value: event.eventValue,
}));
const msg: SimulatorMessage = {
type: "data",
data: eventLabels,
};
simulatorSendMessage(msg);
}
//% shim=TD_NOOP
function simulatorSendMessage(msg: SimulatorMessage): void {
const payload = Buffer.fromUTF8(JSON.stringify(msg));
control.simmessages.send(simChannel, payload, false);
}
function simulateEvent(eventValue: number) {
const simulatedEvent = events.find(
(event) => event.eventValue === eventValue
);
currentEvent = simulatedEvent;
// This will run the MLEvent onEvent block if it exists in the user's code.
// Otherwise, control.onEvent in autogenerated.ts is fired.
control.raiseEvent(MlRunnerIds.MlRunnerInference, eventValue);
}
function handleMessage(buffer: Buffer) {
const msg: SimulatorMessage = JSON.parse(buffer.toString());
switch (msg.type) {
case "request_data": {
simulatorSendData();
break;
}
case "simulate_event": {
if (typeof msg.data === "number") {
simulateEvent(msg.data);
}
}
}
}
simulatorRegister();
// End simulator code.
}