Add new integration for Bond hub (#37477)

* create foundation for Bond integration

* add Bond hub integration (fix lint)

* Update homeassistant/components/bond/__init__.py

adding async_unload_entry per PR review suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* add Bond hub integration (fix missing import after applying PR suggestion)

* Update tests/components/bond/test_init.py

add a unit for unloading per PR review suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update tests/components/bond/test_init.py

add unit test for unload per PR review suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update tests/components/bond/test_init.py

PR review suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update tests/components/bond/test_init.py

PR review suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update tests/components/bond/test_init.py

PR review suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* add Bond hub integration (fix formatting)

* Update homeassistant/components/bond/manifest.json

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update homeassistant/components/bond/manifest.json

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update homeassistant/components/bond/manifest.json

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update homeassistant/components/bond/strings.json

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update homeassistant/components/bond/manifest.json

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update requirements_all.txt

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update homeassistant/components/bond/manifest.json

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update requirements_test_all.txt

PR suggestion

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* add Bond hub integration (remove friendly name from config per PR suggestion)

* Update homeassistant/components/bond/__init__.py

add per PR review feedback

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update homeassistant/components/bond/__init__.py

remove per PR review feedback

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

* Update tests/components/bond/test_init.py

fix unit test

Co-authored-by: Chris Talkington <chris@talkingtontech.com>

Co-authored-by: Chris Talkington <chris@talkingtontech.com>
This commit is contained in:
Eugene PrystupaandChris Talkington authored and GitHub committed 2020-07-05 20:17:53 -05:00
1 parent 6749424508
commit 9b77e16ffc
18 files changed
+617

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
"""The Bond integration."""
import asyncio
from bond import Bond
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST
from homeassistant.core import HomeAssistant
from .const import DOMAIN
CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA)
PLATFORMS = ["cover"]
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Bond component."""
hass.data.setdefault(DOMAIN, {})
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up Bond from a config entry."""
host = entry.data[CONF_HOST]
token = entry.data[CONF_ACCESS_TOKEN]
hass.data[DOMAIN][entry.entry_id] = Bond(bondIp=host, bondToken=token)
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok
@@ -0,0 +1,74 @@
"""Config flow for Bond integration."""
import logging
from bond import Bond
from requests.exceptions import ConnectionError as RequestConnectionError
from simplejson import JSONDecodeError
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST
from .const import DOMAIN # pylint:disable=unused-import
_LOGGER = logging.getLogger(__name__)
DATA_SCHEMA = vol.Schema(
{vol.Required(CONF_HOST): str, vol.Required(CONF_ACCESS_TOKEN): str}
)
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect."""
def authenticate(bond_hub: Bond) -> bool:
try:
bond_hub.getDeviceIds()
return True
except RequestConnectionError:
raise CannotConnect
except JSONDecodeError:
return False
bond = Bond(data[CONF_HOST], data[CONF_ACCESS_TOKEN])
if not await hass.async_add_executor_job(authenticate, bond):
raise InvalidAuth
# Return info that you want to store in the config entry.
return {"title": data[CONF_HOST]}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Bond."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
return self.async_create_entry(title=info["title"], data=user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""
+3
View File
@@ -0,0 +1,3 @@
"""Constants for the Bond integration."""
DOMAIN = "bond"
+84
View File
@@ -0,0 +1,84 @@
"""Support for Bond covers."""
import asyncio
import logging
from typing import Any, Callable, Dict, List, Optional
from bond import BOND_DEVICE_TYPE_MOTORIZED_SHADES, Bond
from homeassistant.components.cover import DEVICE_CLASS_SHADE, CoverEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
from .utils import BondDevice, get_bond_devices
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity]], None],
) -> None:
"""Set up Bond cover devices."""
bond: Bond = hass.data[DOMAIN][entry.entry_id]
async def discover():
devices = await get_bond_devices(hass, bond)
covers = [
BondCover(bond, device)
for device in devices
if device.type == BOND_DEVICE_TYPE_MOTORIZED_SHADES
]
async_add_entities(covers)
asyncio.create_task(discover())
class BondCover(CoverEntity):
"""Representation of a Bond cover."""
def __init__(self, bond: Bond, device: BondDevice):
"""Create HA entity representing Bond cover."""
self._bond = bond
self._device = device
@property
def device_class(self) -> Optional[str]:
"""Get device class."""
return DEVICE_CLASS_SHADE
@property
def unique_id(self) -> Optional[str]:
"""Get unique ID for the entity."""
return self._device.device_id
@property
def name(self) -> Optional[str]:
"""Get entity name."""
return self._device.name
@property
def device_info(self) -> Optional[Dict[str, Any]]:
"""Get a an HA device representing this cover."""
return {ATTR_NAME: self.name, "identifiers": {(DOMAIN, self.unique_id)}}
@property
def is_closed(self):
"""Return if the cover is closed or not."""
return None
def open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
self._bond.open(self._device.device_id)
def close_cover(self, **kwargs: Any) -> None:
"""Close cover."""
self._bond.close(self._device.device_id)
def stop_cover(self, **kwargs):
"""Hold cover."""
self._bond.hold(self._device.device_id)
@@ -0,0 +1,12 @@
{
"domain": "bond",
"name": "Bond",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/bond",
"requirements": [
"bond-home==0.0.8"
],
"codeowners": [
"@prystupa"
]
}
@@ -0,0 +1,17 @@
{
"config": {
"step": {
"user": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
"access_token": "[%key:common::config_flow::data::access_token%]"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
}
}
}
@@ -0,0 +1,18 @@
{
"config": {
"error": {
"cannot_connect": "Unable to connect to Bond device",
"invalid_auth": "Unable to authenticate with Bond device, check provided token",
"unknown": "Unknown error while connecting to Bond device (check the logs for errors)"
},
"step": {
"user": {
"data": {
"host": "Bond device IP address or host name",
"access_token": "Bond device token"
}
}
}
},
"title": "Bond"
}
+38
View File
@@ -0,0 +1,38 @@
"""Reusable utilities for the Bond component."""
from typing import List
from bond import Bond
from homeassistant.core import HomeAssistant
class BondDevice:
"""Helper device class to hold ID and attributes together."""
def __init__(self, device_id: str, attrs: dict):
"""Create a helper device from ID and attributes returned by API."""
self.device_id = device_id
self._attrs = attrs
@property
def name(self):
"""Get the name of this device."""
return self._attrs["name"]
@property
def type(self):
"""Get the type of this device."""
return self._attrs["type"]
async def get_bond_devices(hass: HomeAssistant, bond: Bond) -> List[BondDevice]:
"""Fetch all available devices using Bond API."""
device_ids = await hass.async_add_executor_job(bond.getDeviceIds)
devices = [
BondDevice(
device_id, await hass.async_add_executor_job(bond.getDevice, device_id)
)
for device_id in device_ids
]
return devices
+1
View File
@@ -23,6 +23,7 @@ FLOWS = [
"axis",
"blebox",
"blink",
"bond",
"braviatv",
"brother",
"bsblan",