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

+238 -241
View File
@@ -1,52 +1,48 @@
"""Support for Broadlink RM devices."""
from datetime import timedelta
from ipaddress import ip_address
"""Support for Broadlink switches."""
from abc import ABC, abstractmethod
import logging
import broadlink as blk
from broadlink.exceptions import BroadlinkException, CommandNotSupportedError
from broadlink.exceptions import BroadlinkException
import voluptuous as vol
from homeassistant.components.switch import DOMAIN, PLATFORM_SCHEMA, SwitchEntity
from homeassistant.components.switch import (
DEVICE_CLASS_OUTLET,
DEVICE_CLASS_SWITCH,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
CONF_COMMAND_OFF,
CONF_COMMAND_ON,
CONF_FRIENDLY_NAME,
CONF_HOST,
CONF_MAC,
CONF_NAME,
CONF_SWITCHES,
CONF_TIMEOUT,
CONF_TYPE,
STATE_ON,
)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.util import Throttle, slugify
from . import async_setup_service, data_packet, hostname, mac_address
from .const import (
DEFAULT_NAME,
DEFAULT_PORT,
DEFAULT_TIMEOUT,
MP1_TYPES,
RM4_TYPES,
RM_TYPES,
SP1_TYPES,
SP2_TYPES,
)
from .device import BroadlinkDevice
from .const import DOMAIN, SWITCH_DOMAIN
from .helpers import data_packet, import_device, mac_address
_LOGGER = logging.getLogger(__name__)
TIME_BETWEEN_UPDATES = timedelta(seconds=5)
CONF_SLOTS = "slots"
CONF_RETRY = "retry"
DEVICE_TYPES = RM_TYPES + RM4_TYPES + SP1_TYPES + SP2_TYPES + MP1_TYPES
SWITCH_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_COMMAND_OFF): data_packet,
vol.Optional(CONF_COMMAND_ON): data_packet,
}
)
OLD_SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_COMMAND_OFF): data_packet,
vol.Optional(CONF_COMMAND_ON): data_packet,
@@ -54,288 +50,289 @@ SWITCH_SCHEMA = vol.Schema(
}
)
MP1_SWITCH_SLOT_SCHEMA = vol.Schema(
{
vol.Optional("slot_1"): cv.string,
vol.Optional("slot_2"): cv.string,
vol.Optional("slot_3"): cv.string,
vol.Optional("slot_4"): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_SWITCHES, default={}): cv.schema_with_slug_keys(
SWITCH_SCHEMA
),
vol.Optional(CONF_SLOTS, default={}): MP1_SWITCH_SLOT_SCHEMA,
vol.Required(CONF_HOST): vol.All(vol.Any(hostname, ip_address), cv.string),
vol.Required(CONF_MAC): mac_address,
vol.Optional(CONF_FRIENDLY_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_TYPE, default=DEVICE_TYPES[0]): vol.In(DEVICE_TYPES),
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
}
PLATFORM_SCHEMA = vol.All(
cv.deprecated(CONF_HOST),
cv.deprecated(CONF_SLOTS),
cv.deprecated(CONF_TIMEOUT),
cv.deprecated(CONF_TYPE),
PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MAC): mac_address,
vol.Optional(CONF_HOST): cv.string,
vol.Optional(CONF_SWITCHES, default=[]): vol.Any(
cv.schema_with_slug_keys(OLD_SWITCH_SCHEMA),
vol.All(cv.ensure_list, [SWITCH_SCHEMA]),
),
}
),
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Broadlink switches."""
"""Import the device and set up custom switches.
host = config[CONF_HOST]
This is for backward compatibility.
Do not use this method.
"""
mac_addr = config[CONF_MAC]
friendly_name = config[CONF_FRIENDLY_NAME]
model = config[CONF_TYPE]
timeout = config[CONF_TIMEOUT]
slots = config[CONF_SLOTS]
devices = config[CONF_SWITCHES]
host = config.get(CONF_HOST)
switches = config.get(CONF_SWITCHES)
def generate_rm_switches(switches, broadlink_device):
"""Generate RM switches."""
return [
BroadlinkRMSwitch(
object_id,
config.get(CONF_FRIENDLY_NAME, object_id),
broadlink_device,
config.get(CONF_COMMAND_ON),
config.get(CONF_COMMAND_OFF),
)
for object_id, config in switches.items()
]
def get_mp1_slot_name(switch_friendly_name, slot):
"""Get slot name."""
if not slots[f"slot_{slot}"]:
return f"{switch_friendly_name} slot {slot}"
return slots[f"slot_{slot}"]
if model in RM_TYPES:
api = blk.rm((host, DEFAULT_PORT), mac_addr, None)
broadlink_device = BroadlinkDevice(hass, api)
switches = generate_rm_switches(devices, broadlink_device)
elif model in RM4_TYPES:
api = blk.rm4((host, DEFAULT_PORT), mac_addr, None)
broadlink_device = BroadlinkDevice(hass, api)
switches = generate_rm_switches(devices, broadlink_device)
elif model in SP1_TYPES:
api = blk.sp1((host, DEFAULT_PORT), mac_addr, None)
broadlink_device = BroadlinkDevice(hass, api)
switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
elif model in SP2_TYPES:
api = blk.sp2((host, DEFAULT_PORT), mac_addr, None)
broadlink_device = BroadlinkDevice(hass, api)
switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
elif model in MP1_TYPES:
api = blk.mp1((host, DEFAULT_PORT), mac_addr, None)
broadlink_device = BroadlinkDevice(hass, api)
parent_device = BroadlinkMP1Switch(broadlink_device)
if not isinstance(switches, list):
switches = [
BroadlinkMP1Slot(
get_mp1_slot_name(friendly_name, i), broadlink_device, i, parent_device,
)
for i in range(1, 5)
{CONF_NAME: switch.pop(CONF_FRIENDLY_NAME, name), **switch}
for name, switch in switches.items()
]
api.timeout = timeout
connected = await broadlink_device.async_connect()
if not connected:
raise PlatformNotReady
_LOGGER.warning(
"Your configuration for the switch platform is deprecated. "
"Please refer to the Broadlink documentation to catch up"
)
if model in RM_TYPES or model in RM4_TYPES:
hass.async_create_task(async_setup_service(hass, host, broadlink_device))
if switches:
platform_data = hass.data[DOMAIN].platforms.setdefault(SWITCH_DOMAIN, {})
platform_data.setdefault(mac_addr, []).extend(switches)
else:
_LOGGER.warning(
"The switch platform is deprecated, except for custom IR/RF "
"switches. Please refer to the Broadlink documentation to "
"catch up"
)
if host:
import_device(hass, host)
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Broadlink switch."""
device = hass.data[DOMAIN].devices[config_entry.entry_id]
if device.api.type in {"RM2", "RM4"}:
platform_data = hass.data[DOMAIN].platforms.get(SWITCH_DOMAIN, {})
user_defined_switches = platform_data.get(device.api.mac, {})
switches = [
BroadlinkRMSwitch(device, config) for config in user_defined_switches
]
elif device.api.type == "SP1":
switches = [BroadlinkSP1Switch(device)]
elif device.api.type == "SP2":
switches = [BroadlinkSP2Switch(device)]
elif device.api.type == "MP1":
switches = [BroadlinkMP1Slot(device, slot) for slot in range(1, 5)]
async_add_entities(switches)
class BroadlinkRMSwitch(SwitchEntity, RestoreEntity):
"""Representation of an Broadlink switch."""
class BroadlinkSwitch(SwitchEntity, RestoreEntity, ABC):
"""Representation of a Broadlink switch."""
def __init__(self, name, friendly_name, device, command_on, command_off):
def __init__(self, device, command_on, command_off):
"""Initialize the switch."""
self.device = device
self.entity_id = f"{DOMAIN}.{slugify(name)}"
self._name = friendly_name
self._state = False
self._device = device
self._command_on = command_on
self._command_off = command_off
self._coordinator = device.update_manager.coordinator
self._device_class = None
self._state = None
@property
def name(self):
"""Return the name of the switch."""
return f"{self._device.name} Switch"
@property
def assumed_state(self):
"""Return True if unable to access real state of the switch."""
return True
@property
def available(self):
"""Return True if the switch is available."""
return self._device.update_manager.available
@property
def is_on(self):
"""Return True if the switch is on."""
return self._state
@property
def should_poll(self):
"""Return True if the switch has to be polled for state."""
return False
@property
def device_class(self):
"""Return device class."""
return self._device_class
@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,
}
@callback
def update_data(self):
"""Update data."""
self.async_write_ha_state()
async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
"""Call when the switch is added to hass."""
if self._state is None:
state = await self.async_get_last_state()
self._state = state is not None and state.state == STATE_ON
self.async_on_remove(self._coordinator.async_add_listener(self.update_data))
async def async_update(self):
"""Update the switch."""
await self._coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs):
"""Turn on the switch."""
if await self._async_send_packet(self._command_on):
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Turn off the switch."""
if await self._async_send_packet(self._command_off):
self._state = False
self.async_write_ha_state()
@abstractmethod
async def _async_send_packet(self, packet):
"""Send a packet to the device."""
class BroadlinkRMSwitch(BroadlinkSwitch):
"""Representation of a Broadlink RM switch."""
def __init__(self, device, config):
"""Initialize the switch."""
super().__init__(
device, config.get(CONF_COMMAND_ON), config.get(CONF_COMMAND_OFF)
)
self._name = config[CONF_NAME]
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def assumed_state(self):
"""Return true if unable to access real state of entity."""
return True
@property
def available(self):
"""Return True if entity is available."""
return not self.should_poll or self.device.available
@property
def should_poll(self):
"""Return the polling state."""
return False
@property
def is_on(self):
"""Return true if device is on."""
return self._state
async def async_update(self):
"""Update the state of the device."""
if not self.available:
await self.device.async_connect()
async def async_turn_on(self, **kwargs):
"""Turn the device on."""
if await self._async_send_packet(self._command_on):
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Turn the device off."""
if await self._async_send_packet(self._command_off):
self._state = False
self.async_write_ha_state()
async def _async_send_packet(self, packet):
"""Send packet to device."""
"""Send a packet to the device."""
if packet is None:
_LOGGER.debug("Empty packet")
return True
try:
await self.device.async_request(self.device.api.send_data, packet)
except BroadlinkException as err_msg:
_LOGGER.error("Failed to send packet: %s", err_msg)
await self._device.async_request(self._device.api.send_data, packet)
except (BroadlinkException, OSError) as err:
_LOGGER.error("Failed to send packet: %s", err)
return False
return True
class BroadlinkSP1Switch(BroadlinkRMSwitch):
"""Representation of an Broadlink switch."""
class BroadlinkSP1Switch(BroadlinkSwitch):
"""Representation of a Broadlink SP1 switch."""
def __init__(self, friendly_name, device):
def __init__(self, device):
"""Initialize the switch."""
super().__init__(friendly_name, friendly_name, device, None, None)
self._command_on = 1
self._command_off = 0
self._load_power = None
super().__init__(device, 1, 0)
self._device_class = DEVICE_CLASS_OUTLET
@property
def unique_id(self):
"""Return the unique id of the switch."""
return self._device.unique_id
async def _async_send_packet(self, packet):
"""Send packet to device."""
"""Send a packet to the device."""
try:
await self.device.async_request(self.device.api.set_power, packet)
except BroadlinkException as err_msg:
_LOGGER.error("Failed to send packet: %s", err_msg)
await self._device.async_request(self._device.api.set_power, packet)
except (BroadlinkException, OSError) as err:
_LOGGER.error("Failed to send packet: %s", err)
return False
return True
class BroadlinkSP2Switch(BroadlinkSP1Switch):
"""Representation of an Broadlink switch."""
"""Representation of a Broadlink SP2 switch."""
def __init__(self, device, *args, **kwargs):
"""Initialize the switch."""
super().__init__(device, *args, **kwargs)
self._state = self._coordinator.data["state"]
self._load_power = self._coordinator.data["load_power"]
if device.api.model == "SC1":
self._device_class = DEVICE_CLASS_SWITCH
@property
def assumed_state(self):
"""Return true if unable to access real state of entity."""
"""Return True if unable to access real state of the switch."""
return False
@property
def should_poll(self):
"""Return the polling state."""
return True
@property
def current_power_w(self):
"""Return the current power usage in Watt."""
try:
return round(self._load_power, 2)
except (ValueError, TypeError):
return None
return self._load_power
async def async_update(self):
"""Update the state of the device."""
try:
self._state = await self.device.async_request(self.device.api.check_power)
except BroadlinkException as err_msg:
_LOGGER.error("Failed to update state: %s", err_msg)
return
try:
self._load_power = await self.device.async_request(
self.device.api.get_energy
)
except CommandNotSupportedError:
return
except BroadlinkException as err_msg:
_LOGGER.error("Failed to update load power: %s", err_msg)
@callback
def update_data(self):
"""Update data."""
if self._coordinator.last_update_success:
self._state = self._coordinator.data["state"]
self._load_power = self._coordinator.data["load_power"]
self.async_write_ha_state()
class BroadlinkMP1Slot(BroadlinkRMSwitch):
"""Representation of a slot of Broadlink switch."""
class BroadlinkMP1Slot(BroadlinkSwitch):
"""Representation of a Broadlink MP1 slot."""
def __init__(self, friendly_name, device, slot, parent_device):
"""Initialize the slot of switch."""
super().__init__(friendly_name, friendly_name, device, None, None)
self._command_on = 1
self._command_off = 0
def __init__(self, device, slot):
"""Initialize the switch."""
super().__init__(device, 1, 0)
self._slot = slot
self._parent_device = parent_device
self._state = self._coordinator.data[f"s{slot}"]
self._device_class = DEVICE_CLASS_OUTLET
@property
def unique_id(self):
"""Return the unique id of the slot."""
return f"{self._device.unique_id}-s{self._slot}"
@property
def name(self):
"""Return the name of the switch."""
return f"{self._device.name} S{self._slot}"
@property
def assumed_state(self):
"""Return true if unable to access real state of entity."""
"""Return True if unable to access real state of the switch."""
return False
@property
def should_poll(self):
"""Return the polling state."""
return True
async def async_update(self):
"""Update the state of the device."""
await self._parent_device.async_update()
self._state = self._parent_device.get_outlet_status(self._slot)
@callback
def update_data(self):
"""Update data."""
if self._coordinator.last_update_success:
self._state = self._coordinator.data[f"s{self._slot}"]
self.async_write_ha_state()
async def _async_send_packet(self, packet):
"""Send packet to device."""
"""Send a packet to the device."""
try:
await self.device.async_request(
self.device.api.set_power, self._slot, packet
await self._device.async_request(
self._device.api.set_power, self._slot, packet
)
except BroadlinkException as err_msg:
_LOGGER.error("Failed to send packet: %s", err_msg)
except (BroadlinkException, OSError) as err:
_LOGGER.error("Failed to send packet: %s", err)
return False
return True
class BroadlinkMP1Switch:
"""Representation of a Broadlink switch - To fetch states of all slots."""
def __init__(self, device):
"""Initialize the switch."""
self.device = device
self._states = None
def get_outlet_status(self, slot):
"""Get status of outlet from cached status list."""
if self._states is None:
return None
return self._states[f"s{slot}"]
@Throttle(TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Update the state of the device."""
try:
states = await self.device.async_request(self.device.api.check_power)
except BroadlinkException as err_msg:
_LOGGER.error("Failed to update state: %s", err_msg)
self._states = states