Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use voluptuous for system monitoring sensors #2813

Merged
merged 3 commits into from
Aug 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions homeassistant/components/sensor/cpuspeed.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,38 @@
"""
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

REQUIREMENTS = ['py-cpuinfo==0.2.3']

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = "CPU speed"
DEFAULT_NAME = 'CPU speed'
ATTR_VENDOR = 'Vendor ID'
ATTR_BRAND = 'Brand'
ATTR_HZ = 'GHz Advertised'
ICON = 'mdi:pulse'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})

_LOGGER = logging.getLogger(__name__)


# pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the CPU speed sensor."""
add_devices([CpuSpeedSensor(config.get('name', DEFAULT_NAME))])
name = config.get(CONF_NAME)

add_devices([CpuSpeedSensor(name)])


class CpuSpeedSensor(Entity):
"""Representation a CPU sensor."""
"""Representation of a CPU sensor."""

def __init__(self, name):
"""Initialize the sensor."""
Expand Down
43 changes: 22 additions & 21 deletions homeassistant/components/sensor/glances.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@
from datetime import timedelta

import requests
import voluptuous as vol

from homeassistant.const import STATE_UNKNOWN
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_PORT, STATE_UNKNOWN, CONF_NAME, CONF_RESOURCES)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Glances'
DEFAULT_HOST = 'localhost'
_RESOURCE = 'api/2/all'
DEFAULT_PORT = '61208'

_RESOURCE = '/api/2/all'
CONF_HOST = 'host'
CONF_PORT = '61208'
CONF_RESOURCES = 'resources'
SENSOR_TYPES = {
'disk_use_percent': ['Disk Use', '%'],
'disk_use': ['Disk Use', 'GiB'],
Expand All @@ -36,33 +39,34 @@
'process_sleeping': ['Sleeping', None]
}

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)]),
})

_LOGGER = logging.getLogger(__name__)

# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)


# pylint: disable=unused-variable
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Glances sensor."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get('port', CONF_PORT)
url = 'http://{}:{}{}'.format(host, port, _RESOURCE)
port = config.get(CONF_PORT)
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:
response = requests.get(url, timeout=10)
if not response.ok:
_LOGGER.error('Response status is "%s"', response.status_code)
return False
except requests.exceptions.MissingSchema:
_LOGGER.error("Missing resource or schema in configuration. "
"Please check the details in the configuration file")
return False
except requests.exceptions.ConnectionError:
_LOGGER.error("No route to resource/endpoint: %s", url)
return False
Expand All @@ -71,10 +75,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):

dev = []
for resource in var_conf:
if resource not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', resource)
else:
dev.append(GlancesSensor(rest, config.get('name'), resource))
dev.append(GlancesSensor(rest, name, resource))

add_devices(dev)

Expand Down
23 changes: 17 additions & 6 deletions homeassistant/components/sensor/systemmonitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@
"""
import logging

import voluptuous as vol

import homeassistant.util.dt as dt_util
from homeassistant.const import STATE_OFF, STATE_ON

from homeassistant.const import (CONF_RESOURCES, STATE_OFF, STATE_ON)
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv

REQUIREMENTS = ['psutil==4.3.0']

SENSOR_TYPES = {
'disk_use_percent': ['Disk Use', '%', 'mdi:harddisk'],
'disk_use': ['Disk Use', 'GiB', 'mdi:harddisk'],
Expand All @@ -33,20 +39,25 @@
'since_last_boot': ['Since Last Boot', '', 'mdi:clock']
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_RESOURCES, default=['disk_use']):
vol.All(cv.ensure_list, [vol.Schema({
vol.Required('type'): vol.In(SENSOR_TYPES),
vol.Optional('arg'): cv.string,
})])
})

_LOGGER = logging.getLogger(__name__)


# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the System sensors."""
dev = []
for resource in config['resources']:
for resource in config[CONF_RESOURCES]:
if 'arg' not in resource:
resource['arg'] = ''
if resource['type'] not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', resource['type'])
else:
dev.append(SystemMonitorSensor(resource['type'], resource['arg']))
dev.append(SystemMonitorSensor(resource['type'], resource['arg']))

add_devices(dev)

Expand Down
2 changes: 2 additions & 0 deletions homeassistant/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
CONF_PENDING_TIME = 'pending_time'
CONF_PLATFORM = 'platform'
CONF_PORT = 'port'
CONF_RESOURCE = 'resource'
CONF_RESOURCES = 'resources'
CONF_SCAN_INTERVAL = 'scan_interval'
CONF_STATE = 'state'
CONF_TEMPERATURE_UNIT = 'temperature_unit'
Expand Down