mqtt-test.py 921 B

123456789101112131415161718192021222324252627282930313233
  1. import paho.mqtt.client as mqtt
  2. import time
  3. import random # Replace with actual voltage measurement code
  4. BROKER = "localhost"
  5. PORT = 1883 # Use 8883 for TLS
  6. TOPIC = "cells_inserted/device1" # Change for each device
  7. USERNAME = "robot"
  8. PASSWORD = "robot"
  9. def on_connect(client, userdata, flags, rc):
  10. if rc == 0:
  11. print("Connected to MQTT Broker!")
  12. else:
  13. print(f"Failed to connect, return code {rc}\n")
  14. client = mqtt.Client()
  15. client.username_pw_set(USERNAME, PASSWORD)
  16. client.on_connect = on_connect
  17. client.connect(BROKER, PORT, 60)
  18. client.loop_start()
  19. try:
  20. while True:
  21. slot = int(random.uniform(0, 5)) # Replace with actual measurement
  22. client.publish(TOPIC, slot)
  23. print(f"Published: {slot} to topic {TOPIC}")
  24. time.sleep(2) # Adjust as needed
  25. except KeyboardInterrupt:
  26. print("Disconnecting from broker")
  27. client.disconnect()
  28. client.loop_stop()