mirror of
https://github.com/home-assistant/core.git
synced 2025-07-27 23:27:37 +00:00
Fixed sensor issue with Google Wifi routers in bridge mode (#8710)
* Fixed issue with routers in bridge mode - Router in brdige mode apparently don't report all of the stats - Re-wrote the data_format function so it's a bit easier to follow and able to log keys that aren't supported by a router in a given mode - Changed config so that it properly ignores conditions when not explicitly listed - Added tests to check for the above and also to verify we log that a key doesn't exist rather than throwing an exception * Mistakenly was calling MONITORED_CONDITIONS in data_format - Changed to be the actual config values to prevent log error
This commit is contained in:
parent
a94e7ec25d
commit
418a8bab11
@ -37,32 +37,32 @@ DEFAULT_HOST = 'testwifi.here'
|
|||||||
|
|
||||||
MONITORED_CONDITIONS = {
|
MONITORED_CONDITIONS = {
|
||||||
ATTR_CURRENT_VERSION: [
|
ATTR_CURRENT_VERSION: [
|
||||||
'Current Version',
|
['software', 'softwareVersion'],
|
||||||
None,
|
None,
|
||||||
'mdi:checkbox-marked-circle-outline'
|
'mdi:checkbox-marked-circle-outline'
|
||||||
],
|
],
|
||||||
ATTR_NEW_VERSION: [
|
ATTR_NEW_VERSION: [
|
||||||
'New Version',
|
['software', 'updateNewVersion'],
|
||||||
None,
|
None,
|
||||||
'mdi:update'
|
'mdi:update'
|
||||||
],
|
],
|
||||||
ATTR_UPTIME: [
|
ATTR_UPTIME: [
|
||||||
'Uptime',
|
['system', 'uptime'],
|
||||||
'days',
|
'days',
|
||||||
'mdi:timelapse'
|
'mdi:timelapse'
|
||||||
],
|
],
|
||||||
ATTR_LAST_RESTART: [
|
ATTR_LAST_RESTART: [
|
||||||
'Last Network Restart',
|
['system', 'uptime'],
|
||||||
None,
|
None,
|
||||||
'mdi:restart'
|
'mdi:restart'
|
||||||
],
|
],
|
||||||
ATTR_LOCAL_IP: [
|
ATTR_LOCAL_IP: [
|
||||||
'Local IP Address',
|
['wan', 'localIpAddress'],
|
||||||
None,
|
None,
|
||||||
'mdi:access-point-network'
|
'mdi:access-point-network'
|
||||||
],
|
],
|
||||||
ATTR_STATUS: [
|
ATTR_STATUS: [
|
||||||
'Status',
|
['wan', 'online'],
|
||||||
None,
|
None,
|
||||||
'mdi:google'
|
'mdi:google'
|
||||||
]
|
]
|
||||||
@ -80,13 +80,14 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
|
|||||||
"""Set up the Google Wifi sensor."""
|
"""Set up the Google Wifi sensor."""
|
||||||
name = config.get(CONF_NAME)
|
name = config.get(CONF_NAME)
|
||||||
host = config.get(CONF_HOST)
|
host = config.get(CONF_HOST)
|
||||||
|
conditions = config.get(CONF_MONITORED_CONDITIONS)
|
||||||
|
|
||||||
api = GoogleWifiAPI(host)
|
api = GoogleWifiAPI(host, conditions)
|
||||||
|
dev = []
|
||||||
|
for condition in conditions:
|
||||||
|
dev.append(GoogleWifiSensor(hass, api, name, condition))
|
||||||
|
|
||||||
sensors = [GoogleWifiSensor(hass, api, name, condition)
|
add_devices(dev, True)
|
||||||
for condition in config[CONF_MONITORED_CONDITIONS]]
|
|
||||||
|
|
||||||
add_devices(sensors, True)
|
|
||||||
|
|
||||||
|
|
||||||
class GoogleWifiSensor(Entity):
|
class GoogleWifiSensor(Entity):
|
||||||
@ -141,13 +142,13 @@ class GoogleWifiSensor(Entity):
|
|||||||
class GoogleWifiAPI(object):
|
class GoogleWifiAPI(object):
|
||||||
"""Get the latest data and update the states."""
|
"""Get the latest data and update the states."""
|
||||||
|
|
||||||
def __init__(self, host):
|
def __init__(self, host, conditions):
|
||||||
"""Initialize the data object."""
|
"""Initialize the data object."""
|
||||||
uri = 'http://'
|
uri = 'http://'
|
||||||
resource = "{}{}{}".format(uri, host, ENDPOINT)
|
resource = "{}{}{}".format(uri, host, ENDPOINT)
|
||||||
|
|
||||||
self._request = requests.Request('GET', resource).prepare()
|
self._request = requests.Request('GET', resource).prepare()
|
||||||
self.raw_data = None
|
self.raw_data = None
|
||||||
|
self.conditions = conditions
|
||||||
self.data = {
|
self.data = {
|
||||||
ATTR_CURRENT_VERSION: STATE_UNKNOWN,
|
ATTR_CURRENT_VERSION: STATE_UNKNOWN,
|
||||||
ATTR_NEW_VERSION: STATE_UNKNOWN,
|
ATTR_NEW_VERSION: STATE_UNKNOWN,
|
||||||
@ -163,39 +164,49 @@ class GoogleWifiAPI(object):
|
|||||||
def update(self):
|
def update(self):
|
||||||
"""Get the latest data from the router."""
|
"""Get the latest data from the router."""
|
||||||
try:
|
try:
|
||||||
_LOGGER.error("Before request")
|
|
||||||
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()
|
||||||
_LOGGER.error(self.raw_data)
|
|
||||||
self.data_format()
|
self.data_format()
|
||||||
self.availiable = True
|
self.availiable = True
|
||||||
except ValueError:
|
except ValueError:
|
||||||
_LOGGER.error("Unable to fetch data from Google Wifi")
|
_LOGGER.error('Unable to fetch data from Google Wifi')
|
||||||
self.availiable = False
|
self.availiable = False
|
||||||
self.raw_data = None
|
self.raw_data = None
|
||||||
|
|
||||||
def data_format(self):
|
def data_format(self):
|
||||||
"""Format raw data into easily accessible dict."""
|
"""Format raw data into easily accessible dict."""
|
||||||
for key, value in self.raw_data.items():
|
for attr_key in self.conditions:
|
||||||
if key == 'software':
|
value = MONITORED_CONDITIONS[attr_key]
|
||||||
self.data[ATTR_CURRENT_VERSION] = value['softwareVersion']
|
try:
|
||||||
if value['updateNewVersion'] == '0.0.0.0':
|
primary_key = value[0][0]
|
||||||
self.data[ATTR_NEW_VERSION] = 'Latest'
|
sensor_key = value[0][1]
|
||||||
else:
|
if primary_key in self.raw_data:
|
||||||
self.data[ATTR_NEW_VERSION] = value['updateNewVersion']
|
sensor_value = self.raw_data[primary_key][sensor_key]
|
||||||
elif key == 'system':
|
# Format sensor for better readability
|
||||||
self.data[ATTR_UPTIME] = value['uptime'] / (3600 * 24)
|
if (attr_key == ATTR_NEW_VERSION and
|
||||||
last_restart = dt.now() - timedelta(seconds=value['uptime'])
|
sensor_value == '0.0.0.0'):
|
||||||
self.data[ATTR_LAST_RESTART] = \
|
sensor_value = 'Latest'
|
||||||
last_restart.strftime("%Y-%m-%d %H:%M:%S")
|
elif attr_key == ATTR_UPTIME:
|
||||||
elif key == 'wan':
|
sensor_value /= 3600 * 24
|
||||||
if value['online']:
|
elif attr_key == ATTR_LAST_RESTART:
|
||||||
self.data[ATTR_STATUS] = 'Online'
|
last_restart = (dt.now() -
|
||||||
else:
|
timedelta(seconds=sensor_value))
|
||||||
self.data[ATTR_STATUS] = 'Offline'
|
sensor_value = last_restart.strftime(('%Y-%m-%d '
|
||||||
if not value['ipAddress']:
|
'%H:%M:%S'))
|
||||||
self.data[ATTR_LOCAL_IP] = STATE_UNKNOWN
|
elif attr_key == ATTR_STATUS:
|
||||||
else:
|
if sensor_value:
|
||||||
self.data[ATTR_LOCAL_IP] = value['localIpAddress']
|
sensor_value = 'Online'
|
||||||
|
else:
|
||||||
|
sensor_value = 'Offline'
|
||||||
|
elif attr_key == ATTR_LOCAL_IP:
|
||||||
|
if not self.raw_data['wan']['online']:
|
||||||
|
sensor_value = STATE_UNKNOWN
|
||||||
|
|
||||||
|
self.data[attr_key] = sensor_value
|
||||||
|
except KeyError:
|
||||||
|
_LOGGER.error('Router does not support %s field. '
|
||||||
|
'Please remove %s from monitored_conditions.',
|
||||||
|
sensor_key, attr_key)
|
||||||
|
self.data[attr_key] = STATE_UNKNOWN
|
||||||
|
@ -26,6 +26,10 @@ MOCK_DATA_NEXT = ('{"software": {"softwareVersion":"next",'
|
|||||||
'"wan": {"localIpAddress":"next", "online":false,'
|
'"wan": {"localIpAddress":"next", "online":false,'
|
||||||
'"ipAddress":false}}')
|
'"ipAddress":false}}')
|
||||||
|
|
||||||
|
MOCK_DATA_MISSING = ('{"software": {},'
|
||||||
|
'"system": {},'
|
||||||
|
'"wan": {}}')
|
||||||
|
|
||||||
|
|
||||||
class TestGoogleWifiSetup(unittest.TestCase):
|
class TestGoogleWifiSetup(unittest.TestCase):
|
||||||
"""Tests for setting up the Google Wifi switch platform."""
|
"""Tests for setting up the Google Wifi switch platform."""
|
||||||
@ -47,9 +51,11 @@ class TestGoogleWifiSetup(unittest.TestCase):
|
|||||||
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': {
|
||||||
'platform': 'google_wifi'
|
'platform': 'google_wifi',
|
||||||
|
'monitored_conditions': ['uptime']
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
assert_setup_component(1, 'sensor')
|
||||||
|
|
||||||
@requests_mock.Mocker()
|
@requests_mock.Mocker()
|
||||||
def test_setup_get(self, mock_req):
|
def test_setup_get(self, mock_req):
|
||||||
@ -95,7 +101,9 @@ class TestGoogleWifiSensor(unittest.TestCase):
|
|||||||
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)
|
||||||
self.api = google_wifi.GoogleWifiAPI("localhost")
|
conditions = google_wifi.MONITORED_CONDITIONS.keys()
|
||||||
|
self.api = google_wifi.GoogleWifiAPI("localhost",
|
||||||
|
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():
|
||||||
@ -188,6 +196,18 @@ class TestGoogleWifiSensor(unittest.TestCase):
|
|||||||
else:
|
else:
|
||||||
self.assertEqual('next', sensor.state)
|
self.assertEqual('next', sensor.state)
|
||||||
|
|
||||||
|
@requests_mock.Mocker()
|
||||||
|
def test_when_api_data_missing(self, mock_req):
|
||||||
|
"""Test state logs an error when data is missing."""
|
||||||
|
self.setup_api(MOCK_DATA_MISSING, mock_req)
|
||||||
|
now = datetime(1970, month=1, day=1)
|
||||||
|
with patch('homeassistant.util.dt.now', return_value=now):
|
||||||
|
for name in self.sensor_dict:
|
||||||
|
sensor = self.sensor_dict[name]['sensor']
|
||||||
|
self.fake_delay(2)
|
||||||
|
sensor.update()
|
||||||
|
self.assertEqual(STATE_UNKNOWN, sensor.state)
|
||||||
|
|
||||||
def test_update_when_unavailiable(self):
|
def test_update_when_unavailiable(self):
|
||||||
"""Test state updates when Google Wifi unavailiable."""
|
"""Test state updates when Google Wifi unavailiable."""
|
||||||
self.api.update = Mock('google_wifi.GoogleWifiAPI.update',
|
self.api.update = Mock('google_wifi.GoogleWifiAPI.update',
|
||||||
|
Loading…
x
Reference in New Issue
Block a user