Add asyncio support for Ebox (#14183)

* Fix Ebox sensor

* Fix #14183 comments

* Update ebox.py

* Update ebox.py

* Continue fixing comments
This commit is contained in:
Thibault Cohen 2018-05-29 10:23:12 -04:00 committed by Paulus Schoutsen
parent 8c93b484c4
commit 4105429639
2 changed files with 30 additions and 18 deletions

View file

@ -9,7 +9,6 @@ https://home-assistant.io/components/sensor.ebox/
import logging import logging
from datetime import timedelta from datetime import timedelta
import requests
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
@ -18,9 +17,11 @@ from homeassistant.const import (
CONF_USERNAME, CONF_PASSWORD, CONF_USERNAME, CONF_PASSWORD,
CONF_NAME, CONF_MONITORED_VARIABLES) CONF_NAME, CONF_MONITORED_VARIABLES)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from homeassistant.exceptions import PlatformNotReady
# pylint: disable=import-error
REQUIREMENTS = [] # ['pyebox==0.1.0'] - disabled because it breaks pip10 REQUIREMENTS = ['pyebox==1.1.4']
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -32,7 +33,8 @@ PERCENT = '%' # type: str
DEFAULT_NAME = 'EBox' DEFAULT_NAME = 'EBox'
REQUESTS_TIMEOUT = 15 REQUESTS_TIMEOUT = 15
SCAN_INTERVAL = timedelta(minutes=5) SCAN_INTERVAL = timedelta(minutes=15)
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15)
SENSOR_TYPES = { SENSOR_TYPES = {
'usage': ['Usage', PERCENT, 'mdi:percent'], 'usage': ['Usage', PERCENT, 'mdi:percent'],
@ -62,25 +64,29 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
def setup_platform(hass, config, add_devices, discovery_info=None): async def async_setup_platform(hass, config, async_add_devices,
discovery_info=None):
"""Set up the EBox sensor.""" """Set up the EBox sensor."""
username = config.get(CONF_USERNAME) username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD) password = config.get(CONF_PASSWORD)
try: httpsession = hass.helpers.aiohttp_client.async_get_clientsession()
ebox_data = EBoxData(username, password) ebox_data = EBoxData(username, password, httpsession)
ebox_data.update()
except requests.exceptions.HTTPError as error:
_LOGGER.error("Failed login: %s", error)
return False
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
from pyebox.client import PyEboxError
try:
await ebox_data.async_update()
except PyEboxError as exp:
_LOGGER.error("Failed login: %s", exp)
raise PlatformNotReady
sensors = [] sensors = []
for variable in config[CONF_MONITORED_VARIABLES]: for variable in config[CONF_MONITORED_VARIABLES]:
sensors.append(EBoxSensor(ebox_data, variable, name)) sensors.append(EBoxSensor(ebox_data, variable, name))
add_devices(sensors, True) async_add_devices(sensors, True)
class EBoxSensor(Entity): class EBoxSensor(Entity):
@ -116,9 +122,9 @@ class EBoxSensor(Entity):
"""Icon to use in the frontend, if any.""" """Icon to use in the frontend, if any."""
return self._icon return self._icon
def update(self): async def async_update(self):
"""Get the latest data from EBox and update the state.""" """Get the latest data from EBox and update the state."""
self.ebox_data.update() await self.ebox_data.async_update()
if self.type in self.ebox_data.data: if self.type in self.ebox_data.data:
self._state = round(self.ebox_data.data[self.type], 2) self._state = round(self.ebox_data.data[self.type], 2)
@ -126,18 +132,21 @@ class EBoxSensor(Entity):
class EBoxData(object): class EBoxData(object):
"""Get data from Ebox.""" """Get data from Ebox."""
def __init__(self, username, password): def __init__(self, username, password, httpsession):
"""Initialize the data object.""" """Initialize the data object."""
from pyebox import EboxClient from pyebox import EboxClient
self.client = EboxClient(username, password, REQUESTS_TIMEOUT) self.client = EboxClient(username, password,
REQUESTS_TIMEOUT, httpsession)
self.data = {} self.data = {}
def update(self): @Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the latest data from Ebox.""" """Get the latest data from Ebox."""
from pyebox.client import PyEboxError from pyebox.client import PyEboxError
try: try:
self.client.fetch_data() await self.client.fetch_data()
except PyEboxError as exp: except PyEboxError as exp:
_LOGGER.error("Error on receive last EBox data: %s", exp) _LOGGER.error("Error on receive last EBox data: %s", exp)
return return
# Update data
self.data = self.client.get_data() self.data = self.client.get_data()

View file

@ -774,6 +774,9 @@ pydispatcher==2.0.5
# homeassistant.components.android_ip_webcam # homeassistant.components.android_ip_webcam
pydroid-ipcam==0.8 pydroid-ipcam==0.8
# homeassistant.components.sensor.ebox
pyebox==1.1.4
# homeassistant.components.climate.econet # homeassistant.components.climate.econet
pyeconet==0.0.5 pyeconet==0.0.5