1use std::sync::{Arc, Mutex, Weak};
6use std::time::Duration;
7
8use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
9use tokio::sync::{mpsc, oneshot};
10
11use crate::frame::{Decoder, Frame};
12use crate::ids::{command, platform};
13use crate::message::{DecodeError, Request, Response};
14
15#[derive(Debug, Clone, thiserror::Error)]
17pub enum DeconzError {
18 #[error("deCONZ port down: {0}")]
20 Down(String),
21 #[error("no deCONZ reply (is this a ConBee or RaspBee at the right baud rate?)")]
23 NoReply,
24 #[error("no response to deCONZ command {0:#04x}")]
26 Timeout(u8),
27 #[error("deCONZ command {command:#04x} failed with status {status}")]
29 Status {
30 command: u8,
32 status: u8,
34 },
35 #[error("bad deCONZ response: {0}")]
37 Decode(#[from] DecodeError),
38 #[error(
40 "deCONZ firmware {0:#010x} is not supported: update it (ConBee II 0x26580700 or newer)"
41 )]
42 Unsupported(u32),
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct FirmwareVersion(pub u32);
48
49impl FirmwareVersion {
50 pub fn platform(&self) -> u8 {
52 (self.0 >> 8) as u8
53 }
54
55 pub fn product(&self) -> &'static str {
57 match self.platform() {
58 platform::AVR => "ConBee/RaspBee",
59 platform::ARM => "ConBee II/RaspBee II",
60 platform::EFR32 => "ConBee III",
61 _ => "deCONZ",
62 }
63 }
64
65 pub fn is_supported(&self) -> bool {
69 self.0 >= 0x2658_0000 || self.platform() == platform::EFR32
70 }
71
72 pub fn text(&self) -> String {
74 format!("{:#010x}", self.0)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum DeconzEvent {
81 State(u8),
83 Notice(Response),
85 Down(String),
87}
88
89#[derive(Debug, Clone)]
91pub struct ClientConfig {
92 pub response_timeout: Duration,
94 pub version_attempts: u32,
96}
97
98impl Default for ClientConfig {
99 fn default() -> Self {
100 ClientConfig {
101 response_timeout: Duration::from_secs(5),
102 version_attempts: 3,
103 }
104 }
105}
106
107struct Pending {
108 command: u8,
109 seq: u8,
110 reply: oneshot::Sender<Result<Response, DeconzError>>,
111}
112
113struct Inner {
114 write: mpsc::Sender<Vec<u8>>,
115 down: Mutex<Option<String>>,
116 lock: tokio::sync::Mutex<u8>,
117 pending: Mutex<Option<Pending>>,
118 timeout: Duration,
119 _close: oneshot::Sender<()>,
120}
121
122#[derive(Clone)]
124pub struct Deconz {
125 inner: Arc<Inner>,
126 version: FirmwareVersion,
127}
128
129impl std::fmt::Debug for Deconz {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 f.debug_struct("Deconz")
132 .field("version", &self.version.text())
133 .finish_non_exhaustive()
134 }
135}
136
137impl Deconz {
138 pub async fn start<T>(
141 io: T,
142 config: ClientConfig,
143 ) -> Result<(Deconz, mpsc::UnboundedReceiver<DeconzEvent>), DeconzError>
144 where
145 T: AsyncRead + AsyncWrite + Send + 'static,
146 {
147 let (d, events) = Deconz::open(io, config).await?;
148 if !d.version.is_supported() {
149 return Err(DeconzError::Unsupported(d.version.0));
150 }
151 Ok((d, events))
152 }
153
154 pub async fn open<T>(
156 io: T,
157 config: ClientConfig,
158 ) -> Result<(Deconz, mpsc::UnboundedReceiver<DeconzEvent>), DeconzError>
159 where
160 T: AsyncRead + AsyncWrite + Send + 'static,
161 {
162 let (inner, events) = spawn(io, &config);
163 let mut d = Deconz {
164 inner,
165 version: FirmwareVersion(0),
166 };
167 for _ in 0..config.version_attempts.max(1) {
168 match d.request(Request::Version).await {
169 Ok(Response::Version { version }) => {
170 d.version = FirmwareVersion(version);
171 return Ok((d, events));
172 }
173 Err(DeconzError::Timeout(_)) => continue,
174 Err(e) => return Err(e),
175 Ok(_) => continue,
176 }
177 }
178 Err(DeconzError::NoReply)
179 }
180
181 pub fn version(&self) -> FirmwareVersion {
183 self.version
184 }
185
186 pub async fn request(&self, request: Request) -> Result<Response, DeconzError> {
188 let command = request.command();
189 let mut seq = self.inner.lock.lock().await;
190 if let Some(why) = self.inner.down.lock().ok().and_then(|d| d.clone()) {
191 return Err(DeconzError::Down(why));
192 }
193 *seq = seq.wrapping_add(1);
194 let this = *seq;
195 let (tx, rx) = oneshot::channel();
196 if let Ok(mut p) = self.inner.pending.lock() {
197 *p = Some(Pending {
198 command,
199 seq: this,
200 reply: tx,
201 });
202 }
203 tracing::trace!(command, seq = this, "deconz tx");
204 self.inner
205 .write
206 .send(request.encode(this).encode())
207 .await
208 .map_err(|_| DeconzError::Down(self.down_reason()))?;
209 let result = match tokio::time::timeout(self.inner.timeout, rx).await {
210 Ok(Ok(result)) => result,
211 Ok(Err(_)) => Err(DeconzError::Down(self.down_reason())),
212 Err(_) => Err(DeconzError::Timeout(command)),
213 };
214 if let Ok(mut p) = self.inner.pending.lock() {
215 *p = None;
216 }
217 result
218 }
219
220 pub async fn read_parameter(&self, param: u8, extra: &[u8]) -> Result<Vec<u8>, DeconzError> {
222 match self
223 .request(Request::ReadParameter {
224 param,
225 extra: extra.to_vec(),
226 })
227 .await?
228 {
229 Response::ReadParameter { value, .. } => Ok(value),
230 _ => Err(DeconzError::Status {
231 command: command::READ_PARAMETER,
232 status: crate::ids::status::ERROR,
233 }),
234 }
235 }
236
237 pub async fn write_parameter(&self, param: u8, value: &[u8]) -> Result<(), DeconzError> {
239 self.request(Request::WriteParameter {
240 param,
241 value: value.to_vec(),
242 })
243 .await
244 .map(|_| ())
245 }
246
247 fn down_reason(&self) -> String {
248 self.inner
249 .down
250 .lock()
251 .ok()
252 .and_then(|d| d.clone())
253 .unwrap_or_else(|| "port closed".into())
254 }
255}
256
257fn spawn<T>(io: T, config: &ClientConfig) -> (Arc<Inner>, mpsc::UnboundedReceiver<DeconzEvent>)
258where
259 T: AsyncRead + AsyncWrite + Send + 'static,
260{
261 let (read, mut write) = tokio::io::split(io);
262 let (write_tx, mut write_rx) = mpsc::channel::<Vec<u8>>(16);
263 let (close_tx, close_rx) = oneshot::channel();
264 let inner = Arc::new(Inner {
265 write: write_tx,
266 down: Mutex::new(None),
267 lock: tokio::sync::Mutex::new(0),
268 pending: Mutex::new(None),
269 timeout: config.response_timeout,
270 _close: close_tx,
271 });
272 let (event_tx, event_rx) = mpsc::unbounded_channel();
273 tokio::spawn(async move {
274 while let Some(bytes) = write_rx.recv().await {
275 if write.write_all(&bytes).await.is_err() || write.flush().await.is_err() {
276 break;
277 }
278 }
279 });
280 tokio::spawn(reader(Arc::downgrade(&inner), read, close_rx, event_tx));
281 (inner, event_rx)
282}
283
284async fn reader<R>(
285 weak: Weak<Inner>,
286 mut read: R,
287 mut close: oneshot::Receiver<()>,
288 events: mpsc::UnboundedSender<DeconzEvent>,
289) where
290 R: AsyncRead + Unpin,
291{
292 let mut decoder = Decoder::new();
293 let mut buf = [0u8; 256];
294 let reason = loop {
295 let n = tokio::select! {
296 r = read.read(&mut buf) => r,
297 _ = &mut close => return,
298 };
299 let n = match n {
300 Ok(0) => break "port closed".to_string(),
301 Ok(n) => n,
302 Err(e) => break format!("read: {e}"),
303 };
304 let Some(inner) = weak.upgrade() else { return };
305 for frame in decoder.push(buf.get(..n).unwrap_or(&[])) {
306 match frame {
307 Ok(frame) => handle(&inner, frame, &events),
308 Err(e) => tracing::warn!(error = %e, "dropping deCONZ frame"),
309 }
310 }
311 };
312 tracing::warn!(%reason, "deCONZ port down");
313 let Some(inner) = weak.upgrade() else { return };
314 if let Ok(mut d) = inner.down.lock() {
315 *d = Some(reason.clone());
316 }
317 if let Some(p) = inner.pending.lock().ok().and_then(|mut p| p.take()) {
318 let _ = p.reply.send(Err(DeconzError::Down(reason.clone())));
319 }
320 let _ = events.send(DeconzEvent::Down(reason));
321}
322
323fn handle(inner: &Inner, frame: Frame, events: &mpsc::UnboundedSender<DeconzEvent>) {
324 let unsolicited = matches!(
325 frame.command,
326 command::DEVICE_STATE_CHANGED | command::MAC_POLL | command::ZIGBEE_GREEN_POWER
327 );
328 if unsolicited {
329 match Response::decode(&frame) {
330 Ok(r) => {
331 if let Some(s) = r.device_state() {
332 let _ = events.send(DeconzEvent::State(s));
333 }
334 let _ = events.send(DeconzEvent::Notice(r));
335 }
336 Err(e) => tracing::trace!(error = %e, "ignoring deCONZ notice"),
337 }
338 return;
339 }
340 let pending = inner.pending.lock().ok().and_then(|mut p| p.take());
341 let Some(pending) = pending else {
342 tracing::warn!(
343 command = frame.command,
344 seq = frame.seq,
345 "deCONZ response with no request waiting"
346 );
347 return;
348 };
349 if frame.command != pending.command || frame.seq != pending.seq {
350 tracing::warn!(
351 command = frame.command,
352 seq = frame.seq,
353 "deCONZ response for another request"
354 );
355 if let Ok(mut p) = inner.pending.lock() {
356 *p = Some(pending);
357 }
358 return;
359 }
360 let result = if frame.status != crate::ids::status::SUCCESS {
361 Err(DeconzError::Status {
362 command: frame.command,
363 status: frame.status,
364 })
365 } else {
366 Response::decode(&frame).map_err(DeconzError::from)
367 };
368 if let Ok(r) = &result {
369 if let Some(s) = r.device_state() {
370 let _ = events.send(DeconzEvent::State(s));
371 }
372 }
373 let _ = pending.reply.send(result);
374}