Skip to main content

matter_bridge/
bridge.rs

1//! The bridge: controller events out to MQTT, MQTT requests and commands in
2//! to the controller.
3
4use std::collections::{BTreeSet, HashMap};
5use std::future::Future;
6use std::net::SocketAddr;
7use std::sync::{Arc, RwLock};
8
9use matter_controller::{
10    AttributePath, CommissionRequest, Controller, Event, Networks, Node, WiFi,
11};
12use serde_json::{json, Value};
13
14use crate::config::{Config, MatterConfig};
15use crate::homeassistant::Discovery;
16use crate::mqtt::{self, Incoming, Mqtt};
17use crate::topics;
18
19const ON_OFF: u32 = 0x0006;
20const LEVEL_CONTROL: u32 = 0x0008;
21
22/// Node names, shared by the event loop and request tasks.
23#[derive(Default)]
24struct Names {
25    by_id: HashMap<u64, Node>,
26}
27
28impl Names {
29    fn name(&self, node: u64) -> Option<&str> {
30        self.by_id.get(&node).map(|n| n.name.as_str())
31    }
32
33    /// The node a request or topic names: by name, or by node id.
34    fn find(&self, name: &str) -> Option<u64> {
35        self.by_id
36            .values()
37            .find(|n| n.name == name)
38            .map(|n| n.node_id)
39            .or_else(|| {
40                let id = match name.strip_prefix("0x") {
41                    Some(hex) => u64::from_str_radix(hex, 16).ok(),
42                    None => name.parse().ok(),
43                }?;
44                self.by_id.contains_key(&id).then_some(id)
45            })
46    }
47}
48
49struct Bridge {
50    controller: Controller,
51    mqtt: Mqtt,
52    config: Config,
53    names: Arc<RwLock<Names>>,
54    /// Retained topics published per node, cleared when it goes or is renamed.
55    retained: HashMap<u64, BTreeSet<String>>,
56}
57
58/// Run the bridge until `shutdown` completes.
59pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(), String> {
60    let controller_config = config.controller();
61    let controller = tokio::task::spawn_blocking(move || Controller::start(controller_config))
62        .await
63        .map_err(|e| e.to_string())?
64        .map_err(|e| format!("controller: {e}"))?;
65    let info = controller.info().clone();
66    tracing::info!(
67        fabric = format!("{:016X}", info.fabric_id),
68        node = format!("{:016X}", info.node_id),
69        "controller started"
70    );
71
72    let (mqtt, mut incoming) = mqtt::connect(&config.mqtt)?;
73    let mut events = controller.events();
74
75    let names = Arc::new(RwLock::new(Names::default()));
76    for node in controller.nodes().await.map_err(|e| e.to_string())? {
77        names.write().unwrap().by_id.insert(node.node_id, node);
78    }
79
80    let mut bridge = Bridge {
81        controller,
82        mqtt,
83        config,
84        names,
85        retained: HashMap::new(),
86    };
87
88    tokio::pin!(shutdown);
89    loop {
90        tokio::select! {
91            msg = incoming.recv() => match msg {
92                Some(msg) => bridge.on_mqtt(msg).await,
93                None => break,
94            },
95            event = events.recv() => match event {
96                Some(event) => bridge.on_event(event).await,
97                None => return Err("the controller stopped".into()),
98            },
99            () = &mut shutdown => break,
100        }
101    }
102
103    let base = &bridge.config.mqtt.base_topic;
104    bridge
105        .mqtt
106        .publish(mqtt::state_topic(base), r#"{"state":"offline"}"#, true)
107        .await;
108    bridge.mqtt.disconnect().await;
109    Ok(())
110}
111
112impl Bridge {
113    fn base(&self) -> &str {
114        &self.config.mqtt.base_topic
115    }
116
117    async fn on_mqtt(&mut self, msg: Incoming) {
118        match msg {
119            Incoming::Connected => self.on_connected().await,
120            Incoming::Message { topic, payload } => {
121                if topic == self.config.homeassistant.status_topic {
122                    if payload == b"online" {
123                        self.publish_discovery_all().await;
124                    }
125                    return;
126                }
127                let Some(rest) = topic
128                    .strip_prefix(self.base())
129                    .and_then(|t| t.strip_prefix('/'))
130                else {
131                    return;
132                };
133                let parts: Vec<&str> = rest.split('/').collect();
134                if let ["bridge", "request", name] = parts.as_slice() {
135                    self.spawn_request(name.to_string(), payload);
136                } else {
137                    self.spawn_device_command(
138                        parts.iter().map(|s| s.to_string()).collect(),
139                        payload,
140                    );
141                }
142            }
143        }
144    }
145
146    async fn on_connected(&mut self) {
147        let base = self.base().to_string();
148        for filter in [
149            format!("{base}/bridge/request/+"),
150            format!("{base}/+/+/+/set"),
151            format!("{base}/+/+/+/+/set"),
152            format!("{base}/+/+/+/command/+"),
153        ] {
154            self.mqtt.subscribe(&filter).await;
155        }
156        if self.config.homeassistant.enabled {
157            let status = self.config.homeassistant.status_topic.clone();
158            self.mqtt.subscribe(&status).await;
159        }
160
161        self.mqtt
162            .publish(mqtt::state_topic(&base), r#"{"state":"online"}"#, true)
163            .await;
164        let info = self.controller.info().clone();
165        self.mqtt
166            .publish_json(
167                format!("{base}/bridge/info"),
168                &json!({
169                    "version": env!("CARGO_PKG_VERSION"),
170                    "fabric_id": format!("{:016X}", info.fabric_id),
171                    "compressed_fabric_id": format!("{:016X}", info.compressed_fabric_id),
172                    "node_id": format!("{:016X}", info.node_id),
173                    "vendor_id": info.vendor_id,
174                }),
175                true,
176            )
177            .await;
178        self.publish_devices().await;
179        self.publish_discovery_all().await;
180    }
181
182    async fn publish_devices(&self) {
183        let nodes: Vec<Node> = self.names.read().unwrap().by_id.values().cloned().collect();
184        self.mqtt
185            .publish_json(
186                format!("{}/bridge/devices", self.base()),
187                &serde_json::to_value(nodes).unwrap_or_default(),
188                true,
189            )
190            .await;
191    }
192
193    fn discovery(&self) -> Discovery<'_> {
194        Discovery {
195            prefix: &self.config.homeassistant.discovery_prefix,
196            base: &self.config.mqtt.base_topic,
197            fabric: self.controller.info().compressed_fabric_id,
198        }
199    }
200
201    async fn publish_discovery_all(&mut self) {
202        let nodes: Vec<Node> = self.names.read().unwrap().by_id.values().cloned().collect();
203        for node in nodes {
204            self.publish_discovery(&node).await;
205        }
206    }
207
208    async fn publish_discovery(&mut self, node: &Node) {
209        if !self.config.homeassistant.enabled {
210            return;
211        }
212        for (topic, config) in self.discovery().configs(node) {
213            self.mqtt.publish_json(topic.clone(), &config, true).await;
214            self.retained.entry(node.node_id).or_default().insert(topic);
215        }
216    }
217
218    /// Clear every retained topic of `node`.
219    async fn clear_retained(&mut self, node: u64) {
220        for topic in self.retained.remove(&node).unwrap_or_default() {
221            self.mqtt.publish(topic, Vec::new(), true).await;
222        }
223    }
224
225    async fn publish_retained(&mut self, node: u64, topic: String, payload: Vec<u8>) {
226        self.mqtt.publish(topic.clone(), payload, true).await;
227        self.retained.entry(node).or_default().insert(topic);
228    }
229
230    async fn on_event(&mut self, event: Event) {
231        let base = self.base().to_string();
232        match event {
233            Event::Attribute(a) => {
234                if a.status.is_some() {
235                    return;
236                }
237                let Some(name) = self.names.read().unwrap().name(a.node).map(str::to_string) else {
238                    return;
239                };
240                let topic = format!(
241                    "{base}/{name}/{}/{}/{}",
242                    a.endpoint,
243                    topics::cluster(a.cluster),
244                    topics::attribute(a.cluster, a.attribute)
245                );
246                let payload = serde_json::to_vec(&a.value).unwrap_or_default();
247                self.publish_retained(a.node, topic, payload).await;
248            }
249            Event::Event(e) => {
250                let Some(name) = self.names.read().unwrap().name(e.node).map(str::to_string) else {
251                    return;
252                };
253                let topic = format!(
254                    "{base}/{name}/{}/{}/event/{}",
255                    e.endpoint,
256                    topics::cluster(e.cluster),
257                    topics::event(e.cluster, e.event)
258                );
259                self.mqtt
260                    .publish_json(topic, &json!({"number": e.number, "data": e.data}), false)
261                    .await;
262            }
263            Event::Availability { node, online } => {
264                let name = self.names.read().unwrap().name(node).map(str::to_string);
265                if let Some(name) = name {
266                    let state = if online { "online" } else { "offline" };
267                    self.publish_retained(
268                        node,
269                        format!("{base}/{name}/availability"),
270                        state.into(),
271                    )
272                    .await;
273                }
274                self.publish_bridge_event(
275                    &json!({"type": "availability", "node": node, "online": online}),
276                )
277                .await;
278            }
279            Event::NodeUpdated(node) => {
280                let renamed = self
281                    .names
282                    .read()
283                    .unwrap()
284                    .by_id
285                    .get(&node.node_id)
286                    .is_some_and(|old| old.name != node.name);
287                if renamed {
288                    // Topics carry the name: drop the old ones, the values come
289                    // back under the new name with the next report.
290                    self.clear_retained(node.node_id).await;
291                }
292                self.names
293                    .write()
294                    .unwrap()
295                    .by_id
296                    .insert(node.node_id, node.clone());
297                self.publish_discovery(&node).await;
298                self.publish_devices().await;
299                self.publish_bridge_event(&json!({"type": "node_updated", "node": node}))
300                    .await;
301            }
302            Event::NodeRemoved { node } => {
303                self.clear_retained(node).await;
304                self.names.write().unwrap().by_id.remove(&node);
305                self.publish_devices().await;
306                self.publish_bridge_event(&json!({"type": "node_removed", "node": node}))
307                    .await;
308            }
309            Event::Commissioning { node, step } => {
310                self.publish_bridge_event(
311                    &json!({"type": "commissioning", "node": node, "step": step}),
312                )
313                .await;
314            }
315            Event::CheckIn { node } => {
316                self.publish_bridge_event(&json!({"type": "check_in", "node": node}))
317                    .await;
318            }
319            Event::Ota {
320                node,
321                step,
322                version,
323            } => {
324                self.publish_bridge_event(
325                    &json!({"type": "ota", "node": node, "step": step, "version": version}),
326                )
327                .await;
328            }
329        }
330    }
331
332    async fn publish_bridge_event(&self, event: &Value) {
333        self.mqtt
334            .publish_json(format!("{}/bridge/event", self.base()), event, false)
335            .await;
336    }
337
338    fn spawn_request(&self, name: String, payload: Vec<u8>) {
339        let controller = self.controller.clone();
340        let mqtt = self.mqtt.clone();
341        let names = self.names.clone();
342        let base = self.base().to_string();
343        let matter = self.config.matter.clone();
344        tokio::spawn(async move {
345            let body: Value = if payload.is_empty() {
346                json!({})
347            } else {
348                serde_json::from_slice(&payload).unwrap_or(Value::Null)
349            };
350            let transaction = body.get("transaction").cloned();
351            let result = request(&controller, &names, &name, &body, &matter).await;
352            let mut response = match result {
353                Ok(data) => json!({"status": "ok", "data": data}),
354                Err(error) => {
355                    tracing::warn!(request = %name, %error, "request failed");
356                    json!({"status": "error", "error": error})
357                }
358            };
359            if let Some(t) = transaction {
360                response["transaction"] = t;
361            }
362            mqtt.publish_json(format!("{base}/bridge/response/{name}"), &response, false)
363                .await;
364        });
365    }
366
367    /// `<device>/<endpoint>/<cluster>/set`, `<device>/<endpoint>/<cluster>/<attribute>/set`
368    /// and `<device>/<endpoint>/<cluster>/command/<command>`.
369    fn spawn_device_command(&self, parts: Vec<String>, payload: Vec<u8>) {
370        let controller = self.controller.clone();
371        let mqtt = self.mqtt.clone();
372        let names = self.names.clone();
373        let base = self.base().to_string();
374        tokio::spawn(async move {
375            let topic = parts.join("/");
376            let is_command = parts.len() == 5 && parts[3] == "command";
377            let result = device_command(&controller, &names, &parts, &payload).await;
378            if let Err(error) = &result {
379                tracing::warn!(%topic, %error, "command failed");
380            }
381            if is_command {
382                let response = match result {
383                    Ok(data) => json!({"status": "ok", "data": data}),
384                    Err(error) => json!({"status": "error", "error": error}),
385                };
386                mqtt.publish_json(format!("{base}/{topic}/result"), &response, false)
387                    .await;
388            }
389        });
390    }
391}
392
393/// The networks a device commissioned over Bluetooth may join: a Thread
394/// dataset (`thread_dataset` as hex, or fetched from `thread_dataset_url` or
395/// the configured border router at commissioning time) and Wi-Fi
396/// (`wifi: {ssid, password}`). Neither is kept or logged.
397async fn networks_of(body: &Value, matter: &MatterConfig) -> Result<Networks, String> {
398    let thread_dataset = match body.get("thread_dataset").and_then(Value::as_str) {
399        Some(hex) => Some(hex.to_string()),
400        None => {
401            let url = body
402                .get("thread_dataset_url")
403                .and_then(Value::as_str)
404                .map(str::to_string)
405                .or_else(|| matter.thread_dataset_url.clone());
406            match url {
407                Some(url) => Some(fetch_dataset(url).await?),
408                None => None,
409            }
410        }
411    };
412    let thread_dataset = thread_dataset
413        .map(|hex| matter_controller::network::parse_thread_dataset_hex(&hex))
414        .transpose()
415        .map_err(|e| e.to_string())?;
416    let wifi = match body.get("wifi") {
417        Some(w) => Some(WiFi {
418            ssid: w
419                .get("ssid")
420                .and_then(Value::as_str)
421                .ok_or("`wifi.ssid` is required")?
422                .as_bytes()
423                .to_vec(),
424            credentials: w
425                .get("password")
426                .and_then(Value::as_str)
427                .unwrap_or_default()
428                .as_bytes()
429                .to_vec(),
430        }),
431        None => None,
432    };
433    Ok(Networks {
434        thread_dataset,
435        wifi,
436    })
437}
438
439/// A Thread border router's active dataset, from its REST API (OpenThread's
440/// `GET /node/dataset/active` with `Accept: text/plain` gives it as hex).
441async fn fetch_dataset(url: String) -> Result<String, String> {
442    tokio::task::spawn_blocking(move || {
443        ureq::get(&url)
444            .header("Accept", "text/plain")
445            .call()
446            .and_then(|mut r| r.body_mut().read_to_string())
447            .map_err(|e| format!("the Thread dataset from {url}: {e}"))
448    })
449    .await
450    .map_err(|e| e.to_string())?
451}
452
453fn node_of(names: &RwLock<Names>, body: &Value) -> Result<u64, String> {
454    let name = body
455        .get("device")
456        .and_then(Value::as_str)
457        .ok_or("`device` is required")?;
458    names
459        .read()
460        .unwrap()
461        .find(name)
462        .ok_or_else(|| format!("no device `{name}`"))
463}
464
465fn group_of(body: &Value) -> Result<u16, String> {
466    body.get("group")
467        .and_then(Value::as_u64)
468        .and_then(|g| u16::try_from(g).ok())
469        .filter(|g| *g != 0)
470        .ok_or_else(|| "`group` is required: 1 to 65535".to_string())
471}
472
473fn path_of(body: &Value) -> Result<(u16, u32), String> {
474    let endpoint = body
475        .get("endpoint")
476        .and_then(Value::as_u64)
477        .and_then(|e| u16::try_from(e).ok())
478        .ok_or("`endpoint` is required")?;
479    let cluster = body
480        .get("cluster")
481        .and_then(|v| topics::value_id(v, topics::parse_cluster))
482        .ok_or("`cluster` is required: a name or a number")?;
483    Ok((endpoint, cluster))
484}
485
486fn timed(body: &Value) -> Option<u16> {
487    body.get("timed")
488        .and_then(Value::as_u64)
489        .and_then(|t| u16::try_from(t).ok())
490}
491
492fn named(values: Vec<matter_controller::AttributeValue>) -> Value {
493    values
494        .into_iter()
495        .map(|a| {
496            json!({
497                "endpoint": a.endpoint,
498                "cluster": topics::cluster(a.cluster),
499                "attribute": topics::attribute(a.cluster, a.attribute),
500                "value": a.value,
501                "status": a.status,
502            })
503        })
504        .collect()
505}
506
507async fn request(
508    controller: &Controller,
509    names: &RwLock<Names>,
510    name: &str,
511    body: &Value,
512    matter: &MatterConfig,
513) -> Result<Value, String> {
514    let e = |e: matter_controller::Error| e.to_string();
515    match name {
516        "commission" => {
517            let code = body
518                .get("code")
519                .and_then(Value::as_str)
520                .ok_or("`code` is required: the QR code payload or the manual pairing code")?;
521            let address = match body.get("address").and_then(Value::as_str) {
522                Some(a) => Some(
523                    a.parse::<SocketAddr>()
524                        .map_err(|_| format!("`address` {a} is not ip:port"))?,
525                ),
526                None => None,
527            };
528            let req_name = body.get("name").and_then(Value::as_str).map(str::to_string);
529            if let Some(n) = &req_name {
530                check_name(n)?;
531                if names.read().unwrap().find(n).is_some() {
532                    return Err(format!("the name `{n}` is taken"));
533                }
534            }
535            let timeout = body
536                .get("timeout")
537                .and_then(Value::as_u64)
538                .and_then(|t| u16::try_from(t).ok())
539                .unwrap_or(matter.discovery_timeout);
540            let networks = networks_of(body, matter).await?;
541            let node = controller
542                .commission(CommissionRequest {
543                    code: code.to_string(),
544                    address,
545                    name: req_name,
546                    discovery_timeout: timeout,
547                    networks,
548                })
549                .await
550                .map_err(e)?;
551            Ok(serde_json::to_value(node).unwrap_or_default())
552        }
553        "remove" => {
554            let node = node_of(names, body)?;
555            let force = body.get("force").and_then(Value::as_bool).unwrap_or(false);
556            controller.remove(node, force).await.map_err(e)?;
557            Ok(json!({"node": node}))
558        }
559        "rename" => {
560            let node = node_of(names, body)?;
561            let to = body
562                .get("to")
563                .and_then(Value::as_str)
564                .ok_or("`to` is required")?;
565            check_name(to)?;
566            let node = controller.rename(node, to.to_string()).await.map_err(e)?;
567            Ok(serde_json::to_value(node).unwrap_or_default())
568        }
569        "interview" => {
570            let node = node_of(names, body)?;
571            let node = controller.interview(node).await.map_err(e)?;
572            Ok(serde_json::to_value(node).unwrap_or_default())
573        }
574        "read" => {
575            let node = node_of(names, body)?;
576            let endpoint = body
577                .get("endpoint")
578                .and_then(Value::as_u64)
579                .and_then(|v| u16::try_from(v).ok());
580            let cluster = body
581                .get("cluster")
582                .map(|v| topics::value_id(v, topics::parse_cluster).ok_or("unknown `cluster`"))
583                .transpose()?;
584            let attribute = match (body.get("attribute"), cluster) {
585                (Some(v), Some(c)) => Some(
586                    topics::value_id(v, |s| topics::parse_attribute(c, s))
587                        .ok_or("unknown `attribute`")?,
588                ),
589                (Some(v), None) => Some(
590                    topics::value_id(v, |_| None).ok_or("`attribute` by name needs `cluster`")?,
591                ),
592                (None, _) => None,
593            };
594            let values = controller
595                .read(
596                    node,
597                    AttributePath {
598                        endpoint,
599                        cluster,
600                        attribute,
601                    },
602                )
603                .await
604                .map_err(e)?;
605            Ok(named(values))
606        }
607        "write" => {
608            let node = node_of(names, body)?;
609            let (endpoint, cluster) = path_of(body)?;
610            let attribute = body
611                .get("attribute")
612                .and_then(|v| topics::value_id(v, |s| topics::parse_attribute(cluster, s)))
613                .ok_or("`attribute` is required")?;
614            let value = body.get("value").cloned().ok_or("`value` is required")?;
615            controller
616                .write(node, endpoint, cluster, attribute, value, timed(body))
617                .await
618                .map_err(e)?;
619            Ok(Value::Null)
620        }
621        "invoke" => {
622            let node = node_of(names, body)?;
623            let (endpoint, cluster) = path_of(body)?;
624            let command = body
625                .get("command")
626                .and_then(|v| topics::value_id(v, |s| topics::parse_command(cluster, s)))
627                .ok_or("`command` is required")?;
628            let fields = body.get("fields").cloned().unwrap_or(Value::Null);
629            controller
630                .invoke(node, endpoint, cluster, command, fields, timed(body))
631                .await
632                .map_err(e)
633        }
634        "add_to_group" | "remove_from_group" => {
635            let node = node_of(names, body)?;
636            let endpoint = body
637                .get("endpoint")
638                .and_then(Value::as_u64)
639                .and_then(|e| u16::try_from(e).ok())
640                .ok_or("`endpoint` is required")?;
641            let group = group_of(body)?;
642            if name == "add_to_group" {
643                let label = body
644                    .get("name")
645                    .and_then(Value::as_str)
646                    .unwrap_or_default()
647                    .to_string();
648                controller
649                    .add_to_group(node, endpoint, group, label)
650                    .await
651                    .map_err(e)?;
652            } else {
653                controller
654                    .remove_from_group(node, endpoint, group)
655                    .await
656                    .map_err(e)?;
657            }
658            Ok(Value::Null)
659        }
660        "group_invoke" => {
661            let group = group_of(body)?;
662            let cluster = body
663                .get("cluster")
664                .and_then(|v| topics::value_id(v, topics::parse_cluster))
665                .ok_or("`cluster` is required: a name or a number")?;
666            let command = body
667                .get("command")
668                .and_then(|v| topics::value_id(v, |s| topics::parse_command(cluster, s)))
669                .ok_or("`command` is required")?;
670            let fields = body.get("fields").cloned().unwrap_or(Value::Null);
671            controller
672                .group_invoke(group, cluster, command, fields)
673                .await
674                .map_err(e)?;
675            Ok(Value::Null)
676        }
677        "open_commissioning_window" => {
678            let node = node_of(names, body)?;
679            let timeout = body
680                .get("timeout")
681                .and_then(Value::as_u64)
682                .and_then(|t| u16::try_from(t).ok())
683                .unwrap_or(300);
684            let window = controller
685                .open_commissioning_window(node, timeout)
686                .await
687                .map_err(e)?;
688            Ok(serde_json::to_value(window).unwrap_or_default())
689        }
690        "discover" => {
691            let seconds = body
692                .get("timeout")
693                .and_then(Value::as_u64)
694                .and_then(|t| u16::try_from(t).ok())
695                .unwrap_or(5);
696            let found = controller.discover(seconds).await.map_err(e)?;
697            Ok(serde_json::to_value(found).unwrap_or_default())
698        }
699        "ota_images" => {
700            let images = controller.ota_images().map_err(e)?;
701            Ok(serde_json::to_value(images).unwrap_or_default())
702        }
703        "ota_update" => {
704            let node = node_of(names, body)?;
705            let image = controller.announce_ota(node).await.map_err(e)?;
706            Ok(serde_json::to_value(image).unwrap_or_default())
707        }
708        "devices" => {
709            let nodes = controller.nodes().await.map_err(e)?;
710            Ok(serde_json::to_value(nodes).unwrap_or_default())
711        }
712        other => Err(format!("unknown request `{other}`")),
713    }
714}
715
716/// A node name must work as one topic segment and not shadow the bridge's
717/// own topics.
718fn check_name(name: &str) -> Result<(), String> {
719    if name.is_empty() || name == "bridge" || name.contains(['/', '#', '+']) {
720        return Err(format!(
721            "`{name}` cannot be a name: it must not be empty, `bridge`, or contain /, # or +"
722        ));
723    }
724    Ok(())
725}
726
727async fn device_command(
728    controller: &Controller,
729    names: &RwLock<Names>,
730    parts: &[String],
731    payload: &[u8],
732) -> Result<Value, String> {
733    let e = |e: matter_controller::Error| e.to_string();
734    let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
735    let (device, endpoint, cluster) = match parts.as_slice() {
736        [d, ep, cl, ..] => (*d, *ep, *cl),
737        _ => return Err("not a device topic".into()),
738    };
739    let node = names
740        .read()
741        .unwrap()
742        .find(device)
743        .ok_or_else(|| format!("no device `{device}`"))?;
744    let endpoint: u16 = endpoint
745        .parse()
746        .map_err(|_| format!("`{endpoint}` is not an endpoint number"))?;
747    let cluster =
748        topics::parse_cluster(cluster).ok_or_else(|| format!("no cluster `{cluster}`"))?;
749    let text = String::from_utf8_lossy(payload);
750    let json: Value =
751        serde_json::from_slice(payload).unwrap_or_else(|_| Value::String(text.trim().to_string()));
752
753    match parts.as_slice() {
754        [_, _, _, "set"] => match cluster {
755            ON_OFF => {
756                let command = match &json {
757                    Value::Bool(true) => 1,
758                    Value::Bool(false) => 0,
759                    Value::String(s) if s.eq_ignore_ascii_case("on") => 1,
760                    Value::String(s) if s.eq_ignore_ascii_case("off") => 0,
761                    Value::String(s) if s.eq_ignore_ascii_case("toggle") => 2,
762                    _ => return Err("on_off/set takes ON, OFF or TOGGLE".into()),
763                };
764                controller
765                    .invoke(node, endpoint, ON_OFF, command, Value::Null, None)
766                    .await
767                    .map_err(e)
768            }
769            LEVEL_CONTROL => {
770                let level = json
771                    .as_u64()
772                    .or_else(|| json.as_str().and_then(|s| s.parse().ok()))
773                    .filter(|l| *l <= 254)
774                    .ok_or("level_control/set takes a level, 0 to 254")?;
775                controller
776                    .invoke(
777                        node,
778                        endpoint,
779                        LEVEL_CONTROL,
780                        0x04, // MoveToLevelWithOnOff
781                        json!({"level": level, "optionsMask": 0, "optionsOverride": 0}),
782                        None,
783                    )
784                    .await
785                    .map_err(e)
786            }
787            _ => Err(format!(
788                "{}/set is not supported; set an attribute or invoke a command",
789                topics::cluster(cluster)
790            )),
791        },
792        [_, _, _, attribute, "set"] => {
793            let attribute = topics::parse_attribute(cluster, attribute)
794                .ok_or_else(|| format!("no attribute `{attribute}`"))?;
795            controller
796                .write(node, endpoint, cluster, attribute, json, None)
797                .await
798                .map_err(e)?;
799            Ok(Value::Null)
800        }
801        [_, _, _, "command", command] => {
802            let command = topics::parse_command(cluster, command)
803                .ok_or_else(|| format!("no command `{command}`"))?;
804            let fields = if payload.is_empty() {
805                Value::Null
806            } else {
807                json
808            };
809            controller
810                .invoke(node, endpoint, cluster, command, fields, None)
811                .await
812                .map_err(e)
813        }
814        _ => Err("not a device topic".into()),
815    }
816}
817
818#[cfg(test)]
819mod tests {
820    use super::*;
821
822    #[test]
823    fn names() {
824        assert!(check_name("lamp").is_ok());
825        assert!(check_name("bridge").is_err());
826        assert!(check_name("a/b").is_err());
827        assert!(check_name("").is_err());
828    }
829}