|
5 | 5 |
|
6 | 6 | from homeassistant_api.models import ( |
7 | 7 | ConfigEntry, |
| 8 | + ConfigEntryEvent, |
8 | 9 | ConfigSubEntry, |
9 | 10 | DisableEnableResult, |
10 | 11 | Domain, |
@@ -287,7 +288,38 @@ def get_config_entries( |
287 | 288 | ) |
288 | 289 | ) |
289 | 290 |
|
290 | | - # TODO: config_entries/subscribe |
| 291 | + def _subscribe_config_entries(self) -> int: |
| 292 | + """ |
| 293 | + Subscribe to config entry flows. |
| 294 | +
|
| 295 | + Sends command :code:`{"type": "config_entries/subscribe"}`. |
| 296 | + """ |
| 297 | + |
| 298 | + return self.recv(self.send("config_entries/subscribe")).id |
| 299 | + |
| 300 | + @contextlib.contextmanager |
| 301 | + def listen_config_entries( |
| 302 | + self, disconnect_client: bool = True |
| 303 | + ) -> Generator[Generator[ConfigEntryEvent, None, None], None, None]: |
| 304 | + """ |
| 305 | + Listen to all config entry flow events. |
| 306 | +
|
| 307 | + For example: |
| 308 | +
|
| 309 | + .. code-block:: python |
| 310 | +
|
| 311 | + with ws_client.listen_config_entries() as flows: |
| 312 | + for i, flow in zip(range(2), flows): # to only wait for two flows to be received |
| 313 | + print(flow) |
| 314 | + """ |
| 315 | + subscription = self._subscribe_config_entries() |
| 316 | + cast(Generator[ConfigEntryEvent, None, None], self._wait_for(subscription)) |
| 317 | + # There is no "unsubscribe" method available for these events. |
| 318 | + # Provide the ability to "unsubscribe" by disconnecting and reconnecting the Websocket client. |
| 319 | + if disconnect_client: |
| 320 | + logger.info("Reloading Websocket Client. Undefined behavior may occur.") |
| 321 | + self.__exit__(None, None, None) |
| 322 | + self.__enter__() |
291 | 323 |
|
292 | 324 | # UNTESTED |
293 | 325 | def get_entry_subentries(self, entry_id: str) -> Tuple[ConfigSubEntry, ...]: |
@@ -468,14 +500,14 @@ def _subscribe_trigger(self, trigger: str, **trigger_fields) -> int: |
468 | 500 |
|
469 | 501 | def _wait_for( |
470 | 502 | self, subscription_id: int |
471 | | - ) -> Generator[Union[FiredEvent, FiredTrigger], None, None]: |
| 503 | + ) -> Generator[Union[FiredEvent, FiredTrigger, ConfigEntryEvent], None, None]: |
472 | 504 | """ |
473 | 505 | An iterator that waits for events of a certain type. |
474 | 506 | """ |
475 | 507 | while True: |
476 | 508 | yield cast( |
477 | 509 | Union[ |
478 | | - FiredEvent, FiredTrigger |
| 510 | + FiredEvent, FiredTrigger, ConfigEntryEvent |
479 | 511 | ], # we can cast this because TemplateEvent is only used for rendering templates |
480 | 512 | cast(EventResponse, self.recv(subscription_id)).event, |
481 | 513 | ) |
|
0 commit comments