rill-core 0.5.0-beta.4

Core foundation for the Rill ecosystem — traits, math, buffers, queues, time, macros
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
//! Signal and command types for queues.
//!
//! This module defines all command types that can be sent through queues
//! between Rill components. Each command type represents a specific
//! action or event in the system.
//!
//! ## Command hierarchy
//!
//! - `CommandEnum` — top-level enum wrapping all command variants
//! - `SetParameter` — parameter change for a signal graph node
//! - `AutomatonCommand` — automaton control
//! - `SensorCommand` — sensor control
//! - `ServoCommand` — servo control
//!
//! ## Example
//!
//! ```rust
//! use rill_core::queues::*;
//! use rill_core::traits::*;
//! #
//! // Create a command queue
//! let queue: CommandQueue<CommandEnum> = CommandQueue::new("signal-control", 1024);
//!
//! // Create identifiers
//! let node = NodeId(1);
//! let port = PortId::control_in(node, 0);
//! let param = ParameterId::new("gain").unwrap();
//!
//! // Somewhere in the world of automatons
//! let cmd = SetParameter::new(port, param, ParamValue::Float(0.5), SignalOrigin::Automaton("lfo".into()));
//! queue.send(CommandEnum::SetParameter(cmd)).unwrap();
//!
//! // Somewhere in the sound world
//! while let Ok(cmd_enum) = queue.try_recv() {
//!     if let CommandEnum::SetParameter(cmd) = cmd_enum {
//!         // apply_parameter(cmd); // function must be defined
//!     }
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use super::command::Command;
use crate::traits::{ParamValue, ParameterId, PortId};
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};

//==============================================================================
// SignalOrigin — signal source
//==============================================================================

/// Origin of a signal or command.
///
/// Used for tracking command provenance, feedback-loop prevention,
/// and telemetry attribution.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SignalOrigin {
    /// Command from an automaton (LFO, envelope, sequencer).
    Automaton(String),
    /// Command from a sensor (physical input device).
    Sensor(String),
    /// Command from a servo (physical output device).
    Servo(String),
    /// Command from an external source (OSC, MIDI, etc.).
    External(String),
    /// Manual user interaction (UI slider, button, etc.).
    Manual,
    /// Command from a script.
    Script,
}

impl SignalOrigin {
    /// Return the human-readable name of this source.
    pub fn name(&self) -> &str {
        match self {
            SignalOrigin::Automaton(name) => name,
            SignalOrigin::Sensor(name) => name,
            SignalOrigin::Servo(name) => name,
            SignalOrigin::External(name) => name,
            SignalOrigin::Manual => "manual",
            SignalOrigin::Script => "script",
        }
    }

    /// Return the type category of this source (e.g. "automaton", "sensor").
    pub fn kind(&self) -> &'static str {
        match self {
            SignalOrigin::Automaton(_) => "automaton",
            SignalOrigin::Sensor(_) => "sensor",
            SignalOrigin::Servo(_) => "servo",
            SignalOrigin::External(_) => "external",
            SignalOrigin::Manual => "manual",
            SignalOrigin::Script => "script",
        }
    }
}

impl fmt::Display for SignalOrigin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SignalOrigin::Automaton(name) => write!(f, "⚙️ {}", name),
            SignalOrigin::Sensor(name) => write!(f, "👁️ {}", name),
            SignalOrigin::Servo(name) => write!(f, "🦾 {}", name),
            SignalOrigin::External(name) => write!(f, "🌍 {}", name),
            SignalOrigin::Manual => write!(f, "👤 manual"),
            SignalOrigin::Script => write!(f, "📜 script"),
        }
    }
}

// ===== SetParameter =====

/// Command to change a parameter value on a signal graph node.
#[derive(Debug, Clone)]
pub struct SetParameter {
    /// Target port.
    pub port: PortId,
    /// Target parameter identifier.
    pub parameter: ParameterId,
    /// New parameter value.
    pub value: ParamValue,
    /// Origin of this command.
    pub source: SignalOrigin,
    /// Unix timestamp (microseconds).
    pub timestamp: u64,
}

impl SetParameter {
    /// Create a new parameter-change command with the current timestamp.
    pub fn new(
        port: PortId,
        parameter: ParameterId,
        value: ParamValue,
        source: SignalOrigin,
    ) -> Self {
        Self {
            port,
            parameter,
            value,
            source,
            timestamp: Self::now(),
        }
    }

    /// Create a new parameter-change command with an explicit timestamp.
    pub fn with_timestamp(
        port: PortId,
        parameter: ParameterId,
        value: ParamValue,
        source: SignalOrigin,
        timestamp: u64,
    ) -> Self {
        Self {
            port,
            parameter,
            value,
            source,
            timestamp,
        }
    }

    /// Return the current Unix time in microseconds.
    pub fn now() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_micros() as u64
    }
}

impl PartialEq for SetParameter {
    fn eq(&self, other: &Self) -> bool {
        self.port == other.port
            && self.parameter == other.parameter
            && self.value == other.value
            && self.source == other.source
    }
}

impl fmt::Display for SetParameter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{}] {}{}::{} = {:?}",
            self.timestamp, self.source, self.port, self.parameter, self.value
        )
    }
}

// Implement the Command trait for SetParameter
impl Command for SetParameter {}

// ===== AutomatonCommand =====

/// Commands for controlling automata (LFOs, envelopes, sequencers).
#[derive(Debug, Clone)]
pub enum AutomatonCommand {
    /// Enable or disable an automaton by ID.
    SetEnabled {
        /// Automaton identifier.
        id: String,
        /// Whether the automaton should be enabled.
        enabled: bool,
    },
    /// Set a named parameter on an automaton.
    SetParameter {
        /// Automaton identifier.
        id: String,
        /// Parameter name.
        name: String,
        /// Parameter value.
        value: f32,
    },
    /// Reset an automaton to its initial state.
    Reset {
        /// Automaton identifier.
        id: String,
    },
    /// Connect an automaton output to another automaton input.
    Connect {
        /// Source automaton identifier.
        from: String,
        /// Destination automaton identifier.
        to: String,
        /// Connection gain.
        gain: f32,
    },
    /// Disconnect two automata.
    Disconnect {
        /// Source automaton identifier.
        from: String,
        /// Destination automaton identifier.
        to: String,
    },
    /// Create a new automaton instance.
    Create {
        /// Automaton type (e.g. "lfo", "envelope").
        kind: String,
        /// New automaton identifier.
        id: String,
        /// Initial parameter values.
        params: Vec<(String, f32)>,
    },
    /// Destroy an automaton by ID.
    Destroy {
        /// Automaton identifier to remove.
        id: String,
    },
}

impl AutomatonCommand {
    /// Return the target automaton ID, if applicable.
    pub fn automaton_id(&self) -> Option<&str> {
        match self {
            AutomatonCommand::SetEnabled { id, .. } => Some(id),
            AutomatonCommand::SetParameter { id, .. } => Some(id),
            AutomatonCommand::Reset { id } => Some(id),
            AutomatonCommand::Connect { from, to: _to, .. } => Some(from),
            AutomatonCommand::Disconnect { from, to: _to } => Some(from),
            AutomatonCommand::Create { id, .. } => Some(id),
            AutomatonCommand::Destroy { id } => Some(id),
        }
    }
}

impl fmt::Display for AutomatonCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AutomatonCommand::SetEnabled { id, enabled } => {
                write!(f, "Automaton[{}] set_enabled({})", id, enabled)
            }
            AutomatonCommand::SetParameter { id, name, value } => {
                write!(f, "Automaton[{}] set_param({}={:.2})", id, name, value)
            }
            AutomatonCommand::Reset { id } => {
                write!(f, "Automaton[{}] reset()", id)
            }
            AutomatonCommand::Connect { from, to, gain } => {
                write!(f, "Automaton connect {}{} gain={:.2}", from, to, gain)
            }
            AutomatonCommand::Disconnect { from, to } => {
                write!(f, "Automaton disconnect {}{}", from, to)
            }
            AutomatonCommand::Create { kind, id, params } => {
                write!(
                    f,
                    "Automaton create {} as {} with {} params",
                    kind,
                    id,
                    params.len()
                )
            }
            AutomatonCommand::Destroy { id } => {
                write!(f, "Automaton destroy {}", id)
            }
        }
    }
}

impl Command for AutomatonCommand {}

// ===== SensorCommand =====

/// Type of sensor calibration to perform.
#[derive(Debug, Clone)]
pub enum CalibrationKind {
    /// Automatically determine min/max from signal range.
    Auto,
    /// Set the current sensor reading as the minimum value.
    SetCurrentAsMin,
    /// Set the current sensor reading as the maximum value.
    SetCurrentAsMax,
    /// Reset calibration to factory defaults.
    Reset,
}

impl fmt::Display for CalibrationKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CalibrationKind::Auto => write!(f, "auto"),
            CalibrationKind::SetCurrentAsMin => write!(f, "set_min"),
            CalibrationKind::SetCurrentAsMax => write!(f, "set_max"),
            CalibrationKind::Reset => write!(f, "reset"),
        }
    }
}

/// Commands for controlling sensors (physical input devices).
#[derive(Debug, Clone)]
pub enum SensorCommand {
    /// Start listening to a sensor data source.
    StartListening {
        /// Sensor identifier.
        id: String,
        /// Data source to listen to.
        source: String,
    },
    /// Stop listening to a sensor.
    StopListening {
        /// Sensor identifier.
        id: String,
    },
    /// Set sensor sensitivity.
    SetSensitivity {
        /// Sensor identifier.
        id: String,
        /// Sensitivity value.
        value: f32,
    },
    /// Calibrate a sensor.
    Calibrate {
        /// Sensor identifier.
        id: String,
        /// Calibration type.
        kind: CalibrationKind,
    },
    /// Enable or disable a sensor.
    SetEnabled {
        /// Sensor identifier.
        id: String,
        /// Whether the sensor should be enabled.
        enabled: bool,
    },
}

impl SensorCommand {
    /// Return the target sensor ID.
    pub fn sensor_id(&self) -> &str {
        match self {
            SensorCommand::StartListening { id, .. } => id,
            SensorCommand::StopListening { id } => id,
            SensorCommand::SetSensitivity { id, .. } => id,
            SensorCommand::Calibrate { id, .. } => id,
            SensorCommand::SetEnabled { id, .. } => id,
        }
    }
}

impl fmt::Display for SensorCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SensorCommand::StartListening { id, source } => {
                write!(f, "Sensor[{}] start listening to {}", id, source)
            }
            SensorCommand::StopListening { id } => {
                write!(f, "Sensor[{}] stop listening", id)
            }
            SensorCommand::SetSensitivity { id, value } => {
                write!(f, "Sensor[{}] set sensitivity to {:.2}", id, value)
            }
            SensorCommand::Calibrate { id, kind } => {
                write!(f, "Sensor[{}] calibrate {}", id, kind)
            }
            SensorCommand::SetEnabled { id, enabled } => {
                write!(f, "Sensor[{}] set enabled({})", id, enabled)
            }
        }
    }
}

impl Command for SensorCommand {}

// ===== ServoCommand =====

/// Mapping function type for servo output value transformation.
#[derive(Debug, Clone)]
pub enum MappingType {
    /// Linear mapping (identity).
    Linear,
    /// Exponential mapping.
    Exponential,
    /// Logarithmic mapping.
    Logarithmic,
    /// Inverted (reverse) mapping.
    Inverted,
    /// Custom named mapping function.
    Custom(String),
}

impl fmt::Display for MappingType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MappingType::Linear => write!(f, "linear"),
            MappingType::Exponential => write!(f, "exponential"),
            MappingType::Logarithmic => write!(f, "logarithmic"),
            MappingType::Inverted => write!(f, "inverted"),
            MappingType::Custom(s) => write!(f, "custom({})", s),
        }
    }
}

/// Commands for controlling servos (physical output devices).
#[derive(Debug, Clone)]
pub enum ServoCommand {
    /// Bind a servo to follow an automaton output.
    BindToAutomaton {
        /// Servo identifier.
        servo_id: String,
        /// Automaton identifier to bind to.
        automaton_id: String,
    },
    /// Bind a servo directly to a signal graph parameter.
    BindToParameter {
        /// Servo identifier.
        servo_id: String,
        /// Target port.
        port: PortId,
        /// Target parameter.
        parameter: ParameterId,
    },
    /// Unbind a servo from all sources.
    Unbind {
        /// Servo identifier.
        servo_id: String,
    },
    /// Set the output range of a servo.
    SetRange {
        /// Servo identifier.
        servo_id: String,
        /// Minimum output value.
        min: f32,
        /// Maximum output value.
        max: f32,
    },
    /// Set the value mapping function for a servo.
    SetMapping {
        /// Servo identifier.
        servo_id: String,
        /// Mapping type.
        mapping: MappingType,
    },
    /// Enable or disable a servo.
    SetEnabled {
        /// Servo identifier.
        servo_id: String,
        /// Whether the servo should be enabled.
        enabled: bool,
    },
}

impl ServoCommand {
    /// Return the target servo ID.
    pub fn servo_id(&self) -> &str {
        match self {
            ServoCommand::BindToAutomaton { servo_id, .. } => servo_id,
            ServoCommand::BindToParameter { servo_id, .. } => servo_id,
            ServoCommand::Unbind { servo_id } => servo_id,
            ServoCommand::SetRange { servo_id, .. } => servo_id,
            ServoCommand::SetMapping { servo_id, .. } => servo_id,
            ServoCommand::SetEnabled { servo_id, .. } => servo_id,
        }
    }
}

impl fmt::Display for ServoCommand {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ServoCommand::BindToAutomaton {
                servo_id,
                automaton_id,
            } => {
                write!(f, "Servo[{}] bind to automaton {}", servo_id, automaton_id)
            }
            ServoCommand::BindToParameter {
                servo_id,
                port,
                parameter,
            } => {
                write!(f, "Servo[{}] bind to {}::{}", servo_id, port, parameter)
            }
            ServoCommand::Unbind { servo_id } => {
                write!(f, "Servo[{}] unbind", servo_id)
            }
            ServoCommand::SetRange { servo_id, min, max } => {
                write!(f, "Servo[{}] set range [{}, {}]", servo_id, min, max)
            }
            ServoCommand::SetMapping { servo_id, mapping } => {
                write!(f, "Servo[{}] set mapping {}", servo_id, mapping)
            }
            ServoCommand::SetEnabled { servo_id, enabled } => {
                write!(f, "Servo[{}] set enabled({})", servo_id, enabled)
            }
        }
    }
}

impl Command for ServoCommand {}

// ===== CommandType (formerly Command) — common command type =====

/// Runtime command type identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CommandType {
    /// Parameter change command.
    SetParameter,
    /// Automaton control command.
    Automaton,
    /// Sensor control command.
    Sensor,
    /// Servo control command.
    Servo,
    /// System command.
    System,
}

impl fmt::Display for CommandType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CommandType::SetParameter => write!(f, "SetParameter"),
            CommandType::Automaton => write!(f, "Automaton"),
            CommandType::Sensor => write!(f, "Sensor"),
            CommandType::Servo => write!(f, "Servo"),
            CommandType::System => write!(f, "System"),
        }
    }
}

/// Universal command enum combining all possible command types.
///
/// Useful when a single queue must transport multiple command types,
/// or when the command type is not known ahead of time.
#[derive(Debug, Clone)]
pub enum CommandEnum {
    /// Parameter change command.
    SetParameter(SetParameter),
    /// Automaton control command.
    Automaton(AutomatonCommand),
    /// Sensor control command.
    Sensor(SensorCommand),
    /// Servo control command.
    Servo(ServoCommand),
    /// System-level command with opaque payload.
    System {
        /// System command kind.
        kind: String,
        /// Opaque command data.
        data: Vec<u8>,
    },
}

impl CommandEnum {
    /// Return the runtime type tag of this command.
    pub fn command_type(&self) -> CommandType {
        match self {
            CommandEnum::SetParameter(_) => CommandType::SetParameter,
            CommandEnum::Automaton(_) => CommandType::Automaton,
            CommandEnum::Sensor(_) => CommandType::Sensor,
            CommandEnum::Servo(_) => CommandType::Servo,
            CommandEnum::System { .. } => CommandType::System,
        }
    }

    /// If this is a `SetParameter` command, return the target `NodeId`.
    pub fn target_node_id(&self) -> Option<crate::traits::NodeId> {
        match self {
            CommandEnum::SetParameter(cmd) => Some(cmd.port.node_id()),
            _ => None,
        }
    }

    /// Return the timestamp if the command carries one.
    pub fn timestamp(&self) -> Option<u64> {
        match self {
            CommandEnum::SetParameter(cmd) => Some(cmd.timestamp),
            _ => None,
        }
    }

    /// Try to downcast to `SetParameter`.
    pub fn as_set_parameter(&self) -> Option<&SetParameter> {
        match self {
            CommandEnum::SetParameter(cmd) => Some(cmd),
            _ => None,
        }
    }

    /// Try to downcast to `AutomatonCommand`.
    pub fn as_automaton(&self) -> Option<&AutomatonCommand> {
        match self {
            CommandEnum::Automaton(cmd) => Some(cmd),
            _ => None,
        }
    }

    /// Try to downcast to `SensorCommand`.
    pub fn as_sensor(&self) -> Option<&SensorCommand> {
        match self {
            CommandEnum::Sensor(cmd) => Some(cmd),
            _ => None,
        }
    }

    /// Try to downcast to `ServoCommand`.
    pub fn as_servo(&self) -> Option<&ServoCommand> {
        match self {
            CommandEnum::Servo(cmd) => Some(cmd),
            _ => None,
        }
    }
}

impl fmt::Display for CommandEnum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CommandEnum::SetParameter(cmd) => write!(f, "{}", cmd),
            CommandEnum::Automaton(cmd) => write!(f, "{}", cmd),
            CommandEnum::Sensor(cmd) => write!(f, "{}", cmd),
            CommandEnum::Servo(cmd) => write!(f, "{}", cmd),
            CommandEnum::System { kind, data } => {
                write!(f, "System[{}] ({} bytes)", kind, data.len())
            }
        }
    }
}

// Implement the Command trait for CommandEnum so it can be used in CommandQueue
impl Command for CommandEnum {}

// ===== Conversions =====

/// Marker trait for types that can be converted into a command.
pub trait ToCommand: Send + 'static {
    /// The command type this type converts into.
    type Command: Into<CommandEnum>;

    /// Convert self into a command.
    fn to_command(self) -> Self::Command;
}

/// Marker trait for types that can be constructed from a command.
pub trait FromCommand: Sized {
    /// The command type this type is constructed from.
    type Command: TryInto<Self> + Clone;

    /// Try to construct from a command.
    fn from_command(cmd: Self::Command) -> Option<Self>;
}

impl From<SetParameter> for CommandEnum {
    fn from(cmd: SetParameter) -> Self {
        CommandEnum::SetParameter(cmd)
    }
}

impl From<AutomatonCommand> for CommandEnum {
    fn from(cmd: AutomatonCommand) -> Self {
        CommandEnum::Automaton(cmd)
    }
}

impl From<SensorCommand> for CommandEnum {
    fn from(cmd: SensorCommand) -> Self {
        CommandEnum::Sensor(cmd)
    }
}

impl From<ServoCommand> for CommandEnum {
    fn from(cmd: ServoCommand) -> Self {
        CommandEnum::Servo(cmd)
    }
}

impl TryFrom<CommandEnum> for SetParameter {
    type Error = ();

    fn try_from(cmd: CommandEnum) -> Result<Self, Self::Error> {
        match cmd {
            CommandEnum::SetParameter(cmd) => Ok(cmd),
            _ => Err(()),
        }
    }
}

impl TryFrom<CommandEnum> for AutomatonCommand {
    type Error = ();

    fn try_from(cmd: CommandEnum) -> Result<Self, Self::Error> {
        match cmd {
            CommandEnum::Automaton(cmd) => Ok(cmd),
            _ => Err(()),
        }
    }
}

impl TryFrom<CommandEnum> for SensorCommand {
    type Error = ();

    fn try_from(cmd: CommandEnum) -> Result<Self, Self::Error> {
        match cmd {
            CommandEnum::Sensor(cmd) => Ok(cmd),
            _ => Err(()),
        }
    }
}

impl TryFrom<CommandEnum> for ServoCommand {
    type Error = ();

    fn try_from(cmd: CommandEnum) -> Result<Self, Self::Error> {
        match cmd {
            CommandEnum::Servo(cmd) => Ok(cmd),
            _ => Err(()),
        }
    }
}