-
Notifications
You must be signed in to change notification settings - Fork 1
/
mwatch
executable file
·406 lines (361 loc) · 12.1 KB
/
mwatch
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#!/usr/bin/python
# mwatch - Watches topics change from an MQTT broker
#
# By Dennis Sell
#
# Inspired by subcurses written by Andrew Elwell <Andrew.Elwell@ivec.org>
__author__ = "Dennis Sell"
__copyright__ = "Copyright (C) Dennis Sell"
#BUGS
# resizing terminal crashes. Possibly some curses/mosquitto interaction.
import os
import sys
import getopt
import mosquitto
import curses
from curses.ascii import isprint
import time
import datetime
import mqttcore
version_number = 0.7
topiclist = []
count = []
numtopics = 0
rxcount = 0
pos = 0
col = 0
topic_col = 0
topic_size = 65
retained_col = topic_size
qos_col = topic_size
count_col = topic_size
timestamp_col = topic_size
message_col = topic_size
def usage():
print "usage: mwatch [options]" #[hostname[:port]] [topics]"
print "Watch topics change 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 --topics TOPICS set topics to watch (default /#)"
print " -q --qos show QOS as recieved"
print " -r --retained show retained status"
print " -c --count show count of receptions"
print " -s --timestamp show timestamp of message reception"
print " -a --all show all data fields"
print " -x --hex show message in hex"
print " -h --help show this help information"
print " -v --version show version information"
print "By Dennis Sell -- 2013"
def version():
print "version: " + str(version_number)
def show_help():
help_cols = curses.COLS/2
help_lines = curses.LINES/2
help_win = curses.newwin(24, 50, help_lines-12, help_cols-25)
help_win.box()
help_win.addstr(1, 1, "Key Commands", curses.A_UNDERLINE)
help_win.addstr(3, 1, "[Home] - Jump to top left")
help_win.addstr(4, 1, "[END] - Jump to bottom of list")
help_win.addstr(5, 1, "b - Jump to begining of line")
help_win.addstr(6, 1, "e - Jump to end of line")
help_win.addstr(7, 1, "[Right Arrow] - Scroll to right")
help_win.addstr(8, 1, "[Left Arrow] - Scroll to left")
help_win.addstr(9, 1, "[Up Arrow] - Scroll up")
help_win.addstr(10, 1, "[Down Arrow] - Scroll down")
help_win.addstr(11, 1, "[Page Up] - Page up")
help_win.addstr(12, 1, "[Page Down] - Page down")
help_win.addstr(14, 1, "Retained flag == True implies the message was")
help_win.addstr(15, 1, "sent before mwatch connected to the broker. ")
help_win.addstr(17, 1, "q - To exit help.")
help_win.noutrefresh()
curses.doupdate()
while True:
key = stdscr.getch()
if key == ord("q"):
break
help_win.erase()
del help_win
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, 0, 2, 1, 2, curses.COLS-3)
stdscr.nooutrefresh()
curses.doupdate()
def on_connect(mosq, userdata, rc):
stdscr.addstr(curses.LINES-1,0,"Connected to %s" % broker)
stdscr.addstr(0,15,"Sunscribed to %s" % topics, curses.A_REVERSE)
stdscr.noutrefresh()
curses.doupdate()
def isprintable(v):
ret = True
for char in v:
if not curses.ascii.isprint(char):
ret = False
return ret
def printable(input):
return ''.join(char for char in input if isprint(char))
def on_message(mosq, userdata, msg):
global numtopics
global rxcount
global retained_flag
global timestamp_flag
rxcount = rxcount + 1
stdscr.addstr(0,80,"Msg count %s" % rxcount, curses.A_REVERSE)
if msg.topic not in topiclist:
topiclist.append(msg.topic)
numtopics = numtopics + 1
count.append(0)
stdscr.addstr(0,60,"Topic count %s" % numtopics, curses.A_REVERSE)
offset = topiclist.index(msg.topic)
count[offset] = count[offset] + 1
stats_txt.move(offset, message_col)
stats_txt.clrtoeol()
stats_txt.addstr(offset, topic_col, msg.topic)
if isprintable(msg.payload) and not hex_flag:
stats_txt.addstr(offset, message_col, msg.payload[0:1900])
else:
v = " ".join([hex(ord(a)) for a in msg.payload]) #Does individual bytes.
stats_txt.addstr(offset, message_col, "#### NON-ALPHANUMERIC #### --> 0x" + msg.payload.encode('hex')[0:1900])
if msg.retain:
retained_value = "True "
else:
retained_value = "False"
if retained_flag:
stats_txt.addstr(offset, retained_col, retained_value)
if qos_flag:
stats_txt.addstr(offset, qos_col, str(msg.qos))
if count_flag:
stats_txt.addstr(offset, count_col, str(count[offset]))
if timestamp_flag:
stats_txt.addstr(offset, timestamp_col, str(datetime.datetime.now()))
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
curses.doupdate()
def getTerminalSize():
"""
returns (lines:int, cols:int)
"""
import os, struct
def ioctl_GWINSZ(fd):
import fcntl, termios
return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
# try stdin, stdout, stderr
for fd in (0, 1, 2):
try:
return ioctl_GWINSZ(fd)
except:
pass
# try os.ctermid()
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
try:
return ioctl_GWINSZ(fd)
finally:
os.close(fd)
except:
pass
# try `stty size`
try:
return tuple(int(x) for x in os.popen("stty size", "r").read().split())
except:
pass
# try environment variables
try:
return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
except:
pass
# i give up. return default.
return (25, 80)
try:
opts, args = getopt.getopt(sys.argv[1:], 'u:p:t:rqcsaxhv', ['hostname=', 'port=', 'topics=', 'retained', 'qos', 'count', 'timestamp', 'all', 'hex', 'help', 'version'])
except getopt.GetoptError as err:
print str(err)
usage()
sys.exit(2)
# defaults
broker = "127.0.0.1"
port = 1883
topics = "/#"
retained_flag = False
qos_flag = False
count_flag = False
timestamp_flag = False
hex_flag = False
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', '--topics'):
topics = arg
elif opt in ('-r', '--retained'):
retained_flag = True
elif opt in ('-q', '--qos'):
qos_flag = True
elif opt in ('-c', '--count'):
count_flag = True
elif opt in ('-s', '--timestamp'):
timestamp_flag = True
elif opt in ('-a', '--all'):
retained_flag = True
qos_flag = True
count_flag = True
timestamp_flag = True
elif opt in ('-x', '--hex'):
hex_flag = True
else:
usage()
sys.exit(2)
# minitialize mosquitto, connect, and subscribe
client = mosquitto.Mosquitto()
client.on_message = on_message
client.on_connect = on_connect
client.connect(broker, port)
if qos_flag:
qos = 2
else:
qos = 0
client.subscribe(topics, qos=qos)
# initialize curses
stdscr = curses.initscr()
if curses.COLS < 95:
curses.endwin()
print "mwatch requires a minimum terminal width of 95 columns."
sys.exit(2)
if curses.LINES < 7:
curses.endwin()
print "mwatch requires a minimum terminal heigth of 7 rows."
sys.exit(2)
stdscr.nodelay(1)
curses.curs_set(0)
if curses.has_colors():
curses.start_color()
curses.cbreak()
curses.noecho()
stdscr.keypad(1)
# draw basic screen
stdscr.addstr("MQTT watch ", curses.A_REVERSE)
stdscr.chgat(-1,curses.A_REVERSE)
stdscr.addstr(curses.LINES-1,curses.COLS-57,"page-up, page-dn, cursor arrows, ? for help, q to Quit")
page = curses.LINES - 3
stats = curses.newwin(curses.LINES-2,curses.COLS,1,0)
stats.box()
header_txt = curses.newpad(1,2000)
stats_txt = curses.newpad(2000,2000)
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
stdscr.noutrefresh()
stats.noutrefresh()
header_txt.addstr(0, topic_col+1, "TOPIC", curses.A_UNDERLINE)
if retained_flag:
qos_col = qos_col + 10
timestamp_col = timestamp_col + 10
count_col = count_col + 10
message_col = message_col + 10
if curses.COLS > retained_col + 2:
header_txt.addstr(0, retained_col+1, "RETAINED", curses.A_UNDERLINE)
if qos_flag:
timestamp_col = timestamp_col + 5
count_col = count_col + 5
message_col = message_col + 5
header_txt.addstr(0, qos_col+1, "QOS", curses.A_UNDERLINE)
if count_flag:
timestamp_col = timestamp_col + 7
message_col = message_col + 7
header_txt.addstr(0, count_col+1, "COUNT", curses.A_UNDERLINE)
if timestamp_flag:
message_col = message_col + 28
header_txt.addstr(0, timestamp_col+1, "RECEIVED TIMESTAMP", curses.A_UNDERLINE)
if curses.COLS > message_col + 10:
header_txt.addstr(0, message_col+1, "MESSAGE", curses.A_UNDERLINE)
header_txt.refresh(0, 0, 2, 1, 2, curses.COLS-3)
stats.noutrefresh()
curses.doupdate()
# main loop
while client.loop(0) == 0:
key = stdscr.getch()
if key == -1:
pass
elif key == ord("q"):
break
elif key == ord("?"):
show_help()
elif key == curses.KEY_DOWN:
pos = pos + 1
if pos > numtopics:
pos = numtopics
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_UP:
pos = pos - 1
if pos < 0:
pos = 0
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_NPAGE:
pos = pos + page - 2
if pos > numtopics:
pos = numtopics
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_PPAGE:
pos = pos - page + 2
if pos < 0:
pos = 0
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_LEFT:
col = col - 1
if col < 0:
col = 0
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_RIGHT:
col = col + 1
if col > 2003-curses.COLS:
col = 2003-curses.COLS
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_HOME:
pos = 0
col = 0
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_END:
pos = numtopics - page + 4
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == ord("b"):
col = 0
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == ord("e"):
col = 2003 - curses.COLS
stats_txt.refresh(pos, col, 3,2, page,curses.COLS-3)
header_txt.refresh(0, col, 2, 1, 2, curses.COLS-3)
curses.doupdate()
elif key == curses.KEY_RESIZE: #Resizing the terminal screen crashes this program.
l, c = getTerminalSize() #It seems to be something to do with calling the mosquitto library in the above while loop.
if c > 50: #Redrawing belongs here if the problem gets solved.
stdscr.addstr(0, curses.COLS-20, "Col: " + str(c) + " Lines: " + str(l))
l, c = getTerminalSize()
if c > 120:
stdscr.addstr(0,c - 27,"%s" % str(datetime.datetime.now()), curses.A_REVERSE)
pass
# clean up terminal settings
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()