@litz-sim/litz 0.0.0-stage → 0.2.0
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/README.md +226 -2
- package/index.d.ts +292 -0
- package/index.js +16 -0
- package/litz_wasm.wasm +0 -0
- package/package.json +51 -4
- 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/README.md
CHANGED
|
@@ -1,3 +1,227 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @litz-sim/litz
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@litz-sim/litz` is the JavaScript binding for Litz, a deterministic electronics and firmware simulator. The package loads `litz_wasm.wasm`, opens a session on one board from a `diagram.json` and an application image, and exposes serial output, part state, pins, probes, decoders, displays and electrical conflicts as plain objects. It has no DOM code, no workers and no runtime dependencies, and it advances only when the host calls `run` or `advance`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @litz-sim/litz
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The package is an ES module for Node 18 or newer and for browsers. It ships `index.js`, `index.d.ts`, `src/` and the compiled `litz_wasm.wasm`, about 5.5 MB uncompressed.
|
|
12
|
+
|
|
13
|
+
## First session
|
|
14
|
+
|
|
15
|
+
`loadLitz` reads, compiles and instantiates the module and returns a `Litz`. `createSession` opens one board, selected by the board named in the diagram. `advance` moves simulated time, `serial.take` drains the console and `close` releases the session. The sample below reads the repository's `blinky` example. In a checkout, `npm run example` runs it from `js/examples/blinky.mjs`, where Node resolves the package name through the enclosing `js/package.json`. In another project, install the package and pass that project's diagram and image.
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { readFile } from "node:fs/promises";
|
|
19
|
+
import { loadLitz } from "@litz-sim/litz";
|
|
20
|
+
|
|
21
|
+
const litz = await loadLitz();
|
|
22
|
+
const session = litz.createSession({
|
|
23
|
+
diagram: await readFile("../examples/blinky/diagram.json", "utf8"),
|
|
24
|
+
app: new Uint8Array(await readFile("../examples/blinky/firmware/blinky.bin")),
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
session.advance(300);
|
|
28
|
+
process.stdout.write(session.serial.take());
|
|
29
|
+
console.log(session.chip().name, session.ms, session.stop);
|
|
30
|
+
session.close();
|
|
31
|
+
litz.close();
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`run(steps)` executes at most `steps` scheduling steps and returns the simulated clock in milliseconds. A step is a unit of the scheduler rather than a fixed span of time, so `advance(ms)` repeats `run` in chunks until the clock reaches the target. Both calls are synchronous and bounded.
|
|
35
|
+
|
|
36
|
+
## Session surface
|
|
37
|
+
|
|
38
|
+
| Member | Kind | Description |
|
|
39
|
+
|---|---|---|
|
|
40
|
+
| `run(steps?)` | method | Advance at most `steps` scheduling steps; returns simulated milliseconds. Default `DEFAULT_STEPS`. |
|
|
41
|
+
| `advance(ms, options?)` | method | Advance until the clock has moved `ms` milliseconds; returns the clock. Throws when `maxSteps` is exhausted. |
|
|
42
|
+
| `ms` | getter | Simulated milliseconds since reset. |
|
|
43
|
+
| `chip()` | method | The booted backend: `{ name, cpuHz, flash }`. |
|
|
44
|
+
| `stop` | getter | How the last `run` ended: `budget`, `idle`, `halted`, `trap`, `reset` or `breakpoint`. |
|
|
45
|
+
| `fault` | getter | The backend's trap text, or `null`. |
|
|
46
|
+
| `heap()` | method | The firmware's free heap in bytes, or `null` when it cannot be asked. |
|
|
47
|
+
| `serial.take()` | method | Drain the console since the last call; returns UTF-8 text. |
|
|
48
|
+
| `serial.write(data)` | method | Deliver a string or bytes to the board's UART0 receiver. |
|
|
49
|
+
| `trace.start()` | method | Begin recording net transitions. |
|
|
50
|
+
| `trace.transitions` | getter | Number of transitions recorded so far. |
|
|
51
|
+
| `trace.vcd()` | method | The recording as a VCD document. |
|
|
52
|
+
| `probe.add(name, point)` | method | Watch `<board>:<GPIO>` or `<part>:<pin>`; samples appear in `scope()`. |
|
|
53
|
+
| `decode.add(spec)` | method | Add a UART, I2C or SPI decoder over probes. |
|
|
54
|
+
| `scope()` | method | Every probe's samples and every decoder's frames. |
|
|
55
|
+
| `parts()` | method | Every part the diagram declares, with current state. |
|
|
56
|
+
| `part(id)` | method | One part by id, including board-expanded ids such as `esp/led_pwr`; `null` when absent. |
|
|
57
|
+
| `press(id, pressed?)` | method | Press or release a pushbutton; defaults to pressed. |
|
|
58
|
+
| `setControl(id, permille)` | method | Move a control through 0 to 1000 permille of its travel. |
|
|
59
|
+
| `setNamedControl(id, name, value)` | method | Set a named control such as a sensor's `temperature` or `lux`. |
|
|
60
|
+
| `partPin(id, pin?)` | method | The level on a part pin, or `null`; the first pin when `pin` is omitted. |
|
|
61
|
+
| `gpio(pin)` | method | The level the chip sees on one of its own pads, by GPIO number. |
|
|
62
|
+
| `display()` | method | The panel, or `null` when the circuit has none. |
|
|
63
|
+
| `touch(x, y, down?)` | method | Deliver a touch at panel pixels; `false` without a panel. |
|
|
64
|
+
| `conflicts()` | method | Electrical conflicts, oldest first. |
|
|
65
|
+
| `handle` | getter | The handle inside the module; `0` is never a session. |
|
|
66
|
+
| `close()` | method | Drop the session and release its module memory. |
|
|
67
|
+
|
|
68
|
+
`Display` carries `width`, `height`, a `version` that grows when pixels change, and `pixels()`, which returns RGBA8888 bytes sized `width * height * 4`.
|
|
69
|
+
|
|
70
|
+
## Session options
|
|
71
|
+
|
|
72
|
+
| Field | Type | Default | Description |
|
|
73
|
+
|---|---|---|---|
|
|
74
|
+
| `diagram` | `string` | required | The `diagram.json` text. Its board selects the chip. |
|
|
75
|
+
| `app` | `Uint8Array \| ArrayBuffer \| ArrayBufferView` | required | The application image. |
|
|
76
|
+
| `rom` | bytes or `null` | `null` | Mask ROM for firmware that needs one. |
|
|
77
|
+
| `boot` | bytes or `null` | `null` | Second-stage bootloader; the module accepts it only with `ptable`. |
|
|
78
|
+
| `ptable` | bytes or `null` | `null` | Partition table; the module accepts it only with `boot`. |
|
|
79
|
+
| `flashSize` | `number` or `null` | board manifest, then module default | Flash size in bytes; must be a positive whole number. |
|
|
80
|
+
| `mac` | `string` or `null` | module default | The station MAC, for example `24:0a:c4:12:34:56`. |
|
|
81
|
+
| `analog` | `boolean` | `false` | Solve the analog network instead of treating every net as digital. |
|
|
82
|
+
| `manifests` | `Array<string \| { toml, schematic }>` | `[]` | Catalog manifests as TOML text; a board with an internal schematic uses `{ toml, schematic }`. |
|
|
83
|
+
| `parts` | `Record<string, () => HostPart>` | `{}` | Wasm part factories keyed by the module name in the part manifest. |
|
|
84
|
+
| `boards` | `Record<string, (host) => HostChip>` | `{}` | Wasm chip factories keyed by the module name in the board manifest. |
|
|
85
|
+
|
|
86
|
+
## Chips and firmware images
|
|
87
|
+
|
|
88
|
+
The board named in `diagram.json` selects the backend. The shipped module boots ESP32-C3, ESP32-C6, ESP32-P4 and ESP32-S31 (RISC-V), the ATmega328P on Arduino Uno, Nano and Pro Mini boards, and the RP2040 on Raspberry Pi Pico boards. The classic ESP32 and ESP32-S3 run on Xtensa, whose simulator executes guest blocks through a host JIT that this module does not carry; `createSession` throws a `LitzError` that names the chip and the supported alternatives.
|
|
89
|
+
|
|
90
|
+
`app` is the application image. `rom` adds a mask ROM. `boot` and `ptable` add the second-stage bootloader and partition table and are supplied together. A merged ESP image is recognised and written at the bootloader offset; a bare application is written at the chip's application offset. `chip().flash` reports where the images landed.
|
|
91
|
+
|
|
92
|
+
## Custom parts and boards with jco
|
|
93
|
+
|
|
94
|
+
A catalog part or board can be a WebAssembly Component. Browsers cannot instantiate a component directly, so transpile it once with [jco](https://github.com/bytecodealliance/jco):
|
|
95
|
+
|
|
96
|
+
```sh
|
|
97
|
+
npx jco transpile 74hc595.wasm -o out --instantiation sync
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The generated JavaScript exports `instantiate(getCoreModule, imports)`. Pass the generated modules to `partFromJco` with `partImports`, or to `chipFromJco` with `chipImports`. The part sample below uses the shipped `74hc595` fixture; save it as `demo-part.mjs` in `js/` and run it from that directory.
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
import { readFile } from "node:fs/promises";
|
|
104
|
+
import { loadLitz, partFromJco, partImports } from "@litz-sim/litz";
|
|
105
|
+
import { instantiate } from "./test/fixtures/74hc595/74hc595.js";
|
|
106
|
+
|
|
107
|
+
const core = new WebAssembly.Module(await readFile("./test/fixtures/74hc595/74hc595.core.wasm"));
|
|
108
|
+
const diagram = JSON.stringify({
|
|
109
|
+
version: 1,
|
|
110
|
+
parts: [
|
|
111
|
+
{ id: "esp", type: "board-esp32-c3-devkitm-1", attrs: {} },
|
|
112
|
+
{ id: "sh", type: "litz-74hc595", attrs: {} },
|
|
113
|
+
{ id: "r1", type: "litz-resistor", attrs: { value: "220" } },
|
|
114
|
+
{ id: "led1", type: "litz-led", attrs: { color: "green" } },
|
|
115
|
+
],
|
|
116
|
+
connections: [
|
|
117
|
+
["esp:GPIO8", "sh:SHCP", "", []],
|
|
118
|
+
["esp:GPIO8", "sh:STCP", "", []],
|
|
119
|
+
["esp:3V3", "sh:DS", "", []],
|
|
120
|
+
["esp:3V3", "sh:MR", "", []],
|
|
121
|
+
["esp:GND.1", "sh:OE", "", []],
|
|
122
|
+
["sh:Q0", "r1:1", "", []],
|
|
123
|
+
["r1:2", "led1:A", "", []],
|
|
124
|
+
["led1:C", "esp:GND.1", "", []],
|
|
125
|
+
],
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
const litz = await loadLitz();
|
|
129
|
+
const session = litz.createSession({
|
|
130
|
+
diagram,
|
|
131
|
+
app: new Uint8Array(await readFile("../examples/blinky/firmware/blinky.bin")),
|
|
132
|
+
parts: {
|
|
133
|
+
"74hc595.wasm": () => partFromJco(instantiate(() => core, partImports())),
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
session.advance(500);
|
|
138
|
+
console.log(session.part("led1"));
|
|
139
|
+
session.close();
|
|
140
|
+
litz.close();
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The factory is called once per part instance while the board is built, and the session keeps the instance until it is closed. `parts` and `boards` are keyed by the module name in the part or board manifest. A chip factory receives the guest's host object:
|
|
144
|
+
|
|
145
|
+
```js
|
|
146
|
+
import { readFileSync } from "node:fs";
|
|
147
|
+
import { chipFromJco, chipImports } from "@litz-sim/litz";
|
|
148
|
+
import { instantiate } from "./test/fixtures/board-v2/board-v2.js";
|
|
149
|
+
|
|
150
|
+
const cores = new Map();
|
|
151
|
+
const getCoreModule = (name) => {
|
|
152
|
+
if (!cores.has(name)) {
|
|
153
|
+
cores.set(name, new WebAssembly.Module(readFileSync(`./test/fixtures/board-v2/${name}`)));
|
|
154
|
+
}
|
|
155
|
+
return cores.get(name);
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const boards = {
|
|
159
|
+
"board-v2.wasm": (host) => chipFromJco(instantiate(getCoreModule, chipImports(host))),
|
|
160
|
+
};
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Pass `boards` with the board manifest in `manifests`; [the JavaScript reference](../docs/javascript.md#a-custom-litzmcu020-chip) has a complete bootable example.
|
|
164
|
+
|
|
165
|
+
## The `litz:mcu` bridge
|
|
166
|
+
|
|
167
|
+
Both `litz:mcu@0.1.0` and `litz:mcu@0.2.0` chips are bridged in full. The 0.1 contract covers images, pins, console and fault. The 0.2 contract adds analog reads, I2C, SPI and UART transactions, Wi-Fi scan, join and resolve with TCP and UDP, BLE scanning, advertising and GATT, and the raw radio. Every 0.2 call reaches the circuit through the module's `litz_guest_call` export, answered by the same host state the native runner uses. `chipImports(host)` turns each contract function into a `host.call(op, args)` request where `op` is the contract's camelCase name and `args` is a plain JSON object; a call the circuit refuses throws `LitzError`.
|
|
168
|
+
|
|
169
|
+
## Errors
|
|
170
|
+
|
|
171
|
+
Every failing loader or session call throws `LitzError`. The message is the reason the module gave, so a bad diagram reports the parse error and a bad pin reports the pin. `LitzError` extends `Error`, sets `name` to `"LitzError"` and accepts an `options` object with a `cause`.
|
|
172
|
+
|
|
173
|
+
```js
|
|
174
|
+
import { loadLitz, LitzError } from "@litz-sim/litz";
|
|
175
|
+
|
|
176
|
+
const litz = await loadLitz();
|
|
177
|
+
try {
|
|
178
|
+
litz.createSession({ diagram: "{}", app: new Uint8Array([1, 2, 3, 4]) });
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (error instanceof LitzError) console.error(error.message);
|
|
181
|
+
} finally {
|
|
182
|
+
litz.close();
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`partFromJco` and `chipFromJco` throw `TypeError` when the transpiled module does not export the expected interface. A factory that returns the wrong shape, or that throws, is reported as a `LitzError` naming the module during `createSession`.
|
|
187
|
+
|
|
188
|
+
## Loading the module
|
|
189
|
+
|
|
190
|
+
`loadLitz` accepts bytes, a URL, a `Response` or an already compiled `WebAssembly.Module`. Without `wasm` it reads the file shipped beside the package, exported as `wasmUrl`. A relative string is resolved against the loader's own module URL, so pass an absolute URL or bytes when the working directory differs.
|
|
191
|
+
|
|
192
|
+
```js
|
|
193
|
+
import { readFile } from "node:fs/promises";
|
|
194
|
+
import { loadLitz, wasmUrl } from "@litz-sim/litz";
|
|
195
|
+
|
|
196
|
+
const bytes = new Uint8Array(await readFile(new URL(wasmUrl)));
|
|
197
|
+
const fromBytes = await loadLitz({ wasm: bytes });
|
|
198
|
+
const fromModule = await loadLitz({ wasm: new WebAssembly.Module(bytes) });
|
|
199
|
+
const fromUrl = await loadLitz({ wasm: wasmUrl });
|
|
200
|
+
|
|
201
|
+
fromBytes.close();
|
|
202
|
+
fromModule.close();
|
|
203
|
+
fromUrl.close();
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`imports` is merged into the module's import object. The `litz_host` namespace holds this package's part and chip bridge and is merged with the built-in runtime; other namespaces are passed through. The shipped module imports only `litz_host`.
|
|
207
|
+
|
|
208
|
+
## Browser and Node
|
|
209
|
+
|
|
210
|
+
In Node, the default source is a `file:` URL and the loader reads it with `node:fs/promises`. In a browser, the default source is fetched from the package URL; pass a `Response` or an absolute URL when the asset lives elsewhere. Bundlers that do not copy arbitrary assets can read the wasm themselves and pass `wasm` as bytes or a compiled module. The package uses standard web APIs and, on Node, `node:fs/promises` for `file:` sources; it contains no DOM access.
|
|
211
|
+
|
|
212
|
+
## Building and testing
|
|
213
|
+
|
|
214
|
+
`npm run build` compiles `crates/litz-wasm` for `wasm32-unknown-unknown`, copies `litz_wasm.wasm` next to `index.js`, and checks that the module imports only `litz_host` and exports every name the wrapper requires. The Rust target must be installed in the toolchain. `npm test` runs `node --test` over `test/*.test.js` against the shipped module and the repository's example firmware.
|
|
215
|
+
|
|
216
|
+
```sh
|
|
217
|
+
npm run build
|
|
218
|
+
npm test
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Reference
|
|
222
|
+
|
|
223
|
+
The full API reference, including every type, lifecycle rule, host import name and a complete custom `litz:mcu@0.2.0` chip, is in [docs/javascript.md](../docs/javascript.md).
|
|
224
|
+
|
|
225
|
+
## License
|
|
226
|
+
|
|
227
|
+
MIT OR Apache-2.0.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/** Loaded Litz module, ready to open sessions. */
|
|
2
|
+
export declare class Litz {
|
|
3
|
+
private constructor();
|
|
4
|
+
/** The raw wasm export object. */
|
|
5
|
+
readonly exports: WebAssembly.Exports;
|
|
6
|
+
/** The instance this runtime was built from. */
|
|
7
|
+
readonly instance: WebAssembly.Instance;
|
|
8
|
+
/** Open a session on one board. */
|
|
9
|
+
createSession(options: SessionOptions): Session;
|
|
10
|
+
/** Release module memory. Sessions must be closed first. */
|
|
11
|
+
close(): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SessionOptions {
|
|
15
|
+
/** The diagram.json text. The board it names selects the chip. */
|
|
16
|
+
diagram: string;
|
|
17
|
+
/** The application image. */
|
|
18
|
+
app: Uint8Array | ArrayBuffer | ArrayBufferView;
|
|
19
|
+
/** Mask ROM, when the firmware needs one. */
|
|
20
|
+
rom?: Uint8Array | ArrayBuffer | ArrayBufferView | null;
|
|
21
|
+
/** Second-stage bootloader; requires `ptable`. */
|
|
22
|
+
boot?: Uint8Array | ArrayBuffer | ArrayBufferView | null;
|
|
23
|
+
/** Partition table; requires `boot`. */
|
|
24
|
+
ptable?: Uint8Array | ArrayBuffer | ArrayBufferView | null;
|
|
25
|
+
/** Flash size in bytes; the board manifest's, then 4 MiB. */
|
|
26
|
+
flashSize?: number | null;
|
|
27
|
+
/** The MAC the station reports, e.g. `24:0a:c4:12:34:56`. */
|
|
28
|
+
mac?: string | null;
|
|
29
|
+
/** Solve the analog network instead of treating every net as digital. */
|
|
30
|
+
analog?: boolean;
|
|
31
|
+
/** Catalog manifests as TOML text: custom parts and boards. */
|
|
32
|
+
manifests?: string[];
|
|
33
|
+
/** Wasm part modules: `{ "x.wasm": () => instance }`. */
|
|
34
|
+
parts?: Record<string, PartFactory>;
|
|
35
|
+
/** Wasm chip modules: `{ "x.wasm": (host) => instance }`. */
|
|
36
|
+
boards?: Record<string, ChipFactory>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** One instantiated `litz:part` component, as the simulator drives it. */
|
|
40
|
+
export interface HostPart {
|
|
41
|
+
setPin(pin: number, level: Level, atNs: number): void;
|
|
42
|
+
advance(toNs: number): void;
|
|
43
|
+
nextEvent(): number | null | undefined;
|
|
44
|
+
drive(pin: number): { level: Level; strength?: "strong" | "weak" } | Level | null;
|
|
45
|
+
state(): { kind: string; value?: number } | null;
|
|
46
|
+
press?(pressed: boolean): boolean;
|
|
47
|
+
setControl?(permille: number): boolean;
|
|
48
|
+
analog?(pin: number): number | null;
|
|
49
|
+
i2cConnect?(address: number, read: boolean): void;
|
|
50
|
+
i2cRead?(): number;
|
|
51
|
+
i2cWrite?(byte: number): boolean;
|
|
52
|
+
i2cStop?(): void;
|
|
53
|
+
spiSelect?(selected: boolean): void;
|
|
54
|
+
spiTransfer?(tx: Uint8Array, rxLen: number): Uint8Array;
|
|
55
|
+
uartReceive?(bytes: Uint8Array, atNs: number): void;
|
|
56
|
+
uartPoll?(): Uint8Array;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One instantiated `litz:mcu` component. */
|
|
60
|
+
export interface HostChip {
|
|
61
|
+
info(): {
|
|
62
|
+
name: string;
|
|
63
|
+
description?: string;
|
|
64
|
+
cpuHz: number;
|
|
65
|
+
flash: { size: number; bootloader: number; partitionTable: number; app: number };
|
|
66
|
+
};
|
|
67
|
+
loadImage(kind: "rom" | "bootloader" | "partition-table" | "firmware", offset: number, bytes: Uint8Array): void;
|
|
68
|
+
boot(): number;
|
|
69
|
+
setInputs(inputs: Array<{ pin: number; level: Level }>): void;
|
|
70
|
+
run(budget: number): { cycles: number; stop: StopWord };
|
|
71
|
+
takeOutputs(): Array<{ pin: number; level: Level; enabled: boolean }>;
|
|
72
|
+
writeConsole(bytes: Uint8Array): void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The guest's host imports. */
|
|
76
|
+
export interface ChipHost {
|
|
77
|
+
console(bytes: string | Uint8Array): void;
|
|
78
|
+
fault(detail: string): void;
|
|
79
|
+
/**
|
|
80
|
+
* Answer one `litz:mcu@0.2.0` host call against the circuit. `op` is the
|
|
81
|
+
* contract's camelCase name and `args` its JSON argument object; the result
|
|
82
|
+
* is the call's plain JSON value. A call the circuit refuses throws
|
|
83
|
+
* `LitzError`.
|
|
84
|
+
*/
|
|
85
|
+
call(op: string, args: Record<string, unknown>): unknown;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type PartFactory = () => HostPart;
|
|
89
|
+
export type ChipFactory = (host: ChipHost) => HostChip;
|
|
90
|
+
|
|
91
|
+
export interface ChipFlash {
|
|
92
|
+
readonly size: number;
|
|
93
|
+
readonly bootloader: number;
|
|
94
|
+
readonly partitionTable: number;
|
|
95
|
+
readonly app: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface ChipInfo {
|
|
99
|
+
/** `esp32c3`, `esp32s3`, `atmega328p`, `rp2040`, ... */
|
|
100
|
+
readonly name: string;
|
|
101
|
+
readonly cpuHz: number;
|
|
102
|
+
readonly flash: ChipFlash;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** How the last `run` ended. */
|
|
106
|
+
export type StopWord = "budget" | "idle" | "halted" | "trap" | "reset" | "breakpoint";
|
|
107
|
+
|
|
108
|
+
/** A pin level as the board sees it. */
|
|
109
|
+
export type Level = "low" | "high" | "high-z";
|
|
110
|
+
|
|
111
|
+
export interface LoadOptions {
|
|
112
|
+
/** Bytes, a URL, a `Response`, or an already compiled module. */
|
|
113
|
+
wasm?: Uint8Array | ArrayBuffer | ArrayBufferView | string | URL | Response | WebAssembly.Module | null;
|
|
114
|
+
/** Extra imports, merged alongside this package's `litz_host` bridge. */
|
|
115
|
+
imports?: WebAssembly.Imports;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Where the shipped wasm file sits. */
|
|
119
|
+
export declare const wasmUrl: string;
|
|
120
|
+
|
|
121
|
+
/** Scheduling steps per call when the host does not choose. */
|
|
122
|
+
export declare const DEFAULT_STEPS: number;
|
|
123
|
+
|
|
124
|
+
/** Load the module. Without `wasm`, the file next to the module is used. */
|
|
125
|
+
export declare function loadLitz(options?: LoadOptions): Promise<Litz>;
|
|
126
|
+
|
|
127
|
+
export declare class LitzError extends Error {}
|
|
128
|
+
|
|
129
|
+
/** Wrap a jco-transpiled `litz:part` root object. */
|
|
130
|
+
export declare function partFromJco(root: unknown): HostPart;
|
|
131
|
+
/** Wrap a jco-transpiled `litz:mcu` root object. */
|
|
132
|
+
export declare function chipFromJco(root: unknown): HostChip;
|
|
133
|
+
/** The imports a transpiled `litz:part@0.2.0` module expects. */
|
|
134
|
+
export declare function partImports(options?: {
|
|
135
|
+
log?: (message: string) => void;
|
|
136
|
+
rom?: () => Uint8Array;
|
|
137
|
+
}): Record<string, unknown>;
|
|
138
|
+
/** The imports a transpiled `litz:mcu` (0.1 or 0.2) module expects. */
|
|
139
|
+
export declare function chipImports(host: ChipHost): Record<string, unknown>;
|
|
140
|
+
|
|
141
|
+
export type PartStateName =
|
|
142
|
+
| "none"
|
|
143
|
+
| "off"
|
|
144
|
+
| "on"
|
|
145
|
+
| "up"
|
|
146
|
+
| "down"
|
|
147
|
+
| "silent"
|
|
148
|
+
| "sounding"
|
|
149
|
+
| "position"
|
|
150
|
+
| "mask"
|
|
151
|
+
| "state"
|
|
152
|
+
| "unknown";
|
|
153
|
+
|
|
154
|
+
export interface PartState {
|
|
155
|
+
/** The id the diagram gave the part. */
|
|
156
|
+
id: string;
|
|
157
|
+
/** The ABI's state code: 0 none, 1 off, 2 on, 3 up, 4 down. */
|
|
158
|
+
code: number;
|
|
159
|
+
/** What the part is: `led`, `button`, `switch`, `servo`, `radio`, ... */
|
|
160
|
+
kind: string;
|
|
161
|
+
/** `code` as a word; `null` for a part that reports nothing (a board). */
|
|
162
|
+
state: PartStateName | null;
|
|
163
|
+
/** The number behind the state: servo degrees, a segment mask, a tone rate. */
|
|
164
|
+
value: number;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export interface Display {
|
|
168
|
+
readonly width: number;
|
|
169
|
+
readonly height: number;
|
|
170
|
+
/** Grows when the pixels change, so a host can skip an unchanged frame. */
|
|
171
|
+
readonly version: number;
|
|
172
|
+
/** The frame as RGBA8888, `width * height * 4` bytes. */
|
|
173
|
+
pixels(): Uint8Array;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface Serial {
|
|
177
|
+
/** Drain what the firmware printed since the last call. */
|
|
178
|
+
take(): string;
|
|
179
|
+
/** Deliver bytes to the board's UART0 receiver. */
|
|
180
|
+
write(data: string | Uint8Array | ArrayBuffer | ArrayBufferView): void;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export interface Trace {
|
|
184
|
+
/** Begin recording net transitions. */
|
|
185
|
+
start(): void;
|
|
186
|
+
/** Recorded transitions so far. */
|
|
187
|
+
readonly transitions: number;
|
|
188
|
+
/** The recording as a VCD document. */
|
|
189
|
+
vcd(): string;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface Probes {
|
|
193
|
+
/**
|
|
194
|
+
* Watch a point: `<board>:<GPIO>` (`esp:GPIO8`) or `<part>:<pin>`
|
|
195
|
+
* (`led1:A`). Samples appear in `session.scope()`.
|
|
196
|
+
*/
|
|
197
|
+
add(name: string, point: string): void;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export interface Decoders {
|
|
201
|
+
/** `uart:rx=<probe>[,baud=N]`, `i2c:sda=<probe>,scl=<probe>`,
|
|
202
|
+
* `spi:sck=<probe>,mosi=<probe>,cs=<probe>[,miso=<probe>][,mode=N]`. */
|
|
203
|
+
add(spec: string): void;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface ProbeRecord {
|
|
207
|
+
name: string;
|
|
208
|
+
point: string;
|
|
209
|
+
/** Net the probe resolves to on the flattened board. */
|
|
210
|
+
net: number;
|
|
211
|
+
/** Level transitions as `[tick_ns, level]`, level 0 low, 1 high, 2 high-Z. */
|
|
212
|
+
digital: Array<[number, number]>;
|
|
213
|
+
/** Voltage samples as `[tick_ns, volts]`. */
|
|
214
|
+
volts: Array<[number, number]>;
|
|
215
|
+
edges: number;
|
|
216
|
+
high_ns: number;
|
|
217
|
+
low_ns: number;
|
|
218
|
+
frequency_hz: number | null;
|
|
219
|
+
duty: number | null;
|
|
220
|
+
min_volts: number | null;
|
|
221
|
+
max_volts: number | null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface DecodeRecord {
|
|
225
|
+
spec: string;
|
|
226
|
+
kind: string;
|
|
227
|
+
name: string;
|
|
228
|
+
frames: Array<{ at: number; end: number; text: string; error: boolean | string }>;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export interface ScopeDocument {
|
|
232
|
+
/** Simulated ms at the time of the call. */
|
|
233
|
+
ms: number;
|
|
234
|
+
probes: ProbeRecord[];
|
|
235
|
+
decodes: DecodeRecord[];
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export interface AdvanceOptions {
|
|
239
|
+
/** Steps per inner `run` call. */
|
|
240
|
+
chunkSteps?: number;
|
|
241
|
+
/** Give up after this many steps. */
|
|
242
|
+
maxSteps?: number;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** One running board. */
|
|
246
|
+
export declare class Session {
|
|
247
|
+
private constructor();
|
|
248
|
+
/** The handle inside the module. */
|
|
249
|
+
readonly handle: number;
|
|
250
|
+
/** Advance by at most `steps` scheduling steps; returns the simulated ms. */
|
|
251
|
+
run(steps?: number): number;
|
|
252
|
+
/** Advance until `ms` of simulated time have passed. */
|
|
253
|
+
advance(ms: number, options?: AdvanceOptions): number;
|
|
254
|
+
/** Simulated milliseconds since reset. */
|
|
255
|
+
readonly ms: number;
|
|
256
|
+
/** The backend the diagram booted, its clock and its flash layout. */
|
|
257
|
+
chip(): ChipInfo;
|
|
258
|
+
/** How the last `run` ended. */
|
|
259
|
+
readonly stop: StopWord;
|
|
260
|
+
/** The backend's explanation for a trap, or `null`. */
|
|
261
|
+
readonly fault: string | null;
|
|
262
|
+
/** The firmware's own free heap in bytes, or `null` when it cannot be asked. */
|
|
263
|
+
heap(): number | null;
|
|
264
|
+
readonly serial: Serial;
|
|
265
|
+
readonly trace: Trace;
|
|
266
|
+
readonly probe: Probes;
|
|
267
|
+
readonly decode: Decoders;
|
|
268
|
+
/** Electrical conflicts, oldest first. */
|
|
269
|
+
conflicts(): string[];
|
|
270
|
+
/** Every part the diagram declares. */
|
|
271
|
+
parts(): PartState[];
|
|
272
|
+
/** One part by id, including board-expanded ids such as `esp/led_pwr`. */
|
|
273
|
+
part(id: string): PartState | null;
|
|
274
|
+
/** Press or release a pushbutton wired to a GPIO. */
|
|
275
|
+
press(id: string, pressed?: boolean): void;
|
|
276
|
+
/** Move a control: 0 to 1000 permille of its travel. */
|
|
277
|
+
setControl(id: string, permille: number): void;
|
|
278
|
+
/** Set a named control such as a sensor's `temperature` or `lux`. */
|
|
279
|
+
setNamedControl(id: string, name: string, value: string | number): void;
|
|
280
|
+
/** The level on one of a part's pins, or `null` when it does not exist. */
|
|
281
|
+
partPin(id: string, pin?: string): Level | null;
|
|
282
|
+
/** The level the chip sees on its own pad, by GPIO number. */
|
|
283
|
+
gpio(pin: number): Level | null;
|
|
284
|
+
/** The panel, or `null` when the circuit has no display. */
|
|
285
|
+
display(): Display | null;
|
|
286
|
+
/** Deliver a touch at panel pixels. False without a panel. */
|
|
287
|
+
touch(x: number, y: number, down?: boolean): boolean;
|
|
288
|
+
/** Probes' samples and decoders' frames. */
|
|
289
|
+
scope(): ScopeDocument;
|
|
290
|
+
/** Drop the session. */
|
|
291
|
+
close(): void;
|
|
292
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Litz as a headless WebAssembly library.
|
|
2
|
+
//
|
|
3
|
+
// The module next to this file is built from `crates/litz-wasm`, which exposes
|
|
4
|
+
// a C ABI over linear memory: pointers are byte offsets, strings are UTF-8 and
|
|
5
|
+
// every call is synchronous. The wrapper turns that into objects — a session,
|
|
6
|
+
// its serial line, its parts, its display — and lives under `src/`; this file
|
|
7
|
+
// is the public entry point.
|
|
8
|
+
//
|
|
9
|
+
// A session owns one board, its flash and its peripherals. `session.run(steps)`
|
|
10
|
+
// advances it and returns the simulated clock; the host decides how much time
|
|
11
|
+
// to simulate per call.
|
|
12
|
+
|
|
13
|
+
export { DEFAULT_STEPS } from "./src/constants.js";
|
|
14
|
+
export { LitzError } from "./src/errors.js";
|
|
15
|
+
export { Litz, loadLitz, Session, wasmUrl } from "./src/litz.js";
|
|
16
|
+
export { chipFromJco, chipImports, partFromJco, partImports } from "./src/jco.js";
|
package/litz_wasm.wasm
ADDED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@litz-sim/litz",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Deterministic electronics and firmware simulator in WebAssembly",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"simulator",
|
|
7
|
+
"emulator",
|
|
8
|
+
"esp32",
|
|
9
|
+
"firmware",
|
|
10
|
+
"electronics",
|
|
11
|
+
"wasm"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT OR Apache-2.0",
|
|
14
|
+
"author": "redelectricity",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/Litz-Sim/litz.git",
|
|
18
|
+
"directory": "js"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/Litz-Sim/litz#readme",
|
|
21
|
+
"bugs": "https://github.com/Litz-Sim/litz/issues",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "./index.js",
|
|
24
|
+
"types": "./index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./index.d.ts",
|
|
28
|
+
"default": "./index.js"
|
|
29
|
+
},
|
|
30
|
+
"./litz_wasm.wasm": "./litz_wasm.wasm",
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"index.js",
|
|
35
|
+
"index.d.ts",
|
|
36
|
+
"src/",
|
|
37
|
+
"litz_wasm.wasm",
|
|
38
|
+
"README.md"
|
|
39
|
+
],
|
|
40
|
+
"sideEffects": false,
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=18"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "node scripts/build.mjs",
|
|
46
|
+
"test": "node --test test/*.test.js",
|
|
47
|
+
"example": "node examples/blinky.mjs",
|
|
48
|
+
"prepublishOnly": "node scripts/build.mjs && node --test test/*.test.js"
|
|
49
|
+
},
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/bytes.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Buffers and the byte boundary: host values in, typed arrays out.
|
|
2
|
+
|
|
3
|
+
import { DECODER } from "./constants.js";
|
|
4
|
+
import { LitzError } from "./errors.js";
|
|
5
|
+
|
|
6
|
+
export function hold(io, bytes) {
|
|
7
|
+
if (bytes.length === 0) return { ptr: 0, len: 0 };
|
|
8
|
+
const ptr = io.exports.litz_alloc(bytes.length);
|
|
9
|
+
if (ptr === 0) throw new LitzError(`could not allocate ${bytes.length} bytes in the module`);
|
|
10
|
+
io.view(ptr, bytes.length).set(bytes);
|
|
11
|
+
return { ptr, len: bytes.length };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function bytesOf(value, label) {
|
|
15
|
+
if (value instanceof Uint8Array) return value;
|
|
16
|
+
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
|
17
|
+
if (ArrayBuffer.isView(value)) {
|
|
18
|
+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
19
|
+
}
|
|
20
|
+
throw new LitzError(`\`${label}\` must be a Uint8Array`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function optionalBytes(value, label) {
|
|
24
|
+
if (value === null || value === undefined) return new Uint8Array(0);
|
|
25
|
+
return bytesOf(value, label);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function decodeChunks(chunks) {
|
|
29
|
+
if (chunks.length === 0) return "";
|
|
30
|
+
if (chunks.length === 1) return DECODER.decode(chunks[0]);
|
|
31
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
32
|
+
const joined = new Uint8Array(total);
|
|
33
|
+
let at = 0;
|
|
34
|
+
for (const chunk of chunks) {
|
|
35
|
+
joined.set(chunk, at);
|
|
36
|
+
at += chunk.length;
|
|
37
|
+
}
|
|
38
|
+
return DECODER.decode(joined);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function toBytes(source) {
|
|
42
|
+
if (source instanceof ArrayBuffer) return new Uint8Array(source.slice(0));
|
|
43
|
+
if (ArrayBuffer.isView(source)) {
|
|
44
|
+
return new Uint8Array(
|
|
45
|
+
source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength),
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
if (typeof Response !== "undefined" && source instanceof Response) {
|
|
49
|
+
if (!source.ok) throw new LitzError(`fetching the wasm module failed: ${source.status}`);
|
|
50
|
+
return new Uint8Array(await source.arrayBuffer());
|
|
51
|
+
}
|
|
52
|
+
const url = source instanceof URL ? source : new URL(String(source), import.meta.url);
|
|
53
|
+
if (url.protocol === "file:") {
|
|
54
|
+
const { readFile } = await import("node:fs/promises");
|
|
55
|
+
try {
|
|
56
|
+
return new Uint8Array(await readFile(url));
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw new LitzError(
|
|
59
|
+
`could not read the wasm module at ${url.href}; run \`npm run build\` in the package, or pass \`wasm\` explicitly`,
|
|
60
|
+
{ cause: error },
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (typeof fetch !== "function") {
|
|
65
|
+
throw new LitzError("this host has no fetch; pass `wasm` as bytes or a URL");
|
|
66
|
+
}
|
|
67
|
+
const response = await fetch(url);
|
|
68
|
+
if (!response.ok) {
|
|
69
|
+
throw new LitzError(`fetching ${url.href} failed: ${response.status}`);
|
|
70
|
+
}
|
|
71
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
72
|
+
}
|
|
73
|
+
|