Quellcode durchsuchen

added mqtt containers

cc vor 2 Jahren
Ursprung
Commit
1442f3cdf9
4 geänderte Dateien mit 69 neuen und 0 gelöschten Zeilen
  1. 12 0
      mqtt/broker/Dockerfile
  2. 5 0
      mqtt/broker/mosquitto.conf
  3. 7 0
      mqtt/client/Dockerfile
  4. 45 0
      mqtt/client/mqtt_client.py

+ 12 - 0
mqtt/broker/Dockerfile

@@ -0,0 +1,12 @@
+FROM python:3.8-slim
+
+# Install Mosquitto to act as the MQTT broker
+RUN apt-get update && \
+    apt-get install -y mosquitto mosquitto-clients
+
+# Expose MQTT port
+EXPOSE 1883
+
+COPY mosquitto.conf /mosquitto.conf
+# Run Mosquitto and the Python MQTT client
+CMD mosquitto -c /mosquitto.conf

+ 5 - 0
mqtt/broker/mosquitto.conf

@@ -0,0 +1,5 @@
+listener 1883 0.0.0.0
+password_file /files/passwordfile.txt
+# log_dest file /tmp/mosquitto.log
+log_type all
+log_timestamp_format %Y-%m-%dT%H:%M:%S

+ 7 - 0
mqtt/client/Dockerfile

@@ -0,0 +1,7 @@
+FROM python:3.11-slim
+
+RUN pip install paho-mqtt
+
+ADD mqtt_client.py /mqtt_client.py
+
+CMD python -u /mqtt_client.py

+ 45 - 0
mqtt/client/mqtt_client.py

@@ -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()