buddy_client 0.0.1

A client for the Prusa Buddy Firmware http api.
Documentation
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#![doc = include_str!("../README.md")]
use std::fmt::Display;
use std::time::Duration;

#[cfg(feature = "async")]
use reqwest::Client as AsyncClient;
/// Re-exports reqwest error so you can evaluate any errors returned by the client.
pub use reqwest::Error;
#[cfg(feature = "blocking")]
use reqwest::blocking::Client as SyncClient;
use reqwest::{
    StatusCode,
    header::{HeaderMap, HeaderValue},
};
use serde::de::DeserializeOwned;

use crate::responses::{OctoJob, OctoPrinter, V1Info, V1Job, V1Status, V1Storage, Version};

pub mod responses;

/// A wrapper type over a `reqwest::Client`.
#[cfg(feature = "async")]
pub type Async = AsyncClient;

/// A wrapper type over a `reqwest::blocking::Client`. Activated using the `blocking` feature flag.
#[cfg(feature = "blocking")]
pub type Sync = SyncClient;

/// A HTTP client for the Prusa Buddy API where `T` is either `reqwest::Client` or `reqwest::blocking::Client`.
pub struct PrusaClient<T> {
    ip: String,
    inner: T,
}

impl<T> PrusaClient<T> {
    /// A utility function to construct a url to query.
    fn format_url(&self, endpoint: impl Display) -> String {
        format!("http://{}/{}", self.ip, endpoint)
    }

    /// Returns the inner reqwest client instance.
    pub fn into_inner(self) -> T {
        self.inner
    }
}

/// Asynchronous implementation using `reqwest::Client` that works with async runtimes, such as [`tokio`](https://tokio.rs/).
#[cfg(feature = "async")]
impl PrusaClient<Async> {
    /// Create a new instance of `PrusaClient<Async>`. You can pass your own timeout duration. The default is set to 1 second.
    pub fn new_async(
        ip: impl Into<String>,
        key: impl AsRef<str>,
        timeout: Option<Duration>,
    ) -> Self {
        // Create the header
        let mut headers = HeaderMap::default();
        headers.insert("X-API-KEY", HeaderValue::from_str(key.as_ref()).unwrap());

        let timeout = timeout.unwrap_or(Duration::from_secs(1));

        // Build the client
        let client = AsyncClient::builder()
            .default_headers(headers)
            .timeout(timeout)
            .build()
            .unwrap();

        Self {
            ip: ip.into(),
            inner: client,
        }
    }

    /// GET request utility function
    async fn get<D: DeserializeOwned>(&self, url: &str) -> Result<D, Error> {
        self.inner.get(url).send().await?.json::<D>().await
    }

    /// PUT request utility function
    async fn put(&self, url: &str) -> Result<(), Error> {
        self.inner.put(url).send().await?.error_for_status()?;
        Ok(())
    }

    /// DELETE request utility function.
    async fn delete(&self, url: &str) -> Result<(), Error> {
        self.inner.delete(url).send().await?.error_for_status()?;
        Ok(())
    }

    /// Get the API version information.
    pub async fn version(&self) -> Result<Version, Error> {
        let url = self.format_url("api/version");
        println!("{}", url);
        self.get(url.as_str()).await
    }

    /// Get the info information.
    pub async fn v1_info(&self) -> Result<V1Info, Error> {
        let url = self.format_url("api/v1/info");
        self.get(url.as_str()).await
    }

    /// Get the status information.
    pub async fn v1_status(&self) -> Result<V1Status, Error> {
        let url = self.format_url("api/v1/status");
        self.get(url.as_str()).await
    }

    /// Get storage info
    pub async fn v1_storage(&self) -> Result<V1Storage, Error> {
        let url = self.format_url("api/v1/storage");
        self.get(url.as_str()).await
    }

    /// Stop a job
    pub async fn v1_stop_job(&self, id: u64) -> Result<(), Error> {
        let endpoint = format!("api/v1/job/{}", id);
        let url = self.format_url(endpoint);
        self.delete(url.as_str()).await
    }

    /// Pause a job
    pub async fn v1_pause_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job().await? {
            let endpoint = format!("api/v1/job/{}/pause", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.put(url.as_str()).await?));
        }
        Ok(None)
    }

    /// Resume a job
    pub async fn v1_resume_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job().await? {
            let endpoint = format!("api/v1/job/{}/resume", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.put(url.as_str()).await?));
        }
        Ok(None)
    }

    /// Continue a job
    pub async fn v1_continue_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job().await? {
            let endpoint = format!("api/v1/job/{}/continue", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.put(url.as_str()).await?));
        }
        Ok(None)
    }

    /// Stop a transfer
    pub async fn v1_delete_transfer(&self, id: u64) -> Result<(), Error> {
        let endpoint = format!("api/v1/transfer/{}", id);
        let url = self.format_url(endpoint);
        self.delete(url.as_str()).await
    }

    /// Get the metadata pertaining to a file or folder.
    pub async fn v1_put_file(
        &self,
        path: &str,
        file: &[u8],
        print_after_upload: bool,
        overwrite: bool,
    ) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        let mut pau: &str = "?1";
        if !print_after_upload {
            pau = "?0";
        }
        let mut o = "?1";
        if !overwrite {
            o = "?0";
        }
        self.inner
            .put(url)
            .header("Content-Type", "application/octet-stream")
            .header("Print-After-Upload", pau)
            .header("Overwrite", o)
            .body(file.to_owned())
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    /// Start a job if there's no print job running
    pub async fn v1_start_job(&self, path: &str) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        self.inner.post(url).send().await?.error_for_status()?;
        Ok(())
    }

    /// Check the presence of a file or folder in storage
    pub async fn v1_is_path(&self, path: &str) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        self.inner.head(url).send().await?.error_for_status()?;
        Ok(())
    }

    // Delete a file or folder
    pub async fn v1_delete_path(&self, path: &str) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        self.delete(url.as_str()).await
    }

    /// Get details of the current job (if any).
    pub async fn v1_get_job(&self) -> Result<Option<V1Job>, Error> {
        let url = self.format_url("api/v1/job");
        let r = self.inner.get(url).send().await?.error_for_status()?;
        if r.status() == StatusCode::NO_CONTENT {
            return Ok(None);
        }
        let json = r.json::<V1Job>().await?;
        Ok(Some(json))
    }

    /// Get settings in the Octoprint form
    pub async fn octo_settings(&self) -> Result<(), Error> {
        let url = self.format_url("api/settings");
        self.inner.get(url).send().await?.error_for_status()?;
        Ok(())
    }

    /// Get settings in the Octoprint form
    pub async fn octo_printer(&self) -> Result<OctoPrinter, Error> {
        let url = self.format_url("api/printer");
        self.get(url.as_str()).await
    }

    /// Get details of the current job (if any).
    pub async fn octo_job(&self) -> Result<OctoJob, Error> {
        let url = self.format_url("api/job");
        self.get(url.as_str()).await
    }
}

/// Blocking implementation using `reqwest::blocking::Client` for synchronous workflows.
#[cfg(feature = "blocking")]
impl PrusaClient<Sync> {
    /// Create a new instance of `PrusaClient<Sync>`. You can pass your own timeout duration. The default is set to 1 second.
    pub fn new_sync(
        ip: impl Into<String>,
        key: impl AsRef<str>,
        timeout: Option<Duration>,
    ) -> Self {
        // Create the header
        let mut headers = HeaderMap::default();
        headers.insert("X-API-KEY", HeaderValue::from_str(key.as_ref()).unwrap());

        let timeout = timeout.unwrap_or(Duration::from_secs(1));

        // Build the client
        let client = SyncClient::builder()
            .default_headers(headers)
            .timeout(timeout)
            .build()
            .unwrap();

        Self {
            ip: ip.into(),
            inner: client,
        }
    }

    /// GET request utility function
    fn get<D: DeserializeOwned>(&self, url: &str) -> Result<D, Error> {
        self.inner.get(url).send()?.json::<D>()
    }

    /// PUT request utility function
    fn put(&self, url: &str) -> Result<(), Error> {
        self.inner.put(url).send()?.error_for_status()?;
        Ok(())
    }

    /// DELETE request utility function
    fn delete(&self, url: &str) -> Result<(), Error> {
        self.inner.delete(url).send()?.error_for_status()?;
        Ok(())
    }

    /// Get the API version information.
    pub fn version(&self) -> Result<Version, Error> {
        let url = self.format_url("api/version");
        println!("{}", url);
        self.get(url.as_str())
    }

    /// Get the info information.
    pub fn v1_info(&self) -> Result<V1Info, Error> {
        let url = self.format_url("api/v1/info");
        self.get(url.as_str())
    }

    /// Get the status information.
    pub fn v1_status(&self) -> Result<V1Status, Error> {
        let url = self.format_url("api/v1/status");
        self.get(url.as_str())
    }

    /// Get storage info
    pub fn v1_storage(&self) -> Result<V1Storage, Error> {
        let url = self.format_url("api/v1/storage");
        self.get(url.as_str())
    }

    /// Stop a job
    pub fn v1_stop_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job()? {
            let endpoint = format!("api/v1/job/{}", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.delete(url.as_str())?));
        }
        Ok(None)
    }

    /// Pause a job
    pub fn v1_pause_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job()? {
            let endpoint = format!("api/v1/job/{}/pause", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.put(url.as_str())?));
        }
        Ok(None)
    }

    /// Resume a job
    pub fn v1_resume_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job()? {
            let endpoint = format!("api/v1/job/{}/resume", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.put(url.as_str())?));
        }
        Ok(None)
    }

    /// Continue a job
    pub fn v1_continue_job(&self) -> Result<Option<()>, Error> {
        if let Some(job) = self.v1_get_job()? {
            let endpoint = format!("api/v1/job/{}/continue", job.id);
            let url = self.format_url(endpoint);
            return Ok(Some(self.put(url.as_str())?));
        }
        Ok(None)
    }

    /// Stop a transfer
    pub fn v1_delete_transfer(&self, id: u64) -> Result<(), Error> {
        let endpoint = format!("api/v1/transfer/{}", id);
        let url = self.format_url(endpoint);
        self.delete(url.as_str())
    }

    /// Get the metadata pertaining to a file or folder.
    pub fn v1_put_file(
        &self,
        path: &str,
        file: &[u8],
        print_after_upload: bool,
        overwrite: bool,
    ) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        let mut pau: &str = "?1";
        if !print_after_upload {
            pau = "?0";
        }
        let mut o = "?1";
        if !overwrite {
            o = "?0";
        }
        self.inner
            .put(url)
            .header("Content-Type", "application/octet-stream")
            .header("Print-After-Upload", pau)
            .header("Overwrite", o)
            .body(file.to_owned())
            .send()?
            .error_for_status()?;
        Ok(())
    }

    /// Start a job if there's no print job running
    pub fn v1_is_path(&self, path: &str) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        self.inner.post(url).send()?.error_for_status()?;
        Ok(())
    }

    /// Check the presence of a file or folder in storage
    pub fn v1_path_exists(&self, path: &str) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        self.inner.head(url).send()?.error_for_status()?;
        Ok(())
    }

    /// Delete a file or folder
    pub fn v1_delete_path(&self, path: &str) -> Result<(), Error> {
        let endpoint = format!("api/v1/files/usb/{}", path);
        let url = self.format_url(endpoint);
        self.delete(url.as_str())
    }

    /// Get details of the current job (if any).
    pub fn v1_get_job(&self) -> Result<Option<V1Job>, Error> {
        let url = self.format_url("api/v1/job");
        let r = self.inner.get(url).send()?.error_for_status()?;
        if r.status() == StatusCode::NO_CONTENT {
            return Ok(None);
        }
        let json = r.json::<V1Job>()?;
        Ok(Some(json))
    }

    /// Get settings in the Octoprint form
    pub fn get_octo_settings(&self) -> Result<(), Error> {
        let url = self.format_url("api/settings");
        self.inner.get(url).send()?.error_for_status()?;
        Ok(())
    }

    /// Get settings in the Octoprint form
    pub fn get_octo_printer(&self) -> Result<OctoPrinter, Error> {
        let url = self.format_url("api/printer");
        self.get(url.as_str())
    }

    /// Get details of the current job (if any).
    pub fn get_octo_job(&self) -> Result<OctoJob, Error> {
        let url = self.format_url("api/job");
        self.get(url.as_str())
    }
}

#[cfg(test)]
mod async_test {
    use dotenvy_macro::dotenv;

    use crate::{Async, PrusaClient};

    fn new_async_client() -> PrusaClient<Async> {
        let ip = dotenv!("PRUSA_IP");
        let key = dotenv!("PRUSA_KEY");
        PrusaClient::new_async(ip, key, None)
    }

    #[tokio::test]
    async fn test_version() {
        let client = new_async_client();
        let status = client.version().await;
        println!("{:?}", status);
        assert!(status.is_ok())
    }
}

#[cfg(feature = "blocking")]
#[cfg(test)]
mod sync_test {
    use dotenvy_macro::dotenv;

    use crate::{PrusaClient, Sync};

    fn new_sync_client() -> PrusaClient<Sync> {
        let ip = dotenv!("PRUSA_IP");
        let key = dotenv!("PRUSA_KEY");
        PrusaClient::new_sync(ip, key, None)
    }

    #[test]
    fn test_version() {
        let client = new_sync_client();
        let status = client.version();
        println!("{:?}", status);
        assert!(status.is_ok())
    }
}