From 2b4cc4db77c660ec2ae57541f94a3d69258a3aa5 Mon Sep 17 00:00:00 2001 From: tony19990828 <58881058+tony19990828@users.noreply.github.com> Date: Wed, 16 Feb 2022 20:33:50 +0800 Subject: [PATCH] Create local_mqtt_pub --- local_mqtt_pub | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 local_mqtt_pub diff --git a/local_mqtt_pub b/local_mqtt_pub new file mode 100644 index 0000000..e7e0a64 --- /dev/null +++ b/local_mqtt_pub @@ -0,0 +1,61 @@ +import paho.mqtt.client as mqtt +import time +import numpy as np + + + + + +receivedMessages = [] + + +def on_connect(self, userdata, flags, rc): + # print("Connected with result code " + str(rc)) + pass + + +def initialise_clients(cname): + # callback assignment + initialise_client = mqtt.Client(cname, True) # don't use clean session + return initialise_client + + +# publish a message +def publish(topics, message, waitForAck=False): + mid = client.publish(topics, message, 2)[1] + print(f"just published {message} to topic") + if waitForAck: + while mid not in receivedMessages: + print("wait for ack") + time.sleep(0.25) + receivedMessages.remove(mid) + + +def on_publish(self, userdata, mid): + print("ack") + receivedMessages.append(mid) + + +host = "192.168.50.180" +port = 1883 + +topic = "mqtt/pub" + +client = initialise_clients("client1") + +client.on_connect = on_connect + +client.connect(host, port, 60) + +client.on_publish = on_publish + +client.loop_start() +# +publish(topic, "Connect", True) +count = 0 +while True: + randTemp = np.random.uniform(25.0, 35.0) + publish(topic, randTemp) + time.sleep(2) + print(count) + count += 1