|
|
@@ -0,0 +1,45 @@
|
|
|
+import paho.mqtt.client as mqtt
|
|
|
+
|
|
|
+# Log the startup sequence
|
|
|
+print("Starting MQTT client...")
|
|
|
+
|
|
|
+IDS = ['d4d4da3634a8']
|
|
|
+# The callback for when the client receives a CONNACK response from the server.
|
|
|
+def on_connect(client, userdata, flags, rc):
|
|
|
+ if rc == 0:
|
|
|
+ msg = "Connected successfully."
|
|
|
+ elif rc == 3:
|
|
|
+ msg = "Connection refused - server unavailable"
|
|
|
+ else:
|
|
|
+ msg = f"Connection failed with error code {rc}"
|
|
|
+
|
|
|
+ print(msg)
|
|
|
+
|
|
|
+ if rc == 0:
|
|
|
+ # Subscribing in on_connect() means that if we lose the connection and
|
|
|
+ # reconnect then subscriptions will be renewed.
|
|
|
+ for id in IDS:
|
|
|
+ channel = f"shellyplusplugs-{id}/events/rpc"
|
|
|
+ print(f"subscribe to {channel}")
|
|
|
+ client.subscribe(channel)
|
|
|
+
|
|
|
+# The callback for when a PUBLISH message is received from the server.
|
|
|
+def on_message(client, userdata, msg):
|
|
|
+ print(f"Received message '{str(msg.payload.decode('utf-8'))}' on topic '{msg.topic}'")
|
|
|
+
|
|
|
+# Create an MQTT client and attach our routines to it.
|
|
|
+print("Initializing MQTT client...")
|
|
|
+client = mqtt.Client(client_id="home_controller")
|
|
|
+client.username_pw_set("rothe", "mqtt99")
|
|
|
+client.on_connect = on_connect
|
|
|
+client.on_message = on_message
|
|
|
+
|
|
|
+# Connect to an MQTT broker
|
|
|
+# Replace 'localhost' with the IP address of your broker if it's not on the same machine
|
|
|
+print("Connecting to MQTT broker...")
|
|
|
+client.connect("himbeere", 1883, 60)
|
|
|
+
|
|
|
+print("MQTT client started. Waiting for messages...")
|
|
|
+# Blocking call that processes network traffic, dispatches callbacks and
|
|
|
+# handles reconnecting.
|
|
|
+client.loop_forever()
|