diff --git a/custom_components/wibeee/sensor.py b/custom_components/wibeee/sensor.py index f764fe01c0..ae72839b1e 100755 --- a/custom_components/wibeee/sensor.py +++ b/custom_components/wibeee/sensor.py @@ -8,17 +8,16 @@ REQUIREMENTS = ["xmltodict"] -import asyncio - +import xml import logging import voluptuous as vol from datetime import timedelta -import aiohttp import async_timeout import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning + requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import homeassistant.helpers.config_validation as cv @@ -54,12 +53,10 @@ _LOGGER = logging.getLogger(__name__) - BASE_URL = 'http://{0}:{1}/{2}' -PORT=80 +PORT = 80 API_PATH = 'en/status.xml' - DOMAIN = 'wibeee_energy' DEFAULT_NAME = 'Wibeee Energy Consumption Sensor' DEFAULT_HOST = '' @@ -86,6 +83,7 @@ 'energia_reactiva_cap': ['Capacitive Reactive Energy', 'VArCh', DEVICE_CLASS_ENERGY] } + async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the RESTful sensor.""" _LOGGER.debug("Setting up Wibeee Sensors...") @@ -158,9 +156,10 @@ def should_poll(self): class WibeeeData(object): """Gets the latest data from Wibeee sensors.""" + def __init__(self, hass, sensor_name_suffix, url_api): """Initialize the data object.""" - _LOGGER.debug("Initializating WibeeeData with url:%s", url_api) + _LOGGER.debug("Initializing WibeeeData with url: %s", url_api) self.hass = hass self.sensor_name_suffix = sensor_name_suffix @@ -172,7 +171,6 @@ def __init__(self, hass, sensor_name_suffix, url_api): self.sensors = None self.data = None - async def set_sensors(self): """Make first Get call to Initialize sensor names""" try: @@ -180,8 +178,7 @@ async def set_sensors(self): resp = await self.session.get(self.url_api) resp.raise_for_status() if resp.status != 200: - try_again("{} returned {}".format(self.url_api, resp.status)) - return(None) + return (None) else: xml_data = await resp.text() _LOGGER.debug("RAW Response from %s: %s)", self.url_api, xml_data) @@ -215,23 +212,22 @@ async def set_sensors(self): #@Throttle(MIN_TIME_BETWEEN_UPDATES) async def fetching_data(self, *_): """ Function to fetch REST Data and transform XML to data to DICT format """ + xml_data = None try: with async_timeout.timeout(10, loop=self.hass.loop): resp = await self.session.get(self.url_api) resp.raise_for_status() if resp.status != 200: - try_again("{} returned {}".format(self.url_api, resp.status)) return(None) else: xml_data = await resp.text() dict_data = xmltodict.parse(xml_data) self.data = dict_data["response"] - except (requests.exceptions.HTTPError, aiohttp.ClientError, asyncio.TimeoutError, ValueError) as exc: - _LOGGER.error('{}: {}'.format(exc.__class__.__name__, str(exc))) - return(None) - except: - _LOGGER.error('unexpected exception for get %s', self.url_api) - return(None) + except Exception as exc: + _LOGGER.error('Error while getting %s: %s: %s', self.url_api, exc.__class__.__name__, exc, exc_info=True) + if isinstance(exc, xml.parsers.expat.ExpatError): + _LOGGER.debug('Received XML:\n%s', xml_data) + return (None) self.updating_sensors()