1use crate::frame::{DataFrame, FrameType};
9use crate::function::FunctionId as F;
10use crate::NodeId;
11
12#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14#[error("malformed {0} payload")]
15pub struct Malformed(pub &'static str);
16
17type Result<T> = std::result::Result<T, Malformed>;
18
19fn need(p: &[u8], n: usize, what: &'static str) -> Result<()> {
20 if p.len() < n {
21 Err(Malformed(what))
22 } else {
23 Ok(())
24 }
25}
26
27pub fn node_bytes(node: NodeId, len: usize, out: &mut Vec<u8>) {
29 if len == 2 {
30 out.extend_from_slice(&node.to_be_bytes());
31 } else {
32 out.push(node as u8);
33 }
34}
35
36pub fn parse_node_id(p: &[u8], len: usize) -> Option<NodeId> {
38 node_id(p, 0, len, "node id").ok()
39}
40
41fn node_id(p: &[u8], at: usize, len: usize, what: &'static str) -> Result<NodeId> {
43 need(p, at + len, what)?;
44 Ok(if len == 2 {
45 u16::from_be_bytes([p[at], p[at + 1]])
46 } else {
47 u16::from(p[at])
48 })
49}
50
51pub fn parse_cc_list(p: &[u8]) -> (Vec<u16>, Vec<u16>) {
54 let mut supported = Vec::new();
55 let mut controlled = Vec::new();
56 let mut after_mark = false;
57 let mut i = 0;
58 while i < p.len() {
59 let b = p[i];
60 if b == 0xef {
61 after_mark = true;
62 i += 1;
63 continue;
64 }
65 let cc = if b >= 0xf1 {
66 let Some(&lo) = p.get(i + 1) else { break };
67 i += 2;
68 (u16::from(b) << 8) | u16::from(lo)
69 } else {
70 i += 1;
71 u16::from(b)
72 };
73 if after_mark {
74 controlled.push(cc);
75 } else {
76 supported.push(cc);
77 }
78 }
79 (supported, controlled)
80}
81
82pub fn encode_cc_list(ccs: &[u16], out: &mut Vec<u8>) {
84 for &cc in ccs {
85 if cc > 0xff {
86 out.extend_from_slice(&cc.to_be_bytes());
87 } else {
88 out.push(cc as u8);
89 }
90 }
91}
92
93pub fn parse_node_mask(mask: &[u8], first: NodeId) -> Vec<NodeId> {
95 let mut v = Vec::new();
96 for (i, b) in mask.iter().enumerate() {
97 for bit in 0..8 {
98 if b & (1 << bit) != 0 {
99 v.push(first + (i * 8 + bit) as NodeId);
100 }
101 }
102 }
103 v
104}
105
106pub fn encode_node_mask(nodes: &[NodeId], len: usize) -> Vec<u8> {
108 let mut m = vec![0u8; len];
109 for &n in nodes {
110 let i = usize::from(n.saturating_sub(1));
111 if n >= 1 && i / 8 < len {
112 m[i / 8] |= 1 << (i % 8);
113 }
114 }
115 m
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct SerialApiCapabilities {
121 pub firmware_major: u8,
123 pub firmware_minor: u8,
125 pub manufacturer_id: u16,
127 pub product_type: u16,
129 pub product_id: u16,
131 pub functions: [u8; 32],
133}
134
135impl SerialApiCapabilities {
136 pub fn parse(p: &[u8]) -> Result<Self> {
138 need(p, 8, "serial API capabilities")?;
139 let mut functions = [0u8; 32];
140 let mask = &p[8..p.len().min(40)];
141 functions[..mask.len()].copy_from_slice(mask);
142 Ok(SerialApiCapabilities {
143 firmware_major: p[0],
144 firmware_minor: p[1],
145 manufacturer_id: u16::from_be_bytes([p[2], p[3]]),
146 product_type: u16::from_be_bytes([p[4], p[5]]),
147 product_id: u16::from_be_bytes([p[6], p[7]]),
148 functions,
149 })
150 }
151
152 pub fn encode(&self) -> Vec<u8> {
154 let mut v = vec![self.firmware_major, self.firmware_minor];
155 v.extend_from_slice(&self.manufacturer_id.to_be_bytes());
156 v.extend_from_slice(&self.product_type.to_be_bytes());
157 v.extend_from_slice(&self.product_id.to_be_bytes());
158 v.extend_from_slice(&self.functions);
159 v
160 }
161
162 pub fn supports(&self, f: F) -> bool {
164 let i = usize::from(f.0.wrapping_sub(1));
165 f.0 != 0 && self.functions[i / 8] & (1 << (i % 8)) != 0
166 }
167
168 pub fn mask(functions: &[F]) -> [u8; 32] {
170 let mut m = [0u8; 32];
171 for f in functions {
172 if f.0 != 0 {
173 let i = usize::from(f.0 - 1);
174 m[i / 8] |= 1 << (i % 8);
175 }
176 }
177 m
178 }
179}
180
181#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct InitData {
184 pub api_version: u8,
186 pub capabilities: u8,
188 pub nodes: Vec<NodeId>,
190 pub chip_type: Option<u8>,
192 pub chip_version: Option<u8>,
194}
195
196impl InitData {
197 pub fn is_end_node(&self) -> bool {
199 self.capabilities & 0x01 != 0
200 }
201 pub fn is_secondary(&self) -> bool {
203 self.capabilities & 0x04 != 0
204 }
205 pub fn is_sis(&self) -> bool {
207 self.capabilities & 0x08 != 0
208 }
209
210 pub fn parse(p: &[u8]) -> Result<Self> {
212 need(p, 3, "init data")?;
213 let len = usize::from(p[2]).min(p.len() - 3);
214 let nodes = parse_node_mask(&p[3..3 + len], 1);
215 Ok(InitData {
216 api_version: p[0],
217 capabilities: p[1],
218 nodes,
219 chip_type: p.get(3 + len).copied(),
220 chip_version: p.get(4 + len).copied(),
221 })
222 }
223
224 pub fn encode(&self) -> Vec<u8> {
226 let mut v = vec![self.api_version, self.capabilities, 29];
227 v.extend_from_slice(&encode_node_mask(&self.nodes, 29));
228 v.extend(self.chip_type);
229 v.extend(self.chip_version);
230 v
231 }
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct ControllerVersion {
237 pub version: String,
239 pub library_type: u8,
241}
242
243impl ControllerVersion {
244 pub fn parse(p: &[u8]) -> Result<Self> {
246 let nul = p
247 .iter()
248 .position(|&b| b == 0)
249 .ok_or(Malformed("controller version"))?;
250 let version = String::from_utf8_lossy(&p[..nul]).trim().to_string();
251 Ok(ControllerVersion {
252 version,
253 library_type: p.get(nul + 1).copied().unwrap_or(0),
254 })
255 }
256
257 pub fn encode(&self) -> Vec<u8> {
259 let mut v = self.version.as_bytes().to_vec();
260 v.push(0);
261 v.push(self.library_type);
262 v
263 }
264
265 pub fn library_name(&self) -> &'static str {
267 match self.library_type {
268 0x01 => "static controller",
269 0x02 => "controller",
270 0x03 => "enhanced end node",
271 0x04 => "end node",
272 0x05 => "installer",
273 0x06 => "routing end node",
274 0x07 => "bridge controller",
275 0x08 => "device under test",
276 _ => "unknown",
277 }
278 }
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
283pub struct ControllerId {
284 pub home_id: u32,
286 pub node_id: NodeId,
288}
289
290impl ControllerId {
291 pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
293 need(p, 4 + node_id_len, "controller id")?;
294 Ok(ControllerId {
295 home_id: u32::from_be_bytes([p[0], p[1], p[2], p[3]]),
296 node_id: node_id(p, 4, node_id_len, "controller id")?,
297 })
298 }
299
300 pub fn encode(&self, node_id_len: usize) -> Vec<u8> {
302 let mut v = self.home_id.to_be_bytes().to_vec();
303 node_bytes(self.node_id, node_id_len, &mut v);
304 v
305 }
306}
307
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub struct NodeProtocolInfo {
311 pub listening: bool,
313 pub routing: bool,
315 pub flirs_1000: bool,
317 pub flirs_250: bool,
319 pub beaming: bool,
321 pub controller: bool,
323 pub security: bool,
325 pub protocol_version: u8,
327 pub speeds: u8,
329 pub basic: u8,
331 pub generic: u8,
333 pub specific: u8,
335}
336
337impl NodeProtocolInfo {
338 pub fn reachable(&self) -> bool {
340 self.listening || self.flirs_250 || self.flirs_1000
341 }
342
343 pub fn parse(p: &[u8]) -> Result<Option<Self>> {
345 need(p, 6, "node protocol info")?;
346 if p[3] == 0 && p[4] == 0 {
347 return Ok(None);
348 }
349 let cap = p[0];
350 let sec = p[1];
351 let max_baud = (cap >> 3) & 0x07;
352 let mut speeds = match max_baud {
353 0b010 => 0b011,
354 0b001 => 0b001,
355 _ => 0b001,
356 };
357 if p[2] & 0x01 != 0 {
358 speeds |= 0b100;
359 }
360 Ok(Some(NodeProtocolInfo {
361 listening: cap & 0x80 != 0,
362 routing: cap & 0x40 != 0,
363 flirs_1000: sec & 0x40 != 0,
364 flirs_250: sec & 0x20 != 0,
365 beaming: sec & 0x10 != 0,
366 controller: sec & 0x02 != 0,
367 security: sec & 0x01 != 0,
368 protocol_version: cap & 0x07,
369 speeds,
370 basic: p[3],
371 generic: p[4],
372 specific: p[5],
373 }))
374 }
375
376 pub fn encode(&self) -> Vec<u8> {
378 let cap = (if self.listening { 0x80 } else { 0 })
379 | (if self.routing { 0x40 } else { 0 })
380 | (0b010 << 3)
381 | (self.protocol_version & 0x07);
382 let sec = (if self.flirs_1000 { 0x40 } else { 0 })
383 | (if self.flirs_250 { 0x20 } else { 0 })
384 | (if self.beaming { 0x10 } else { 0 })
385 | (if self.controller { 0x02 } else { 0 })
386 | (if self.security { 0x01 } else { 0 })
387 | 0x04;
388 vec![
389 cap,
390 sec,
391 if self.speeds & 0b100 != 0 { 1 } else { 0 },
392 self.basic,
393 self.generic,
394 self.specific,
395 ]
396 }
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Default)]
401pub struct NodeInfo {
402 pub basic: u8,
404 pub generic: u8,
406 pub specific: u8,
408 pub supported: Vec<u16>,
410 pub controlled: Vec<u16>,
412}
413
414impl NodeInfo {
415 pub fn parse(p: &[u8]) -> Result<Self> {
417 need(p, 3, "node info")?;
418 let (supported, controlled) = parse_cc_list(&p[3..]);
419 Ok(NodeInfo {
420 basic: p[0],
421 generic: p[1],
422 specific: p[2],
423 supported,
424 controlled,
425 })
426 }
427
428 pub fn encode(&self) -> Vec<u8> {
430 let mut v = vec![self.basic, self.generic, self.specific];
431 encode_cc_list(&self.supported, &mut v);
432 if !self.controlled.is_empty() {
433 v.push(0xef);
434 encode_cc_list(&self.controlled, &mut v);
435 }
436 v
437 }
438}
439
440#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
442pub struct RxStatus(pub u8);
443
444impl RxStatus {
445 pub fn low_power(self) -> bool {
447 self.0 & 0x02 != 0
448 }
449 pub fn broadcast(self) -> bool {
451 self.0 & 0x0c == 0x04
452 }
453 pub fn multicast(self) -> bool {
455 self.0 & 0x0c == 0x08
456 }
457 pub fn routed(self) -> bool {
459 self.0 & 0x01 != 0
460 }
461}
462
463#[derive(Debug, Clone, PartialEq, Eq)]
466pub struct ApplicationCommand {
467 pub rx_status: RxStatus,
469 pub source: NodeId,
471 pub destination: Option<NodeId>,
473 pub command: Vec<u8>,
475 pub rssi: Option<i8>,
477}
478
479fn rssi(b: Option<&u8>) -> Option<i8> {
480 b.map(|&v| v as i8).filter(|v| *v < 0x7d)
482}
483
484impl ApplicationCommand {
485 pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
487 need(p, 2 + node_id_len, "application command")?;
488 let source = node_id(p, 1, node_id_len, "application command")?;
489 let at = 1 + node_id_len;
490 let len = usize::from(p[at]);
491 let body = p
492 .get(at + 1..at + 1 + len)
493 .ok_or(Malformed("application command"))?;
494 Ok(ApplicationCommand {
495 rx_status: RxStatus(p[0]),
496 source,
497 destination: None,
498 command: body.to_vec(),
499 rssi: rssi(p.get(at + 1 + len)),
500 })
501 }
502
503 pub fn parse_bridge(p: &[u8], node_id_len: usize) -> Result<Self> {
505 need(p, 2 + 2 * node_id_len, "bridge application command")?;
506 let destination = node_id(p, 1, node_id_len, "bridge application command")?;
507 let source = node_id(
508 p,
509 1 + node_id_len,
510 node_id_len,
511 "bridge application command",
512 )?;
513 let at = 1 + 2 * node_id_len;
514 let len = usize::from(p[at]);
515 let body = p
516 .get(at + 1..at + 1 + len)
517 .ok_or(Malformed("bridge application command"))?;
518 let mut rest = at + 1 + len;
519 if let Some(&mlen) = p.get(rest) {
521 rest += 1 + usize::from(mlen);
522 }
523 Ok(ApplicationCommand {
524 rx_status: RxStatus(p[0]),
525 source,
526 destination: Some(destination),
527 command: body.to_vec(),
528 rssi: rssi(p.get(rest)),
529 })
530 }
531
532 pub fn to_frame(&self, node_id_len: usize) -> DataFrame {
534 let mut v = vec![self.rx_status.0];
535 node_bytes(self.source, node_id_len, &mut v);
536 v.push(self.command.len() as u8);
537 v.extend_from_slice(&self.command);
538 if let Some(r) = self.rssi {
539 v.push(r as u8);
540 }
541 DataFrame::request(F::APPLICATION_COMMAND_HANDLER, v)
542 }
543}
544
545#[derive(Debug, Clone, PartialEq, Eq)]
547pub enum ApplicationUpdate {
548 NodeInfoReceived {
550 node: NodeId,
552 info: NodeInfo,
554 },
555 NodeInfoRequestFailed,
557 SmartStartHomeIdReceived {
559 nwi_home_id: [u8; 4],
561 long_range: bool,
563 info: NodeInfo,
565 },
566 SmartStartIncludedNodeInfo {
568 nwi_home_id: [u8; 4],
570 },
571 NodeAdded {
573 node: NodeId,
575 },
576 NodeRemoved {
578 node: NodeId,
580 },
581 SucIdChanged,
583 Other {
585 kind: u8,
587 },
588}
589
590impl ApplicationUpdate {
591 pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
593 need(p, 1, "application update")?;
594 let kind = p[0];
595 let rest = &p[1..];
596 let node_info = |rest: &[u8]| -> Result<(NodeId, NodeInfo)> {
597 let node = node_id(rest, 0, node_id_len, "node info update")?;
598 let len_at = node_id_len;
599 need(rest, len_at + 1, "node info update")?;
600 let len = usize::from(rest[len_at]);
601 let body = &rest[len_at + 1..rest.len().min(len_at + 1 + len)];
602 Ok((node, NodeInfo::parse(body)?))
603 };
604 Ok(match kind {
605 0x84 => {
606 let (node, info) = node_info(rest)?;
607 ApplicationUpdate::NodeInfoReceived { node, info }
608 }
609 0x81 => ApplicationUpdate::NodeInfoRequestFailed,
610 0x85 | 0x87 => {
611 let at = node_id_len + 1;
613 need(rest, at + 5, "smartstart request")?;
614 let nwi: [u8; 4] = rest[at..at + 4].try_into().expect("4 bytes");
615 let body = &rest[at + 5..];
616 let info = NodeInfo::parse(body).unwrap_or_default();
617 ApplicationUpdate::SmartStartHomeIdReceived {
618 nwi_home_id: nwi,
619 long_range: kind == 0x87,
620 info,
621 }
622 }
623 0x86 => {
624 let at = node_id_len + 1;
625 need(rest, at + 4, "smartstart node info")?;
626 ApplicationUpdate::SmartStartIncludedNodeInfo {
627 nwi_home_id: rest[at..at + 4].try_into().expect("4 bytes"),
628 }
629 }
630 0x40 => ApplicationUpdate::NodeAdded {
631 node: node_id(rest, 0, node_id_len, "node added")?,
632 },
633 0x20 => ApplicationUpdate::NodeRemoved {
634 node: node_id(rest, 0, node_id_len, "node removed")?,
635 },
636 0x10 => ApplicationUpdate::SucIdChanged,
637 k => ApplicationUpdate::Other { kind: k },
638 })
639 }
640
641 pub fn to_frame(&self, node_id_len: usize) -> DataFrame {
643 let zero = |kind: u8| {
644 let mut v = vec![kind];
645 node_bytes(0, node_id_len, &mut v);
646 v
647 };
648 let p = match self {
649 ApplicationUpdate::NodeInfoReceived { node, info } => {
650 let body = info.encode();
651 let mut v = vec![0x84];
652 node_bytes(*node, node_id_len, &mut v);
653 v.push(body.len() as u8);
654 v.extend_from_slice(&body);
655 v
656 }
657 ApplicationUpdate::NodeInfoRequestFailed => {
658 let mut v = zero(0x81);
659 v.push(0);
660 v
661 }
662 ApplicationUpdate::SmartStartHomeIdReceived {
663 nwi_home_id,
664 long_range,
665 info,
666 } => {
667 let body = info.encode();
668 let mut v = zero(if *long_range { 0x87 } else { 0x85 });
669 v.push(0);
670 v.extend_from_slice(nwi_home_id);
671 v.push(body.len().saturating_sub(3) as u8);
672 v.extend_from_slice(&body);
673 v
674 }
675 ApplicationUpdate::SmartStartIncludedNodeInfo { nwi_home_id } => {
676 let mut v = zero(0x86);
677 v.push(0);
678 v.extend_from_slice(nwi_home_id);
679 v
680 }
681 ApplicationUpdate::NodeAdded { node } | ApplicationUpdate::NodeRemoved { node } => {
682 let mut v = vec![if matches!(self, ApplicationUpdate::NodeAdded { .. }) {
683 0x40
684 } else {
685 0x20
686 }];
687 node_bytes(*node, node_id_len, &mut v);
688 v.push(0);
689 v
690 }
691 ApplicationUpdate::SucIdChanged => {
692 let mut v = zero(0x10);
693 v.push(0);
694 v
695 }
696 ApplicationUpdate::Other { kind } => {
697 let mut v = zero(*kind);
698 v.push(0);
699 v
700 }
701 };
702 DataFrame::request(F::APPLICATION_UPDATE, p)
703 }
704}
705
706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
708pub enum TransmitStatus {
709 Ok,
711 NoAck,
713 Fail,
715 NotIdle,
717 NoRoute,
719 Other(u8),
721}
722
723impl TransmitStatus {
724 pub fn from_u8(v: u8) -> Self {
726 match v {
727 0x00 => TransmitStatus::Ok,
728 0x01 => TransmitStatus::NoAck,
729 0x02 => TransmitStatus::Fail,
730 0x03 => TransmitStatus::NotIdle,
731 0x04 => TransmitStatus::NoRoute,
732 o => TransmitStatus::Other(o),
733 }
734 }
735 pub fn to_u8(self) -> u8 {
737 match self {
738 TransmitStatus::Ok => 0,
739 TransmitStatus::NoAck => 1,
740 TransmitStatus::Fail => 2,
741 TransmitStatus::NotIdle => 3,
742 TransmitStatus::NoRoute => 4,
743 TransmitStatus::Other(o) => o,
744 }
745 }
746}
747
748#[derive(Debug, Clone, PartialEq, Eq, Default)]
751pub struct TxReport {
752 pub ticks: u16,
754 pub repeaters: Vec<NodeId>,
756 pub ack_rssi: Option<i8>,
758 pub repeater_rssi: Vec<i8>,
760 pub ack_channel: Option<u8>,
762 pub tx_channel: u8,
764 pub route_scheme: u8,
766 pub speed: u8,
768 pub attempts: u8,
770 pub failed_from: Option<NodeId>,
772 pub failed_to: Option<NodeId>,
774}
775
776impl TxReport {
777 pub fn parse(p: &[u8]) -> Option<Self> {
780 if p.len() < 17 {
781 return None;
782 }
783 let n = usize::from(p[2]).min(4);
784 let repeaters: Vec<NodeId> = p[11..11 + n].iter().map(|&b| NodeId::from(b)).collect();
785 let repeater_rssi = p[4..4 + n]
786 .iter()
787 .map(|&b| b as i8)
788 .filter(|v| *v < 0x7d)
789 .collect();
790 let failed = |i: usize| p.get(i).copied().filter(|&b| b != 0).map(NodeId::from);
791 Some(TxReport {
792 ticks: u16::from_be_bytes([p[0], p[1]]),
793 repeaters,
794 ack_rssi: rssi(p.get(3)),
795 repeater_rssi,
796 ack_channel: Some(p[8]),
797 tx_channel: p[9],
798 route_scheme: p[10],
799 speed: p[15] & 0x07,
800 attempts: p[16],
801 failed_from: failed(17),
802 failed_to: failed(18),
803 })
804 }
805
806 pub fn encode(&self) -> Vec<u8> {
808 let mut v = self.ticks.to_be_bytes().to_vec();
809 v.push(self.repeaters.len() as u8);
810 v.push(self.ack_rssi.map(|r| r as u8).unwrap_or(0x7f));
811 for i in 0..4 {
812 v.push(self.repeater_rssi.get(i).map(|r| *r as u8).unwrap_or(0x7f));
813 }
814 v.push(self.ack_channel.unwrap_or(0));
815 v.push(self.tx_channel);
816 v.push(self.route_scheme);
817 for i in 0..4 {
818 v.push(self.repeaters.get(i).map(|r| *r as u8).unwrap_or(0));
819 }
820 v.push(self.speed);
821 v.push(self.attempts);
822 v.push(self.failed_from.unwrap_or(0) as u8);
823 v.push(self.failed_to.unwrap_or(0) as u8);
824 v
825 }
826}
827
828#[derive(Debug, Clone, PartialEq, Eq)]
830pub struct SendDataResult {
831 pub status: TransmitStatus,
833 pub report: Option<TxReport>,
835}
836
837impl SendDataResult {
838 pub fn parse(p: &[u8]) -> Result<Self> {
840 need(p, 2, "send data callback")?;
841 Ok(SendDataResult {
842 status: TransmitStatus::from_u8(p[1]),
843 report: TxReport::parse(&p[2..]),
844 })
845 }
846}
847
848pub mod tx_options {
850 pub const ACK: u8 = 0x01;
852 pub const LOW_POWER: u8 = 0x02;
854 pub const AUTO_ROUTE: u8 = 0x04;
856 pub const NO_ROUTE: u8 = 0x10;
858 pub const EXPLORE: u8 = 0x20;
860 pub const DEFAULT: u8 = ACK | AUTO_ROUTE | EXPLORE;
862}
863
864pub fn send_data(
866 node: NodeId,
867 node_id_len: usize,
868 command: &[u8],
869 options: u8,
870 callback_id: u8,
871) -> DataFrame {
872 let mut v = Vec::with_capacity(command.len() + 5);
873 node_bytes(node, node_id_len, &mut v);
874 v.push(command.len() as u8);
875 v.extend_from_slice(command);
876 v.push(options);
877 v.push(callback_id);
878 DataFrame::request(F::SEND_DATA, v)
879}
880
881pub mod add_mode {
883 pub const ANY: u8 = 0x01;
885 pub const STOP: u8 = 0x05;
887 pub const SMART_START_DSK: u8 = 0x08;
889 pub const SMART_START_LISTEN: u8 = 0x09;
891 pub const HIGH_POWER: u8 = 0x80;
893 pub const PROTOCOL_LONG_RANGE: u8 = 0x20;
895 pub const NETWORK_WIDE: u8 = 0x40;
897}
898
899#[derive(Debug, Clone, PartialEq, Eq)]
901pub enum AddNodeStatus {
902 Ready,
904 NodeFound,
906 AddingEndNode {
908 node: NodeId,
910 info: NodeInfo,
912 },
913 AddingController {
915 node: NodeId,
917 info: NodeInfo,
919 },
920 ProtocolDone,
922 Done {
924 node: NodeId,
926 },
927 Failed,
929 Other(u8),
931}
932
933impl AddNodeStatus {
934 pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
936 need(p, 2, "add node status")?;
937 let node = || node_id(p, 2, node_id_len, "add node status");
938 let info = || -> Result<NodeInfo> {
939 let at = 2 + node_id_len;
940 need(p, at + 1, "add node status")?;
941 let len = usize::from(p[at]);
942 NodeInfo::parse(&p[at + 1..p.len().min(at + 1 + len)])
943 };
944 Ok(match p[1] {
945 0x01 => AddNodeStatus::Ready,
946 0x02 => AddNodeStatus::NodeFound,
947 0x03 => AddNodeStatus::AddingEndNode {
948 node: node()?,
949 info: info()?,
950 },
951 0x04 => AddNodeStatus::AddingController {
952 node: node()?,
953 info: info()?,
954 },
955 0x05 => AddNodeStatus::ProtocolDone,
956 0x06 => AddNodeStatus::Done {
957 node: node().unwrap_or(0),
958 },
959 0x07 => AddNodeStatus::Failed,
960 o => AddNodeStatus::Other(o),
961 })
962 }
963
964 pub fn to_frame(&self, callback_id: u8, node_id_len: usize) -> DataFrame {
966 let with_info = |status: u8, node: NodeId, info: Option<&NodeInfo>| {
967 let body = info.map(NodeInfo::encode).unwrap_or_default();
968 let mut v = vec![callback_id, status];
969 node_bytes(node, node_id_len, &mut v);
970 v.push(body.len() as u8);
971 v.extend_from_slice(&body);
972 v
973 };
974 let p = match self {
975 AddNodeStatus::Ready => with_info(0x01, 0, None),
976 AddNodeStatus::NodeFound => with_info(0x02, 0, None),
977 AddNodeStatus::AddingEndNode { node, info } => with_info(0x03, *node, Some(info)),
978 AddNodeStatus::AddingController { node, info } => with_info(0x04, *node, Some(info)),
979 AddNodeStatus::ProtocolDone => with_info(0x05, 0, None),
980 AddNodeStatus::Done { node } => with_info(0x06, *node, None),
981 AddNodeStatus::Failed => with_info(0x07, 0, None),
982 AddNodeStatus::Other(o) => with_info(*o, 0, None),
983 };
984 DataFrame::request(F::ADD_NODE_TO_NETWORK, p)
985 }
986}
987
988#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum RemoveNodeStatus {
991 Ready,
993 NodeFound,
995 RemovingEndNode {
997 node: NodeId,
999 },
1000 RemovingController {
1002 node: NodeId,
1004 },
1005 Done {
1007 node: NodeId,
1009 },
1010 Failed,
1012 Other(u8),
1014}
1015
1016impl RemoveNodeStatus {
1017 pub fn parse(p: &[u8], node_id_len: usize) -> Result<Self> {
1019 need(p, 2, "remove node status")?;
1020 let node = || node_id(p, 2, node_id_len, "remove node status").unwrap_or(0);
1021 Ok(match p[1] {
1022 0x01 => RemoveNodeStatus::Ready,
1023 0x02 => RemoveNodeStatus::NodeFound,
1024 0x03 => RemoveNodeStatus::RemovingEndNode { node: node() },
1025 0x04 => RemoveNodeStatus::RemovingController { node: node() },
1026 0x06 => RemoveNodeStatus::Done { node: node() },
1027 0x07 => RemoveNodeStatus::Failed,
1028 o => RemoveNodeStatus::Other(o),
1029 })
1030 }
1031
1032 pub fn to_frame(&self, callback_id: u8, node_id_len: usize) -> DataFrame {
1034 let (s, n) = match *self {
1035 RemoveNodeStatus::Ready => (0x01, 0),
1036 RemoveNodeStatus::NodeFound => (0x02, 0),
1037 RemoveNodeStatus::RemovingEndNode { node } => (0x03, node),
1038 RemoveNodeStatus::RemovingController { node } => (0x04, node),
1039 RemoveNodeStatus::Done { node } => (0x06, node),
1040 RemoveNodeStatus::Failed => (0x07, 0),
1041 RemoveNodeStatus::Other(o) => (o, 0),
1042 };
1043 let mut v = vec![callback_id, s];
1044 node_bytes(n, node_id_len, &mut v);
1045 v.push(0);
1046 DataFrame::request(F::REMOVE_NODE_FROM_NETWORK, v)
1047 }
1048}
1049
1050pub mod setup {
1052 pub const GET_SUPPORTED: u8 = 0x01;
1054 pub const SET_TX_STATUS_REPORT: u8 = 0x02;
1056 pub const GET_RF_REGION: u8 = 0x20;
1058 pub const SET_RF_REGION: u8 = 0x40;
1060 pub const SET_NODE_ID_TYPE: u8 = 0x80;
1062 pub const NODE_ID_SHORT: u8 = 0x01;
1064 pub const NODE_ID_LONG: u8 = 0x02;
1066}
1067
1068#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1070pub enum RfRegion {
1071 Europe,
1073 Usa,
1075 AustraliaNewZealand,
1077 HongKong,
1079 India,
1081 Israel,
1083 Russia,
1085 China,
1087 UsaLongRange,
1089 EuropeLongRange,
1091 Japan,
1093 Korea,
1095 Other(u8),
1097}
1098
1099impl RfRegion {
1100 pub fn from_u8(v: u8) -> Self {
1102 match v {
1103 0x00 => RfRegion::Europe,
1104 0x01 => RfRegion::Usa,
1105 0x02 => RfRegion::AustraliaNewZealand,
1106 0x03 => RfRegion::HongKong,
1107 0x05 => RfRegion::India,
1108 0x06 => RfRegion::Israel,
1109 0x07 => RfRegion::Russia,
1110 0x08 => RfRegion::China,
1111 0x09 => RfRegion::UsaLongRange,
1112 0x0b => RfRegion::EuropeLongRange,
1113 0x20 => RfRegion::Japan,
1114 0x21 => RfRegion::Korea,
1115 o => RfRegion::Other(o),
1116 }
1117 }
1118
1119 pub fn to_u8(self) -> u8 {
1121 match self {
1122 RfRegion::Europe => 0x00,
1123 RfRegion::Usa => 0x01,
1124 RfRegion::AustraliaNewZealand => 0x02,
1125 RfRegion::HongKong => 0x03,
1126 RfRegion::India => 0x05,
1127 RfRegion::Israel => 0x06,
1128 RfRegion::Russia => 0x07,
1129 RfRegion::China => 0x08,
1130 RfRegion::UsaLongRange => 0x09,
1131 RfRegion::EuropeLongRange => 0x0b,
1132 RfRegion::Japan => 0x20,
1133 RfRegion::Korea => 0x21,
1134 RfRegion::Other(o) => o,
1135 }
1136 }
1137}
1138
1139pub fn parse_routing_info(p: &[u8]) -> Result<Vec<NodeId>> {
1141 need(p, 29, "routing info")?;
1142 Ok(parse_node_mask(&p[..29], 1))
1143}
1144
1145pub fn get_routing_info(node: NodeId, node_id_len: usize) -> DataFrame {
1147 let mut v = Vec::with_capacity(5);
1148 node_bytes(node, node_id_len, &mut v);
1149 v.extend_from_slice(&[0, 0, 0]);
1150 DataFrame::request(F::GET_ROUTING_INFO, v)
1151}
1152
1153pub const LONG_RANGE_NODES_PER_SEGMENT: u16 = 1024;
1155
1156pub fn parse_long_range_nodes(p: &[u8]) -> Result<(bool, u8, Vec<NodeId>)> {
1158 need(p, 3, "long range nodes")?;
1159 let segment = p[1];
1160 let len = usize::from(p[2]).min(p.len() - 3).min(128);
1161 let first = 256 + LONG_RANGE_NODES_PER_SEGMENT * NodeId::from(segment);
1162 Ok((p[0] != 0, segment, parse_node_mask(&p[3..3 + len], first)))
1163}
1164
1165pub fn encode_long_range_nodes(more: bool, segment: u8, nodes: &[NodeId]) -> Vec<u8> {
1167 let first = 256 + LONG_RANGE_NODES_PER_SEGMENT * NodeId::from(segment);
1168 let mut mask = vec![0u8; 128];
1169 for &n in nodes {
1170 if n >= first && n < first + LONG_RANGE_NODES_PER_SEGMENT {
1171 let i = usize::from(n - first);
1172 mask[i / 8] |= 1 << (i % 8);
1173 }
1174 }
1175 let mut v = vec![u8::from(more), segment, 128];
1176 v.extend_from_slice(&mask);
1177 v
1178}
1179
1180pub mod nvm {
1182 pub const OPEN: u8 = 0x00;
1184 pub const READ: u8 = 0x01;
1186 pub const WRITE: u8 = 0x02;
1188 pub const CLOSE: u8 = 0x03;
1190 pub const STATUS_OK: u8 = 0x00;
1192 pub const STATUS_EOF: u8 = 0xff;
1194}
1195
1196#[derive(Debug, Clone, PartialEq, Eq)]
1198pub struct NvmResponse {
1199 pub status: u8,
1201 pub offset_or_size: u32,
1203 pub data: Vec<u8>,
1205}
1206
1207impl NvmResponse {
1208 pub fn parse(p: &[u8], extended: bool) -> Result<Self> {
1210 let off_len = if extended { 4 } else { 2 };
1211 need(p, 2, "NVM response")?;
1212 let status = p[0];
1213 let len = usize::from(p[1]);
1214 let offset_or_size = if p.len() >= 2 + off_len {
1215 if extended {
1216 u32::from_be_bytes([p[2], p[3], p[4], p[5]])
1217 } else {
1218 u32::from(u16::from_be_bytes([p[2], p[3]]))
1219 }
1220 } else {
1221 0
1222 };
1223 let start = (2 + off_len).min(p.len());
1224 let data = p[start..p.len().min(start + len)].to_vec();
1225 Ok(NvmResponse {
1226 status,
1227 offset_or_size,
1228 data,
1229 })
1230 }
1231
1232 pub fn encode(&self, extended: bool) -> Vec<u8> {
1234 let mut v = vec![self.status, self.data.len() as u8];
1235 if extended {
1236 v.extend_from_slice(&self.offset_or_size.to_be_bytes());
1237 } else {
1238 v.extend_from_slice(&(self.offset_or_size as u16).to_be_bytes());
1239 }
1240 v.extend_from_slice(&self.data);
1241 v
1242 }
1243}
1244
1245pub fn nvm_request(extended: bool, op: u8, length: u8, offset: u32) -> DataFrame {
1247 let f = if extended {
1248 F::EXTENDED_NVM_OPERATIONS
1249 } else {
1250 F::NVM_OPERATIONS
1251 };
1252 let mut v = vec![op];
1253 if op == nvm::READ {
1254 v.push(length);
1255 if extended {
1256 v.extend_from_slice(&offset.to_be_bytes());
1257 } else {
1258 v.extend_from_slice(&(offset as u16).to_be_bytes());
1259 }
1260 }
1261 DataFrame::request(f, v)
1262}
1263
1264pub fn nvm_write(extended: bool, offset: u32, data: &[u8]) -> DataFrame {
1266 let f = if extended {
1267 F::EXTENDED_NVM_OPERATIONS
1268 } else {
1269 F::NVM_OPERATIONS
1270 };
1271 let mut v = vec![nvm::WRITE, data.len() as u8];
1272 if extended {
1273 v.extend_from_slice(&offset.to_be_bytes());
1274 } else {
1275 v.extend_from_slice(&(offset as u16).to_be_bytes());
1276 }
1277 v.extend_from_slice(data);
1278 DataFrame::request(f, v)
1279}
1280
1281pub fn is_response(f: &DataFrame, function: crate::FunctionId) -> bool {
1283 f.kind == FrameType::Response && f.function == function.0
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288 use super::*;
1289
1290 #[test]
1291 fn capabilities_mask() {
1292 let c = SerialApiCapabilities {
1293 firmware_major: 7,
1294 firmware_minor: 21,
1295 manufacturer_id: 0,
1296 product_type: 4,
1297 product_id: 1,
1298 functions: SerialApiCapabilities::mask(&[
1299 F::SEND_DATA,
1300 F::GET_ROUTING_INFO,
1301 F::NVM_OPERATIONS,
1302 ]),
1303 };
1304 let back = SerialApiCapabilities::parse(&c.encode()).unwrap();
1305 assert!(back.supports(F::SEND_DATA));
1306 assert!(back.supports(F::GET_ROUTING_INFO));
1307 assert!(!back.supports(F::EXTENDED_NVM_OPERATIONS));
1308 assert_eq!(back, c);
1309 }
1310
1311 #[test]
1312 fn init_data_and_masks() {
1313 let d = InitData {
1314 api_version: 9,
1315 capabilities: 0x08,
1316 nodes: vec![1, 2, 5, 232],
1317 chip_type: Some(8),
1318 chip_version: Some(0),
1319 };
1320 let back = InitData::parse(&d.encode()).unwrap();
1321 assert_eq!(back, d);
1322 assert!(back.is_sis());
1323 assert!(InitData::parse(&[1, 2]).is_err());
1324 assert!(InitData::parse(&[1, 2, 200, 0xff]).unwrap().nodes.len() == 8);
1326 }
1327
1328 #[test]
1329 fn cc_list_with_mark_and_extended() {
1330 let (s, c) = parse_cc_list(&[0x5e, 0x25, 0xf1, 0x00, 0xef, 0x20, 0xf2]);
1331 assert_eq!(s, vec![0x5e, 0x25, 0xf100]);
1332 assert_eq!(c, vec![0x20]);
1333 }
1334
1335 #[test]
1336 fn application_command_variants() {
1337 let a = ApplicationCommand {
1338 rx_status: RxStatus(0),
1339 source: 4,
1340 destination: None,
1341 command: vec![0x31, 0x05, 0x01, 0x22, 0x00, 0xe1],
1342 rssi: Some(-60),
1343 };
1344 let f = a.to_frame(1);
1345 assert_eq!(ApplicationCommand::parse(&f.payload, 1).unwrap(), a);
1346 assert!(ApplicationCommand::parse(&[0, 4, 9, 0x20], 1).is_err());
1348 let b = ApplicationCommand::parse_bridge(&[0, 1, 4, 2, 0x20, 0x02, 0, 0xc4], 1).unwrap();
1350 assert_eq!(b.source, 4);
1351 assert_eq!(b.destination, Some(1));
1352 assert_eq!(b.command, vec![0x20, 0x02]);
1353 assert_eq!(b.rssi, Some(-60));
1354 }
1355
1356 #[test]
1357 fn tx_report_roundtrip() {
1358 let r = TxReport {
1359 ticks: 3,
1360 repeaters: vec![7, 9],
1361 ack_rssi: Some(-71),
1362 repeater_rssi: vec![-50, -60],
1363 ack_channel: Some(1),
1364 tx_channel: 1,
1365 route_scheme: 3,
1366 speed: 3,
1367 attempts: 1,
1368 failed_from: None,
1369 failed_to: None,
1370 };
1371 let mut p = vec![0x01, 0x00];
1372 p.extend_from_slice(&r.encode());
1373 let res = SendDataResult::parse(&p).unwrap();
1374 assert_eq!(res.status, TransmitStatus::Ok);
1375 assert_eq!(res.report.unwrap(), r);
1376 assert_eq!(SendDataResult::parse(&[1, 1]).unwrap().report, None);
1377 }
1378
1379 #[test]
1380 fn add_node_status() {
1381 let info = NodeInfo {
1382 basic: 4,
1383 generic: 0x21,
1384 specific: 1,
1385 supported: vec![0x5e, 0x9f],
1386 controlled: vec![],
1387 };
1388 let s = AddNodeStatus::AddingEndNode { node: 7, info };
1389 assert_eq!(
1390 AddNodeStatus::parse(&s.to_frame(3, 1).payload, 1).unwrap(),
1391 s
1392 );
1393 assert_eq!(
1394 AddNodeStatus::parse(&[3, 6, 7, 0], 1).unwrap(),
1395 AddNodeStatus::Done { node: 7 }
1396 );
1397 }
1398
1399 #[test]
1400 fn application_updates() {
1401 let info = NodeInfo {
1402 basic: 4,
1403 generic: 0x07,
1404 specific: 1,
1405 supported: vec![0x5e, 0x71],
1406 controlled: vec![],
1407 };
1408 let u = ApplicationUpdate::NodeInfoReceived {
1409 node: 3,
1410 info: info.clone(),
1411 };
1412 assert_eq!(
1413 ApplicationUpdate::parse(&u.to_frame(1).payload, 1).unwrap(),
1414 u
1415 );
1416 let s = ApplicationUpdate::SmartStartHomeIdReceived {
1417 nwi_home_id: [0xc1, 2, 3, 4],
1418 long_range: false,
1419 info,
1420 };
1421 assert_eq!(
1422 ApplicationUpdate::parse(&s.to_frame(1).payload, 1).unwrap(),
1423 s
1424 );
1425 }
1426
1427 #[test]
1428 fn protocol_info() {
1429 let i = NodeProtocolInfo {
1430 listening: false,
1431 routing: true,
1432 flirs_1000: false,
1433 flirs_250: false,
1434 beaming: true,
1435 controller: false,
1436 security: true,
1437 protocol_version: 3,
1438 speeds: 0b111,
1439 basic: 4,
1440 generic: 0x21,
1441 specific: 1,
1442 };
1443 assert_eq!(NodeProtocolInfo::parse(&i.encode()).unwrap(), Some(i));
1444 assert_eq!(NodeProtocolInfo::parse(&[0; 6]).unwrap(), None);
1445 }
1446
1447 #[test]
1448 fn nvm_responses() {
1449 let r = NvmResponse {
1450 status: 0,
1451 offset_or_size: 0x1000,
1452 data: vec![],
1453 };
1454 assert_eq!(NvmResponse::parse(&r.encode(false), false).unwrap(), r);
1455 let r = NvmResponse {
1456 status: 0xff,
1457 offset_or_size: 0x20,
1458 data: vec![1, 2, 3],
1459 };
1460 assert_eq!(NvmResponse::parse(&r.encode(true), true).unwrap(), r);
1461 }
1462}