aactuator
DEVELOP / SOURCE-BOUND REFERENCE

Find the code.
Change one thing. Test it.

Choose the right boundary: browser experiment, reusable controller, or external mechanics. These interfaces serve different jobs and have different ownership and return conventions.

01 / MECHANICS MUST HAVE ONE OWNER

Three front ends. Shared electrical and control code.

Code ownership across browser, native and MuJoCo pathsBrowser UI sends Worker messages to the live C ABI and shared C++ components compiled to WebAssembly. Native bench uses the same components. MuJoCo uses the external ABI; MuJoCo owns both inertias and poses while C++ supplies electrical dynamics and reaction torques. STM32 has a port contract only.Browser: app.js → worker.jsUI / Three.js renders; it does not solve motionNative: qdd_sim → BenchProfiles / experiment runner / evidenceMuJoCo: run.py ↔ bridge.pyRigid bodies / contact / renderingweb/live.cpp → lab_* exportsC++ WASM: 1-axis plant + periodic stopsrc/bench.cppNative plant owns coordinates + both inertiassrc/external.cpp → C ABIMuJoCo owns mechanics, C++ does notShared implementation: Drive / PiFoc / PredictiveCurrent / SVPWM · Plant electrical model · Inverter · Sensors · FastTripinclude/qdd + src/ · no parallel JavaScript FOC · host plant not part of embedded controller storageFuture board path: qdd_core → qdd/c_api.h or stm32::BoardPort → board-specific BSP (not implemented)
The motor model, sensors and protection are synthetic SIL components. Shared source does not imply identical mechanics or validated hardware.
TaskStart in source
Change current-control algorithmCurrentAlgorithm / Drive → implementation
Change motor, gearbox, bus or sensingPlantConfig / Mechanical / SensorConfig → plant.cpp
Change geometry, not physicsModel recipe. Group 1 decorations have zero mass and no contacts.
Change the browser obstacleGeometry envelope generation → periodic spring-damper stop.
Change plots and user controlsapp.js and worker.js, not the FOC equations.
02 / AN EXECUTABLE EXAMPLE, NOT PSEUDOCODE

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-failure

Source: 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.

03 / BROWSER + HOST EXPERIMENT FACADE

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 NaN

lab_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

FieldCommandUnits / accepted range
0Mode0 current · 1 torque · 2 velocity · 3 position · 4 impedance
1Output position−1.2…+1.2 rad; unwrapped command, not electrical angle
2Output velocity−6…+6 rad/s
3Feed-forward output torque−8…+8 N·m
4Constant external load−8…+8 N·m; positive is subtracted by the plant
5Finite stop enabled0 or 1; enabling inside the solid interval is rejected
6Injected driver fault0 or 1; clearing input does not clear a latched fault
7Load pulse−8…+8 N·m for the next 0.12 simulated seconds
8q-axis current request−15…+15 A; active in Current mode
9Impedance stiffness Kp1…150 N·m/rad
10Impedance damping Kd0…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.

IndexCSV name / quantityMeaning
0time_sSimulated time, not wall time
1output_angle_radTrue unwrapped output angle
2output_speed_rad_sTrue output speed
3id_ATrue plant d-axis current
4iq_ATrue plant q-axis current
5iq_reference_ALimited controller q-axis request
6gear_torque_NmCompliant gearbox torque at output
7bus_VDC-link voltage
8rotor_angle_radTrue unwrapped motor angle
9winding_CLumped winding temperature
10fet_CLumped inverter temperature
11state0 Disabled / 1 Calibrating / 2 Ready / 3 Armed / 4 Fault
12faultFault enum; 0 means none, 9 means GateDriver
13gates_onEffective enable after independent inhibit
14duty_aPhase A duty, dimensionless
15duty_bPhase B duty, dimensionless
16duty_cPhase C duty, dimensionless
17interval_peak_phase_current_AMaximum in the LAST 50 μs interval, not a 1 ms aggregate
18target_angle_radOutput-angle command; not relevant as a velocity reference
19external_load_NmApplied constant load plus active pulse
20stop_reaction_NmSigned load reaction; negative at the reverse face
21torque_reference_NmLimited outer-loop output request
22voltage_saturatedBoolean; final voltage vector differs from requested
23break_latchedIndependent protection latch
24rotor_speed_rad_sTrue motor speed
25current_reference_limitedBoolean; current request exceeded current circle
26fatalIntegrator/API fatal error; stepping is inhibited
27stop_lower_limit_radLower boundary of the anchored free arc; use only when enabled
28stop_upper_limit_radUpper boundary of the anchored free arc; use only when enabled
29stop_enabledEffective contact state, not an optimistic UI checkbox
30stop_penetration_radCompliant 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.

04 / NO BACKEND, NO REST SERVER

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
MessageEffect / reply
resetNew paused experiment. Optional scenario, algorithm, values. Reply: reset + row.
setValidated command change. It is not a telemetry sample.
run / stepToggle integration, or advance one millisecond while paused.
rate0.25 or 1 target wall-time rate; fixed physics timestep is unchanged.
samplesReply with rows of plant state and controller outputs.
rejectedStop activation intersects the solid obstacle. Undo the checkbox, keep the experiment alive, move clear or reset.
errorEngine/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.

05 / THE REUSABLE LOW-LEVEL CONTROLLER

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.

06 / A PHYSICS ENGINE, NOT A POSE PLAYER

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.

MuJoCo qpos/qvel → QddExternalInput C++: sensor frame → FOC → bridge + PMSM electrical substeps QddExternalOutput: average rotor torque + output gearbox torque MuJoCo qfrc_applied += those torques → mj_step → next qpos/qvel

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.

07 / CHANGE THE OWNER, THEN TEST ITS CONTRACT

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 _site

Use 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.

ChangeMinimum test lane
FOC or limitsNative Release/Debug/sanitizer; current step, saturation, fault and mismatch cases.
Geometry / stopGeometry envelope and reverse round-trip tests; live positive/negative contact and a visual check.
API or guide exampleCompile the example, validate field tables and Worker width; never silently reorder telemetry.
UI / guideBrowser controls, keyboard diagram steps, local links, narrow layout and public source binding.

Method references and claim boundaries · Guided experiments · Actual MuJoCo recordings