1use std::collections::{BTreeMap, HashMap};
5
6use zigbee_primitives::{Ieee, Key, NodeId};
7use zigbee_zcl::foundation::{self, Global, ReadRecord, ReportingConfig, ReportingStatus};
8use zigbee_zcl::{attr, cluster_id, status, DataType, Direction, Frame, FrameType, Value};
9use zigbee_zdo::{Binding, Body, Message, NodeDescriptor, SimpleDescriptor};
10
11#[derive(Debug, Clone)]
13pub struct SimEndpoint {
14 pub endpoint: u8,
16 pub profile_id: u16,
18 pub device_id: u16,
20 pub servers: BTreeMap<u16, BTreeMap<u16, Value>>,
22 pub clients: Vec<u16>,
24}
25
26#[derive(Debug, Clone)]
28pub struct SimDevice {
29 pub ieee: Ieee,
31 pub router: bool,
33 pub sleepy: bool,
35 pub legacy: bool,
37 pub install_code_key: Option<Key>,
39 pub manufacturer_code: u16,
41 pub endpoints: Vec<SimEndpoint>,
43 pub lqi: u8,
45 pub rssi: i8,
47 pub pairing: bool,
49 pub firmware: Option<SimFirmware>,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct SimFirmware {
57 pub image_type: u16,
59 pub file_version: u32,
61 pub image: Vec<u8>,
63}
64
65#[derive(Debug, Clone, Default)]
67pub struct OtaDownload {
68 manufacturer: u16,
69 image_type: u16,
70 file_version: u32,
71 size: u32,
72 data: Vec<u8>,
73}
74
75const OTA_BLOCK: u8 = 48;
76
77fn basic(manufacturer: &str, model: &str, power_source: u8) -> BTreeMap<u16, Value> {
78 BTreeMap::from([
79 (attr::basic::ZCL_VERSION, Value::u8(8)),
80 (attr::basic::APPLICATION_VERSION, Value::u8(1)),
81 (attr::basic::STACK_VERSION, Value::u8(2)),
82 (attr::basic::HW_VERSION, Value::u8(1)),
83 (attr::basic::MANUFACTURER_NAME, Value::string(manufacturer)),
84 (attr::basic::MODEL_IDENTIFIER, Value::string(model)),
85 (attr::basic::DATE_CODE, Value::string("20261119")),
86 (attr::basic::POWER_SOURCE, Value::enum8(power_source)),
87 (attr::basic::SW_BUILD_ID, Value::string("1.0.0")),
88 ])
89}
90
91pub const SIM_MANUFACTURER: &str = "zigbee-bridge-sim";
93
94impl SimDevice {
95 pub fn temperature_humidity_sensor(ieee: Ieee) -> SimDevice {
97 let servers = BTreeMap::from([
98 (cluster_id::BASIC, basic(SIM_MANUFACTURER, "SIM-TH1", 0x03)),
99 (
100 cluster_id::POWER_CONFIGURATION,
101 BTreeMap::from([
102 (attr::power_configuration::BATTERY_VOLTAGE, Value::u8(30)),
103 (
104 attr::power_configuration::BATTERY_PERCENTAGE_REMAINING,
105 Value::u8(200),
106 ),
107 ]),
108 ),
109 (
110 cluster_id::IDENTIFY,
111 BTreeMap::from([(attr::identify::IDENTIFY_TIME, Value::u16(0))]),
112 ),
113 (
114 cluster_id::TEMPERATURE_MEASUREMENT,
115 BTreeMap::from([
116 (
117 attr::temperature_measurement::MEASURED_VALUE,
118 Value::i16(2000),
119 ),
120 (
121 attr::temperature_measurement::MIN_MEASURED_VALUE,
122 Value::i16(-4000),
123 ),
124 (
125 attr::temperature_measurement::MAX_MEASURED_VALUE,
126 Value::i16(12500),
127 ),
128 ]),
129 ),
130 (
131 cluster_id::RELATIVE_HUMIDITY_MEASUREMENT,
132 BTreeMap::from([(
133 attr::relative_humidity_measurement::MEASURED_VALUE,
134 Value::u16(4500),
135 )]),
136 ),
137 ]);
138 SimDevice {
139 ieee,
140 router: false,
141 sleepy: true,
142 legacy: false,
143 install_code_key: None,
144 manufacturer_code: 0x1234,
145 endpoints: vec![SimEndpoint {
146 endpoint: 1,
147 profile_id: 0x0104,
148 device_id: 0x0302,
149 servers,
150 clients: vec![cluster_id::OTA_UPGRADE],
151 }],
152 lqi: 180,
153 rssi: -58,
154 pairing: true,
155 firmware: None,
156 }
157 }
158
159 pub fn plug(ieee: Ieee) -> SimDevice {
161 let servers = BTreeMap::from([
162 (
163 cluster_id::BASIC,
164 basic(SIM_MANUFACTURER, "SIM-PLUG1", 0x01),
165 ),
166 (
167 cluster_id::IDENTIFY,
168 BTreeMap::from([(attr::identify::IDENTIFY_TIME, Value::u16(0))]),
169 ),
170 (
171 cluster_id::GROUPS,
172 BTreeMap::from([(attr::groups::NAME_SUPPORT, Value::map8(0))]),
173 ),
174 (
175 cluster_id::ON_OFF,
176 BTreeMap::from([(attr::on_off::ON_OFF, Value::bool(false))]),
177 ),
178 (
179 cluster_id::ELECTRICAL_MEASUREMENT,
180 BTreeMap::from([
181 (
182 attr::electrical_measurement::ACTIVE_POWER,
183 Value::Int(DataType::Int16, 0),
184 ),
185 (attr::electrical_measurement::RMS_VOLTAGE, Value::u16(230)),
186 (
187 attr::electrical_measurement::AC_POWER_MULTIPLIER,
188 Value::u16(1),
189 ),
190 (
191 attr::electrical_measurement::AC_POWER_DIVISOR,
192 Value::u16(1),
193 ),
194 ]),
195 ),
196 ]);
197 SimDevice {
198 ieee,
199 router: true,
200 sleepy: false,
201 legacy: false,
202 install_code_key: None,
203 manufacturer_code: 0x1234,
204 endpoints: vec![SimEndpoint {
205 endpoint: 1,
206 profile_id: 0x0104,
207 device_id: 0x0051,
208 servers,
209 clients: vec![cluster_id::OTA_UPGRADE],
210 }],
211 lqi: 230,
212 rssi: -40,
213 pairing: true,
214 firmware: Some(SimFirmware {
215 image_type: 0x0001,
216 file_version: 0x0100_0000,
217 image: Vec::new(),
218 }),
219 }
220 }
221
222 pub fn contact_sensor(ieee: Ieee) -> SimDevice {
224 let servers = BTreeMap::from([
225 (
226 cluster_id::BASIC,
227 basic(SIM_MANUFACTURER, "SIM-DOOR1", 0x03),
228 ),
229 (
230 cluster_id::POWER_CONFIGURATION,
231 BTreeMap::from([(
232 attr::power_configuration::BATTERY_PERCENTAGE_REMAINING,
233 Value::u8(180),
234 )]),
235 ),
236 (
237 cluster_id::IAS_ZONE,
238 BTreeMap::from([
239 (attr::ias_zone::ZONE_STATE, Value::enum8(0)),
240 (attr::ias_zone::ZONE_TYPE, Value::enum16(0x0015)),
241 (attr::ias_zone::ZONE_STATUS, Value::map16(0)),
242 (attr::ias_zone::IAS_CIE_ADDRESS, Value::Ieee(Ieee::ZERO)),
243 (attr::ias_zone::ZONE_ID, Value::u8(0xFF)),
244 ]),
245 ),
246 ]);
247 SimDevice {
248 ieee,
249 router: false,
250 sleepy: true,
251 legacy: false,
252 install_code_key: None,
253 manufacturer_code: 0x1234,
254 endpoints: vec![SimEndpoint {
255 endpoint: 1,
256 profile_id: 0x0104,
257 device_id: 0x0402,
258 servers,
259 clients: vec![],
260 }],
261 lqi: 150,
262 rssi: -70,
263 pairing: true,
264 firmware: None,
265 }
266 }
267
268 fn node_descriptor(&self) -> NodeDescriptor {
269 let (logical, mac) = if self.router {
270 (1, 0x8E)
271 } else if self.sleepy {
272 (2, 0x80)
273 } else {
274 (2, 0x88)
275 };
276 NodeDescriptor {
277 byte0: logical,
278 byte1: 0x40,
279 mac_capabilities: mac,
280 manufacturer_code: self.manufacturer_code,
281 max_buffer_size: 82,
282 max_incoming_transfer: 82,
283 server_mask: 22 << 9,
284 max_outgoing_transfer: 82,
285 descriptor_capability: 0,
286 }
287 }
288
289 fn simple_descriptor(&self, endpoint: u8) -> Option<SimpleDescriptor> {
290 self.endpoints
291 .iter()
292 .find(|e| e.endpoint == endpoint)
293 .map(|e| SimpleDescriptor {
294 endpoint: e.endpoint,
295 profile_id: e.profile_id,
296 device_id: e.device_id,
297 device_version: 1,
298 input_clusters: e.servers.keys().copied().collect(),
299 output_clusters: e.clients.clone(),
300 })
301 }
302}
303
304#[derive(Debug, Clone, Default)]
306pub struct DeviceState {
307 pub bindings: Vec<Binding>,
309 pub reporting: HashMap<(u8, u16, u16), ReportingConfig>,
311 pub seq: u8,
313 pub ias_enrolled: bool,
315 pub ota: Option<OtaDownload>,
317}
318
319#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct Outgoing {
322 pub profile: u16,
324 pub cluster: u16,
326 pub source_endpoint: u8,
328 pub destination_endpoint: u8,
330 pub payload: Vec<u8>,
332}
333
334#[derive(Debug, Default)]
336pub struct Reaction {
337 pub replies: Vec<Outgoing>,
339 pub leave: bool,
341}
342
343impl SimDevice {
344 pub fn handle_zdo(
346 &self,
347 nwk: NodeId,
348 state: &mut DeviceState,
349 cluster: u16,
350 payload: &[u8],
351 coordinator: Ieee,
352 ) -> Reaction {
353 let mut reaction = Reaction::default();
354 let Ok(request) = Message::parse(cluster, payload) else {
355 return reaction;
356 };
357 let body = match request.body {
358 Body::NodeDescReq { .. } => Body::NodeDescRsp {
359 status: 0,
360 nwk,
361 descriptor: Some(self.node_descriptor()),
362 },
363 Body::ActiveEpReq { .. } => Body::ActiveEpRsp {
364 status: 0,
365 nwk,
366 endpoints: self.endpoints.iter().map(|e| e.endpoint).collect(),
367 },
368 Body::SimpleDescReq { endpoint, .. } => match self.simple_descriptor(endpoint) {
369 Some(d) => Body::SimpleDescRsp {
370 status: 0,
371 nwk,
372 descriptor: Some(d),
373 },
374 None => Body::SimpleDescRsp {
375 status: zigbee_zdo::status::INVALID_EP,
376 nwk,
377 descriptor: None,
378 },
379 },
380 Body::BindReq(binding) => {
381 let ok = binding.source == self.ieee
382 && self
383 .endpoints
384 .iter()
385 .any(|e| e.endpoint == binding.source_endpoint);
386 if ok && !state.bindings.contains(&binding) {
387 state.bindings.push(binding);
388 }
389 Body::BindRsp {
390 status: if ok {
391 0
392 } else {
393 zigbee_zdo::status::NOT_SUPPORTED
394 },
395 }
396 }
397 Body::UnbindReq(binding) => {
398 let before = state.bindings.len();
399 state.bindings.retain(|b| *b != binding);
400 Body::UnbindRsp {
401 status: if state.bindings.len() < before {
402 0
403 } else {
404 zigbee_zdo::status::NO_ENTRY
405 },
406 }
407 }
408 Body::MgmtLeaveReq { ieee, .. } if ieee == self.ieee || ieee == Ieee::ZERO => {
409 reaction.leave = true;
410 Body::MgmtLeaveRsp { status: 0 }
411 }
412 Body::MgmtLqiReq { .. } => Body::MgmtLqiRsp {
413 status: 0,
414 total: 1,
415 start_index: 0,
416 neighbors: vec![zigbee_zdo::Neighbor {
417 extended_pan_id: zigbee_primitives::ExtPanId(0),
418 ieee: coordinator,
419 nwk: 0,
420 flags: 0x04,
421 permit_joining: 2,
422 depth: 0,
423 lqi: self.lqi,
424 }],
425 },
426 Body::MgmtRtgReq { start_index } if self.router => Body::MgmtRtgRsp {
428 status: 0,
429 total: 1,
430 start_index,
431 routes: if start_index == 0 {
432 vec![zigbee_zdo::Route {
433 destination: 0x0000,
434 flags: 0,
435 next_hop: 0x0000,
436 }]
437 } else {
438 Vec::new()
439 },
440 },
441 Body::MgmtRtgReq { start_index } => Body::MgmtRtgRsp {
442 status: zigbee_zdo::status::NOT_SUPPORTED,
443 total: 0,
444 start_index,
445 routes: Vec::new(),
446 },
447 Body::MgmtPermitJoiningReq { .. } => Body::MgmtPermitJoiningRsp { status: 0 },
448 Body::IeeeAddrReq { .. } => Body::IeeeAddrRsp {
449 status: 0,
450 ieee: self.ieee,
451 nwk,
452 associated: None,
453 },
454 Body::NwkAddrReq { .. } => Body::NwkAddrRsp {
455 status: 0,
456 ieee: self.ieee,
457 nwk,
458 associated: None,
459 },
460 _ => return reaction,
461 };
462 let (cluster, payload) = Message {
463 tsn: request.tsn,
464 body,
465 }
466 .encode();
467 reaction.replies.push(Outgoing {
468 profile: 0,
469 cluster,
470 source_endpoint: 0,
471 destination_endpoint: 0,
472 payload,
473 });
474 reaction
475 }
476
477 fn handle_ota(
480 &mut self,
481 state: &mut DeviceState,
482 command: u8,
483 payload: &[u8],
484 ) -> Option<(u8, Vec<u8>)> {
485 let manufacturer = self.manufacturer_code;
486 let firmware = self.firmware.as_mut()?;
487 let mut r = zigbee_primitives::wire::Reader::new(payload);
488 let block_request = |d: &OtaDownload| {
489 let mut p = vec![0u8];
490 p.extend_from_slice(&d.manufacturer.to_le_bytes());
491 p.extend_from_slice(&d.image_type.to_le_bytes());
492 p.extend_from_slice(&d.file_version.to_le_bytes());
493 p.extend_from_slice(&(d.data.len() as u32).to_le_bytes());
494 p.push(OTA_BLOCK);
495 (0x03, p)
496 };
497 match command {
498 0x00 => {
500 let mut p = vec![0u8];
501 p.extend_from_slice(&manufacturer.to_le_bytes());
502 p.extend_from_slice(&firmware.image_type.to_le_bytes());
503 p.extend_from_slice(&firmware.file_version.to_le_bytes());
504 Some((0x01, p))
505 }
506 0x02 => {
508 if r.u8().ok()? != 0 {
509 return None;
510 }
511 let d = OtaDownload {
512 manufacturer: r.u16().ok()?,
513 image_type: r.u16().ok()?,
514 file_version: r.u32().ok()?,
515 size: r.u32().ok()?,
516 data: Vec::new(),
517 };
518 let next = block_request(&d);
519 state.ota = Some(d);
520 Some(next)
521 }
522 0x05 => {
524 if r.u8().ok()? != 0 {
525 state.ota = None;
526 return None;
527 }
528 let d = state.ota.as_mut()?;
529 let _ = (r.u16().ok()?, r.u16().ok()?, r.u32().ok()?);
530 let offset = r.u32().ok()?;
531 let n = usize::from(r.u8().ok()?);
532 let data = r.bytes(n).ok()?;
533 if offset as usize != d.data.len() || n == 0 {
534 return Some(block_request(d));
535 }
536 d.data.extend_from_slice(data);
537 if d.data.len() as u32 >= d.size {
538 let mut p = vec![0u8];
539 p.extend_from_slice(&d.manufacturer.to_le_bytes());
540 p.extend_from_slice(&d.image_type.to_le_bytes());
541 p.extend_from_slice(&d.file_version.to_le_bytes());
542 Some((0x06, p))
543 } else {
544 Some(block_request(d))
545 }
546 }
547 0x07 => {
549 let d = state.ota.take()?;
550 firmware.file_version = d.file_version;
551 firmware.image = d.data;
552 None
553 }
554 _ => None,
555 }
556 }
557
558 fn endpoint_mut(&mut self, endpoint: u8) -> Option<&mut SimEndpoint> {
559 self.endpoints.iter_mut().find(|e| e.endpoint == endpoint)
560 }
561
562 pub fn handle_zcl(
565 &mut self,
566 state: &mut DeviceState,
567 endpoint: u8,
568 cluster: u16,
569 source_endpoint: u8,
570 payload: &[u8],
571 ) -> Reaction {
572 let mut reaction = Reaction::default();
573 let Ok(frame) = Frame::parse(payload) else {
574 return reaction;
575 };
576 let h = frame.header;
577 let reply_to = |frame: Frame| Outgoing {
578 profile: 0x0104,
579 cluster,
580 source_endpoint: endpoint,
581 destination_endpoint: source_endpoint,
582 payload: frame.encode(),
583 };
584 let default_response = |status: u8| {
585 let mut f = Frame::global(
586 Direction::ServerToClient,
587 h.seq,
588 foundation::id::DEFAULT_RESPONSE,
589 Global::DefaultResponse {
590 command: h.command,
591 status,
592 }
593 .encode(),
594 );
595 f.header.disable_default_response = true;
596 f
597 };
598 if cluster == cluster_id::OTA_UPGRADE
599 && h.frame_type == FrameType::Cluster
600 && h.direction == Direction::ServerToClient
601 {
602 if let Some(payload) = self.handle_ota(state, h.command, &frame.payload) {
603 state.seq = state.seq.wrapping_add(1);
604 let request =
605 Frame::cluster(Direction::ClientToServer, state.seq, payload.0, payload.1);
606 reaction.replies.push(reply_to(request));
607 }
608 return reaction;
609 }
610 let Some(ep) = self.endpoint_mut(endpoint) else {
611 return reaction;
612 };
613 let Some(attributes) = ep.servers.get_mut(&cluster) else {
614 if !h.disable_default_response {
615 reaction
616 .replies
617 .push(reply_to(default_response(status::UNSUPPORTED_CLUSTER)));
618 }
619 return reaction;
620 };
621 let mut changed = Vec::new();
622 let response = match h.frame_type {
623 FrameType::Global => match Global::decode(h.command, &frame.payload) {
624 Ok(Global::ReadAttributes(ids)) => Some(Global::ReadAttributesResponse(
625 ids.into_iter()
626 .map(|id| match attributes.get(&id) {
627 Some(v) => ReadRecord {
628 attribute: id,
629 status: status::SUCCESS,
630 value: Some(v.clone()),
631 },
632 None => ReadRecord {
633 attribute: id,
634 status: status::UNSUPPORTED_ATTRIBUTE,
635 value: None,
636 },
637 })
638 .collect(),
639 )),
640 Ok(Global::WriteAttributes(values)) => {
641 let mut failures = Vec::new();
642 for (id, value) in values {
643 match attributes.get_mut(&id) {
644 Some(slot) => *slot = value,
645 None => failures.push((status::UNSUPPORTED_ATTRIBUTE, Some(id))),
646 }
647 }
648 Some(Global::WriteAttributesResponse(if failures.is_empty() {
649 vec![(status::SUCCESS, None)]
650 } else {
651 failures
652 }))
653 }
654 Ok(Global::ConfigureReporting(configs)) => {
655 let mut failures = Vec::new();
656 for c in configs {
657 if attributes.contains_key(&c.attribute) {
658 state.reporting.insert((endpoint, cluster, c.attribute), c);
659 } else {
660 failures.push(ReportingStatus {
661 status: status::UNSUPPORTED_ATTRIBUTE,
662 attribute: Some(c.attribute),
663 });
664 }
665 }
666 Some(Global::ConfigureReportingResponse(if failures.is_empty() {
667 vec![ReportingStatus {
668 status: status::SUCCESS,
669 attribute: None,
670 }]
671 } else {
672 failures
673 }))
674 }
675 Ok(_) => None,
676 Err(_) => {
677 reaction
678 .replies
679 .push(reply_to(default_response(status::MALFORMED_COMMAND)));
680 return reaction;
681 }
682 },
683 FrameType::Cluster => {
684 let handled = match (cluster, h.command) {
685 (cluster_id::ON_OFF, 0x00..=0x02) => {
686 let current = attributes
687 .get(&attr::on_off::ON_OFF)
688 .and_then(Value::as_bool)
689 .unwrap_or(false);
690 let next = match h.command {
691 0x00 => false,
692 0x01 => true,
693 _ => !current,
694 };
695 attributes.insert(attr::on_off::ON_OFF, Value::bool(next));
696 changed.push(attr::on_off::ON_OFF);
697 true
698 }
699 (cluster_id::IDENTIFY, 0x00) => true,
700 (cluster_id::IAS_ZONE, 0x00) => {
701 state.ias_enrolled = true;
702 if let [_, zone_id, ..] = frame.payload.as_slice() {
703 attributes.insert(attr::ias_zone::ZONE_ID, Value::u8(*zone_id));
704 attributes.insert(attr::ias_zone::ZONE_STATE, Value::enum8(1));
705 }
706 true
707 }
708 _ => false,
709 };
710 if !h.disable_default_response {
711 reaction.replies.push(reply_to(default_response(if handled {
712 status::SUCCESS
713 } else {
714 status::UNSUP_COMMAND
715 })));
716 }
717 None
718 }
719 };
720 if let Some(g) = response {
721 let mut f = Frame::global(Direction::ServerToClient, h.seq, g.command_id(), g.encode());
722 f.header.disable_default_response = true;
723 reaction.replies.push(reply_to(f));
724 }
725 for attribute in changed {
726 reaction
727 .replies
728 .extend(self.report(state, endpoint, cluster, attribute));
729 }
730 reaction
731 }
732
733 pub fn set_attribute(
736 &mut self,
737 state: &mut DeviceState,
738 endpoint: u8,
739 cluster: u16,
740 attribute: u16,
741 value: Value,
742 ) -> Vec<Outgoing> {
743 if let Some(attributes) = self
744 .endpoint_mut(endpoint)
745 .and_then(|e| e.servers.get_mut(&cluster))
746 {
747 attributes.insert(attribute, value);
748 }
749 self.report(state, endpoint, cluster, attribute)
750 }
751
752 fn report(
753 &self,
754 state: &mut DeviceState,
755 endpoint: u8,
756 cluster: u16,
757 attribute: u16,
758 ) -> Vec<Outgoing> {
759 if !state
760 .reporting
761 .contains_key(&(endpoint, cluster, attribute))
762 {
763 return Vec::new();
764 }
765 let Some(value) = self
766 .endpoints
767 .iter()
768 .find(|e| e.endpoint == endpoint)
769 .and_then(|e| e.servers.get(&cluster))
770 .and_then(|a| a.get(&attribute))
771 .cloned()
772 else {
773 return Vec::new();
774 };
775 state
776 .bindings
777 .iter()
778 .filter(|b| b.source_endpoint == endpoint && b.cluster == cluster)
779 .filter_map(|b| match b.target {
780 zigbee_zdo::BindTarget::Endpoint { endpoint: dst, .. } => Some(dst),
781 zigbee_zdo::BindTarget::Group(_) => None,
782 })
783 .map(|dst| {
784 state.seq = state.seq.wrapping_add(1);
785 let mut f = Frame::global(
786 Direction::ServerToClient,
787 state.seq,
788 foundation::id::REPORT_ATTRIBUTES,
789 Global::ReportAttributes(vec![(attribute, value.clone())]).encode(),
790 );
791 f.header.disable_default_response = true;
792 Outgoing {
793 profile: 0x0104,
794 cluster,
795 source_endpoint: endpoint,
796 destination_endpoint: dst,
797 payload: f.encode(),
798 }
799 })
800 .collect()
801 }
802
803 pub fn announce(&self, nwk: NodeId) -> Outgoing {
805 let capability = self.node_descriptor().mac_capabilities;
806 let (cluster, payload) = Message {
807 tsn: 0x80,
808 body: Body::DeviceAnnce {
809 nwk,
810 ieee: self.ieee,
811 capability,
812 },
813 }
814 .encode();
815 Outgoing {
816 profile: 0,
817 cluster,
818 source_endpoint: 0,
819 destination_endpoint: 0,
820 payload,
821 }
822 }
823}