Improve error messages, use constants, and fix docstrings
This commit is contained in:
parent
bc48e4f98e
commit
646618a25e
1 changed files with 45 additions and 39 deletions
|
@ -12,11 +12,14 @@ from datetime import timedelta
|
||||||
|
|
||||||
from homeassistant.util import Throttle
|
from homeassistant.util import Throttle
|
||||||
from homeassistant.helpers.entity import Entity
|
from homeassistant.helpers.entity import Entity
|
||||||
|
from homeassistant.const import STATE_UNKNOWN
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
DEFAULT_NAME = 'Glances Sensor'
|
|
||||||
_RESOURCE = '/api/2/all'
|
_RESOURCE = '/api/2/all'
|
||||||
|
CONF_HOST = 'host'
|
||||||
|
CONF_PORT = '61208'
|
||||||
|
CONF_RESOURCES = 'resources'
|
||||||
SENSOR_TYPES = {
|
SENSOR_TYPES = {
|
||||||
'disk_use_percent': ['Disk Use', '%'],
|
'disk_use_percent': ['Disk Use', '%'],
|
||||||
'disk_use': ['Disk Use', 'GiB'],
|
'disk_use': ['Disk Use', 'GiB'],
|
||||||
|
@ -43,13 +46,15 @@ MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
|
||||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
""" Setup the Glances sensor. """
|
""" Setup the Glances sensor. """
|
||||||
|
|
||||||
if not config.get('host'):
|
host = config.get(CONF_HOST)
|
||||||
_LOGGER.error('"host:" is missing your configuration')
|
port = config.get('port', CONF_PORT)
|
||||||
return False
|
|
||||||
|
|
||||||
host = config.get('host')
|
|
||||||
port = config.get('port', 61208)
|
|
||||||
url = 'http://{}:{}{}'.format(host, port, _RESOURCE)
|
url = 'http://{}:{}{}'.format(host, port, _RESOURCE)
|
||||||
|
var_conf = config.get(CONF_RESOURCES)
|
||||||
|
|
||||||
|
if None in (host, var_conf):
|
||||||
|
_LOGGER.error('Not all required config keys present: %s',
|
||||||
|
', '.join((CONF_HOST, CONF_RESOURCES)))
|
||||||
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.get(url, timeout=10)
|
response = requests.get(url, timeout=10)
|
||||||
|
@ -57,18 +62,19 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
_LOGGER.error('Response status is "%s"', response.status_code)
|
_LOGGER.error('Response status is "%s"', response.status_code)
|
||||||
return False
|
return False
|
||||||
except requests.exceptions.MissingSchema:
|
except requests.exceptions.MissingSchema:
|
||||||
_LOGGER.error('Missing resource or schema in configuration. '
|
_LOGGER.error("Missing resource or schema in configuration. "
|
||||||
'Please heck our details in the configuration file.')
|
"Please check the details in the configuration file.")
|
||||||
return False
|
return False
|
||||||
except requests.exceptions.ConnectionError:
|
except requests.exceptions.ConnectionError:
|
||||||
_LOGGER.error('No route to resource/endpoint. '
|
_LOGGER.error("No route to resource/endpoint: '%s'. "
|
||||||
'Please check the details in the configuration file.')
|
"Please check the details in the configuration file.",
|
||||||
|
url)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
rest = GlancesData(url)
|
rest = GlancesData(url)
|
||||||
|
|
||||||
dev = []
|
dev = []
|
||||||
for resource in config['resources']:
|
for resource in var_conf:
|
||||||
if resource not in SENSOR_TYPES:
|
if resource not in SENSOR_TYPES:
|
||||||
_LOGGER.error('Sensor type: "%s" does not exist', resource)
|
_LOGGER.error('Sensor type: "%s" does not exist', resource)
|
||||||
else:
|
else:
|
||||||
|
@ -78,13 +84,13 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
|
|
||||||
|
|
||||||
class GlancesSensor(Entity):
|
class GlancesSensor(Entity):
|
||||||
""" Implements a REST sensor. """
|
""" Implements a Glances sensor. """
|
||||||
|
|
||||||
def __init__(self, rest, sensor_type):
|
def __init__(self, rest, sensor_type):
|
||||||
self.rest = rest
|
self.rest = rest
|
||||||
self._name = SENSOR_TYPES[sensor_type][0]
|
self._name = SENSOR_TYPES[sensor_type][0]
|
||||||
self.type = sensor_type
|
self.type = sensor_type
|
||||||
self._state = None
|
self._state = STATE_UNKNOWN
|
||||||
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
|
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
|
||||||
self.update()
|
self.update()
|
||||||
|
|
||||||
|
@ -98,46 +104,45 @@ class GlancesSensor(Entity):
|
||||||
""" Unit the value is expressed in. """
|
""" Unit the value is expressed in. """
|
||||||
return self._unit_of_measurement
|
return self._unit_of_measurement
|
||||||
|
|
||||||
|
# pylint: disable=too-many-branches, too-many-return-statements
|
||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
""" Returns the state of the device. """
|
""" Returns the state of the resources. """
|
||||||
return self._state
|
|
||||||
|
|
||||||
# pylint: disable=too-many-branches
|
|
||||||
def update(self):
|
|
||||||
""" Gets the latest data from REST API and updates the state. """
|
|
||||||
self.rest.update()
|
|
||||||
value = self.rest.data
|
value = self.rest.data
|
||||||
|
|
||||||
if value is not None:
|
if value is not None:
|
||||||
if self.type == 'disk_use_percent':
|
if self.type == 'disk_use_percent':
|
||||||
self._state = value['fs'][0]['percent']
|
return value['fs'][0]['percent']
|
||||||
elif self.type == 'disk_use':
|
elif self.type == 'disk_use':
|
||||||
self._state = round(value['fs'][0]['used'] / 1024**3, 1)
|
return round(value['fs'][0]['used'] / 1024**3, 1)
|
||||||
elif self.type == 'disk_free':
|
elif self.type == 'disk_free':
|
||||||
self._state = round(value['fs'][0]['free'] / 1024**3, 1)
|
return round(value['fs'][0]['free'] / 1024**3, 1)
|
||||||
elif self.type == 'memory_use_percent':
|
elif self.type == 'memory_use_percent':
|
||||||
self._state = value['mem']['percent']
|
return value['mem']['percent']
|
||||||
elif self.type == 'memory_use':
|
elif self.type == 'memory_use':
|
||||||
self._state = round(value['mem']['used'] / 1024**2, 1)
|
return round(value['mem']['used'] / 1024**2, 1)
|
||||||
elif self.type == 'memory_free':
|
elif self.type == 'memory_free':
|
||||||
self._state = round(value['mem']['free'] / 1024**2, 1)
|
return round(value['mem']['free'] / 1024**2, 1)
|
||||||
elif self.type == 'swap_use_percent':
|
elif self.type == 'swap_use_percent':
|
||||||
self._state = value['memswap']['percent']
|
return value['memswap']['percent']
|
||||||
elif self.type == 'swap_use':
|
elif self.type == 'swap_use':
|
||||||
self._state = round(value['memswap']['used'] / 1024**3, 1)
|
return round(value['memswap']['used'] / 1024**3, 1)
|
||||||
elif self.type == 'swap_free':
|
elif self.type == 'swap_free':
|
||||||
self._state = round(value['memswap']['free'] / 1024**3, 1)
|
return round(value['memswap']['free'] / 1024**3, 1)
|
||||||
elif self.type == 'processor_load':
|
elif self.type == 'processor_load':
|
||||||
self._state = value['load']['min15']
|
return value['load']['min15']
|
||||||
elif self.type == 'process_running':
|
elif self.type == 'process_running':
|
||||||
self._state = value['processcount']['running']
|
return value['processcount']['running']
|
||||||
elif self.type == 'process_total':
|
elif self.type == 'process_total':
|
||||||
self._state = value['processcount']['total']
|
return value['processcount']['total']
|
||||||
elif self.type == 'process_thread':
|
elif self.type == 'process_thread':
|
||||||
self._state = value['processcount']['thread']
|
return value['processcount']['thread']
|
||||||
elif self.type == 'process_sleeping':
|
elif self.type == 'process_sleeping':
|
||||||
self._state = value['processcount']['sleeping']
|
return value['processcount']['sleeping']
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
""" Gets the latest data from REST API. """
|
||||||
|
self.rest.update()
|
||||||
|
|
||||||
|
|
||||||
# pylint: disable=too-few-public-methods
|
# pylint: disable=too-few-public-methods
|
||||||
|
@ -145,15 +150,16 @@ class GlancesData(object):
|
||||||
""" Class for handling the data retrieval. """
|
""" Class for handling the data retrieval. """
|
||||||
|
|
||||||
def __init__(self, resource):
|
def __init__(self, resource):
|
||||||
self.resource = resource
|
self._resource = resource
|
||||||
self.data = dict()
|
self.data = dict()
|
||||||
|
|
||||||
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
||||||
def update(self):
|
def update(self):
|
||||||
""" Gets the latest data from REST service. """
|
""" Gets the latest data from teh Glances REST API. """
|
||||||
try:
|
try:
|
||||||
response = requests.get(self.resource, timeout=10)
|
response = requests.get(self._resource, timeout=10)
|
||||||
self.data = response.json()
|
self.data = response.json()
|
||||||
except requests.exceptions.ConnectionError:
|
except requests.exceptions.ConnectionError:
|
||||||
_LOGGER.error("No route to host/endpoint.")
|
_LOGGER.error("No route to host/endpoint '%s'. Is device offline?",
|
||||||
|
self._resource)
|
||||||
self.data = None
|
self.data = None
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue