core/homeassistant/components/sensor/speedtest.py

168 lines
5.3 KiB
Python
Raw Normal View History

2016-02-04 23:21:37 +00:00
"""
2016-11-25 20:30:53 +00:00
Support for Speedtest.net.
2016-02-04 23:21:37 +00:00
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.speedtest/
"""
import asyncio
2016-02-04 23:21:37 +00:00
import logging
import re
2016-02-19 05:27:50 +00:00
import sys
from subprocess import check_output, CalledProcessError
2016-11-25 20:30:53 +00:00
import voluptuous as vol
2016-02-19 05:27:50 +00:00
import homeassistant.util.dt as dt_util
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import (DOMAIN, PLATFORM_SCHEMA)
from homeassistant.const import CONF_MONITORED_CONDITIONS
2016-02-04 23:21:37 +00:00
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import track_time_change
from homeassistant.helpers.restore_state import async_get_last_state
2016-02-04 23:21:37 +00:00
2017-10-20 18:28:11 +00:00
REQUIREMENTS = ['speedtest-cli==1.0.7']
2016-02-04 23:21:37 +00:00
2016-11-25 20:30:53 +00:00
_LOGGER = logging.getLogger(__name__)
2016-02-12 16:44:24 +00:00
_SPEEDTEST_REGEX = re.compile(r'Ping:\s(\d+\.\d+)\sms[\r\n]+'
r'Download:\s(\d+\.\d+)\sMbit/s[\r\n]+'
r'Upload:\s(\d+\.\d+)\sMbit/s[\r\n]+')
2016-02-04 23:21:37 +00:00
CONF_SECOND = 'second'
2016-02-12 00:09:51 +00:00
CONF_MINUTE = 'minute'
CONF_HOUR = 'hour'
CONF_DAY = 'day'
CONF_SERVER_ID = 'server_id'
CONF_MANUAL = 'manual'
2016-11-25 20:30:53 +00:00
ICON = 'mdi:speedometer'
2016-02-04 23:21:37 +00:00
SENSOR_TYPES = {
'ping': ['Ping', 'ms'],
'download': ['Download', 'Mbit/s'],
'upload': ['Upload', 'Mbit/s'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_MONITORED_CONDITIONS):
2016-11-25 20:30:53 +00:00
vol.All(cv.ensure_list, [vol.In(list(SENSOR_TYPES))]),
vol.Optional(CONF_SERVER_ID): cv.positive_int,
vol.Optional(CONF_SECOND, default=[0]):
vol.All(cv.ensure_list, [vol.All(vol.Coerce(int), vol.Range(0, 59))]),
vol.Optional(CONF_MINUTE, default=[0]):
vol.All(cv.ensure_list, [vol.All(vol.Coerce(int), vol.Range(0, 59))]),
vol.Optional(CONF_HOUR):
vol.All(cv.ensure_list, [vol.All(vol.Coerce(int), vol.Range(0, 23))]),
vol.Optional(CONF_DAY):
vol.All(cv.ensure_list, [vol.All(vol.Coerce(int), vol.Range(1, 31))]),
vol.Optional(CONF_MANUAL, default=False): cv.boolean,
})
2016-02-04 23:21:37 +00:00
def setup_platform(hass, config, add_devices, discovery_info=None):
2016-11-25 20:30:53 +00:00
"""Set up the Speedtest sensor."""
data = SpeedtestData(hass, config)
2016-02-04 23:21:37 +00:00
dev = []
2016-02-12 00:09:51 +00:00
for sensor in config[CONF_MONITORED_CONDITIONS]:
if sensor not in SENSOR_TYPES:
2016-11-25 20:30:53 +00:00
_LOGGER.error("Sensor type: %s does not exist", sensor)
2016-02-04 23:21:37 +00:00
else:
2016-02-12 00:09:51 +00:00
dev.append(SpeedtestSensor(data, sensor))
2016-02-04 23:21:37 +00:00
add_devices(dev)
def update(call=None):
"""Update service for manual updates."""
data.update(dt_util.now())
for sensor in dev:
sensor.update()
hass.services.register(DOMAIN, 'update_speedtest', update)
2016-02-04 23:21:37 +00:00
class SpeedtestSensor(Entity):
2016-03-08 15:46:34 +00:00
"""Implementation of a speedtest.net sensor."""
2016-02-04 23:21:37 +00:00
def __init__(self, speedtest_data, sensor_type):
2016-03-08 15:46:34 +00:00
"""Initialize the sensor."""
2016-02-04 23:21:37 +00:00
self._name = SENSOR_TYPES[sensor_type][0]
self.speedtest_client = speedtest_data
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[self.type][1]
@property
def name(self):
2016-03-08 15:46:34 +00:00
"""Return the name of the sensor."""
2016-02-12 00:09:51 +00:00
return '{} {}'.format('Speedtest', self._name)
2016-02-04 23:21:37 +00:00
@property
def state(self):
2016-03-08 15:46:34 +00:00
"""Return the state of the device."""
2016-02-04 23:21:37 +00:00
return self._state
@property
def unit_of_measurement(self):
2016-03-08 15:46:34 +00:00
"""Return the unit of measurement of this entity, if any."""
2016-02-04 23:21:37 +00:00
return self._unit_of_measurement
@property
def icon(self):
"""Return icon."""
return ICON
2016-02-04 23:21:37 +00:00
def update(self):
2016-03-08 15:46:34 +00:00
"""Get the latest data and update the states."""
2016-02-04 23:21:37 +00:00
data = self.speedtest_client.data
if data is None:
return
if self.type == 'ping':
self._state = data['ping']
elif self.type == 'download':
self._state = data['download']
elif self.type == 'upload':
self._state = data['upload']
2016-02-04 23:21:37 +00:00
@asyncio.coroutine
def async_added_to_hass(self):
"""Handle all entity which are about to be added."""
state = yield from async_get_last_state(self.hass, self.entity_id)
if not state:
return
self._state = state.state
2016-02-04 23:21:37 +00:00
class SpeedtestData(object):
2016-03-08 15:46:34 +00:00
"""Get the latest data from speedtest.net."""
2016-02-04 23:21:37 +00:00
def __init__(self, hass, config):
2016-03-08 15:46:34 +00:00
"""Initialize the data object."""
2016-02-04 23:21:37 +00:00
self.data = None
self._server_id = config.get(CONF_SERVER_ID)
if not config.get(CONF_MANUAL):
track_time_change(
hass, self.update, second=config.get(CONF_SECOND),
minute=config.get(CONF_MINUTE), hour=config.get(CONF_HOUR),
day=config.get(CONF_DAY))
2016-02-04 23:21:37 +00:00
def update(self, now):
2016-03-08 15:46:34 +00:00
"""Get the latest data from speedtest.net."""
2016-11-25 20:30:53 +00:00
import speedtest
2017-04-29 22:00:04 +00:00
_LOGGER.info("Executing speedtest...")
try:
2016-11-25 20:30:53 +00:00
args = [sys.executable, speedtest.__file__, '--simple']
if self._server_id:
args = args + ['--server', str(self._server_id)]
re_output = _SPEEDTEST_REGEX.split(
2016-11-25 20:30:53 +00:00
check_output(args).decode('utf-8'))
except CalledProcessError as process_error:
2016-11-25 20:30:53 +00:00
_LOGGER.error("Error executing speedtest: %s", process_error)
return
2017-04-29 22:00:04 +00:00
self.data = {
'ping': round(float(re_output[1]), 2),
'download': round(float(re_output[2]), 2),
'upload': round(float(re_output[3]), 2),
}