Files
linuxcncWebWASM/web/worker/test_plc_runtime.mjs

36 lines
2.5 KiB
JavaScript

import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import createModule from "../../build-wasm/linuxcnc-sim-core.js";
import { PlcRuntime, parseClassicLadder } from "./plc-runtime.mjs";
import { SimSession, CONTEXT_ID } from "./sim-session.mjs";
const plc = new PlcRuntime();
const clp = parseClassicLadder("_FILES_CLASSICLADDER\n_FILE-rung_0.csv\n#VER=2.0\n1-0-50/0 , 9-0-0/0 , 50-0-60/1\n_/FILE-rung_0.csv\n");
assert.equal(clp.status, "verified");
assert.equal(clp.rungs[0].cells, 3);
assert.equal(parseClassicLadder("_FILES_CLASSICLADDER\n_FILE-rung_0.csv\ninvalid\n_/FILE-rung_0.csv\n").code, "clp_cell_invalid");
assert.equal(plc.configure({ rungs: [{ op: "SET", target: "input", value: 1 }, { op: "ADD", target: "count", source: "input" }, { op: "TIMER", target: "done", source: "input", preset: 2 }], sample_capacity: 2, backpressure: "drop_oldest" }).status, "verified");
assert.equal(plc.scan(1).state.registers.count, 1);
assert.equal(plc.scan(2).state.registers.count, 2);
assert.equal(plc.trigger().status, "verified");
assert.equal(plc.state.sampler.samples.length, 2);
assert.equal(plc.configure({ rungs: [], sample_capacity: 1, backpressure: "block" }).status, "verified");
plc.scan(3);
assert.equal(plc.trigger().code, "plc_backpressure");
const saved = plc.export();
const restored = new PlcRuntime();
assert.deepEqual(restored.restore(saved), saved);
const core = await createModule({ wasmBinary: await readFile(new URL("../../build-wasm/linuxcnc-sim-core.wasm", import.meta.url)) });
const session = new SimSession(core, { sessionId: "plc-state" });
const base = { schema_version: 1, context_id: CONTEXT_ID, session_id: "plc-state" };
const send = (kind, seq, operation_id, payload = {}) => session.accept({ ...base, kind, seq, operation_id, payload });
send("HELLO", 1); send("SESSION_ATTACH", 2, "attach"); send("LOAD_WORKSPACE", 3, "workspace", { root_path: "/workspace" });
assert.equal(send("PLC_CONFIG", 4, "plc-config", { rungs: [{ op: "SET", target: "ready", value: 1 }], sample_capacity: 4, backpressure: "drop_newest" }).payload.plc.state_hash.startsWith("fnv1a64:"), true);
const stepped = send("SIM_STEP", 5, "plc-step", { cycles: 1 });
assert.equal(stepped.payload.plc.registers.ready, 1);
const malformed = send("PLC_CONFIG", 6, "plc-bad", { rungs: [{ op: "UNKNOWN", target: "bad" }] });
assert.equal(malformed.kind, "ERROR");
assert.equal(malformed.payload.code, "plc_rung_unsupported");
console.log(`plc_runtime=passed count=${plc.state.registers.count} dropped=${plc.state.sampler.dropped} worker_tick=${stepped.payload.plc.tick}`);