Skip to content

Commit 60d55d4

Browse files
authored
Create publish.py
1 parent 6ab8ff4 commit 60d55d4

1 file changed

Lines changed: 209 additions & 0 deletions

File tree

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# Copyright (c) 2014 Roger Light <roger@atchoo.org>
2+
#
3+
# All rights reserved. This program and the accompanying materials
4+
# are made available under the terms of the Eclipse Public License v1.0
5+
# and Eclipse Distribution License v1.0 which accompany this distribution.
6+
#
7+
# The Eclipse Public License is available at
8+
# http://www.eclipse.org/legal/epl-v10.html
9+
# and the Eclipse Distribution License is available at
10+
# http://www.eclipse.org/org/documents/edl-v10.php.
11+
#
12+
# Contributors:
13+
# Roger Light - initial API and implementation
14+
15+
"""
16+
This module provides some helper functions to allow straightforward publishing
17+
of messages in a one-shot manner. In other words, they are useful for the
18+
situation where you have a single/multiple messages you want to publish to a
19+
broker, then disconnect and nothing else is required.
20+
"""
21+
22+
import paho.mqtt.client as mqtt
23+
24+
25+
def _do_publish(c):
26+
"""Internal function"""
27+
m = c._userdata[0]
28+
c._userdata = c._userdata[1:]
29+
if type(m) is dict:
30+
topic = m['topic']
31+
try:
32+
payload = m['payload']
33+
except KeyError:
34+
payload = None
35+
try:
36+
qos = m['qos']
37+
except KeyError:
38+
qos = 0
39+
try:
40+
retain = m['retain']
41+
except KeyError:
42+
retain = False
43+
elif type(m) is tuple:
44+
(topic, payload, qos, retain) = m
45+
else:
46+
raise ValueError('message must be a dict or a tuple')
47+
48+
c.publish(topic, payload, qos, retain)
49+
50+
51+
def _on_connect(c, userdata, flags, rc):
52+
"""Internal callback"""
53+
_do_publish(c)
54+
55+
56+
def _on_publish(c, userdata, mid):
57+
"""Internal callback"""
58+
if len(userdata) == 0:
59+
c.disconnect()
60+
else:
61+
_do_publish(c)
62+
63+
64+
def multiple(msgs, hostname="localhost", port=1883, client_id="", keepalive=60,
65+
will=None, auth=None, tls=None, protocol=mqtt.MQTTv31):
66+
"""Publish multiple messages to a broker, then disconnect cleanly.
67+
This function creates an MQTT client, connects to a broker and publishes a
68+
list of messages. Once the messages have been delivered, it disconnects
69+
cleanly from the broker.
70+
msgs : a list of messages to publish. Each message is either a dict or a
71+
tuple.
72+
If a dict, only the topic must be present. Default values will be
73+
used for any missing arguments. The dict must be of the form:
74+
msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>,
75+
'retain':<retain>}
76+
topic must be present and may not be empty.
77+
If payload is "", None or not present then a zero length payload
78+
will be published.
79+
If qos is not present, the default of 0 is used.
80+
If retain is not present, the default of False is used.
81+
If a tuple, then it must be of the form:
82+
("<topic>", "<payload>", qos, retain)
83+
hostname : a string containing the address of the broker to connect to.
84+
Defaults to localhost.
85+
port : the port to connect to the broker on. Defaults to 1883.
86+
client_id : the MQTT client id to use. If "" or None, the Paho library will
87+
generate a client id automatically.
88+
keepalive : the keepalive timeout value for the client. Defaults to 60
89+
seconds.
90+
will : a dict containing will parameters for the client: will = {'topic':
91+
"<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
92+
Topic is required, all other parameters are optional and will
93+
default to None, 0 and False respectively.
94+
Defaults to None, which indicates no will should be used.
95+
auth : a dict containing authentication parameters for the client:
96+
auth = {'username':"<username>", 'password':"<password>"}
97+
Username is required, password is optional and will default to None
98+
if not provided.
99+
Defaults to None, which indicates no authentication is to be used.
100+
tls : a dict containing TLS configuration parameters for the client:
101+
dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
102+
'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
103+
'ciphers':"<ciphers">}
104+
ca_certs is required, all other parameters are optional and will
105+
default to None if not provided, which results in the client using
106+
the default behaviour - see the paho.mqtt.client documentation.
107+
Defaults to None, which indicates that TLS should not be used.
108+
"""
109+
110+
if type(msgs) is not list:
111+
raise ValueError('msgs must be a list')
112+
113+
client = mqtt.Client(client_id=client_id,
114+
userdata=msgs, protocol=protocol)
115+
client.on_publish = _on_publish
116+
client.on_connect = _on_connect
117+
118+
if auth is not None:
119+
username = auth['username']
120+
try:
121+
password = auth['password']
122+
except KeyError:
123+
password = None
124+
client.username_pw_set(username, password)
125+
126+
if will is not None:
127+
will_topic = will['topic']
128+
try:
129+
will_payload = will['payload']
130+
except KeyError:
131+
will_payload = None
132+
try:
133+
will_qos = will['qos']
134+
except KeyError:
135+
will_qos = 0
136+
try:
137+
will_retain = will['retain']
138+
except KeyError:
139+
will_retain = False
140+
141+
client.will_set(will_topic, will_payload, will_qos, will_retain)
142+
143+
if tls is not None:
144+
ca_certs = tls['ca_certs']
145+
try:
146+
certfile = tls['certfile']
147+
except KeyError:
148+
certfile = None
149+
try:
150+
keyfile = tls['keyfile']
151+
except KeyError:
152+
keyfile = None
153+
try:
154+
tls_version = tls['tls_version']
155+
except KeyError:
156+
tls_version = None
157+
try:
158+
ciphers = tls['ciphers']
159+
except KeyError:
160+
ciphers = None
161+
client.tls_set(ca_certs, certfile, keyfile, tls_version=tls_version,
162+
ciphers=ciphers)
163+
164+
client.connect(hostname, port, keepalive)
165+
client.loop_forever()
166+
167+
168+
def single(topic, payload=None, qos=0, retain=False, hostname="localhost",
169+
port=1883, client_id="", keepalive=60, will=None, auth=None,
170+
tls=None, protocol=mqtt.MQTTv31):
171+
"""Publish a single message to a broker, then disconnect cleanly.
172+
This function creates an MQTT client, connects to a broker and publishes a
173+
single message. Once the message has been delivered, it disconnects cleanly
174+
from the broker.
175+
topic : the only required argument must be the topic string to which the
176+
payload will be published.
177+
payload : the payload to be published. If "" or None, a zero length payload
178+
will be published.
179+
qos : the qos to use when publishing, default to 0.
180+
retain : set the message to be retained (True) or not (False).
181+
hostname : a string containing the address of the broker to connect to.
182+
Defaults to localhost.
183+
port : the port to connect to the broker on. Defaults to 1883.
184+
client_id : the MQTT client id to use. If "" or None, the Paho library will
185+
generate a client id automatically.
186+
keepalive : the keepalive timeout value for the client. Defaults to 60
187+
seconds.
188+
will : a dict containing will parameters for the client: will = {'topic':
189+
"<topic>", 'payload':"<payload">, 'qos':<qos>, 'retain':<retain>}.
190+
Topic is required, all other parameters are optional and will
191+
default to None, 0 and False respectively.
192+
Defaults to None, which indicates no will should be used.
193+
auth : a dict containing authentication parameters for the client:
194+
auth = {'username':"<username>", 'password':"<password>"}
195+
Username is required, password is optional and will default to None
196+
if not provided.
197+
Defaults to None, which indicates no authentication is to be used.
198+
tls : a dict containing TLS configuration parameters for the client:
199+
dict = {'ca_certs':"<ca_certs>", 'certfile':"<certfile>",
200+
'keyfile':"<keyfile>", 'tls_version':"<tls_version>",
201+
'ciphers':"<ciphers">}
202+
ca_certs is required, all other parameters are optional and will
203+
default to None if not provided, which results in the client using
204+
the default behaviour - see the paho.mqtt.client documentation.
205+
Defaults to None, which indicates that TLS should not be used.
206+
"""
207+
208+
msg = {'topic':topic, 'payload':payload, 'qos':qos, 'retain':retain}
209+
multiple([msg], hostname, port, client_id, keepalive, will, auth, tls, protocol)

0 commit comments

Comments
 (0)