summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 9d85c3ed67c6faa8ab367fd13875ba1045bc1ab4 (plain)
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
use serde::Deserialize;

#[derive(Debug)]
pub struct PrinterState {
    pub name: String,
    pub bed_temp: f32,
}

#[derive(Debug, Deserialize)]
pub struct Config {
    // This allows you to have a list of different printer types
    pub printers: Vec<Printer>,
}

impl Config {
    pub fn load(toml: &str) -> Config {
        toml::from_str(toml).expect("Couldn't parse config.toml")
    }
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Printer {
    Prusa {
        name: String,
        host: String,
        api_key: String,
    },
    Bambu {
        name: String,
        host: String,
        access_code: String,
        serial_number: String,
    },
}

pub fn prusa_fetch(client: &reqwest::blocking::Client, printer: &Printer) {
    let Printer::Prusa {
        name,
        host,
        api_key,
    } = printer
    else {
        panic!("Expected a Prusa printer, but received a different variant!");
    };

    let url = format!("http://{}/api/v1/status", host);

    let mut req = client.get(&url);
    req = req.header("X-Api-Key", api_key);

    match req.send() {
        Err(e) => {
            eprintln!("Could not reach Prusa printer {} at {}: {}", name, host, e);
            return;
        }
        Ok(resp) => {
            if !resp.status().is_success() {
                eprintln!("HTTP {}: {}", resp.status(), url);
                if resp.status().as_u16() == 403 {
                    eprintln!("Invalid PrusaLink key for {}.", name);
                }
                return;
            }
            match resp.text() {
                Err(e) => eprintln!("Failed to parse response for Prusa printer {}: {}", host, e),
                Ok(text) => println!("{}", text),
            }
        }
    }
}