Skip to main content

matter_model/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod json;
4mod schema;
5
6pub use json::{encode_to_vec, from_json, to_json, ConvertError, MAX_DEPTH};
7pub use schema::*;
8
9include!(concat!(env!("OUT_DIR"), "/model.rs"));
10
11/// The cluster with `id`, if the IDL has it.
12pub fn cluster(id: u32) -> Option<&'static Cluster> {
13    CLUSTERS
14        .binary_search_by_key(&id, |c| c.id)
15        .ok()
16        .map(|i| &CLUSTERS[i])
17}
18
19/// The cluster named `name`, compared without case or underscores, so
20/// `OnOff`, `onOff` and `on_off` all find the On/Off cluster.
21pub fn cluster_by_name(name: &str) -> Option<&'static Cluster> {
22    CLUSTERS.iter().find(|c| names_match(c.name, name))
23}
24
25/// Whether two IDL-style names are the same name: ignoring case and `_`.
26pub fn names_match(a: &str, b: &str) -> bool {
27    let mut a = a.bytes().filter(|c| *c != b'_');
28    let mut b = b.bytes().filter(|c| *c != b'_');
29    loop {
30        match (a.next(), b.next()) {
31            (None, None) => return true,
32            (Some(x), Some(y)) if x.eq_ignore_ascii_case(&y) => {}
33            _ => return false,
34        }
35    }
36}
37
38/// The `snake_case` form of an IDL name (`OnOff` and `onOff` give `on_off`),
39/// as used in MQTT topics.
40pub fn snake_case(name: &str) -> String {
41    let mut out = String::with_capacity(name.len() + 4);
42    let bytes = name.as_bytes();
43    for (i, &c) in bytes.iter().enumerate() {
44        if c.is_ascii_uppercase() {
45            let prev_lower =
46                i > 0 && (bytes[i - 1].is_ascii_lowercase() || bytes[i - 1].is_ascii_digit());
47            let next_lower = bytes.get(i + 1).is_some_and(|n| n.is_ascii_lowercase());
48            let prev_upper = i > 0 && bytes[i - 1].is_ascii_uppercase();
49            if i > 0 && (prev_lower || (prev_upper && next_lower)) && !out.ends_with('_') {
50                out.push('_');
51            }
52            out.push(c.to_ascii_lowercase() as char);
53        } else {
54            out.push(c as char);
55        }
56    }
57    out
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn tables_are_sorted_and_complete() {
66        assert!(CLUSTERS.len() > 80, "{} clusters", CLUSTERS.len());
67        assert!(CLUSTERS.windows(2).all(|w| w[0].id < w[1].id));
68        for c in CLUSTERS {
69            assert!(
70                c.attributes.windows(2).all(|w| w[0].id < w[1].id),
71                "{}",
72                c.name
73            );
74            assert!(
75                c.commands.windows(2).all(|w| w[0].id < w[1].id),
76                "{}",
77                c.name
78            );
79        }
80    }
81
82    #[test]
83    fn well_known_clusters() {
84        let on_off = cluster(0x0006).unwrap();
85        assert_eq!(on_off.name, "OnOff");
86        assert_eq!(on_off.command_by_name("toggle").unwrap().id, 2);
87        let level = cluster_by_name("LevelControl").unwrap();
88        let move_to = level.command_by_name("MoveToLevel").unwrap();
89        let req = move_to.request.unwrap();
90        assert_eq!(req.field_by_name("level").unwrap().tag, 0);
91
92        let descriptor = cluster(0x001D).unwrap();
93        let dtl = descriptor.attribute_by_name("DeviceTypeList").unwrap();
94        assert!(dtl.list);
95        assert!(matches!(dtl.ty, Type::Struct(s) if s.name == "DeviceTypeStruct"));
96
97        let basic = cluster(0x0028).unwrap();
98        assert_eq!(basic.attribute(1).unwrap().name, "vendorName");
99        assert!(matches!(basic.attribute(1).unwrap().ty, Type::String));
100
101        let adm = cluster_by_name("AdministratorCommissioning").unwrap();
102        assert!(
103            adm.command_by_name("OpenCommissioningWindow")
104                .unwrap()
105                .timed
106        );
107
108        // Global attributes are in every cluster.
109        assert_eq!(on_off.attribute(0xFFFD).unwrap().name, "clusterRevision");
110    }
111
112    #[test]
113    fn names() {
114        assert!(names_match("OnOff", "on_off"));
115        assert!(names_match("onOff", "ONOFF"));
116        assert!(!names_match("OnOff", "OnOf"));
117        assert_eq!(snake_case("OnOff"), "on_off");
118        assert_eq!(snake_case("onOff"), "on_off");
119        assert_eq!(
120            snake_case("MoveToLevelWithOnOff"),
121            "move_to_level_with_on_off"
122        );
123        assert_eq!(snake_case("currentX"), "current_x");
124        assert_eq!(snake_case("ICDManagement"), "icd_management");
125        assert_eq!(snake_case("measuredValue"), "measured_value");
126    }
127}