-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
44 lines (36 loc) · 1.28 KB
/
server.py
File metadata and controls
44 lines (36 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# The server is a client for the broker (On the home assistant)
# The server receive a mqtt packet from the ESP32 and send the information
# to the Home Assistant to switch between light and leds
import os
import paho.mqtt.client as mqtt
from dotenv import load_dotenv
# Load from the .env (make a copy of .env.example -> .env)
load_dotenv()
HOST = os.getenv("HOST", "127.0.0.1")
PORT = int(os.getenv("PORT", "1884"))
TOPIC = os.getenv("TOPIC", "haleds")
KEEP_ALIVE = int(os.getenv("KEEP_ALIVE", "60"))
def on_connect(cli: mqtt.Client, data, flags, code, properties=None):
if code == 0:
print(f"Connected to {HOST}:{PORT}")
cli.subscribe(TOPIC)
print(f"Subscribed to {TOPIC}")
else:
print("ERROR")
def on_message(cli: mqtt.Client, data, msg: mqtt.MQTTMessage):
content = msg.payload.decode("utf-8",errors="replace").strip("\n")
print(f"Topic={TOPIC}, Content={content}")
if content == "1":
print("SWITCH LED")
elif content == "0":
print("SWITCH LIGHT")
else:
print("UNKNOWN")
def main():
cli = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
cli.on_connect = on_connect
cli.on_message = on_message
cli.connect(HOST, PORT, keepalive=KEEP_ALIVE)
cli.loop_forever()
if __name__ == "__main__":
main()