Skip to content

Architecture

Layers

flowchart TB
    C["controllers (yours)<br>via Arm · Controller · Runner"]

    subgraph ARM["arm/ — L3 · the sim⇄real bridge"]
        SIM["SimArm"]
        REAL["RealArm"]
    end

    MODEL["model/ — L2<br>roki wrappers: ChainModel, JointMap,<br>IkSolver, Cartesian PTP, trajectories"]
    HW["hw/ — L4<br>CraneX7, safety, Config"]
    MILIB["mi-lib<br>(roki, zm, …)"]
    DXL["dxl/ — L1<br>PacketIO seam, Port(SDK), SyncGroup,<br>control table, conversions"]

    subgraph EMU["emu/ — test double"]
        direction TB
        ME["MotorEmulator"]
        PTY["PtyBus<br>(wire-level Protocol 2.0)"]
        FAKE["FakePacketIO<br>(in-process)"]
        ME --- PTY
        ME --- FAKE
    end

    MOTORS["CRANE-X7 servos<br>(7× XM430-W350, 1× XM540-W270,<br>USB serial bus)"]

    C --> SIM
    C --> REAL
    SIM --> MODEL
    REAL --> HW
    MODEL --> MILIB
    HW --> DXL
    DXL --> MOTORS
    HW -.-> FAKE
    DXL -.-> PTY
  • dxl/: motor communication. PacketIO is the abstract transaction seam (ping/read/write/syncRead/syncWrite). Port implements it over DynamixelSDK; the emulator implements it twice for tests. SyncGroup programs the servos' indirect-address banks so one sync-read fetches position/velocity/current/voltage/ temperature for the whole group and one sync-write sets the goals. readMotionWindow reads only the window's first 10 bytes (current, velocity, position) and keeps the voltage and temperature it holds. control_table.hpp/conversions.hpp fix the XM register map and raw-unit conversions (incl. per-model torque constants). StatusReplyParser checks the status replies to one grouped read strictly (header, ID and order, length, byte stuffing, CRC, nothing after the last reply) and reports a fault as soon as the bytes received rule out a valid reply. It also checks a Fast Sync Read's single packet (broadcast ID, exact length, each servo's ID in order, the final CRC; never stuffed).
  • The bounded grouped read (control-rate Phase R). Above 100 Hz, Port::armBoundedSyncRead replaces the SDK's receive for its grouped read windows (one list of servos, one or more lengths) with its own: a deadline (budget) on the monotonic clock after the instruction leaves, and StatusReplyParser on the bytes as they arrive. Nothing is accepted at or after the deadline, even bytes that a receiver paused across it then holds complete. A timeout or a malformed reply is ambiguous, since late bytes may still come. The read fails, and a quiet guard holds every transmission (fallback writes included) until budget + guard after the instruction. Input received meanwhile is discarded, and the next read, of whichever window, asks for one byte more, so a late reply of the normal length fails on its length field. A reply does not name its register, so two windows of one instruction must differ in length by at least 2. A window is a Sync Read or a Fast Sync Read (PacketIO::fastSyncRead, firmware v45 and later), which Port sends only on an armed window. Unarmed, every transaction takes the SDK path unchanged, and no guard is ever set. CraneX7 registers its quiesce flag with the port (PacketIO::setTransmitInhibit): once it is set, every transmission is refused just before sending, and one waiting in the guard gives up instead of going out after it. emu::PtyBus can delay, truncate, garble or drop sync-read replies and records when each instruction arrived, for the fault tests. CraneX7::Options::bounded_read arms it for a session. Activation then checks, before its first torque write and again after the activation configurator, every servo's Return Delay Time, Status Return Level, baud register and (for Fast Sync Read) firmware, plus the adapter's latency timer where the device exposes one. It also checks that the longest silence on the bus (budget + guard and the scheduling and transport allowances) stays below the programmed Bus Watchdog interval less one 20 ms unit, a conservative engineering reserve. After programming the watchdog it reads it back, and only then arms the feedback window, just before torque-on. The checks are read-only. Any mismatch refuses activation with nothing armed, and the usual release cleans up: it clears a servo's Bus Watchdog only after a confirmed torque-off. busDiscovery() reports what was found. Deactivation, a failed activation and the destructor disarm.
  • The motion-only read (control-rate Phase B2). CraneX7::Options::feedback_read with motion_only reads current, velocity and position every cycle, and the full window (with input voltage and temperature) on the thread's first cycle, then every aux_interval_s (default 0.1 s, rounded up to whole cycles), or never after activation with 0. A failed full read is retried the next cycle. Only voltage and temperature carry over from activation: until the thread's first successful read, of either window, the current and velocity writers have no feedback and refuse, as with the full read. It needs the bounded read, which then arms both windows; activation refuses it otherwise, before any bus access. Each CycleRecord notes the bytes per servo its read requested (read_len), so the cycles with the full read, the longest, can be budgeted on their own. Nothing in the control path uses voltage or temperature. With instruction kFastSync (Phase B3) the feedback reads become Fast Sync Reads from the arming on; activation then also checks firmware v45 on every servo.
  • model/: kinematics and dynamics. RAII wrappers over mi-lib's C API: ChainModel (load .ztk, FK, gravity torque, inverse dynamics), JointMap (coordinate/force mappings), IkSolver (error-damped LM with structured IkResult), continuation-seeded Cartesian PTP planning, trajectories, and .zvs motion logging for rk_anim.
  • arm/: the bridge. Arm (activate/deactivate/setMode/ readState/writeCommand/step), Controller + run(), the two implementations SimArm/RealArm, and the shipped controllers GravityComp, textbook ComputedTorque, and the retained historical PracticalComputedTorque.
  • hw/: the real robot. Config (TOML), CraneX7 (activation sequence, mode-checked limited writers, background RW thread, deadman), consumed by RealArm.
  • util/: support. AsyncWriter keeps row-oriented file logging off control threads: rows go into a bounded in-memory queue that its own writer thread drains. Every app run log goes through it, and x7_wave's .zvs export through model::AsyncZvsWriter, built on it.
  • emu/: the test double. One control-table state machine, two transports. Everything ships in the single rtctrl library for build simplicity, so the emulator is linked everywhere, but no controller or production header ever includes it; only tests and the standalone dxl_emu do.

Include-dependency rule (what may #include what; the build is one library, so this, not linkage, is the real boundary): dxl and model are independent of each other; hw depends on dxl + model, plus arm/types.hpp for the shared bridge DATA types (command records and snapshots: types only, no behavior); arm's bridge types and SimArm depend on model, and its RealArm adapter additionally on hw (the arm→hw edge exists solely there); emu depends only on dxl types; util depends on nothing else in the library. Controllers depend on arm (and model for dynamics), never on dxl/hw/emu directly.

Directory map

include/rtctrl/{dxl,model,arm,hw,emu,util}/   public headers (src/ mirrors)
apps/         sources by domain: bus/ (dxl_emu, dxl_inspect,
              dxl_load_params),
              bringup/ (x7_onoff, x7_read, x7_set_param,
              x7_move_simple, x7_pose), gravity/ (x7_float,
              x7_gravity_demo), track/ (x7_track, x7_track_sim),
              plan/ (x7_plan_ptp), follow/ (x7_follow, x7_follow_sim),
              ident/ (x7_ident_sim),
              study/ (x7_efl_study), disturb/ (x7_force_budget),
              common/ (shared app headers); binaries land flat in
              build/apps/
examples/     make_motion, make_pose (kinematic .zvs), x7_wave
              (bridge demo), x7_ct_mass_error (offline study)
models/crane_x7/   crane_x7.ztk + meshes + contactinfo.ztk  (generated, committed),
              crane_x7.init.ztk (hand-written rk_pen posture)
config/       crane_x7.toml (bus, joints, limits, margins),
              ptp_example.toml, link_force_example.toml,
              force_budget_example.toml, versioned postures/*.toml
tools/        port_model.py, ident_analysis.py, replay_compare.py,
              ct_mass_error_study.py, plot/{ptp_trajectory,
              follow_tracking,follow_mode_comparison,track_comparison}.py (uv),
              bootstrap_milib.sh
tests/{unit,integration}/   Catch2; integration = pty emulator + sim
docs/         this documentation
third_party/  pinned submodules (mi-lib metapackage, DynamixelSDK, URDF source)

Canonical coordinates

One joint order is fixed project-wide (model::canonicalJoints()):

canonical joint DXL id servo
0 shoulder pan 2 XM430-W350
1 shoulder tilt 3 XM540-W270
2 upper-arm twist 4 XM430-W350
3 elbow 5 XM430-W350
4 forearm twist 6 XM430-W350
5 wrist pitch 7 XM430-W350
6 wrist rotate 8 XM430-W350
7 gripper (finger A) 9 XM430-W350

The roki model has a ninth joint (finger B, mimicking A). JointMap resolves model indices by link name at load time and provides expand (\(q_9 = E q_8\)), reduce, and reduceTorque (\(\tau_8 = E^\mathsf{T}\tau_9\)); see dynamics foundations. Every JointState/JointCommand on the bridge is canonical 8-DOF; only SimArm/RealArm translate at their boundaries.

The model also carries one virtual fixed link, crane_x7_tcp_link: the tool-center frame at the closed-fingertip midpoint, aligned with the world axes when the gripper points forward. It adds no degree of freedom; it exists as the IK target for world-frame pose commands (x7_pose --tcp).

The bridge contract

class Arm {
  int dof();                    // 8
  double dt();                  // control period
  bool activate();              // torque on, safety armed; holds in
                                // position mode, zero-current in
                                // current mode unless preloaded
  bool deactivate();            // verified torque-off, NOT an e-stop
  bool setMode(ControlMode);    // Position=3 / Velocity=1 / Current=0
  bool readState(JointState&);  // q, dq, tau (est.), t
  bool writeCommand(const JointCommand&);
  bool step();                  // sim: integrate dt; real: wait feedback
};

One cycle is readState → Controller::update → writeCommand → step (arm::run). SimArm integrates plain-roki forward dynamics, \((M + \mathrm{diag}\,J_r)\,\ddot q = \tau - b\), with reflected motor inertia \(J_r\), semi-implicit Euler, inelastic joint stops, and an overdamped equal-and-opposite finger coupling. RealArm rides CraneX7's background thread. A successful grouped read opens a command window and wakes the controller. A feedback-tagged command is accepted only before the window cutoff, leaving the configured margin for limiting, transmission, and safety bookkeeping. step() blocks until the next grouped read opens the next window.

The default 10 ms cycle reserves its final 2 ms for limiting, bus transmission, and safety bookkeeping. A command that misses the open window is rejected instead of being applied from stale feedback. On a missed window, position mode retains its preceding goal, velocity mode sends zero, and current mode retains the preceding bounded current for that cycle. Continued misses reach the 250 ms submission deadman. CycleStats reports rejected stale submissions and command-window misses separately.

Scheduling uses absolute monotonic deadlines. When work finishes after a deadline, the producer advances to the next future boundary instead of issuing catch-up bus traffic. This bounds burst behavior but is not a hard real-time guarantee: the process still uses ordinary operating-system thread scheduling. Maximum cycle duration, lateness, skipped periods, failed reads, and failed writes remain observable in CycleStats.

File I/O stays off the control thread for the same reason. A buffered write to a regular file can block in the kernel for tens to hundreds of milliseconds, long enough to miss command windows, trip arm::run's 25 ms feedback-gap abort, or reach the 250 ms deadman. The apps therefore queue their CSV rows through util::AsyncWriter and close the log only after the arm is released.

Safety architecture (hardware)

Two independent watchdog layers, because each alone has a blind spot:

  1. Servo-side Bus Watchdog (register 98, armed at activation, firmware ≥ v38 enforced): the servo freezes itself (motion halted, goal writes locked out, torque stays on) when no instruction packet arrives in time. Covers host death and cable loss. Blind spot: any packet feeds it, so a host whose reads continue while command writes stall never trips it.
  2. Host-side deadman: tracks the time since the last successful command write and, once a controller has submitted targets, the last fresh submission (write success alone is not liveness: the background thread's retransmissions succeed even when the controller is dead). On staleness it best-effort zeroes/torque-offs and then silences the bus entirely (closes the port), which guarantees layer 1 fires even if the safety writes themselves were failing. The same escalation fires after a few consecutive failed feedback reads: frozen feedback would otherwise leave the controller commanding into a robot it can no longer see, while broadcast sync writes keep "succeeding" and never trip the staleness check (CycleStats::read_failures counts these).

The activation sequence additionally verifies servo models and firmware, clears previously tripped watchdogs, snaps goals to the present posture, and applies soft-start gains. Before any write it refuses a servo whose Drive Mode has bit 3 (Torque On by Goal Update, firmware v45 and later) set, since the goal snap would switch that servo's torque on ahead of the sequence. An activation configurator (the motor parameter loader can write Drive Mode) voids that check, so Drive Mode is checked again after it. Until the check holds, cleanup after a failure or an exception (activation's own release, or deactivate()) writes torque-off alone, never a goal. Activation's own steps never change Drive Mode. Command writers clamp against position/velocity/effort limits and reject mode-mismatched or feedback-less commands. All of it is asserted in tests whose acceptance criterion is the emulated motor's end state, and was drilled on the physical arm (USB pull → freeze within 100 ms).

deactivate() is not an emergency stop. Hardware sessions require an independent actuator-power cutoff within reach (bring-up checklist).

Verification tiers

Tier Command Covers
unit ctest -L unit pure logic + in-process emulator
integration ctest -L integration wire-level emulator through the real SDK; roki dynamics sim
hardware staged apps the physical checklist + controller phases

CI runs the first two from a clean clone, including the mi-lib bootstrap.