@litz-sim/litz 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +176 -0
- package/README.md +168 -100
- package/index.d.ts +114 -2
- package/index.js +7 -652
- package/litz_wasm.wasm +0 -0
- package/package.json +4 -2
- package/src/bytes.js +73 -0
- package/src/constants.js +98 -0
- package/src/errors.js +9 -0
- package/src/host.js +423 -0
- package/src/jco.js +257 -0
- package/src/litz.js +261 -0
- package/src/session.js +432 -0
package/src/jco.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Adapters from `@bytecodealliance/jco` output to the host interfaces this
|
|
2
|
+
// package drives.
|
|
3
|
+
//
|
|
4
|
+
// A component from the Litz catalog is a Component Model binary. Browsers
|
|
5
|
+
// cannot instantiate one, so it is transpiled once with
|
|
6
|
+
// `jco transpile --instantiation sync`, which emits a core module plus a JS
|
|
7
|
+
// module exporting `instantiate(getCoreModule, imports)`. That function
|
|
8
|
+
// returns the guest's interfaces; these adapters translate between their
|
|
9
|
+
// shapes and the plain objects `createSession` expects.
|
|
10
|
+
//
|
|
11
|
+
// Nothing here depends on jco at run time: the transpiled output is the input.
|
|
12
|
+
|
|
13
|
+
/** Build the `imports` object a transpiled `litz:part` component expects. */
|
|
14
|
+
export function partImports({ log = () => {}, rom = () => new Uint8Array(0) } = {}) {
|
|
15
|
+
// jco reads the import object by package name without the version, which
|
|
16
|
+
// is the key the generated glue actually indexes.
|
|
17
|
+
return {
|
|
18
|
+
"litz:part/host": { log, rom },
|
|
19
|
+
"litz:part/types": {},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Build the `imports` object a transpiled `litz:mcu@0.1.0` or `0.2.0`
|
|
25
|
+
* component expects.
|
|
26
|
+
*
|
|
27
|
+
* Every 0.2 call goes to the circuit through `host.call`, the bridge's one
|
|
28
|
+
* JSON door into the module; there is no host-side logic here beyond turning
|
|
29
|
+
* the contract's records into plain objects. A WIT `result<_, string>` error
|
|
30
|
+
* has to be thrown with a `payload` property, which is how jco tells a
|
|
31
|
+
* declared error from a trap.
|
|
32
|
+
*/
|
|
33
|
+
export function chipImports(host) {
|
|
34
|
+
const call = (op, args) => host.call(op, args);
|
|
35
|
+
const result = (op, args) => {
|
|
36
|
+
try {
|
|
37
|
+
return call(op, args);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
const failed = new Error(error?.message ?? String(error));
|
|
40
|
+
failed.payload = failed.message;
|
|
41
|
+
throw failed;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const list = (bytes) => Array.from(bytes ?? []);
|
|
45
|
+
const bytes = (value) => Uint8Array.from(value ?? []);
|
|
46
|
+
const optional = (value) => (value === null || value === undefined ? undefined : value);
|
|
47
|
+
const services = (value) =>
|
|
48
|
+
(value ?? []).map((service) => ({
|
|
49
|
+
uuid: service.uuid,
|
|
50
|
+
characteristics: (service.characteristics ?? []).map((characteristic) => ({
|
|
51
|
+
uuid: characteristic.uuid,
|
|
52
|
+
access: characteristic.access,
|
|
53
|
+
value: bytes(characteristic.value),
|
|
54
|
+
})),
|
|
55
|
+
}));
|
|
56
|
+
const notifications = (value) =>
|
|
57
|
+
(value ?? []).map((notification) => ({
|
|
58
|
+
service: notification.service,
|
|
59
|
+
characteristic: notification.characteristic,
|
|
60
|
+
value: bytes(notification.value),
|
|
61
|
+
}));
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
"litz:mcu/host": {
|
|
65
|
+
console: (data) => host.console(data),
|
|
66
|
+
fault: (detail) => host.fault(detail),
|
|
67
|
+
analogRead: (pin) => optional(call("analogRead", { pin })),
|
|
68
|
+
i2cTransfer: (controller, address, write, readLen) =>
|
|
69
|
+
bytes(result("i2cTransfer", { controller, address, write: list(write), readLen })),
|
|
70
|
+
spiTransfer: (controller, chipSelect, tx, readLen) =>
|
|
71
|
+
bytes(result("spiTransfer", { controller, chipSelect, tx: list(tx), readLen })),
|
|
72
|
+
uartWrite: (port, data) => call("uartWrite", { port, bytes: list(data) }),
|
|
73
|
+
uartRead: (port) => bytes(call("uartRead", { port })),
|
|
74
|
+
wifiScan: () => call("wifiScan", {}),
|
|
75
|
+
wifiJoin: (ssid, psk) => {
|
|
76
|
+
const lease = result("wifiJoin", { ssid, psk: optional(psk) ?? null });
|
|
77
|
+
return {
|
|
78
|
+
ip: bytes(lease.ip),
|
|
79
|
+
gateway: bytes(lease.gateway),
|
|
80
|
+
dns: bytes(lease.dns),
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
wifiLeave: () => call("wifiLeave", {}),
|
|
84
|
+
wifiResolve: (name) => bytes(result("wifiResolve", { name })),
|
|
85
|
+
tcpConnect: (address, port) => result("tcpConnect", { host: list(address), port }),
|
|
86
|
+
tcpWrite: (id, data) => result("tcpWrite", { id, bytes: list(data) }),
|
|
87
|
+
tcpRead: (id, max) => bytes(result("tcpRead", { id, max })),
|
|
88
|
+
tcpClose: (id) => call("tcpClose", { id }),
|
|
89
|
+
udpOpen: (port) => result("udpOpen", { port }),
|
|
90
|
+
udpSend: (id, address, port, data) =>
|
|
91
|
+
result("udpSend", { id, host: list(address), port, bytes: list(data) }),
|
|
92
|
+
udpRead: (id, max) => bytes(result("udpRead", { id, max })),
|
|
93
|
+
udpClose: (id) => call("udpClose", { id }),
|
|
94
|
+
bleScan: () =>
|
|
95
|
+
call("bleScan", {}).map((beacon) => ({
|
|
96
|
+
address: bytes(beacon.address),
|
|
97
|
+
name: optional(beacon.name),
|
|
98
|
+
rssi: beacon.rssi,
|
|
99
|
+
data: bytes(beacon.data),
|
|
100
|
+
scanResponse: bytes(beacon.scanResponse),
|
|
101
|
+
})),
|
|
102
|
+
bleAdvertise: (address, data, scanResponse) =>
|
|
103
|
+
bytes(
|
|
104
|
+
result("bleAdvertise", {
|
|
105
|
+
address: list(address),
|
|
106
|
+
data: list(data),
|
|
107
|
+
scanResponse: list(scanResponse),
|
|
108
|
+
}),
|
|
109
|
+
),
|
|
110
|
+
bleStopAdvertising: (address) => call("bleStopAdvertising", { address: list(address) }),
|
|
111
|
+
bleSetGatt: (table) =>
|
|
112
|
+
result("bleSetGatt", {
|
|
113
|
+
services: (table ?? []).map((service) => ({
|
|
114
|
+
uuid: service.uuid,
|
|
115
|
+
characteristics: (service.characteristics ?? []).map((characteristic) => ({
|
|
116
|
+
uuid: characteristic.uuid,
|
|
117
|
+
access: characteristic.access,
|
|
118
|
+
value: list(characteristic.value),
|
|
119
|
+
})),
|
|
120
|
+
})),
|
|
121
|
+
}),
|
|
122
|
+
bleConnect: (address) => result("bleConnect", { address: list(address) }),
|
|
123
|
+
bleDisconnect: (handle) => call("bleDisconnect", { handle }),
|
|
124
|
+
bleDiscover: (handle) => services(result("bleDiscover", { handle })),
|
|
125
|
+
bleRead: (handle, service, characteristic) =>
|
|
126
|
+
bytes(result("bleRead", { handle, service, characteristic })),
|
|
127
|
+
bleWrite: (handle, service, characteristic, value) =>
|
|
128
|
+
result("bleWrite", { handle, service, characteristic, value: list(value) }),
|
|
129
|
+
bleSubscribe: (handle, service, characteristic, enabled) =>
|
|
130
|
+
result("bleSubscribe", { handle, service, characteristic, enabled }),
|
|
131
|
+
bleNotifications: (handle) => notifications(call("bleNotifications", { handle })),
|
|
132
|
+
bleTakeWrites: () =>
|
|
133
|
+
call("bleTakeWrites", {}).map((write) => ({
|
|
134
|
+
service: write.service,
|
|
135
|
+
characteristic: write.characteristic,
|
|
136
|
+
value: bytes(write.value),
|
|
137
|
+
})),
|
|
138
|
+
bleNotify: (service, characteristic, value) =>
|
|
139
|
+
result("bleNotify", { service, characteristic, value: list(value) }),
|
|
140
|
+
radioConfigure: (network, channel, address) =>
|
|
141
|
+
result("radioConfigure", { network, channel, address: list(address) }),
|
|
142
|
+
radioSend: (data, to, airtimeNs) =>
|
|
143
|
+
result("radioSend", {
|
|
144
|
+
bytes: list(data),
|
|
145
|
+
to: to === undefined ? null : list(to),
|
|
146
|
+
airtimeNs: Number(airtimeNs),
|
|
147
|
+
}),
|
|
148
|
+
radioReceive: () =>
|
|
149
|
+
call("radioReceive", {}).map((frame) => ({
|
|
150
|
+
sender: bytes(frame.sender),
|
|
151
|
+
to: optional(frame.to) === undefined ? undefined : bytes(frame.to),
|
|
152
|
+
bytes: bytes(frame.bytes),
|
|
153
|
+
sentAt: BigInt(frame.sentAt),
|
|
154
|
+
airtime: BigInt(frame.airtime),
|
|
155
|
+
})),
|
|
156
|
+
},
|
|
157
|
+
"litz:mcu/types": {},
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Wrap the root object a transpiled part's `instantiate` returned.
|
|
163
|
+
*
|
|
164
|
+
* `root` is the whole return value, not just its `part` key, because the
|
|
165
|
+
* interface is also exported under its versioned name.
|
|
166
|
+
*/
|
|
167
|
+
export function partFromJco(root) {
|
|
168
|
+
const part = root.part ?? root["litz:part/part@0.2.0"] ?? root["litz:part/part@0.1.0"];
|
|
169
|
+
if (!part) throw new TypeError("the transpiled module exports no litz:part interface");
|
|
170
|
+
const at = (ns) => BigInt(Math.round(ns));
|
|
171
|
+
return {
|
|
172
|
+
info: () => part.info(),
|
|
173
|
+
setPin: (pin, level, atNs) => part.setPin(pin, level, at(atNs)),
|
|
174
|
+
advance: (toNs) => part.advance(at(toNs)),
|
|
175
|
+
nextEvent: () => {
|
|
176
|
+
const event = part.nextEvent();
|
|
177
|
+
return event === undefined || event === null ? null : Number(event);
|
|
178
|
+
},
|
|
179
|
+
drive: (pin) => part.drive(pin),
|
|
180
|
+
state: () => partState(part.state()),
|
|
181
|
+
press: (pressed) => part.press(pressed),
|
|
182
|
+
setControl: (permille) => part.setControl(permille),
|
|
183
|
+
analog: (pin) => {
|
|
184
|
+
const volts = part.analog?.(pin);
|
|
185
|
+
return volts === undefined ? null : volts;
|
|
186
|
+
},
|
|
187
|
+
i2cConnect: (address, read) => part.i2cConnect?.(address, read),
|
|
188
|
+
i2cRead: () => part.i2cRead?.() ?? 0xff,
|
|
189
|
+
i2cWrite: (byte) => part.i2cWrite?.(byte) ?? false,
|
|
190
|
+
i2cStop: () => part.i2cStop?.(),
|
|
191
|
+
spiSelect: (selected) => part.spiSelect?.(selected),
|
|
192
|
+
spiTransfer: (tx, rxLen) => part.spiTransfer?.(tx, rxLen) ?? new Uint8Array(rxLen),
|
|
193
|
+
uartReceive: (bytes, atNs) => part.uartReceive?.(bytes, at(atNs)),
|
|
194
|
+
uartPoll: () => part.uartPoll?.() ?? new Uint8Array(0),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Wrap the root object a transpiled chip's `instantiate` returned.
|
|
200
|
+
*
|
|
201
|
+
* The guest's `host` import is answered by the adapter given in `imports`;
|
|
202
|
+
* this function only translates the chip interface.
|
|
203
|
+
*/
|
|
204
|
+
export function chipFromJco(root) {
|
|
205
|
+
const chip = root.chip ?? root["litz:mcu/chip@0.2.0"] ?? root["litz:mcu/chip@0.1.0"];
|
|
206
|
+
if (!chip) throw new TypeError("the transpiled module exports no litz:mcu interface");
|
|
207
|
+
return {
|
|
208
|
+
info: () => {
|
|
209
|
+
const info = chip.info();
|
|
210
|
+
return {
|
|
211
|
+
name: info.name,
|
|
212
|
+
description: info.description,
|
|
213
|
+
cpuHz: Number(info.cpuHz),
|
|
214
|
+
flash: {
|
|
215
|
+
size: Number(info.flash.size),
|
|
216
|
+
bootloader: Number(info.flash.bootloader),
|
|
217
|
+
partitionTable: Number(info.flash.partitionTable),
|
|
218
|
+
app: Number(info.flash.app),
|
|
219
|
+
},
|
|
220
|
+
};
|
|
221
|
+
},
|
|
222
|
+
loadImage: (kind, offset, bytes) => chip.loadImage(kind, BigInt(Math.round(offset)), bytes),
|
|
223
|
+
boot: () => chip.boot(),
|
|
224
|
+
setInputs: (inputs) => chip.setInputs(inputs),
|
|
225
|
+
run: (budget) => {
|
|
226
|
+
const result = chip.run(BigInt(Math.round(budget)));
|
|
227
|
+
return { cycles: Number(result.cycles), stop: result.stop };
|
|
228
|
+
},
|
|
229
|
+
takeOutputs: () => chip.takeOutputs(),
|
|
230
|
+
writeConsole: (bytes) => chip.writeConsole(bytes),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** `litz:part/types@0.2.0`'s tagged `part-state` as the bridge's kind/value. */
|
|
235
|
+
function partState(state) {
|
|
236
|
+
switch (state?.tag) {
|
|
237
|
+
case "led":
|
|
238
|
+
return { kind: state.val ? "led-on" : "led-off" };
|
|
239
|
+
case "button":
|
|
240
|
+
return { kind: state.val ? "button-down" : "button-up" };
|
|
241
|
+
case "switch":
|
|
242
|
+
return { kind: state.val ? "switch-on" : "switch-off" };
|
|
243
|
+
case "tone":
|
|
244
|
+
return {
|
|
245
|
+
kind: state.val.sounding ? "tone-sounding" : "tone-silent",
|
|
246
|
+
value: state.val.hz,
|
|
247
|
+
};
|
|
248
|
+
case "segments":
|
|
249
|
+
return { kind: "segments", value: state.val };
|
|
250
|
+
case "servo":
|
|
251
|
+
return { kind: "servo", value: state.val };
|
|
252
|
+
case "knob":
|
|
253
|
+
return { kind: "knob", value: state.val };
|
|
254
|
+
default:
|
|
255
|
+
return { kind: "none" };
|
|
256
|
+
}
|
|
257
|
+
}
|
package/src/litz.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// Loading the module and opening sessions.
|
|
2
|
+
|
|
3
|
+
import { DECODER, ENCODER, REQUIRED_EXPORTS } from "./constants.js";
|
|
4
|
+
import { bytesOf, optionalBytes, hold, toBytes } from "./bytes.js";
|
|
5
|
+
import { LitzError } from "./errors.js";
|
|
6
|
+
import { HostRuntime } from "./host.js";
|
|
7
|
+
import { Session } from "./session.js";
|
|
8
|
+
|
|
9
|
+
/** Where the wasm file sits when the package is loaded as a module. */
|
|
10
|
+
export const wasmUrl = new URL("../litz_wasm.wasm", import.meta.url).href;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Load the module and return a runtime that can open sessions.
|
|
14
|
+
*
|
|
15
|
+
* `wasm` takes bytes, a URL, a `Response`, an `ArrayBuffer` or an already
|
|
16
|
+
* instantiated `WebAssembly.Module`; without it the file shipped next to this
|
|
17
|
+
* module is used. `imports` is merged into the module's import object: the
|
|
18
|
+
* `litz_host` namespace is this package's custom-part bridge, and anything the
|
|
19
|
+
* caller supplies is added alongside it.
|
|
20
|
+
*/
|
|
21
|
+
export async function loadLitz({ wasm = null, imports = {} } = {}) {
|
|
22
|
+
const host = new HostRuntime();
|
|
23
|
+
const merged = {
|
|
24
|
+
...imports,
|
|
25
|
+
litz_host: { ...(imports.litz_host ?? {}), ...host.imports },
|
|
26
|
+
};
|
|
27
|
+
const instance = await instantiate(wasm ?? wasmUrl, merged);
|
|
28
|
+
host.attach(instance.exports.memory, instance.exports);
|
|
29
|
+
return new Litz(instance, host);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function instantiate(source, imports) {
|
|
33
|
+
if (source instanceof WebAssembly.Module) {
|
|
34
|
+
const missing = missingExports(source);
|
|
35
|
+
if (missing.length > 0) throw new LitzError(`the wasm module is missing ${missing.join(", ")}`);
|
|
36
|
+
const instance = await WebAssembly.instantiate(source, imports);
|
|
37
|
+
return instance instanceof WebAssembly.Instance ? instance : instance.instance;
|
|
38
|
+
}
|
|
39
|
+
const bytes = await toBytes(source);
|
|
40
|
+
let module;
|
|
41
|
+
try {
|
|
42
|
+
module = await WebAssembly.compile(bytes);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new LitzError("the wasm module could not be compiled", { cause: error });
|
|
45
|
+
}
|
|
46
|
+
const missing = missingExports(module);
|
|
47
|
+
if (missing.length > 0) {
|
|
48
|
+
throw new LitzError(`the wasm module is missing ${missing.join(", ")}`);
|
|
49
|
+
}
|
|
50
|
+
const result = await WebAssembly.instantiate(module, imports);
|
|
51
|
+
return result instanceof WebAssembly.Instance ? result : result.instance;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function missingExports(module) {
|
|
55
|
+
const present = new Set(WebAssembly.Module.exports(module).map((entry) => entry.name));
|
|
56
|
+
return REQUIRED_EXPORTS.filter((name) => !present.has(name));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class Litz {
|
|
60
|
+
#instance;
|
|
61
|
+
#exports;
|
|
62
|
+
#closed = false;
|
|
63
|
+
#scratchIn = 0;
|
|
64
|
+
#scratchInSize = 0;
|
|
65
|
+
#scratchOut = 0;
|
|
66
|
+
#scratchOutSize = 0;
|
|
67
|
+
#io;
|
|
68
|
+
#host;
|
|
69
|
+
|
|
70
|
+
constructor(instance, host) {
|
|
71
|
+
this.#instance = instance;
|
|
72
|
+
this.#exports = instance.exports;
|
|
73
|
+
this.#host = host;
|
|
74
|
+
const litz = this;
|
|
75
|
+
// The memory boundary, handed to sessions so they never reach into this
|
|
76
|
+
// object's state. Buffers are reused between calls and grow on demand.
|
|
77
|
+
this.#io = {
|
|
78
|
+
get exports() {
|
|
79
|
+
return litz.#exports;
|
|
80
|
+
},
|
|
81
|
+
view(ptr, len) {
|
|
82
|
+
return new Uint8Array(litz.#exports.memory.buffer, ptr, len);
|
|
83
|
+
},
|
|
84
|
+
writeIn(bytes) {
|
|
85
|
+
if (bytes.length > litz.#scratchInSize) {
|
|
86
|
+
litz.#release({ ptr: litz.#scratchIn, len: litz.#scratchInSize });
|
|
87
|
+
litz.#scratchInSize = Math.max(bytes.length, 4096);
|
|
88
|
+
litz.#scratchIn = litz.#exports.litz_alloc(litz.#scratchInSize);
|
|
89
|
+
if (litz.#scratchIn === 0) {
|
|
90
|
+
litz.#scratchInSize = 0;
|
|
91
|
+
throw new LitzError(`could not allocate ${bytes.length} bytes in the module`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
litz.#view(litz.#scratchIn, bytes.length).set(bytes);
|
|
95
|
+
return { ptr: litz.#scratchIn, len: bytes.length };
|
|
96
|
+
},
|
|
97
|
+
writeOut(len) {
|
|
98
|
+
if (len > litz.#scratchOutSize) {
|
|
99
|
+
litz.#release({ ptr: litz.#scratchOut, len: litz.#scratchOutSize });
|
|
100
|
+
litz.#scratchOutSize = Math.max(len, 4096);
|
|
101
|
+
litz.#scratchOut = litz.#exports.litz_alloc(litz.#scratchOutSize);
|
|
102
|
+
if (litz.#scratchOut === 0) {
|
|
103
|
+
litz.#scratchOutSize = 0;
|
|
104
|
+
throw new LitzError(`could not allocate ${len} bytes in the module`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return { ptr: litz.#scratchOut, len };
|
|
108
|
+
},
|
|
109
|
+
copyOut(len) {
|
|
110
|
+
return new Uint8Array(litz.#view(litz.#scratchOut, len));
|
|
111
|
+
},
|
|
112
|
+
release(buffer) {
|
|
113
|
+
litz.#release(buffer);
|
|
114
|
+
},
|
|
115
|
+
error(fallback) {
|
|
116
|
+
const cap = litz.#io.writeOut(1024);
|
|
117
|
+
const written = litz.#exports.litz_last_error(cap.ptr, cap.len);
|
|
118
|
+
const text = written ? DECODER.decode(litz.#view(cap.ptr, written)) : "";
|
|
119
|
+
return new LitzError(text || fallback);
|
|
120
|
+
},
|
|
121
|
+
stored() {
|
|
122
|
+
const cap = litz.#io.writeOut(1024);
|
|
123
|
+
const written = litz.#exports.litz_last_error(cap.ptr, cap.len);
|
|
124
|
+
return written ? DECODER.decode(litz.#view(cap.ptr, written)) : "";
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** The raw export object, for a host that needs an export this API omits. */
|
|
130
|
+
get exports() {
|
|
131
|
+
return this.#exports;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The instance this runtime was built from. */
|
|
135
|
+
get instance() {
|
|
136
|
+
return this.#instance;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Open a session.
|
|
141
|
+
*
|
|
142
|
+
* `diagram` is the diagram.json text and `app` the application image. The
|
|
143
|
+
* chip is chosen by the board the diagram names: any builtin board boots —
|
|
144
|
+
* the ESP32 family, the ATmega328P and the RP2040.
|
|
145
|
+
*
|
|
146
|
+
* `rom`, `boot` and `ptable` are optional; giving `boot` without `ptable`
|
|
147
|
+
* (or the reverse) is an error, because the bootloader cannot find the
|
|
148
|
+
* application without the table. `flashSize`, `mac` and `analog` override
|
|
149
|
+
* the board manifest and the module defaults.
|
|
150
|
+
*
|
|
151
|
+
* `manifests` adds catalog manifests as TOML text (custom parts and boards),
|
|
152
|
+
* and `parts` maps a wasm module name to a factory that returns one
|
|
153
|
+
* instance of the component's `part` interface. The factory is called once
|
|
154
|
+
* per part instance while the board is built; the session keeps the
|
|
155
|
+
* instance afterwards.
|
|
156
|
+
*/
|
|
157
|
+
createSession({
|
|
158
|
+
diagram,
|
|
159
|
+
app,
|
|
160
|
+
rom = null,
|
|
161
|
+
boot = null,
|
|
162
|
+
ptable = null,
|
|
163
|
+
flashSize = null,
|
|
164
|
+
mac = null,
|
|
165
|
+
analog = false,
|
|
166
|
+
manifests = [],
|
|
167
|
+
parts = {},
|
|
168
|
+
boards = {},
|
|
169
|
+
} = {}) {
|
|
170
|
+
this.#assertOpen();
|
|
171
|
+
if (typeof diagram !== "string" || diagram.length === 0) {
|
|
172
|
+
throw new LitzError("createSession needs the diagram.json text as `diagram`");
|
|
173
|
+
}
|
|
174
|
+
const appBytes = bytesOf(app, "app");
|
|
175
|
+
if (appBytes.length === 0) {
|
|
176
|
+
throw new LitzError("createSession needs the application image as `app`");
|
|
177
|
+
}
|
|
178
|
+
if (flashSize !== null && !(Number.isInteger(flashSize) && flashSize > 0)) {
|
|
179
|
+
throw new LitzError("`flashSize` must be a positive whole number of bytes");
|
|
180
|
+
}
|
|
181
|
+
if (mac !== null && typeof mac !== "string") {
|
|
182
|
+
throw new LitzError("`mac` must be a string such as 24:0a:c4:12:34:56");
|
|
183
|
+
}
|
|
184
|
+
if (
|
|
185
|
+
!Array.isArray(manifests) ||
|
|
186
|
+
manifests.some(
|
|
187
|
+
(entry) =>
|
|
188
|
+
typeof entry !== "string" &&
|
|
189
|
+
(typeof entry !== "object" || entry === null || typeof entry.toml !== "string"),
|
|
190
|
+
)
|
|
191
|
+
) {
|
|
192
|
+
throw new LitzError("`manifests` must be an array of TOML texts or {toml, schematic}");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const io = this.#io;
|
|
196
|
+
const romBytes = optionalBytes(rom, "rom");
|
|
197
|
+
const bootBytes = optionalBytes(boot, "boot");
|
|
198
|
+
const ptableBytes = optionalBytes(ptable, "ptable");
|
|
199
|
+
const buffers = [
|
|
200
|
+
hold(io, appBytes),
|
|
201
|
+
hold(io, romBytes),
|
|
202
|
+
hold(io, bootBytes),
|
|
203
|
+
hold(io, ptableBytes),
|
|
204
|
+
];
|
|
205
|
+
const [appBuf, romBuf, bootBuf, ptableBuf] = buffers;
|
|
206
|
+
const spec = {
|
|
207
|
+
diagram,
|
|
208
|
+
app: { ptr: appBuf.ptr, len: appBuf.len },
|
|
209
|
+
rom: romBuf.len > 0 ? { ptr: romBuf.ptr, len: romBuf.len } : null,
|
|
210
|
+
boot: bootBuf.len > 0 ? { ptr: bootBuf.ptr, len: bootBuf.len } : null,
|
|
211
|
+
ptable: ptableBuf.len > 0 ? { ptr: ptableBuf.ptr, len: ptableBuf.len } : null,
|
|
212
|
+
};
|
|
213
|
+
if (flashSize !== null) spec.flashSize = flashSize;
|
|
214
|
+
if (mac !== null) spec.mac = mac;
|
|
215
|
+
if (analog) spec.analog = true;
|
|
216
|
+
if (manifests.length > 0) spec.manifests = manifests;
|
|
217
|
+
const jsonBuf = hold(io, ENCODER.encode(JSON.stringify(spec)));
|
|
218
|
+
const previous = this.#host.register({ parts, boards });
|
|
219
|
+
let handle;
|
|
220
|
+
try {
|
|
221
|
+
handle = io.exports.litz_new_json(jsonBuf.ptr, jsonBuf.len);
|
|
222
|
+
} finally {
|
|
223
|
+
this.#host.restore(previous);
|
|
224
|
+
io.release(jsonBuf);
|
|
225
|
+
for (const buffer of buffers) io.release(buffer);
|
|
226
|
+
}
|
|
227
|
+
if (handle === 0) throw io.error("the session could not be created");
|
|
228
|
+
return new Session(io, handle);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Release the module memory this runtime holds. Sessions must be closed first. */
|
|
232
|
+
close() {
|
|
233
|
+
if (this.#closed) return;
|
|
234
|
+
this.#closed = true;
|
|
235
|
+
this.#host.release();
|
|
236
|
+
this.#release({ ptr: this.#scratchIn, len: this.#scratchInSize });
|
|
237
|
+
this.#release({ ptr: this.#scratchOut, len: this.#scratchOutSize });
|
|
238
|
+
this.#scratchIn = 0;
|
|
239
|
+
this.#scratchOut = 0;
|
|
240
|
+
this.#scratchInSize = 0;
|
|
241
|
+
this.#scratchOutSize = 0;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
#assertOpen() {
|
|
245
|
+
if (this.#closed) throw new LitzError("this runtime has been closed");
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
#view(ptr, len) {
|
|
249
|
+
return new Uint8Array(this.#exports.memory.buffer, ptr, len);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
#release(buffer) {
|
|
253
|
+
// The two reusable buffers belong to the runtime; a caller "releasing" one
|
|
254
|
+
// of them is a no-op, not a free that the next call would then reuse.
|
|
255
|
+
if (buffer.ptr === 0) return;
|
|
256
|
+
if (buffer.ptr === this.#scratchIn || buffer.ptr === this.#scratchOut) return;
|
|
257
|
+
this.#exports.litz_free(buffer.ptr, buffer.len);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export { Session };
|