FanLedCtrl/mqttclient/fanATserial2mqtt.py

53 lines
1.2 KiB
Python
Raw Normal View History

2024-12-07 14:25:04 +01:00
#! /usr/bin/python3
import time
import sys
from paho.mqtt import client as mqtt_client
import os
2024-12-07 14:36:47 +01:00
import serial
# MQTT Settings
2024-12-07 14:25:04 +01:00
mqtt_server=os.environ['MQTT_SERVER']
mqtt_topic=os.environ['MQTT_TOPIC']
2024-12-07 14:36:47 +01:00
# SERIAL Port
serial_device=os.environ['SERIAL_DEVICE']
2024-12-07 14:25:04 +01:00
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# Start mqtt
client_id = f'python-fan-ctrl'
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2)
client.on_message = on_message
if (not (mqtt_server)):
print("MQTT_SERVER is not set")
if (not (mqtt_topic)):
print("MQTT_TOPIC is not set")
client.connect(mqtt_server, 1883)
val=0
client.loop_start()
2024-12-07 14:36:47 +01:00
ser = serial.Serial(serial_device, 115200, timeout=1) # open serial port
client.publish(mqtt_topic + "device", ser.name) # check which port was really used
line = ser.readline() # read a '\n' terminated line
client.publish(mqtt_topic + "debug", line) # check which port was really used
2024-12-07 14:25:04 +01:00
# Endless Loop
while True:
try:
client.publish(mqtt_topic + "val", val)
time.sleep(0.2)
val = val + 1
except (KeyboardInterrupt, SystemExit):
cleanAndExit()
client.loop_stop()