Black
This commit is contained in:
1 parent
da05dfe708
commit
4de97abc3a
2676 files changed
+163166
-140084
No files matched your search
@@ -12,11 +12,9 @@ from .const import DOMAIN, KNOWN_DEVICES
|
||||
from .connection import get_bridge_information, get_accessory_name
|
||||
|
||||
|
||||
HOMEKIT_IGNORE = [
|
||||
'Home Assistant Bridge',
|
||||
]
|
||||
HOMEKIT_DIR = '.homekit'
|
||||
PAIRING_FILE = 'pairing.json'
|
||||
HOMEKIT_IGNORE = ["Home Assistant Bridge"]
|
||||
HOMEKIT_DIR = ".homekit"
|
||||
PAIRING_FILE = "pairing.json"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -36,7 +34,7 @@ def load_old_pairings(hass):
|
||||
# Find any pairings created in HA <= 0.84
|
||||
if os.path.exists(data_dir):
|
||||
for device in os.listdir(data_dir):
|
||||
if not device.startswith('hk-'):
|
||||
if not device.startswith("hk-"):
|
||||
continue
|
||||
alias = device[3:]
|
||||
if alias in old_pairings:
|
||||
@@ -51,7 +49,7 @@ def load_old_pairings(hass):
|
||||
def find_existing_host(hass, serial):
|
||||
"""Return a set of the configured hosts."""
|
||||
for entry in hass.config_entries.async_entries(DOMAIN):
|
||||
if entry.data['AccessoryPairingID'] == serial:
|
||||
if entry.data["AccessoryPairingID"] == serial:
|
||||
return entry
|
||||
|
||||
|
||||
@@ -77,34 +75,30 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
errors = {}
|
||||
|
||||
if user_input is not None:
|
||||
key = user_input['device']
|
||||
self.hkid = self.devices[key]['id']
|
||||
self.model = self.devices[key]['md']
|
||||
key = user_input["device"]
|
||||
self.hkid = self.devices[key]["id"]
|
||||
self.model = self.devices[key]["md"]
|
||||
return await self.async_step_pair()
|
||||
|
||||
all_hosts = await self.hass.async_add_executor_job(
|
||||
self.controller.discover, 5
|
||||
)
|
||||
all_hosts = await self.hass.async_add_executor_job(self.controller.discover, 5)
|
||||
|
||||
self.devices = {}
|
||||
for host in all_hosts:
|
||||
status_flags = int(host['sf'])
|
||||
status_flags = int(host["sf"])
|
||||
paired = not status_flags & 0x01
|
||||
if paired:
|
||||
continue
|
||||
self.devices[host['name']] = host
|
||||
self.devices[host["name"]] = host
|
||||
|
||||
if not self.devices:
|
||||
return self.async_abort(
|
||||
reason='no_devices'
|
||||
)
|
||||
return self.async_abort(reason="no_devices")
|
||||
|
||||
return self.async_show_form(
|
||||
step_id='user',
|
||||
step_id="user",
|
||||
errors=errors,
|
||||
data_schema=vol.Schema({
|
||||
vol.Required('device'): vol.In(self.devices.keys()),
|
||||
})
|
||||
data_schema=vol.Schema(
|
||||
{vol.Required("device"): vol.In(self.devices.keys())}
|
||||
),
|
||||
)
|
||||
|
||||
async def async_step_zeroconf(self, discovery_info):
|
||||
@@ -116,41 +110,38 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
# homekit_python has code to do this, but not in a form we can
|
||||
# easily use, so do the bare minimum ourselves here instead.
|
||||
properties = {
|
||||
key.lower(): value
|
||||
for (key, value) in discovery_info['properties'].items()
|
||||
key.lower(): value for (key, value) in discovery_info["properties"].items()
|
||||
}
|
||||
|
||||
# The hkid is a unique random number that looks like a pairing code.
|
||||
# It changes if a device is factory reset.
|
||||
hkid = properties['id']
|
||||
model = properties['md']
|
||||
name = discovery_info['name'].replace('._hap._tcp.local.', '')
|
||||
status_flags = int(properties['sf'])
|
||||
hkid = properties["id"]
|
||||
model = properties["md"]
|
||||
name = discovery_info["name"].replace("._hap._tcp.local.", "")
|
||||
status_flags = int(properties["sf"])
|
||||
paired = not status_flags & 0x01
|
||||
|
||||
_LOGGER.debug("Discovered device %s (%s - %s)", name, model, hkid)
|
||||
|
||||
# pylint: disable=unsupported-assignment-operation
|
||||
self.context['hkid'] = hkid
|
||||
self.context['title_placeholders'] = {
|
||||
'name': name,
|
||||
}
|
||||
self.context["hkid"] = hkid
|
||||
self.context["title_placeholders"] = {"name": name}
|
||||
|
||||
# If multiple HomekitControllerFlowHandler end up getting created
|
||||
# for the same accessory dont let duplicates hang around
|
||||
active_flows = self._async_in_progress()
|
||||
if any(hkid == flow['context']['hkid'] for flow in active_flows):
|
||||
return self.async_abort(reason='already_in_progress')
|
||||
if any(hkid == flow["context"]["hkid"] for flow in active_flows):
|
||||
return self.async_abort(reason="already_in_progress")
|
||||
|
||||
# The configuration number increases every time the characteristic map
|
||||
# needs updating. Some devices use a slightly off-spec name so handle
|
||||
# both cases.
|
||||
try:
|
||||
config_num = int(properties['c#'])
|
||||
config_num = int(properties["c#"])
|
||||
except KeyError:
|
||||
_LOGGER.warning(
|
||||
"HomeKit device %s: c# not exposed, in violation of spec",
|
||||
hkid)
|
||||
"HomeKit device %s: c# not exposed, in violation of spec", hkid
|
||||
)
|
||||
config_num = None
|
||||
|
||||
if paired:
|
||||
@@ -161,32 +152,31 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
conn = self.hass.data[KNOWN_DEVICES][hkid]
|
||||
if conn.config_num != config_num:
|
||||
_LOGGER.debug(
|
||||
"HomeKit info %s: c# incremented, refreshing entities",
|
||||
hkid)
|
||||
"HomeKit info %s: c# incremented, refreshing entities", hkid
|
||||
)
|
||||
self.hass.async_create_task(
|
||||
conn.async_refresh_entity_map(config_num))
|
||||
return self.async_abort(reason='already_configured')
|
||||
conn.async_refresh_entity_map(config_num)
|
||||
)
|
||||
return self.async_abort(reason="already_configured")
|
||||
|
||||
old_pairings = await self.hass.async_add_executor_job(
|
||||
load_old_pairings,
|
||||
self.hass
|
||||
load_old_pairings, self.hass
|
||||
)
|
||||
|
||||
if hkid in old_pairings:
|
||||
return await self.async_import_legacy_pairing(
|
||||
properties,
|
||||
old_pairings[hkid]
|
||||
properties, old_pairings[hkid]
|
||||
)
|
||||
|
||||
# Device is paired but not to us - ignore it
|
||||
_LOGGER.debug("HomeKit device %s ignored as already paired", hkid)
|
||||
return self.async_abort(reason='already_paired')
|
||||
return self.async_abort(reason="already_paired")
|
||||
|
||||
# Devices in HOMEKIT_IGNORE have native local integrations - users
|
||||
# should be encouraged to use native integration and not confused
|
||||
# by alternative HK API.
|
||||
if model in HOMEKIT_IGNORE:
|
||||
return self.async_abort(reason='ignored_model')
|
||||
return self.async_abort(reason="ignored_model")
|
||||
|
||||
# Device isn't paired with us or anyone else.
|
||||
# But we have a 'complete' config entry for it - that is probably
|
||||
@@ -207,18 +197,26 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
"""Migrate a legacy pairing to config entries."""
|
||||
from homekit.controller.ip_implementation import IpPairing
|
||||
|
||||
hkid = discovery_props['id']
|
||||
hkid = discovery_props["id"]
|
||||
|
||||
existing = find_existing_host(self.hass, hkid)
|
||||
if existing:
|
||||
_LOGGER.info(
|
||||
("Legacy configuration for homekit accessory %s"
|
||||
"not loaded as already migrated"), hkid)
|
||||
return self.async_abort(reason='already_configured')
|
||||
(
|
||||
"Legacy configuration for homekit accessory %s"
|
||||
"not loaded as already migrated"
|
||||
),
|
||||
hkid,
|
||||
)
|
||||
return self.async_abort(reason="already_configured")
|
||||
|
||||
_LOGGER.info(
|
||||
("Legacy configuration %s for homekit"
|
||||
"accessory migrated to config entries"), hkid)
|
||||
(
|
||||
"Legacy configuration %s for homekit"
|
||||
"accessory migrated to config entries"
|
||||
),
|
||||
hkid,
|
||||
)
|
||||
|
||||
pairing = IpPairing(pairing_data)
|
||||
|
||||
@@ -247,40 +245,35 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
errors = {}
|
||||
|
||||
if pair_info:
|
||||
code = pair_info['pairing_code']
|
||||
code = pair_info["pairing_code"]
|
||||
try:
|
||||
await self.hass.async_add_executor_job(
|
||||
self.finish_pairing, code
|
||||
)
|
||||
await self.hass.async_add_executor_job(self.finish_pairing, code)
|
||||
|
||||
pairing = self.controller.pairings.get(self.hkid)
|
||||
if pairing:
|
||||
return await self._entry_from_accessory(
|
||||
pairing)
|
||||
return await self._entry_from_accessory(pairing)
|
||||
|
||||
errors['pairing_code'] = 'unable_to_pair'
|
||||
errors["pairing_code"] = "unable_to_pair"
|
||||
except homekit.AuthenticationError:
|
||||
# PairSetup M4 - SRP proof failed
|
||||
# PairSetup M6 - Ed25519 signature verification failed
|
||||
# PairVerify M4 - Decryption failed
|
||||
# PairVerify M4 - Device not recognised
|
||||
# PairVerify M4 - Ed25519 signature verification failed
|
||||
errors['pairing_code'] = 'authentication_error'
|
||||
errors["pairing_code"] = "authentication_error"
|
||||
except homekit.UnknownError:
|
||||
# An error occured on the device whilst performing this
|
||||
# operation.
|
||||
errors['pairing_code'] = 'unknown_error'
|
||||
errors["pairing_code"] = "unknown_error"
|
||||
except homekit.MaxPeersError:
|
||||
# The device can't pair with any more accessories.
|
||||
errors['pairing_code'] = 'max_peers_error'
|
||||
errors["pairing_code"] = "max_peers_error"
|
||||
except homekit.AccessoryNotFoundError:
|
||||
# Can no longer find the device on the network
|
||||
return self.async_abort(reason='accessory_not_found_error')
|
||||
return self.async_abort(reason="accessory_not_found_error")
|
||||
except Exception: # pylint: disable=broad-except
|
||||
_LOGGER.exception(
|
||||
"Pairing attempt failed with an unhandled exception"
|
||||
)
|
||||
errors['pairing_code'] = 'pairing_failed'
|
||||
_LOGGER.exception("Pairing attempt failed with an unhandled exception")
|
||||
errors["pairing_code"] = "pairing_failed"
|
||||
|
||||
start_pairing = self.controller.start_pairing
|
||||
try:
|
||||
@@ -290,32 +283,30 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
except homekit.BusyError:
|
||||
# Already performing a pair setup operation with a different
|
||||
# controller
|
||||
errors['pairing_code'] = 'busy_error'
|
||||
errors["pairing_code"] = "busy_error"
|
||||
except homekit.MaxTriesError:
|
||||
# The accessory has received more than 100 unsuccessful auth
|
||||
# attempts.
|
||||
errors['pairing_code'] = 'max_tries_error'
|
||||
errors["pairing_code"] = "max_tries_error"
|
||||
except homekit.UnavailableError:
|
||||
# The accessory is already paired - cannot try to pair again.
|
||||
return self.async_abort(reason='already_paired')
|
||||
return self.async_abort(reason="already_paired")
|
||||
except homekit.AccessoryNotFoundError:
|
||||
# Can no longer find the device on the network
|
||||
return self.async_abort(reason='accessory_not_found_error')
|
||||
return self.async_abort(reason="accessory_not_found_error")
|
||||
except Exception: # pylint: disable=broad-except
|
||||
_LOGGER.exception(
|
||||
"Pairing attempt failed with an unhandled exception"
|
||||
)
|
||||
errors['pairing_code'] = 'pairing_failed'
|
||||
_LOGGER.exception("Pairing attempt failed with an unhandled exception")
|
||||
errors["pairing_code"] = "pairing_failed"
|
||||
|
||||
return self._async_step_pair_show_form(errors)
|
||||
|
||||
def _async_step_pair_show_form(self, errors=None):
|
||||
return self.async_show_form(
|
||||
step_id='pair',
|
||||
step_id="pair",
|
||||
errors=errors or {},
|
||||
data_schema=vol.Schema({
|
||||
vol.Required('pairing_code'): vol.All(str, vol.Strip),
|
||||
})
|
||||
data_schema=vol.Schema(
|
||||
{vol.Required("pairing_code"): vol.All(str, vol.Strip)}
|
||||
),
|
||||
)
|
||||
|
||||
async def _entry_from_accessory(self, pairing):
|
||||
@@ -330,7 +321,7 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
# available. Otherwise request a fresh copy from the API.
|
||||
# This removes the 'accessories' key from pairing_data at
|
||||
# the same time.
|
||||
accessories = pairing_data.pop('accessories', None)
|
||||
accessories = pairing_data.pop("accessories", None)
|
||||
if not accessories:
|
||||
accessories = await self.hass.async_add_executor_job(
|
||||
pairing.list_accessories_and_characteristics
|
||||
@@ -339,7 +330,4 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow):
|
||||
bridge_info = get_bridge_information(accessories)
|
||||
name = get_accessory_name(bridge_info)
|
||||
|
||||
return self.async_create_entry(
|
||||
title=name,
|
||||
data=pairing_data,
|
||||
)
|
||||
return self.async_create_entry(title=name, data=pairing_data)
|
||||
Reference in new issue
Block a user