or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration-security.mdcore-client.mderror-handling.mdindex.mdmessage-handling.mdtopic-management.md

configuration-security.mddocs/

0

# Configuration & Security

1

2

TLS/SSL configuration, authentication, protocol versions, proxy settings, and connection parameters for secure and customized MQTT connections.

3

4

## Capabilities

5

6

### Protocol Version Selection

7

8

Choose the MQTT protocol version for compatibility with different brokers and feature requirements.

9

10

```python { .api }

11

class ProtocolVersion(Enum):

12

V31 = mqtt.MQTTv31

13

V311 = mqtt.MQTTv311

14

V5 = mqtt.MQTTv5

15

```

16

17

**Protocol version differences:**

18

- **V31 (MQTT 3.1)**: Original protocol, basic features

19

- **V311 (MQTT 3.1.1)**: Improved error handling, widely supported

20

- **V5 (MQTT 5.0)**: Latest version with enhanced features, properties, reason codes

21

22

**Usage examples:**

23

24

```python

25

import asyncio

26

from aiomqtt import Client, ProtocolVersion

27

28

async def protocol_version_examples():

29

# Use MQTT v5.0 for latest features

30

async with Client(

31

"test.mosquitto.org",

32

protocol=ProtocolVersion.V5

33

) as client:

34

await client.publish("test/v5", "Using MQTT 5.0")

35

36

# Use MQTT v3.1.1 for compatibility

37

async with Client(

38

"broker.example.com",

39

protocol=ProtocolVersion.V311

40

) as client:

41

await client.publish("test/v311", "Using MQTT 3.1.1")

42

43

# Default protocol (let client decide)

44

async with Client("test.mosquitto.org") as client:

45

await client.publish("test/default", "Using default protocol")

46

47

asyncio.run(protocol_version_examples())

48

```

49

50

### TLS/SSL Configuration

51

52

Secure MQTT connections using TLS/SSL with certificate-based authentication and custom SSL contexts.

53

54

```python { .api }

55

@dataclass

56

class TLSParameters:

57

ca_certs: str | None = None

58

certfile: str | None = None

59

keyfile: str | None = None

60

cert_reqs: ssl.VerifyMode | None = None

61

tls_version: Any | None = None

62

ciphers: str | None = None

63

keyfile_password: str | None = None

64

```

65

66

**TLS Configuration Parameters:**

67

- **ca_certs**: Path to Certificate Authority certificates file

68

- **certfile**: Path to client certificate file

69

- **keyfile**: Path to client private key file

70

- **cert_reqs**: Certificate verification requirements

71

- **tls_version**: Specific TLS version to use

72

- **ciphers**: Allowed cipher suites

73

- **keyfile_password**: Password for encrypted private key

74

75

**Usage examples:**

76

77

```python

78

import asyncio

79

import ssl

80

from aiomqtt import Client, TLSParameters

81

82

async def tls_configuration_examples():

83

# Basic TLS with CA certificate verification

84

tls_params = TLSParameters(

85

ca_certs="/path/to/ca-certificates.crt"

86

)

87

88

async with Client(

89

"secure-broker.example.com",

90

port=8883, # Standard MQTT TLS port

91

tls_params=tls_params

92

) as client:

93

await client.publish("secure/test", "TLS enabled")

94

95

# Mutual TLS authentication with client certificates

96

mutual_tls_params = TLSParameters(

97

ca_certs="/path/to/ca-cert.pem",

98

certfile="/path/to/client-cert.pem",

99

keyfile="/path/to/client-key.pem",

100

keyfile_password="key_password"

101

)

102

103

async with Client(

104

"mtls-broker.example.com",

105

port=8883,

106

tls_params=mutual_tls_params

107

) as client:

108

await client.publish("mtls/test", "Mutual TLS authenticated")

109

110

# Custom SSL context for advanced configuration

111

ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)

112

ssl_context.check_hostname = False

113

ssl_context.verify_mode = ssl.CERT_NONE

114

115

async with Client(

116

"test-broker.example.com",

117

port=8883,

118

tls_context=ssl_context

119

) as client:

120

await client.publish("custom-ssl/test", "Custom SSL context")

121

122

# Disable hostname verification (not recommended for production)

123

async with Client(

124

"test-broker.example.com",

125

port=8883,

126

tls_params=TLSParameters(ca_certs="/path/to/ca.crt"),

127

tls_insecure=True

128

) as client:

129

await client.publish("insecure/test", "Hostname verification disabled")

130

131

asyncio.run(tls_configuration_examples())

132

```

133

134

### Authentication Configuration

135

136

Configure username/password authentication and client identification.

137

138

**Client authentication parameters:**

139

```python

140

# In Client.__init__():

141

username: str | None = None # Authentication username

142

password: str | None = None # Authentication password

143

identifier: str | None = None # Client ID (auto-generated if None)

144

```

145

146

**Usage examples:**

147

148

```python

149

import asyncio

150

from aiomqtt import Client

151

152

async def authentication_examples():

153

# Username/password authentication

154

async with Client(

155

"broker.example.com",

156

username="mqtt_user",

157

password="secure_password"

158

) as client:

159

await client.publish("auth/test", "Authenticated connection")

160

161

# Custom client identifier

162

async with Client(

163

"broker.example.com",

164

identifier="my-custom-client-id"

165

) as client:

166

print(f"Connected with ID: {client.identifier}")

167

await client.publish("id/test", "Custom client ID")

168

169

# Auto-generated client ID (default behavior)

170

async with Client("broker.example.com") as client:

171

print(f"Auto-generated ID: {client.identifier}")

172

await client.publish("auto-id/test", "Auto-generated client ID")

173

174

asyncio.run(authentication_examples())

175

```

176

177

### Proxy Configuration

178

179

Connect through SOCKS or HTTP proxies for network environments requiring proxy access.

180

181

```python { .api }

182

class ProxySettings:

183

def __init__(

184

self,

185

*,

186

proxy_type: int,

187

proxy_addr: str,

188

proxy_rdns: bool | None = True,

189

proxy_username: str | None = None,

190

proxy_password: str | None = None,

191

proxy_port: int | None = None,

192

):

193

"""

194

Configure proxy settings for MQTT connection.

195

196

Args:

197

proxy_type (int): Proxy type (SOCKS4, SOCKS5, HTTP)

198

proxy_addr (str): Proxy server address

199

proxy_rdns (bool, optional): Use remote DNS resolution

200

proxy_username (str, optional): Proxy authentication username

201

proxy_password (str, optional): Proxy authentication password

202

proxy_port (int, optional): Proxy server port

203

"""

204

```

205

206

**Usage example:**

207

208

```python

209

import asyncio

210

import socks

211

from aiomqtt import Client, ProxySettings

212

213

async def proxy_configuration():

214

# SOCKS5 proxy configuration

215

proxy_settings = ProxySettings(

216

proxy_type=socks.SOCKS5,

217

proxy_addr="proxy.example.com",

218

proxy_port=1080,

219

proxy_username="proxy_user",

220

proxy_password="proxy_pass"

221

)

222

223

async with Client(

224

"broker.example.com",

225

proxy=proxy_settings

226

) as client:

227

await client.publish("proxy/test", "Connected through SOCKS5 proxy")

228

229

# Note: Requires python-socks package

230

# pip install python-socks

231

asyncio.run(proxy_configuration())

232

```

233

234

### Last Will and Testament

235

236

Configure last will messages to be published automatically when the client disconnects unexpectedly.

237

238

```python { .api }

239

@dataclass

240

class Will:

241

topic: str

242

payload: str | bytes | bytearray | int | float | None = None

243

qos: int = 0

244

retain: bool = False

245

properties: Properties | None = None

246

```

247

248

**Usage examples:**

249

250

```python

251

import asyncio

252

from aiomqtt import Client, Will

253

254

async def will_message_examples():

255

# Basic will message

256

will = Will(

257

topic="status/device123",

258

payload="offline",

259

qos=1,

260

retain=True

261

)

262

263

async with Client(

264

"broker.example.com",

265

will=will

266

) as client:

267

# Publish online status

268

await client.publish("status/device123", "online", qos=1, retain=True)

269

270

# Do work - if client disconnects unexpectedly,

271

# broker will publish the will message

272

await client.publish("data/sensor", "42.5")

273

274

# JSON will message with device information

275

import json

276

device_info = {

277

"device_id": "sensor123",

278

"status": "offline",

279

"timestamp": "2023-01-01T00:00:00Z",

280

"reason": "unexpected_disconnect"

281

}

282

283

will_with_json = Will(

284

topic="devices/sensor123/status",

285

payload=json.dumps(device_info),

286

qos=2,

287

retain=True

288

)

289

290

async with Client(

291

"broker.example.com",

292

will=will_with_json

293

) as client:

294

await client.publish("devices/sensor123/data", "25.4")

295

296

asyncio.run(will_message_examples())

297

```

298

299

### Connection Parameters

300

301

Configure connection behavior, timeouts, and session management.

302

303

**Key connection parameters:**

304

```python

305

# In Client.__init__():

306

keepalive: int = 60 # Keep-alive interval in seconds

307

timeout: float | None = None # Default operation timeout

308

clean_session: bool | None = None # Clean session flag (MQTT v3.1.1)

309

clean_start: mqtt.CleanStartOption # Clean start option (MQTT v5.0)

310

bind_address: str = "" # Local interface to bind

311

bind_port: int = 0 # Local port to bind

312

```

313

314

**Usage examples:**

315

316

```python

317

import asyncio

318

from aiomqtt import Client

319

import paho.mqtt.client as mqtt

320

321

async def connection_parameter_examples():

322

# Custom keepalive and timeout

323

async with Client(

324

"broker.example.com",

325

keepalive=30, # Send keepalive every 30 seconds

326

timeout=10.0 # 10 second default timeout

327

) as client:

328

await client.publish("config/test", "Custom keepalive/timeout")

329

330

# Clean session configuration (MQTT v3.1.1)

331

async with Client(

332

"broker.example.com",

333

clean_session=False # Persistent session

334

) as client:

335

await client.subscribe("persistent/data", qos=1)

336

# Session will be preserved after disconnect

337

338

# Clean start configuration (MQTT v5.0)

339

async with Client(

340

"broker.example.com",

341

clean_start=mqtt.MQTT_CLEAN_START_FIRST_ONLY

342

) as client:

343

await client.publish("v5/test", "Clean start configuration")

344

345

# Bind to specific local interface

346

async with Client(

347

"broker.example.com",

348

bind_address="192.168.1.100", # Bind to specific interface

349

bind_port=0 # Let system choose port

350

) as client:

351

await client.publish("bind/test", "Bound to specific interface")

352

353

asyncio.run(connection_parameter_examples())

354

```

355

356

### WebSocket Configuration

357

358

Configure WebSocket transport for browser compatibility or firewall traversal.

359

360

**WebSocket parameters:**

361

```python

362

# In Client.__init__():

363

transport: Literal["tcp", "websockets", "unix"] = "tcp"

364

websocket_path: str | None = None # WebSocket path

365

websocket_headers: WebSocketHeaders | None = None # Custom headers

366

```

367

368

**Usage examples:**

369

370

```python

371

import asyncio

372

from aiomqtt import Client

373

374

async def websocket_configuration():

375

# Basic WebSocket connection

376

async with Client(

377

"broker.example.com",

378

port=9001, # WebSocket port

379

transport="websockets"

380

) as client:

381

await client.publish("websocket/test", "WebSocket transport")

382

383

# WebSocket with custom path and headers

384

custom_headers = {

385

"Authorization": "Bearer token123",

386

"X-Client-Type": "aiomqtt"

387

}

388

389

async with Client(

390

"broker.example.com",

391

port=9001,

392

transport="websockets",

393

websocket_path="/mqtt/websocket",

394

websocket_headers=custom_headers

395

) as client:

396

await client.publish("websocket/custom", "Custom WebSocket config")

397

398

asyncio.run(websocket_configuration())

399

```

400

401

### Advanced Configuration

402

403

Configure message queue limits, concurrency, and socket options for performance tuning.

404

405

**Advanced parameters:**

406

```python

407

# In Client.__init__():

408

max_queued_incoming_messages: int | None = None # Incoming queue limit

409

max_queued_outgoing_messages: int | None = None # Outgoing queue limit

410

max_inflight_messages: int | None = None # Max inflight messages

411

max_concurrent_outgoing_calls: int | None = None # Concurrency limit

412

socket_options: Iterable[SocketOption] | None = None # Socket options

413

```

414

415

**Usage example:**

416

417

```python

418

import asyncio

419

import socket

420

from aiomqtt import Client

421

422

async def advanced_configuration():

423

# Configure message queue limits and concurrency

424

async with Client(

425

"broker.example.com",

426

max_queued_incoming_messages=1000, # Limit incoming queue

427

max_queued_outgoing_messages=500, # Limit outgoing queue

428

max_inflight_messages=20, # Max unacknowledged messages

429

max_concurrent_outgoing_calls=10 # Max concurrent operations

430

) as client:

431

await client.publish("advanced/test", "Advanced configuration")

432

433

# Custom socket options

434

socket_opts = [

435

(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), # Enable keepalive

436

(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Disable Nagle algorithm

437

]

438

439

async with Client(

440

"broker.example.com",

441

socket_options=socket_opts

442

) as client:

443

await client.publish("socket/test", "Custom socket options")

444

445

asyncio.run(advanced_configuration())

446

```

447

448

## Type Definitions

449

450

```python { .api }

451

WebSocketHeaders = dict[str, str] | Callable[[dict[str, str]], dict[str, str]]

452

453

SocketOption = tuple[int, int, int | bytes] | tuple[int, int, None, int]

454

```