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
//!
//! This engine is intended to provide behavior over time
//! for one or more RGB LEDs (though could also be useful
//! for any kind of color sequencing).
//!
//! In most cases:
//!
//! * Each LED will get a [`Sequence`] of some max length `N`.
//! * Each [`Sequence`] contains up to `N` [`Action`]s
//! * Each [`Action`] consists of:
//!   * A [`Context`], which contains information like the color,
//!       start time, and duration of an Action
//!   * A [behavior], which is what the LED will do over time
//!   * A [`LoopBehavior`], which describes whether the individual
//!       Action will repeat in some way
//! * The [`Sequence`] also contains a [`LoopBehavior`], which describes
//!       whether the ENTIRE SEQUENCE will repeat in some way
//!
//! A typical usage example would be to:
//!
//! 1. Create an array of [`Sequence`]s, one for each LED (see the [`Sequence::new_array()`] method)
//! 1. Use either the [`ActionBuilder`] or [`script!()`] macro
//!     to define each [`Action`] in each [`Sequence`]
//! 1. Periodically poll each [`Sequence`], using the resulting
//!     color to update the physical LED
//! 1. Modify or replace the [`Sequence`]s as necessary, for example
//!     at a regular interval, or in response to some event, such as
//!     a button press or received packet
//!
//! [`Sequence`]: crate::engine::Sequence
//! [`Sequence::new_array()`]: crate::engine::Sequence::new_array
//! [`Action`]: crate::engine::Action
//! [`Context`]: crate::engine::Context
//! [behavior]: crate::behaviors
//! [`script!()`]: crate::script
//! [`ActionBuilder`]: crate::engine::ActionBuilder
//! [`LoopBehavior`]: crate::engine::LoopBehavior

use core::cmp::min;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};

use crate::behaviors::{Cycler, FadeColor, SeekColor, StayColor};
use crate::LossyIntoF32;
use groundhog::RollingTimer;
use heapless::Vec;
use smart_leds::colors::BLACK;
use smart_leds::RGB8;

/// A sequence of [`Action`]s with maximum length N.
///
/// The total [`Sequence`] also has a [`LoopBehavior`]
/// that describes the looping behavior of the entire
/// sequence (e.g. play the sequence N times, once,
/// forever).
///
/// [`Action`]: Action
/// [`LoopBehavior`]: LoopBehavior)
/// [`Sequence`]: Sequence
#[derive(Clone)]
pub struct Sequence<R, const N: usize> {
    seq: Vec<Action<R>, N>,
    position: usize,
    behavior: LoopBehavior,
    never_run: bool,
}

impl<R, const N: usize> Sequence<R, N> {
    const INIT: Sequence<R, N> = Sequence::new();

    /// Create a new, empty sequence
    pub const fn new() -> Self {
        Self {
            seq: Vec::new(),
            position: 0,
            behavior: LoopBehavior::Nop,
            never_run: true,
        }
    }

    /// Create an array of new, empty sequences.
    ///
    /// This is often useful when creating an array for multiple
    /// LEDs. Alternatively, call [`Default::default()`] for the same effect.
    ///
    /// # Example
    ///
    /// Creating an array of [`Sequence`]s and setting each one to a script:
    ///
    /// ```rust
    /// # use choreographer::{script, engine::{ActionBuilder, Sequence, LoopBehavior}};
    /// # use groundhog::std_timer::Timer;
    /// # type MicroTimer = Timer<1_000_000>;
    /// let mut leds: [Sequence<MicroTimer, 8>; 16] = Sequence::new_array();
    /// for led in leds.iter_mut() {
    ///     led.set(&script!(
    ///         | action |  color | duration_ms | period_ms_f | phase_offset_ms | repeat |
    ///         |  solid |  BLACK |        1000 |         0.0 |               0 |   once |
    ///         |    sin |  WHITE |        2500 |      2500.0 |               0 |   once |
    ///         |  solid |  BLACK |        1000 |         0.0 |               0 |   once |
    ///     ), LoopBehavior::OneShot);
    ///
    /// }
    /// ```
    pub const fn new_array<const M: usize>() -> [Self; M] {
        [Self::INIT; M]
    }
}

impl<R, const N: usize> Default for Sequence<R, N>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<R, const N: usize> Sequence<R, N>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    /// Create a new, empty sequence
    pub fn empty() -> Self {
        Self {
            seq: Vec::new(),
            position: 0,
            behavior: LoopBehavior::OneShot,
            never_run: true,
        }
    }

    /// Clear the current set of actions, leaving the
    /// Sequence empty
    pub fn clear(&mut self) {
        self.seq.clear();
        self.position = 0;
    }

    /// Clear the current set of actions, and fill the sequence with
    /// the given new actions.
    ///
    /// If `actions` is larger than the capacity of `self`, remaining items
    /// will be ignored
    pub fn set(&mut self, actions: &[Action<R>], behavior: LoopBehavior) {
        let amt = min(N, actions.len());
        self.clear();

        self.never_run = true;

        self.seq.extend_from_slice(&actions[..amt]).ok();
        self.behavior = behavior;
    }

    /// Poll the currently active Action, potentially also moving
    /// to the next Action if necessary.
    ///
    /// When any Action is active, an RGB8 will be returned
    pub fn poll(&mut self) -> Option<RGB8> {
        if self.seq.is_empty() || (self.position >= self.seq.len()) {
            return None;
        }

        let behavior = &mut self.behavior;
        let seq = &mut self.seq;
        let position = &mut self.position;

        // If we are running this sequence for the first time,
        // re-initialize to ensure time is current
        if self.never_run {
            let ph = seq[*position].action.context.phase_offset_ms;
            let timer = R::default();
            seq[*position].reinit(timer.get_ticks(), ph, BLACK);
            self.never_run = false;
        }

        use LoopBehavior::*;
        match behavior {
            OneShot => seq[*position].poll().or_else(|| {
                let end = seq[*position].calc_end();
                let end_ph = seq[*position].calc_end_phase();
                let last_color = seq[*position].color;
                *position += 1;
                if *position < seq.len() {
                    seq[*position].reinit(end, end_ph, last_color);
                    seq[*position].poll()
                } else {
                    None
                }
            }),
            LoopForever => seq[*position].poll().or_else(|| {
                let end = seq[*position].calc_end();
                let end_ph = seq[*position].calc_end_phase();
                let last_color = seq[*position].color;
                *position += 1;

                if *position >= seq.len() {
                    *position = 0;
                }

                seq[*position].reinit(end, end_ph, last_color);
                seq[*position].poll()
            }),
            LoopN {
                ref mut current,
                cycles,
            } => seq[*position].poll().or_else(|| {
                let end = seq[*position].calc_end();
                let end_ph = seq[*position].calc_end_phase();
                let last_color = seq[*position].color;
                *position += 1;

                if *position >= seq.len() {
                    if *current < *cycles {
                        *position = 0;
                        *current += 1;
                        seq[*position].reinit(end, end_ph, last_color);
                        seq[*position].poll()
                    } else {
                        None
                    }
                } else {
                    seq[*position].reinit(end, end_ph, last_color);
                    seq[*position].poll()
                }
            }),
            Nop => None,
        }
    }
}

/// A single behavior step
///
/// An Action is a single describable step in a sequence
/// of events.
///
/// * Each [`Action`] consists of:
///   * A [`Context`], which contains information like the color,
///       start time, and duration of an Action
///   * A [behavior], which is what the LED will do over time
///   * A [`LoopBehavior`], which describes whether the individual
///       Action will repeat in some way
///
/// Actions are typically constructed through either the
/// [`ActionBuilder`] or [`script!()`] macro.
///
/// Actions are not usually interacted with directly, but rather
/// as part of a [`Sequence`].
///
/// [`Sequence`]: crate::engine::Sequence
/// [`Action`]: crate::engine::Action
/// [`Context`]: crate::engine::Context
/// [behavior]: crate::behaviors
/// [`script!()`]: crate::script
/// [`ActionBuilder`]: crate::engine::ActionBuilder
/// [`LoopBehavior`]: crate::engine::LoopBehavior
///
/// # Example
///
/// Creating an array of [`Action`]s and setting each one to a different color:
///
/// ```rust
/// # use choreographer::engine::{Action, ActionBuilder};
/// use choreographer::colors::{RED, YELLOW, GREEN, CYAN, BLUE, MAGENTA};
/// use groundhog::std_timer::Timer;
/// type MicroTimer = Timer<1_000_000>;
///
/// let colors = [RED, YELLOW, GREEN, CYAN, BLUE, MAGENTA];
/// let mut actions: [Action<MicroTimer>; 6] = Default::default();
///
/// for (action, color) in actions.iter_mut().zip(colors.iter()) {
///     *action = ActionBuilder::new().once().seek().color(*color).for_ms(100).finish();
/// }
/// ```
#[derive(Clone)]
pub struct Action<R> {
    action: InnerAction<R>,
    behavior: LoopBehavior,
}

impl<R> Default for Action<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    fn default() -> Self {
        Self {
            action: Default::default(),
            behavior: Default::default(),
        }
    }
}

impl<R> Deref for Action<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    type Target = Context<R>;

    fn deref(&self) -> &Self::Target {
        &self.action.context
    }
}

impl<R> Action<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    /// Return an ActionBuilder structure to configure a new
    /// Action
    pub fn build() -> ActionBuilder<R> {
        ActionBuilder::new()
    }

    pub(crate) fn reinit(&mut self, start: R::Tick, end_ph: R::Tick, last_color: RGB8) {
        self.action.reinit(start, end_ph, last_color);

        use LoopBehavior::*;
        match &mut self.behavior {
            OneShot => {}
            LoopForever => {}
            Nop => {}
            LoopN {
                ref mut current, ..
            } => {
                *current = 0;
            }
        }
    }

    pub(crate) fn poll(&mut self) -> Option<RGB8> {
        use LoopBehavior::*;

        let action = &mut self.action;
        let behavior = &mut self.behavior;

        match behavior {
            OneShot => action.poll(),
            LoopForever => action.poll().or_else(|| {
                let end = action.calc_end();
                let end_ph = action.calc_end_phase();
                let last_color = action.context.color;
                action.reinit(end, end_ph, last_color);
                action.poll()
            }),
            LoopN {
                ref mut current,
                cycles,
            } => action.poll().or_else(|| {
                if *current < *cycles {
                    *current += 1;
                    // TODO: Reinit as above?
                    action.poll()
                } else {
                    None
                }
            }),
            Nop => None,
        }
    }
}

/// The behavior-independent information of an [`Action`]
///
/// The Context structure contains information like the color,
/// start time, and duration of an [`Action`].
///
/// It is not usually necessary to interact with a Context directly.
///
/// [`Action`]: crate::engine::Action
#[derive(Clone, Default)]
pub struct Context<R> {
    pub(crate) start_tick: u32, // TODO: Hack - Not R::Tick because const init
    pub(crate) auto_incr_phase: AutoIncr,
    pub(crate) period_ms: f32,
    pub(crate) duration_ms: u32, // TODO: Hack - Not R::Tick because const init
    pub(crate) phase_offset_ms: u32, // TODO: Hack - Not R::Tick because const init
    pub(crate) last_color: RGB8,
    pub(crate) color: RGB8,
    _pd: PhantomData<R>,
}

impl<R> Context<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    pub(crate) fn calc_end(&self) -> R::Tick {
        self.start_tick
            .wrapping_add(self.duration_ms * (R::TICKS_PER_SECOND / 1000))
    }

    pub(crate) fn calc_end_phase(&self) -> R::Tick {
        self.phase_offset_ms.wrapping_add(self.duration_ms)
    }

    pub(crate) fn reinit(&mut self, start: R::Tick, start_ph: R::Tick, last_color: RGB8) {
        self.start_tick = start;
        self.last_color = last_color;
        match self.auto_incr_phase {
            AutoIncr::Never => {}
            AutoIncr::Once => {
                self.phase_offset_ms = start_ph;
                self.auto_incr_phase = AutoIncr::Never;
            }
            AutoIncr::Forever => {
                self.phase_offset_ms = start_ph;
            }
        }
    }
}

#[derive(Clone)]
struct InnerAction<R> {
    context: Context<R>,
    kind: InnerActionKind,
}

impl<R> Default for InnerAction<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    fn default() -> Self {
        Self {
            context: Context::default(),
            kind: InnerActionKind::Static(StayColor::new()),
        }
    }
}

impl<R> Deref for InnerAction<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    type Target = Context<R>;

    fn deref(&self) -> &Self::Target {
        &self.context
    }
}

impl<R> DerefMut for InnerAction<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.context
    }
}

impl<R> InnerAction<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    pub fn poll(&self) -> Option<RGB8> {
        use InnerActionKind::*;
        match &self.kind {
            Sin(s) => s.poll(&self.context),
            Static(s) => s.poll(&self.context),
            Fade(f) => f.poll(&self.context),
            Seek(s) => s.poll(&self.context),
        }
    }
}

#[derive(Clone)]
enum InnerActionKind {
    Sin(Cycler),
    Static(StayColor),
    Fade(FadeColor),
    Seek(SeekColor),
}

/// A description of the looping behavior of an [`Action`] or [`Sequence`]
///
/// [`Sequence`]: crate::engine::Sequence
/// [`Action`]: crate::engine::Action
#[derive(Clone)]
pub enum LoopBehavior {
    /// Execute this action or sequence exactly once
    OneShot,

    /// Loop this action or sequence endlessly
    LoopForever,

    /// Loop this action or sequence N times
    LoopN {
        /// The current iteration
        current: usize,

        /// The total number of iterations
        cycles: usize,
    },

    /// This action will immediately yield to the next
    Nop,
}

impl Default for LoopBehavior {
    fn default() -> Self {
        LoopBehavior::Nop
    }
}

/// A builder for the [`Action`] structure
///
/// [`Action`]: crate::engine::Action
pub struct ActionBuilder<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    act: Action<R>,
}

// Builder Methods
impl<R> ActionBuilder<R>
where
    R: RollingTimer<Tick = u32> + Default + Clone,
{
    /// Create a new ActionBuilder with default settings
    #[inline(always)]
    pub fn new() -> Self {
        Self {
            act: Action {
                action: InnerAction::default(),
                behavior: LoopBehavior::default(),
            },
        }
    }

    /// Finalize the ActionBuilder into an Action
    #[inline(always)]
    pub fn finish(self) -> Action<R> {
        self.act
    }

    /// Set the LoopBehavior to repeat `ct` times
    #[inline(always)]
    pub fn times(mut self, ct: usize) -> Self {
        self.act.behavior = LoopBehavior::LoopN {
            current: 0,
            cycles: ct,
        };
        self
    }

    /// Set the LoopBehavior to repeat never
    #[inline(always)]
    pub fn once(mut self) -> Self {
        self.act.behavior = LoopBehavior::OneShot;
        self
    }

    /// Set the LoopBehavior to loop forever
    #[inline(always)]
    pub fn forever(mut self) -> Self {
        self.act.behavior = LoopBehavior::LoopForever;
        self
    }

    /// Set the color
    #[inline(always)]
    pub fn color(mut self, color: RGB8) -> Self {
        self.act.action.context.color = color;
        self
    }

    /// Set the duration in milliseconds
    #[inline(always)]
    pub fn for_ms(mut self, duration: R::Tick) -> Self {
        self.act.action.context.duration_ms = duration;

        // TODO: This might be better to remove later? Probably
        // conside how to handle these "hacks", or abstract over
        // the cycler type more reasonably
        if let InnerActionKind::Fade(_) = self.act.action.kind {
            self.act.action.context.period_ms = duration.lossy_into() * 4.0;
        }
        self
    }

    /// Set the phase offset behavior
    #[inline(always)]
    pub fn phase_offset_ms(mut self, phase_offset_ms: PhaseIncr) -> Self {
        let (phase_offset_ms, incr) = match phase_offset_ms {
            PhaseIncr::Millis(ms) => (ms, AutoIncr::Never),
            PhaseIncr::AutoIncr => (0, AutoIncr::Forever),
            PhaseIncr::AutoIncrOnStart => (0, AutoIncr::Once),
        };
        self.act.action.context.phase_offset_ms = phase_offset_ms;
        self.act.action.context.auto_incr_phase = incr;
        self
    }

    /// Set the duration and period in one step
    #[inline(always)]
    pub fn dur_per_ms(mut self, duration: R::Tick, period_ms: f32) -> Self {
        self.act.action.context.duration_ms = duration;

        // TODO: fix hax?
        self.act.action.context.period_ms = match self.act.action.kind {
            InnerActionKind::Sin(_) => period_ms * 2.0,
            InnerActionKind::Static(_) => period_ms,
            InnerActionKind::Fade(_) => duration.lossy_into() * 4.0,
            InnerActionKind::Seek(_) => period_ms,
        };

        self
    }

    /// Set the period, in milliseconds (as an f32)
    #[inline(always)]
    pub fn period_ms(mut self, duration: f32) -> Self {
        self.act.action.context.period_ms = duration;
        self
    }

    /// Convert the current ActionBuilder to produce a Sine Cycler
    #[inline(always)]
    pub fn sin(mut self) -> Self {
        let mut sin = Cycler::new();
        sin.start_low();
        self.act.action.kind = InnerActionKind::Sin(sin);
        self
    }

    /// Convert the current ActionBuilder to produce a SeekColor behavior
    #[inline(always)]
    pub fn seek(mut self) -> Self {
        self.act.action.kind = InnerActionKind::Seek(SeekColor);
        self
    }

    /// Convert the current ActionBuilder to produce a Cosine Cycler
    #[inline(always)]
    pub fn cos(mut self) -> Self {
        let mut cos = Cycler::new();
        cos.start_high();
        self.act.action.kind = InnerActionKind::Sin(cos);
        self
    }

    /// Convert the current ActionBuilder to produce a StayColor action
    #[inline(always)]
    pub fn solid(mut self) -> Self {
        self.act.action.kind = InnerActionKind::Static(StayColor::new());
        self
    }

    /// Convert the current ActionBuilder to produce a Fade Up action
    #[inline(always)]
    pub fn fade_up(mut self) -> Self {
        self.act.action.kind =
            InnerActionKind::Fade(FadeColor::new_fade_up(&mut self.act.action.context));
        self
    }

    /// Convert the current ActionBuilder to produce a Fade Down action
    #[inline(always)]
    pub fn fade_down(mut self) -> Self {
        self.act.action.kind =
            InnerActionKind::Fade(FadeColor::new_fade_down(&mut self.act.action.context));
        self
    }
}

/// A description of Phase Increment Behavior
pub enum PhaseIncr {
    /// A specific phase increment, in milliseconds
    Millis(u32),

    /// Increment the phase from the last elapsed phase
    /// on every action transition
    AutoIncr,

    /// Increment the phase from the last elapsed phase
    /// on the first action transition
    AutoIncrOnStart,
}

impl From<u32> for PhaseIncr {
    fn from(data: u32) -> Self {
        PhaseIncr::Millis(data)
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum AutoIncr {
    Never,
    Once,
    Forever,
}

impl Default for AutoIncr {
    fn default() -> Self {
        AutoIncr::Never
    }
}