Skip to content

Commit

Permalink
fix: improve error logging to allow bug reports (#8)
Browse files Browse the repository at this point in the history
* fix: clean up error logging, ensure traceback is available for bug reports

* fix: dump XML as debug log when there is a parsing error
  • Loading branch information
luuuis authored Aug 25, 2021
1 parent a8d75c3 commit 3d0297e
Showing 1 changed file with 13 additions and 17 deletions.
30 changes: 13 additions & 17 deletions custom_components/wibeee/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = ''
Expand All @@ -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...")
Expand Down Expand Up @@ -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
Expand All @@ -172,16 +171,14 @@ 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:
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)
return (None)
else:
xml_data = await resp.text()
_LOGGER.debug("RAW Response from %s: %s)", self.url_api, xml_data)
Expand Down Expand Up @@ -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()

Expand Down

0 comments on commit 3d0297e

Please sign in to comment.