~jojo/jojos-hue

ref: 6a5bfbbc145e573e6e6639805684b3dcb5336a98 jojos-hue/server/src/main.rs -rw-r--r-- 5.6 KiB
6a5bfbbcJoJo custom UDP protocol & offload FastLED to second core on ESP32 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
use byteorder::{ByteOrder, LittleEndian};
use palette::{FromColor, Hsv, RgbHue, 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};

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 Cmd {
    All(Srgb),
    Off,
    Cycle,
    Breathing,
}

#[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<Cmd>) -> tide::Result {
    let c: QueryRgb = req.query()?;
    tx.send(Cmd::All(Srgb::new(c.r, c.g, c.b))).unwrap();
    Ok("cool, ty".into())
}

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

fn controller(heartbeat_rx: Receiver<Heartbeat>, cmd_rx: Receiver<Cmd>) {
    let t0 = Instant::now();
    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 cmd = Cmd::All(Srgb::new(0.0, 0.0, 0.0));
    loop {
        while let Ok((addr, nleds)) = heartbeat_rx.try_recv() {
            match clients.get_mut(&addr) {
                Some(client) => client.0 = Instant::now(),
                None => {
                    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);
            cmd = new_cmd;
        }
        for (_, tx) in clients.values() {
            let t = t0.elapsed().as_secs_f64();
            tx.send((cmd, 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<(Cmd, f64)> {
    let (tx, rx) = channel::<(Cmd, f64)>();
    thread::spawn(move || loop {
        let magic_cookie = b"satan";
        let (cmd, t) = rx
            .recv()
            .expect("Client channel closed. Time for this thread to die!");
        let color_data = lightf(cmd, t, 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]);
        println!("Heartbeat from {} with {} LEDs", addr, nleds);
        Some((addr, nleds))
    } else {
        None
    }
}

fn lightf(cmd: Cmd, t: f64, nleds: u16) -> Vec<Srgb> {
    match cmd {
        Cmd::All(c) => vec![c; nleds as usize],
        Cmd::Off => vec![Srgb::new(0.0, 0.0, 0.0); nleds as usize],
        Cmd::Cycle => {
            vec![
                Srgb::from_color(Hsv::new(RgbHue::from_radians(t / 2.0), 1.0, 1.0)).into_format();
                nleds as usize
            ]
        }
        Cmd::Breathing => {
            vec![
                Srgb::from_color(Hsv::new(
                    RgbHue::from_radians(1.9 * f32::PI),
                    1.0,
                    0.5 + 0.4 * (t * 0.8).sin() as f32
                ));
                nleds as usize
            ]
        }
    }
}