Improve stability of homekit accessory ids (#35691)

This commit is contained in:
J. Nick Koston authored and GitHub committed 2020-05-26 22:15:00 -07:00
1 parent cfaa851b5b
commit 879e2d1afd
3 files changed
+442 -460

No files matched your search

+7 -21
View File
@@ -11,7 +11,6 @@ This module generates and stores them in a HA storage.
"""
import logging
import random
from zlib import adler32
from fnvhash import fnv1a_32
@@ -44,11 +43,6 @@ def get_system_unique_id(entity: RegistryEntry):
def _generate_aids(unique_id: str, entity_id: str) -> int:
"""Generate accessory aid."""
# Backward compatibility: Previously HA used to *only* do adler32 on the entity id.
# Not stable if entity ID changes
# Not robust against collisions
yield adler32(entity_id.encode("utf-8"))
if unique_id:
# Use fnv1a_32 of the unique id as
# fnv1a_32 has less collisions than
@@ -96,15 +90,7 @@ class AccessoryAidStorage:
# There is no data about aid allocations yet
return
# Remove the UNIQUE_IDS_KEY in 0.112 and later
# The beta version used UNIQUE_IDS_KEY but
# since we now have entity ids in the dict
# we use ALLOCATIONS_KEY but check for
# UNIQUE_IDS_KEY in case the database has not
# been upgraded yet
self.allocations = raw_storage.get(
ALLOCATIONS_KEY, raw_storage.get(UNIQUE_IDS_KEY, {})
)
self.allocations = raw_storage.get(ALLOCATIONS_KEY, {})
self.allocated_aids = set(self.allocations.values())
def get_or_allocate_aid_for_entity_id(self, entity_id: str):
@@ -118,17 +104,17 @@ class AccessoryAidStorage:
def _get_or_allocate_aid(self, unique_id: str, entity_id: str):
"""Allocate (and return) a new aid for an accessory."""
# Prefer the unique_id over the
# entitiy_id
storage_key = unique_id or entity_id
if storage_key in self.allocations:
return self.allocations[storage_key]
if unique_id and unique_id in self.allocations:
return self.allocations[unique_id]
if entity_id in self.allocations:
return self.allocations[entity_id]
for aid in _generate_aids(unique_id, entity_id):
if aid in INVALID_AIDS:
continue
if aid not in self.allocated_aids:
# Prefer the unique_id over the entitiy_id
storage_key = unique_id or entity_id
self.allocations[storage_key] = aid
self.allocated_aids.add(aid)
self.async_schedule_save()