mqtt-halt-pack/client/client.py
2025-02-21 16:58:18 +01:00

75 lines
2.1 KiB
Python

#!/usr/bin/python3
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import traceback
import os
import datetime
monitor_state = 1
def on_connect(mqttc, obj, flags, rc):
now = datetime.datetime.now()
print(str(now) + ": " +"Connected to %s:%s" % (mqttc._host, mqttc._port))
def on_message(mqttc, obj, msg):
global monitor_state
now = datetime.datetime.now()
print(str(now) + ": " +msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
if msg.payload.decode('UTF-8') == 'halt':
print('powering off')
try:
publish.single("dom/pimirror-ack", "went-halt", hostname="192.168.31.5")
print("ack sent")
except Exception as e:
print("Exception when sending:" + str(e))
except:
print("Exception when sending:" + traceback.format_exc())
os.system("sudo shutdown now -h")
elif msg.payload.decode('UTF-8') == 'display_on':
if monitor_state == 0:
monitor_state = 1
os.system("/home/pi/display_on.sh")
print("display on")
elif msg.payload.decode('UTF-8') == 'display_off':
if monitor_state == 1:
monitor_state = 0
os.system("/home/pi/display_off.sh")
print("display off")
def on_publish(mqttc, obj, mid):
now = datetime.datetime.now()
print(str(now) + ": " +"mid: "+str(mid))
def on_subscribe(mqttc, obj, mid, granted_qos):
now = datetime.datetime.now()
print(str(now) + ": " +"Subscribed: "+str(mid)+" "+str(granted_qos))
def on_log(mqttc, obj, level, string):
now = datetime.datetime.now()
print(str(now) + ": " +string)
# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
mqttc.on_log = on_log
mqttc.connect("192.168.31.5")
mqttc.subscribe("dom/pimirror", 0)
mqttc.loop_forever()