ghpascon_rust/devices/generic/serial/
config.rs1use std::collections::HashMap;
2
3use serde_json::{Number, Value};
4
5pub type ParamMap = HashMap<String, Value>;
6
7pub const DEFAULT_CONFIG_JSON: &str = r#"{"name":"SERIAL","port":"AUTO","baudrate":9600,"vid":259,"pid":24673,"reconnection_time":3}"#;
8
9#[derive(Debug, Clone)]
10pub struct SerialDeviceConfig {
11 pub name: String,
12 pub port: String,
13 pub baudrate: u32,
14 pub vid: u16,
15 pub pid: u16,
16 pub reconnection_time: u64,
17}
18
19impl Default for SerialDeviceConfig {
20 fn default() -> Self {
21 let params: ParamMap =
22 serde_json::from_str(DEFAULT_CONFIG_JSON).expect("DEFAULT_CONFIG_JSON is valid");
23 Self::from_map(params)
24 }
25}
26
27impl SerialDeviceConfig {
28 fn base() -> Self {
29 Self {
30 name: "SERIAL".to_string(),
31 port: "AUTO".to_string(),
32 baudrate: 9600,
33 vid: 259,
34 pid: 24673,
35 reconnection_time: 3,
36 }
37 }
38
39 pub fn from_map(params: ParamMap) -> Self {
40 let mut config = Self::base();
41 if let Some(v) = params.get("name").and_then(Value::as_str) {
42 config.name = v.to_string();
43 }
44 if let Some(v) = params.get("port").and_then(Value::as_str) {
45 config.port = v.to_string();
46 }
47 if let Some(v) = params
48 .get("baudrate")
49 .and_then(Value::as_u64)
50 .and_then(|v| u32::try_from(v).ok())
51 {
52 config.baudrate = v;
53 }
54 if let Some(v) = params
55 .get("vid")
56 .and_then(Value::as_u64)
57 .and_then(|v| u16::try_from(v).ok())
58 {
59 config.vid = v;
60 }
61 if let Some(v) = params
62 .get("pid")
63 .and_then(Value::as_u64)
64 .and_then(|v| u16::try_from(v).ok())
65 {
66 config.pid = v;
67 }
68 if let Some(v) = params.get("reconnection_time").and_then(Value::as_u64) {
69 config.reconnection_time = v;
70 }
71 config
72 }
73
74 pub fn to_map(&self) -> ParamMap {
75 let mut out = HashMap::new();
76 out.insert("name".to_string(), Value::String(self.name.clone()));
77 out.insert("port".to_string(), Value::String(self.port.clone()));
78 out.insert(
79 "baudrate".to_string(),
80 Value::Number(Number::from(self.baudrate)),
81 );
82 out.insert("vid".to_string(), Value::Number(Number::from(self.vid)));
83 out.insert("pid".to_string(), Value::Number(Number::from(self.pid)));
84 out.insert(
85 "reconnection_time".to_string(),
86 Value::Number(Number::from(self.reconnection_time)),
87 );
88 out
89 }
90}