bambu-rs 0.1.0

AI-agent-friendly Bambu Lab 3D printer CLI & library
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
//! MQTT command envelopes — the JSON published to `device/{serial}/request`.
//!
//! Each command renders to `{ "<category>": { "sequence_id": .., "command": ..,
//! .. } }`. The printer echoes `sequence_id` back in its report, which is how we
//! match a command to its effect (verify-by-reread).
//!
//! Shapes here are derived from the OpenBambuAPI spec and **must be confirmed
//! against a real A1 mini**; where the device disagrees with the spec, the
//! device wins.

use serde_json::{Value, json};

/// Monotonic allocator for the `sequence_id` field. Owned by the session/client
/// — kept out of [`Command`] so commands stay pure, data-only values.
#[derive(Debug, Default)]
pub struct SequenceIds {
    next: u64,
}

impl SequenceIds {
    pub fn new() -> Self {
        Self::default()
    }

    /// Allocate the next sequence id. Bambu's `sequence_id` is a string.
    pub fn next_id(&mut self) -> String {
        let id = self.next;
        self.next += 1;
        id.to_string()
    }
}

/// Basic AMS control action (`print.ams_control` `param`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AmsControl {
    /// Resume after an AMS pause/error.
    Resume,
    /// Reset the AMS state.
    Reset,
    /// Pause the AMS.
    Pause,
}

impl AmsControl {
    pub fn as_str(self) -> &'static str {
        match self {
            AmsControl::Resume => "resume",
            AmsControl::Reset => "reset",
            AmsControl::Pause => "pause",
        }
    }
}

/// Parameters for `print.ams_filament_setting` — set a tray's filament profile.
/// Shapes are from the OpenBambuAPI spec. **[spec]**
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AmsFilamentSetting {
    /// Index of the AMS unit.
    pub ams_id: u32,
    /// Index of the tray within the unit.
    pub tray_id: u32,
    /// Filament profile id (e.g. `GFA00`); empty if unknown.
    pub tray_info_idx: String,
    /// Colour as hex `RRGGBBAA` (alpha usually `FF`).
    pub tray_color: String,
    /// Minimum/maximum nozzle temperature for the filament (°C).
    pub nozzle_temp_min: i64,
    pub nozzle_temp_max: i64,
    /// Material, e.g. `PLA`, `PETG`.
    pub tray_type: String,
}

/// Which LED a `system.ledctrl` command targets. The node name is what the
/// printer matches in `lights_report`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LedNode {
    /// The chamber/logo light — present on the A1 mini. **[observed]**
    ChamberLight,
    /// A separate work light. **[spec]** — not present on every model (this A1
    /// mini's `lights_report` only carries `chamber_light`), so it may ACK
    /// without effect.
    WorkLight,
}

impl LedNode {
    /// The `led_node` token (also the `lights_report` node name).
    pub fn as_str(self) -> &'static str {
        match self {
            LedNode::ChamberLight => "chamber_light",
            LedNode::WorkLight => "work_light",
        }
    }
}

/// Whether to enable or disable the printer's per-print timelapse recording.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimelapseControl {
    Enable,
    Disable,
}

impl TimelapseControl {
    /// The wire token the printer expects (`"enable"` / `"disable"`), which is
    /// also exactly what the `ipcam.timelapse` report field reads back.
    pub fn as_str(self) -> &'static str {
        match self {
            TimelapseControl::Enable => "enable",
            TimelapseControl::Disable => "disable",
        }
    }
}

/// Print-speed profile. A1/P1 use four levels; the printer echoes the active
/// one back as `spd_lvl` in its report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpeedLevel {
    Silent,
    Standard,
    Sport,
    Ludicrous,
}

impl SpeedLevel {
    /// The numeric level the printer expects (and reports as `spd_lvl`).
    pub fn level(self) -> i64 {
        match self {
            SpeedLevel::Silent => 1,
            SpeedLevel::Standard => 2,
            SpeedLevel::Sport => 3,
            SpeedLevel::Ludicrous => 4,
        }
    }

    /// Map a numeric `spd_lvl` back to a level (`None` for an unknown value).
    pub fn from_level(n: i64) -> Option<Self> {
        match n {
            1 => Some(SpeedLevel::Silent),
            2 => Some(SpeedLevel::Standard),
            3 => Some(SpeedLevel::Sport),
            4 => Some(SpeedLevel::Ludicrous),
            _ => None,
        }
    }

    /// The lowercase name (`silent`/`standard`/`sport`/`ludicrous`).
    pub fn as_str(self) -> &'static str {
        match self {
            SpeedLevel::Silent => "silent",
            SpeedLevel::Standard => "standard",
            SpeedLevel::Sport => "sport",
            SpeedLevel::Ludicrous => "ludicrous",
        }
    }
}

/// A control/query command sent to the printer.
///
/// Pure and data-only: rendering to JSON ([`Command::to_payload`]) takes the
/// caller-allocated `sequence_id`, so the value itself carries no mutable state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    /// Request a full state snapshot (`pushing.pushall`).
    PushAll,
    /// Request the module/firmware inventory (`info.get_version`). A read; the
    /// response comes back under `/info` with a `module[]` array.
    GetVersion,
    /// Pause the current print.
    Pause,
    /// Resume a paused print.
    Resume,
    /// Stop (cancel) the current print — irreversible.
    Stop,
    /// Clear a print error / dismiss the error popup (`print.clean_print_error`).
    /// This is what Bambu Studio sends to acknowledge an error popup. Command name
    /// is from vendor docs; the A1 mini **ACKs it `success`** (observed). What it
    /// does NOT do, observed on this unit: it did not move `gcode_state` out of
    /// `FAILED` (tested with `print_error` already 0), and `ams_change_filament`
    /// stayed rejected while `FAILED`. So treat it as "dismiss the error", not
    /// "return to idle". Sending it *while an error is active* is still
    /// uncharacterised. **[spec]**
    CleanPrintError,
    /// Send a single raw G-code line (`print.gcode_line`).
    GcodeLine(String),
    /// Print a raw G-code file already on the printer (`print.gcode_file`,
    /// single-material — no AMS mapping). The value is the on-printer path.
    GcodeFile(String),
    /// Set the print-speed profile (`print.print_speed`). Effect is read back
    /// from `spd_lvl`; can be sent mid-print.
    PrintSpeed(SpeedLevel),
    /// Start a print of a sliced 3MF on the printer (`print.project_file`).
    ProjectFile(ProjectFile),
    /// Turn an LED on/off (`system.ledctrl`). Effect is read back from
    /// `lights_report` for the matching node, not the ACK alone.
    Led { node: LedNode, on: bool },
    /// Enable/disable the printer's per-print timelapse recording
    /// (`camera.ipcam_timelapse`). Its effect is read back from the
    /// `ipcam.timelapse` report field. **[spec]** — shape is from OpenBambuAPI;
    /// not device-confirmed (this unit's camera is hardware-dead).
    IpcamTimelapse(TimelapseControl),
    /// Reboot the printer (`system.reboot`). Undocumented in the spec but
    /// **accepted by the A1 mini** (observed). The connection drops and the
    /// printer restarts, so there is no ACK — send it fire-and-forget.
    Reboot,
    /// Basic AMS control (`print.ams_control`): resume/reset/pause. **[spec]**
    AmsControl(AmsControl),
    /// Change the loaded filament via the AMS (`print.ams_change_filament`):
    /// `target` tray, with the old (`curr_temp`) and new (`tar_temp`) nozzle
    /// temps. Physically moves filament. **[spec]** — not device-confirmed.
    AmsChangeFilament {
        target: u32,
        curr_temp: i64,
        tar_temp: i64,
    },
    /// AMS RFID-read settings (`print.ams_user_setting`). **[spec]**
    AmsUserSetting {
        ams_id: u32,
        /// Read RFID on startup.
        startup_read: bool,
        /// Read RFID on tray insertion.
        tray_read: bool,
    },
    /// Set a tray's filament profile (`print.ams_filament_setting`). **[spec]**
    AmsFilamentSetting(Box<AmsFilamentSetting>),
    /// Run printer calibration (`print.calibration`, an `option` bitmask).
    /// (Lidar — bit 0 — is X1-only and intentionally not exposed here.)
    Calibration {
        /// Bed leveling (bit 1 = 2).
        bed_level: bool,
        /// Vibration compensation (bit 2 = 4).
        vibration: bool,
        /// Motor-noise calibration (bit 3 = 8).
        motor_noise: bool,
    },
}

/// Parameters for `print.project_file` — start a sliced `.gcode.3mf` that is
/// already on the printer's storage.
///
/// Field shapes are spec-derived (OpenBambuAPI) and must be confirmed on real
/// hardware (the device is the source of truth — start the print and verify it
/// reaches `RUNNING`). Calibration flags default to on, matching a normal slice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectFile {
    /// URL of the file on the printer, e.g. `ftp:///cache/foo.gcode.3mf`.
    pub url: String,
    /// Plate number; the gcode is read from `Metadata/plate_{plate}.gcode`.
    pub plate: u32,
    /// Job name shown on the printer.
    pub subtask_name: String,
    /// Lowercase-hex md5 of the plate gcode (empty to skip the check).
    pub md5: String,
    /// Build-plate type (`auto`, or a specific plate name).
    pub bed_type: String,
    /// Use the AMS, with a per-filament tray mapping (`-1` = external spool).
    pub use_ams: bool,
    pub ams_mapping: Vec<i32>,
    pub timelapse: bool,
    pub flow_cali: bool,
    pub bed_leveling: bool,
    pub vibration_cali: bool,
    pub layer_inspect: bool,
}

impl ProjectFile {
    /// A minimal project print: no AMS, `auto` bed type, calibrations on.
    pub fn new(url: impl Into<String>, plate: u32, subtask_name: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            plate,
            subtask_name: subtask_name.into(),
            md5: String::new(),
            bed_type: "auto".to_string(),
            use_ams: false,
            ams_mapping: Vec::new(),
            timelapse: false,
            flow_cali: true,
            bed_leveling: true,
            vibration_cali: true,
            layer_inspect: true,
        }
    }
}

impl Command {
    /// The top-level message category — the single JSON key this command nests
    /// under, and the key its ACK comes back under (`print` commands are ACKed
    /// at `/print/...`, `system` commands at `/system/...`).
    pub fn category(&self) -> &'static str {
        match self {
            Command::PushAll => "pushing",
            Command::GetVersion => "info",
            Command::Pause
            | Command::Resume
            | Command::Stop
            | Command::CleanPrintError
            | Command::GcodeLine(_)
            | Command::GcodeFile(_)
            | Command::PrintSpeed(_)
            | Command::ProjectFile(_)
            | Command::AmsControl(_)
            | Command::AmsChangeFilament { .. }
            | Command::AmsUserSetting { .. }
            | Command::AmsFilamentSetting(_)
            | Command::Calibration { .. } => "print",
            Command::Led { .. } | Command::Reboot => "system",
            Command::IpcamTimelapse(_) => "camera",
        }
    }

    /// Render this command to its request-payload JSON, stamping `sequence_id`.
    pub fn to_payload(&self, sequence_id: &str) -> Value {
        match self {
            Command::PushAll => json!({
                "pushing": { "sequence_id": sequence_id, "command": "pushall" }
            }),
            Command::GetVersion => json!({
                "info": { "sequence_id": sequence_id, "command": "get_version" }
            }),
            Command::Pause => print_command(sequence_id, "pause", ""),
            Command::Resume => print_command(sequence_id, "resume", ""),
            Command::Stop => print_command(sequence_id, "stop", ""),
            Command::CleanPrintError => json!({
                "print": {
                    "sequence_id": sequence_id,
                    "command": "clean_print_error",
                    "subtask_id": "0",
                }
            }),
            Command::GcodeLine(line) => print_command(sequence_id, "gcode_line", line),
            Command::GcodeFile(path) => print_command(sequence_id, "gcode_file", path),
            Command::PrintSpeed(level) => {
                print_command(sequence_id, "print_speed", &level.level().to_string())
            }
            Command::AmsControl(action) => json!({
                "print": {
                    "sequence_id": sequence_id,
                    "command": "ams_control",
                    "param": action.as_str(),
                }
            }),
            Command::AmsChangeFilament {
                target,
                curr_temp,
                tar_temp,
            } => json!({
                "print": {
                    "sequence_id": sequence_id,
                    "command": "ams_change_filament",
                    "target": target,
                    "curr_temp": curr_temp,
                    "tar_temp": tar_temp,
                }
            }),
            Command::AmsUserSetting {
                ams_id,
                startup_read,
                tray_read,
            } => json!({
                "print": {
                    "sequence_id": sequence_id,
                    "command": "ams_user_setting",
                    "ams_id": ams_id,
                    "startup_read_option": startup_read,
                    "tray_read_option": tray_read,
                }
            }),
            Command::AmsFilamentSetting(s) => json!({
                "print": {
                    "sequence_id": sequence_id,
                    "command": "ams_filament_setting",
                    "ams_id": s.ams_id,
                    "tray_id": s.tray_id,
                    "tray_info_idx": s.tray_info_idx,
                    "tray_color": s.tray_color,
                    "nozzle_temp_min": s.nozzle_temp_min,
                    "nozzle_temp_max": s.nozzle_temp_max,
                    "tray_type": s.tray_type,
                }
            }),
            Command::ProjectFile(p) => json!({
                "print": {
                    "sequence_id": sequence_id,
                    "command": "project_file",
                    "param": format!("Metadata/plate_{}.gcode", p.plate),
                    "url": p.url,
                    "subtask_name": p.subtask_name,
                    "md5": p.md5,
                    "bed_type": p.bed_type,
                    "timelapse": p.timelapse,
                    "flow_cali": p.flow_cali,
                    "bed_leveling": p.bed_leveling,
                    "vibration_cali": p.vibration_cali,
                    "layer_inspect": p.layer_inspect,
                    "use_ams": p.use_ams,
                    "ams_mapping": p.ams_mapping,
                    "project_id": "0",
                    "profile_id": "0",
                    "task_id": "0",
                    "subtask_id": "0",
                }
            }),
            Command::Calibration {
                bed_level,
                vibration,
                motor_noise,
            } => {
                let option = i64::from(*bed_level) * 2
                    + i64::from(*vibration) * 4
                    + i64::from(*motor_noise) * 8;
                json!({
                    "print": { "sequence_id": sequence_id, "command": "calibration", "option": option }
                })
            }
            Command::Led { node, on } => json!({
                "system": {
                    "sequence_id": sequence_id,
                    "command": "ledctrl",
                    "led_node": node.as_str(),
                    "led_mode": if *on { "on" } else { "off" },
                    "led_on_time": 500,
                    "led_off_time": 500,
                    "loop_times": 0,
                    "interval_time": 0,
                }
            }),
            Command::Reboot => json!({
                "system": { "sequence_id": sequence_id, "command": "reboot" }
            }),
            Command::IpcamTimelapse(control) => json!({
                "camera": {
                    "sequence_id": sequence_id,
                    "command": "ipcam_timelapse",
                    "control": control.as_str(),
                }
            }),
        }
    }
}

/// Build a `print.<command>` envelope carrying a `param` field.
fn print_command(sequence_id: &str, command: &str, param: &str) -> Value {
    json!({
        "print": { "sequence_id": sequence_id, "command": command, "param": param }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn sequence_ids_are_monotonic_strings_from_zero() {
        let mut ids = SequenceIds::new();
        assert_eq!(ids.next_id(), "0");
        assert_eq!(ids.next_id(), "1");
        assert_eq!(ids.next_id(), "2");
    }

    #[test]
    fn categories_match_the_envelope_key() {
        assert_eq!(Command::PushAll.category(), "pushing");
        assert_eq!(Command::Pause.category(), "print");
        assert_eq!(Command::GcodeLine("G28".into()).category(), "print");
        assert_eq!(Command::GcodeFile("/x".into()).category(), "print");
        assert_eq!(
            Command::ProjectFile(ProjectFile::new("u", 1, "n")).category(),
            "print"
        );
        assert_eq!(
            Command::Led {
                node: LedNode::ChamberLight,
                on: true
            }
            .category(),
            "system"
        );
    }

    #[test]
    fn calibration_option_is_a_bitmask() {
        let v = Command::Calibration {
            bed_level: true,
            vibration: true,
            motor_noise: false,
        }
        .to_payload("1");
        assert_eq!(v["print"]["command"], "calibration");
        assert_eq!(v["print"]["option"], 6); // 2 (bed) | 4 (vibration)
        assert_eq!(
            Command::Calibration {
                bed_level: false,
                vibration: false,
                motor_noise: true,
            }
            .to_payload("1")["print"]["option"],
            8
        );
    }

    #[test]
    fn clean_print_error_payload() {
        let v = Command::CleanPrintError.to_payload("3");
        assert_eq!(v["print"]["command"], "clean_print_error");
        assert_eq!(v["print"]["sequence_id"], "3");
        assert_eq!(v["print"]["subtask_id"], "0");
        assert_eq!(Command::CleanPrintError.category(), "print");
    }

    #[test]
    fn gcode_file_payload() {
        assert_eq!(
            Command::GcodeFile("/cache/foo.gcode".into()).to_payload("2"),
            json!({ "print": { "sequence_id": "2", "command": "gcode_file", "param": "/cache/foo.gcode" } })
        );
    }

    #[test]
    fn project_file_payload_has_plate_and_lan_ids() {
        let pf = ProjectFile::new("ftp:///cache/x.gcode.3mf", 2, "x job");
        let v = Command::ProjectFile(pf).to_payload("3");
        let p = &v["print"];
        assert_eq!(p["command"], "project_file");
        assert_eq!(p["sequence_id"], "3");
        assert_eq!(p["param"], "Metadata/plate_2.gcode");
        assert_eq!(p["url"], "ftp:///cache/x.gcode.3mf");
        assert_eq!(p["subtask_name"], "x job");
        assert_eq!(p["use_ams"], false);
        assert_eq!(p["task_id"], "0"); // LAN SD print uses "0" ids
        assert!(p["ams_mapping"].is_array());
    }

    #[test]
    fn get_version_is_an_info_read() {
        assert_eq!(Command::GetVersion.category(), "info");
        assert_eq!(
            Command::GetVersion.to_payload("1"),
            json!({ "info": { "sequence_id": "1", "command": "get_version" } })
        );
    }

    #[test]
    fn pushall_payload() {
        assert_eq!(
            Command::PushAll.to_payload("0"),
            json!({ "pushing": { "sequence_id": "0", "command": "pushall" } })
        );
    }

    #[test]
    fn pause_resume_stop_payloads() {
        assert_eq!(
            Command::Pause.to_payload("3"),
            json!({ "print": { "sequence_id": "3", "command": "pause", "param": "" } })
        );
        assert_eq!(
            Command::Resume.to_payload("4"),
            json!({ "print": { "sequence_id": "4", "command": "resume", "param": "" } })
        );
        assert_eq!(
            Command::Stop.to_payload("5"),
            json!({ "print": { "sequence_id": "5", "command": "stop", "param": "" } })
        );
    }

    #[test]
    fn gcode_line_payload_carries_the_line_in_param() {
        assert_eq!(
            Command::GcodeLine("M104 S210".to_string()).to_payload("7"),
            json!({ "print": { "sequence_id": "7", "command": "gcode_line", "param": "M104 S210" } })
        );
    }

    #[test]
    fn ledctrl_on_and_off_payloads_carry_the_node() {
        let on = Command::Led {
            node: LedNode::ChamberLight,
            on: true,
        }
        .to_payload("8");
        assert_eq!(on["system"]["command"], "ledctrl");
        assert_eq!(on["system"]["led_node"], "chamber_light");
        assert_eq!(on["system"]["led_mode"], "on");
        assert_eq!(on["system"]["sequence_id"], "8");

        let off = Command::Led {
            node: LedNode::ChamberLight,
            on: false,
        }
        .to_payload("9");
        assert_eq!(off["system"]["led_mode"], "off");

        // work_light targets a different node (same envelope).
        let work = Command::Led {
            node: LedNode::WorkLight,
            on: true,
        }
        .to_payload("1");
        assert_eq!(work["system"]["led_node"], "work_light");
    }

    #[test]
    fn print_speed_renders_the_level_as_a_print_param() {
        let v = Command::PrintSpeed(SpeedLevel::Sport).to_payload("6");
        assert_eq!(
            v,
            json!({ "print": { "sequence_id": "6", "command": "print_speed", "param": "3" } })
        );
        assert_eq!(Command::PrintSpeed(SpeedLevel::Silent).category(), "print");
    }

    #[test]
    fn speed_level_maps_to_and_from_its_number() {
        for (lvl, n) in [
            (SpeedLevel::Silent, 1),
            (SpeedLevel::Standard, 2),
            (SpeedLevel::Sport, 3),
            (SpeedLevel::Ludicrous, 4),
        ] {
            assert_eq!(lvl.level(), n);
            assert_eq!(SpeedLevel::from_level(n), Some(lvl));
        }
        assert_eq!(SpeedLevel::from_level(0), None);
        assert_eq!(SpeedLevel::from_level(5), None);
    }

    #[test]
    fn ipcam_timelapse_is_a_camera_command() {
        assert_eq!(
            Command::IpcamTimelapse(TimelapseControl::Enable).category(),
            "camera"
        );
        let on = Command::IpcamTimelapse(TimelapseControl::Enable).to_payload("4");
        assert_eq!(on["camera"]["command"], "ipcam_timelapse");
        assert_eq!(on["camera"]["control"], "enable");
        assert_eq!(on["camera"]["sequence_id"], "4");
        let off = Command::IpcamTimelapse(TimelapseControl::Disable).to_payload("5");
        assert_eq!(off["camera"]["control"], "disable");
    }

    #[test]
    fn ams_control_payload_matches_spec() {
        let v = Command::AmsControl(AmsControl::Resume).to_payload("1");
        assert_eq!(
            v,
            json!({ "print": { "sequence_id": "1", "command": "ams_control", "param": "resume" } })
        );
        assert_eq!(
            Command::AmsControl(AmsControl::Reset).to_payload("1")["print"]["param"],
            "reset"
        );
        assert_eq!(Command::AmsControl(AmsControl::Pause).category(), "print");
    }

    #[test]
    fn ams_change_filament_payload_matches_spec() {
        let v = Command::AmsChangeFilament {
            target: 2,
            curr_temp: 220,
            tar_temp: 240,
        }
        .to_payload("1");
        let p = &v["print"];
        assert_eq!(p["command"], "ams_change_filament");
        assert_eq!(p["target"], 2);
        assert_eq!(p["curr_temp"], 220);
        assert_eq!(p["tar_temp"], 240);
    }

    #[test]
    fn ams_user_setting_payload_matches_spec() {
        let v = Command::AmsUserSetting {
            ams_id: 0,
            startup_read: true,
            tray_read: false,
        }
        .to_payload("1");
        let p = &v["print"];
        assert_eq!(p["command"], "ams_user_setting");
        assert_eq!(p["ams_id"], 0);
        assert_eq!(p["startup_read_option"], true);
        assert_eq!(p["tray_read_option"], false);
    }

    #[test]
    fn ams_filament_setting_payload_matches_spec() {
        let v = Command::AmsFilamentSetting(Box::new(AmsFilamentSetting {
            ams_id: 0,
            tray_id: 1,
            tray_info_idx: "GFA00".to_string(),
            tray_color: "00112233".to_string(),
            nozzle_temp_min: 190,
            nozzle_temp_max: 230,
            tray_type: "PLA".to_string(),
        }))
        .to_payload("1");
        let p = &v["print"];
        assert_eq!(p["command"], "ams_filament_setting");
        assert_eq!(p["ams_id"], 0);
        assert_eq!(p["tray_id"], 1);
        assert_eq!(p["tray_info_idx"], "GFA00");
        assert_eq!(p["tray_color"], "00112233");
        assert_eq!(p["nozzle_temp_min"], 190);
        assert_eq!(p["nozzle_temp_max"], 230);
        assert_eq!(p["tray_type"], "PLA");
    }

    #[test]
    fn reboot_is_a_system_command() {
        assert_eq!(Command::Reboot.category(), "system");
        assert_eq!(
            Command::Reboot.to_payload("3"),
            json!({ "system": { "sequence_id": "3", "command": "reboot" } })
        );
    }

    #[test]
    fn sequence_id_is_serialised_as_a_string_not_a_number() {
        let payload = Command::PushAll.to_payload("42");
        assert!(payload["pushing"]["sequence_id"].is_string());
    }

    #[test]
    fn rendering_does_not_consume_or_mutate_the_command() {
        let cmd = Command::GcodeLine("G28".to_string());
        let _ = cmd.to_payload("0");
        // Still usable / unchanged afterwards.
        assert_eq!(cmd, Command::GcodeLine("G28".to_string()));
    }
}