Home Assistant Unofficial Reference 2024.12.1
async_client.py
Go to the documentation of this file.
1 """Async wrappings for mqtt client."""
2 
3 from __future__ import annotations
4 
5 from functools import lru_cache
6 from types import TracebackType
7 from typing import Self
8 
9 from paho.mqtt.client import Client as MQTTClient
10 
11 _MQTT_LOCK_COUNT = 7
12 
13 
14 class NullLock:
15  """Null lock."""
16 
17  @lru_cache(maxsize=_MQTT_LOCK_COUNT)
18  def __enter__(self) -> Self:
19  """Enter the lock."""
20  return self
21 
22  @lru_cache(maxsize=_MQTT_LOCK_COUNT)
23  def __exit__(
24  self,
25  exc_type: type[BaseException] | None,
26  exc_value: BaseException | None,
27  traceback: TracebackType | None,
28  ) -> None:
29  """Exit the lock."""
30 
31  @lru_cache(maxsize=_MQTT_LOCK_COUNT)
32  def acquire(self, blocking: bool = False, timeout: int = -1) -> None:
33  """Acquire the lock."""
34 
35  @lru_cache(maxsize=_MQTT_LOCK_COUNT)
36  def release(self) -> None:
37  """Release the lock."""
38 
39 
40 class AsyncMQTTClient(MQTTClient):
41  """Async MQTT Client.
42 
43  Wrapper around paho.mqtt.client.Client to remove the locking
44  that is not needed since we are running in an async event loop.
45  """
46 
47  def setup(self) -> None:
48  """Set up the client.
49 
50  All the threading locks are replaced with NullLock
51  since the client is running in an async event loop
52  and will never run in multiple threads.
53  """
54  self._in_callback_mutex_in_callback_mutex = NullLock()
55  self._callback_mutex_callback_mutex = NullLock()
56  self._msgtime_mutex_msgtime_mutex = NullLock()
57  self._out_message_mutex_out_message_mutex = NullLock()
58  self._in_message_mutex_in_message_mutex = NullLock()
59  self._reconnect_delay_mutex_reconnect_delay_mutex = NullLock()
60  self._mid_generate_mutex_mid_generate_mutex = NullLock()
None __exit__(self, type[BaseException]|None exc_type, BaseException|None exc_value, TracebackType|None traceback)
Definition: async_client.py:28
None acquire(self, bool blocking=False, int timeout=-1)
Definition: async_client.py:32