ddeexxiikk

Python - MQTT

May 20th, 2025
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | Source Code | 0 0
  1. import serial
  2. import time
  3. import paho.mqtt.client as mqtt
  4.  
  5. SERIAL_PORT = 'COM10'
  6. BAUD_RATE = 9600
  7.  
  8. MQTT_BROKER = 'broker.emqx.io'
  9. MQTT_PORT = 1883
  10. MQTT_TOPIC = 'temperatura-arduino'
  11.  
  12. client = mqtt.Client()
  13.  
  14. def send_temperature_to_mqtt(temperature):
  15.     client.publish(MQTT_TOPIC, temperature)
  16.     print(f"Temperature sent to MQTT: {temperature} C")
  17.  
  18. def on_connect(client, userdata, flags, rc):
  19.     if rc == 0:
  20.         print("Connected to MQTT broker")
  21.     else:
  22.         print("Failed to connect, return code:", rc)
  23.  
  24. client.on_connect = on_connect
  25.  
  26. client.connect(MQTT_BROKER, MQTT_PORT)
  27.  
  28. ser = serial.Serial(SERIAL_PORT, BAUD_RATE)
  29.  
  30. time.sleep(2)
  31.  
  32. try:
  33.     while True:
  34.         if ser.in_waiting > 0:
  35.             temperature = ser.readline().decode('utf-8').strip()
  36.             print(f"Received temperature from serial: {temperature} C")
  37.            
  38.             send_temperature_to_mqtt(temperature)
  39.        
  40.         client.loop()
  41.         time.sleep(1)
  42.  
  43. except KeyboardInterrupt:
  44.     print("Program interrupted. Closing...")
  45. finally:
  46.     # Zamknij port szeregowy
  47.     ser.close()
Add Comment
Please, Sign In to add comment