rust_lum/src/runner.rs

58 lines
1.6 KiB
Rust

use crate::patterns::Patterns;
use crate::Strip;
use serde_derive::{Deserialize, Serialize};
use std::fs;
use std::time::Duration;
use tokio::sync::watch::Sender;
#[derive(Serialize, Deserialize, Debug)]
pub struct Context<const N: usize> {
pub(crate) pattern: Patterns<N>,
pub period: Duration,
}
impl<const N: usize> IntoIterator for Runner<N> {
type Item = Context<N>;
type IntoIter = <Vec<Context<N>> as IntoIterator>::IntoIter; // so that you don't have to write std::vec::IntoIter, which nobody remembers anyway
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct Runner<const N: usize>(Vec<Context<N>>);
impl<const N: usize> Runner<N> {
pub fn new() -> Runner<N> {
let runner = Vec::<Context<N>>::new();
Runner(runner)
}
pub fn push(&mut self, value: Context<N>) {
self.0.push(value)
}
pub async fn runner_loop(self, tx: Sender<Strip<N>>) {
for mut context in self {
let mut strip = context.pattern.next().unwrap();
let delay = context.period;
println!("{:?}", delay);
while tx.send(strip).is_ok() {
if let Some(value) = context.pattern.next() {
strip = value;
} else {
break;
}
tokio::time::sleep(delay).await;
}
}
}
pub fn load_from_file(file: &std::path::Path) -> Runner<N> {
let file = fs::read_to_string(file).unwrap();
let spectacle: Runner<N> = serde_yaml::from_str(&*file).unwrap();
spectacle
}
}