parent
365f21b209
commit
50cd6c9a9c
2 changed files with 55 additions and 60 deletions
|
@ -1,5 +1,5 @@
|
||||||
"""
|
"""
|
||||||
Support for retreiving status info from Google Wifi/OnHub routers.
|
Support for retrieving status info from Google Wifi/OnHub routers.
|
||||||
|
|
||||||
For more details about this platform, please refer to the documentation at
|
For more details about this platform, please refer to the documentation at
|
||||||
https://home-assistant.io/components/sensor.google_wifi/
|
https://home-assistant.io/components/sensor.google_wifi/
|
||||||
|
@ -12,28 +12,27 @@ import requests
|
||||||
|
|
||||||
import homeassistant.util.dt as dt
|
import homeassistant.util.dt as dt
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
from homeassistant.helpers.entity import Entity
|
|
||||||
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
from homeassistant.components.sensor import PLATFORM_SCHEMA
|
||||||
from homeassistant.util import Throttle
|
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
CONF_NAME, CONF_HOST, CONF_MONITORED_CONDITIONS,
|
CONF_NAME, CONF_HOST, CONF_MONITORED_CONDITIONS, STATE_UNKNOWN)
|
||||||
STATE_UNKNOWN)
|
from homeassistant.helpers.entity import Entity
|
||||||
|
from homeassistant.util import Throttle
|
||||||
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
ENDPOINT = '/api/v1/status'
|
|
||||||
|
|
||||||
ATTR_CURRENT_VERSION = 'current_version'
|
ATTR_CURRENT_VERSION = 'current_version'
|
||||||
ATTR_NEW_VERSION = 'new_version'
|
|
||||||
ATTR_UPTIME = 'uptime'
|
|
||||||
ATTR_LAST_RESTART = 'last_restart'
|
ATTR_LAST_RESTART = 'last_restart'
|
||||||
ATTR_LOCAL_IP = 'local_ip'
|
ATTR_LOCAL_IP = 'local_ip'
|
||||||
|
ATTR_NEW_VERSION = 'new_version'
|
||||||
ATTR_STATUS = 'status'
|
ATTR_STATUS = 'status'
|
||||||
|
ATTR_UPTIME = 'uptime'
|
||||||
|
|
||||||
DEFAULT_NAME = 'google_wifi'
|
|
||||||
DEFAULT_HOST = 'testwifi.here'
|
DEFAULT_HOST = 'testwifi.here'
|
||||||
|
DEFAULT_NAME = 'google_wifi'
|
||||||
|
|
||||||
|
ENDPOINT = '/api/v1/status'
|
||||||
|
|
||||||
|
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=1)
|
||||||
|
|
||||||
MONITORED_CONDITIONS = {
|
MONITORED_CONDITIONS = {
|
||||||
ATTR_CURRENT_VERSION: [
|
ATTR_CURRENT_VERSION: [
|
||||||
|
@ -69,10 +68,10 @@ MONITORED_CONDITIONS = {
|
||||||
}
|
}
|
||||||
|
|
||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||||
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
|
||||||
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
|
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
|
||||||
vol.Optional(CONF_MONITORED_CONDITIONS, default=MONITORED_CONDITIONS):
|
vol.Optional(CONF_MONITORED_CONDITIONS, default=MONITORED_CONDITIONS):
|
||||||
vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]),
|
vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]),
|
||||||
|
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@ -85,7 +84,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
api = GoogleWifiAPI(host, conditions)
|
api = GoogleWifiAPI(host, conditions)
|
||||||
dev = []
|
dev = []
|
||||||
for condition in conditions:
|
for condition in conditions:
|
||||||
dev.append(GoogleWifiSensor(hass, api, name, condition))
|
dev.append(GoogleWifiSensor(api, name, condition))
|
||||||
|
|
||||||
add_devices(dev, True)
|
add_devices(dev, True)
|
||||||
|
|
||||||
|
@ -93,9 +92,8 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
class GoogleWifiSensor(Entity):
|
class GoogleWifiSensor(Entity):
|
||||||
"""Representation of a Google Wifi sensor."""
|
"""Representation of a Google Wifi sensor."""
|
||||||
|
|
||||||
def __init__(self, hass, api, name, variable):
|
def __init__(self, api, name, variable):
|
||||||
"""Initialize a Pi-Hole sensor."""
|
"""Initialize a Google Wifi sensor."""
|
||||||
self._hass = hass
|
|
||||||
self._api = api
|
self._api = api
|
||||||
self._name = name
|
self._name = name
|
||||||
self._state = STATE_UNKNOWN
|
self._state = STATE_UNKNOWN
|
||||||
|
@ -108,7 +106,7 @@ class GoogleWifiSensor(Entity):
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
"""Return the name of the sensor."""
|
"""Return the name of the sensor."""
|
||||||
return "{}_{}".format(self._name, self._var_name)
|
return '{}_{}'.format(self._name, self._var_name)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def icon(self):
|
def icon(self):
|
||||||
|
@ -121,9 +119,9 @@ class GoogleWifiSensor(Entity):
|
||||||
return self._var_units
|
return self._var_units
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def availiable(self):
|
def available(self):
|
||||||
"""Return availiability of goole wifi api."""
|
"""Return availability of Google Wifi API."""
|
||||||
return self._api.availiable
|
return self._api.available
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self):
|
def state(self):
|
||||||
|
@ -133,7 +131,7 @@ class GoogleWifiSensor(Entity):
|
||||||
def update(self):
|
def update(self):
|
||||||
"""Get the latest data from the Google Wifi API."""
|
"""Get the latest data from the Google Wifi API."""
|
||||||
self._api.update()
|
self._api.update()
|
||||||
if self.availiable:
|
if self.available:
|
||||||
self._state = self._api.data[self._var_name]
|
self._state = self._api.data[self._var_name]
|
||||||
else:
|
else:
|
||||||
self._state = STATE_UNKNOWN
|
self._state = STATE_UNKNOWN
|
||||||
|
@ -157,7 +155,7 @@ class GoogleWifiAPI(object):
|
||||||
ATTR_LOCAL_IP: STATE_UNKNOWN,
|
ATTR_LOCAL_IP: STATE_UNKNOWN,
|
||||||
ATTR_STATUS: STATE_UNKNOWN
|
ATTR_STATUS: STATE_UNKNOWN
|
||||||
}
|
}
|
||||||
self.availiable = True
|
self.available = True
|
||||||
self.update()
|
self.update()
|
||||||
|
|
||||||
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
@Throttle(MIN_TIME_BETWEEN_UPDATES)
|
||||||
|
@ -165,14 +163,13 @@ class GoogleWifiAPI(object):
|
||||||
"""Get the latest data from the router."""
|
"""Get the latest data from the router."""
|
||||||
try:
|
try:
|
||||||
with requests.Session() as sess:
|
with requests.Session() as sess:
|
||||||
response = sess.send(
|
response = sess.send(self._request, timeout=10)
|
||||||
self._request, timeout=10)
|
|
||||||
self.raw_data = response.json()
|
self.raw_data = response.json()
|
||||||
self.data_format()
|
self.data_format()
|
||||||
self.availiable = True
|
self.available = True
|
||||||
except ValueError:
|
except (ValueError, requests.exceptions.ConnectionError):
|
||||||
_LOGGER.error('Unable to fetch data from Google Wifi')
|
_LOGGER.warning("Unable to fetch data from Google Wifi")
|
||||||
self.availiable = False
|
self.available = False
|
||||||
self.raw_data = None
|
self.raw_data = None
|
||||||
|
|
||||||
def data_format(self):
|
def data_format(self):
|
||||||
|
@ -191,10 +188,10 @@ class GoogleWifiAPI(object):
|
||||||
elif attr_key == ATTR_UPTIME:
|
elif attr_key == ATTR_UPTIME:
|
||||||
sensor_value /= 3600 * 24
|
sensor_value /= 3600 * 24
|
||||||
elif attr_key == ATTR_LAST_RESTART:
|
elif attr_key == ATTR_LAST_RESTART:
|
||||||
last_restart = (dt.now() -
|
last_restart = (
|
||||||
timedelta(seconds=sensor_value))
|
dt.now() - timedelta(seconds=sensor_value))
|
||||||
sensor_value = last_restart.strftime(('%Y-%m-%d '
|
sensor_value = last_restart.strftime(
|
||||||
'%H:%M:%S'))
|
'%Y-%m-%d %H:%M:%S')
|
||||||
elif attr_key == ATTR_STATUS:
|
elif attr_key == ATTR_STATUS:
|
||||||
if sensor_value:
|
if sensor_value:
|
||||||
sensor_value = 'Online'
|
sensor_value = 'Online'
|
||||||
|
@ -206,7 +203,7 @@ class GoogleWifiAPI(object):
|
||||||
|
|
||||||
self.data[attr_key] = sensor_value
|
self.data[attr_key] = sensor_value
|
||||||
except KeyError:
|
except KeyError:
|
||||||
_LOGGER.error('Router does not support %s field. '
|
_LOGGER.error("Router does not support %s field. "
|
||||||
'Please remove %s from monitored_conditions.',
|
"Please remove %s from monitored_conditions",
|
||||||
sensor_key, attr_key)
|
sensor_key, attr_key)
|
||||||
self.data[attr_key] = STATE_UNKNOWN
|
self.data[attr_key] = STATE_UNKNOWN
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import patch, Mock
|
from unittest.mock import patch, Mock
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
import requests_mock
|
import requests_mock
|
||||||
|
|
||||||
from homeassistant import core as ha
|
from homeassistant import core as ha
|
||||||
|
@ -32,7 +33,7 @@ MOCK_DATA_MISSING = ('{"software": {},'
|
||||||
|
|
||||||
|
|
||||||
class TestGoogleWifiSetup(unittest.TestCase):
|
class TestGoogleWifiSetup(unittest.TestCase):
|
||||||
"""Tests for setting up the Google Wifi switch platform."""
|
"""Tests for setting up the Google Wifi sensor platform."""
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
"""Setup things to be run when tests are started."""
|
"""Setup things to be run when tests are started."""
|
||||||
|
@ -45,9 +46,8 @@ class TestGoogleWifiSetup(unittest.TestCase):
|
||||||
@requests_mock.Mocker()
|
@requests_mock.Mocker()
|
||||||
def test_setup_minimum(self, mock_req):
|
def test_setup_minimum(self, mock_req):
|
||||||
"""Test setup with minimum configuration."""
|
"""Test setup with minimum configuration."""
|
||||||
resource = '{}{}{}'.format('http://',
|
resource = '{}{}{}'.format(
|
||||||
google_wifi.DEFAULT_HOST,
|
'http://', google_wifi.DEFAULT_HOST, google_wifi.ENDPOINT)
|
||||||
google_wifi.ENDPOINT)
|
|
||||||
mock_req.get(resource, status_code=200)
|
mock_req.get(resource, status_code=200)
|
||||||
self.assertTrue(setup_component(self.hass, 'sensor', {
|
self.assertTrue(setup_component(self.hass, 'sensor', {
|
||||||
'sensor': {
|
'sensor': {
|
||||||
|
@ -60,9 +60,8 @@ class TestGoogleWifiSetup(unittest.TestCase):
|
||||||
@requests_mock.Mocker()
|
@requests_mock.Mocker()
|
||||||
def test_setup_get(self, mock_req):
|
def test_setup_get(self, mock_req):
|
||||||
"""Test setup with full configuration."""
|
"""Test setup with full configuration."""
|
||||||
resource = '{}{}{}'.format('http://',
|
resource = '{}{}{}'.format(
|
||||||
'localhost',
|
'http://', 'localhost', google_wifi.ENDPOINT)
|
||||||
google_wifi.ENDPOINT)
|
|
||||||
mock_req.get(resource, status_code=200)
|
mock_req.get(resource, status_code=200)
|
||||||
self.assertTrue(setup_component(self.hass, 'sensor', {
|
self.assertTrue(setup_component(self.hass, 'sensor', {
|
||||||
'sensor': {
|
'sensor': {
|
||||||
|
@ -95,34 +94,33 @@ class TestGoogleWifiSensor(unittest.TestCase):
|
||||||
|
|
||||||
def setup_api(self, data, mock_req):
|
def setup_api(self, data, mock_req):
|
||||||
"""Setup API with fake data."""
|
"""Setup API with fake data."""
|
||||||
resource = '{}{}{}'.format('http://',
|
resource = '{}{}{}'.format(
|
||||||
'localhost',
|
'http://', 'localhost', google_wifi.ENDPOINT)
|
||||||
google_wifi.ENDPOINT)
|
|
||||||
now = datetime(1970, month=1, day=1)
|
now = datetime(1970, month=1, day=1)
|
||||||
with patch('homeassistant.util.dt.now', return_value=now):
|
with patch('homeassistant.util.dt.now', return_value=now):
|
||||||
mock_req.get(resource, text=data, status_code=200)
|
mock_req.get(resource, text=data, status_code=200)
|
||||||
conditions = google_wifi.MONITORED_CONDITIONS.keys()
|
conditions = google_wifi.MONITORED_CONDITIONS.keys()
|
||||||
self.api = google_wifi.GoogleWifiAPI("localhost",
|
self.api = google_wifi.GoogleWifiAPI("localhost", conditions)
|
||||||
conditions)
|
|
||||||
self.name = NAME
|
self.name = NAME
|
||||||
self.sensor_dict = dict()
|
self.sensor_dict = dict()
|
||||||
for condition, cond_list in google_wifi.MONITORED_CONDITIONS.items():
|
for condition, cond_list in google_wifi.MONITORED_CONDITIONS.items():
|
||||||
sensor = google_wifi.GoogleWifiSensor(self.hass, self.api,
|
sensor = google_wifi.GoogleWifiSensor(
|
||||||
self.name, condition)
|
self.api, self.name, condition)
|
||||||
name = '{}_{}'.format(self.name, condition)
|
name = '{}_{}'.format(self.name, condition)
|
||||||
units = cond_list[1]
|
units = cond_list[1]
|
||||||
icon = cond_list[2]
|
icon = cond_list[2]
|
||||||
self.sensor_dict[condition] = {'sensor': sensor,
|
self.sensor_dict[condition] = {
|
||||||
'name': name,
|
'sensor': sensor,
|
||||||
'units': units,
|
'name': name,
|
||||||
'icon': icon}
|
'units': units,
|
||||||
|
'icon': icon
|
||||||
|
}
|
||||||
|
|
||||||
def fake_delay(self, ha_delay):
|
def fake_delay(self, ha_delay):
|
||||||
"""Fake delay to prevent update throttle."""
|
"""Fake delay to prevent update throttle."""
|
||||||
hass_now = dt_util.utcnow()
|
hass_now = dt_util.utcnow()
|
||||||
shifted_time = hass_now + timedelta(seconds=ha_delay)
|
shifted_time = hass_now + timedelta(seconds=ha_delay)
|
||||||
self.hass.bus.fire(ha.EVENT_TIME_CHANGED,
|
self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: shifted_time})
|
||||||
{ha.ATTR_NOW: shifted_time})
|
|
||||||
|
|
||||||
def test_name(self):
|
def test_name(self):
|
||||||
"""Test the name."""
|
"""Test the name."""
|
||||||
|
@ -135,8 +133,8 @@ class TestGoogleWifiSensor(unittest.TestCase):
|
||||||
"""Test the unit of measurement."""
|
"""Test the unit of measurement."""
|
||||||
for name in self.sensor_dict:
|
for name in self.sensor_dict:
|
||||||
sensor = self.sensor_dict[name]['sensor']
|
sensor = self.sensor_dict[name]['sensor']
|
||||||
self.assertEqual(self.sensor_dict[name]['units'],
|
self.assertEqual(
|
||||||
sensor.unit_of_measurement)
|
self.sensor_dict[name]['units'], sensor.unit_of_measurement)
|
||||||
|
|
||||||
def test_icon(self):
|
def test_icon(self):
|
||||||
"""Test the icon."""
|
"""Test the icon."""
|
||||||
|
@ -208,8 +206,8 @@ class TestGoogleWifiSensor(unittest.TestCase):
|
||||||
sensor.update()
|
sensor.update()
|
||||||
self.assertEqual(STATE_UNKNOWN, sensor.state)
|
self.assertEqual(STATE_UNKNOWN, sensor.state)
|
||||||
|
|
||||||
def test_update_when_unavailiable(self):
|
def test_update_when_unavailable(self):
|
||||||
"""Test state updates when Google Wifi unavailiable."""
|
"""Test state updates when Google Wifi unavailable."""
|
||||||
self.api.update = Mock('google_wifi.GoogleWifiAPI.update',
|
self.api.update = Mock('google_wifi.GoogleWifiAPI.update',
|
||||||
side_effect=self.update_side_effect())
|
side_effect=self.update_side_effect())
|
||||||
for name in self.sensor_dict:
|
for name in self.sensor_dict:
|
||||||
|
@ -220,4 +218,4 @@ class TestGoogleWifiSensor(unittest.TestCase):
|
||||||
def update_side_effect(self):
|
def update_side_effect(self):
|
||||||
"""Mock representation of update function."""
|
"""Mock representation of update function."""
|
||||||
self.api.data = None
|
self.api.data = None
|
||||||
self.api.availiable = False
|
self.api.available = False
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue