# kcan Baby Docs

This is the tiny version of the docs: what the crate is, what the `kcan` command does, what the CAN frames mean, and what to be careful about first.

## What This Is

`kcan` is a Rust crate and command for building and reading CAN frames for actuators.
It is built by Trevor Knott, Knott Dynamics.

Keywords: KCAN, CubeMars, RobStride, Scrin, Aisling, Trevor Knott, Knott Dynamics.

It currently focuses on:

- CubeMars AK actuators.
- RobStride/Seeed protocol helpers.
- Generic CAN frame and bus types.
- Optional Linux SocketCAN support.
- Optional Scrin TUI dashboard and CAN monitor, including a wide-screen actuator pane wall.
- Basic `kcan` CLI frame generation.

This crate builds frames. It does not make the motor safe by itself.

## Repo Map

The files you will open most often:

| File | What it is for |
| --- | --- |
| `src/actuator.rs` | Cross-family actuator configs, snapshots, health labels, and dashboard metrics. |
| `src/bus.rs` | `CanFrame`, `CanId`, and the `CanBus` trait. |
| `src/protocol.rs` | CubeMars AK protocol constants, frame builders, feedback decoding, and model specs. |
| `src/motor.rs` | `MotorController`, one-motor control helpers, MIT keepalive, and feedback reads. |
| `src/manager.rs` | `MotorManager`, multi-motor routing on one bus. |
| `src/monitor.rs` | Rolling CAN frame log, stats, formatting, trace export/replay, and protocol classification. |
| `src/socketcan_transport.rs` | Linux SocketCAN adapter behind the `socketcan` feature. |
| `src/tui.rs` | Scrin dashboard and CAN monitor behind the `tui` feature. |
| `src/bin/kcan.rs` | Basic command wrapper for model listing and frame generation. |
| `src/protocols/robstride.rs` | RobStride/Seeed frame builders and feedback parser. |
| `examples/cubemars_models.rs` | Hardware-free CubeMars model and frame-ID listing. |
| `examples/cubemars_direct_frames.rs` | Hardware-free CubeMars direct frame listing. |
| `examples/robstride_frames.rs` | Hardware-free RobStride frame listing. |
| `examples/socketcan_ak60.rs` | Live AK60-6 SocketCAN motion example. |
| `examples/socketcan_monitor.rs` | Live read-only CAN monitor. |
| `examples/socketcan_dashboard.rs` | Live read-only CubeMars/RobStride actuator dashboard. |
| `examples/can_monitor_demo.rs` | Hardware-free CAN monitor demo. |
| `examples/tui_dashboard.rs` | Hardware-free actuator dashboard demo. |

If you are changing CubeMars bytes, start in `src/protocol.rs` and add or update tests in `tests/protocol.rs`.

If you are changing live bus behavior, start in `src/bus.rs`, `src/socketcan_transport.rs`, and the in-memory bus tests.

Published companion crates hold reusable pieces that should stay separate when they are useful outside the main control crate:

| Crate | What it is for |
| --- | --- |
| `kcan-core` | No-std CAN/protocol primitives for embedded or dependency-light reuse. |
| `kcan-viewer` | Scrin pane-wall viewer components for actuator dashboards. |

The main `kcan` crate remains the user-facing name and still owns actuator control, bus integration, examples, optional SocketCAN, optional TUI integration, and the `kcan` binary. Use `kcan-core` and `kcan-viewer` directly only when a larger app needs those narrower layers.

## Feature Flags

Default build has no optional runtime dependencies.

| Feature | Adds | Use when |
| --- | --- | --- |
| default | Core protocol, controllers, monitor model, tests | You only need frame building/parsing. |
| `serde` | Serialize/deserialize support for configs, snapshots, commands, and feedback | You want to save/load app configuration or logs. |
| `socketcan` | Linux SocketCAN transport | You want to talk to `can0`. |
| `tui` | Scrin dashboard and CAN monitor UI | You want the terminal dashboards. |

Common commands:

```sh
cargo test
cargo test --all-features
cargo test --features serde
cargo test --examples --all-features
cargo run --bin kcan -- models
cargo run --example socketcan_monitor --features socketcan,tui -- can0
```

The `socketcan_ak60` example sends motion commands. Do not use it as a smoke test.

Cargo packaging is whitelist-based so local notes, sessions, build artifacts, and scratch files stay out.

Model names, direct modes, MIT helper commands, origin modes, and RobStride frame kinds implement `Display` and `FromStr` for simple CLI/app parsing.

`CanId` and `CanFrame` implement `Display` for the same `standard 0x123 len=... data=...` format used by the CLI. `CanId` also implements `FromStr` for explicit strings like `standard 0x123`, `extended:0x501`, `s:0x123`, and `e:0x501`.

## Basic CLI

Run CLI help:

```sh
cargo run --bin kcan -- help
```

List supported actuator models:

```sh
cargo run --bin kcan -- models
```

Build a CubeMars MIT neutral frame:

```sh
cargo run --bin kcan -- cubemars mit ak60-6 0x03
```

Build a CubeMars direct velocity frame:

```sh
cargo run --bin kcan -- cubemars direct 0x03 velocity 1000
```

Build a RobStride status query frame:

```sh
cargo run --bin kcan -- robstride status rs01 0x01
```

Build a RobStride frame in Rust:

```rust
use kcan::robstride_status_query_frame;
use kcan::RobStrideModel;

let model: RobStrideModel = "rs01".parse()?;
let frame = robstride_status_query_frame(0x01)?;

assert_eq!(model.to_string(), "RS-01");
assert_eq!(frame.id().raw(), 0x501);
# Ok::<(), kcan::Error>(())
```

Build a CubeMars frame in Rust:

```rust
use kcan::{DirectCommand, direct_command_frame};

let frame = direct_command_frame(0x03, DirectCommand::Velocity(1_000))?;

assert_eq!(frame.id().raw(), 0x0303);
# Ok::<(), kcan::Error>(())
```

## Safety First

- Test with the motor unloaded first.
- Keep people, cables, and tools away from the actuator output.
- Use a current-limited supply when possible.
- Using the wrong protocol mode can damage a driver.
- Do not switch CubeMars Servo Mode and MIT Mode while the driver is running. Change mode in CubeMarsTool, then restart power if needed.
- Calibrate after reinstalling the driver board, changing motor phase wiring, or updating firmware.
- Hardware validation has not been done in this workspace.

## Hardware Basics

CubeMars AK drivers use:

- CAN speed: `1_000_000` bits/sec.
- Use the voltage range required by the actuator and driver.
- CAN wires: `CAN_H` to `CAN_H`, `CAN_L` to `CAN_L`.
- R-Link can bridge USB from the PC to CAN/UART for CubeMarsTool.

Basic Linux CAN setup usually looks like:

```sh
sudo ip link set can0 up type can bitrate 1000000
```

Then run examples with `can0` if the interface exists.

## CAN Frame Anatomy

A classic CAN frame has three pieces you care about first:

| Piece | Meaning |
| --- | --- |
| ID | Who the message is for, or what kind of message it is. |
| Extended flag | Whether the ID is 11-bit standard or 29-bit extended. |
| Data | 0 to 8 payload bytes. |

In `kcan`, that is `CanFrame`:

```rust
use kcan::{CanFrame, CanId};

let frame = CanFrame::new(CanId::extended(0x0303)?, &[0x00, 0x00, 0x03, 0xE8])?;

assert_eq!(frame.id().raw(), 0x0303);
assert_eq!(frame.len(), 4);
# Ok::<(), kcan::Error>(())
```

`CanFrame::new` keeps the payload length you pass. `CanFrame::new_padded` forces the frame length to 8 bytes.

That matters because CubeMars Servo Direct commands often use 4 or 1 data bytes, while MIT commands use 8 data bytes.

## can-utils Quick Look

If `can-utils` is installed, `candump` is the simplest read-only check:

```sh
candump can0
```

`cansend` format is `ID#DATA`. Use 8 hex digits for an extended ID, and 3 hex digits for a standard ID.

Examples for motor `0x03`:

```sh
cansend can0 00000303#000003E8
cansend can0 00000003#FFFFFFFFFFFFFFFC
cansend can0 003#FFFFFFFFFFFFFFFC
```

Those mean:

| Command | Meaning |
| --- | --- |
| `00000303#000003E8` | CubeMars Servo Direct velocity `1000 ERPM` to motor `0x03`. |
| `00000003#FFFFFFFFFFFFFFFC` | AK60-style extended MIT enter-control helper for motor `0x03`. |
| `003#FFFFFFFFFFFFFFFC` | AK80-style standard MIT enter-control helper for motor `0x03`. |

Do not use `cansend` motion commands unless the actuator is physically safe to move.

## Zero-To-First-Test

Start in this order:

1. Run `cargo test` with no hardware attached.
2. Run `cargo run --example can_monitor_demo --features tui` to make sure the TUI path works.
3. Wire CAN and power with the actuator output unloaded.
4. Bring up SocketCAN at `1000000` bitrate.
5. Run the live monitor before sending motion commands.
6. Confirm the motor ID and mode in CubeMarsTool.
7. Send the smallest useful command only after feedback looks sane.

Read-only monitor command:

```sh
cargo run --example socketcan_monitor --features socketcan,tui -- can0
```

## Which Mode Do I Use

Use Servo Direct Mode when:

- The driver is in CubeMars Servo Mode.
- You want simple duty, current, velocity, position, origin, or position-speed commands.
- You want the mode number visible in the extended CAN ID.

Use MIT Force Control Mode when:

- The driver is in CubeMars MIT Mode.
- You want one packet containing position, velocity, gains, and torque.
- You are using `MotorController::set_velocity_erpm`, `set_position_degrees`, or `set_torque_nm`.

Do not mix them while the driver is running.

## CubeMars Modes

CubeMars has two important CAN control styles.

### Servo Direct Mode

Servo direct commands use extended CAN IDs:

```text
id = (mode << 8) | motor_id
```

Mode IDs:

| Mode | Number | kcan command |
| --- | ---: | --- |
| Duty cycle | `0` | `DirectCommand::DutyCycle` |
| Current loop | `1` | `DirectCommand::Current` |
| Brake current | `2` | `DirectCommand::BrakeCurrent` |
| Velocity | `3` | `DirectCommand::Velocity` |
| Position | `4` | `DirectCommand::Position` |
| Set origin | `5` | `DirectCommand::SetOrigin` |
| Position-speed | `6` | `DirectCommand::PositionVelocity` |

Basic scaling:

| Command | Payload value |
| --- | --- |
| Duty | `duty * 100000` as signed 32-bit big-endian |
| Current | `amps * 1000` as signed 32-bit big-endian |
| Velocity | ERPM as signed 32-bit big-endian, clamped to `-100000..100000` |
| Position | degrees times `10000` as signed 32-bit big-endian |
| Origin | `0` temporary, `1` permanent |
| Position-speed | position, then speed/10, then acceleration/10 |

Exact examples for motor ID `0x03`:

| Meaning | CAN ID | Data |
| --- | --- | --- |
| Duty `0.2` | `00000003` extended | `00 00 4E 20` |
| Current `2.5 A` | `00000103` extended | `00 00 09 C4` |
| Velocity `1000 ERPM` | `00000303` extended | `00 00 03 E8` |
| Position `90 deg` | `00000403` extended | `00 0D BB A0` |
| Temporary origin | `00000503` extended | `00` |
| Position-speed `180 deg`, `5000 ERPM`, `30000 ERPM/s` | `00000603` extended | `00 1B 77 40 01 F4 0B B8` |

Packet math examples:

| Goal | Math | Bytes |
| --- | --- | --- |
| Duty `0.2` | `0.2 * 100000 = 20000 = 0x00004E20` | `00 00 4E 20` |
| Current `1.0 A` | `1.0 * 1000 = 1000 = 0x000003E8` | `00 00 03 E8` |
| Velocity `-1000 ERPM` | `-1000` as signed int32 | `FF FF FC 18` |
| Position `90 deg` | `90 * 10000 = 900000 = 0x000DBBA0` | `00 0D BB A0` |
| Position-speed speed `5000 ERPM` | `5000 / 10 = 500 = 0x01F4` | `01 F4` |
| Position-speed accel `30000 ERPM/s` | `30000 / 10 = 3000 = 0x0BB8` | `0B B8` |

Example:

```rust
use kcan::protocol::{DirectCommand, direct_command_frame};

let frame = direct_command_frame(0x03, DirectCommand::Velocity(1_000))?;

assert_eq!(frame.id().raw(), 0x0303);
# Ok::<(), kcan::Error>(())
```

### MIT Force Control Mode

MIT mode is for position, velocity, and torque control in one 8-byte packet.

CubeMars helper packets:

| Helper | Bytes |
| --- | --- |
| Enter motor control | `FF FF FF FF FF FF FF FC` |
| Exit motor control | `FF FF FF FF FF FF FF FD` |
| Set current position as zero | `FF FF FF FF FF FF FF FE` |

Supported CubeMars model names:

```text
AK10-9, AK45-10, AK60-6, AK70-10, AK80-6, AK80-8, AK80-9, AK80-64,
AK90-6, AK90-9, AK90-12, AK90-30, AK100-9, AK100-15, AK100-25,
AK100-33, AK110-9, AK120-12, AK125-9, AK140-10, AK150-9
```

CubeMars MIT IDs are model-profile specific in this crate:

| Profile | Models | Command ID | Helper ID | Common feedback ID |
| --- | --- | --- | --- | --- |
| Extended MIT | AK60-6 | extended `(0x08 << 8) | motor_id` | extended `motor_id` | extended `0x2900 | motor_id` |
| Standard MIT | Other supported AK models | standard `motor_id` | standard `motor_id` | standard `motor_id` |

MIT limits used by `kcan`:

| Model | Position | Velocity | Torque | Kp | Kd |
| --- | --- | --- | --- | --- | --- |
| AK60-6 | `-12.56..12.56 rad` | `-60..60 rad/s` | `-12..12 Nm` | `0..500` | `0..5` |
| AK80-6 | `-12.5..12.5 rad` | `-76..76 rad/s` | `-12..12 Nm` | `0..500` | `0..5` |
| Other AK models | `-12.5..12.5 rad` | `-60..60 rad/s` | `-12..12 Nm` | `0..500` | `0..5` |

`kcan` handles the CubeMars MIT byte layouts through `MotorModel`.
AK60-6 and AK80-6 keep tuned model specs. Other AK names use conservative protocol defaults for shared frame building until hardware-specific values are configured.

Example:

```rust
use kcan::{MitCommand, MotorModel};

let payload = MotorModel::Ak60_6.pack_mit(MitCommand {
    position_rad: 0.0,
    velocity_rad_s: 1.0,
    kp: 0.0,
    kd: 0.2,
    torque_nm: 0.0,
})?;

assert_eq!(payload.len(), 8);
# Ok::<(), kcan::Error>(())
```

## Feedback Basics

CubeMars Servo Mode feedback is 8 bytes:

| Bytes | Meaning | Scaling |
| --- | --- | --- |
| `0..1` | position | signed 16-bit times `0.1 deg` |
| `2..3` | speed | signed 16-bit times `10 ERPM` |
| `4..5` | current | signed 16-bit times `0.01 A` |
| `6` | temperature | signed 8-bit Celsius |
| `7` | error code | `0` means no fault |

CubeMars basic error codes:

| Code | Meaning |
| ---: | --- |
| `0` | No fault |
| `1` | Motor over-temperature |
| `2` | Over-current |
| `3` | Over-voltage |
| `4` | Under-voltage |
| `5` | Encoder fault |
| `6` | MOSFET over-temperature |
| `7` | Motor lock-up |

Basic decode example:

```text
data = 00 64 00 0A FF 9C 19 02
position = 0x0064 * 0.1 = 10.0 deg
speed = 0x000A * 10 = 100 ERPM
current = -100 * 0.01 = -1.0 A
temperature = 25 C
fault = 2, over-current
```

Feedback sanity checks:

| Field | Usually suspicious when |
| --- | --- |
| Position | It jumps wildly while the motor is still. |
| Speed | It is nonzero while the motor is stopped. |
| Current | It is large at idle. |
| Temperature | It is outside the plausible room/driver range. |
| Fault | It is anything other than `0`. |

If the numbers are suspicious, do not send motion. Fix mode, ID, wiring, bitrate, or parser assumptions first.

## First Live Read-Only Check

Before sending motion:

1. Confirm `can0` is up at `1000000` bitrate.
2. Power the actuator and CAN adapter.
3. Open the live monitor.
4. Look for frames with the expected ID family.
5. Confirm feedback values are plausible before control.

Useful Linux status command:

```sh
ip -details -statistics link show can0
```

If you see bus errors climbing, stop and check bitrate, wiring, termination, power, and ground path.

## Hardware Validation Worksheet

Use this as a scratch checklist before trusting motion.

```text
Date:
Operator:
Motor model:
Motor ID:
Mode in CubeMarsTool:
Power supply voltage:
Current limit:
CAN adapter:
CAN interface:
Bitrate:
Termination checked:
Actuator unloaded:
Emergency stop plan:

Read-only checks:
[ ] can0 is up
[ ] candump or socketcan_monitor sees frames
[ ] feedback ID matches expected model/mode
[ ] position is plausible
[ ] speed is plausible
[ ] current is plausible
[ ] temperature is plausible
[ ] fault code is 0

First command:
Command type:
Target value:
Expected CAN ID:
Expected data bytes:
Observed behavior:
Observed feedback:
Stop command tested:
Notes:
```

Do not skip the read-only checks. They catch most wrong-ID and wrong-mode mistakes before motion.

## Safe First Commands

Prefer read-only first, then tiny commands.

| Mode | First useful command | Why |
| --- | --- | --- |
| Servo Direct | `DirectCommand::Velocity(100)` | Easy to see, easy to stop, low magnitude. |
| Servo Direct | `DirectCommand::Current(0.1)` | Small torque-producing command if velocity mode is not desired. |
| MIT | `MitCommand::neutral()` after enter-control | Confirms packet path without requesting motion. |
| MIT | `set_velocity_erpm(100)` | Uses controller clamping and default damping gain. |

Always test `stop()` or a known stop frame before increasing command size.

## Stop Behavior

In `MotorController`, `stop()` sends neutral MIT frames and then disables MIT mode.

That is useful for MIT control, but it is not the same as cutting power.

For Servo Direct control, use the matching safe command for your mode, such as velocity `0`, duty `0`, or current `0`, and keep a real hardware power cutoff available.

## The High-Level Controller

Use `MotorController` when you want `kcan` to manage frame creation and remember the active MIT command.

```rust
use kcan::{MotorConfig, MotorController, SocketCanBus};

let bus = SocketCanBus::open("can0")?;
let mut motor = MotorController::new(bus, MotorConfig::default())?;

motor.enable_mit_mode()?;
motor.set_velocity_erpm(1_000)?;
motor.stop()?;
# Ok::<(), kcan::Error>(())
```

`MotorConfig::default()` means:

- Motor ID: `0x03`.
- Model: `AK60-6`.
- CAN interface is not stored there; the bus object handles that.

The live `socketcan_ak60` example sends a real velocity command. Treat it as a hardware test, not a harmless demo.

## API Cookbook

Build a CubeMars Servo Direct frame without hardware:

```rust
use kcan::protocol::{DirectCommand, direct_command_frame};

let frame = direct_command_frame(0x03, DirectCommand::Current(1.0))?;

assert_eq!(frame.id().raw(), 0x0103);
assert_eq!(frame.data(), &[0x00, 0x00, 0x03, 0xE8]);
# Ok::<(), kcan::Error>(())
```

Build the same CubeMars Servo Direct payload without allocating a `Vec`:

```rust
use kcan::DirectCommand;

let payload = DirectCommand::Current(1.0).payload_bytes();

assert_eq!(payload.len(), 4);
assert_eq!(payload.data(), &[0x00, 0x00, 0x03, 0xE8]);
```

Configure an AK80-6 instead of the default AK60-6:

```rust
use kcan::{MotorConfig, MotorModel};

let config = MotorConfig {
    motor_id: 0x01,
    model: MotorModel::Ak80_6,
    ..MotorConfig::default()
};

assert_eq!(config.model.name(), "AK80-6");
```

Send a low direct velocity command in Servo Mode:

```rust
use kcan::{MotorConfig, MotorController, SocketCanBus};

let bus = SocketCanBus::open("can0")?;
let mut motor = MotorController::new(bus, MotorConfig::default())?;

motor.set_direct_velocity_erpm(500)?;
# Ok::<(), kcan::Error>(())
```

Send a low MIT velocity command in MIT Mode:

```rust
use kcan::{MotorConfig, MotorController, SocketCanBus};

let bus = SocketCanBus::open("can0")?;
let mut motor = MotorController::new(bus, MotorConfig::default())?;

motor.enable_mit_mode()?;
motor.set_velocity_erpm(500)?;
motor.stop()?;
# Ok::<(), kcan::Error>(())
```

Receive one feedback frame:

```rust
use std::time::Duration;
use kcan::{MotorConfig, MotorController, SocketCanBus};

let bus = SocketCanBus::open("can0")?;
let mut motor = MotorController::new(bus, MotorConfig::default())?;

if let Some(feedback) = motor.receive_feedback(Duration::from_millis(100))? {
    println!("pos={} deg fault={}", feedback.position_degrees, feedback.error_code);
}
# Ok::<(), kcan::Error>(())
```

Set up two CubeMars motors on one bus:

```rust
use kcan::{MotorConfig, MotorManager, SocketCanBus};

let left = MotorConfig {
    motor_id: 0x03,
    ..MotorConfig::default()
};
let right = MotorConfig {
    motor_id: 0x04,
    ..MotorConfig::default()
};

let bus = SocketCanBus::open("can0")?;
let mut manager = MotorManager::new(bus, [left, right])?;

manager.send_keepalive_all()?;
# Ok::<(), kcan::Error>(())
```

Build a RobStride status query frame:

```rust
use kcan::protocols::robstride::{RobStrideCommand, RobStrideModel, robstride_command_frame};

let frame = robstride_command_frame(RobStrideModel::Rs01, 1, RobStrideCommand::StatusQuery)?;

assert_eq!(frame.id().raw(), 0x501);
assert_eq!(frame.len(), 8);
# Ok::<(), kcan::Error>(())
```

Create a fake bus in tests:

```rust
use std::time::Duration;
use kcan::{CanBus, CanFrame, Result};

#[derive(Default)]
struct RecordingBus {
    sent: Vec<CanFrame>,
}

impl CanBus for RecordingBus {
    fn send(&mut self, frame: &CanFrame) -> Result<()> {
        self.sent.push(frame.clone());
        Ok(())
    }

    fn receive(&mut self, _timeout: Duration) -> Result<Option<CanFrame>> {
        Ok(None)
    }
}
```

Use fake buses for frame-level tests. Use real SocketCAN only for hardware integration checks.

## Troubleshooting

No `can0` interface:

- Check that the CAN adapter is plugged in and recognized by Linux.
- Check `ip link`.
- Bring the interface up with `sudo ip link set can0 up type can bitrate 1000000`.

No frames in the monitor:

- Confirm actuator power.
- Confirm `CAN_H` and `CAN_L` are not swapped.
- Confirm all devices use `1 Mbps`.
- Confirm the motor is configured to send status over CAN.
- Confirm the motor ID you expect is the motor ID configured in CubeMarsTool.

Frames appear but values look wrong:

- Check whether the motor is in Servo Mode or MIT Mode.
- Check AK60-6 vs AK80-6 model selection.
- Check whether the frame is standard or extended.
- Check byte length. Servo direct commands are often 4 bytes or 1 byte; MIT packets are 8 bytes.

Motor does not move:

- Check that the driver is in the mode your command expects.
- For MIT, send enter-control helper before normal commands.
- Check motor ID.
- Use very small commands first.
- Check for a nonzero fault code.

Motor faults:

- Stop sending motion commands.
- Decode the error byte if feedback is available.
- Fix the electrical or mechanical cause before trying again.

Unexpected direction or rough motion:

- Stop testing.
- Recheck calibration.
- Recheck phase wiring and encoder setup.
- Do not paper over a bad calibration with software signs until hardware setup is known-good.

## Useful Commands

Run normal tests:

```sh
cargo test
```

Run everything with optional features:

```sh
cargo test --all-features
```

Run examples as tests:

```sh
cargo test --examples --all-features
```

Run ignored hardware integration tests only after the bench is safe and `can0` is configured:

```sh
KCAN_ENABLE_HARDWARE_TESTS=1 KCAN_CAN_IFACE=can0 cargo test --features socketcan --test hardware -- --ignored
```

The neutral MIT write test is also gated by `KCAN_ENABLE_WRITE_TESTS=1`, `KCAN_MOTOR_MODEL`, and `KCAN_MOTOR_ID`:

```sh
KCAN_ENABLE_HARDWARE_TESTS=1 KCAN_ENABLE_WRITE_TESTS=1 KCAN_MOTOR_MODEL=ak60-6 KCAN_MOTOR_ID=0x03 cargo test --features socketcan --test hardware -- --ignored
```

Do not enable write tests until the motor is unloaded, IDs are confirmed, and a real power cutoff is ready.

Run the simulated TUI dashboard:

```sh
cargo run --example tui_dashboard --features tui
```

List supported CubeMars models and generated frame IDs:

```sh
cargo run --example cubemars_models
```

Print CubeMars direct frames without hardware:

```sh
cargo run --example cubemars_direct_frames
```

Print RobStride frames without hardware:

```sh
cargo run --example robstride_frames
```

Run the simulated CAN monitor:

```sh
cargo run --example can_monitor_demo --features tui
```

Run the live SocketCAN monitor:

```sh
cargo run --example socketcan_monitor --features socketcan,tui -- can0
```

Run the live read-only actuator dashboard with CubeMars and RobStride targets:

```sh
cargo run --example socketcan_dashboard --features socketcan,tui -- can0 cubemars:ak60-6:0x03 robstride:rs01:0x01
```

Each target is `cubemars:<model>:<id>` or `robstride:<model>:<id>`. The old CubeMars shorthand also works, for example `can0 ak60-6 0x03 0x04`. The dashboard only reads feedback frames and disables TUI control intents.

Export a monitor trace in tests or tools:

```rust
use kcan::{CanFrame, CanId, CanMonitor, parse_can_trace_csv};

let mut monitor = CanMonitor::new(32);
monitor.observe(CanFrame::new(CanId::standard(0x123)?, b"kcan")?);

let csv = monitor.to_trace_csv();
let trace = parse_can_trace_csv(&csv)?;

assert_eq!(trace[0].frame.data(), b"kcan");
# Ok::<(), kcan::Error>(())
```

Trace CSV rows use `sequence,elapsed_us,frame_format,id,len,data_hex`. `frame_format` is `S` for standard IDs and `E` for extended IDs. `tests/fixtures/can_trace_protocols.csv` is a small protocol fixture for parser/classifier regression tests. `replay_can_trace` sends frames immediately; use `elapsed_us` yourself if you need timed playback.

TUI dashboard keys:

| Key | Action |
| --- | --- |
| `j` or `n` | Select next actuator. |
| `k` or `p` | Select previous actuator. |
| `r` | Refresh selected actuator intent. |
| `a` | Arm or disarm control intents. |
| `e` | Enable selected actuator intent, only when armed. |
| `s` | Stop selected actuator intent, only when armed. |
| `z` | Zero selected actuator intent, only when armed. |
| `!` | Emergency stop all intent. |
| `q` | Quit. |

Dashboard arming is one-shot. After `e`, `s`, or `z` emits an intent, after selection changes, or after actuator data changes, the dashboard locks back to `VIEW`. `!` emergency stop intent is available without arming and also locks controls. The live `socketcan_dashboard` example runs the dashboard in read-only mode, so those control intents are disabled.

On wide terminals, the actuator dashboard switches from list/detail mode to a pane wall. Each pane shows the actuator name, model, derived health label, protocol-specific metrics from `ActuatorSnapshot::metrics()`, and read-only analytics from observed feedback.

Dashboard analytics are local UI history only. They track feedback sample count, last-seen age in dashboard ticks, fault sample count, observed position span, and peak absolute effort (`A` for CubeMars current, `Nm` for RobStride torque). They do not send CAN frames or make safety decisions.

CAN monitor keys:

| Key | Action |
| --- | --- |
| `j` or `n` | Select next frame. |
| `k` or `p` | Select previous frame. |
| Space | Pause or resume capture. |
| `c` | Clear the frame log. |
| `q` | Quit. |

## RobStride Basics

RobStride/Seeed support is separate from CubeMars support.

The current ID families are:

| Kind | Base ID |
| --- | ---: |
| MIT | `0x200 + motor_id` |
| Position | `0x300 + motor_id` |
| Speed | `0x400 + motor_id` |
| Status | `0x500 + motor_id` |
| Config | `0x600 + motor_id` |

RobStride packet behavior is encoded explicitly and locked with tests, but live hardware validation is still required.

RobStride model specs currently encoded:

| Model | Max torque | Max speed | Kp range | Kd range |
| --- | ---: | ---: | --- | --- |
| RS-00 | `14.0 Nm` | `315 RPM` | `0..500` | `0..5` |
| RS-01 | `17.0 Nm` | `315 RPM` | `0..500` | `0..5` |
| RS-02 | `17.0 Nm` | `410 RPM` | `0..500` | `0..5` |
| RS-03 | `60.0 Nm` | `195 RPM` | `0..5000` | `0..100` |
| RS-04 | `120.0 Nm` | `200 RPM` | `0..5000` | `0..100` |
| RS-05 | `5.5 Nm` | `480 RPM` | `0..500` | `0..5` |
| RS-06 | `36.0 Nm` | `480 RPM` | `0..5000` | `0..100` |

RobStride quick decode assumptions in this crate:

| Bytes | Meaning | Scaling |
| --- | --- | --- |
| `0..3` | position | little-endian signed int32 divided by `1000` gives radians |
| `4..5` | velocity | little-endian signed int16 divided by `1000` gives rad/s |
| `6..7` | torque | little-endian signed int16 divided by `10` gives Nm |

Treat this as current parser behavior, not a final hardware guarantee.

## Tiny Glossary

| Word | Meaning |
| --- | --- |
| CAN ID | The identifier on a CAN frame. Receivers use it to decide what the frame means. |
| Standard ID | 11-bit CAN ID. AK80-style MIT uses this. |
| Extended ID | 29-bit CAN ID. CubeMars Servo Direct and AK60-6 MIT use this. |
| DLC | Data length code. Classic CAN payload length is 0 to 8 bytes. |
| ERPM | Electrical RPM. It is not always the same as output shaft RPM. |
| MIT Mode | Control style that packs position, velocity, gains, and torque into one packet. |
| Servo Mode | CubeMars mode for direct duty/current/velocity/position style commands. |
| Kp | Position stiffness gain. Higher values can move harder/faster. |
| Kd | Damping gain. Often used with velocity or position control. |
| Clamp | Limit a value before encoding it, so commands stay inside known ranges. |
| SocketCAN | Linux CAN networking interface used by `can0`, `can1`, etc. |

## What To Remember

- Use `1 Mbps` CAN.
- CubeMars Servo Mode uses extended IDs based on `(mode << 8) | motor_id`.
- CubeMars MIT Mode is model-specific, so always pass the right `MotorModel`.
- Feedback scaling is simple but easy to misread.
- Hardware-test before trusting live motion.
- Use the `kcan` command for frame generation and the Rust API for embedded or app integration.
