Initial commit: UlHub workspace
This commit is contained in:
35
test/publish_sample.py
Normal file
35
test/publish_sample.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
BROKER_HOST = os.getenv("MQTT_HOST", "127.0.0.1")
|
||||
BROKER_PORT = int(os.getenv("MQTT_PORT", "1883"))
|
||||
USERNAME = os.getenv("MQTT_USERNAME", "testuser")
|
||||
PASSWORD = os.getenv("MQTT_PASSWORD", "testpass")
|
||||
TOPIC = os.getenv("MQTT_TOPIC", "devices/demo")
|
||||
INTERVAL = float(os.getenv("MQTT_INTERVAL", "2"))
|
||||
|
||||
client = mqtt.Client()
|
||||
if USERNAME:
|
||||
client.username_pw_set(USERNAME, PASSWORD)
|
||||
|
||||
client.connect(BROKER_HOST, BROKER_PORT, 60)
|
||||
|
||||
try:
|
||||
counter = 0
|
||||
while True:
|
||||
payload = {
|
||||
"message": f"hello from host {counter}",
|
||||
"timestamp": datetime.utcnow().isoformat() + "Z",
|
||||
}
|
||||
client.publish(TOPIC, json.dumps(payload), qos=0)
|
||||
print(f"published to {TOPIC}: {payload}")
|
||||
counter += 1
|
||||
time.sleep(INTERVAL)
|
||||
except KeyboardInterrupt:
|
||||
print("stopped")
|
||||
finally:
|
||||
client.disconnect()
|
||||
Reference in New Issue
Block a user