-
Notifications
You must be signed in to change notification settings - Fork 33
/
pub_example.py
52 lines (44 loc) · 1.64 KB
/
pub_example.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
#!usr/bin/env python
# -*- coding: utf-8 -*-
#
# python3 -m pip install -U paho-mqtt
import time
import argparse
import paho.mqtt
import paho.mqtt.client as mqtt
# Handler when connecting to broker
def on_connect(client, userdata, flag, rc):
print("Connected with result code " + str(rc))
client.subscribe("/system/#")
# Handler when broker disconnects
def on_disconnect(client, userdata, flag):
print("disconnection.")
# # Handler when message arrives
def on_message(client, userdata, msg):
# msg.topic contains the topic name and msg.payload contains the received data
print("Received message '" + str(msg.payload) + "' on topic '" + msg.topic + "' with QoS " + str(msg.qos))
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--topic', help='mqtt topic', default="/system/test")
parser.add_argument('--host', help='mqtt host', default="esp32-broker.local")
parser.add_argument('--port', type=int, help='mqtt port', default=1883)
args = parser.parse_args()
print("args.topic={}".format(args.topic))
print("args.host={}".format(args.host))
print("args.port={}".format(args.port))
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.will_set('/system/message', 'Publisher Down')
client.connect(args.host, args.port, 60)
# keep waiting in an endless loop
#client.loop_forever()
while True:
t = time.time()
local_time = time.localtime(t)
payload = time.asctime(local_time)
print("payload={}".format(payload))
result = client.publish(args.topic, payload)
print("result={}".format(result))
time.sleep(1)