2023-08-31 22:39:20 -07:00
|
|
|
---
|
|
|
|
id: mqtt-python
|
|
|
|
title: Python
|
|
|
|
sidebar_label: Python
|
|
|
|
sidebar_position: 2
|
|
|
|
---
|
|
|
|
|
|
|
|
### Sending/receiving messages on mosquitto server using python
|
|
|
|
|
2024-03-11 11:17:23 -07:00
|
|
|
Here is an example publish message in python (run `pip install paho-mqtt` first):
|
2023-08-31 22:39:20 -07:00
|
|
|
|
|
|
|
```python
|
|
|
|
#!/usr/bin/env python3
|
|
|
|
import paho.mqtt.client as mqtt
|
2024-03-11 11:17:23 -07:00
|
|
|
from random import uniform
|
2023-08-31 22:39:20 -07:00
|
|
|
import time
|
|
|
|
|
2024-03-11 11:17:23 -07:00
|
|
|
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
2023-08-31 22:39:20 -07:00
|
|
|
client.connect('localhost')
|
|
|
|
|
|
|
|
while True:
|
|
|
|
randNumber = uniform(20.0, 21.0)
|
|
|
|
client.publish("env/test/TEMPERATURE", randNumber)
|
|
|
|
print("Just published " + str(randNumber) + " to topic TEMPERATURE")
|
|
|
|
time.sleep(1)
|
|
|
|
```
|
|
|
|
|
|
|
|
Here is example subscribe in python:
|
|
|
|
|
|
|
|
```python
|
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import paho.mqtt.client as paho
|
|
|
|
|
|
|
|
def on_message(mosq, obj, msg):
|
|
|
|
print("%-20s %d %s" % (msg.topic, msg.qos, msg.payload))
|
|
|
|
mosq.publish('pong', 'ack', 0)
|
|
|
|
|
2024-03-11 11:17:23 -07:00
|
|
|
def on_publish(mosq, obj, mid, reason_codes, properties):
|
2023-08-31 22:39:20 -07:00
|
|
|
pass
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2024-03-11 11:17:23 -07:00
|
|
|
client = paho.Client(paho.CallbackAPIVersion.VERSION2)
|
2023-08-31 22:39:20 -07:00
|
|
|
client.on_message = on_message
|
|
|
|
client.on_publish = on_publish
|
|
|
|
|
|
|
|
client.connect("localhost", 1883, 60)
|
|
|
|
|
|
|
|
client.subscribe("env/test/TEMPERATURE", 0)
|
|
|
|
|
|
|
|
while client.loop() == 0:
|
|
|
|
pass
|
|
|
|
```
|