Implement config flow in the Broadlink integration (#36914)

* Implement config flow in the Broadlink integration

* General improvements to the Broadlink config flow

* Remove unnecessary else after return

* Fix translations

* Rename device to device_entry

* Add tests for the config flow

* Improve docstrings

* Test we do not accept more than one config entry per device

* Improve helpers

* Allow empty packets

* Allow multiple config files for switches related to the same device

* Rename mock_device to mock_api

* General improvements

* Make new attempts before marking the device as unavailable

* Let the name be the template for the entity_id

* Handle OSError

* Test network unavailable in the configuration flow

* Rename lock attribute

* Update manifest.json

* Import devices from platforms

* Test import flow

* Add deprecation warnings

* General improvements

* Rename deprecate to discontinue

* Test device setup

* Add type attribute to mock api

* Test we handle an update failure at startup

* Remove BroadlinkDevice from tests

* Remove device.py from .coveragerc

* Add tests for the config flow

* Add tests for the device

* Test device registry and update listener

* Test MAC address validation

* Add tests for the device

* Extract domains and types to a helper function

* Do not patch integration details

* Add tests for the device

* Set device classes where appropriate

* Set an appropriate connection class

* Do not set device class for custom switches

* Fix tests and improve code readability

* Use RM4 to test authentication errors

* Handle BroadlinkException in the authentication
This commit is contained in:
Felipe Martins Diel authored and GitHub committed 2020-08-20 17:30:41 +02:00
1 parent eb4f667a1a
commit a2c1f08c8c
21 files changed
+2497 -795

No files matched your search

+168 -141
View File
@@ -1,14 +1,11 @@
"""Support for Broadlink IR/RF remotes."""
"""Support for Broadlink remotes."""
import asyncio
from base64 import b64encode
from binascii import hexlify
from collections import defaultdict
from datetime import timedelta
from ipaddress import ip_address
from itertools import product
import logging
import broadlink as blk
from broadlink.exceptions import (
AuthorizationError,
BroadlinkException,
@@ -25,131 +22,108 @@ from homeassistant.components.remote import (
ATTR_DEVICE,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
DOMAIN as COMPONENT,
PLATFORM_SCHEMA,
SUPPORT_LEARN_COMMAND,
RemoteEntity,
)
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_NAME, CONF_TIMEOUT, CONF_TYPE
from homeassistant.const import CONF_HOST, STATE_ON
from homeassistant.core import callback
from homeassistant.exceptions import HomeAssistantError, PlatformNotReady
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.storage import Store
from homeassistant.util.dt import utcnow
from . import DOMAIN, data_packet, hostname, mac_address
from .const import (
DEFAULT_NAME,
DEFAULT_PORT,
DEFAULT_TIMEOUT,
LEARNING_TIMEOUT,
RM4_TYPES,
RM_TYPES,
)
from .device import BroadlinkDevice
from .const import DOMAIN
from .helpers import data_packet, import_device
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=2)
LEARNING_TIMEOUT = timedelta(seconds=30)
CODE_STORAGE_VERSION = 1
FLAG_STORAGE_VERSION = 1
FLAG_SAVE_DELAY = 15
DEVICE_TYPES = RM_TYPES + RM4_TYPES
MINIMUM_SERVICE_SCHEMA = vol.Schema(
COMMAND_SCHEMA = vol.Schema(
{
vol.Required(ATTR_COMMAND): vol.All(
cv.ensure_list, [vol.All(cv.string, vol.Length(min=1))], vol.Length(min=1)
),
vol.Required(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
},
extra=vol.ALLOW_EXTRA,
)
SERVICE_SEND_SCHEMA = MINIMUM_SERVICE_SCHEMA.extend(
{vol.Optional(ATTR_DELAY_SECS, default=DEFAULT_DELAY_SECS): vol.Coerce(float)}
SERVICE_SEND_SCHEMA = COMMAND_SCHEMA.extend(
{
vol.Optional(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
vol.Optional(ATTR_DELAY_SECS, default=DEFAULT_DELAY_SECS): vol.Coerce(float),
}
)
SERVICE_LEARN_SCHEMA = MINIMUM_SERVICE_SCHEMA.extend(
{vol.Optional(ATTR_ALTERNATIVE, default=False): cv.boolean}
SERVICE_LEARN_SCHEMA = COMMAND_SCHEMA.extend(
{
vol.Required(ATTR_DEVICE): vol.All(cv.string, vol.Length(min=1)),
vol.Optional(ATTR_ALTERNATIVE, default=False): cv.boolean,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): vol.All(vol.Any(hostname, ip_address), cv.string),
vol.Required(CONF_MAC): mac_address,
vol.Optional(CONF_TYPE, default=DEVICE_TYPES[0]): vol.In(DEVICE_TYPES),
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
{vol.Required(CONF_HOST): cv.string}, extra=vol.ALLOW_EXTRA
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Broadlink remote."""
host = config[CONF_HOST]
mac_addr = config[CONF_MAC]
model = config[CONF_TYPE]
timeout = config[CONF_TIMEOUT]
name = config[CONF_NAME]
unique_id = f"remote_{hexlify(mac_addr).decode('utf-8')}"
"""Import the device and discontinue platform.
if unique_id in hass.data.setdefault(DOMAIN, {}).setdefault(COMPONENT, []):
_LOGGER.error("Duplicate: %s", unique_id)
return
hass.data[DOMAIN][COMPONENT].append(unique_id)
if model in RM_TYPES:
api = blk.rm((host, DEFAULT_PORT), mac_addr, None)
else:
api = blk.rm4((host, DEFAULT_PORT), mac_addr, None)
api.timeout = timeout
device = BroadlinkDevice(hass, api)
code_storage = Store(hass, CODE_STORAGE_VERSION, f"broadlink_{unique_id}_codes")
flag_storage = Store(hass, FLAG_STORAGE_VERSION, f"broadlink_{unique_id}_flags")
remote = BroadlinkRemote(name, unique_id, device, code_storage, flag_storage)
connected, loaded = await asyncio.gather(
device.async_connect(), remote.async_load_storage_files()
This is for backward compatibility.
Do not use this method.
"""
import_device(hass, config[CONF_HOST])
_LOGGER.warning(
"The remote platform is deprecated, please remove it from your configuration"
)
if not connected:
hass.data[DOMAIN][COMPONENT].remove(unique_id)
raise PlatformNotReady
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a Broadlink remote."""
device = hass.data[DOMAIN].devices[config_entry.entry_id]
remote = BroadlinkRemote(
device,
Store(hass, CODE_STORAGE_VERSION, f"broadlink_remote_{device.unique_id}_codes"),
Store(hass, FLAG_STORAGE_VERSION, f"broadlink_remote_{device.unique_id}_flags"),
)
loaded = await remote.async_load_storage_files()
if not loaded:
_LOGGER.error("Failed to set up %s", unique_id)
hass.data[DOMAIN][COMPONENT].remove(unique_id)
_LOGGER.error("Failed to create '%s Remote' entity: Storage error", device.name)
return
async_add_entities([remote], False)
class BroadlinkRemote(RemoteEntity):
class BroadlinkRemote(RemoteEntity, RestoreEntity):
"""Representation of a Broadlink remote."""
def __init__(self, name, unique_id, device, code_storage, flag_storage):
def __init__(self, device, codes, flags):
"""Initialize the remote."""
self.device = device
self._name = name
self._unique_id = unique_id
self._code_storage = code_storage
self._flag_storage = flag_storage
self._device = device
self._coordinator = device.update_manager.coordinator
self._code_storage = codes
self._flag_storage = flags
self._codes = {}
self._flags = defaultdict(int)
self._state = True
self._available = True
@property
def name(self):
"""Return the name of the remote."""
return self._name
return f"{self._device.name} Remote"
@property
def unique_id(self):
"""Return the unique ID of the remote."""
return self._unique_id
"""Return the unique id of the remote."""
return self._device.unique_id
@property
def is_on(self):
@@ -159,42 +133,104 @@ class BroadlinkRemote(RemoteEntity):
@property
def available(self):
"""Return True if the remote is available."""
return self.device.available
return self._device.update_manager.available
@property
def should_poll(self):
"""Return True if the remote has to be polled for state."""
return False
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_LEARN_COMMAND
@property
def device_info(self):
"""Return device info."""
return {
"identifiers": {(DOMAIN, self._device.unique_id)},
"manufacturer": self._device.api.manufacturer,
"model": self._device.api.model,
"name": self._device.name,
"sw_version": self._device.fw_version,
}
def get_code(self, command, device):
"""Return a code and a boolean indicating a toggle command.
If the command starts with `b64:`, extract the code from it.
Otherwise, extract the code from the dictionary, using the device
and command as keys.
You need to change the flag whenever a toggle command is sent
successfully. Use `self._flags[device] ^= 1`.
"""
if command.startswith("b64:"):
code, is_toggle_cmd = command[4:], False
else:
if device is None:
raise KeyError("You need to specify a device")
try:
code = self._codes[device][command]
except KeyError:
raise KeyError("Command not found")
# For toggle commands, alternate between codes in a list.
if isinstance(code, list):
code = code[self._flags[device]]
is_toggle_cmd = True
else:
is_toggle_cmd = False
try:
return data_packet(code), is_toggle_cmd
except ValueError:
raise ValueError("Invalid code")
@callback
def get_flags(self):
"""Return dictionary of toggle flags.
"""Return a dictionary of toggle flags.
A toggle flag indicates whether `self._async_send_code()`
should send an alternative code for a key device.
A toggle flag indicates whether the remote should send an
alternative code.
"""
return self._flags
async def async_turn_on(self, **kwargs):
"""Turn the remote on."""
self._state = True
async def async_added_to_hass(self):
"""Call when the remote is added to hass."""
state = await self.async_get_last_state()
self._state = state is None or state.state == STATE_ON
async def async_turn_off(self, **kwargs):
"""Turn the remote off."""
self._state = False
self.async_on_remove(
self._coordinator.async_add_listener(self.async_write_ha_state)
)
async def async_update(self):
"""Update the availability of the device."""
if not self.available:
await self.device.async_connect()
"""Update the remote."""
await self._coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs):
"""Turn on the remote."""
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Turn off the remote."""
self._state = False
self.async_write_ha_state()
async def async_load_storage_files(self):
"""Load codes and toggle flags from storage files."""
try:
self._codes.update(await self._code_storage.async_load() or {})
self._flags.update(await self._flag_storage.async_load() or {})
except HomeAssistantError:
return False
return True
async def async_send_command(self, command, **kwargs):
@@ -202,7 +238,7 @@ class BroadlinkRemote(RemoteEntity):
kwargs[ATTR_COMMAND] = command
kwargs = SERVICE_SEND_SCHEMA(kwargs)
commands = kwargs[ATTR_COMMAND]
device = kwargs[ATTR_DEVICE]
device = kwargs.get(ATTR_DEVICE)
repeat = kwargs[ATTR_NUM_REPEATS]
delay = kwargs[ATTR_DELAY_SECS]
@@ -210,53 +246,37 @@ class BroadlinkRemote(RemoteEntity):
return
should_delay = False
for _, cmd in product(range(repeat), commands):
if should_delay:
await asyncio.sleep(delay)
try:
should_delay = await self._async_send_code(
cmd, device, delay if should_delay else 0
)
except (AuthorizationError, DeviceOfflineError):
code, is_toggle_cmd = self.get_code(cmd, device)
except (KeyError, ValueError) as err:
_LOGGER.error("Failed to send '%s': %s", cmd, err)
should_delay = False
continue
try:
await self._device.async_request(self._device.api.send_data, code)
except (AuthorizationError, DeviceOfflineError, OSError) as err:
_LOGGER.error("Failed to send '%s': %s", command, err)
break
except BroadlinkException:
pass
except BroadlinkException as err:
_LOGGER.error("Failed to send '%s': %s", command, err)
should_delay = False
continue
should_delay = True
if is_toggle_cmd:
self._flags[device] ^= 1
self._flag_storage.async_delay_save(self.get_flags, FLAG_SAVE_DELAY)
async def _async_send_code(self, command, device, delay):
"""Send a code to a device.
For toggle commands, alternate between codes in a list,
ensuring that the same code is never sent twice in a row.
"""
try:
code = self._codes[device][command]
except KeyError:
_LOGGER.error("Failed to send '%s/%s': Command not found", command, device)
return False
if isinstance(code, list):
code = code[self._flags[device]]
should_alternate = True
else:
should_alternate = False
await asyncio.sleep(delay)
try:
await self.device.async_request(
self.device.api.send_data, data_packet(code)
)
except ValueError:
_LOGGER.error("Failed to send '%s/%s': Invalid code", command, device)
return False
except BroadlinkException as err_msg:
_LOGGER.error("Failed to send '%s/%s': %s", command, device, err_msg)
raise
if should_alternate:
self._flags[device] ^= 1
return True
async def async_learn_command(self, **kwargs):
"""Learn a list of commands from a remote."""
kwargs = SERVICE_LEARN_SCHEMA(kwargs)
@@ -268,20 +288,23 @@ class BroadlinkRemote(RemoteEntity):
return
should_store = False
for command in commands:
try:
code = await self._async_learn_command(command)
if toggle:
code = [code, await self._async_learn_command(command)]
except (AuthorizationError, DeviceOfflineError) as err_msg:
_LOGGER.error("Failed to learn '%s': %s", command, err_msg)
except (AuthorizationError, DeviceOfflineError, OSError) as err:
_LOGGER.error("Failed to learn '%s': %s", command, err)
break
except (BroadlinkException, TimeoutError) as err_msg:
_LOGGER.error("Failed to learn '%s': %s", command, err_msg)
except BroadlinkException as err:
_LOGGER.error("Failed to learn '%s': %s", command, err)
continue
else:
self._codes.setdefault(device, {}).update({command: code})
should_store = True
self._codes.setdefault(device, {}).update({command: code})
should_store = True
if should_store:
await self._code_storage.async_save(self._codes)
@@ -289,9 +312,10 @@ class BroadlinkRemote(RemoteEntity):
async def _async_learn_command(self, command):
"""Learn a command from a remote."""
try:
await self.device.async_request(self.device.api.enter_learning)
except BroadlinkException as err_msg:
_LOGGER.debug("Failed to enter learning mode: %s", err_msg)
await self._device.async_request(self._device.api.enter_learning)
except (BroadlinkException, OSError) as err:
_LOGGER.debug("Failed to enter learning mode: %s", err)
raise
self.hass.components.persistent_notification.async_create(
@@ -305,11 +329,14 @@ class BroadlinkRemote(RemoteEntity):
while (utcnow() - start_time) < LEARNING_TIMEOUT:
await asyncio.sleep(1)
try:
code = await self.device.async_request(self.device.api.check_data)
code = await self._device.async_request(self._device.api.check_data)
except (ReadError, StorageError):
continue
return b64encode(code).decode("utf8")
raise TimeoutError("No code received")
finally:
self.hass.components.persistent_notification.async_dismiss(
notification_id="learn_command"