Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store devices as dict instead of list #16229

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 8 additions & 6 deletions homeassistant/helpers/device_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import logging
import uuid

from collections import OrderedDict

import attr

from homeassistant.core import callback
Expand Down Expand Up @@ -45,7 +47,7 @@ def __init__(self, hass):
@callback
def async_get_device(self, identifiers: str, connections: tuple):
"""Check if device is registered."""
for device in self.devices:
for device in self.devices.values():
if any(iden in device.identifiers for iden in identifiers) or \
any(conn in device.connections for conn in connections):
return device
Expand Down Expand Up @@ -75,7 +77,7 @@ def async_get_or_create(self, *, config_entry, connections, identifiers,
name=name,
sw_version=sw_version
)
self.devices.append(device)
self.devices[device.id] = device

self.async_schedule_save()

Expand All @@ -86,10 +88,10 @@ async def async_load(self):
devices = await self._store.async_load()

if devices is None:
self.devices = []
self.devices = OrderedDict()
return

self.devices = [DeviceEntry(
self.devices = {device['id']: DeviceEntry(
config_entries=device['config_entries'],
connections={tuple(conn) for conn in device['connections']},
identifiers={tuple(iden) for iden in device['identifiers']},
Expand All @@ -98,7 +100,7 @@ async def async_load(self):
name=device['name'],
sw_version=device['sw_version'],
id=device['id'],
) for device in devices['devices']]
) for device in devices['devices']}

@callback
def async_schedule_save(self):
Expand All @@ -120,7 +122,7 @@ def _data_to_save(self):
'name': entry.name,
'sw_version': entry.sw_version,
'id': entry.id,
} for entry in self.devices
} for entry in self.devices.values()
]

return data
Expand Down
4 changes: 3 additions & 1 deletion tests/helpers/test_device_registry.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""Tests for the Device Registry."""
import pytest

from collections import OrderedDict

from homeassistant.helpers import device_registry


def mock_registry(hass, mock_entries=None):
"""Mock the Device Registry."""
registry = device_registry.DeviceRegistry(hass)
registry.devices = mock_entries or []
registry.devices = mock_entries or OrderedDict()

async def _get_reg():
return registry
Expand Down