UniFi integration move to push messaging (#31086)

* Rewrite UniFi integration to use push messaging

* Add signalling for new clients/devices

* Update list of known wireless clients when we get events of them connecting

* Reconnection logic for websocket

* Fix failing tests

* Bump requirement to v12

* Add new tests

* Update homeassistant/components/unifi/controller.py

Co-Authored-By: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Robert SvenssonandMartin Hjelmare authored and GitHub committed 2020-01-31 20:23:25 +01:00
1 parent 06c8e53323
commit 958a867c11
14 files changed
+296 -377

No files matched your search

+23 -39
View File
@@ -111,9 +111,12 @@ async def setup_unifi_integration(
return mock_client_all_responses.popleft()
return {}
# "aiounifi.Controller.start_websocket", return_value=True
with patch("aiounifi.Controller.login", return_value=True), patch(
"aiounifi.Controller.sites", return_value=sites
), patch("aiounifi.Controller.request", new=mock_request):
), patch("aiounifi.Controller.request", new=mock_request), patch.object(
aiounifi.websocket.WSClient, "start", return_value=True
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@@ -233,47 +236,28 @@ async def test_reset_after_successful_setup(hass):
assert len(controller.listeners) == 0
async def test_failed_update_failed_login(hass):
"""Running update can handle a failed login."""
async def test_wireless_client_event_calls_update_wireless_devices(hass):
"""Call update_wireless_devices method when receiving wireless client event."""
controller = await setup_unifi_integration(hass)
with patch.object(
controller.api.clients, "update", side_effect=aiounifi.LoginRequired
), patch.object(controller.api, "login", side_effect=aiounifi.AiounifiException):
await controller.async_update()
await hass.async_block_till_done()
with patch(
"homeassistant.components.unifi.controller.UniFiController.update_wireless_clients",
return_value=None,
) as wireless_clients_mock:
controller.api.websocket._data = {
"meta": {"rc": "ok", "message": "events"},
"data": [
{
"datetime": "2020-01-20T19:37:04Z",
"key": aiounifi.events.WIRELESS_CLIENT_CONNECTED,
"msg": "User[11:22:33:44:55:66] has connected to WLAN",
"time": 1579549024893,
}
],
}
controller.api.session_handler("data")
assert controller.available is False
async def test_failed_update_successful_login(hass):
"""Running update can login when requested."""
controller = await setup_unifi_integration(hass)
with patch.object(
controller.api.clients, "update", side_effect=aiounifi.LoginRequired
), patch.object(controller.api, "login", return_value=Mock(True)):
await controller.async_update()
await hass.async_block_till_done()
assert controller.available is True
async def test_failed_update(hass):
"""Running update can login when requested."""
controller = await setup_unifi_integration(hass)
with patch.object(
controller.api.clients, "update", side_effect=aiounifi.AiounifiException
):
await controller.async_update()
await hass.async_block_till_done()
assert controller.available is False
await controller.async_update()
await hass.async_block_till_done()
assert controller.available is True
assert wireless_clients_mock.assert_called_once
async def test_get_controller(hass):
+38 -15
View File
@@ -2,6 +2,8 @@
from copy import copy
from datetime import timedelta
from aiounifi.controller import SIGNAL_CONNECTION_STATE
from aiounifi.websocket import STATE_DISCONNECTED, STATE_RUNNING
from asynctest import patch
from homeassistant import config_entries
@@ -136,11 +138,12 @@ async def test_tracked_devices(hass):
client_1_copy = copy(CLIENT_1)
client_1_copy["last_seen"] = dt_util.as_timestamp(dt_util.utcnow())
event = {"meta": {"message": "sta:sync"}, "data": [client_1_copy]}
controller.api.message_handler(event)
device_1_copy = copy(DEVICE_1)
device_1_copy["last_seen"] = dt_util.as_timestamp(dt_util.utcnow())
controller.mock_client_responses.append([client_1_copy])
controller.mock_device_responses.append([device_1_copy])
await controller.async_update()
event = {"meta": {"message": "device:sync"}, "data": [device_1_copy]}
controller.api.message_handler(event)
await hass.async_block_till_done()
client_1 = hass.states.get("device_tracker.client_1")
@@ -149,16 +152,39 @@ async def test_tracked_devices(hass):
device_1 = hass.states.get("device_tracker.device_1")
assert device_1.state == "home"
# Controller unavailable
controller.async_unifi_signalling_callback(
SIGNAL_CONNECTION_STATE, STATE_DISCONNECTED
)
await hass.async_block_till_done()
client_1 = hass.states.get("device_tracker.client_1")
assert client_1.state == STATE_UNAVAILABLE
device_1 = hass.states.get("device_tracker.device_1")
assert device_1.state == STATE_UNAVAILABLE
# Controller available
controller.async_unifi_signalling_callback(SIGNAL_CONNECTION_STATE, STATE_RUNNING)
await hass.async_block_till_done()
client_1 = hass.states.get("device_tracker.client_1")
assert client_1.state == "home"
device_1 = hass.states.get("device_tracker.device_1")
assert device_1.state == "home"
# Disabled device is unavailable
device_1_copy = copy(DEVICE_1)
device_1_copy["disabled"] = True
controller.mock_client_responses.append({})
controller.mock_device_responses.append([device_1_copy])
await controller.async_update()
event = {"meta": {"message": "device:sync"}, "data": [device_1_copy]}
controller.api.message_handler(event)
await hass.async_block_till_done()
device_1 = hass.states.get("device_tracker.device_1")
assert device_1.state == STATE_UNAVAILABLE
# Don't track wired clients nor devices
controller.config_entry.add_update_listener(controller.async_options_updated)
hass.config_entries.async_update_entry(
controller.config_entry,
@@ -194,9 +220,8 @@ async def test_wireless_client_go_wired_issue(hass):
client_1_client["is_wired"] = True
client_1_client["last_seen"] = dt_util.as_timestamp(dt_util.utcnow())
controller.mock_client_responses.append([client_1_client])
controller.mock_device_responses.append({})
await controller.async_update()
event = {"meta": {"message": "sta:sync"}, "data": [client_1_client]}
controller.api.message_handler(event)
await hass.async_block_till_done()
client_1 = hass.states.get("device_tracker.client_1")
@@ -207,9 +232,8 @@ async def test_wireless_client_go_wired_issue(hass):
"utcnow",
return_value=(dt_util.utcnow() + timedelta(minutes=5)),
):
controller.mock_client_responses.append([client_1_client])
controller.mock_device_responses.append({})
await controller.async_update()
event = {"meta": {"message": "sta:sync"}, "data": [client_1_client]}
controller.api.message_handler(event)
await hass.async_block_till_done()
client_1 = hass.states.get("device_tracker.client_1")
@@ -217,9 +241,8 @@ async def test_wireless_client_go_wired_issue(hass):
client_1_client["is_wired"] = False
client_1_client["last_seen"] = dt_util.as_timestamp(dt_util.utcnow())
controller.mock_client_responses.append([client_1_client])
controller.mock_device_responses.append({})
await controller.async_update()
event = {"meta": {"message": "sta:sync"}, "data": [client_1_client]}
controller.api.message_handler(event)
await hass.async_block_till_done()
client_1 = hass.states.get("device_tracker.client_1")
+9 -84
View File
@@ -4,6 +4,8 @@ from unittest.mock import Mock, patch
from homeassistant.components import unifi
from homeassistant.setup import async_setup_component
from .test_controller import setup_unifi_integration
from tests.common import MockConfigEntry, mock_coro
@@ -42,67 +44,15 @@ async def test_setup_with_config(hass):
async def test_successful_config_entry(hass):
"""Test that configured options for a host are loaded via config entry."""
entry = MockConfigEntry(
domain=unifi.DOMAIN,
data={
"controller": {
"host": "0.0.0.0",
"username": "user",
"password": "pass",
"port": 80,
"site": "default",
"verify_ssl": True,
},
"poe_control": True,
},
)
entry.add_to_hass(hass)
mock_registry = Mock()
with patch.object(unifi, "UniFiController") as mock_controller, patch(
"homeassistant.helpers.device_registry.async_get_registry",
return_value=mock_coro(mock_registry),
):
mock_controller.return_value.async_setup.return_value = mock_coro(True)
mock_controller.return_value.mac = "00:11:22:33:44:55"
assert await unifi.async_setup_entry(hass, entry) is True
assert len(mock_controller.mock_calls) == 2
p_hass, p_entry = mock_controller.mock_calls[0][1]
assert p_hass is hass
assert p_entry is entry
assert len(mock_registry.mock_calls) == 1
assert mock_registry.mock_calls[0][2] == {
"config_entry_id": entry.entry_id,
"connections": {("mac", "00:11:22:33:44:55")},
"manufacturer": unifi.ATTR_MANUFACTURER,
"model": "UniFi Controller",
"name": "UniFi Controller",
}
await setup_unifi_integration(hass)
assert hass.data[unifi.DOMAIN]
async def test_controller_fail_setup(hass):
"""Test that a failed setup still stores controller."""
entry = MockConfigEntry(
domain=unifi.DOMAIN,
data={
"controller": {
"host": "0.0.0.0",
"username": "user",
"password": "pass",
"port": 80,
"site": "default",
"verify_ssl": True,
},
"poe_control": True,
},
)
entry.add_to_hass(hass)
with patch.object(unifi, "UniFiController") as mock_cntrlr:
mock_cntrlr.return_value.async_setup.return_value = mock_coro(False)
assert await unifi.async_setup_entry(hass, entry) is False
await setup_unifi_integration(hass)
assert hass.data[unifi.DOMAIN] == {}
@@ -140,33 +90,8 @@ async def test_controller_no_mac(hass):
async def test_unload_entry(hass):
"""Test being able to unload an entry."""
entry = MockConfigEntry(
domain=unifi.DOMAIN,
data={
"controller": {
"host": "0.0.0.0",
"username": "user",
"password": "pass",
"port": 80,
"site": "default",
"verify_ssl": True,
},
"poe_control": True,
},
)
entry.add_to_hass(hass)
controller = await setup_unifi_integration(hass)
assert hass.data[unifi.DOMAIN]
with patch.object(unifi, "UniFiController") as mock_controller, patch(
"homeassistant.helpers.device_registry.async_get_registry",
return_value=mock_coro(Mock()),
):
mock_controller.return_value.async_setup.return_value = mock_coro(True)
mock_controller.return_value.mac = "00:11:22:33:44:55"
assert await unifi.async_setup_entry(hass, entry) is True
assert len(mock_controller.return_value.mock_calls) == 1
mock_controller.return_value.async_reset.return_value = mock_coro(True)
assert await unifi.async_unload_entry(hass, entry)
assert len(mock_controller.return_value.async_reset.mock_calls) == 1
assert hass.data[unifi.DOMAIN] == {}
assert await unifi.async_unload_entry(hass, controller.config_entry)
assert not hass.data[unifi.DOMAIN]
+2 -2
View File
@@ -90,8 +90,8 @@ async def test_sensors(hass):
clients[1]["rx_bytes"] = 2345000000
clients[1]["tx_bytes"] = 6789000000
controller.mock_client_responses.append(clients)
await controller.async_update()
event = {"meta": {"message": "sta:sync"}, "data": clients}
controller.api.message_handler(event)
await hass.async_block_till_done()
wireless_client_rx = hass.states.get("sensor.wireless_client_name_rx")
+15 -8
View File
@@ -300,13 +300,17 @@ async def test_new_client_discovered_on_block_control(hass):
assert len(controller.mock_requests) == 3
assert len(hass.states.async_all()) == 2
controller.mock_client_all_responses.append([BLOCKED])
controller.api.websocket._data = {
"meta": {"message": "sta:sync"},
"data": [BLOCKED],
}
controller.api.session_handler("data")
# Calling a service will trigger the updates to run
await hass.services.async_call(
"switch", "turn_off", {"entity_id": "switch.block_client_1"}, blocking=True
)
assert len(controller.mock_requests) == 7
assert len(controller.mock_requests) == 4
assert len(hass.states.async_all()) == 2
assert controller.mock_requests[3] == {
"json": {"mac": "00:00:00:00:01:01", "cmd": "block-sta"},
@@ -317,8 +321,8 @@ async def test_new_client_discovered_on_block_control(hass):
await hass.services.async_call(
"switch", "turn_on", {"entity_id": "switch.block_client_1"}, blocking=True
)
assert len(controller.mock_requests) == 11
assert controller.mock_requests[7] == {
assert len(controller.mock_requests) == 5
assert controller.mock_requests[4] == {
"json": {"mac": "00:00:00:00:01:01", "cmd": "unblock-sta"},
"method": "post",
"path": "s/{site}/cmd/stamgr/",
@@ -340,14 +344,17 @@ async def test_new_client_discovered_on_poe_control(hass):
assert len(controller.mock_requests) == 3
assert len(hass.states.async_all()) == 2
controller.mock_client_responses.append([CLIENT_1, CLIENT_2])
controller.mock_device_responses.append([DEVICE_1])
controller.api.websocket._data = {
"meta": {"message": "sta:sync"},
"data": [CLIENT_2],
}
controller.api.session_handler("data")
# Calling a service will trigger the updates to run
await hass.services.async_call(
"switch", "turn_off", {"entity_id": "switch.poe_client_1"}, blocking=True
)
assert len(controller.mock_requests) == 6
assert len(controller.mock_requests) == 4
assert len(hass.states.async_all()) == 3
assert controller.mock_requests[3] == {
"json": {
@@ -360,7 +367,7 @@ async def test_new_client_discovered_on_poe_control(hass):
await hass.services.async_call(
"switch", "turn_on", {"entity_id": "switch.poe_client_1"}, blocking=True
)
assert len(controller.mock_requests) == 9
assert len(controller.mock_requests) == 5
assert controller.mock_requests[3] == {
"json": {
"port_overrides": [