From 22ad4a47d4b95183571f4bfd724e51902bc42bba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ebbe=20Ba=C3=9F?= Date: Wed, 29 Jun 2022 21:59:06 +0200 Subject: [PATCH] added basic mqtt mechanic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ebbe Baß --- main.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index c6eaa25..9029fa6 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,4 @@ +from base64 import b16decode import time import os from datetime import datetime @@ -10,6 +11,7 @@ try: import json from argparse import ArgumentParser import threading + import paho.mqtt.client as mqtt except ImportError: print('Some modules are missing. Try to install them with "pip3 install -r requirements.txt"') exit() @@ -24,6 +26,7 @@ LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 + def debug_print(message: str): now = datetime.now() current_time = now.strftime("%H:%M:%S") @@ -56,11 +59,21 @@ def setColor(strip, color, wait_ms=10): strip.show() time.sleep(wait_ms/1000.0) +def mqtt_on_connect(client, userdata, flags, rc): + client.subscribe("server-rack-led-1/power") + client.subscribe("server-rack-led-1/mode") + client.subscribe("server-rack-led-1/r") + client.subscribe("server-rack-led-1/g") + client.subscribe("server-rack-led-1/b") + +def mqtt_on_message(client, userdata, msg): + print(f"Message received [{msg.topic}]: {msg.payload}") + + if __name__ == '__main__': app = Flask(__name__) #api - @app.route('/api/') def index(): return ''' @@ -159,17 +172,32 @@ if __name__ == '__main__': threading.Thread(target=lambda: app.run(host='0.0.0.0', port=80)).start() + mqttBroker ="homeassistant.ping-mee.local" + client = mqtt.Client("server-rack-led-1") + client.connect(mqttBroker) + client.on_connect = mqtt_on_connect + client.on_message = mqtt_on_message + threading.Thread(target=lambda: client.loop_forever()) + try: while True: if power == "True": + client.publish("server-rack-led-1/power","True") if mode == 0: + client.publish("server-rack-led-1/mode","0") rainbowCycle(strip) elif mode == 1: + client.publish("server-rack-led-1/mode","1") + client.publish("server-rack-led-1/r",str(r)) + client.publish("server-rack-led-1/g",str(g)) + client.publish("server-rack-led-1/b",str(b)) setColor(strip, Color(int(r), int(g), int(b))) time.sleep(1) else: + client.publish("server-rack-led-1/power","False") setColor(strip, Color(0,0,0)) time.sleep(1) except KeyboardInterrupt: + client.disconnect() setColor(strip, Color(0,0,0)) GPIO.cleanup()