Skip to content

Instantly share code, notes, and snippets.

@shimarin
Last active May 2, 2019 00:29
Show Gist options
  • Save shimarin/b4bcc71d0a39b6afa91e5c8a9d10945b to your computer and use it in GitHub Desktop.
Save shimarin/b4bcc71d0a39b6afa91e5c8a9d10945b to your computer and use it in GitHub Desktop.
#!/usr/bin/python2
import os,sys,argparse
import paho.mqtt.client as mqtt
import mdns_resolver
dirname = os.path.dirname(os.path.abspath(__file__))
nodename = "unknown-node"
force_check_topic = "gearchange-force-check"
gear_num = 0
subscribe_mid = None
def shutdown_system():
print "Executing shutdown script..."
script = os.path.join(dirname, "shutdown.sh")
if os.path.isfile(script) and os.system(script) == 0: sys.exit(0)
def start_job():
print "Executing startup script..."
script = os.path.join(dirname, "startup.sh")
if not os.path.isfile(script) or os.system(script) != 0:
print "Failed to execute startup.sh"
def gear_up():
global gear_num
script = os.path.join(dirname, "gear%d.sh" % (gear_num + 1))
if not os.path.isfile(script) or os.system(script) != 0: return
#else
gear_num += 1
print "gear up:%d" % gear_num
def gear_down():
global gear_num
if gear_num <= 1: return
#else
script = os.path.join(dirname, "gear%d.sh" % (gear_num - 1))
if not os.path.isfile(script) or os.system(script) != 0: return
#else
gear_num -= 1
print "gear down:%d" % gear_num
def on_connect(client, userdata, flags, response_code):
global subscribe_mid, nodename
topic = "gearchange-" + nodename
result, subscribe_mid = client.subscribe(topic)
if result != mqtt.MQTT_ERR_SUCCESS:
print "Could not subscribe %s" % topic
print "MQTT connected. nodename=%s" % nodename
def on_subscribe(client, userdata, mid, granted_qos):
global subscribe_mid
if mid != subscribe_mid: return
#else
client.publish(force_check_topic, "check")
def on_message(client, userdata, msg):
global gear_num
if msg.topic != "gearchange-" + nodename: return
msg = str(msg.payload)
if gear_num == 0:
if msg == "down": shutdown_system()
else:
start_job()
gear_num = 1
return
#else
if msg == "up": gear_up()
elif msg == "down": gear_down()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("nodename", type = str)
parser.add_argument("--mqtt-host", type = str)
parser.add_argument("-p", "--port", type = int, default=1883)
args = parser.parse_args()
nodename = args.nodename
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
if args.mqtt_host is None:
print "Discovering MQTT service..."
host_and_port = mdns_resolver.resolve("_mqtt._tcp.local.")
if host_and_port is None:
print "No MQTT sevice in network."
sys.exit(1)
#else
print "Found."
host,port = host_and_port
else:
host,port = args.mqtt_host, args.port
client.connect(host, port=port, keepalive=60)
client.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment