Skip to main content

ghpascon_rust/devices/printer/sato/
config.rs

1use std::collections::HashMap;
2
3use serde_json::{Number, Value};
4
5pub type ParamMap = HashMap<String, Value>;
6
7pub const DEFAULT_CONFIG_JSON: &str =
8    r#"{"name":"SATO","ip":"192.168.1.112","port":9100,"reconnection_time":3}"#;
9
10#[derive(Debug, Clone)]
11pub struct SatoConfig {
12    pub name: String,
13    pub ip: String,
14    pub port: u16,
15    pub reconnection_time: u64,
16}
17
18impl Default for SatoConfig {
19    fn default() -> Self {
20        let params: ParamMap =
21            serde_json::from_str(DEFAULT_CONFIG_JSON).expect("DEFAULT_CONFIG_JSON is valid");
22        Self::from_map(params)
23    }
24}
25
26impl SatoConfig {
27    fn base() -> Self {
28        Self {
29            name: "SATO".to_string(),
30            ip: "192.168.1.112".to_string(),
31            port: 9100,
32            reconnection_time: 3,
33        }
34    }
35
36    pub fn from_map(params: ParamMap) -> Self {
37        let mut config = Self::base();
38        if let Some(v) = params.get("name").and_then(Value::as_str) {
39            config.name = v.to_string();
40        }
41        if let Some(v) = params.get("ip").and_then(Value::as_str) {
42            config.ip = v.to_string();
43        }
44        if let Some(v) = params
45            .get("port")
46            .and_then(Value::as_u64)
47            .and_then(|v| u16::try_from(v).ok())
48        {
49            config.port = v;
50        }
51        if let Some(v) = params.get("reconnection_time").and_then(Value::as_u64) {
52            config.reconnection_time = v;
53        }
54        config
55    }
56
57    pub fn to_map(&self) -> ParamMap {
58        let mut out = HashMap::new();
59        out.insert("name".to_string(), Value::String(self.name.clone()));
60        out.insert("ip".to_string(), Value::String(self.ip.clone()));
61        out.insert("port".to_string(), Value::Number(Number::from(self.port)));
62        out.insert(
63            "reconnection_time".to_string(),
64            Value::Number(Number::from(self.reconnection_time)),
65        );
66        out
67    }
68}