'mqtt client publish based on incoming message conditions
I am experimenting with mqtt with python paho mqtt library and a mqtt client mobile app with the test.mosquito.org server/broker.
This basic script works below connecting to the test.mosquitto server where I can publish a message from a mobile mqtt client app to this script and this script can also publish to the mobile app every 20 seconds a test message via the def publish(client):
function.
import random
import time
from paho.mqtt import client as mqtt_client
broker = 'test.mosquitto.org'
port = 1883
# generate client ID with pub prefix randomly
client_id = "test_1"
topic_to_publish = f"laptop/publish"
topic_to_listen = f"mobile/publish"
topic_to_wildcard = f"testing/*"
username = ""
password = ""
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
client.subscribe(topic_to_listen)
print(f"Connected to MQTT Broker on topic: {topic_to_wildcard}")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
client.on_connect = on_connect # Define callback function for successful connection
client.on_message = on_message # Define callback function for receipt of a message
return client
def publish(client):
msg_count = 0
while True:
time.sleep(20)
msg = f"hello from {client_id}: {msg_count}"
result = client.publish(topic_to_publish, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send {msg} to topic {topic_to_publish}")
else:
print(f"Failed to send message to topic {topic_to_publish}")
msg_count += 1
def on_message(client, userdata, msg): # The callback for when a PUBLISH message is received from the server.
print("Message received-> " + msg.topic + " " + str(msg.payload))
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
Can someone give me a tip on how to modify the def publish(client):
function not to be a while loop
that will fire off messages every 20 seconds but to only publish if the message from the mobile app received equals a string "zone temps"
?
Am I on track at all removing the publish(client)
from main run
function as well as the while loop from def publish(client):
? Thanks any tips greatly appreciated. What I am running into is I am missing something when I run this modified version there is no message exchange between at all.
def on_message(client, userdata, msg):
print("Message received-> " + msg.topic + " " + str(msg.payload))
if str(msg.payload) == "zone temps":
publish(client,"avg=72.1;min=66.4;max=78.8")
def run():
client = connect_mqtt()
client.loop_start()
if __name__ == '__main__':
run()
Solution 1:[1]
I m also beginner; but ill create a variable to is it publish or listening, like:
phoneAppListener = 0
and also
if str(msg.payload) == "zone temps":
when i print my payload it looks like:
b'payload'
firstly you need to split your payload like:
tempMsgHolder = str(msg.payload).split("'")
when you do this. tempMsgHolder[1] is your pure payload.
if tempMsgHolder[1] == "zone temps": phoneAppListener = 1
phoneAppListener value make the decision 0 is listen, 1 is publish. on your publish loop you set this
phoneAppListener == 1: publish your message
import random
import time
import threading
from paho.mqtt import client as mqtt_client
class moduleDatas:
broker = ('test.mosquitto.org')
port = (1883)
# generate client ID with pub prefix randomly
client_id = "test_1"
topic_to_publish = f"laptop/publish"
topic_to_listen = f"mobile/publish"
topic_to_wildcard = f"testing/*"
username = ""
password = ""
# Create clients object:
# You can create mqtt client obj using same pattern. Client has different on_msg or ex.
mqttClient_1 = mqtt_client.Client(moduleDatas.client_id) # You can create what ever you want to create a new thread
def mqttClientConnect():
mqttClient_1.connect(moduleDatas.broker[0], moduleDatas.port[0])
mqttClient_1.loop_start() # It creates daemon thread while your main thread running, this will handle your mqtt connection.
@mqttClient_1.connect_callback()
def on_connect(client, userdata, flags, rc):
if rc == 0:
print(f"Connected to MQTT Broker on topic: {moduleDatas.topic_to_wildcard}")
else:
print("Failed to connect, return code %d\n", rc)
@mqttClient_1.publish_callback()
def on_publish(client, userdata, mid):
print(mid) # If publish is success its return 1 || If mid = 1 publish success. || You can check your publish msg if it return failed try to send again or check your connection.
@mqttClient_1.message_callback()
def on_message(client, userdata, message):
temp_str = str(message.payload).split("'")
if temp_str[1] == "zone temps":
msg = "hello world" # <-- Your message here. Some func return or simple texts
mqttClient_1.publish(topic= moduleDatas.topic_to_publish, payload= msg, qos= 0)
def mqttClientSubscribe():
mqttClient_1.subscribe(moduleDatas.topic_to_listen)
def threadMqttClient1():
mqttClientConnect()
mqttClientSubscribe()
def buildThreads():
threads= []
t = threading.Thread(target=threadMqttClient1(), daemon= True)
threads.append(t)
# You can create on same pattern and append threads list.
for t in threads:
t.start()
while True: # this will your main thread, you can create an operation, ill go with just idling.
pass
if __name__ == "__main__":
buildThreads()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |