meshtastic/docs/software/integrations/mqtt/python.mdx

54 lines
1.2 KiB
Plaintext
Raw Normal View History

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
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
from random import uniform
2023-08-31 22:39:20 -07:00
import time
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)
def on_publish(mosq, obj, mid, reason_codes, properties):
2023-08-31 22:39:20 -07:00
pass
if __name__ == '__main__':
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
```