test: add docker-compose with mosquitto and python subscriber
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
broker = os.getenv('MQTT_BROKER', 'localhost:1883')
|
||||
topic = os.getenv('MQTT_TOPIC', 'lambdaiot')
|
||||
|
||||
if broker.startswith('tcp://'):
|
||||
broker = broker[len('tcp://'):]
|
||||
|
||||
host, sep, port = broker.partition(':')
|
||||
port = int(port) if sep else 1883
|
||||
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
print(f"Connected with result code {rc}")
|
||||
client.subscribe(topic)
|
||||
print(f"Subscribed to {topic}")
|
||||
|
||||
def on_message(client, userdata, msg):
|
||||
try:
|
||||
payload = msg.payload.decode()
|
||||
except Exception:
|
||||
payload = str(msg.payload)
|
||||
print(f"[{msg.topic}] {payload}")
|
||||
|
||||
client = mqtt.Client()
|
||||
client.on_connect = on_connect
|
||||
client.on_message = on_message
|
||||
|
||||
try:
|
||||
client.connect(host, port, 60)
|
||||
except Exception as e:
|
||||
print("Could not connect to broker:", e)
|
||||
sys.exit(1)
|
||||
|
||||
client.loop_forever()
|
||||
Reference in New Issue
Block a user