1use matter_model::{names_match, snake_case};
6use serde_json::Value;
7
8fn number(s: &str) -> Option<u32> {
10 match s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
11 Some(hex) => u32::from_str_radix(hex, 16).ok(),
12 None => s.parse().ok(),
13 }
14}
15
16fn hex_id(id: u32) -> String {
17 format!("0x{id:04x}")
18}
19
20pub fn cluster(id: u32) -> String {
22 matter_model::cluster(id).map_or_else(|| hex_id(id), |c| snake_case(c.name))
23}
24
25pub fn attribute(cluster: u32, id: u32) -> String {
27 matter_model::cluster(cluster)
28 .and_then(|c| c.attribute(id))
29 .map_or_else(|| hex_id(id), |a| snake_case(a.name))
30}
31
32pub fn event(cluster: u32, id: u32) -> String {
34 matter_model::cluster(cluster)
35 .and_then(|c| c.event(id))
36 .map_or_else(|| hex_id(id), |e| snake_case(e.name))
37}
38
39pub fn parse_cluster(s: &str) -> Option<u32> {
41 number(s).or_else(|| {
42 matter_model::CLUSTERS
43 .iter()
44 .find(|c| names_match(c.name, s))
45 .map(|c| c.id)
46 })
47}
48
49pub fn parse_attribute(cluster: u32, s: &str) -> Option<u32> {
51 number(s).or_else(|| {
52 matter_model::cluster(cluster)?
53 .attribute_by_name(s)
54 .map(|a| a.id)
55 })
56}
57
58pub fn parse_command(cluster: u32, s: &str) -> Option<u32> {
60 number(s).or_else(|| {
61 matter_model::cluster(cluster)?
62 .command_by_name(s)
63 .map(|c| c.id)
64 })
65}
66
67pub fn value_id(v: &Value, parse: impl Fn(&str) -> Option<u32>) -> Option<u32> {
69 match v {
70 Value::Number(n) => n.as_u64().and_then(|n| u32::try_from(n).ok()),
71 Value::String(s) => parse(s),
72 _ => None,
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn segments_round_trip() {
82 assert_eq!(cluster(6), "on_off");
83 assert_eq!(parse_cluster("on_off"), Some(6));
84 assert_eq!(parse_cluster("OnOff"), Some(6));
85 assert_eq!(parse_cluster("0x0006"), Some(6));
86 assert_eq!(attribute(6, 0), "on_off");
87 assert_eq!(parse_attribute(6, "on_off"), Some(0));
88 assert_eq!(parse_command(6, "toggle"), Some(2));
89 assert_eq!(event(0x28, 0), "start_up");
90 assert_eq!(cluster(0xFFF1_FC01), "0xfff1fc01");
91 assert_eq!(parse_cluster("0xfff1fc01"), Some(0xFFF1_FC01));
92 assert_eq!(attribute(0x0402, 0), "measured_value");
93 assert_eq!(cluster(0x0008), "level_control");
94 assert_eq!(attribute(0x0008, 0), "current_level");
95 }
96}