matroskin 0.1.0

whatsminer api client lib
Documentation
//! Implement `set.miner.power` command
//!
//! Sets the miner's power consumption to a specific value in watts.
//!
//! - Command: [SetMinerPower]
//! - ApiDoc: <https://apidoc.whatsminer.com/#api-Miner-btminer_set_power>
use core::str;

use crate::{
    command::{Command, CommandLevel},
    error::Result,
};

/// This command represents the `set.miner.power` operation.
///
/// Sets the miner's power consumption to a specific value in watts.
/// Records setting in user config. Can be set before or during runtime.
/// If set during frequency tuning, effective next boot. If after tuning, dynamic effective.
///
/// - ApiDoc: <https://apidoc.whatsminer.com/#api-Miner-btminer_set_power>
///
/// # Example
/// ```rust,no_run
/// use matroskin::actor::Actor;
/// use matroskin::account::Account;
/// use matroskin::password::Password;
/// use matroskin::command::set_miner_power::SetMinerPower;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let addr = "10.10.10.10:4433";
///     let username = Account::Super;
///     let password = Password::Super;
///     let actor = Actor::new(addr, username, password);
///     actor.connect()?;
///
///     let cmd = SetMinerPower::new(3500);
///     let response = actor.send(cmd).await?;
///     println!("Response: {:#?}", response);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SetMinerPower {
    /// Target power consumption in watts
    pub power: u32,
}

impl SetMinerPower {
    /// Create a new `set.miner.power` command.
    pub const fn new(power: u32) -> Self {
        Self { power }
    }
}

impl Command for SetMinerPower {
    type Response = String;
    const CMD_NAME: &'static str = "set.miner.power";
    const LEVEL: CommandLevel = CommandLevel::Secured;
    fn params(&self) -> Result<Option<impl serde::Serialize>> {
        Ok(Some(self.power))
    }
}

#[cfg(test)]
mod tests {
    use crate::account::Account;
    use crate::auth_data::AuthData;

    use super::*;

    const RESPONSE_JSON: &str =
        r#"{"code":0,"when":1692685512,"msg":"ok","desc":"set.miner.power"}"#;

    #[test]
    fn request_has_param() {
        let cmd = SetMinerPower::new(3500);
        assert!(cmd.is_secured());
        assert!(!cmd.is_encrypted());

        let auth = AuthData::new::<SetMinerPower>(Account::Super, "pass", "salt").unwrap();
        let encoded = cmd.encode(Some(auth)).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();

        assert_eq!(json["cmd"], "set.miner.power");
        assert_eq!(json["param"], 3500);
        assert_eq!(json["account"], "super");
        assert!(json["ts"].as_u64().unwrap() > 0);
        assert_eq!(json["token"].as_str().unwrap().len(), 8);
    }

    #[test]
    fn request_without_auth_omits_token() {
        let cmd = SetMinerPower::new(3500);
        let encoded = cmd.encode(None).unwrap();
        let json: serde_json::Value = serde_json::from_slice(&encoded.0).unwrap();
        assert!(json.get("token").is_none());
        assert_eq!(json["param"], 3500);
    }

    #[test]
    fn deserialize_response_fixture() {
        let response = SetMinerPower::parse_response(RESPONSE_JSON.as_bytes()).unwrap();
        assert!(response.code.is_success());
        assert_eq!(response.desc, "set.miner.power");
        assert_eq!(response.when, 1692685512);
        assert_eq!(response.msg, "ok");
    }
}