forked from emqx/MQTT-Client-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pub_tcp.py
66 lines (52 loc) · 1.44 KB
/
pub_tcp.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
# python 3.x
import json
import random
import time
from paho.mqtt import client as mqtt_client
BROKER = 'broker.emqx.io'
PORT = 1883
TOPIC = "python-mqtt/tcp"
# generate client ID with pub prefix randomly
CLIENT_ID = "python-mqtt-tcp-pub-{id}".format(id=random.randint(0, 1000))
USERNAME = 'emqx'
PASSWORD = 'public'
FLAG_CONNECTED = 0
def on_connect(client, userdata, flags, rc):
global FLAG_CONNECTED
if rc == 0:
FLAG_CONNECTED = 1
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code {rc}".format(rc=rc), )
def connect_mqtt():
client = mqtt_client.Client(CLIENT_ID)
client.username_pw_set(USERNAME, PASSWORD)
client.on_connect = on_connect
client.connect(BROKER, PORT)
return client
def publish(client):
msg_count = 0
while True:
msg_dict = {
'msg': msg_count
}
msg = json.dumps(msg_dict)
result = client.publish(TOPIC, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print("Send `{msg}` to topic `{topic}`".format(msg=msg, topic=TOPIC))
else:
print("Failed to send message to topic {topic}".format(topic=TOPIC))
msg_count += 1
time.sleep(1)
def run():
client = connect_mqtt()
client.loop_start()
time.sleep(1)
if FLAG_CONNECTED:
publish(client)
else:
client.loop_stop()
if __name__ == '__main__':
run()