cppmodel
v0.15.0
Published
Write CppModel simulations in Node.js
Maintainers
Readme
CppModel for Node.js
Write CppModel simulations in JavaScript or TypeScript. Every run fetches the inputs and parameters posted for it in your CppModel workspace and submits its execution there, just like a C or C++ simulation built with the CppModel SDK.
npm install cppmodelWorks on Linux (x64 and arm64, glibc 2.28+), Windows (x64 and ARM64) and macOS 11+ (Apple silicon and Intel) with Node.js 18 or later. The package contains the CppModel library for each of these platforms, so nothing needs compiling or installing.
A simulation
import { Simulation } from 'cppmodel';
class Heater extends Simulation {
init() {
this.temperature = 20.0;
}
step(timeMs) {
const setpoint = this.inputs.get('Setpoint', 22.0); // input, with its fallback
const gain = this.parameters.get('HeaterGain', 0.05); // parameter, with its fallback
const heaterOn = this.temperature < setpoint; // the controller under test
this.temperature += heaterOn ? gain : -0.01;
this.outputs
.set('Temperature', this.temperature)
.set('HeaterOn', heaterOn)
.set('CppModel.Step', timeMs)
.set('CppModel.StepResult', this.temperature < setpoint + 1.0);
}
}
const simulation = new Heater('Example - Heater (Node)', 60_000, 100);
process.exitCode = simulation.run();
simulation.close();run() fetches the pending inputs and parameters, calls init(), then step(timeMs) for every step
from 0 to totalTimeMs, then finalize(), and submits the execution. It returns 0 when every step
passed, otherwise the CppModel.Step of the first step whose CppModel.StepResult was 0.
An exception thrown in init(), step() or finalize() aborts the run, submits nothing and is
rethrown by run().
Instead of extending Simulation, you can pass the functions as options; they get the simulation as
their first argument:
const sim = new Simulation('Ramp', 1000, 100, {
step: (sim, timeMs) => sim.outputs.set('Ramp', timeMs),
});
sim.run();require('cppmodel') works too, and TypeScript types are included.
Inputs, outputs and parameters
| | |
|---|---|
| sim.inputs.get(name, fallback = 0) | The input's value at the current step, or fallback (recorded as its value) |
| sim.inputs.load([{label, x, y}, ...]) | Loads input series locally (x in ms) |
| sim.outputs.set(name, value) | Sets an output; it holds until set again and is recorded every step. Values are numbers; booleans become 1/0 |
| sim.outputs.get(name) | The output's current value |
| sim.parameters.get(name, fallback) | The parameter, storing fallback when it isn't set; a fetched value replaces the fallback |
| sim.parameters.set(name, value) | Sets a parameter that fetched values never replace |
| sim.parameters.toObject() | Every parameter |
| sim.results() | The execution as submitted: {inputs, results, parameters, ...} |
Inputs and outputs are numbers. Parameters keep their JSON type. All three have has(name),
keys() and size.
Steps and input profiles
A simulation is a use case. Inside it, an InputProfile runs steps one after the other: a function
for its duration ([fn, durationMs]), a nested input profile run whole, or an inputs step that reads
an input document (the --inputs format, a file path or the JSON text) during the step. A step
function gets the time since its step started and returns whether the cycle passed.
const { InputProfile, Simulation } = require('cppmodel');
class MotorStarter extends Simulation {
constructor() {
const start = new InputProfile([[(t) => pressStart(t), 100], [(t) => releaseStart(t), 200]]);
const test = new InputProfile([
[(t) => reset(t), 200],
start, // nested, run whole
[(t) => pressStop(t), 100],
InputProfile.inputs('inputs/guard-flicker.json', (t) => motorStops(t)),
[null, 500], // only waits
]);
super('Motor starter', test.duration(10), 10);
this.test = test;
}
step(timeMs) {
this.outputs.set('CppModel.StepResult', this.runInputProfile(this.test, timeMs));
}
}runInputProfile records the running step's number as CppModel.Step, so a failed run's result is
the first failing step's number. A nested profile is copied when added. Inputs passed with --inputs
or posted win over a step's document. See documentation/Steps.md in the SDK.
Verification rules and requirements
Rules check how a run behaves over time. Each one is an object you create once, e.g. in the constructor. The CppModel library tracks it:
- Failing steps: a step at which a rule is violated, or has certainly failed and still is, gets
CppModel.StepResult0, so the run fails. - Per-rule output: each rule records the output
CppModel.Verify.<name>: 1 until it first fails, then 0. - Outcome: when the run ends, each rule's outcome is printed and stored under the rule's name
in the execution's
verificationfield (sim.results().verification).
const { Simulation, verify } = require('cppmodel');
class Zone extends Simulation {
constructor() {
super('Zone', 3_600_000, 1000);
this.valveRange = new verify.Always(this, 'valve range');
this.smoke = new verify.Response(this, 'smoke stops fan', 2, 60);
this.stepResponse = new verify.Settle(this, 'setpoint step', 0.5, 1800, 600);
this.modes = new verify.Mode(this, 'modes').allow(OFF, STARTUP).allow(STARTUP, RUN).dwell(STARTUP, null, 30);
new verify.Rate(this, 'temperature rate', 'Zone.T', 0.01); // reads the output by itself
this.verifyRequirement('ZONE-SAF-001'); // this run verifies the requirement
}
step(timeMs) {
// ...
this.valveRange.update(verify.between(valve, 0, 100));
this.smoke.update(smoke, !fan && valve === 0);
this.stepResponse.update(temperature, setpoint);
this.modes.update(mode);
if (smoke) this.verifyRequirement('ZONE-SAF-004'); // verified at these steps
}
}Step rules are updated in step():
Always(sim, name, debounceS);Response(sim, name, deadlineS, holdS);Settle(sim, name, band, settleLimitS, stayS, overshootLimit);Mode(sim, name), configured with.allow(from, to)and.dwell(mode, minS, maxS).
A step without the update doesn't count for the rule.
Signal rules read an output (or input) by name after every step. active names one that is
non-zero while the rule applies:
Oscillation(sim, name, signal, amplitude, durationS, active);Wear(sim, name, signal, {maxReversalsPerHour, maxTravelPerHour, deadband, active});Rate(sim, name, signal, maxRate, active);Energy(sim, name, signal, factor, budget, active);Percent(sim, name, signal, minPercent, active).
Conditions carry a margin: verify.atMost, atLeast, between, near, and, or, not
and implies. A plain boolean has no margin.
Checking a rule: rule.passed and rule.margin give its verdict so far.
Requirements: sim.verifyRequirement(id) names a requirement the simulation verifies:
- in the constructor or
init(), for the whole run; - in
step(), for that step.
The IDs are printed and recorded in the execution's requirements field and in
cppmodel-requirements.json (or $CPPMODEL_REQUIREMENTS_FILE).
See documentation/Verification.md of the CppModel SDK for the details of each rule.
Structured Text (VirtualPLC)
PLC code in IEC 61131-3 Structured Text runs in a simulation through VirtualPlc, the library's
interpreter: the plant model is JavaScript, the controller under test is the .st files. Each
step, set the PLC's inputs, run the tasks due and read its outputs:
const { Simulation, VirtualPlc } = require('cppmodel');
let plc, level;
const sim = new Simulation('Tank (ST)', 60000, 100, {
init: () => {
plc = new VirtualPlc('Tank.st'); // loads and starts
level = 50;
},
step: (s, timeMs) => {
plc.set('Level', level).cycle(timeMs); // the PLC's inputs, the tasks due
const valve = plc.get('Valve'); // its outputs
level += (valve ? 0.8 : 0) - 0.3;
s.outputs.set('Level', level);
},
});
sim.run();Variables are addressed by path: 'Main.Motor' for a variable of program instance Main,
'Pump' for a global, 'Main.Levels[2]' or 'Main.Axis.Position' for an array element or
struct member. get() returns a number (BOOL is 0/1, TIME milliseconds, an enum its value);
getString()/setString() read and write any value as text, a STRING included. variables()
lists the PLC's inputs, outputs, locals and globals. new VirtualPlc() without files starts empty:
load() or loadSource() the sources, then start(), which also restarts the PLC from its
initial values. Tasks come from the sources' CONFIGURATION; without one, every PROGRAM runs on
each cycle. A syntax error, or a fault while cycling, throws CppModelError with Status.PROGRAM
and the .st file and line. Call close() when done (a garbage-collected PLC is freed too). The
SDK's VirtualPlc.hpp lists the language supported.
Things to know
run()is synchronous. It blocks the event loop until the simulation has finished, which is fine for scripts and tests. In a server, run simulations in a worker thread.- Workspace access: every run reads its inputs from and records its execution in your
workspace. Set
CPPMODEL_USERNAMEandCPPMODEL_PASSWORDfor scripts and CI. Without credentials, the first run prints a sign-in link and waits 60 seconds for you to sign in (CPPMODEL_LOGIN_TIMEOUTchanges that, in seconds); without a sign-in,run()throws. - Fingerprint: each execution records a
CppModel.BinaryFingerprintof the simulation's code, so the workspace can tell runs of the same code from runs of changed code. It is the fingerprint of the file that creates the simulation. Setsim.fingerprintFileto use another file. When that file is in a git repository, the execution also recordsCppModel.GitHash: the commit checked out, with-dirtywhen a tracked file has uncommitted changes. - Cleanup: call
close()when you're done with a simulation. One that is garbage-collected is freed too. - Errors: a failing library call throws a
CppModelErrorwhosestatusis one ofStatus.
License
The CppModel library is proprietary software of Control Edge AB, used under the
CppModel Terms of Service; see LICENSE. The package also
contains third-party components under their own licenses, in licenses/.
