mirror of
https://github.com/home-assistant/core.git
synced 2025-04-24 01:08:12 +00:00
Add model to rachio device info (#32814)
* Add model to rachio device info Address followup items * Address review items, retest zone updates back and forth, and standby mode * Remove super * Revert "Remove super" This reverts commit 02e2f156a9e0d5316f52341871071912d7207321. * Update homeassistant/components/rachio/switch.py Co-Authored-By: Martin Hjelmare <marhje52@gmail.com> * Update homeassistant/components/rachio/binary_sensor.py Co-Authored-By: Martin Hjelmare <marhje52@gmail.com> Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
parent
ef54f33af7
commit
d62bb9ed47
@ -13,19 +13,22 @@ from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY, EVENT_HOMEASSISTANT_STOP, URL_API
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers import config_validation as cv, device_registry
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
from .const import (
|
||||
CONF_CUSTOM_URL,
|
||||
CONF_MANUAL_RUN_MINS,
|
||||
DEFAULT_MANUAL_RUN_MINS,
|
||||
DEFAULT_NAME,
|
||||
DOMAIN,
|
||||
KEY_DEVICES,
|
||||
KEY_ENABLED,
|
||||
KEY_EXTERNAL_ID,
|
||||
KEY_ID,
|
||||
KEY_MAC_ADDRESS,
|
||||
KEY_MODEL,
|
||||
KEY_NAME,
|
||||
KEY_SERIAL_NUMBER,
|
||||
KEY_STATUS,
|
||||
@ -142,10 +145,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
|
||||
# CONF_MANUAL_RUN_MINS can only come from a yaml import
|
||||
if not options.get(CONF_MANUAL_RUN_MINS) and config.get(CONF_MANUAL_RUN_MINS):
|
||||
options[CONF_MANUAL_RUN_MINS] = config[CONF_MANUAL_RUN_MINS]
|
||||
options_copy = options.copy()
|
||||
options_copy[CONF_MANUAL_RUN_MINS] = config[CONF_MANUAL_RUN_MINS]
|
||||
hass.config_entries.async_update_entry(options=options_copy)
|
||||
|
||||
# Configure API
|
||||
api_key = config.get(CONF_API_KEY)
|
||||
api_key = config[CONF_API_KEY]
|
||||
rachio = Rachio(api_key)
|
||||
|
||||
# Get the URL of this server
|
||||
@ -155,9 +160,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
webhook_url_path = f"{WEBHOOK_PATH}-{entry.entry_id}"
|
||||
rachio.webhook_url = f"{hass_url}{webhook_url_path}"
|
||||
|
||||
person = RachioPerson(rachio, entry)
|
||||
|
||||
# Get the API user
|
||||
try:
|
||||
person = await hass.async_add_executor_job(RachioPerson, hass, rachio, entry)
|
||||
await hass.async_add_executor_job(person.setup, hass)
|
||||
# Yes we really do get all these exceptions (hopefully rachiopy switches to requests)
|
||||
# and there is not a reasonable timeout here so it can block for a long time
|
||||
except RACHIO_API_EXCEPTIONS as error:
|
||||
@ -187,23 +194,26 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||
class RachioPerson:
|
||||
"""Represent a Rachio user."""
|
||||
|
||||
def __init__(self, hass, rachio, config_entry):
|
||||
def __init__(self, rachio, config_entry):
|
||||
"""Create an object from the provided API instance."""
|
||||
# Use API token to get user ID
|
||||
self._hass = hass
|
||||
self.rachio = rachio
|
||||
self.config_entry = config_entry
|
||||
self.username = None
|
||||
self._id = None
|
||||
self._controllers = []
|
||||
|
||||
response = rachio.person.getInfo()
|
||||
def setup(self, hass):
|
||||
"""Rachio device setup."""
|
||||
response = self.rachio.person.getInfo()
|
||||
assert int(response[0][KEY_STATUS]) == 200, "API key error"
|
||||
self._id = response[1][KEY_ID]
|
||||
|
||||
# Use user ID to get user data
|
||||
data = rachio.person.get(self._id)
|
||||
data = self.rachio.person.get(self._id)
|
||||
assert int(data[0][KEY_STATUS]) == 200, "User ID error"
|
||||
self.username = data[1][KEY_USERNAME]
|
||||
devices = data[1][KEY_DEVICES]
|
||||
self._controllers = []
|
||||
for controller in devices:
|
||||
webhooks = self.rachio.notification.getDeviceWebhook(controller[KEY_ID])[1]
|
||||
# The API does not provide a way to tell if a controller is shared
|
||||
@ -218,9 +228,10 @@ class RachioPerson:
|
||||
webhooks.get("error", "Unknown Error"),
|
||||
)
|
||||
continue
|
||||
self._controllers.append(
|
||||
RachioIro(self._hass, self.rachio, controller, webhooks)
|
||||
)
|
||||
|
||||
rachio_iro = RachioIro(hass, self.rachio, controller, webhooks)
|
||||
rachio_iro.setup()
|
||||
self._controllers.append(rachio_iro)
|
||||
_LOGGER.info('Using Rachio API as user "%s"', self.username)
|
||||
|
||||
@property
|
||||
@ -242,14 +253,17 @@ class RachioIro:
|
||||
self.hass = hass
|
||||
self.rachio = rachio
|
||||
self._id = data[KEY_ID]
|
||||
self._name = data[KEY_NAME]
|
||||
self._serial_number = data[KEY_SERIAL_NUMBER]
|
||||
self._mac_address = data[KEY_MAC_ADDRESS]
|
||||
self.name = data[KEY_NAME]
|
||||
self.serial_number = data[KEY_SERIAL_NUMBER]
|
||||
self.mac_address = data[KEY_MAC_ADDRESS]
|
||||
self.model = data[KEY_MODEL]
|
||||
self._zones = data[KEY_ZONES]
|
||||
self._init_data = data
|
||||
self._webhooks = webhooks
|
||||
_LOGGER.debug('%s has ID "%s"', str(self), self.controller_id)
|
||||
|
||||
def setup(self):
|
||||
"""Rachio Iro setup for webhooks."""
|
||||
# Listen for all updates
|
||||
self._init_webhooks()
|
||||
|
||||
@ -301,21 +315,6 @@ class RachioIro:
|
||||
"""Return the Rachio API controller ID."""
|
||||
return self._id
|
||||
|
||||
@property
|
||||
def serial_number(self) -> str:
|
||||
"""Return the Rachio API controller serial number."""
|
||||
return self._serial_number
|
||||
|
||||
@property
|
||||
def mac_address(self) -> str:
|
||||
"""Return the Rachio API controller mac address."""
|
||||
return self._mac_address
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
"""Return the user-defined name of the controller."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def current_schedule(self) -> str:
|
||||
"""Return the schedule that the device is running right now."""
|
||||
@ -349,6 +348,28 @@ class RachioIro:
|
||||
_LOGGER.info("Stopped watering of all zones on %s", str(self))
|
||||
|
||||
|
||||
class RachioDeviceInfoProvider(Entity):
|
||||
"""Mixin to provide device_info."""
|
||||
|
||||
def __init__(self, controller):
|
||||
"""Initialize a Rachio device."""
|
||||
super().__init__()
|
||||
self._controller = controller
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device_info of the device."""
|
||||
return {
|
||||
"identifiers": {(DOMAIN, self._controller.serial_number,)},
|
||||
"connections": {
|
||||
(device_registry.CONNECTION_NETWORK_MAC, self._controller.mac_address,)
|
||||
},
|
||||
"name": self._controller.name,
|
||||
"model": self._controller.model,
|
||||
"manufacturer": DEFAULT_NAME,
|
||||
}
|
||||
|
||||
|
||||
class RachioWebhookView(HomeAssistantView):
|
||||
"""Provide a page for the server to call."""
|
||||
|
||||
@ -365,7 +386,9 @@ class RachioWebhookView(HomeAssistantView):
|
||||
self._entry_id = entry_id
|
||||
self.url = webhook_url
|
||||
self.name = webhook_url[1:].replace("/", ":")
|
||||
_LOGGER.debug("Created webhook at url: %s, with name %s", self.url, self.name)
|
||||
_LOGGER.debug(
|
||||
"Initialize webhook at url: %s, with name %s", self.url, self.name
|
||||
)
|
||||
|
||||
async def post(self, request) -> web.Response:
|
||||
"""Handle webhook calls from the server."""
|
||||
|
@ -3,8 +3,7 @@ from abc import abstractmethod
|
||||
import logging
|
||||
|
||||
from homeassistant.components.binary_sensor import BinarySensorDevice
|
||||
from homeassistant.helpers import device_registry
|
||||
from homeassistant.helpers.dispatcher import dispatcher_connect
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
|
||||
from . import (
|
||||
SIGNAL_RACHIO_CONTROLLER_UPDATE,
|
||||
@ -12,48 +11,39 @@ from . import (
|
||||
STATUS_ONLINE,
|
||||
SUBTYPE_OFFLINE,
|
||||
SUBTYPE_ONLINE,
|
||||
RachioDeviceInfoProvider,
|
||||
)
|
||||
from .const import (
|
||||
DEFAULT_NAME,
|
||||
DOMAIN as DOMAIN_RACHIO,
|
||||
KEY_DEVICE_ID,
|
||||
KEY_STATUS,
|
||||
KEY_SUBTYPE,
|
||||
)
|
||||
from .const import DOMAIN as DOMAIN_RACHIO, KEY_DEVICE_ID, KEY_STATUS, KEY_SUBTYPE
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up the Rachio binary sensors."""
|
||||
devices = await hass.async_add_executor_job(_create_devices, hass, config_entry)
|
||||
async_add_entities(devices)
|
||||
_LOGGER.info("%d Rachio binary sensor(s) added", len(devices))
|
||||
entities = await hass.async_add_executor_job(_create_entities, hass, config_entry)
|
||||
async_add_entities(entities)
|
||||
_LOGGER.info("%d Rachio binary sensor(s) added", len(entities))
|
||||
|
||||
|
||||
def _create_devices(hass, config_entry):
|
||||
devices = []
|
||||
def _create_entities(hass, config_entry):
|
||||
entities = []
|
||||
for controller in hass.data[DOMAIN_RACHIO][config_entry.entry_id].controllers:
|
||||
devices.append(RachioControllerOnlineBinarySensor(hass, controller))
|
||||
return devices
|
||||
entities.append(RachioControllerOnlineBinarySensor(controller))
|
||||
return entities
|
||||
|
||||
|
||||
class RachioControllerBinarySensor(BinarySensorDevice):
|
||||
class RachioControllerBinarySensor(RachioDeviceInfoProvider, BinarySensorDevice):
|
||||
"""Represent a binary sensor that reflects a Rachio state."""
|
||||
|
||||
def __init__(self, hass, controller, poll=True):
|
||||
def __init__(self, controller, poll=True):
|
||||
"""Set up a new Rachio controller binary sensor."""
|
||||
self._controller = controller
|
||||
super().__init__(controller)
|
||||
|
||||
if poll:
|
||||
self._state = self._poll_update()
|
||||
else:
|
||||
self._state = None
|
||||
|
||||
dispatcher_connect(
|
||||
hass, SIGNAL_RACHIO_CONTROLLER_UPDATE, self._handle_any_update
|
||||
)
|
||||
|
||||
@property
|
||||
def should_poll(self) -> bool:
|
||||
"""Declare that this entity pushes its state to HA."""
|
||||
@ -78,30 +68,24 @@ class RachioControllerBinarySensor(BinarySensorDevice):
|
||||
"""Request the state from the API."""
|
||||
pass
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device_info of the device."""
|
||||
return {
|
||||
"identifiers": {(DOMAIN_RACHIO, self._controller.serial_number,)},
|
||||
"connections": {
|
||||
(device_registry.CONNECTION_NETWORK_MAC, self._controller.mac_address,)
|
||||
},
|
||||
"name": self._controller.name,
|
||||
"manufacturer": DEFAULT_NAME,
|
||||
}
|
||||
|
||||
@abstractmethod
|
||||
def _handle_update(self, *args, **kwargs) -> None:
|
||||
"""Handle an update to the state of this sensor."""
|
||||
pass
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Subscribe to updates."""
|
||||
async_dispatcher_connect(
|
||||
self.hass, SIGNAL_RACHIO_CONTROLLER_UPDATE, self._handle_any_update
|
||||
)
|
||||
|
||||
|
||||
class RachioControllerOnlineBinarySensor(RachioControllerBinarySensor):
|
||||
"""Represent a binary sensor that reflects if the controller is online."""
|
||||
|
||||
def __init__(self, hass, controller):
|
||||
def __init__(self, controller):
|
||||
"""Set up a new Rachio controller online binary sensor."""
|
||||
super().__init__(hass, controller, poll=False)
|
||||
super().__init__(controller, poll=False)
|
||||
self._state = self._poll_update(controller.init_data)
|
||||
|
||||
@property
|
||||
|
@ -61,12 +61,10 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Handle the initial step."""
|
||||
errors = {}
|
||||
_LOGGER.debug("async_step_user: %s", user_input)
|
||||
if user_input is not None:
|
||||
try:
|
||||
info = await validate_input(self.hass, user_input)
|
||||
await self.async_set_unique_id(user_input[CONF_API_KEY])
|
||||
return self.async_create_entry(title=info["title"], data=user_input)
|
||||
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
@ -75,6 +73,11 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
|
||||
if "base" not in errors:
|
||||
await self.async_set_unique_id(user_input[CONF_API_KEY])
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(title=info["title"], data=user_input)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=DATA_SCHEMA, errors=errors
|
||||
)
|
||||
|
@ -20,6 +20,7 @@ KEY_ENABLED = "enabled"
|
||||
KEY_EXTERNAL_ID = "externalId"
|
||||
KEY_ID = "id"
|
||||
KEY_NAME = "name"
|
||||
KEY_MODEL = "model"
|
||||
KEY_ON = "on"
|
||||
KEY_STATUS = "status"
|
||||
KEY_SUBTYPE = "subType"
|
||||
|
@ -4,8 +4,7 @@ from datetime import timedelta
|
||||
import logging
|
||||
|
||||
from homeassistant.components.switch import SwitchDevice
|
||||
from homeassistant.helpers import device_registry
|
||||
from homeassistant.helpers.dispatcher import dispatcher_connect
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
|
||||
from . import (
|
||||
SIGNAL_RACHIO_CONTROLLER_UPDATE,
|
||||
@ -15,11 +14,11 @@ from . import (
|
||||
SUBTYPE_ZONE_COMPLETED,
|
||||
SUBTYPE_ZONE_STARTED,
|
||||
SUBTYPE_ZONE_STOPPED,
|
||||
RachioDeviceInfoProvider,
|
||||
)
|
||||
from .const import (
|
||||
CONF_MANUAL_RUN_MINS,
|
||||
DEFAULT_MANUAL_RUN_MINS,
|
||||
DEFAULT_NAME,
|
||||
DOMAIN as DOMAIN_RACHIO,
|
||||
KEY_DEVICE_ID,
|
||||
KEY_ENABLED,
|
||||
@ -42,33 +41,33 @@ ATTR_ZONE_NUMBER = "Zone number"
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up the Rachio switches."""
|
||||
# Add all zones from all controllers as switches
|
||||
devices = await hass.async_add_executor_job(_create_devices, hass, config_entry)
|
||||
async_add_entities(devices)
|
||||
_LOGGER.info("%d Rachio switch(es) added", len(devices))
|
||||
entities = await hass.async_add_executor_job(_create_entities, hass, config_entry)
|
||||
async_add_entities(entities)
|
||||
_LOGGER.info("%d Rachio switch(es) added", len(entities))
|
||||
|
||||
|
||||
def _create_devices(hass, config_entry):
|
||||
devices = []
|
||||
def _create_entities(hass, config_entry):
|
||||
entities = []
|
||||
person = hass.data[DOMAIN_RACHIO][config_entry.entry_id]
|
||||
# Fetch the schedule once at startup
|
||||
# in order to avoid every zone doing it
|
||||
for controller in person.controllers:
|
||||
devices.append(RachioStandbySwitch(hass, controller))
|
||||
entities.append(RachioStandbySwitch(controller))
|
||||
zones = controller.list_zones()
|
||||
current_schedule = controller.current_schedule
|
||||
_LOGGER.debug("Rachio setting up zones: %s", zones)
|
||||
for zone in zones:
|
||||
_LOGGER.debug("Rachio setting up zone: %s", zone)
|
||||
devices.append(RachioZone(hass, person, controller, zone, current_schedule))
|
||||
return devices
|
||||
entities.append(RachioZone(person, controller, zone, current_schedule))
|
||||
return entities
|
||||
|
||||
|
||||
class RachioSwitch(SwitchDevice):
|
||||
class RachioSwitch(RachioDeviceInfoProvider, SwitchDevice):
|
||||
"""Represent a Rachio state that can be toggled."""
|
||||
|
||||
def __init__(self, controller, poll=True):
|
||||
"""Initialize a new Rachio switch."""
|
||||
self._controller = controller
|
||||
super().__init__(controller)
|
||||
|
||||
if poll:
|
||||
self._state = self._poll_update()
|
||||
@ -104,18 +103,6 @@ class RachioSwitch(SwitchDevice):
|
||||
# For this device
|
||||
self._handle_update(args, kwargs)
|
||||
|
||||
@property
|
||||
def device_info(self):
|
||||
"""Return the device_info of the device."""
|
||||
return {
|
||||
"identifiers": {(DOMAIN_RACHIO, self._controller.serial_number,)},
|
||||
"connections": {
|
||||
(device_registry.CONNECTION_NETWORK_MAC, self._controller.mac_address,)
|
||||
},
|
||||
"name": self._controller.name,
|
||||
"manufacturer": DEFAULT_NAME,
|
||||
}
|
||||
|
||||
@abstractmethod
|
||||
def _handle_update(self, *args, **kwargs) -> None:
|
||||
"""Handle incoming webhook data."""
|
||||
@ -125,11 +112,8 @@ class RachioSwitch(SwitchDevice):
|
||||
class RachioStandbySwitch(RachioSwitch):
|
||||
"""Representation of a standby status/button."""
|
||||
|
||||
def __init__(self, hass, controller):
|
||||
def __init__(self, controller):
|
||||
"""Instantiate a new Rachio standby mode switch."""
|
||||
dispatcher_connect(
|
||||
hass, SIGNAL_RACHIO_CONTROLLER_UPDATE, self._handle_any_update
|
||||
)
|
||||
super().__init__(controller, poll=True)
|
||||
self._poll_update(controller.init_data)
|
||||
|
||||
@ -172,11 +156,17 @@ class RachioStandbySwitch(RachioSwitch):
|
||||
"""Resume controller functionality."""
|
||||
self._controller.rachio.device.on(self._controller.controller_id)
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Subscribe to updates."""
|
||||
async_dispatcher_connect(
|
||||
self.hass, SIGNAL_RACHIO_CONTROLLER_UPDATE, self._handle_any_update
|
||||
)
|
||||
|
||||
|
||||
class RachioZone(RachioSwitch):
|
||||
"""Representation of one zone of sprinklers connected to the Rachio Iro."""
|
||||
|
||||
def __init__(self, hass, person, controller, data, current_schedule):
|
||||
def __init__(self, person, controller, data, current_schedule):
|
||||
"""Initialize a new Rachio Zone."""
|
||||
self._id = data[KEY_ID]
|
||||
self._zone_name = data[KEY_NAME]
|
||||
@ -189,9 +179,6 @@ class RachioZone(RachioSwitch):
|
||||
super().__init__(controller, poll=False)
|
||||
self._state = self.zone_id == self._current_schedule.get(KEY_ZONE_ID)
|
||||
|
||||
# Listen for all zone updates
|
||||
dispatcher_connect(hass, SIGNAL_RACHIO_ZONE_UPDATE, self._handle_update)
|
||||
|
||||
def __str__(self):
|
||||
"""Display the zone as a string."""
|
||||
return 'Rachio Zone "{}" on {}'.format(self.name, str(self._controller))
|
||||
@ -272,3 +259,9 @@ class RachioZone(RachioSwitch):
|
||||
self._state = False
|
||||
|
||||
self.schedule_update_ha_state()
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Subscribe to updates."""
|
||||
async_dispatcher_connect(
|
||||
self.hass, SIGNAL_RACHIO_ZONE_UPDATE, self._handle_update
|
||||
)
|
||||
|
Loading…
x
Reference in New Issue
Block a user