use zigbee_primitives::wire::{Reader, Writer};
use crate::frame::Direction;
use crate::types::DataType;
use crate::value::{Value, ValueError};
#[derive(Debug)]
pub struct ClusterDef {
pub id: u16,
pub name: &'static str,
pub attributes: &'static [AttributeDef],
pub commands: &'static [CommandDef],
pub responses: &'static [CommandDef],
}
#[derive(Debug)]
pub struct AttributeDef {
pub id: u16,
pub name: &'static str,
pub data_type: DataType,
pub writable: bool,
pub report: Option<ReportDefault>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReportDefault {
pub min_interval: u16,
pub max_interval: u16,
pub change: Option<u64>,
}
#[derive(Debug)]
pub struct CommandDef {
pub id: u8,
pub name: &'static str,
pub fields: &'static [FieldDef],
}
#[derive(Debug)]
pub struct FieldDef {
pub name: &'static str,
pub kind: FieldKind,
pub optional: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldKind {
Value(DataType),
List8(DataType),
Rest,
}
include!(concat!(env!("OUT_DIR"), "/clusters.rs"));
pub fn cluster(id: u16) -> Option<&'static ClusterDef> {
CLUSTERS
.binary_search_by_key(&id, |c| c.id)
.ok()
.and_then(|i| CLUSTERS.get(i))
}
pub fn cluster_by_name(name: &str) -> Option<&'static ClusterDef> {
CLUSTERS.iter().find(|c| c.name == name)
}
impl ClusterDef {
pub fn attribute(&self, id: u16) -> Option<&'static AttributeDef> {
self.attributes
.binary_search_by_key(&id, |a| a.id)
.ok()
.and_then(|i| self.attributes.get(i))
}
pub fn attribute_by_name(&self, name: &str) -> Option<&'static AttributeDef> {
self.attributes.iter().find(|a| a.name == name)
}
pub fn command(&self, direction: Direction, id: u8) -> Option<&'static CommandDef> {
let list = match direction {
Direction::ClientToServer => self.commands,
Direction::ServerToClient => self.responses,
};
list.binary_search_by_key(&id, |c| c.id)
.ok()
.and_then(|i| list.get(i))
}
pub fn command_by_name(&self, direction: Direction, name: &str) -> Option<&'static CommandDef> {
let list = match direction {
Direction::ClientToServer => self.commands,
Direction::ServerToClient => self.responses,
};
list.iter().find(|c| c.name == name)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum EncodeError {
#[error("missing field {0}")]
Missing(&'static str),
#[error("{0} values for {1} fields")]
TooMany(usize, usize),
}
impl CommandDef {
pub fn decode(&self, payload: &[u8]) -> Result<Vec<(&'static str, Value)>, ValueError> {
let mut r = Reader::new(payload);
let mut out = Vec::with_capacity(self.fields.len());
for field in self.fields {
if field.optional && r.is_empty() {
break;
}
let value = match field.kind {
FieldKind::Value(t) => Value::decode(t, &mut r)?,
FieldKind::List8(t) => {
let count = usize::from(r.u8()?);
let mut items = Vec::with_capacity(count.min(r.remaining()));
for _ in 0..count {
items.push(Value::decode(t, &mut r)?);
}
Value::List(DataType::Array, t, Some(items))
}
FieldKind::Rest => Value::Octets(DataType::OctetString, Some(r.rest().to_vec())),
};
out.push((field.name, value));
}
Ok(out)
}
pub fn encode(&self, values: &[Value]) -> Result<Vec<u8>, EncodeError> {
if values.len() > self.fields.len() {
return Err(EncodeError::TooMany(values.len(), self.fields.len()));
}
let mut w = Vec::new();
for (i, field) in self.fields.iter().enumerate() {
let Some(value) = values.get(i) else {
if field.optional {
break;
}
return Err(EncodeError::Missing(field.name));
};
match (field.kind, value) {
(FieldKind::List8(_), Value::List(_, _, items)) => {
let items = items.as_deref().unwrap_or(&[]);
w.put_u8(items.len().min(255) as u8);
items.iter().take(255).for_each(|v| v.encode(&mut w));
}
(FieldKind::Rest, Value::Octets(_, bytes)) => {
w.put_bytes(bytes.as_deref().unwrap_or(&[]))
}
_ => value.encode(&mut w),
}
}
Ok(w)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tables_are_sorted_and_findable() {
assert!(CLUSTERS.windows(2).all(|w| w[0].id < w[1].id));
for c in CLUSTERS {
assert!(
c.attributes.windows(2).all(|w| w[0].id < w[1].id),
"{}",
c.name
);
assert_eq!(cluster(c.id).map(|x| x.name), Some(c.name));
}
let t = cluster(cluster_id::TEMPERATURE_MEASUREMENT).unwrap();
let mv = t
.attribute(attr::temperature_measurement::MEASURED_VALUE)
.unwrap();
assert_eq!(mv.data_type, DataType::Int16);
assert_eq!(
mv.report,
Some(ReportDefault {
min_interval: 10,
max_interval: 3600,
change: Some(10)
})
);
assert_eq!(cluster_by_name("on_off").unwrap().id, 0x0006);
}
#[test]
fn commands_encode_and_decode_from_the_table() {
let level = cluster(cluster_id::LEVEL_CONTROL).unwrap();
let mtl = level
.command(
Direction::ClientToServer,
command::level_control::MOVE_TO_LEVEL,
)
.unwrap();
let bytes = mtl.encode(&[Value::u8(128), Value::u16(10)]).unwrap();
assert_eq!(bytes, [128, 10, 0]);
let fields = mtl.decode(&bytes).unwrap();
assert_eq!(
fields,
vec![
("level", Value::u8(128)),
("transition_time", Value::u16(10))
]
);
assert_eq!(
mtl.encode(&[Value::u8(1)]),
Err(EncodeError::Missing("transition_time"))
);
let ias = cluster(cluster_id::IAS_ZONE).unwrap();
let notify = ias
.command(
Direction::ServerToClient,
response::ias_zone::ZONE_STATUS_CHANGE_NOTIFICATION,
)
.unwrap();
let fields = notify.decode(&[0x01, 0x00, 0x00]).unwrap();
assert_eq!(
fields,
vec![
("zone_status", Value::map16(1)),
("extended_status", Value::map8(0))
]
);
let groups = cluster(cluster_id::GROUPS).unwrap();
let get = groups
.command(
Direction::ClientToServer,
command::groups::GET_GROUP_MEMBERSHIP,
)
.unwrap();
let list = Value::List(
DataType::Array,
DataType::Uint16,
Some(vec![Value::u16(1), Value::u16(2)]),
);
let bytes = get.encode(std::slice::from_ref(&list)).unwrap();
assert_eq!(bytes, [2, 1, 0, 2, 0]);
assert_eq!(get.decode(&bytes).unwrap(), vec![("group_list", list)]);
}
}