~jojo/jojos-hue

ref: 1ca4225edef1863d947306fb4c52d8dda84c4740 jojos-hue/server/src/main.rs -rw-r--r-- 6.6 KiB
1ca4225eJoJo Add command AudioVis to visualise playback audio spectrum a month ago
                                                                                
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
use audiovis::AudioVis;
use byteorder::{ByteOrder, LittleEndian};
use palette::{FromColor, Hsv, Hue, RgbHue, Shade, Srgb};
use std::{
    collections::HashMap,
    f32::consts as f32,
    iter::once,
    net::{SocketAddr, UdpSocket},
    sync::{
        mpsc::{channel, sync_channel, Receiver, Sender, SyncSender},
        Arc,
    },
    thread,
    time::{Duration, Instant},
};
use tide::{prelude::*, Request};

mod audiovis;

const FPS: f32 = 100.0;
const DEADLINE: Duration = Duration::from_secs(10);

type Heartbeat = (SocketAddr, u16);

#[derive(Clone, Copy, Deserialize)]
struct QueryRgb {
    r: f32,
    g: f32,
    b: f32,
}

#[derive(Clone, Copy, Debug)]
enum QueryCmd {
    All(Srgb),
    Off,
    Cycle,
    Breathing,
    AudioVis,
}

enum Cmd {
    All,
    Off,
    Cycle,
    Breathing,
    AudioVis(AudioVis),
}

impl Cmd {
    fn render_cmd(&mut self, base: Hsv, t: f64) -> RenderCmd {
        match self {
            Cmd::All => RenderCmd::All(Srgb::from_color(base)),
            Cmd::Off => RenderCmd::All(Srgb::from_color(base.darken(t.min(1.0) as f32))),
            Cmd::Cycle => RenderCmd::All(Srgb::from_color(
                base.shift_hue(hue_f64_to_f32(RgbHue::from_radians(t / 6.0))),
            )),
            Cmd::Breathing => RenderCmd::All(Srgb::from_color(
                base.darken(0.9 * (t / 2.0).sin().powi(2) as f32),
            )),
            Cmd::AudioVis(av) => RenderCmd::All(Srgb::from_color(av.color())),
        }
    }
}

#[derive(Clone, Copy)]
enum RenderCmd {
    All(Srgb),
}

#[async_std::main]
async fn main() -> tide::Result<()> {
    let (heartbeat_tx, heartbeat_rx) = channel();
    let (cmd_tx, cmd_rx) = sync_channel(8);

    thread::spawn(move || {
        let listener = UdpSocket::bind("192.168.0.41:7017").unwrap();
        loop {
            let mut msg = [0; 13];
            if let Some((_, addr)) = listener.recv_from(&mut msg).ok() {
                if let Some(beat) = parse_heartbeat(&msg, addr) {
                    heartbeat_tx.send(beat).unwrap();
                } else {
                    println!(
                        "Malformed message from {}, {:?} / {:?}",
                        addr,
                        String::from_utf8_lossy(&msg),
                        msg
                    )
                }
            }
        }
    });

    thread::spawn(move || controller(heartbeat_rx, cmd_rx));

    let mut web = tide::new();
    web.at("/").serve_file("static/index.html")?;
    web.at("/static").serve_dir("static/")?;
    let cmd_tx1 = cmd_tx.clone();
    web.at("/all")
        .get(move |req| all_handler(req, cmd_tx.clone()));
    web.at("/proc/:name")
        .get(move |req| proc_handler(req, cmd_tx1.clone()));
    web.listen("192.168.0.41:8558").await?;
    Ok(())
}

async fn all_handler(req: Request<()>, tx: SyncSender<QueryCmd>) -> tide::Result {
    let c: QueryRgb = req.query()?;
    tx.send(QueryCmd::All(Srgb::new(c.r, c.g, c.b))).unwrap();
    Ok("cool, ty".into())
}

async fn proc_handler(req: Request<()>, tx: SyncSender<QueryCmd>) -> tide::Result {
    let s = req.param("name")?;
    match s {
        "off" => tx.send(QueryCmd::Off).unwrap(),
        "cycle" => tx.send(QueryCmd::Cycle).unwrap(),
        "breathing" => tx.send(QueryCmd::Breathing).unwrap(),
        "audiovis" => tx.send(QueryCmd::AudioVis).unwrap(),
        _ => {}
    }
    Ok("cool, ty".into())
}

fn controller(heartbeat_rx: Receiver<Heartbeat>, cmd_rx: Receiver<QueryCmd>) {
    let sender = Arc::new(UdpSocket::bind("192.168.0.41:7018").unwrap());
    let mut clients = HashMap::<SocketAddr, (Instant, Sender<_>)>::new();
    let mut tprev = Instant::now();
    let mut tcmd = Instant::now();
    let mut base = Hsv::new(0.0, 0.0, 0.0);
    let mut cmd = Cmd::Off;
    loop {
        while let Ok((addr, nleds)) = heartbeat_rx.try_recv() {
            match clients.get_mut(&addr) {
                Some(client) => client.0 = Instant::now(),
                None => {
                    println!("Registered client {} with {} LEDs", addr, nleds);
                    clients.insert(
                        addr,
                        (Instant::now(), setup_client(addr, nleds, sender.clone())),
                    );
                }
            }
        }
        clients.retain(|addr, (tbeat, _)| {
            let live = tbeat.elapsed() < DEADLINE;
            if !live {
                println!("Sadly, client {} hasn't had a hearbeat for a while, and must thus be pronounced dead!", addr);
            }
            live
        });
        while let Some(new_cmd) = cmd_rx.try_iter().last() {
            println!("New command: {:?}", new_cmd);
            tcmd = Instant::now();
            match new_cmd {
                QueryCmd::All(c) => {
                    base = Hsv::from_color(c);
                    cmd = Cmd::All;
                }
                QueryCmd::Off => cmd = Cmd::Off,
                QueryCmd::Cycle => cmd = Cmd::Cycle,
                QueryCmd::Breathing => cmd = Cmd::Breathing,
                QueryCmd::AudioVis => cmd = Cmd::AudioVis(AudioVis::new()),
            }
        }
        for (_, tx) in clients.values() {
            let t = tcmd.elapsed().as_secs_f64();
            tx.send(cmd.render_cmd(base, t)).ok();
        }
        let dt = tprev.elapsed();
        tprev = Instant::now();
        let period = Duration::from_secs_f32(1.0 / FPS);
        if dt < period {
            thread::sleep(period - dt);
        }
    }
}

fn setup_client(addr: SocketAddr, nleds: u16, sender: Arc<UdpSocket>) -> Sender<RenderCmd> {
    let (tx, rx) = channel();
    thread::spawn(move || loop {
        let magic_cookie = b"satan";
        let cmd = rx
            .recv()
            .expect("Client channel closed. Time for this thread to die!");
        let color_data = lightf(cmd, nleds)
            .into_iter()
            .flat_map(|c| once(c.red).chain(once(c.green)).chain(once(c.blue)))
            .map(|x| (x * 256.0).min(256.0).max(0.0) as u8);
        let data = magic_cookie
            .iter()
            .cloned()
            .chain(color_data)
            .collect::<Vec<u8>>();
        sender.send_to(&data, addr).ok();
    });
    tx
}

fn parse_heartbeat(msg: &[u8; 13], addr: SocketAddr) -> Option<Heartbeat> {
    if msg.starts_with(b"heart<") && msg.ends_with(b">beat") {
        let nleds = LittleEndian::read_u16(&msg[6..8]);
        Some((addr, nleds))
    } else {
        None
    }
}

fn lightf(cmd: RenderCmd, nleds: u16) -> Vec<Srgb> {
    match cmd {
        RenderCmd::All(color) => vec![color; nleds as usize],
    }
}

fn hue_f64_to_f32(h: RgbHue<f64>) -> RgbHue<f32> {
    RgbHue::from_radians(h.to_radians() as f32)
}