Last active
December 13, 2016 18:43
-
-
Save koma5/17df379098ca631a512d2b5e325cd5bb to your computer and use it in GitHub Desktop.
every minute like that: byteli/mqtt/heartbeat 19:40:01 up 6 days, 4:42, 1 user, load average: 0.00, 0.00, 0.00
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, time, mosquitto, subprocess | |
# cronjon | |
# */2 * * * * /usr/bin/python /root/mqttHeartbeat.py 2>&1 > /dev/null | |
pidFile = '/var/run/mqttHeartbeatPid' | |
def on_connect(userdata, flags, rc): | |
print "connected..." | |
def isRunning(pid): | |
try: | |
pid = int(pid) | |
os.kill(pid, 0) | |
return True | |
except (OSError, ValueError): | |
return False | |
mqttClient = mosquitto.Mosquitto("python-heartbeat-"+str(os.getpid())); | |
#define the callbacks | |
mqttClient.on_connect = on_connect | |
try: | |
f = open(pidFile,'r') | |
runningPid = f.read() | |
f.close() | |
pidFileExists = True | |
except IOError: | |
pidFileExists = False | |
if (not pidFileExists or not isRunning(runningPid)): | |
#not allready running | |
mqttClient.connect("127.0.0.1", 1883, 62, True) | |
# create pid file | |
f = open(pidFile,'w') | |
f.write(str(os.getpid())) | |
f.close() | |
else: | |
print "not supposed to run, allready running here: " + runningPid | |
raise SystemExit(0) | |
def publishHeartbeat(): | |
process = subprocess.Popen("uptime", shell=True, stdout=subprocess.PIPE) | |
process.wait() | |
uptime = process.stdout.read().rstrip() | |
mqttClient.publish("byteli/mqtt/heartbeat", uptime , 1) | |
try: | |
while True: | |
mqttClient.loop() | |
time.sleep(60) | |
publishHeartbeat() | |
except (KeyboardInterrupt): | |
print "Time to die ... disconnecting and deleting pidFile" | |
mqttClient.disconnect() | |
# remove pid file | |
os.remove(pidFile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment