-
Notifications
You must be signed in to change notification settings - Fork 44
/
pub_script.py
172 lines (145 loc) · 5.92 KB
/
pub_script.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
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
# Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
"""
hbmqtt_pub - MQTT 3.1.1 publisher
Usage:
hbmqtt_pub --version
hbmqtt_pub (-h | --help)
hbmqtt_pub --url BROKER_URL -t TOPIC (-f FILE | -l | -m MESSAGE | -n | -s) [-c CONFIG_FILE] [-i CLIENT_ID] [-q | --qos QOS] [-d] [-k KEEP_ALIVE] [--clean-session] [--ca-file CAFILE] [--ca-path CAPATH] [--ca-data CADATA] [ --will-topic WILL_TOPIC [--will-message WILL_MESSAGE] [--will-qos WILL_QOS] [--will-retain] ] [--extra-headers HEADER] [-r]
Options:
-h --help Show this screen.
--version Show version.
--url BROKER_URL Broker connection URL (musr conform to MQTT URI scheme (see https://github.com/mqtt/mqtt.github.io/wiki/URI-Scheme>)
-c CONFIG_FILE Broker configuration file (YAML format)
-i CLIENT_ID Id to use as client ID.
-q | --qos QOS Quality of service to use for the message, from 0, 1 and 2. Defaults to 0.
-r Set retain flag on connect
-t TOPIC Message topic
-m MESSAGE Message data to send
-f FILE Read file by line and publish message for each line
-s Read from stdin and publish message for each line
-k KEEP_ALIVE Keep alive timeout in second
--clean-session Clean session on connect (defaults to False)
--ca-file CAFILE] CA file
--ca-path CAPATH] CA Path
--ca-data CADATA CA data
--will-topic WILL_TOPIC
--will-message WILL_MESSAGE
--will-qos WILL_QOS
--will-retain
--extra-headers EXTRA_HEADERS JSON object with key-value pairs of additional headers for websocket connections
-d Enable debug messages
"""
import sys
import logging
import asyncio
import os
import json
import hbmqtt
from hbmqtt.client import MQTTClient, ConnectException
from docopt import docopt
from hbmqtt.utils import read_yaml_config
logger = logging.getLogger(__name__)
def _gen_client_id():
import os
import socket
pid = os.getpid()
hostname = socket.gethostname()
return "hbmqtt_pub/%d-%s" % (pid, hostname)
def _get_qos(arguments):
try:
return int(arguments['--qos'][0])
except:
return None
def _get_extra_headers(arguments):
try:
return json.loads(arguments['--extra-headers'])
except:
return {}
def _get_message(arguments):
if arguments['-n']:
yield b''
if arguments['-m']:
yield arguments['-m'].encode(encoding='utf-8')
if arguments['-f']:
try:
with open(arguments['-f'], 'r') as f:
for line in f:
yield line.encode(encoding='utf-8')
except:
logger.error("Failed to read file '%s'" % arguments['-f'])
if arguments['-l']:
import sys
for line in sys.stdin:
if line:
yield line.encode(encoding='utf-8')
if arguments['-s']:
import sys
message = bytearray()
for line in sys.stdin:
message.extend(line.encode(encoding='utf-8'))
yield message
async def do_pub(client, arguments):
running_tasks = []
try:
logger.info("%s Connecting to broker" % client.client_id)
await client.connect(uri=arguments['--url'],
cleansession=arguments['--clean-session'],
cafile=arguments['--ca-file'],
capath=arguments['--ca-path'],
cadata=arguments['--ca-data'],
extra_headers=_get_extra_headers(arguments))
qos = _get_qos(arguments)
topic = arguments['-t']
retain = arguments['-r']
for message in _get_message(arguments):
logger.info("%s Publishing to '%s'" % (client.client_id, topic))
task = asyncio.ensure_future(client.publish(topic, message, qos, retain))
running_tasks.append(task)
if running_tasks:
await asyncio.wait(running_tasks)
await client.disconnect()
logger.info("%s Disconnected from broker" % client.client_id)
except KeyboardInterrupt:
await client.disconnect()
logger.info("%s Disconnected from broker" % client.client_id)
except ConnectException as ce:
logger.fatal("connection to '%s' failed: %r" % (arguments['--url'], ce))
except asyncio.CancelledError as cae:
logger.fatal("Publish canceled due to prvious error")
def main(*args, **kwargs):
if sys.version_info[:2] < (3, 4):
logger.fatal("Error: Python 3.4+ is required")
sys.exit(-1)
arguments = docopt(__doc__, version=hbmqtt.__version__)
#print(arguments)
formatter = "[%(asctime)s] :: %(levelname)s - %(message)s"
if arguments['-d']:
level = logging.DEBUG
else:
level = logging.INFO
logging.basicConfig(level=level, format=formatter)
config = None
if arguments['-c']:
config = read_yaml_config(arguments['-c'])
else:
config = read_yaml_config(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'default_client.yaml'))
logger.debug("Using default configuration")
loop = asyncio.get_event_loop()
client_id = arguments.get("-i", None)
if not client_id:
client_id = _gen_client_id()
if arguments['-k']:
config['keep_alive'] = int(arguments['-k'])
if arguments['--will-topic'] and arguments['--will-message'] and arguments['--will-qos']:
config['will'] = dict()
config['will']['topic'] = arguments['--will-topic']
config['will']['message'] = arguments['--will-message'].encode('utf-8')
config['will']['qos'] = int(arguments['--will-qos'])
config['will']['retain'] = arguments['--will-retain']
client = MQTTClient(client_id=client_id, config=config, loop=loop)
loop.run_until_complete(do_pub(client, arguments))
loop.close()
if __name__ == "__main__":
main()