0
# aiomqtt
1
2
The idiomatic asyncio MQTT client library that eliminates callback-based programming in favor of modern Python async/await patterns. It provides a clean, Pythonic API for MQTT communication with support for MQTT versions 5.0, 3.1.1, and 3.1, featuring comprehensive type hints, graceful connection management, and seamless integration with asyncio event loops.
3
4
## Package Information
5
6
- **Package Name**: aiomqtt
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install aiomqtt`
10
11
## Core Imports
12
13
```python
14
import aiomqtt
15
```
16
17
Common usage patterns:
18
19
```python
20
from aiomqtt import Client, Message, Topic, Wildcard
21
```
22
23
All public components:
24
25
```python
26
from aiomqtt import (
27
Client,
28
Message,
29
MessagesIterator,
30
MqttCodeError,
31
MqttError,
32
MqttReentrantError,
33
ProtocolVersion,
34
ProxySettings,
35
TLSParameters,
36
Topic,
37
TopicLike,
38
Wildcard,
39
WildcardLike,
40
Will,
41
)
42
```
43
44
## Basic Usage
45
46
```python
47
import asyncio
48
from aiomqtt import Client
49
50
async def publish_example():
51
async with Client("test.mosquitto.org") as client:
52
await client.publish("temperature/outside", payload=28.4)
53
54
async def subscribe_example():
55
async with Client("test.mosquitto.org") as client:
56
await client.subscribe("temperature/#")
57
async for message in client.messages:
58
print(f"Received: {message.payload} on {message.topic}")
59
60
# Run examples
61
asyncio.run(publish_example())
62
asyncio.run(subscribe_example())
63
```
64
65
## Architecture
66
67
aiomqtt is built on the proven paho-mqtt foundation while providing an asyncio-native interface. Key architectural components:
68
69
- **Client**: Async context manager handling broker connections and operations
70
- **MessagesIterator**: Dynamic view of the client's message queue for async iteration
71
- **Message**: Immutable message wrapper with topic matching capabilities
72
- **Topic/Wildcard**: Validation and matching logic for MQTT topic patterns
73
- **Error Hierarchy**: Structured exception handling replacing callback-based error reporting
74
75
The library eliminates callbacks entirely, using async/await patterns and structured exceptions for clean, maintainable MQTT client code.
76
77
## Capabilities
78
79
### Core Client Operations
80
81
Essential MQTT client functionality including connection management, publishing, and subscribing. The Client class serves as the main entry point for all MQTT operations.
82
83
```python { .api }
84
class Client:
85
def __init__(
86
self,
87
hostname: str,
88
port: int = 1883,
89
*,
90
username: str | None = None,
91
password: str | None = None,
92
logger: logging.Logger | None = None,
93
identifier: str | None = None,
94
queue_type: type[asyncio.Queue[Message]] | None = None,
95
protocol: ProtocolVersion | None = None,
96
will: Will | None = None,
97
clean_session: bool | None = None,
98
transport: Literal["tcp", "websockets", "unix"] = "tcp",
99
timeout: float | None = None,
100
keepalive: int = 60,
101
bind_address: str = "",
102
bind_port: int = 0,
103
clean_start: mqtt.CleanStartOption = mqtt.MQTT_CLEAN_START_FIRST_ONLY,
104
max_queued_incoming_messages: int | None = None,
105
max_queued_outgoing_messages: int | None = None,
106
max_inflight_messages: int | None = None,
107
max_concurrent_outgoing_calls: int | None = None,
108
properties: Properties | None = None,
109
tls_context: ssl.SSLContext | None = None,
110
tls_params: TLSParameters | None = None,
111
tls_insecure: bool | None = None,
112
proxy: ProxySettings | None = None,
113
socket_options: Iterable[SocketOption] | None = None,
114
websocket_path: str | None = None,
115
websocket_headers: WebSocketHeaders | None = None,
116
): ...
117
118
async def __aenter__(self) -> Self: ...
119
async def __aexit__(self, exc_type, exc, tb) -> None: ...
120
async def publish(
121
self,
122
/,
123
topic: str,
124
payload: PayloadType = None,
125
qos: int = 0,
126
retain: bool = False,
127
properties: Properties | None = None,
128
*args: Any,
129
timeout: float | None = None,
130
**kwargs: Any,
131
) -> None: ...
132
async def subscribe(
133
self,
134
/,
135
topic: SubscribeTopic,
136
qos: int = 0,
137
options: SubscribeOptions | None = None,
138
properties: Properties | None = None,
139
*args: Any,
140
timeout: float | None = None,
141
**kwargs: Any,
142
) -> tuple[int, ...] | list[ReasonCode]: ...
143
```
144
145
[Core Client Operations](./core-client.md)
146
147
### Message Handling
148
149
Message structure and processing capabilities for received MQTT messages, including topic matching and payload access.
150
151
```python { .api }
152
class Message:
153
topic: Topic
154
payload: PayloadType
155
qos: int
156
retain: bool
157
mid: int
158
properties: Properties | None
159
160
class MessagesIterator:
161
def __aiter__(self) -> AsyncIterator[Message]: ...
162
def __anext__(self) -> Message: ...
163
def __len__(self) -> int: ...
164
```
165
166
[Message Handling](./message-handling.md)
167
168
### Topic Management
169
170
Topic validation, wildcard support, and matching logic for MQTT topic patterns.
171
172
```python { .api }
173
@dataclass
174
class Topic:
175
value: str
176
def matches(self, wildcard: WildcardLike) -> bool: ...
177
178
@dataclass
179
class Wildcard:
180
value: str
181
182
TopicLike = str | Topic
183
WildcardLike = str | Wildcard
184
185
PayloadType = str | bytes | bytearray | int | float | None
186
SubscribeTopic = str | tuple[str, SubscribeOptions] | list[tuple[str, SubscribeOptions]] | list[tuple[str, int]]
187
WebSocketHeaders = dict[str, str] | Callable[[dict[str, str]], dict[str, str]]
188
SocketOption = tuple[int, int, int | bytes] | tuple[int, int, None, int]
189
```
190
191
[Topic Management](./topic-management.md)
192
193
### Configuration & Security
194
195
TLS/SSL configuration, authentication, protocol versions, proxy settings, and connection parameters.
196
197
```python { .api }
198
# From paho.mqtt.client and paho.mqtt.properties
199
class Properties:
200
# MQTT v5.0 properties (from paho-mqtt)
201
pass
202
203
class ReasonCode:
204
# MQTT v5.0 reason codes (from paho-mqtt)
205
value: int
206
207
class SubscribeOptions:
208
# MQTT v5.0 subscription options (from paho-mqtt)
209
pass
210
211
# Module types and classes
212
class ProtocolVersion(Enum):
213
V31 = mqtt.MQTTv31
214
V311 = mqtt.MQTTv311
215
V5 = mqtt.MQTTv5
216
217
@dataclass
218
class TLSParameters:
219
ca_certs: str | None = None
220
certfile: str | None = None
221
keyfile: str | None = None
222
cert_reqs: ssl.VerifyMode | None = None
223
tls_version: Any | None = None
224
ciphers: str | None = None
225
keyfile_password: str | None = None
226
227
@dataclass
228
class ProxySettings:
229
def __init__(
230
self,
231
*,
232
proxy_type: int,
233
proxy_addr: str,
234
proxy_rdns: bool | None = True,
235
proxy_username: str | None = None,
236
proxy_password: str | None = None,
237
proxy_port: int | None = None,
238
) -> None: ...
239
240
@dataclass
241
class Will:
242
topic: str
243
payload: PayloadType | None = None
244
qos: int = 0
245
retain: bool = False
246
properties: Properties | None = None
247
```
248
249
[Configuration & Security](./configuration-security.md)
250
251
### Error Handling
252
253
Structured exception hierarchy for MQTT errors, replacing callback-based error reporting with modern exception handling.
254
255
```python { .api }
256
class MqttError(Exception): ...
257
258
class MqttCodeError(MqttError):
259
rc: int | ReasonCode | None
260
261
262
class MqttReentrantError(MqttError): ...
263
```
264
265
[Error Handling](./error-handling.md)
266
267
## Version Information
268
269
```python { .api }
270
__version__: str
271
__version_tuple__: tuple[int, int, int]
272
```