Skip to main content

ghpascon_rust/devices/generic/tcp/
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":"TCP","ip":"192.168.99.202","port":23,"reconnection_time":3}"#;
9
10#[derive(Debug, Clone)]
11pub struct TcpDeviceConfig {
12    pub name: String,
13    pub ip: String,
14    pub port: u16,
15    pub reconnection_time: u64,
16}
17
18impl Default for TcpDeviceConfig {
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 TcpDeviceConfig {
27    fn base() -> Self {
28        Self {
29            name: "TCP".to_string(),
30            ip: "192.168.99.202".to_string(),
31            port: 23,
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.get("host").and_then(Value::as_str) {
45            config.ip = v.to_string();
46        }
47        if let Some(v) = params
48            .get("port")
49            .and_then(Value::as_u64)
50            .and_then(|v| u16::try_from(v).ok())
51        {
52            config.port = v;
53        }
54        if let Some(v) = params.get("reconnection_time").and_then(Value::as_u64) {
55            config.reconnection_time = v;
56        }
57        config
58    }
59
60    pub fn to_map(&self) -> ParamMap {
61        let mut out = HashMap::new();
62        out.insert("name".to_string(), Value::String(self.name.clone()));
63        out.insert("ip".to_string(), Value::String(self.ip.clone()));
64        out.insert("port".to_string(), Value::Number(Number::from(self.port)));
65        out.insert(
66            "reconnection_time".to_string(),
67            Value::Number(Number::from(self.reconnection_time)),
68        );
69        out
70    }
71}