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
219
220
221
|
use axum::{Json, Router, extract::State, routing::get};
use clap::Parser;
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::process;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tracing::{debug, error, info, warn};
type PrinterStateRef = Arc<RwLock<PrinterState>>;
type StateMap = HashMap<String, PrinterStateRef>;
#[derive(Parser, Debug)]
#[command(about = "Print statistics scraper")]
struct Args {
/// Path to the configuration file
#[arg(long, default_value = "config.toml")]
config: String,
/// Address to bind the HTTP server to
#[arg(long, default_value = "0.0.0.0:3000")]
bind: String,
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let args = Args::parse();
let content = fs::read_to_string(&args.config).unwrap_or_else(|e| {
error!(path = %args.config, error = %e, "Failed to read config file");
process::exit(1);
});
let config = Config::load(&content).unwrap_or_else(|e| {
error!(path = %args.config, error = %e, "Failed to parse config file");
process::exit(1);
});
let mut map: StateMap = HashMap::new();
for printer in config.printers {
match printer {
Printer::Prusa {
name,
host,
api_key,
} => {
info!(name, host, "Found Prusa");
let printer_state = Arc::new(RwLock::new(PrinterState::default()));
map.insert(name.clone(), printer_state.clone());
tokio::spawn(async move {
match tokio::spawn(poll_prusa(name.clone(), host, api_key, printer_state)).await
{
Ok(()) => warn!(name, "Prusa polling task exited unexpectedly"),
Err(e) => error!(name, error = ?e, "Prusa polling task panicked"),
}
});
}
Printer::Bambu {
name,
host,
serial_number,
access_code,
} => {
info!(name, host, "Found Bambu");
let printer_state = Arc::new(RwLock::new(PrinterState::default()));
map.insert(name.clone(), printer_state.clone());
tokio::spawn(async move {
match tokio::spawn(poll_bambu(
name.clone(),
host,
serial_number,
access_code,
printer_state,
))
.await
{
Ok(()) => warn!(name, "Bambu polling task exited unexpectedly"),
Err(e) => error!(name, error = ?e, "Bambu polling task panicked"),
}
});
}
}
}
// Drop mutability on the StateMap
let state: StateMap = map;
let app = Router::new().route("/", get(root)).with_state(state);
let listener = tokio::net::TcpListener::bind(&args.bind)
.await
.unwrap_or_else(|e| {
error!(addr = %args.bind, error = %e, "Failed to bind to address");
process::exit(1);
});
info!(addr = %args.bind, "Listening");
axum::serve(listener, app).await.unwrap_or_else(|e| {
error!(error = %e, "HTTP server error");
process::exit(1);
});
}
async fn fetch_prusa(
client: &Client,
host: &str,
api_key: &str,
state: &PrinterStateRef,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let response = client
.get(format!("http://{}/api/v1/status", host))
.header("X-Api-Key", api_key)
.send()
.await?
.json::<PrusaStatus>()
.await?;
state.write().unwrap().update_from(&response);
Ok(())
}
async fn poll_prusa(name: String, host: String, api_key: String, state: PrinterStateRef) {
let client = Client::builder()
.timeout(Duration::from_secs(10))
.build()
.unwrap_or_else(|e| {
error!(name, error = %e, "Failed to build HTTP client");
process::exit(1);
});
loop {
if let Err(e) = fetch_prusa(&client, &host, &api_key, &state).await {
error!(name, error = %e, "Error polling Prusa printer");
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
async fn poll_bambu(
name: String,
host: String,
serial_number: String,
access_code: String,
state: PrinterStateRef,
) {
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 = match TlsConnector::builder()
.danger_accept_invalid_certs(true)
.build()
{
Ok(c) => c,
Err(e) => {
error!(name, error = %e, "Failed to build TLS connector");
process::exit(1);
}
};
mqttoptions.set_transport(Transport::tls_with_config(connector.into()));
let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
loop {
// eventloop.poll() yields back to Tokio when there's no data
match eventloop.poll().await {
Ok(Event::Incoming(Packet::ConnAck(_))) => {
if let Err(e) = client
.subscribe(format!("device/{}/report", serial_number), QoS::AtMostOnce)
.await
{
error!(name, error = %e, "Failed to subscribe to Bambu MQTT topic");
}
// Send a request to push all values to us; otherwise we'll have to wait for the values to come in incremental updates.
if let Err(e) = client
.publish(
format!("device/{}/request", serial_number),
QoS::AtMostOnce,
false,
serde_json::json!({
"pushing": {
"sequence_id": "0",
"command": "pushall",
"version": 1,
"push_target": 1
}
})
.to_string(),
)
.await
{
error!(name, error = %e, "Failed to send pushall to Bambu printer");
}
}
Ok(Event::Incoming(Packet::Publish(p))) => {
debug!(payload = ?p.payload, "Received Bambu payload");
match serde_json::from_slice::<BambuStatus>(&p.payload) {
Ok(msg) => {
state.write().unwrap().update_from(&msg);
debug!(name, "Updated state");
}
Err(e) => error!(error = %e, "Failed to deserialize BambuStatus"),
}
}
Ok(_) => {}
Err(e) => {
error!(error = ?e, "MQTT error");
tokio::time::sleep(Duration::from_secs(5)).await; // Simple retry
}
}
}
}
async fn root(State(state): State<StateMap>) -> Json<HashMap<String, PrinterState>> {
Json(
state
.iter()
.map(|(k, v)| (k.clone(), v.read().unwrap().clone()))
.collect(),
)
}
|