use {
crate::{client::TpLinkClient, devices::Device, error::Result},
std::{collections::HashMap, sync::Arc},
tokio::sync::RwLock,
};
#[derive(Debug)]
pub struct DeviceRegistry {
devices: HashMap<String, Device>, client: Arc<TpLinkClient>,
}
impl DeviceRegistry {
pub fn new() -> Self {
Self {
devices: HashMap::new(),
client: Arc::new(TpLinkClient::new()),
}
}
pub fn with_client(client: Arc<TpLinkClient>) -> Self {
Self {
devices: HashMap::new(),
client,
}
}
pub async fn discover_and_register(&mut self) -> Result<Vec<Device>> {
let devices = crate::discovery::discover_devices_with_client(self.client.clone()).await?;
self.devices.clear();
for device in &devices {
if let Some(ip) = device.ip_string() {
self.devices.insert(ip, device.clone());
}
}
Ok(devices)
}
pub fn get_device(&self, ip: &str) -> Option<&Device> {
self.devices.get(ip)
}
pub fn get_smart_plug(&self, ip: &str) -> Option<&crate::devices::SmartPlug> {
match self.devices.get(ip) {
Some(Device::SmartPlug(plug)) => Some(plug),
_ => None,
}
}
pub fn get_smart_light(&self, ip: &str) -> Option<&crate::devices::SmartLight> {
match self.devices.get(ip) {
Some(Device::SmartLight(light)) => Some(light),
_ => None,
}
}
pub fn get_smart_dimmer(&self, ip: &str) -> Option<&crate::devices::SmartDimmer> {
match self.devices.get(ip) {
Some(Device::SmartDimmer(dimmer)) => Some(dimmer),
_ => None,
}
}
pub fn get_power_strip(&self, ip: &str) -> Option<&crate::devices::PowerStrip> {
match self.devices.get(ip) {
Some(Device::PowerStrip(strip)) => Some(strip),
_ => None,
}
}
pub fn register_device(&mut self, device: Device) {
if let Some(ip) = device.ip_string() {
self.devices.insert(ip, device);
}
}
pub fn remove_device(&mut self, ip: &str) -> Option<Device> {
self.devices.remove(ip)
}
pub fn devices(&self) -> impl Iterator<Item = &Device> {
self.devices.values()
}
pub fn device_count(&self) -> usize {
self.devices.len()
}
pub fn clear(&mut self) {
self.devices.clear();
}
pub fn client(&self) -> &Arc<TpLinkClient> {
&self.client
}
}
impl Default for DeviceRegistry {
fn default() -> Self {
Self::new()
}
}
pub type SafeDeviceRegistry = Arc<RwLock<DeviceRegistry>>;
pub fn create_registry() -> SafeDeviceRegistry {
Arc::new(RwLock::new(DeviceRegistry::new()))
}