summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 0a24ed6912267fd8e54c6e3d6f31443b2288cec0 (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
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
use axum::{Json, Router, extract::State, routing::get};
use native_tls::TlsConnector;
use printstats::*;
use reqwest::Client;
use rumqttc::{AsyncClient, Event, MqttOptions, Packet, QoS, Transport};
use std::collections::HashMap;
use std::fs;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let content = fs::read_to_string("config.toml").expect("Couldn't read config.toml");
    let config = Config::load(&content);
    let state: Arc<Mutex<HashMap<String, PrinterState>>> = Arc::new(Mutex::new(HashMap::new()));

    for printer in config.printers {
        match printer {
            Printer::Prusa {
                name,
                host,
                api_key,
                ..
            } => {
                let state_clone = state.clone();
                tokio::spawn(async move {
                    loop {
                        let result: Result<(), Box<dyn std::error::Error + Send + Sync>> = async {
                            let client = Client::new();
                            let response = client
                                .get(format!("http://{}/api/v1/status", host))
                                .header("X-Api-Key", &api_key)
                                .send()
                                .await?
                                .json::<PrusaStatus>()
                                .await?;
                            let mut lock = state_clone.lock().await;
                            let entry = lock.entry(name.clone()).or_default();
                            extract_status_from_prusa(&response, entry);
                            Ok(())
                        }
                        .await;
                        if let Err(e) = result {
                            eprintln!("Error polling Prusa printer {}: {}", name, e);
                        }
                        tokio::time::sleep(Duration::from_secs(5)).await;
                    }
                });
            }
            Printer::Bambu {
                name,
                host,
                serial_number,
                access_code,
            } => {
                println!("Found Bambu: {} at {}", name, host);
                let state_clone = Arc::clone(&state);
                tokio::spawn(async move {
                    let mut mqttoptions = MqttOptions::new(&name, &host, 8883);
                    mqttoptions.set_keep_alive(Duration::from_secs(5));
                    mqttoptions.set_credentials("bblp", &access_code);

                    // Bambu printers use TLS with a self-signed certificate
                    let connector = TlsConnector::builder()
                        .danger_accept_invalid_certs(true)
                        .build()
                        .unwrap();
                    mqttoptions.set_transport(Transport::tls_with_config(connector.into()));

                    let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
                    client
                        .subscribe(format!("device/{}/report", serial_number), QoS::AtMostOnce)
                        .await
                        .unwrap();

                    loop {
                        // eventloop.poll() yields back to Tokio when there's no data
                        match eventloop.poll().await {
                            Ok(notification) => {
                                if let Event::Incoming(Packet::Publish(p)) = notification {
                                    let mut lock = state_clone.lock().await;
                                    println!("{:?}", &p.payload);
                                    match serde_json::from_slice::<BambuStatus>(&p.payload) {
                                        Ok(msg) => {
                                            let entry = lock.entry(name.clone()).or_default();
                                            extract_status_from_bambu(&msg, entry);
                                            println!(
                                                "Updated state for {}: {:?}",
                                                &name, p.payload
                                            );
                                        }
                                        Err(e) => {
                                            eprintln!("Failed to deserialize BambuStatus: {}", e);
                                        }
                                    }
                                }
                            }
                            Err(e) => {
                                eprintln!("MQTT error: {:?}", e);
                                tokio::time::sleep(Duration::from_secs(5)).await; // Simple retry
                            }
                        }
                    }
                });
            }
        }
    }

    tracing_subscriber::fmt::init();

    let app = Router::new()
        .route("/", get(root))
        .with_state(Arc::clone(&state));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    let _ = axum::serve(listener, app).await;

    loop {
        tokio::select! {
            _ = tokio::signal::ctrl_c() => {
                println!("Shutting down...");
                break;
            }
            _ = tokio::time::sleep(Duration::from_secs(1)) => {
                println!("-- PRINTER STATE --");
                let lock = state.lock().await;
                for (key, value) in lock.iter() {
                    println!("{}: {:?}", key, value);
                }
            }
        }
    }
}

async fn root(
    State(state): State<Arc<Mutex<HashMap<String, PrinterState>>>>,
) -> Json<HashMap<String, PrinterState>> {
    let lock = state.lock().await;
    Json(lock.clone())
}