-
-
Notifications
You must be signed in to change notification settings - Fork 31.5k
/
storage.py
68 lines (55 loc) · 2.28 KB
/
storage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Storage for remote scanners."""
from __future__ import annotations
from bluetooth_adapters import (
DiscoveredDeviceAdvertisementData,
DiscoveredDeviceAdvertisementDataDict,
DiscoveryStorageType,
discovered_device_advertisement_data_from_dict,
discovered_device_advertisement_data_to_dict,
expire_stale_scanner_discovered_device_advertisement_data,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.storage import Store
REMOTE_SCANNER_STORAGE_VERSION = 1
REMOTE_SCANNER_STORAGE_KEY = "bluetooth.remote_scanners"
SCANNER_SAVE_DELAY = 5
class BluetoothStorage:
"""Storage for remote scanners."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the storage."""
self._store: Store[DiscoveryStorageType] = Store(
hass, REMOTE_SCANNER_STORAGE_VERSION, REMOTE_SCANNER_STORAGE_KEY
)
self._data: DiscoveryStorageType = {}
async def async_setup(self) -> None:
"""Set up the storage."""
self._data = await self._store.async_load() or {}
expire_stale_scanner_discovered_device_advertisement_data(self._data)
def scanners(self) -> list[str]:
"""Get all scanners."""
return list(self._data.keys())
@callback
def async_get_advertisement_history(
self, scanner: str
) -> DiscoveredDeviceAdvertisementData | None:
"""Get discovered devices by scanner."""
if not (scanner_data := self._data.get(scanner)):
return None
return discovered_device_advertisement_data_from_dict(scanner_data)
@callback
def async_get_advertisement_history_as_dict(
self, scanner: str
) -> DiscoveredDeviceAdvertisementDataDict | None:
"""Get discovered devices by scanner as a dict."""
return self._data.get(scanner)
@callback
def _async_get_data(self) -> DiscoveryStorageType:
"""Get data to save to disk."""
return self._data
@callback
def async_set_advertisement_history(
self, scanner: str, data: DiscoveredDeviceAdvertisementData
) -> None:
"""Set discovered devices by scanner."""
self._data[scanner] = discovered_device_advertisement_data_to_dict(data)
self._store.async_delay_save(self._async_get_data, SCANNER_SAVE_DELAY)