LED-Control/mqtt.py

69 lines
1.8 KiB
Python
Raw Normal View History

2021-10-28 10:06:23 +01:00
import random
import json
2021-10-28 12:34:09 +01:00
import os
2021-10-28 10:06:23 +01:00
2021-10-28 12:34:09 +01:00
from dotenv import load_dotenv
2021-10-28 10:06:23 +01:00
from paho.mqtt import client as mqtt_client
2021-10-28 12:34:09 +01:00
from lib.shared import run_bulb_action, convert_to_bulb_format
2021-10-28 10:06:23 +01:00
2021-10-28 12:34:09 +01:00
load_dotenv()
2021-10-28 10:06:23 +01:00
2021-10-28 12:34:09 +01:00
broker = os.getenv("BROKER")
port = os.getenv("PORT")
topic = os.getenv("SUB_TOPIC")
2021-10-28 10:06:23 +01:00
# generate client ID with pub prefix randomly
client_id = f"python-mqtt-{random.randint(0, 100)}"
2021-10-28 12:34:09 +01:00
username = os.getenv("USERNAME")
password = os.getenv("PASSWORD")
2021-10-28 10:06:23 +01:00
def connect_mqtt() -> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
2021-10-28 12:34:09 +01:00
result = client.publish(os.getenv('PUB_TOPIC'), "ON")
2021-10-28 10:06:23 +01:00
status = result[0]
if status == 0:
2021-10-28 10:18:05 +01:00
print(f"Send `ON` to topic `{topic}`")
2021-10-28 10:06:23 +01:00
else:
print(f"Failed to send message to topic {topic}")
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
2021-10-28 10:17:11 +01:00
json_response = json.loads(msg.payload.decode())
if "color" in json_response:
hex = convert_to_bulb_format(json_response)
2021-10-28 10:13:03 +01:00
run_bulb_action(hex)
else:
2021-10-28 10:17:11 +01:00
if json_response["state"] == "OFF":
2021-10-28 10:13:03 +01:00
run_bulb_action("cc2433")
else:
run_bulb_action("cc2333")
2021-10-28 10:06:23 +01:00
client.subscribe(topic)
client.on_message = on_message
def run():
client = connect_mqtt()
publish(client)
subscribe(client)
client.loop_forever()
if __name__ == "__main__":
run()