Skip to content

Commit

Permalink
Fixed I/O inside the event loop
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberjunky committed Apr 29, 2020
1 parent f8734fe commit c533d43
Showing 1 changed file with 100 additions and 49 deletions.
149 changes: 100 additions & 49 deletions custom_components/hvcgroep/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,26 @@
configuration.yaml
sensor:
- platform: hvcgroep
postcode: 1234AB
huisnummer: 1
resources:
- gft
- plastic
- papier
- restafval
- platform: hvcgroep
postcode: 1234AB
huisnummer: 1
resources:
- gft
- plastic
- papier
- restafval
"""
import logging
from datetime import timedelta
from datetime import datetime
import requests
import voluptuous as vol

import aiohttp
import asyncio
import async_timeout

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_SCAN_INTERVAL, CONF_RESOURCES
Expand Down Expand Up @@ -62,9 +66,9 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
huisnummer = config.get(CONST_HUISNUMMER)
default_name = config.get(CONF_NAME)

data = TrashData(postcode, huisnummer)
trashdata = TrashData(hass, postcode, huisnummer)
try:
await data.async_update()
await trashdata.async_update()
except ValueError as err:
_LOGGER.error("Error while fetching data from HVCGroep: %s", err)
return
Expand All @@ -76,8 +80,8 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
id = TRASH_TYPES[resource][0]
icon = TRASH_TYPES[resource][2]

_LOGGER.debug("Adding HVCGroep sensor: {}, {}, {}, {}".format(trash_type, name, id, icon))
entities.append(TrashSensor(data, trash_type, name, id, icon))
_LOGGER.debug("Adding HVCGroep sensor: {}, {}, {}, {}".format(name, trash_type, id, icon))
entities.append(TrashSensor(trashdata, name, trash_type, id, icon))

async_add_entities(entities, True)

Expand All @@ -86,21 +90,51 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
class TrashData(object):
"""Handle HVCGroep object and limit updates."""

def __init__(self, postcode, huisnummer):
def __init__(self, hass, postcode, huisnummer):
"""Initialize."""
self._hass = hass
self._postcode = postcode
self._huisnummer = huisnummer
self._bagid = None
self._data = None


async def _get_bagid(self):

"""Get the bagid using postcode and huisnummer."""
try:
json_data = requests.get(self._build_bagid_url(), timeout=5).json()
websession = async_get_clientsession(self._hass)
with async_timeout.timeout(5):
response = await websession.get(self._build_bagid_url())
_LOGGER.debug(
"Response status from HVC bagid: %s", response.status
)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Cannot connect to HVC for bagid: %s", err)
self._data = None
return
except Exception as err:
_LOGGER.error("Error downloading bagid from HVC: %s", err)
self._data = None
return

try:
json_data = await response.json()
_LOGGER.debug("Data received from HVC: %s", json_data)
self._bagid = json_data[0]["bagId"]
_LOGGER.debug("Found BagId = %s", self._bagid)
except (requests.exceptions.RequestException) as error:
_LOGGER.error("Unable to get BagId from HVCGroep: %s", error)

except Exception as err:
_LOGGER.error("Cannot parse data from HVC: %s", err)
self._data = None
return

# try:
# json_data = requests.get(self._build_bagid_url(), timeout=5).json()
# self._bagid = json_data[0]["bagId"]
# _LOGGER.debug("Found BagId = %s", self._bagid)
# except (requests.exceptions.RequestException) as error:
# _LOGGER.error("Unable to get BagId from HVCGroep: %s", error)

def _build_bagid_url(self):
"""Build the URL for the requests."""
url = BAGID_URL.format(self._postcode, self._huisnummer)
Expand All @@ -123,14 +157,33 @@ def latest_data(self):
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the afvalstromen data."""
if not self._bagid:
await self._get_bagid()

trashschedule = []
try:
json_data = requests.get(self._build_waste_url(), timeout=5).json()
_LOGGER.debug("Afvalstromen fetched data = %s", json_data)
except requests.exceptions.RequestException:
_LOGGER.error("Unable to get afvalstromen data from HVCGroep: %s", error)
websession = async_get_clientsession(self._hass)
with async_timeout.timeout(5):
response = await websession.get(self._build_waste_url())
_LOGGER.debug(
"Response status from HVC: %s", response.status
)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Cannot connect to HVC: %s", err)
self._data = None
return False
return
except Exception as err:
_LOGGER.error("Error downloading bagid from HVC: %s", err)
self._data = None
return

try:
json_data = await response.json()
_LOGGER.debug("Data received from HVC: %s", json_data)
except Exception as err:
_LOGGER.error("Cannot parse data from HVC: %s", err)
self._data = None
return

"""Parse the afvalstromen data."""
try:
Expand All @@ -152,11 +205,11 @@ async def async_update(self):
class TrashSensor(Entity):
"""Representation of a HVCGroep Sensor."""

def __init__(self, data, trash_type, name, id, icon):
def __init__(self, trashdata, name, trash_type, id, icon):
"""Initialize the sensor."""
self._data = data
self._trash_type = trash_type
self._trashdata = trashdata
self._name = name
self._trash_type = trash_type
self._id = id
self._icon = icon

Expand Down Expand Up @@ -188,29 +241,27 @@ def device_state_attributes(self):
async def async_update(self):
"""Get the latest data and use it to update our sensor state."""

await self._data.async_update()
if not self._data:
_LOGGER.error("Didn't receive data from TOON")
return
await self._trashdata.async_update()
trashdata = self._trashdata.latest_data

trashdata = self._data.latest_data
today = datetime.today()

for d in trashdata:
pickupdate = d['date']
datediff = (pickupdate - today).days + 1
if d['id'] == self._id:
if datediff > 1:
self._state = pickupdate.strftime('%d-%m-%Y')
self._day = None
elif datediff == 1:
self._state = pickupdate.strftime('Morgen %d-%m-%Y')
self._day = "Morgen"
elif datediff <= 0:
self._state = pickupdate.strftime('Vandaag %d-%m-%Y')
self._day = "Vandaag"
else:
self._state = None
self._day = None

_LOGGER.debug("Device id: {} State: {}".format(self._id, self._state))
if trashdata:
for d in trashdata:
pickupdate = d['date']
datediff = (pickupdate - today).days + 1
if d['id'] == self._id:
if datediff > 1:
self._state = pickupdate.strftime('%d-%m-%Y')
self._day = None
elif datediff == 1:
self._state = pickupdate.strftime('Morgen %d-%m-%Y')
self._day = "Morgen"
elif datediff <= 0:
self._state = pickupdate.strftime('Vandaag %d-%m-%Y')
self._day = "Vandaag"
else:
self._state = None
self._day = None

_LOGGER.debug("Device: {} State: {}".format(self._name, self._state))

0 comments on commit c533d43

Please sign in to comment.