matroskin 0.1.0

whatsminer api client lib
Documentation
//! Implement `set.device.custom_data` command
//!
//! Set or update custom data fields, such as a customer-defined serial number (CustomerSn)
//! or informational messages (msg0-msg9).
//!
//! - Command: [SetDeviceCustomData]
//! - ApiDoc: <https://apidoc.whatsminer.com/#api-Device-btminer_set_device_custom_data>
use core::str;

use serde::Serialize;

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

/// This command represents the `set.device.custom_data` operation.
///
/// Set or update custom data fields, such as a customer-defined serial number (CustomerSn)
/// or informational messages (msg0-msg9).
///
/// - ApiDoc: <https://apidoc.whatsminer.com/#api-Device-btminer_set_device_custom_data>
///
/// # Example
/// ```rust,no_run
/// use matroskin::actor::Actor;
/// use matroskin::command::set_device_custom_data::SetDeviceCustomData;
/// use matroskin::account::Account;
/// use matroskin::password::Password;
///
/// #[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 = SetDeviceCustomData::new("CustomerSn", "CUSTSN-12345");
///     let response = actor.send(cmd).await?;
///     println!("Response: {:#?}", response);
///
///     Ok(())
/// }
/// ```
#[derive(Debug, Serialize, Clone, PartialEq, Eq)]
pub struct SetDeviceCustomData {
    /// The name of the custom data field to set. Valid values: `CustomerSn`, `msg0`-`msg9`.
    pub key: String,
    /// The value to assign to the custom data field. For `msg` fields, the length must be less than 128 bytes.
    pub value: String,
}

impl SetDeviceCustomData {
    /// Create a new `set.device.custom_data` command.
    ///
    /// # Arguments
    /// * `key` — The name of the custom data field (`CustomerSn` or `msg0`-`msg9`).
    /// * `value` — The value to assign to the custom data field.
    pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            value: value.into(),
        }
    }
}

impl Command for SetDeviceCustomData {
    type Response = String;
    const CMD_NAME: &'static str = "set.device.custom_data";
    const LEVEL: CommandLevel = CommandLevel::Secured;

    fn params(&self) -> Result<Option<impl serde::Serialize>> {
        Ok(Some(self))
    }
}

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

    use super::*;

    const RESPONSE_JSON: &str =
        r#"{"code":0,"when":3521,"msg":"ok","desc":"set.device.custom_data"}"#;

    #[test]
    fn request_has_correct_structure() {
        let cmd = SetDeviceCustomData::new("CustomerSn", "CUSTSN-12345");
        assert!(cmd.is_secured());
        assert!(!cmd.is_encrypted());

        let auth = AuthData::new::<SetDeviceCustomData>(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.device.custom_data");
        assert_eq!(json["account"], "super");
        assert!(json["ts"].as_u64().unwrap() > 0);
        assert_eq!(json["token"].as_str().unwrap().len(), 8);
        assert_eq!(json["param"]["key"], "CustomerSn");
        assert_eq!(json["param"]["value"], "CUSTSN-12345");
    }

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