rgb-sequencer 0.2.1

A no_std-compatible Rust library for controlling RGB LEDs through timed color sequences on embedded systems
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
//! RGB LED sequencer with state management.

use crate::BLACK;
use crate::command::SequencerAction;
use crate::sequence::RgbSequence;
use crate::time::{TimeDuration, TimeInstant, TimeSource};
use palette::Srgb;

/// Trait for abstracting RGB LED hardware.
pub trait RgbLed {
    /// Sets LED to specified color.
    ///
    /// Color components are in 0.0-1.0 range. Convert to your hardware's native format
    /// (PWM duty cycles, 8-bit values, etc.) in your implementation.
    fn set_color(&mut self, color: Srgb);
}

/// RGB sequencer state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SequencerState {
    /// No sequence loaded.
    Idle,
    /// Sequence loaded.
    Loaded,
    /// Sequence running.
    Running,
    /// Sequence paused.
    Paused,
    /// Sequence complete.
    Complete,
}

/// Timing information returned by service operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ServiceTiming<D> {
    /// Continuous animation - service again at your target frame rate (e.g., 16-33ms for 30-60 FPS).
    Continuous,
    /// Static hold - can delay this duration before next service call.
    Delay(D),
    /// Sequence complete - no further servicing needed.
    Complete,
}

/// Current playback position within a sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Position {
    /// Current step index (0-based).
    pub step_index: usize,
    /// Current loop number (0-based).
    pub loop_number: u32,
}

/// Errors that can occur during sequencer operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SequencerError {
    /// Invalid state.
    InvalidState {
        /// Expected state description.
        expected: &'static str,
        /// Actual current state.
        actual: SequencerState,
    },
    /// No sequence loaded.
    NoSequenceLoaded,
}

impl core::fmt::Display for SequencerError {
    /// Formats the error for display.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            SequencerError::InvalidState { expected, actual } => {
                write!(
                    f,
                    "invalid state: expected {}, but sequencer is in {:?}",
                    expected, actual
                )
            }
            SequencerError::NoSequenceLoaded => {
                write!(f, "no sequence loaded")
            }
        }
    }
}

/// Controls a single RGB LED through sequences.
pub struct RgbSequencer<'t, I: TimeInstant, L: RgbLed, T: TimeSource<I>, const N: usize> {
    led: L,
    time_source: &'t T,
    state: SequencerState,
    sequence: Option<RgbSequence<I::Duration, N>>,
    start_time: Option<I>,
    pause_start_time: Option<I>,
    current_color: Srgb,
    color_epsilon: f32,
    brightness: f32,
}

/// Default epsilon for floating-point color comparisons.
pub const DEFAULT_COLOR_EPSILON: f32 = 0.001;

/// Returns true if two colors are approximately equal within the given epsilon.
#[inline]
fn colors_approximately_equal(a: Srgb, b: Srgb, epsilon: f32) -> bool {
    (a.red - b.red).abs() < epsilon
        && (a.green - b.green).abs() < epsilon
        && (a.blue - b.blue).abs() < epsilon
}

impl<'t, I: TimeInstant, L: RgbLed, T: TimeSource<I>, const N: usize> RgbSequencer<'t, I, L, T, N> {
    /// Creates sequencer with LED off and default color epsilon.
    pub fn new(mut led: L, time_source: &'t T) -> Self {
        led.set_color(BLACK);

        Self {
            led,
            time_source,
            state: SequencerState::Idle,
            sequence: None,
            start_time: None,
            pause_start_time: None,
            current_color: BLACK,
            color_epsilon: DEFAULT_COLOR_EPSILON,
            brightness: 1.0,
        }
    }

    /// Creates sequencer with custom color epsilon threshold.
    pub fn with_epsilon(mut led: L, time_source: &'t T, epsilon: f32) -> Self {
        led.set_color(BLACK);

        Self {
            led,
            time_source,
            state: SequencerState::Idle,
            sequence: None,
            start_time: None,
            pause_start_time: None,
            current_color: BLACK,
            color_epsilon: epsilon,
            brightness: 1.0,
        }
    }

    /// Dispatches action to appropriate method.
    pub fn handle_action(
        &mut self,
        action: SequencerAction<I::Duration, N>,
    ) -> Result<(), SequencerError> {
        match action {
            SequencerAction::Load(sequence) => {
                self.load(sequence);
                Ok(())
            }
            SequencerAction::Start => self.start(),
            SequencerAction::Stop => self.stop(),
            SequencerAction::Pause => self.pause(),
            SequencerAction::Resume => self.resume(),
            SequencerAction::Restart => self.restart(),
            SequencerAction::Clear => {
                self.clear();
                Ok(())
            }
            SequencerAction::SetBrightness(brightness) => {
                self.set_brightness(brightness);
                Ok(())
            }
        }
    }

    /// Loads a sequence.
    pub fn load(&mut self, sequence: RgbSequence<I::Duration, N>) {
        self.sequence = Some(sequence);
        self.start_time = None;
        self.pause_start_time = None;
        self.state = SequencerState::Loaded;
    }

    /// Starts sequence playback.
    ///
    /// Transitions from `Loaded` to `Running` state.
    pub fn start(&mut self) -> Result<(), SequencerError> {
        if self.state != SequencerState::Loaded {
            return Err(SequencerError::InvalidState {
                expected: "Loaded",
                actual: self.state,
            });
        }

        if self.sequence.is_none() {
            return Err(SequencerError::NoSequenceLoaded);
        }

        self.start_time = Some(self.time_source.now());
        self.state = SequencerState::Running;
        Ok(())
    }

    /// Loads and immediately starts a sequence.
    ///
    /// Convenience method that combines `load()` and `start()`.
    pub fn load_and_start(
        &mut self,
        sequence: RgbSequence<I::Duration, N>,
    ) -> Result<(), SequencerError> {
        self.load(sequence);
        self.start()
    }

    /// Restarts sequence from beginning.
    ///
    /// Resets the start time and transitions to `Running` state.
    pub fn restart(&mut self) -> Result<(), SequencerError> {
        match self.state {
            SequencerState::Running | SequencerState::Paused | SequencerState::Complete => {
                if self.sequence.is_none() {
                    return Err(SequencerError::NoSequenceLoaded);
                }

                self.start_time = Some(self.time_source.now());
                self.pause_start_time = None;
                self.state = SequencerState::Running;
                Ok(())
            }
            _ => Err(SequencerError::InvalidState {
                expected: "Running, Paused, or Complete",
                actual: self.state,
            }),
        }
    }

    /// Services sequencer, updating LED if color changed.
    ///
    /// Must be called from `Running` state. Returns timing hint for next service call.
    #[inline]
    pub fn service(&mut self) -> Result<ServiceTiming<I::Duration>, SequencerError> {
        if self.state != SequencerState::Running {
            return Err(SequencerError::InvalidState {
                expected: "Running",
                actual: self.state,
            });
        }

        let sequence = self.sequence.as_ref().unwrap();
        let start_time = self.start_time.unwrap();
        let current_time = self.time_source.now();
        let elapsed = current_time.duration_since(start_time);

        // Evaluate color and timing
        let (new_color, next_service) = sequence.evaluate(elapsed);

        // Apply brightness to the evaluated color
        let dimmed_color = Srgb::new(
            new_color.red * self.brightness,
            new_color.green * self.brightness,
            new_color.blue * self.brightness,
        );

        // Update LED only if color changed (using epsilon for f32 comparison).
        // This avoids unnecessary hardware writes during static holds and prevents
        // spurious updates from floating-point rounding (<0.1% difference).
        // Particularly valuable for slow I2C/SPI LED drivers.
        if !colors_approximately_equal(dimmed_color, self.current_color, self.color_epsilon) {
            self.led.set_color(dimmed_color);
            self.current_color = dimmed_color;
        }

        // Convert timing hint to ServiceTiming
        match next_service {
            None => {
                self.state = SequencerState::Complete;
                Ok(ServiceTiming::Complete)
            }
            Some(duration) if duration == I::Duration::ZERO => Ok(ServiceTiming::Continuous),
            Some(duration) => Ok(ServiceTiming::Delay(duration)),
        }
    }

    /// Peeks at next timing hint without updating LED or advancing state.
    ///
    /// Returns `SequencerError::InvalidState` if not in `Running` state.
    #[inline]
    pub fn peek_next_timing(&self) -> Result<ServiceTiming<I::Duration>, SequencerError> {
        if self.state != SequencerState::Running {
            return Err(SequencerError::InvalidState {
                expected: "Running",
                actual: self.state,
            });
        }

        let sequence = self.sequence.as_ref().unwrap();
        let start_time = self.start_time.unwrap();
        let current_time = self.time_source.now();
        let elapsed = current_time.duration_since(start_time);

        // Evaluate timing without updating state
        let (_color, next_service) = sequence.evaluate(elapsed);

        // Convert timing hint to ServiceTiming
        match next_service {
            None => Ok(ServiceTiming::Complete),
            Some(duration) if duration == I::Duration::ZERO => Ok(ServiceTiming::Continuous),
            Some(duration) => Ok(ServiceTiming::Delay(duration)),
        }
    }

    /// Stops sequence and turns LED off.
    pub fn stop(&mut self) -> Result<(), SequencerError> {
        match self.state {
            SequencerState::Running | SequencerState::Paused | SequencerState::Complete => {
                self.start_time = None;
                self.pause_start_time = None;
                self.state = SequencerState::Loaded;

                self.led.set_color(BLACK);
                self.current_color = BLACK;

                Ok(())
            }
            _ => Err(SequencerError::InvalidState {
                expected: "Running, Paused, or Complete",
                actual: self.state,
            }),
        }
    }

    /// Pauses sequence at current color.
    ///
    /// Timing is compensated on resume - sequence continues from same position.
    pub fn pause(&mut self) -> Result<(), SequencerError> {
        if self.state != SequencerState::Running {
            return Err(SequencerError::InvalidState {
                expected: "Running",
                actual: self.state,
            });
        }

        self.pause_start_time = Some(self.time_source.now());
        self.state = SequencerState::Paused;
        Ok(())
    }

    /// Resumes paused sequence.
    ///
    /// Automatically compensates for the paused duration to maintain timing continuity.
    pub fn resume(&mut self) -> Result<(), SequencerError> {
        if self.state != SequencerState::Paused {
            return Err(SequencerError::InvalidState {
                expected: "Paused",
                actual: self.state,
            });
        }

        let pause_start = self.pause_start_time.unwrap();
        let current_time = self.time_source.now();
        let pause_duration = current_time.duration_since(pause_start);

        // Add the pause duration to start time to compensate for the time spent paused.
        // This keeps the sequence at the same position it was at when paused.
        // If checked_add returns None (overflow, e.g., due to very long pause on 32-bit timers),
        // we fall back to the old start time. This causes the sequence to jump forward but
        // prevents a crash. This is a graceful degradation on timer overflow.
        let old_start = self.start_time.unwrap();
        self.start_time = Some(old_start.checked_add(pause_duration).unwrap_or(old_start));

        self.pause_start_time = None;
        self.state = SequencerState::Running;
        Ok(())
    }

    /// Clears sequence and turns LED off.
    pub fn clear(&mut self) {
        self.sequence = None;
        self.start_time = None;
        self.pause_start_time = None;
        self.state = SequencerState::Idle;

        self.led.set_color(BLACK);
        self.current_color = BLACK;
    }

    /// Returns current state.
    #[inline]
    pub fn state(&self) -> SequencerState {
        self.state
    }

    /// Returns current color.
    #[inline]
    pub fn current_color(&self) -> Srgb {
        self.current_color
    }

    /// Returns true if paused.
    #[inline]
    pub fn is_paused(&self) -> bool {
        self.state == SequencerState::Paused
    }

    /// Returns true if running.
    #[inline]
    pub fn is_running(&self) -> bool {
        self.state == SequencerState::Running
    }

    /// Returns current sequence reference.
    #[inline]
    pub fn current_sequence(&self) -> Option<&RgbSequence<I::Duration, N>> {
        self.sequence.as_ref()
    }

    /// Returns elapsed time since start.
    pub fn elapsed_time(&self) -> Option<I::Duration> {
        self.start_time.map(|start| {
            let now = self.time_source.now();
            now.duration_since(start)
        })
    }

    /// Returns the current color epsilon threshold.
    #[inline]
    pub fn color_epsilon(&self) -> f32 {
        self.color_epsilon
    }

    /// Sets the color epsilon threshold.
    ///
    /// Controls the sensitivity of color change detection.
    #[inline]
    pub fn set_color_epsilon(&mut self, epsilon: f32) {
        self.color_epsilon = epsilon;
    }

    /// Returns current brightness multiplier (0.0-1.0).
    #[inline]
    pub fn brightness(&self) -> f32 {
        self.brightness
    }

    /// Sets global brightness multiplier.
    #[inline]
    pub fn set_brightness(&mut self, brightness: f32) {
        self.brightness = brightness.clamp(0.0, 1.0);
    }

    /// Returns current playback position.
    ///
    /// When running, returns the current position. When paused, returns the frozen position
    /// where the sequence will resume from. Returns `None` if not running/paused or sequence
    /// is function-based.
    #[inline]
    pub fn current_position(&self) -> Option<Position> {
        match self.state {
            SequencerState::Running | SequencerState::Paused => {
                let sequence = self.sequence.as_ref()?;
                let start_time = self.start_time?;

                // Use pause_start_time for paused state to get frozen position,
                // otherwise use current time for running state
                let reference_time = if self.state == SequencerState::Paused {
                    self.pause_start_time?
                } else {
                    self.time_source.now()
                };

                let elapsed = reference_time.duration_since(start_time);

                let step_position = sequence.find_step_position(elapsed)?;
                Some(Position {
                    step_index: step_position.step_index,
                    loop_number: step_position.current_loop,
                })
            }
            _ => None,
        }
    }

    /// Consumes the sequencer and returns the LED.
    #[inline]
    pub fn into_led(self) -> L {
        self.led
    }

    /// Consumes the sequencer and returns the LED and current sequence.
    #[inline]
    pub fn into_parts(self) -> (L, Option<RgbSequence<I::Duration, N>>) {
        (self.led, self.sequence)
    }
}