Add Rainmachine config entry (#18419)

* Initial stuff

* More work in place

* Starting with tests

* Device registry in place

* Hound

* Linting

* Member comments (including extracting device registry)

* Member comments (plus I forgot cleanup!)

* Hound

* More Hound

* Removed old import

* Adding config entry test to coverage

* Updated strings
This commit is contained in:
Aaron Bach authored and GitHub committed 2018-11-14 13:23:49 -07:00
1 parent 312872961f
commit 8aa1283adc
15 files changed
+400 -87

No files matched your search

@@ -9,25 +9,25 @@ from datetime import timedelta
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import (
ATTR_ATTRIBUTION, CONF_BINARY_SENSORS, CONF_IP_ADDRESS, CONF_PASSWORD,
CONF_PORT, CONF_SCAN_INTERVAL, CONF_SENSORS, CONF_SSL,
CONF_MONITORED_CONDITIONS, CONF_SWITCHES)
from homeassistant.helpers import (
aiohttp_client, config_validation as cv, discovery)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval
REQUIREMENTS = ['regenmaschine==1.0.2']
from .config_flow import configured_instances
from .const import DATA_CLIENT, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN
REQUIREMENTS = ['regenmaschine==1.0.7']
_LOGGER = logging.getLogger(__name__)
DATA_RAINMACHINE = 'data_rainmachine'
DOMAIN = 'rainmachine'
NOTIFICATION_ID = 'rainmachine_notification'
NOTIFICATION_TITLE = 'RainMachine Component Setup'
DATA_LISTENER = 'listener'
PROGRAM_UPDATE_TOPIC = '{0}_program_update'.format(DOMAIN)
SENSOR_UPDATE_TOPIC = '{0}_data_update'.format(DOMAIN)
@@ -39,8 +39,6 @@ CONF_ZONE_RUN_TIME = 'zone_run_time'
DEFAULT_ATTRIBUTION = 'Data provided by Green Electronics LLC'
DEFAULT_ICON = 'mdi:water'
DEFAULT_PORT = 8080
DEFAULT_SCAN_INTERVAL = timedelta(seconds=60)
DEFAULT_SSL = True
DEFAULT_ZONE_RUN = 60 * 10
@@ -120,48 +118,73 @@ CONFIG_SCHEMA = vol.Schema(
async def async_setup(hass, config):
"""Set up the RainMachine component."""
from regenmaschine import Client
from regenmaschine.errors import RequestError
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DATA_CLIENT] = {}
hass.data[DOMAIN][DATA_LISTENER] = {}
if DOMAIN not in config:
return True
conf = config[DOMAIN]
ip_address = conf[CONF_IP_ADDRESS]
password = conf[CONF_PASSWORD]
port = conf[CONF_PORT]
ssl = conf[CONF_SSL]
if conf[CONF_IP_ADDRESS] in configured_instances(hass):
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={'source': SOURCE_IMPORT},
data=conf))
return True
async def async_setup_entry(hass, config_entry):
"""Set up RainMachine as config entry."""
from regenmaschine import login
from regenmaschine.errors import RainMachineError
ip_address = config_entry.data[CONF_IP_ADDRESS]
password = config_entry.data[CONF_PASSWORD]
port = config_entry.data[CONF_PORT]
ssl = config_entry.data.get(CONF_SSL, DEFAULT_SSL)
websession = aiohttp_client.async_get_clientsession(hass)
try:
websession = aiohttp_client.async_get_clientsession(hass)
client = Client(ip_address, websession, port=port, ssl=ssl)
await client.authenticate(password)
rainmachine = RainMachine(client)
client = await login(
ip_address, password, websession, port=port, ssl=ssl)
rainmachine = RainMachine(
client,
config_entry.data.get(CONF_BINARY_SENSORS, {}).get(
CONF_MONITORED_CONDITIONS, list(BINARY_SENSORS)),
config_entry.data.get(CONF_SENSORS, {}).get(
CONF_MONITORED_CONDITIONS, list(SENSORS)),
config_entry.data.get(CONF_ZONE_RUN_TIME, DEFAULT_ZONE_RUN)
)
await rainmachine.async_update()
hass.data[DATA_RAINMACHINE] = rainmachine
except RequestError as err:
_LOGGER.error('An error occurred: %s', str(err))
hass.components.persistent_notification.create(
'Error: {0}<br />'
'You will need to restart hass after fixing.'
''.format(err),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID)
return False
except RainMachineError as err:
_LOGGER.error('An error occurred: %s', err)
raise ConfigEntryNotReady
for component, schema in [
('binary_sensor', conf[CONF_BINARY_SENSORS]),
('sensor', conf[CONF_SENSORS]),
('switch', conf[CONF_SWITCHES]),
]:
hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = rainmachine
for component in ('binary_sensor', 'sensor', 'switch'):
hass.async_create_task(
discovery.async_load_platform(hass, component, DOMAIN, schema,
config))
hass.config_entries.async_forward_entry_setup(
config_entry, component))
async def refresh_sensors(event_time):
async def refresh(event_time):
"""Refresh RainMachine sensor data."""
_LOGGER.debug('Updating RainMachine sensor data')
await rainmachine.async_update()
async_dispatcher_send(hass, SENSOR_UPDATE_TOPIC)
async_track_time_interval(hass, refresh_sensors, conf[CONF_SCAN_INTERVAL])
hass.data[DOMAIN][DATA_LISTENER][
config_entry.entry_id] = async_track_time_interval(
hass,
refresh,
timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL]))
async def start_program(service):
"""Start a particular program."""
@@ -170,8 +193,8 @@ async def async_setup(hass, config):
async def start_zone(service):
"""Start a particular zone for a certain amount of time."""
await rainmachine.client.zones.start(service.data[CONF_ZONE_ID],
service.data[CONF_ZONE_RUN_TIME])
await rainmachine.client.zones.start(
service.data[CONF_ZONE_ID], service.data[CONF_ZONE_RUN_TIME])
async_dispatcher_send(hass, ZONE_UPDATE_TOPIC)
async def stop_all(service):
@@ -201,14 +224,34 @@ async def async_setup(hass, config):
return True
async def async_unload_entry(hass, config_entry):
"""Unload an OpenUV config entry."""
hass.data[DOMAIN][DATA_CLIENT].pop(config_entry.entry_id)
remove_listener = hass.data[DOMAIN][DATA_LISTENER].pop(
config_entry.entry_id)
remove_listener()
for component in ('binary_sensor', 'sensor', 'switch'):
await hass.config_entries.async_forward_entry_unload(
config_entry, component)
return True
class RainMachine:
"""Define a generic RainMachine object."""
def __init__(self, client):
def __init__(
self, client, binary_sensor_conditions, sensor_conditions,
default_zone_runtime):
"""Initialize."""
self.binary_sensor_conditions = binary_sensor_conditions
self.client = client
self.default_zone_runtime = default_zone_runtime
self.device_mac = self.client.mac
self.restrictions = {}
self.sensor_conditions = sensor_conditions
async def async_update(self):
"""Update sensor/binary sensor data."""
@@ -224,6 +267,7 @@ class RainMachineEntity(Entity):
def __init__(self, rainmachine):
"""Initialize."""
self._attrs = {ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION}
self._async_unsub_dispatcher_connect = None
self._name = None
self.rainmachine = rainmachine