Skip to main content

zwave_host/
device_config.rs

1//! Device configuration files in Z-Wave JS's published format.
2//!
3//! The Z-Wave JS project keeps a library of device files (`@zwave-js/config`,
4//! MIT): each describes devices by manufacturer, product type and product id,
5//! with their configuration parameters, associations and compatibility flags.
6//! This module reads those files as published, without converting them:
7//!
8//! - JSON5 text (comments, trailing commas);
9//! - `$import` of templates: `~/path.json#selector` from the library root,
10//!   `path.json#selector` relative to the importing file, `#selector` within
11//!   it; a selector walks properties and picks parameters by their `#`;
12//!   the imported object is merged where the `$import` key stands, later keys
13//!   overriding it;
14//! - `$if` conditions over `firmwareVersion` and `sdkVersion` (compared as
15//!   versions) and `manufacturerId`, `productType` and `productId`;
16//!   conditional values take the first entry that applies;
17//! - parameters, including partial parameters (`"41[0xf00]"`), associations,
18//!   compatibility flags, endpoints and metadata.
19//!
20//! A [`Library`] reads from a [`Source`]: a directory (the package's
21//! `config/devices`) or an in-memory map of paths to text, such as a single
22//! device's file and the templates it needs.
23
24use serde_json::{Map, Value};
25use std::collections::{BTreeMap, HashMap};
26use std::path::{Component, Path, PathBuf};
27use std::sync::{Arc, Mutex};
28use zwave_cc::{configuration, Command};
29
30/// Largest config file accepted.
31pub const MAX_FILE: usize = 4 * 1024 * 1024;
32/// Deepest chain of `$import`s accepted.
33pub const MAX_IMPORT_DEPTH: usize = 32;
34
35/// A problem with a config file.
36#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
37#[error("{file}: {message}")]
38pub struct ConfigError {
39    /// The file (relative to the library root).
40    pub file: String,
41    /// What is wrong.
42    pub message: String,
43}
44
45fn err(file: &str, message: impl Into<String>) -> ConfigError {
46    ConfigError {
47        file: file.to_string(),
48        message: message.into(),
49    }
50}
51
52/// Where config files come from. Paths are relative to the library root
53/// (the package's `config/devices`), with `/` separators.
54pub trait Source: Send + Sync {
55    /// The text of a file, if it exists.
56    fn read(&self, path: &str) -> Option<String>;
57    /// Every `.json` file's path.
58    fn paths(&self) -> Vec<String>;
59}
60
61/// Files in a directory.
62#[derive(Debug, Clone)]
63pub struct DirSource {
64    root: PathBuf,
65}
66
67impl DirSource {
68    /// The package's `config/devices` directory (or a copy of it).
69    pub fn new(root: impl Into<PathBuf>) -> Self {
70        DirSource { root: root.into() }
71    }
72}
73
74impl Source for DirSource {
75    fn read(&self, path: &str) -> Option<String> {
76        let p = self.root.join(path);
77        let meta = std::fs::metadata(&p).ok()?;
78        if !meta.is_file() || meta.len() as usize > MAX_FILE {
79            return None;
80        }
81        std::fs::read_to_string(p).ok()
82    }
83
84    fn paths(&self) -> Vec<String> {
85        fn walk(dir: &Path, prefix: &str, out: &mut Vec<String>) {
86            let Ok(rd) = std::fs::read_dir(dir) else {
87                return;
88            };
89            let mut entries: Vec<_> = rd.flatten().collect();
90            entries.sort_by_key(|e| e.file_name());
91            for e in entries {
92                let name = e.file_name().to_string_lossy().to_string();
93                let rel = if prefix.is_empty() {
94                    name.clone()
95                } else {
96                    format!("{prefix}/{name}")
97                };
98                match e.file_type() {
99                    Ok(t) if t.is_dir() => walk(&e.path(), &rel, out),
100                    Ok(t) if t.is_file() && name.ends_with(".json") => out.push(rel),
101                    _ => {}
102                }
103            }
104        }
105        let mut out = Vec::new();
106        walk(&self.root, "", &mut out);
107        out
108    }
109}
110
111/// Files held in memory, keyed by path.
112#[derive(Debug, Clone, Default)]
113pub struct MapSource {
114    files: BTreeMap<String, String>,
115}
116
117impl MapSource {
118    /// A source over these files.
119    pub fn new(files: BTreeMap<String, String>) -> Self {
120        MapSource { files }
121    }
122}
123
124impl Source for MapSource {
125    fn read(&self, path: &str) -> Option<String> {
126        self.files
127            .get(path)
128            .filter(|t| t.len() <= MAX_FILE)
129            .cloned()
130    }
131
132    fn paths(&self) -> Vec<String> {
133        self.files
134            .keys()
135            .filter(|k| k.ends_with(".json"))
136            .cloned()
137            .collect()
138    }
139}
140
141/// Joins and normalizes a path inside the library; `None` if it escapes the root.
142fn normalize(base_dir: &str, rel: &str) -> Option<String> {
143    let mut parts: Vec<String> = base_dir
144        .split('/')
145        .filter(|s| !s.is_empty())
146        .map(String::from)
147        .collect();
148    for c in Path::new(rel).components() {
149        match c {
150            Component::Normal(s) => parts.push(s.to_string_lossy().to_string()),
151            Component::ParentDir => {
152                parts.pop()?;
153            }
154            Component::CurDir => {}
155            _ => return None,
156        }
157    }
158    Some(parts.join("/"))
159}
160
161fn dir_of(path: &str) -> &str {
162    path.rsplit_once('/').map(|(d, _)| d).unwrap_or("")
163}
164
165/// Reads device files from a [`Source`], caching parsed files.
166pub struct Library {
167    src: Box<dyn Source>,
168    parsed: Mutex<HashMap<String, Arc<Value>>>,
169}
170
171impl std::fmt::Debug for Library {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.write_str("Library(..)")
174    }
175}
176
177/// The ids a device file is chosen and evaluated by.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct DeviceId {
180    /// Manufacturer id.
181    pub manufacturer_id: u16,
182    /// Product type.
183    pub product_type: u16,
184    /// Product id.
185    pub product_id: u16,
186    /// Firmware version, `major.minor[.patch]`.
187    pub firmware_version: String,
188    /// Z-Wave SDK version, if known.
189    pub sdk_version: Option<String>,
190}
191
192/// One device file's identity, without resolving its imports.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct IndexEntry {
195    /// Path relative to the root.
196    pub path: String,
197    /// Manufacturer id.
198    pub manufacturer_id: u16,
199    /// Product type and product id pairs it covers.
200    pub devices: Vec<(u16, u16)>,
201    /// Firmware range it covers.
202    pub firmware: (String, String),
203    /// Marked `preferred` over other files for the same ids.
204    pub preferred: bool,
205}
206
207fn parse_hex(v: &Value) -> Option<u16> {
208    let s = v.as_str()?;
209    u16::from_str_radix(s.strip_prefix("0x").or(s.strip_prefix("0X"))?, 16).ok()
210}
211
212impl Library {
213    /// A library reading from `src`.
214    pub fn new(src: impl Source + 'static) -> Self {
215        Library {
216            src: Box::new(src),
217            parsed: Mutex::new(HashMap::new()),
218        }
219    }
220
221    fn parse(&self, path: &str) -> Result<Arc<Value>, ConfigError> {
222        if let Some(v) = self.parsed.lock().expect("lock").get(path) {
223            return Ok(v.clone());
224        }
225        let text = self.src.read(path).ok_or_else(|| err(path, "not found"))?;
226        let v: Value = json5::from_str(&text).map_err(|e| err(path, e.to_string()))?;
227        let v = Arc::new(v);
228        // Only templates are worth keeping; device files are read once.
229        if path.contains("templates/") {
230            self.parsed
231                .lock()
232                .expect("lock")
233                .insert(path.to_string(), v.clone());
234        }
235        Ok(v)
236    }
237
238    /// A file with every `$import` resolved (conditions not yet evaluated).
239    pub fn resolve(&self, path: &str) -> Result<Value, ConfigError> {
240        self.resolve_file(path, None, &mut Vec::new())
241    }
242
243    fn resolve_file(
244        &self,
245        path: &str,
246        selector: Option<&str>,
247        stack: &mut Vec<String>,
248    ) -> Result<Value, ConfigError> {
249        let key = format!("{path}#{}", selector.unwrap_or(""));
250        if stack.contains(&key) {
251            return Err(err(
252                path,
253                format!("circular $import: {} -> {key}", stack.join(" -> ")),
254            ));
255        }
256        if stack.len() >= MAX_IMPORT_DEPTH {
257            return Err(err(path, "$import chain too deep"));
258        }
259        let json = self.parse(path)?;
260        let target = match selector {
261            Some(s) => select(&json, s)
262                .ok_or_else(|| err(path, format!("import target #{s} is not an object")))?,
263            None => (*json).clone(),
264        };
265        stack.push(key);
266        let r = self.resolve_imports(target, path, stack);
267        stack.pop();
268        r
269    }
270
271    fn resolve_imports(
272        &self,
273        v: Value,
274        file: &str,
275        stack: &mut Vec<String>,
276    ) -> Result<Value, ConfigError> {
277        match v {
278            Value::Object(m) => {
279                let mut out = Map::new();
280                for (k, val) in m {
281                    if k == "$import" {
282                        let spec = val
283                            .as_str()
284                            .ok_or_else(|| err(file, "$import must be a string"))?;
285                        let (fname, selector) = match spec.split_once('#') {
286                            Some((f, s)) => (f, Some(s)),
287                            None => (spec, None),
288                        };
289                        let target = if fname.is_empty() {
290                            file.to_string()
291                        } else if let Some(rooted) = fname.strip_prefix("~/") {
292                            normalize("", rooted)
293                                .ok_or_else(|| err(file, format!("bad import path {spec}")))?
294                        } else {
295                            normalize(dir_of(file), fname).ok_or_else(|| {
296                                err(file, format!("import {spec} leaves the library"))
297                            })?
298                        };
299                        if !target.ends_with(".json") {
300                            return Err(err(file, format!("bad import {spec}")));
301                        }
302                        let imported =
303                            self.resolve_file(&target, selector.filter(|s| !s.is_empty()), stack)?;
304                        if let Value::Object(im) = imported {
305                            for (ik, iv) in im {
306                                out.insert(ik, iv);
307                            }
308                        }
309                    } else {
310                        out.insert(k, self.resolve_imports(val, file, stack)?);
311                    }
312                }
313                Ok(Value::Object(out))
314            }
315            Value::Array(a) => Ok(Value::Array(
316                a.into_iter()
317                    .map(|x| self.resolve_imports(x, file, stack))
318                    .collect::<Result<_, _>>()?,
319            )),
320            other => Ok(other),
321        }
322    }
323
324    /// Every device file's identity (template files excluded).
325    pub fn index(&self) -> Vec<Result<IndexEntry, ConfigError>> {
326        self.src
327            .paths()
328            .into_iter()
329            .filter(|p| !p.split('/').any(|c| c == "templates") && p.contains('/'))
330            .map(|p| {
331                let v = self.parse(&p)?;
332                let mfr = v
333                    .get("manufacturerId")
334                    .and_then(parse_hex)
335                    .ok_or_else(|| err(&p, "manufacturerId missing"))?;
336                let devices = v
337                    .get("devices")
338                    .and_then(Value::as_array)
339                    .map(|a| {
340                        a.iter()
341                            .filter_map(|d| {
342                                Some((
343                                    d.get("productType").and_then(parse_hex)?,
344                                    d.get("productId").and_then(parse_hex)?,
345                                ))
346                            })
347                            .collect()
348                    })
349                    .unwrap_or_default();
350                let fw = v.get("firmwareVersion");
351                let s = |k: &str| {
352                    fw.and_then(|f| f.get(k))
353                        .and_then(Value::as_str)
354                        .unwrap_or("")
355                        .to_string()
356                };
357                Ok(IndexEntry {
358                    path: p.clone(),
359                    manufacturer_id: mfr,
360                    devices,
361                    firmware: (s("min"), s("max")),
362                    preferred: v.get("preferred").and_then(Value::as_bool).unwrap_or(false),
363                })
364            })
365            .collect()
366    }
367
368    /// Finds the file for a device and evaluates it for its firmware.
369    pub fn lookup(&self, id: &DeviceId) -> Result<Option<DeviceConfig>, ConfigError> {
370        let mut candidates: Vec<IndexEntry> = self
371            .index()
372            .into_iter()
373            .filter_map(Result::ok)
374            .filter(|e| {
375                e.manufacturer_id == id.manufacturer_id
376                    && e.devices.contains(&(id.product_type, id.product_id))
377                    && version_cmp(&id.firmware_version, &e.firmware.0) != std::cmp::Ordering::Less
378                    && version_cmp(&id.firmware_version, &e.firmware.1)
379                        != std::cmp::Ordering::Greater
380            })
381            .collect();
382        candidates.sort_by_key(|e| !e.preferred);
383        match candidates.first() {
384            Some(e) => self.load(&e.path, id).map(Some),
385            None => Ok(None),
386        }
387    }
388
389    /// Loads one file and evaluates it for a device.
390    pub fn load(&self, path: &str, id: &DeviceId) -> Result<DeviceConfig, ConfigError> {
391        let v = self.resolve(path)?;
392        DeviceConfig::from_value(path, &v, id)
393    }
394}
395
396/// Walks a selector: properties, or in arrays the entry whose `#` matches (without its `#`).
397fn select(v: &Value, selector: &str) -> Option<Value> {
398    let mut cur = v.clone();
399    for part in selector.split('/').filter(|s| !s.is_empty()) {
400        cur = match cur {
401            Value::Array(a) => {
402                let mut item = a
403                    .into_iter()
404                    .find(|i| i.get("#").and_then(Value::as_str) == Some(part))?;
405                item.as_object_mut()?.shift_remove("#");
406                item
407            }
408            Value::Object(mut m) => m.shift_remove(part)?,
409            _ => return None,
410        };
411    }
412    cur.is_object().then_some(cur)
413}
414
415// ------------------------------------------------------------------ conditions
416
417/// Compares versions component by component (`1.10` > `1.9`), missing components as 0.
418pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering {
419    let parse = |s: &str| -> Vec<u64> {
420        s.trim()
421            .split('.')
422            .map(|p| p.parse().unwrap_or(0))
423            .collect()
424    };
425    let (mut x, mut y) = (parse(a), parse(b));
426    let n = x.len().max(y.len()).max(3);
427    x.resize(n, 0);
428    y.resize(n, 0);
429    x.cmp(&y)
430}
431
432#[derive(Debug, Clone, PartialEq)]
433enum Tok {
434    Ident(String),
435    Lit(String),
436    Op(&'static str),
437    LParen,
438    RParen,
439}
440
441fn lex(s: &str) -> Option<Vec<Tok>> {
442    let b = s.as_bytes();
443    let mut i = 0;
444    let mut out = Vec::new();
445    while i < b.len() {
446        let c = b[i];
447        if c.is_ascii_whitespace() {
448            i += 1;
449        } else if c == b'(' {
450            out.push(Tok::LParen);
451            i += 1;
452        } else if c == b')' {
453            out.push(Tok::RParen);
454            i += 1;
455        } else if c.is_ascii_alphabetic() {
456            let st = i;
457            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
458                i += 1;
459            }
460            out.push(Tok::Ident(s[st..i].to_string()));
461        } else if c.is_ascii_digit() {
462            let st = i;
463            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'.') {
464                i += 1;
465            }
466            out.push(Tok::Lit(s[st..i].to_string()));
467        } else {
468            let rest = &s[i..];
469            let op = ["===", "!==", ">=", "<=", "&&", "||", ">", "<", "!"]
470                .into_iter()
471                .find(|o| rest.starts_with(o))?;
472            out.push(Tok::Op(op));
473            i += op.len();
474        }
475    }
476    Some(out)
477}
478
479struct Parser<'a> {
480    t: &'a [Tok],
481    i: usize,
482    id: &'a DeviceId,
483}
484
485impl Parser<'_> {
486    fn or(&mut self) -> Option<bool> {
487        let mut v = self.and()?;
488        while self.t.get(self.i) == Some(&Tok::Op("||")) {
489            self.i += 1;
490            let r = self.and()?;
491            v = v || r;
492        }
493        Some(v)
494    }
495    fn and(&mut self) -> Option<bool> {
496        let mut v = self.unary()?;
497        while self.t.get(self.i) == Some(&Tok::Op("&&")) {
498            self.i += 1;
499            let r = self.unary()?;
500            v = v && r;
501        }
502        Some(v)
503    }
504    fn unary(&mut self) -> Option<bool> {
505        match self.t.get(self.i)? {
506            Tok::Op("!") => {
507                self.i += 1;
508                Some(!self.unary()?)
509            }
510            Tok::LParen => {
511                self.i += 1;
512                let v = self.or()?;
513                (self.t.get(self.i)? == &Tok::RParen).then_some(())?;
514                self.i += 1;
515                Some(v)
516            }
517            _ => self.cmp(),
518        }
519    }
520    fn cmp(&mut self) -> Option<bool> {
521        let Tok::Ident(name) = self.t.get(self.i)?.clone() else {
522            return None;
523        };
524        let Tok::Op(op) = *self.t.get(self.i + 1)? else {
525            return None;
526        };
527        let Tok::Lit(lit) = self.t.get(self.i + 2)?.clone() else {
528            return None;
529        };
530        self.i += 3;
531        use std::cmp::Ordering::*;
532        let ord = match name.as_str() {
533            "firmwareVersion" => Some(version_cmp(&self.id.firmware_version, &lit)),
534            // Unknown SDK version: no comparison holds.
535            "sdkVersion" => self.id.sdk_version.as_deref().map(|v| version_cmp(v, &lit)),
536            "manufacturerId" | "productType" | "productId" => {
537                let have = match name.as_str() {
538                    "manufacturerId" => self.id.manufacturer_id,
539                    "productType" => self.id.product_type,
540                    _ => self.id.product_id,
541                };
542                let want = match lit.strip_prefix("0x").or(lit.strip_prefix("0X")) {
543                    Some(h) => u64::from_str_radix(h, 16).ok()?,
544                    None => lit.parse().ok()?,
545                };
546                Some(u64::from(have).cmp(&want))
547            }
548            _ => return None,
549        };
550        let Some(ord) = ord else { return Some(false) };
551        Some(match op {
552            "===" => ord == Equal,
553            "!==" => ord != Equal,
554            ">=" => ord != Less,
555            "<=" => ord != Greater,
556            ">" => ord == Greater,
557            "<" => ord == Less,
558            _ => return None,
559        })
560    }
561}
562
563/// Evaluates a `$if` expression for a device; `Err` for an expression this parser does not understand.
564pub fn evaluate(expr: &str, id: &DeviceId) -> Result<bool, String> {
565    let toks = lex(expr).ok_or_else(|| format!("cannot read condition {expr:?}"))?;
566    let mut p = Parser { t: &toks, i: 0, id };
567    let v = p
568        .or()
569        .ok_or_else(|| format!("cannot read condition {expr:?}"))?;
570    if p.i != toks.len() {
571        return Err(format!("cannot read condition {expr:?}"));
572    }
573    Ok(v)
574}
575
576/// Applies `$if` throughout a value: objects whose condition fails disappear
577/// (from arrays and maps), `$if` keys are removed.
578fn deep(v: &Value, id: &DeviceId, file: &str) -> Result<Option<Value>, ConfigError> {
579    Ok(match v {
580        Value::Object(m) => {
581            if let Some(c) = m.get("$if") {
582                let c = c
583                    .as_str()
584                    .ok_or_else(|| err(file, "$if must be a string"))?;
585                if !evaluate(c, id).map_err(|e| err(file, e))? {
586                    return Ok(None);
587                }
588            }
589            let mut out = Map::new();
590            for (k, x) in m {
591                if k == "$if" {
592                    continue;
593                }
594                if let Some(x) = deep(x, id, file)? {
595                    out.insert(k.clone(), x);
596                }
597            }
598            Some(Value::Object(out))
599        }
600        Value::Array(a) => {
601            let mut out = Vec::new();
602            for x in a {
603                if let Some(x) = deep(x, id, file)? {
604                    out.push(x);
605                }
606            }
607            Some(Value::Array(out))
608        }
609        other => Some(other.clone()),
610    })
611}
612
613/// A conditional primitive: the value itself, or the first applicable entry of
614/// `[{"$if": .., "value": ..}, .., fallback]`.
615fn first_value(v: Option<&Value>, id: &DeviceId, file: &str) -> Result<Option<Value>, ConfigError> {
616    match v {
617        Some(Value::Array(a)) => {
618            for item in a {
619                match item {
620                    Value::Object(m) => {
621                        let ok = match m.get("$if").and_then(Value::as_str) {
622                            Some(c) => evaluate(c, id).map_err(|e| err(file, e))?,
623                            None => true,
624                        };
625                        if ok {
626                            return Ok(m.get("value").cloned());
627                        }
628                    }
629                    other => return Ok(Some(other.clone())),
630                }
631            }
632            Ok(None)
633        }
634        Some(other) => Ok(Some(other.clone())),
635        None => Ok(None),
636    }
637}
638
639/// The first applicable variant of a value that may be an array of conditional objects.
640fn first_object(
641    v: Option<&Value>,
642    id: &DeviceId,
643    file: &str,
644) -> Result<Option<Value>, ConfigError> {
645    match v {
646        Some(Value::Array(a)) => {
647            for item in a {
648                if let Some(x) = deep(item, id, file)? {
649                    return Ok(Some(x));
650                }
651            }
652            Ok(None)
653        }
654        Some(other) => deep(other, id, file),
655        None => Ok(None),
656    }
657}
658
659// --------------------------------------------------------------- evaluated
660
661/// A configuration parameter as the file describes it for this device.
662#[derive(Debug, Clone, PartialEq)]
663pub struct ParamConfig {
664    /// Parameter number.
665    pub parameter: u16,
666    /// Bit mask of a partial parameter.
667    pub mask: Option<u32>,
668    /// The key as written in the file: `"41"` or `"41[0xf00]"`.
669    pub key: String,
670    /// Label.
671    pub label: String,
672    /// Description.
673    pub description: Option<String>,
674    /// Size in bytes: 1, 2 or 4.
675    pub size: u8,
676    /// Minimum value.
677    pub min: i64,
678    /// Maximum value.
679    pub max: i64,
680    /// Default value.
681    pub default: i64,
682    /// The value is unsigned.
683    pub unsigned: bool,
684    /// Cannot be written.
685    pub read_only: bool,
686    /// Cannot be read.
687    pub write_only: bool,
688    /// Values other than the options may be entered.
689    pub allow_manual_entry: bool,
690    /// Named values.
691    pub options: Vec<(i64, String)>,
692    /// Unit.
693    pub unit: Option<String>,
694}
695
696/// An association group.
697#[derive(Debug, Clone, PartialEq, Eq)]
698pub struct AssociationConfig {
699    /// Label.
700    pub label: String,
701    /// Most nodes the group holds.
702    pub max_nodes: u8,
703    /// The lifeline group (reports to the controller).
704    pub is_lifeline: bool,
705    /// Multi Channel association required, if stated.
706    pub multi_channel: Option<bool>,
707}
708
709/// A device file evaluated for one device.
710#[derive(Debug, Clone, PartialEq)]
711pub struct DeviceConfig {
712    /// The file it came from.
713    pub file: String,
714    /// Manufacturer name.
715    pub manufacturer: String,
716    /// Manufacturer id.
717    pub manufacturer_id: u16,
718    /// Product label.
719    pub label: String,
720    /// Product description.
721    pub description: String,
722    /// Product type and id pairs.
723    pub devices: Vec<(u16, u16)>,
724    /// Firmware range.
725    pub firmware: (String, String),
726    /// Association groups.
727    pub associations: BTreeMap<u8, AssociationConfig>,
728    /// Parameters, in file order, keyed as in the file.
729    pub params: Vec<ParamConfig>,
730    /// Compatibility flags (as in the file, conditions applied).
731    pub compat: Option<Value>,
732    /// Endpoint definitions (conditions applied).
733    pub endpoints: Option<Value>,
734    /// Inclusion, exclusion and reset instructions (conditions applied).
735    pub metadata: Option<Value>,
736}
737
738fn int(v: Option<&Value>) -> Option<i64> {
739    match v? {
740        Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)),
741        Value::String(s) => match s.strip_prefix("0x") {
742            Some(h) => i64::from_str_radix(h, 16).ok(),
743            None => s.parse().ok(),
744        },
745        Value::Bool(b) => Some(i64::from(*b)),
746        _ => None,
747    }
748}
749
750fn string(v: Option<Value>) -> Option<String> {
751    match v? {
752        Value::String(s) => Some(s),
753        other => Some(other.to_string()),
754    }
755}
756
757/// Splits `"41[0xf00]"` into the parameter and the mask.
758pub fn parse_param_key(key: &str) -> Option<(u16, Option<u32>)> {
759    match key.split_once('[') {
760        Some((p, m)) => {
761            let m = m.strip_suffix(']')?;
762            let m = u32::from_str_radix(m.strip_prefix("0x").or(m.strip_prefix("0X"))?, 16).ok()?;
763            Some((p.trim().parse().ok()?, Some(m).filter(|&m| m != 0)))
764        }
765        None => Some((key.trim().parse().ok()?, None)),
766    }
767}
768
769impl DeviceConfig {
770    fn from_value(file: &str, v: &Value, id: &DeviceId) -> Result<Self, ConfigError> {
771        let s = |k: &str| -> Result<Option<String>, ConfigError> {
772            Ok(string(first_value(v.get(k), id, file)?))
773        };
774        let manufacturer_id = v
775            .get("manufacturerId")
776            .and_then(parse_hex)
777            .ok_or_else(|| err(file, "manufacturerId missing"))?;
778        let devices = v
779            .get("devices")
780            .and_then(Value::as_array)
781            .map(|a| {
782                a.iter()
783                    .filter_map(|d| {
784                        Some((
785                            d.get("productType").and_then(parse_hex)?,
786                            d.get("productId").and_then(parse_hex)?,
787                        ))
788                    })
789                    .collect()
790            })
791            .unwrap_or_default();
792        let fw = v.get("firmwareVersion");
793        let fs = |k: &str| {
794            fw.and_then(|f| f.get(k))
795                .and_then(Value::as_str)
796                .unwrap_or("")
797                .to_string()
798        };
799
800        let mut associations = BTreeMap::new();
801        if let Some(Value::Object(m)) = v.get("associations") {
802            for (k, a) in m {
803                let Some(a) = first_object(Some(a), id, file)? else {
804                    continue;
805                };
806                let group: u8 = k
807                    .parse()
808                    .map_err(|_| err(file, format!("association group {k}")))?;
809                associations.insert(
810                    group,
811                    AssociationConfig {
812                        label: string(first_value(a.get("label"), id, file)?).unwrap_or_default(),
813                        max_nodes: int(a.get("maxNodes")).unwrap_or(1).clamp(0, 255) as u8,
814                        is_lifeline: a
815                            .get("isLifeline")
816                            .and_then(Value::as_bool)
817                            .unwrap_or(false),
818                        multi_channel: a.get("multiChannel").and_then(Value::as_bool),
819                    },
820                );
821            }
822        }
823
824        // Parameters: the first applicable variant per "#", in file order.
825        let mut params: Vec<ParamConfig> = Vec::new();
826        let mut seen: Vec<String> = Vec::new();
827        if let Some(Value::Array(list)) = v.get("paramInformation") {
828            let mut groups: Vec<(String, Vec<&Value>)> = Vec::new();
829            for p in list {
830                let key = p
831                    .get("#")
832                    .and_then(Value::as_str)
833                    .ok_or_else(|| err(file, "parameter without #"))?
834                    .to_string();
835                match groups.iter_mut().find(|(k, _)| *k == key) {
836                    Some((_, g)) => g.push(p),
837                    None => groups.push((key, vec![p])),
838                }
839            }
840            for (key, variants) in groups {
841                let mut chosen = None;
842                for p in variants {
843                    if let Some(x) = deep(p, id, file)? {
844                        chosen = Some(x);
845                        break;
846                    }
847                }
848                let Some(p) = chosen else { continue };
849                let (parameter, mask) = parse_param_key(&key)
850                    .ok_or_else(|| err(file, format!("bad parameter key {key}")))?;
851                let size = int(p.get("valueSize")).unwrap_or(0);
852                let options: Vec<(i64, String)> = p
853                    .get("options")
854                    .and_then(Value::as_array)
855                    .map(|a| {
856                        a.iter()
857                            .filter_map(|o| {
858                                Some((int(o.get("value"))?, o.get("label")?.as_str()?.to_string()))
859                            })
860                            .collect()
861                    })
862                    .unwrap_or_default();
863                let min = int(p.get("minValue"))
864                    .or_else(|| options.iter().map(|o| o.0).min())
865                    .unwrap_or(0);
866                let max = int(p.get("maxValue"))
867                    .or_else(|| options.iter().map(|o| o.0).max())
868                    .unwrap_or(0);
869                params.push(ParamConfig {
870                    parameter,
871                    mask,
872                    key: key.clone(),
873                    label: string(first_value(p.get("label"), id, file)?).unwrap_or_default(),
874                    description: string(first_value(p.get("description"), id, file)?),
875                    size: size.clamp(0, 4) as u8,
876                    min,
877                    max,
878                    default: int(p.get("defaultValue")).unwrap_or(0),
879                    unsigned: p.get("unsigned").and_then(Value::as_bool).unwrap_or(false),
880                    read_only: p.get("readOnly").and_then(Value::as_bool).unwrap_or(false),
881                    write_only: p.get("writeOnly").and_then(Value::as_bool).unwrap_or(false),
882                    allow_manual_entry: p
883                        .get("allowManualEntry")
884                        .and_then(Value::as_bool)
885                        .unwrap_or(options.is_empty()),
886                    options,
887                    unit: string(first_value(p.get("unit"), id, file)?),
888                });
889                seen.push(key);
890            }
891        }
892        // Partial parameters take their size from the whole parameter's other parts.
893        let sizes: HashMap<u16, u8> = params
894            .iter()
895            .filter(|p| p.size > 0)
896            .map(|p| (p.parameter, p.size))
897            .collect();
898        for p in &mut params {
899            if p.size == 0 {
900                p.size = sizes.get(&p.parameter).copied().unwrap_or(0);
901            }
902        }
903        let mut metadata =
904            deep(v.get("metadata").unwrap_or(&Value::Null), id, file)?.filter(|m| !m.is_null());
905        if let Some(Value::Object(m)) = metadata.as_mut() {
906            let keys: Vec<String> = m.keys().cloned().collect();
907            for k in keys {
908                if let Some(Value::Array(_)) = m.get(&k) {
909                    let raw = v.get("metadata").and_then(|x| x.get(&k)).cloned();
910                    if let Some(val) = first_value(raw.as_ref(), id, file)? {
911                        if !val.is_object() {
912                            m.insert(k, val);
913                        }
914                    }
915                }
916            }
917        }
918        Ok(DeviceConfig {
919            file: file.to_string(),
920            manufacturer: s("manufacturer")?.unwrap_or_default(),
921            manufacturer_id,
922            label: s("label")?.unwrap_or_default(),
923            description: s("description")?.unwrap_or_default(),
924            devices,
925            firmware: (fs("min"), fs("max")),
926            associations,
927            params,
928            compat: first_object(v.get("compat"), id, file)?,
929            endpoints: deep(v.get("endpoints").unwrap_or(&Value::Null), id, file)?
930                .filter(|x| !x.is_null()),
931            metadata,
932        })
933    }
934
935    /// The parameter for a key (`"3"` or `"41[0xf00]"`).
936    pub fn param(&self, key: &str) -> Option<&ParamConfig> {
937        let (n, m) = parse_param_key(key)?;
938        self.params.iter().find(|p| p.parameter == n && p.mask == m)
939    }
940
941    /// The lifeline group, if the file names one.
942    pub fn lifeline(&self) -> Option<u8> {
943        self.associations
944            .iter()
945            .find(|(_, a)| a.is_lifeline)
946            .map(|(g, _)| *g)
947    }
948}
949
950/// Why settings cannot be applied.
951#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
952pub enum SettingsError {
953    /// The file has no such parameter.
954    #[error("unknown parameter {0}")]
955    Unknown(String),
956    /// The parameter cannot be written.
957    #[error("parameter {0} is read-only")]
958    ReadOnly(String),
959    /// Out of the parameter's range.
960    #[error("{key}: {value} is outside {min}..={max}")]
961    OutOfRange {
962        /// Key.
963        key: String,
964        /// Value given.
965        value: i64,
966        /// Minimum.
967        min: i64,
968        /// Maximum.
969        max: i64,
970    },
971    /// The parameter's size is unknown or not 1, 2 or 4.
972    #[error("parameter {0} has no valid size")]
973    Size(String),
974}
975
976/// One parameter write, partials merged.
977#[derive(Debug, Clone, PartialEq, Eq)]
978pub struct ParamWrite {
979    /// Parameter number.
980    pub parameter: u16,
981    /// Size in bytes.
982    pub size: u8,
983    /// The whole value, as the unsigned bit pattern of `size` bytes.
984    pub raw: u32,
985    /// Partial values that need the parameter's current value to merge into.
986    pub needs_current: bool,
987}
988
989impl ParamWrite {
990    /// The Configuration Set command (value as the signed integer the wire carries).
991    pub fn command(&self) -> Command {
992        let value = match self.size {
993            1 => i32::from(self.raw as u8 as i8),
994            2 => i32::from(self.raw as u16 as i16),
995            _ => self.raw as i32,
996        };
997        configuration::Set {
998            parameter: self.parameter as u8,
999            default: false,
1000            size: self.size,
1001            value,
1002        }
1003        .into()
1004    }
1005}
1006
1007/// Plans the writes for settings keyed as in the file (`{"1": 0, "41[0xf00]": 2}`).
1008///
1009/// `current` gives a parameter's current raw value when known; partial
1010/// parameters are merged into it (or into the other parts' defaults).
1011pub fn plan_settings(
1012    cfg: &DeviceConfig,
1013    settings: &[(String, i64)],
1014    current: &dyn Fn(u16) -> Option<u32>,
1015) -> Result<Vec<ParamWrite>, SettingsError> {
1016    let mut writes: BTreeMap<u16, ParamWrite> = BTreeMap::new();
1017    for (key, value) in settings {
1018        let p = cfg
1019            .param(key)
1020            .ok_or_else(|| SettingsError::Unknown(key.clone()))?;
1021        if p.read_only {
1022            return Err(SettingsError::ReadOnly(key.clone()));
1023        }
1024        if (p.min != 0 || p.max != 0) && !p.allow_manual_entry && !p.options.is_empty() {
1025            if !p.options.iter().any(|o| o.0 == *value) {
1026                return Err(SettingsError::OutOfRange {
1027                    key: key.clone(),
1028                    value: *value,
1029                    min: p.min,
1030                    max: p.max,
1031                });
1032            }
1033        } else if (p.min != 0 || p.max != 0) && (*value < p.min || *value > p.max) {
1034            return Err(SettingsError::OutOfRange {
1035                key: key.clone(),
1036                value: *value,
1037                min: p.min,
1038                max: p.max,
1039            });
1040        }
1041        if !matches!(p.size, 1 | 2 | 4) {
1042            return Err(SettingsError::Size(key.clone()));
1043        }
1044        let width_mask: u32 = if p.size == 4 {
1045            u32::MAX
1046        } else {
1047            (1u32 << (8 * u32::from(p.size))) - 1
1048        };
1049        match p.mask {
1050            None => {
1051                writes.insert(
1052                    p.parameter,
1053                    ParamWrite {
1054                        parameter: p.parameter,
1055                        size: p.size,
1056                        raw: (*value as u32) & width_mask,
1057                        needs_current: false,
1058                    },
1059                );
1060            }
1061            Some(mask) => {
1062                let w = writes.entry(p.parameter).or_insert_with(|| {
1063                    let base = current(p.parameter).unwrap_or_else(|| {
1064                        cfg.params
1065                            .iter()
1066                            .filter(|q| q.parameter == p.parameter)
1067                            .filter_map(|q| {
1068                                q.mask
1069                                    .map(|m| ((q.default as u32) << m.trailing_zeros()) & m)
1070                            })
1071                            .fold(0, |a, b| a | b)
1072                    });
1073                    ParamWrite {
1074                        parameter: p.parameter,
1075                        size: p.size,
1076                        raw: base & width_mask,
1077                        needs_current: current(p.parameter).is_none(),
1078                    }
1079                });
1080                let shifted = ((*value as u32) << mask.trailing_zeros()) & mask;
1081                w.raw = (w.raw & !mask) | shifted;
1082            }
1083        }
1084    }
1085    Ok(writes.into_values().collect())
1086}
1087
1088/// The device ids of a node, from its interview.
1089pub fn device_id(rec: &crate::NodeRecord) -> Option<DeviceId> {
1090    let m = rec.manufacturer?;
1091    Some(DeviceId {
1092        manufacturer_id: m.manufacturer_id,
1093        product_type: m.product_type,
1094        product_id: m.product_id,
1095        firmware_version: rec.firmware.clone().unwrap_or_else(|| "0.0".into()),
1096        sdk_version: None,
1097    })
1098}
1099
1100#[cfg(test)]
1101mod tests {
1102    use super::*;
1103
1104    fn id(fw: &str) -> DeviceId {
1105        DeviceId {
1106            manufacturer_id: 0x027a,
1107            product_type: 0x2021,
1108            product_id: 0x2101,
1109            firmware_version: fw.into(),
1110            sdk_version: None,
1111        }
1112    }
1113
1114    #[test]
1115    fn conditions() {
1116        let d = id("32.32");
1117        assert!(evaluate(
1118            "firmwareVersion >= 32.32 || firmwareVersion >= 1.10 && firmwareVersion < 16.9",
1119            &d
1120        )
1121        .unwrap());
1122        assert!(evaluate(
1123            "firmwareVersion >= 1.10 && firmwareVersion < 16.9",
1124            &id("1.10")
1125        )
1126        .unwrap());
1127        assert!(!evaluate("firmwareVersion >= 1.10", &id("1.9")).unwrap());
1128        assert!(evaluate("productType === 0x2021 && productId === 0x2101", &d).unwrap());
1129        assert!(!evaluate("sdkVersion >= 7.0", &d).unwrap());
1130        assert!(evaluate("!(productId === 0x0001)", &d).unwrap());
1131        assert!(evaluate("firmwareVersion = 1", &d).is_err());
1132        assert!(evaluate("bogus > 1", &d).is_err());
1133    }
1134
1135    #[test]
1136    fn keys_and_versions() {
1137        assert_eq!(parse_param_key("41[0xf00]"), Some((41, Some(0xf00))));
1138        assert_eq!(parse_param_key("7"), Some((7, None)));
1139        assert_eq!(version_cmp("1.10", "1.9"), std::cmp::Ordering::Greater);
1140        assert_eq!(version_cmp("2.0", "2.0.0"), std::cmp::Ordering::Equal);
1141    }
1142}