|
1 | 1 | """Hold configuration variables for the emulated hue bridge.""" |
| 2 | +import asyncio |
2 | 3 | import datetime |
3 | 4 | import hashlib |
4 | 5 | import logging |
|
7 | 8 |
|
8 | 9 | from getmac import get_mac_address |
9 | 10 |
|
| 11 | +from .const import CONFIG_WRITE_INTERVAL_SECONDS |
10 | 12 | from .utils import async_save_json, create_secure_string, get_local_ip, load_json |
11 | 13 |
|
12 | 14 | if TYPE_CHECKING: |
@@ -76,6 +78,29 @@ def __init__( |
76 | 78 | self._bridge_serial = mac_str.lower() |
77 | 79 | self._bridge_uid = f"2f402f80-da50-11e1-9b23-{mac_str}" |
78 | 80 |
|
| 81 | + # Flag to initiate shutdown of background saving |
| 82 | + self._interrupted = False |
| 83 | + self._need_save = False |
| 84 | + self._saver_task = None # type: asyncio.Task | None |
| 85 | + |
| 86 | + async def _background_saver(self) -> None: |
| 87 | + last_save = 0 |
| 88 | + while not self._interrupted: |
| 89 | + now = datetime.datetime.now().timestamp() |
| 90 | + if self._need_save and now - last_save > CONFIG_WRITE_INTERVAL_SECONDS: |
| 91 | + await async_save_json(self.get_path(CONFIG_FILE), self._config) |
| 92 | + last_save = now |
| 93 | + await asyncio.sleep(1) |
| 94 | + |
| 95 | + async def async_start(self, loop: asyncio.AbstractEventLoop) -> None: |
| 96 | + """Start background saving task.""" |
| 97 | + self._saver_task = loop.create_task(self._background_saver()) |
| 98 | + |
| 99 | + async def async_stop(self) -> None: |
| 100 | + """Save the config.""" |
| 101 | + self._interrupted = True |
| 102 | + await self._saver_task |
| 103 | + |
79 | 104 | @property |
80 | 105 | def ip_addr(self) -> str: |
81 | 106 | """Return ip address of the emulated bridge.""" |
@@ -252,7 +277,7 @@ async def async_set_storage_value( |
252 | 277 | needs_save = True |
253 | 278 | # save config to file if changed |
254 | 279 | if needs_save: |
255 | | - await async_save_json(self.get_path(CONFIG_FILE), self._config) |
| 280 | + self._need_save = True |
256 | 281 |
|
257 | 282 | async def async_delete_storage_value(self, key: str, subkey: str = None) -> None: |
258 | 283 | """Delete a value in persistent storage.""" |
|
0 commit comments