Adapt Axis integration to async HTTPx calls (#42095)

This commit is contained in:
Robert Svensson 2020-10-20 09:31:04 +02:00 committed by GitHub
parent fcdb54d878
commit 1303d20064
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 41 additions and 40 deletions

View file

@ -161,9 +161,7 @@ class AxisNetworkDevice:
async def use_mqtt(self, hass: HomeAssistant, component: str) -> None: async def use_mqtt(self, hass: HomeAssistant, component: str) -> None:
"""Set up to use MQTT.""" """Set up to use MQTT."""
try: try:
status = await hass.async_add_executor_job( status = await self.api.vapix.mqtt.get_client_status()
self.api.vapix.mqtt.get_client_status
)
except Unauthorized: except Unauthorized:
# This means the user has too low privileges # This means the user has too low privileges
status = {} status = {}
@ -238,14 +236,15 @@ class AxisNetworkDevice:
) )
self.api.stream.stop() self.api.stream.stop()
@callback async def shutdown(self, event):
def shutdown(self, event):
"""Stop the event stream.""" """Stop the event stream."""
self.disconnect_from_stream() self.disconnect_from_stream()
await self.api.vapix.close()
async def async_reset(self): async def async_reset(self):
"""Reset this device to default state.""" """Reset this device to default state."""
self.disconnect_from_stream() self.disconnect_from_stream()
await self.api.vapix.close()
unload_ok = all( unload_ok = all(
await asyncio.gather( await asyncio.gather(
@ -275,7 +274,7 @@ async def get_device(hass, host, port, username, password):
try: try:
with async_timeout.timeout(15): with async_timeout.timeout(15):
await hass.async_add_executor_job(device.vapix.initialize) await device.vapix.initialize()
return device return device

View file

@ -52,19 +52,17 @@ class AxisLight(AxisEventBase, LightEntity):
"""Subscribe lights events.""" """Subscribe lights events."""
await super().async_added_to_hass() await super().async_added_to_hass()
def get_light_capabilities(): current_intensity = (
"""Get light capabilities.""" await self.device.api.vapix.light_control.get_current_intensity(
current_intensity = (
self.device.api.vapix.light_control.get_current_intensity(self.light_id)
)
self.current_intensity = current_intensity["data"]["intensity"]
max_intensity = self.device.api.vapix.light_control.get_valid_intensity(
self.light_id self.light_id
) )
self.max_intensity = max_intensity["data"]["ranges"][0]["high"] )
self.current_intensity = current_intensity["data"]["intensity"]
await self.hass.async_add_executor_job(get_light_capabilities) max_intensity = await self.device.api.vapix.light_control.get_valid_intensity(
self.light_id
)
self.max_intensity = max_intensity["data"]["ranges"][0]["high"]
@property @property
def supported_features(self): def supported_features(self):
@ -87,26 +85,28 @@ class AxisLight(AxisEventBase, LightEntity):
"""Return the brightness of this light between 0..255.""" """Return the brightness of this light between 0..255."""
return int((self.current_intensity / self.max_intensity) * 255) return int((self.current_intensity / self.max_intensity) * 255)
def turn_on(self, **kwargs): async def async_turn_on(self, **kwargs):
"""Turn on light.""" """Turn on light."""
if not self.is_on: if not self.is_on:
self.device.api.vapix.light_control.activate_light(self.light_id) await self.device.api.vapix.light_control.activate_light(self.light_id)
if ATTR_BRIGHTNESS in kwargs: if ATTR_BRIGHTNESS in kwargs:
intensity = int((kwargs[ATTR_BRIGHTNESS] / 255) * self.max_intensity) intensity = int((kwargs[ATTR_BRIGHTNESS] / 255) * self.max_intensity)
self.device.api.vapix.light_control.set_manual_intensity( await self.device.api.vapix.light_control.set_manual_intensity(
self.light_id, intensity self.light_id, intensity
) )
def turn_off(self, **kwargs): async def async_turn_off(self, **kwargs):
"""Turn off light.""" """Turn off light."""
if self.is_on: if self.is_on:
self.device.api.vapix.light_control.deactivate_light(self.light_id) await self.device.api.vapix.light_control.deactivate_light(self.light_id)
def update(self): async def async_update(self):
"""Update brightness.""" """Update brightness."""
current_intensity = self.device.api.vapix.light_control.get_current_intensity( current_intensity = (
self.light_id await self.device.api.vapix.light_control.get_current_intensity(
self.light_id
)
) )
self.current_intensity = current_intensity["data"]["intensity"] self.current_intensity = current_intensity["data"]["intensity"]

View file

@ -3,7 +3,7 @@
"name": "Axis", "name": "Axis",
"config_flow": true, "config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/axis", "documentation": "https://www.home-assistant.io/integrations/axis",
"requirements": ["axis==39"], "requirements": ["axis==40"],
"zeroconf": [ "zeroconf": [
{ "type": "_axis-video._tcp.local.", "macaddress": "00408C*" }, { "type": "_axis-video._tcp.local.", "macaddress": "00408C*" },
{ "type": "_axis-video._tcp.local.", "macaddress": "ACCC8E*" }, { "type": "_axis-video._tcp.local.", "macaddress": "ACCC8E*" },

View file

@ -37,15 +37,11 @@ class AxisSwitch(AxisEventBase, SwitchEntity):
async def async_turn_on(self, **kwargs): async def async_turn_on(self, **kwargs):
"""Turn on switch.""" """Turn on switch."""
await self.hass.async_add_executor_job( await self.device.api.vapix.ports[self.event.id].close()
self.device.api.vapix.ports[self.event.id].close
)
async def async_turn_off(self, **kwargs): async def async_turn_off(self, **kwargs):
"""Turn off switch.""" """Turn off switch."""
await self.hass.async_add_executor_job( await self.device.api.vapix.ports[self.event.id].open()
self.device.api.vapix.ports[self.event.id].open
)
@property @property
def name(self): def name(self):

View file

@ -309,7 +309,7 @@ av==8.0.2
avri-api==0.1.7 avri-api==0.1.7
# homeassistant.components.axis # homeassistant.components.axis
axis==39 axis==40
# homeassistant.components.azure_event_hub # homeassistant.components.azure_event_hub
azure-eventhub==5.1.0 azure-eventhub==5.1.0

View file

@ -180,7 +180,7 @@ av==8.0.2
avri-api==0.1.7 avri-api==0.1.7
# homeassistant.components.axis # homeassistant.components.axis
axis==39 axis==40
# homeassistant.components.azure_event_hub # homeassistant.components.azure_event_hub
azure-eventhub==5.1.0 azure-eventhub==5.1.0

View file

@ -38,7 +38,7 @@ from homeassistant.const import (
CONF_USERNAME, CONF_USERNAME,
) )
from tests.async_mock import Mock, patch from tests.async_mock import AsyncMock, Mock, patch
from tests.common import MockConfigEntry, async_fire_mqtt_message from tests.common import MockConfigEntry, async_fire_mqtt_message
MAC = "00408C12345" MAC = "00408C12345"
@ -196,7 +196,7 @@ root.StreamProfile.S1.Parameters=videocodec=h265
""" """
def vapix_request(self, session, url, **kwargs): async def vapix_request(self, session, url, **kwargs):
"""Return data based on url.""" """Return data based on url."""
if API_DISCOVERY_URL in url: if API_DISCOVERY_URL in url:
return API_DISCOVERY_RESPONSE return API_DISCOVERY_RESPONSE
@ -384,10 +384,12 @@ async def test_shutdown():
axis_device = axis.device.AxisNetworkDevice(hass, entry) axis_device = axis.device.AxisNetworkDevice(hass, entry)
axis_device.api = Mock() axis_device.api = Mock()
axis_device.api.vapix.close = AsyncMock()
axis_device.shutdown(None) await axis_device.shutdown(None)
assert len(axis_device.api.stream.stop.mock_calls) == 1 assert len(axis_device.api.stream.stop.mock_calls) == 1
assert len(axis_device.api.vapix.close.mock_calls) == 1
async def test_get_device_fails(hass): async def test_get_device_fails(hass):

View file

@ -91,7 +91,7 @@ async def test_lights(hass):
{"entity_id": f"light.{NAME}_ir_light_0", ATTR_BRIGHTNESS: 50}, {"entity_id": f"light.{NAME}_ir_light_0", ATTR_BRIGHTNESS: 50},
blocking=True, blocking=True,
) )
mock_activate.not_called() mock_activate.assert_not_awaited()
mock_set_intensity.assert_called_once_with("led0", 29) mock_set_intensity.assert_called_once_with("led0", 29)
# Turn off # Turn off

View file

@ -13,7 +13,7 @@ from .test_device import (
setup_axis_integration, setup_axis_integration,
) )
from tests.async_mock import Mock, patch from tests.async_mock import AsyncMock, patch
EVENTS = [ EVENTS = [
{ {
@ -55,8 +55,10 @@ async def test_switches_with_port_cgi(hass):
"""Test that switches are loaded properly using port.cgi.""" """Test that switches are loaded properly using port.cgi."""
device = await setup_axis_integration(hass) device = await setup_axis_integration(hass)
device.api.vapix.ports = {"0": Mock(), "1": Mock()} device.api.vapix.ports = {"0": AsyncMock(), "1": AsyncMock()}
device.api.vapix.ports["0"].name = "Doorbell" device.api.vapix.ports["0"].name = "Doorbell"
device.api.vapix.ports["0"].open = AsyncMock()
device.api.vapix.ports["0"].close = AsyncMock()
device.api.vapix.ports["1"].name = "" device.api.vapix.ports["1"].name = ""
for event in EVENTS: for event in EVENTS:
@ -98,8 +100,10 @@ async def test_switches_with_port_management(hass):
with patch.dict(API_DISCOVERY_RESPONSE, api_discovery): with patch.dict(API_DISCOVERY_RESPONSE, api_discovery):
device = await setup_axis_integration(hass) device = await setup_axis_integration(hass)
device.api.vapix.ports = {"0": Mock(), "1": Mock()} device.api.vapix.ports = {"0": AsyncMock(), "1": AsyncMock()}
device.api.vapix.ports["0"].name = "Doorbell" device.api.vapix.ports["0"].name = "Doorbell"
device.api.vapix.ports["0"].open = AsyncMock()
device.api.vapix.ports["0"].close = AsyncMock()
device.api.vapix.ports["1"].name = "" device.api.vapix.ports["1"].name = ""
for event in EVENTS: for event in EVENTS: