#!/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(client, userdata, flags, reason_code, properties): now = datetime.datetime.now() print(str(now) + ": " +"Connected to %s:%s" % (mqttc._host, mqttc._port)) def on_disconnect(client, userdata, flags, reason_code, properties): now = datetime.datetime.now() print(str(now) + ": disconnected") def on_message(client, userdata, message): global monitor_state now = datetime.datetime.now() print(str(now) + ": " + message.topic + " " + str(message.qos) + " " + str(message.payload)) if message.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 message.payload.decode('UTF-8') == 'display_on': if monitor_state == 0: monitor_state = 1 os.system("/home/pi/display_on.sh") print("display on") elif message.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(client, userdata, mid, reason_codes, properties): now = datetime.datetime.now() print(str(now) + ": " +"mid: "+str(mid)) def on_subscribe(client, userdata, mid, reason_codes, properties): now = datetime.datetime.now() print(str(now) + ": " +"Subscribed: "+str(mid)+" "+str(reason_codes)) def on_unsubscribe(client, userdata, mid, reason_codes, properties): now = datetime.datetime.now() print(str(now) + ": unsubscribe") # In NEW version, reason_codes is always a list. Empty for MQTTv3 for unsub_result in reason_codes: # Any reason code >= 128 is a failure. if reason_codes[0] >= 128: print("unsubscribe code: " + str(reason_codes[0])) def on_log(client, 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. client_id = 'mqtt-client-solaria' mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id) 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()