Skip to content

Commit

Permalink
v0.0.21 - fixing bug #23, #24 and #25.
Browse files Browse the repository at this point in the history
  • Loading branch information
jeroenterheerdt committed May 29, 2020
1 parent 81a27c6 commit 1b28ce4
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 33 deletions.
31 changes: 18 additions & 13 deletions custom_components/smart_irrigation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
CONF_AUTO_REFRESH,
CONF_AUTO_REFRESH_TIME,
CONF_NAME,
EVENT_HOURLY_DATA_UPDATED,
)

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -257,49 +258,52 @@ def __init__(
self.hass = hass
self.entities = {}
self.entry_setup_completed = False
# should this be name? or domain?
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL)
super().__init__(hass, _LOGGER, name=name, update_interval=SCAN_INTERVAL)

# last update of the day happens at specified local time if auto_refresh is on
if self.auto_refresh:
hour = int(self.auto_refresh_time.split(":")[0])
minute = int(self.auto_refresh_time.split(":")[1])
_LOGGER.info(
"Auto refresh is enabled. Scheduling for {}".format(
self.auto_refresh_time
)
"Auto refresh is enabled. Scheduling for {}:{}".format(hour, minute)
)
async_track_time_change(
hass,
self._async_update_last_of_day,
hour=self.auto_refresh_time.split(":")[0],
minute=self.auto_refresh_time.split(":")[1],
hour=hour,
minute=minute,
second=0,
)
self.entry_setup_completed = True

def register_entity(self, thetype, entity):
_LOGGER.info("registering: type: {}, entity: {}".format(thetype, entity))
self.entities[thetype] = entity
self.entry_setup_completed = True

def handle_reset_bucket(self, call):
"""Handle the service reset_bucket call."""
_LOGGER.info("Reset bucket service called, resetting bucket to 0.")
self.bucket = 0
# fire an event so the sensor can update itself.
self.hass.bus.fire(EVENT_BUCKET_UPDATED, {CONF_BUCKET: self.bucket})
eventToFire = f"{self.name}_{EVENT_BUCKET_UPDATED}"
self.hass.bus.fire(eventToFire, {CONF_BUCKET: self.bucket})

def handle_calculate_daily_adjusted_run_time(self, call):
async def handle_calculate_daily_adjusted_run_time(self, call):
"""Handle the service calculate_daily_adjusted_run_time call."""
_LOGGER.info(
"Calculate Daily Adjusted Run Time service called, calculating now."
)
self._update_last_of_day()

def handle_calculate_hourly_adjusted_run_time(self, call):
async def handle_calculate_hourly_adjusted_run_time(self, call):
"""Handle the service calculate_hourly_adjusted_run_time call."""
_LOGGER.info(
"Calculate Hourly Adjusted Run Time service called, calculating now."
)
self._async_update_data()
self.data = await self._async_update_data()
# fire an event so the sensor can update itself.
eventToFire = f"{self.name}_{EVENT_HOURLY_DATA_UPDATED}"
self.hass.bus.fire(eventToFire, {})

def _update_last_of_day(self):
cart_entity_id = self.entities[TYPE_CURRENT_ADJUSTED_RUN_TIME]
Expand All @@ -312,7 +316,8 @@ def _update_last_of_day(self):
self.bucket = self.bucket + bucket_delta

# fire an event so the sensor can update itself.
self.hass.bus.fire(EVENT_BUCKET_UPDATED, {CONF_BUCKET: self.bucket})
eventToFire = f"{self.name}_{EVENT_BUCKET_UPDATED}"
self.hass.bus.fire(eventToFire, {CONF_BUCKET: self.bucket})

async def _async_update_last_of_day(self, *args):
_LOGGER.info(
Expand Down
5 changes: 3 additions & 2 deletions custom_components/smart_irrigation/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
DOMAIN = "smart_irrigation"
NAME = "Smart Irrigation"
DOMAIN_DATA = f"{DOMAIN}_data"
VERSION = "0.0.20"
VERSION = "0.0.21"

ISSUE_URL = "https://github.com/jeroenterheerdt/HASmartIrrigation/issues"

Expand Down Expand Up @@ -54,7 +54,8 @@
CONF_NAME = "name"

# Events
EVENT_BUCKET_UPDATED = "smart_irrigation_bucket_updated_event"
EVENT_BUCKET_UPDATED = "bucket_updated_event"
EVENT_HOURLY_DATA_UPDATED = "hourly_updated_event"

# Services
SERVICE_RESET_BUCKET = "reset_bucket"
Expand Down
58 changes: 40 additions & 18 deletions custom_components/smart_irrigation/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
CONF_MAXIMUM_DURATION,
CONF_ADJUSTED_RUN_TIME_MINUTES,
CONF_BASE_SCHEDULE_INDEX_MINUTES,
EVENT_HOURLY_DATA_UPDATED,
CONF_AUTO_REFRESH,
CONF_AUTO_REFRESH_TIME,
CONF_FORCE_MODE_DURATION,
)
from .entity import SmartIrrigationEntity

Expand Down Expand Up @@ -98,10 +102,16 @@ async def async_added_to_hass(self):

# listen to the bucket update event only for the adjusted run time sensor
if self.type == TYPE_ADJUSTED_RUN_TIME:
eventToListen = f"{self.coordinator.name}_{EVENT_BUCKET_UPDATED}"
self.hass.bus.async_listen(
EVENT_BUCKET_UPDATED, lambda event: self._bucket_updated(event)
eventToListen, lambda event: self._bucket_updated(event),
)
# listen to the hourly data updated event only for the current adjusted run time sensor
if self.type == TYPE_CURRENT_ADJUSTED_RUN_TIME:
eventToListen = f"{self.coordinator.name}_{EVENT_HOURLY_DATA_UPDATED}"
self.hass.bus.async_listen(
eventToListen, lambda event: self._hourly_data_updated(event),
)

state = await self.async_get_last_state()
if state is not None and state.state != "unavailable":
self._state = float(state.state)
Expand Down Expand Up @@ -179,19 +189,34 @@ def _bucket_updated(self, ev: Event):
self.bucket = float(e["data"][CONF_BUCKET])
result = self.calculate_water_budget_and_adjusted_run_time(self.bucket)
art_entity_id = self.coordinator.entities[TYPE_ADJUSTED_RUN_TIME]
attr = self.get_attributes_for_daily_adjusted_run_time(
self.bucket, result["wb"], result["art"]
)
self.hass.states.set(
art_entity_id,
result["art"],
{
CONF_BUCKET: self.show_mm_or_inch(self.bucket),
CONF_WATER_BUDGET: self.show_percentage(result["wb"]),
},
art_entity_id, result["art"], attr,
)

@callback
def _hourly_data_updated(self, ev: Event):
"""Receive the hourly data updated event."""
self._state = self.update_state()
_LOGGER.warning("new state: {}".format(self._state))
self.hass.add_job(self.async_update_ha_state)

@property
def name(self):
"""Return the name of the sensor."""
return f"{self.coordinator.name} {self.type}"
return f"{self.type}"

def get_attributes_for_daily_adjusted_run_time(self, bucket, water_budget, art):
"""Returns the attributes for daily_adjusted_run_time."""
return {
CONF_WATER_BUDGET: self.show_percentage(water_budget),
CONF_BUCKET: self.show_mm_or_inch(bucket),
CONF_LEAD_TIME: self.show_seconds(self.coordinator.lead_time),
CONF_MAXIMUM_DURATION: self.show_seconds(self.coordinator.maximum_duration),
CONF_ADJUSTED_RUN_TIME_MINUTES: self.show_minutes(art),
}

def update_state(self):
"""Update the state."""
Expand Down Expand Up @@ -248,6 +273,9 @@ def device_state_attributes(self):
self.coordinator.precipitation_rate
),
CONF_BASE_SCHEDULE_INDEX_MINUTES: self.show_minutes(self.state),
CONF_AUTO_REFRESH: self.coordinator.auto_refresh,
CONF_AUTO_REFRESH_TIME: self.coordinator.auto_refresh_time,
CONF_FORCE_MODE_DURATION: self.coordinator.force_mode_duration,
}
elif self.type == TYPE_CURRENT_ADJUSTED_RUN_TIME:
return {
Expand All @@ -260,15 +288,9 @@ def device_state_attributes(self):
CONF_ADJUSTED_RUN_TIME_MINUTES: self.show_minutes(self.state),
}
else:
return {
CONF_WATER_BUDGET: self.show_percentage(self.water_budget),
CONF_BUCKET: self.show_mm_or_inch(self.bucket),
CONF_LEAD_TIME: self.show_seconds(self.coordinator.lead_time),
CONF_MAXIMUM_DURATION: self.show_seconds(
self.coordinator.maximum_duration
),
CONF_ADJUSTED_RUN_TIME_MINUTES: self.show_minutes(self.state),
}
return self.get_attributes_for_daily_adjusted_run_time(
self.bucket, self.water_budget, self.state
)

@property
def icon(self):
Expand Down

0 comments on commit 1b28ce4

Please sign in to comment.