Skip to content

Commit

Permalink
Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
sebr committed Jul 12, 2020
1 parent dc4c6fe commit 75f0ff4
Show file tree
Hide file tree
Showing 6 changed files with 79 additions and 55 deletions.
2 changes: 1 addition & 1 deletion custom_components/bhyve/pybhyve/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class OrbitWebsocket:
# pylint: disable=too-many-arguments
def __init__(self, token, loop, session, url, async_callback):
"""Create resources for websocket communication."""
self._token = token
self._token: str = token
self._loop = loop
self._session = session
self._url = url
Expand Down
12 changes: 9 additions & 3 deletions custom_components/bhyve/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
ATTR_CONSUMPTION_GALLONS = "consumption_gallons"
ATTR_CONSUMPTION_LITRES = "consumption_litres"


async def async_setup_platform(hass, config, async_add_entities, _discovery_info=None):
"""Set up BHyve sensors based on a config entry."""
bhyve = hass.data[DATA_BHYVE]
Expand Down Expand Up @@ -103,6 +104,7 @@ async def async_update(self):

await self._refetch_device()


class BHyveZoneHistorySensor(BHyveDeviceEntity):
"""Define a BHyve sensor."""

Expand Down Expand Up @@ -153,16 +155,19 @@ async def async_update(self):
zone_irrigation = list(
filter(
lambda i: i.get("station") == self._zone_id,
history_item.get(ATTR_IRRIGATION, [])
history_item.get(ATTR_IRRIGATION, []),
)
)
if zone_irrigation:
latest_irrigation = zone_irrigation[-1] # This is a bit crude - assumes the list is ordered by time.
# This is a bit crude - assumes the list is ordered by time.
latest_irrigation = zone_irrigation[-1]

gallons = latest_irrigation.get("water_volume_gal")
litres = round(gallons * 3.785, 2) if gallons else None

self._state = orbit_time_to_local_time(latest_irrigation.get("start_time"))
self._state = orbit_time_to_local_time(
latest_irrigation.get("start_time")
)
self._attrs = {
ATTR_BUDGET: latest_irrigation.get(ATTR_BUDGET),
ATTR_PROGRAM: latest_irrigation.get(ATTR_PROGRAM),
Expand All @@ -178,6 +183,7 @@ async def async_update(self):
self._available = False
raise (err)


class BHyveStateSensor(BHyveDeviceEntity):
"""Define a BHyve sensor."""

Expand Down
12 changes: 6 additions & 6 deletions custom_components/bhyve/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ enable_rain_delay:
fields:
entity_id:
description: Zone
example: 'switch.backyard_zone'
example: "switch.backyard_zone"
hours:
description: Number of hours of rain delay
example: 24
Expand All @@ -15,14 +15,14 @@ disable_rain_delay:
fields:
entity_id:
description: Zone
example: 'switch.backyard_zone'
example: "switch.backyard_zone"

start_watering:
description: Start watering a zone
fields:
entity_id:
description: Zone
example: 'switch.backyard_zone'
example: "switch.backyard_zone"
minutes:
description: Number of minutes to water the zone
example: 15
Expand All @@ -32,14 +32,14 @@ stop_watering:
fields:
entity_id:
description: Zone
example: 'switch.backyard_zone'
example: "switch.backyard_zone"

set_manual_preset_runtime:
description: Set the manual preset runtime for a device entity
fields:
entity_id:
description: Zone
example: 'switch.backyard_zone'
example: "switch.backyard_zone"
minutes:
description: Number of minutes to set the preset runtime
example: 15
example: 15
72 changes: 41 additions & 31 deletions custom_components/bhyve/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,19 @@

ATTR_PROGRAM = "program_{}"

SERVICE_BASE_SCHEMA = vol.Schema({
vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids,
})
SERVICE_BASE_SCHEMA = vol.Schema({vol.Required(ATTR_ENTITY_ID): cv.comp_entity_ids,})

ENABLE_RAIN_DELAY_SCHEMA = SERVICE_BASE_SCHEMA.extend({
vol.Required(ATTR_HOURS): cv.positive_int,
})
ENABLE_RAIN_DELAY_SCHEMA = SERVICE_BASE_SCHEMA.extend(
{vol.Required(ATTR_HOURS): cv.positive_int,}
)

START_WATERING_SCHEMA = SERVICE_BASE_SCHEMA.extend({
vol.Required(ATTR_MINUTES): cv.positive_int,
})
START_WATERING_SCHEMA = SERVICE_BASE_SCHEMA.extend(
{vol.Required(ATTR_MINUTES): cv.positive_int,}
)

SET_PRESET_RUNTIME_SCHEMA = SERVICE_BASE_SCHEMA.extend({
vol.Required(ATTR_MINUTES): cv.positive_int,
})
SET_PRESET_RUNTIME_SCHEMA = SERVICE_BASE_SCHEMA.extend(
{vol.Required(ATTR_MINUTES): cv.positive_int,}
)

SERVICE_ENABLE_RAIN_DELAY = "enable_rain_delay"
SERVICE_DISABLE_RAIN_DELAY = "disable_rain_delay"
Expand All @@ -95,11 +93,23 @@
SERVICE_SET_MANUAL_PRESET_RUNTIME = "set_manual_preset_runtime"

SERVICE_TO_METHOD = {
SERVICE_ENABLE_RAIN_DELAY: {"method": "enable_rain_delay", "schema": ENABLE_RAIN_DELAY_SCHEMA},
SERVICE_DISABLE_RAIN_DELAY: {"method": "disable_rain_delay", "schema": SERVICE_BASE_SCHEMA},
SERVICE_START_WATERING: {"method": "start_watering", "schema": START_WATERING_SCHEMA},
SERVICE_ENABLE_RAIN_DELAY: {
"method": "enable_rain_delay",
"schema": ENABLE_RAIN_DELAY_SCHEMA,
},
SERVICE_DISABLE_RAIN_DELAY: {
"method": "disable_rain_delay",
"schema": SERVICE_BASE_SCHEMA,
},
SERVICE_START_WATERING: {
"method": "start_watering",
"schema": START_WATERING_SCHEMA,
},
SERVICE_STOP_WATERING: {"method": "stop_watering", "schema": SERVICE_BASE_SCHEMA},
SERVICE_SET_MANUAL_PRESET_RUNTIME: {"method": "set_manual_preset_runtime", "schema": SET_PRESET_RUNTIME_SCHEMA},
SERVICE_SET_MANUAL_PRESET_RUNTIME: {
"method": "set_manual_preset_runtime",
"schema": SET_PRESET_RUNTIME_SCHEMA,
},
}


Expand All @@ -120,9 +130,7 @@ async def async_setup_platform(hass, config, async_add_entities, _discovery_info

# Filter out any programs which are not for this device
device_programs = [
program
for program in programs
if program.get("device_id") == device_id
program for program in programs if program.get("device_id") == device_id
]

switches.append(
Expand All @@ -131,15 +139,21 @@ async def async_setup_platform(hass, config, async_add_entities, _discovery_info

for zone in device.get("zones"):
switches.append(
BHyveZoneSwitch(hass, bhyve, device, zone, device_programs, "water-pump")
BHyveZoneSwitch(
hass, bhyve, device, zone, device_programs, "water-pump"
)
)

for program in programs:
program_device = device_by_id.get(program.get("device_id"))
program_id = program.get("program")
if program_id is not None:
_LOGGER.info("Creating switch: Program %s", program.get("name"))
switches.append(BHyveProgramSwitch(hass, bhyve, program, program_device, "bulletin-board"))
switches.append(
BHyveProgramSwitch(
hass, bhyve, program, program_device, "bulletin-board"
)
)

async_add_entities(switches, True)

Expand All @@ -157,10 +171,7 @@ async def async_service_handler(service):
entity_ids = service.data.get(ATTR_ENTITY_ID)
component = hass.data.get(SWITCH_DOMAIN)
if entity_ids:
target_switches = [
component.get_entity(entity)
for entity in entity_ids
]
target_switches = [component.get_entity(entity) for entity in entity_ids]
else:
return

Expand All @@ -179,6 +190,7 @@ async def async_service_handler(service):
DOMAIN, service, async_service_handler, schema=schema
)


class BHyveProgramSwitch(BHyveWebsocketEntity, SwitchEntity):
"""Define a BHyve program switch."""

Expand Down Expand Up @@ -276,6 +288,7 @@ def _on_ws_data(self, data):
def _should_handle_event(self, event_name):
return event_name in [EVENT_PROGRAM_CHANGED]


class BHyveZoneSwitch(BHyveDeviceEntity, SwitchEntity):
"""Define a BHyve zone switch."""

Expand Down Expand Up @@ -417,9 +430,7 @@ def _set_watering_program(self, program):
plan_date + timedelta(hours=t.hour, minutes=t.minute)
)
self._attrs[program_attr].update(
{
ATTR_SMART_WATERING_PLAN: upcoming_run_times
}
{ATTR_SMART_WATERING_PLAN: upcoming_run_times}
)
else:
self._attrs[program_attr].update(
Expand Down Expand Up @@ -495,9 +506,7 @@ def is_on(self):
return self._is_on

async def start_watering(self, minutes):
station_payload = [
{"station": self._zone_id, "run_time": minutes}
]
station_payload = [{"station": self._zone_id, "run_time": minutes}]
self._is_on = True
await self._send_station_message(station_payload)

Expand All @@ -515,6 +524,7 @@ async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
await self.stop_watering()


class BHyveRainDelaySwitch(BHyveDeviceEntity, SwitchEntity):
"""Define a BHyve rain delay switch."""

Expand Down
3 changes: 2 additions & 1 deletion custom_components/bhyve/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ def orbit_time_to_local_time(timestamp: str):
return dt.as_local(dt.parse_datetime(timestamp))
return None


def anonymize(device):
device["address"] = "REDACTED"
device["full_location"] = "REDACTED"
device["location"] = "REDACTED"
return device
return device
33 changes: 20 additions & 13 deletions python_scripts/bhyve_next_watering.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# pylint: disable=undefined-variable
now = dt_util.now()

zone_entity_id = data.get("entity_id")
Expand All @@ -10,42 +11,48 @@
logger.info("updating next_watering for zone: ({}: {})".format(zone_name, zone))

next_watering_entity = f"sensor.{zone_name}_next_watering".replace(" ", "_").lower()
next_watering_attrs = {
"friendly_name": f"{zone_name} next watering"
}
next_watering_attrs = {"friendly_name": f"{zone_name} next watering"}

rain_delay_finishing_entity = f"sensor.{device_name}_rain_delay_finishing".replace(" ", "_").lower()
rain_delay_finishing_attrs = {
"friendly_name": f"{device_name} rain delay finishing"
}
rain_delay_finishing_entity = f"sensor.{device_name}_rain_delay_finishing".replace(
" ", "_"
).lower()
rain_delay_finishing_attrs = {"friendly_name": f"{device_name} rain delay finishing"}

rain_delay = hass.states.get(f"switch.{device_name}_rain_delay")

if zone.state == "unavailable":
hass.states.set(next_watering_entity, "Unavailable", next_watering_attrs)
hass.states.set(rain_delay_finishing_entity, "Unavailable", rain_delay_finishing_attrs)
hass.states.set(
rain_delay_finishing_entity, "Unavailable", rain_delay_finishing_attrs
)
else:
delay_finishes_at = None
next_watering = None

if rain_delay.state == "on":
started_at = dt_util.as_timestamp(rain_delay.attributes.get("started_at"))
delay_seconds = rain_delay.attributes.get("delay") * 3600
delay_finishes_at = dt_util.as_local(dt_util.utc_from_timestamp(started_at + delay_seconds))
hass.states.set(rain_delay_finishing_entity, delay_finishes_at, rain_delay_finishing_attrs)
delay_finishes_at = dt_util.as_local(
dt_util.utc_from_timestamp(started_at + delay_seconds)
)
hass.states.set(
rain_delay_finishing_entity, delay_finishes_at, rain_delay_finishing_attrs
)
else:
hass.states.set(rain_delay_finishing_entity, None, rain_delay_finishing_attrs)

for program_id in ['a', 'b', 'c', 'e']:
for program_id in ["a", "b", "c", "e"]:
program = zone.attributes.get(f"program_{program_id}")
logger.info("program: %s", program)
if program is None or program.get("enabled", False) is False:
continue

if program.get("is_smart_program"):
for timestamp in program.get('watering_program', []):
for timestamp in program.get("watering_program", []):
watering_time = dt_util.parse_datetime(str(timestamp))
if watering_time > now and (delay_finishes_at is None or watering_time > delay_finishes_at):
if watering_time > now and (
delay_finishes_at is None or watering_time > delay_finishes_at
):
next_watering = watering_time
break
else:
Expand Down

0 comments on commit 75f0ff4

Please sign in to comment.