use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite};
use zigbee_primitives::{Ieee, Key, NodeId};
use zigbee_zcl::Value;
use crate::deconz::DeconzFront;
use crate::device::{DeviceState, Outgoing, SimDevice};
use crate::ezsp::EzspFront;
use crate::mesh::{Mesh, SimNetwork};
use crate::znp::ZnpFront;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimNcp {
Ezsp {
protocol: u8,
},
Znp {
product: u8,
},
Deconz,
}
impl Default for SimNcp {
fn default() -> Self {
SimNcp::Ezsp { protocol: 13 }
}
}
#[derive(Debug, Clone)]
pub struct SimConfig {
pub ncp: SimNcp,
pub ieee: Ieee,
pub devices: Vec<SimDevice>,
pub join_delay: Duration,
pub reply_delay: Duration,
pub key_table_size: u16,
pub neighbors: Vec<SimNeighbor>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimNeighbor {
pub channel: u8,
pub pan_id: u16,
pub extended_pan_id: zigbee_primitives::ExtPanId,
pub permit_joining: bool,
}
impl Default for SimConfig {
fn default() -> Self {
SimConfig {
ncp: SimNcp::default(),
ieee: Ieee(0x00_0D_6F_FF_FE_00_00_01),
devices: Vec::new(),
join_delay: Duration::from_millis(200),
reply_delay: Duration::from_millis(20),
key_table_size: 12,
neighbors: Vec::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct SimSnapshot {
pub network: Option<SimNetwork>,
pub joined: Vec<(Ieee, NodeId)>,
pub bindings: Vec<(Ieee, u8, u16)>,
pub reporting: Vec<(Ieee, u8, u16, u16)>,
pub permit_join: bool,
pub ieee: Ieee,
pub key_table: Vec<(Ieee, Key)>,
pub ias_enrolled: Vec<Ieee>,
pub firmware: Vec<(Ieee, crate::device::SimFirmware)>,
}
pub(crate) enum Front {
Ezsp(EzspFront),
Znp(ZnpFront),
Deconz(DeconzFront),
}
impl Front {
pub fn ezsp(&mut self) -> Option<&mut EzspFront> {
match self {
Front::Ezsp(f) => Some(f),
_ => None,
}
}
pub fn znp(&mut self) -> Option<&mut ZnpFront> {
match self {
Front::Znp(f) => Some(f),
_ => None,
}
}
pub fn deconz(&mut self) -> Option<&mut DeconzFront> {
match self {
Front::Deconz(f) => Some(f),
_ => None,
}
}
fn link_keys(&self) -> Vec<(Ieee, Key)> {
match self {
Front::Ezsp(f) => f.key_table.values().copied().collect(),
Front::Znp(f) => f.link_keys.iter().map(|(i, k)| (*i, *k)).collect(),
Front::Deconz(f) => f.link_keys.iter().map(|(i, k)| (*i, *k)).collect(),
}
}
}
pub(crate) struct SimState {
pub mesh: Mesh,
pub front: Front,
}
#[derive(Clone)]
pub struct Simulator {
pub(crate) state: Arc<Mutex<SimState>>,
}
impl std::fmt::Debug for Simulator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Simulator").finish_non_exhaustive()
}
}
#[derive(Debug, thiserror::Error)]
pub enum SimError {
#[error("host link closed: {0}")]
Closed(String),
}
pub(crate) fn lock(m: &Mutex<SimState>) -> MutexGuard<'_, SimState> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
impl Simulator {
pub fn new(config: SimConfig) -> Simulator {
let mut mesh = Mesh::new(
config.ieee,
&config.devices,
config.join_delay,
config.reply_delay,
);
mesh.neighbors = config.neighbors.clone();
let front = match config.ncp {
SimNcp::Ezsp { protocol } => {
Front::Ezsp(EzspFront::new(protocol, config.key_table_size))
}
SimNcp::Znp { product } => Front::Znp(ZnpFront::new(product)),
SimNcp::Deconz => Front::Deconz(DeconzFront::new()),
};
Simulator {
state: Arc::new(Mutex::new(SimState { mesh, front })),
}
}
pub fn snapshot(&self) -> SimSnapshot {
let s = lock(&self.state);
let mut bindings = Vec::new();
let mut reporting = Vec::new();
for (ieee, j) in &s.mesh.joined {
bindings.extend(
j.state
.bindings
.iter()
.map(|b| (*ieee, b.source_endpoint, b.cluster)),
);
reporting.extend(
j.state
.reporting
.keys()
.map(|(e, c, a)| (*ieee, *e, *c, *a)),
);
}
reporting.sort_unstable();
SimSnapshot {
network: s.mesh.network.clone(),
joined: s.mesh.joined.iter().map(|(i, j)| (*i, j.nwk)).collect(),
bindings,
reporting,
permit_join: s.mesh.permit_open(),
ieee: s.mesh.ieee(),
key_table: s.front.link_keys(),
ias_enrolled: s
.mesh
.joined
.iter()
.filter(|(_, j)| j.state.ias_enrolled)
.map(|(i, _)| *i)
.collect(),
firmware: s
.mesh
.devices
.iter()
.filter_map(|(i, d)| d.firmware.clone().map(|f| (*i, f)))
.collect(),
}
}
pub fn set_attribute(
&self,
ieee: Ieee,
endpoint: u8,
cluster: u16,
attribute: u16,
value: Value,
) -> usize {
let mut s = lock(&self.state);
let mesh = &mut s.mesh;
let Some(mut device) = mesh.devices.get(&ieee).cloned() else {
return 0;
};
let reports = match mesh.joined.get_mut(&ieee) {
Some(j) => device.set_attribute(&mut j.state, endpoint, cluster, attribute, value),
None => {
device.set_attribute(
&mut DeviceState::default(),
endpoint,
cluster,
attribute,
value,
);
Vec::new()
}
};
mesh.devices.insert(ieee, device);
let n = reports.len();
for r in reports {
mesh.deliver(ieee, r, Duration::ZERO);
}
n
}
pub fn send_from(&self, ieee: Ieee, out: Outgoing) {
lock(&self.state).mesh.deliver(ieee, out, Duration::ZERO);
}
pub fn add_device(&self, device: SimDevice) {
let mut s = lock(&self.state);
let ieee = device.ieee;
s.mesh.devices.insert(ieee, device);
if s.mesh.permit_open() {
let delay = s.mesh.join_delay;
s.mesh.schedule(delay, crate::mesh::Scheduled::Join(ieee));
}
}
pub fn leave(&self, ieee: Ieee) {
lock(&self.state).mesh.leave_device(ieee);
}
pub async fn serve<T>(&self, io: T) -> Result<(), SimError>
where
T: AsyncRead + AsyncWrite + Send + 'static,
{
let kind = match lock(&self.state).front {
Front::Ezsp(_) => 0,
Front::Znp(_) => 1,
Front::Deconz(_) => 2,
};
match kind {
0 => crate::ezsp::serve(self, io).await,
1 => crate::znp::serve(self, io).await,
_ => crate::deconz::serve(self, io).await,
}
}
}