kcan 0.1.3

CAN controller primitives for actuator and motor control.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
# 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.

Private sibling crates under `/home/x4/Workspace/AgenticSpace/` hold reusable pieces that should stay separate when they are useful outside the main control crate:

| Repo | What it is for |
| --- | --- |
| `kcan-core` | No-std CAN/protocol primitives for embedded or dependency-light reuse. |
| `kcan-analytics` | Dependency-free telemetry and bus analytics helpers. |
| `kcan-viewer` | Scrin pane-wall viewer components for actuator dashboards. |

The main `kcan` crate still owns actuator control, bus integration, examples, optional SocketCAN, and the built-in TUI.

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

## 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;

let frame = robstride_status_query_frame(0x01)?;

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.