-
Notifications
You must be signed in to change notification settings - Fork 1
/
mprune
executable file
·115 lines (86 loc) · 2.47 KB
/
mprune
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/python
# mprune - Prunes a topic tree of retained messages in an MQTT broker
#
# By Dennis Sell
#
#
__author__ = "Dennis Sell"
__copyright__ = "Copyright (C) Dennis Sell"
import sys
import signal
import getopt
import mosquitto
topiclist = []
broker = "127.0.0.1"
port = 1883
topics = "/#"
connected = False
def usage():
print "usage: mprune [options]" #[hostname[:port]] [topics]"
print "Delete retained topics from an MQTT broker."
print
print " -u --hostname HOSTNAME set hostname for broker (default localhost)"
print " -p --port PORT set port for mqtt broker (default 1883)"
print " -t --topic TOPIC set topic tree to delete"
print " -h --help show this help information"
print " -v --version show version information"
print "By Dennis Sell -- 2013"
def on_connect(mosq, userdata, rc):
global connected
connected = True
print "Connected to ", broker
def on_message(mosq, userdata, msg):
if msg.topic not in topiclist and msg.retain:
topiclist.append(msg.topic)
print " " + msg.topic
try:
opts, args = getopt.getopt(sys.argv[1:], 'u:p:t:hv', ['hostname=', 'port', 'topic', 'help', 'version'])
except getopt.GetoptError as err:
print str(err)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(2)
if opt in ('-v', '--version'):
version()
sys.exit(2)
elif opt in ('-u', '--hostname'):
broker = arg
elif opt in ('-p', '--port'):
port = int(arg)
elif opt in ('-t', '--topic'):
topics = arg
else:
usage()
sys.exit(2)
client = mosquitto.Mosquitto()
client.on_message = on_message
client.on_connect = on_connect
client.connect(broker, port)
client.subscribe(topics)
def alarm_handler(signal, frame):
global collect_state, flush_state
collect_state = False
flush_state = False
print "Waiting for connection"
while not connected:
client.loop(0)
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(5) # generate SIGALRM after 5 secs
collect_state = True
print "Collecting topics"
while collect_state:
client.loop(0)
pass
client.unsubscribe(topics)
print "Erasing topics"
for t in topiclist:
print " Erasing topic: ", t
client.publish(t, "", retain = True)
client.loop(0)
signal.alarm(2) # generate SIGALRM after 2 secs
flush_state = True
while flush_state:
client.loop(0)