mqtt_client.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import paho.mqtt.client as mqtt
  2. # Log the startup sequence
  3. print("Starting MQTT client...")
  4. IDS = ['d4d4da3634a8']
  5. # The callback for when the client receives a CONNACK response from the server.
  6. def on_connect(client, userdata, flags, rc):
  7. if rc == 0:
  8. msg = "Connected successfully."
  9. elif rc == 3:
  10. msg = "Connection refused - server unavailable"
  11. else:
  12. msg = f"Connection failed with error code {rc}"
  13. print(msg)
  14. if rc == 0:
  15. # Subscribing in on_connect() means that if we lose the connection and
  16. # reconnect then subscriptions will be renewed.
  17. for id in IDS:
  18. channel = f"shellyplusplugs-{id}/events/rpc"
  19. print(f"subscribe to {channel}")
  20. client.subscribe(channel)
  21. # The callback for when a PUBLISH message is received from the server.
  22. def on_message(client, userdata, msg):
  23. print(f"Received message '{str(msg.payload.decode('utf-8'))}' on topic '{msg.topic}'")
  24. # Create an MQTT client and attach our routines to it.
  25. print("Initializing MQTT client...")
  26. client = mqtt.Client(client_id="home_controller")
  27. client.username_pw_set("rothe", "mqtt99")
  28. client.on_connect = on_connect
  29. client.on_message = on_message
  30. # Connect to an MQTT broker
  31. # Replace 'localhost' with the IP address of your broker if it's not on the same machine
  32. print("Connecting to MQTT broker...")
  33. client.connect("himbeere", 1883, 60)
  34. print("MQTT client started. Waiting for messages...")
  35. # Blocking call that processes network traffic, dispatches callbacks and
  36. # handles reconnecting.
  37. client.loop_forever()