-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsub.py
executable file
·57 lines (40 loc) · 1.29 KB
/
sub.py
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
#!/usr/bin/env python3
import datetime
import os
import sys
from shared import argparse
from shared import setup
from shared import sleep
try:
MESSAGE_LIMIT = int(os.getenv('MESSAGE_LIMIT'))
except TypeError as ex:
MESSAGE_LIMIT = None
MESSAGE_COUNT = 0
RUNNING = True
parser = argparse.ArgumentParser(description='Subscribe to a topic or topics')
parser.add_argument('topics', nargs='+',
help='The topics to subscribe to. Make sure to put topics with # wildcards in single quotes so the shell does not ignore them.')
args = parser.parse_args()
topics = args.topics
if not isinstance(topics, list):
topics = [topics]
print('Subscribing to ' + ', '.join(topics))
def disconnect_and_exit():
global RUNNING
global mqtt_client
RUNNING = False
mqtt_client.disconnect()
sys.exit(0)
def print_payload(client, userdata, message):
global MESSAGE_COUNT
global MESSAGE_LIMIT
print(str(datetime.datetime.now()) + ' - ' + str(message.topic) + ' - ' + str(message.payload))
MESSAGE_COUNT = MESSAGE_COUNT + 1
if (MESSAGE_LIMIT is None): return
if (MESSAGE_COUNT >= MESSAGE_LIMIT): disconnect_and_exit()
mqtt_client = setup()
mqtt_client.connect()
for topic in topics:
mqtt_client.subscribe(topic, 0, print_payload)
while RUNNING:
sleep(1)