Three front ends. Shared electrical and control code.
| Task | Start in source |
|---|---|
| Change current-control algorithm | CurrentAlgorithm / Drive → implementation |
| Change motor, gearbox, bus or sensing | PlantConfig / Mechanical / SensorConfig → plant.cpp |
| Change geometry, not physics | Model recipe. Group 1 decorations have zero mass and no contacts. |
| Change the browser obstacle | Geometry envelope generation → periodic spring-damper stop. |
| Change plots and user controls | app.js and worker.js, not the FOC equations. |
Run 0.8 simulated seconds from C++.
This example is built as qdd_live_example and run by CTest. It uses the exact facade compiled to WASM. The output angle should be within 0.03 rad of 0.4 rad and the fault code should remain zero.
// Host/SIL example of the SAME facade exported to WebAssembly. No hardware I/O.
#include "../web/live.h"
#include <cmath>
#include <iostream>
int main() {
if (!lab_reset(0) || !lab_set(0, 4) || !lab_set(1, 0.4)) return 1;
// reset(0) chooses PI; set(0,4) chooses impedance; set(1,...) is output radians.
for (int i=0; i<160; ++i) if (lab_step(100)!=100) return 2;
// 16,000 ticks * 50 us = 0.8 simulated seconds; not wall-clock pacing.
const double position=lab_get(1), current=lab_get(4);
std::cout << "output_rad=" << position << ", iq_A=" << current << '\n';
if (lab_get(12)!=0 || std::abs(position-0.4)>0.03) return 3;
return 0;
}
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --parallel
./build/qdd_live_example
ctest --test-dir build --output-on-failureSource: examples/live_api.cpp. Python is needed at build time for geometry-derived browser stop bounds. It is not in the C++ simulation loop. A core-only build remains available with -DQDD_HOST=OFF.
web/live.h: four exported functions.
int lab_reset(int predictive); // 0 = PI, 1 = relaxed predictive
int lab_set(int field, double value); // validated command, 1 accepted / 0 rejected
int lab_step(int ticks); // n ticks at 50 us; n on success, 0 on failure
double lab_get(int field); // numeric snapshot; invalid field returns NaNlab_reset returns 1 on success and 0 on failure. Positive stepping requests are bounded to 10,000 ticks per call; zero ticks is a no-op. This is a single-instance, heap-using, serialized host facade, not the embedded C11 interface. Reset discards plant, temperature, energy and fault history. Fatal integration errors inhibit further stepping until reset.
All writable command fields
| Field | Command | Units / accepted range |
|---|---|---|
0 | Mode | 0 current · 1 torque · 2 velocity · 3 position · 4 impedance |
1 | Output position | −1.2…+1.2 rad; unwrapped command, not electrical angle |
2 | Output velocity | −6…+6 rad/s |
3 | Feed-forward output torque | −8…+8 N·m |
4 | Constant external load | −8…+8 N·m; positive is subtracted by the plant |
5 | Finite stop enabled | 0 or 1; enabling inside the solid interval is rejected |
6 | Injected driver fault | 0 or 1; clearing input does not clear a latched fault |
7 | Load pulse | −8…+8 N·m for the next 0.12 simulated seconds |
8 | q-axis current request | −15…+15 A; active in Current mode |
9 | Impedance stiffness Kp | 1…150 N·m/rad |
10 | Impedance damping Kd | 0…10 N·m·s/rad |
Non-finite or out-of-range commands return 0 without partial application. A current algorithm cannot be hot-swapped here: the UI resets and pauses when the algorithm changes.
All telemetry fields
Indices 0–26 preserve the original layout. Indices 27–30 add the contact contract. A row contains 31 doubles. In the browser a row is emitted every 20 control ticks (1 kHz); the last 8,000 rows are kept for CSV export. This does not capture every PWM edge or every transient peak.
| Index | CSV name / quantity | Meaning |
|---|---|---|
0 | time_s | Simulated time, not wall time |
1 | output_angle_rad | True unwrapped output angle |
2 | output_speed_rad_s | True output speed |
3 | id_A | True plant d-axis current |
4 | iq_A | True plant q-axis current |
5 | iq_reference_A | Limited controller q-axis request |
6 | gear_torque_Nm | Compliant gearbox torque at output |
7 | bus_V | DC-link voltage |
8 | rotor_angle_rad | True unwrapped motor angle |
9 | winding_C | Lumped winding temperature |
10 | fet_C | Lumped inverter temperature |
11 | state | 0 Disabled / 1 Calibrating / 2 Ready / 3 Armed / 4 Fault |
12 | fault | Fault enum; 0 means none, 9 means GateDriver |
13 | gates_on | Effective enable after independent inhibit |
14 | duty_a | Phase A duty, dimensionless |
15 | duty_b | Phase B duty, dimensionless |
16 | duty_c | Phase C duty, dimensionless |
17 | interval_peak_phase_current_A | Maximum in the LAST 50 μs interval, not a 1 ms aggregate |
18 | target_angle_rad | Output-angle command; not relevant as a velocity reference |
19 | external_load_Nm | Applied constant load plus active pulse |
20 | stop_reaction_Nm | Signed load reaction; negative at the reverse face |
21 | torque_reference_Nm | Limited outer-loop output request |
22 | voltage_saturated | Boolean; final voltage vector differs from requested |
23 | break_latched | Independent protection latch |
24 | rotor_speed_rad_s | True motor speed |
25 | current_reference_limited | Boolean; current request exceeded current circle |
26 | fatal | Integrator/API fatal error; stepping is inhibited |
27 | stop_lower_limit_rad | Lower boundary of the anchored free arc; use only when enabled |
28 | stop_upper_limit_rad | Upper boundary of the anchored free arc; use only when enabled |
29 | stop_enabled | Effective contact state, not an optimistic UI checkbox |
30 | stop_penetration_rad | Compliant angular deflection beyond the free arc; not metres |
Do not confuse state with measurement. Fields 1–4 and 8 are plant truth. The controller consumes filtered, quantized and aged sensor frames internally. A 1 kHz plant trace is not a 20 kHz ADC log.
The Worker is the browser control boundary.
worker.js instantiates Emscripten's createQdd() module and calls core._lab_* exports. The UI sends messages; it does not call Drive directly and does not need an API key.
// Send to your Worker instance; the existing app already creates one.
worker.postMessage({type: 'set', key: 1, value: 0.7});
worker.postMessage({type: 'run', value: true});
worker.postMessage({type: 'set', key: 7, value: 4}); // 120 ms load pulse
worker.postMessage({type: 'run', value: false});
worker.postMessage({type: 'step'}); // paused: 20 ticks = 1 ms| Message | Effect / reply |
|---|---|
reset | New paused experiment. Optional scenario, algorithm, values. Reply: reset + row. |
set | Validated command change. It is not a telemetry sample. |
run / step | Toggle integration, or advance one millisecond while paused. |
rate | 0.25 or 1 target wall-time rate; fixed physics timestep is unchanged. |
samples | Reply with rows of plant state and controller outputs. |
rejected | Stop activation intersects the solid obstacle. Undo the checkbox, keep the experiment alive, move clear or reset. |
error | Engine/validation failure; show it and stop rather than animating stale state. |
Do not infer real-time deadlines from setInterval: the browser may throttle or fall behind. Simulated time comes from the C++ tick count. Hiding the document pauses the UI's run request.
Drive::tick(Measurement, Command)
Drive owns the state machine, sensor-offset calibration, outer-loop state, current reference limits, current algorithm and modulation. Each tick returns DriveOutput: duties, estimated dq current, limited references, voltage, gate enable, state, fault and saturation flags. It does not advance the physical plant.
class CurrentAlgorithm {
public:
virtual ~CurrentAlgorithm() = default;
virtual DQ voltage(DQ reference, const CurrentFeedback&, float dt) noexcept = 0;
virtual void track(DQ requested, DQ applied, float dt) noexcept = 0;
virtual void reset() noexcept = 0;
};voltage() requests a voltage vector; track() receives the final vector after limiting for anti-windup; reset() clears algorithm state. Drive::use_algorithm() accepts a caller-owned instance only while Disabled or Ready. The algorithm must outlive the Drive and all calls must be serialized. Do not allocate, block, log, or access hardware inside the control method.
The allocation-free C11 boundary is different
qdd/c_api.h uses a caller-owned, zero-initialized qdd_context with 1024 bytes of aligned storage, one per motor. qdd_default_config → qdd_init → qdd_tick → qdd_destroy is the lifecycle. Do not copy an initialized context or call it concurrently.
qdd_init returns 0 on success, −1 for invalid pointers/storage, −2 for invalid configuration. qdd_tick can return 0 while its output contains a latched motor fault: inspect out.fault and out.gate_enable, not only the return value. Calibration, valid measurements, arming and coherent sample ages are caller responsibilities. Tested C11 caller →
STM32 is still a port contract
BoardPort / control_irq requires coherent ADC/encoder snapshots, hardware BREAK status, commissioning approval, gate-off and atomic PWM/gate commit. It does not configure TIM1, ADC, DMA, MOSFETs, CAN-FD, or a real board. The host mock test is not hardware execution evidence.
MuJoCo owns positions, velocities and both inertias.
external.h is host-only C ABI v1. Create a handle with qdd_external_create(switched, predictive), query qdd_external_period(), call qdd_external_tick() and finally destroy the handle. Creation may return null; tick returns 0 on success, −1 on invalid/fatal input.
Internal mechanical integration is disabled for both inertias in this mode. C++ still computes reciprocal gearbox reaction, rotor friction, electrical current, bus and thermal state. MuJoCo owns output friction, gravity and contact. Imposing commanded positions on qpos after stepping would destroy that closed loop; the bridge does not do that.
The exchange interval is 50 μs with explicit torque holds. More mechanical substeps refine MuJoCo integration but not the exchange rate. Previous contact/impact refinement results therefore do not establish coupling-rate convergence. Runner · ctypes layout.
A practical edit–test loop.
# Motor mismatch: change plant values without changing controller assumptions.
./build/qdd_sim --case locked-current --duration 0.12 \
--profile profiles/mismatch_RL.ini --log-every 1 --output results/mismatch-01
# Actual external-engine verification (install dependencies first).
python -m pip install -r examples/mujoco/requirements.txt
python tools/verify_mujoco.py --backend osmesa --record --output results/mj-01
# Regenerate model, static site and SAME C++ browser code.
npm install --prefix web --ignore-scripts
python tools/build_site.py
python tools/build_signal_data.py
bash tools/build_wasm.sh
python -m http.server 8765 --directory _siteUse a fresh output directory for every evidence run. The web build needs Emscripten; recording needs ffmpeg and an available graphics backend. The Pages workflow builds WASM, renders actual MuJoCo films, tests controls and guides in Chromium, then checks the deployed URL and its source commit. A local server without generated recordings is not the complete video gallery.
| Change | Minimum test lane |
|---|---|
| FOC or limits | Native Release/Debug/sanitizer; current step, saturation, fault and mismatch cases. |
| Geometry / stop | Geometry envelope and reverse round-trip tests; live positive/negative contact and a visual check. |
| API or guide example | Compile the example, validate field tables and Worker width; never silently reorder telemetry. |
| UI / guide | Browser controls, keyboard diagram steps, local links, narrow layout and public source binding. |
Method references and claim boundaries · Guided experiments · Actual MuJoCo recordings