hrobot/api/
wol.rs

1//! Wake-on-LAN structs and implementation.
2
3use serde::{Deserialize, Serialize};
4
5use crate::{
6    error::{ApiError, Error},
7    AsyncRobot,
8};
9
10use super::{server::ServerId, wrapper::Single, UnauthenticatedRequest};
11
12fn get_wake_on_lan(server_number: ServerId) -> UnauthenticatedRequest<Single<Wol>> {
13    UnauthenticatedRequest::from(&format!(
14        "https://robot-ws.your-server.de/wol/{server_number}"
15    ))
16}
17
18fn post_wake_on_lan(server_number: ServerId) -> UnauthenticatedRequest<Single<Wol>> {
19    UnauthenticatedRequest::from(&format!(
20        "https://robot-ws.your-server.de/wol/{server_number}"
21    ))
22    .with_method("POST")
23}
24
25impl AsyncRobot {
26    /// Check if Wake-on-LAN is available for the server.
27    ///
28    /// # Example
29    /// ```rust,no_run
30    /// # use hrobot::api::server::ServerId;
31    /// # #[tokio::main]
32    /// # async fn main() {
33    /// let robot = hrobot::AsyncRobot::default();
34    /// assert!(robot.is_wake_on_lan_available(ServerId(1234567)).await.unwrap());
35    /// # }
36    /// ```
37    pub async fn is_wake_on_lan_available(&self, server_number: ServerId) -> Result<bool, Error> {
38        let response = self.go(get_wake_on_lan(server_number)).await;
39
40        match response {
41            Ok(_) => Ok(true),
42            Err(Error::Api(ApiError::WolNotAvailable { .. })) => Ok(false),
43            Err(e) => Err(e),
44        }
45    }
46
47    /// Send a Wake-on-LAN packet to the specified server.
48    ///
49    /// # Example
50    /// ```rust,no_run
51    /// # use hrobot::api::server::ServerId;
52    /// # #[tokio::main]
53    /// # async fn main() {
54    /// let robot = hrobot::AsyncRobot::default();
55    /// robot.trigger_wake_on_lan(ServerId(1234567)).await.unwrap();
56    /// # }
57    /// ```
58    pub async fn trigger_wake_on_lan(&self, server_number: ServerId) -> Result<(), Error> {
59        self.go(post_wake_on_lan(server_number)).await.map(|_| ())
60    }
61}
62
63// The API endpoint returns a struct with information about the server,
64// but we only care about the presence of a non-404 response.
65#[derive(Debug, Serialize, Deserialize)]
66struct Wol {
67    #[serde(rename = "server_number")]
68    _server_number: ServerId,
69}