cat_dev/mion/cgis/status.rs
1//! API's for interacting with `/mion/status.cgi`.
2//!
3//! These APIs allow changing the status of Disc In/Disc Out, etc. You can view
4//! the setup page on the actual main page of the MION dashboard.
5
6use crate::{
7 errors::NetworkError,
8 mion::{
9 cgis::{do_simple_request, parse_result_from_body},
10 proto::cgis::{MIONCGIErrors, StatusOperation},
11 },
12};
13use reqwest::{Client, Method};
14use serde::Serialize;
15use std::net::Ipv4Addr;
16
17/// Perform an `eject` event to set the current DISC IN/Eject state for the
18/// MION.
19///
20/// ## Errors
21///
22/// - If we cannot encode the parameters as a form url encoded.
23/// - If we cannot make the HTTP request.
24/// - If the server does not respond with a 200.
25/// - If we cannot read the body from HTTP.
26/// - If we cannot parse the HTML response.
27pub async fn set_disc_eject_state(mion_ip: Ipv4Addr, disc_in: bool) -> Result<bool, NetworkError> {
28 set_disc_eject_state_with_raw_client(&Client::default(), mion_ip, disc_in).await
29}
30
31/// Perform an `eject` event to set the current DISC IN/Eject state for the
32/// MION, but with an already existing HTTP Client.
33///
34/// ## Errors
35///
36/// - If we cannot encode the parameters as a form url encoded.
37/// - If we cannot make the HTTP request.
38/// - If the server does not respond with a 200.
39/// - If we cannot read the body from HTTP.
40/// - If we cannot parse the HTML response.
41pub async fn set_disc_eject_state_with_raw_client(
42 client: &Client,
43 mion_ip: Ipv4Addr,
44 disc_in: bool,
45) -> Result<bool, NetworkError> {
46 let body_as_string = do_raw_status_request(
47 client,
48 mion_ip,
49 &[
50 ("operation", Into::<&str>::into(StatusOperation::Eject)),
51 ("disc", if disc_in { "in" } else { "out" }),
52 ("frommenu", "no"),
53 ],
54 )
55 .await?;
56
57 Ok(parse_result_from_body(
58 &body_as_string,
59 Into::<&str>::into(StatusOperation::Eject),
60 )?)
61}
62
63/// Perform a raw operation on the MION board's `/mion/status.cgi` page.
64///
65/// *note: you probably want to call one of the actual methods, as this is
66/// basically just a thin wrapper around an HTTP Post Request. Not doing much
67/// else more. A lot of it requires that you set things up correctly.*
68///
69/// ## Errors
70///
71/// - If we cannot make an HTTP request to the MION Request.
72/// - If we fail to encode your parameters into a request body.
73pub async fn do_raw_status_request<UrlEncodableType>(
74 client: &Client,
75 mion_ip: Ipv4Addr,
76 url_parameters: UrlEncodableType,
77) -> Result<String, NetworkError>
78where
79 UrlEncodableType: Serialize,
80{
81 do_simple_request::<String>(
82 client,
83 Method::POST,
84 format!("http://{mion_ip}/mion/status.cgi"),
85 Some(
86 serde_urlencoded::to_string(&url_parameters)
87 .map_err(MIONCGIErrors::FormDataEncodeError)?,
88 ),
89 )
90 .await
91}