Skip to content

Commit

Permalink
Merge pull request #124 from chipp/elisheba-fix
Browse files Browse the repository at this point in the history
[elisheba] Fixed storing lights states
  • Loading branch information
chipp authored Aug 17, 2024
2 parents 324459a + 554ea1e commit af1d15d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 25 deletions.
39 changes: 16 additions & 23 deletions bin/elisheba/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use sonoff::{Client, SonoffDevice};
use transport::{
action::{ActionRequest, ActionResponse, ActionResult},
Expand All @@ -11,38 +13,29 @@ use paho_mqtt::{AsyncClient as MqClient, Message, MessageBuilder, PropertyCode};

pub type ErasedError = Box<dyn std::error::Error + Send + Sync + 'static>;

#[derive(Default)]
pub struct Storage {
nursery_light: Option<State>,
lights: HashMap<Room, State>,
}

impl Storage {
pub fn new() -> Self {
Self {
nursery_light: None,
}
}

pub fn apply(&mut self, device: &SonoffDevice) -> Option<State> {
let state = map_device_to_state(device)?;

match state.room {
Room::Nursery => {
if let Some(ref nursery_light) = self.nursery_light {
if nursery_light.is_enabled == state.is_enabled {
return None;
}
}

info!(
"ligths at nursery are toggled {}",
if state.is_enabled { "on" } else { "off" }
);

self.nursery_light = Some(state);
Some(state)
if let Some(prev) = self.lights.get(&state.room) {
if prev.is_enabled == state.is_enabled {
return None;
}
_ => None,
}

info!(
"ligths at {room} are toggled {state}",
room = state.room,
state = if state.is_enabled { "on" } else { "off" }
);

self.lights.insert(state.room, state);
Some(state)
}
}

Expand Down
4 changes: 2 additions & 2 deletions bin/elisheba/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use transport::state::StateUpdate;
use transport::{connect_mqtt, Topic};

use futures_util::StreamExt;
use log::{debug, error, info, trace};
use log::{error, info, trace};
use paho_mqtt::{AsyncClient as MqClient, MessageBuilder, QOS_1};
use tokio::signal::unix::{signal, SignalKind};
use tokio::{task, time};
Expand All @@ -37,7 +37,7 @@ async fn main() -> Result<(), ErasedError> {
let mqtt_client = connect_mqtt(mqtt_address, mqtt_username, mqtt_password, "elisheba").await?;
info!("connected mqtt");

let mut storage = Storage::new();
let mut storage = Storage::default();
send_initial_state(devices, &mut storage, mqtt_client.clone()).await?;

let set_handle = task::spawn(subscribe_action(mqtt_client.clone(), client.clone()));
Expand Down

0 comments on commit af1d15d

Please sign in to comment.