|
2 | 2 | from django.conf import settings |
3 | 3 |
|
4 | 4 |
|
5 | | -def on_connect(mqtt_client, userdata, flags, rc): |
6 | | - if rc == 0: |
7 | | - print('Connected successfully') |
8 | | - mqtt_client.subscribe('django/mqtt') |
| 5 | +def on_connect(mqtt_client, userdata, flags, reason_code, properties): |
| 6 | + if reason_code == 0: |
| 7 | + print("Connected successfully") |
| 8 | + mqtt_client.subscribe("django/mqtt") |
9 | 9 | else: |
10 | | - print('Bad connection. Code:', rc) |
| 10 | + print("Bad connection. Code:", reason_code) |
11 | 11 |
|
12 | 12 |
|
13 | 13 | def on_message(mqtt_client, userdata, msg): |
14 | | - print(f'Received message on topic: {msg.topic} with payload: {msg.payload}') |
| 14 | + print(f"Received message on topic: {msg.topic} with payload: {msg.payload}") |
15 | 15 |
|
16 | 16 |
|
17 | | -client = mqtt.Client() |
18 | | -client.on_connect = on_connect |
19 | | -client.on_message = on_message |
20 | | -client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD) |
21 | | -client.connect( |
22 | | - host=settings.MQTT_SERVER, |
23 | | - port=settings.MQTT_PORT, |
24 | | - keepalive=settings.MQTT_KEEPALIVE |
25 | | -) |
| 17 | +def create_mqtt_client(): |
| 18 | + """Create and return an MQTT client configured for connection""" |
| 19 | + client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2) |
| 20 | + client.on_connect = on_connect |
| 21 | + client.on_message = on_message |
| 22 | + |
| 23 | + # Only set credentials if they are provided |
| 24 | + if settings.MQTT_USER and settings.MQTT_PASSWORD: |
| 25 | + client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD) |
| 26 | + |
| 27 | + client.connect( |
| 28 | + host=settings.MQTT_SERVER, |
| 29 | + port=settings.MQTT_PORT, |
| 30 | + keepalive=settings.MQTT_KEEPALIVE |
| 31 | + ) |
| 32 | + |
| 33 | + return client |
| 34 | + |
0 commit comments