core/homeassistant/components/sensor/glances.py

169 lines
5.7 KiB
Python
Raw Normal View History

2015-09-14 12:08:30 +00:00
"""
2016-10-01 15:35:32 +00:00
Support gathering system information of hosts which are running glances.
2015-09-14 12:08:30 +00:00
For more details about this platform, please refer to the documentation at
2015-11-09 12:12:18 +00:00
https://home-assistant.io/components/sensor.glances/
2015-09-14 12:08:30 +00:00
"""
import logging
2016-02-19 05:27:50 +00:00
from datetime import timedelta
2015-11-29 21:49:05 +00:00
2015-09-14 12:08:30 +00:00
import requests
import voluptuous as vol
2015-09-14 12:08:30 +00:00
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_PORT, STATE_UNKNOWN, CONF_NAME, CONF_RESOURCES)
2016-02-19 05:27:50 +00:00
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv
2015-09-14 12:08:30 +00:00
_LOGGER = logging.getLogger(__name__)
_RESOURCE = 'api/2/all'
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'Glances'
DEFAULT_PORT = '61208'
2015-09-14 12:08:30 +00:00
2016-10-01 15:35:32 +00:00
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
2015-09-14 12:08:30 +00:00
SENSOR_TYPES = {
'disk_use_percent': ['Disk Use', '%'],
'disk_use': ['Disk Use', 'GiB'],
'disk_free': ['Disk Free', 'GiB'],
'memory_use_percent': ['RAM Use', '%'],
'memory_use': ['RAM Use', 'MiB'],
'memory_free': ['RAM Free', 'MiB'],
'swap_use_percent': ['Swap Use', '%'],
'swap_use': ['Swap Use', 'GiB'],
'swap_free': ['Swap Free', 'GiB'],
2016-10-01 15:35:32 +00:00
'processor_load': ['CPU Load', '15 min'],
'process_running': ['Running', 'Count'],
'process_total': ['Total', 'Count'],
'process_thread': ['Thread', 'Count'],
'process_sleeping': ['Sleeping', 'Count']
2015-09-14 12:08:30 +00:00
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_RESOURCES, default=['disk_use']):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})
2015-09-14 12:08:30 +00:00
# pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-02-23 05:21:49 +00:00
"""Setup the Glances sensor."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
url = 'http://{}:{}/{}'.format(host, port, _RESOURCE)
var_conf = config.get(CONF_RESOURCES)
2015-09-14 12:08:30 +00:00
try:
response = requests.get(url, timeout=10)
if not response.ok:
2016-10-01 15:35:32 +00:00
_LOGGER.error("Response status is '%s'", response.status_code)
2015-09-15 06:21:58 +00:00
return False
2015-09-14 12:08:30 +00:00
except requests.exceptions.ConnectionError:
2016-03-15 22:52:55 +00:00
_LOGGER.error("No route to resource/endpoint: %s", url)
2015-09-14 12:08:30 +00:00
return False
rest = GlancesData(url)
dev = []
for resource in var_conf:
dev.append(GlancesSensor(rest, name, resource))
2015-09-14 12:08:30 +00:00
add_devices(dev)
class GlancesSensor(Entity):
2016-03-08 15:46:34 +00:00
"""Implementation of a Glances sensor."""
2015-09-14 12:08:30 +00:00
2015-12-15 22:12:43 +00:00
def __init__(self, rest, name, sensor_type):
2016-03-08 15:46:34 +00:00
"""Initialize the sensor."""
2015-09-14 12:08:30 +00:00
self.rest = rest
2015-12-15 22:12:43 +00:00
self._name = name
2015-09-14 12:08:30 +00:00
self.type = sensor_type
self._state = STATE_UNKNOWN
2015-09-14 12:08:30 +00:00
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.update()
@property
def name(self):
2016-02-23 05:21:49 +00:00
"""The name of the sensor."""
2015-12-15 22:12:43 +00:00
if self._name is None:
return SENSOR_TYPES[self.type][0]
else:
return '{} {}'.format(self._name, SENSOR_TYPES[self.type][0])
2015-09-14 12:08:30 +00:00
@property
def unit_of_measurement(self):
2016-03-08 15:46:34 +00:00
"""Return the unit the value is expressed in."""
2015-09-14 12:08:30 +00:00
return self._unit_of_measurement
# pylint: disable=too-many-return-statements
2015-09-14 12:08:30 +00:00
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the resources."""
2015-09-14 12:08:30 +00:00
value = self.rest.data
if value is not None:
if self.type == 'disk_use_percent':
return value['fs'][0]['percent']
2015-09-14 12:08:30 +00:00
elif self.type == 'disk_use':
return round(value['fs'][0]['used'] / 1024**3, 1)
2015-09-14 12:08:30 +00:00
elif self.type == 'disk_free':
try:
return round(value['fs'][0]['free'] / 1024**3, 1)
except KeyError:
return round((value['fs'][0]['size'] -
2015-11-19 17:07:54 +00:00
value['fs'][0]['used']) / 1024**3, 1)
2015-09-14 12:08:30 +00:00
elif self.type == 'memory_use_percent':
return value['mem']['percent']
2015-09-14 12:08:30 +00:00
elif self.type == 'memory_use':
return round(value['mem']['used'] / 1024**2, 1)
2015-09-14 12:08:30 +00:00
elif self.type == 'memory_free':
return round(value['mem']['free'] / 1024**2, 1)
2015-09-14 12:08:30 +00:00
elif self.type == 'swap_use_percent':
return value['memswap']['percent']
2015-09-14 12:08:30 +00:00
elif self.type == 'swap_use':
return round(value['memswap']['used'] / 1024**3, 1)
2015-09-14 12:08:30 +00:00
elif self.type == 'swap_free':
return round(value['memswap']['free'] / 1024**3, 1)
2015-09-14 12:08:30 +00:00
elif self.type == 'processor_load':
return value['load']['min15']
2015-09-14 12:08:30 +00:00
elif self.type == 'process_running':
return value['processcount']['running']
2015-09-14 12:08:30 +00:00
elif self.type == 'process_total':
return value['processcount']['total']
2015-09-14 12:08:30 +00:00
elif self.type == 'process_thread':
return value['processcount']['thread']
2015-09-14 12:08:30 +00:00
elif self.type == 'process_sleeping':
return value['processcount']['sleeping']
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from REST API."""
self.rest.update()
2015-09-14 12:08:30 +00:00
class GlancesData(object):
2016-03-08 15:46:34 +00:00
"""The class for handling the data retrieval."""
2015-09-14 12:08:30 +00:00
def __init__(self, resource):
2016-03-08 15:46:34 +00:00
"""Initialize the data object."""
self._resource = resource
2015-09-14 12:08:30 +00:00
self.data = dict()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data from the Glances REST API."""
2015-09-14 12:08:30 +00:00
try:
response = requests.get(self._resource, timeout=10)
2015-09-14 12:08:30 +00:00
self.data = response.json()
except requests.exceptions.ConnectionError:
2016-03-15 22:52:55 +00:00
_LOGGER.error("No route to host/endpoint: %s", self._resource)
2015-09-14 12:08:30 +00:00
self.data = None