Skip to content

Instantly share code, notes, and snippets.

@matbor
Created October 25, 2013 11:34
Show Gist options
  • Save matbor/7153280 to your computer and use it in GitHub Desktop.
Save matbor/7153280 to your computer and use it in GitHub Desktop.
last will and testament notify when one of them goes offline. for MQTT.
#!/usr/bin/python
#
# October 2013
# Subscribes to multiple topics (and will also block sub-topics, based on keywords) and if it see's the work
# 'offline' it sends a notification to the pushingbox topic. Mainly using this to track if a program goes offline
#
# by Matthew Bordignon / @bordignon
#
import mosquitto
try:
import json
except ImportError:
import simplejson as json
#used for re-connecting broker and exiting
import signal
import sys
import socket
import time
#BEGIN SETTINGS
broker = "mqtt.localdomain" #mqtt broker location
broker_port = 1883 #mqtt broker port
topics = [
'/house/xbmc/+/status',
'/lwt/#'
]
blocked_topics = [
'lwt2notify', #this program no need to notify
'tweet2mqtt', #the tweet2mqtt program as it runs as a cronjob
'xvsdfi44-PC', #xbmc on my lenovo laptop
'projector' #xbmc on my projector
]
willtopic = "/lwt/lwt2notify" #last will and testament (will_set) topic location
topic_notify = "/software/mqtt2pushingbox/message"
#END SETTINGS
mqttc = mosquitto.Mosquitto()
def cleanup(signum, frame):
"""
Signal handler to disconnect and cleanup.
"""
try:
mqttc.publish(willtopic, "offline", retain=True)
print("Disconnecting from broker")
mqttc.disconnect()
except:
print("no broker?")
print("Exiting on signal %d", signum)
sys.exit(signum)
def on_connect(mosq, obj, rc):
print("on-connect - rc: "+str(rc))
for topic in topics: #subscibing to multiple topics
print("Subscribing to %s", topic)
mqttc.subscribe(topic, 0)
mqttc.publish(willtopic, payload="online", qos=0, retain=True)
print("--")
def on_message(mosq, obj, msg):
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
if msg.retain == 1:
print("Skipping retained %s" % msg.topic)
return
if blocked_topics is not None:
for t in blocked_topics:
if t in msg.topic:
print("Skipping blocked topic %s" % msg.topic)
return
if str(msg.payload) == 'offline':
print('device is offline, sending notification')
try:
subject = 'Program offline atm'
mess_text = msg.topic+" -- "+msg.payload
payload = json.dumps(dict(
sub = subject.encode('utf-8'),
txt = mess_text.encode('utf-8')
))
print ""
print payload
print ""
mqttc.publish(topic_notify, payload , retain=False)
except:
raise
def on_publish(mosq, obj, mid):
print("on-publish - mid: "+str(mid))
def on_subscribe(mosq, obj, mid, granted_qos):
print("on-Subscribed: "+str(mid)+" "+str(granted_qos))
def on_log(mosq, obj, level, string):
print(string)
def main():
"""
The main loop in which we stay connected to the broker
"""
#define the callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.will_set(willtopic, payload="offline", qos=0, retain=True)
mqttc.reconnect_delay_set(delay=3, delay_max=30, exponential_backoff=True)
try:
mqttc.connect(broker, broker_port, 60)
except Exception, e:
print("MQTT connection failed: %s" % (str(e)))
sys.exit(1)
while True:
try:
mqttc.loop_forever()
except socket.error:
print("MQTT server disconnected; sleeping")
time.sleep(5)
except:
raise
if __name__ == '__main__':
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
main()
@matbor
Copy link
Author

matbor commented Mar 20, 2014

@summerboy12 here you go, mqttwarn version. https://gist.github.com/matbor/9657897

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment