2022年12月28日 星期三

Paho Python MQTT Client – Publish With Examples

 Paho Python MQTT Client – Publish With Examples

  源自於 http://www.steves-internet-guide.com/publishing-messages-mqtt-client/


Publishing a Message

To publish a message you need to:

  1. Create a client object.
  2. Create a client connection.
  3. publish the message
  4. Examine the return code of the publish request
  5. Examine the publish acknowledgement using the on_publish callback
Example code:
import paho.mqtt.client as paho
broker="192.168.1.184"
port=1883
def on_publish(client,userdata,result):             #create function for callback
    print("data published \n")
    pass
client1= paho.Client("control1")                           #create client object
client1.on_publish = on_publish                          #assign function to callback
client1.connect(broker,port)                                 #establish connection
ret= client1.publish("house/bulb1","on")                   #publish

Note 1: you don’t appear to need a client loop to process the on_publish callback.

Note2: When you publish a message the publish method returns a tuple (result, mid).

The result is the error code. A result of 0 indicates success.

The mid value is an integer that corresponds to the published message number as assigned by the client.

The mid value can be used with the on_publish callback to check that the messages was published even when publishing with a qos of 0.

If you publish with a qos of 0 the published message has a mid of 0 but internally it has a mid just like qos 1,2 messages.

So on the broker you see a mid of 0 but on the client you see an incrementing mid.

On_publish Callback

When the message has been published to the Broker an acknowledgement is sent that results in the on_publish callback being called.

The on_publish callback function must receive three parameters

on_publish(client, userdata, mid)

The client is the client object, and is useful when you have multiple clients that are publishing data.

The userdata is user defined data which isn’t normally used.

The mid value is the message id and can be used with the mid value returned from the publish method to check that a particular message has been published.

In the screen shot below I have printed the mid value from the publish message and on publish callback.

You can see that the numbers match which indicated that both messages were published OK


import paho.mqtt.client as mqtt

broker="broker.hivemq.com"

port=1883


def on_publish(client,userdata,result):             #create function for callback

    print("Published message.result : " + str(result))

    print("data published \n")

    pass


client1= mqtt.Client("control1")                           #create client object

client1.on_publish = on_publish                          #assign function to callback

client1.connect(broker,port)                                 #establish connection

ret= client1.publish("alex9ufo/house/bulb1","on",qos=0, retain=False)                   #publish

>>> %Run Publish_1.py
Published message.result : 1
data published 

>>> 


import paho.mqtt.client as mqtt
broker="broker.hivemq.com"
port=1883

def on_publish(client,userdata,mid):             #create function for callback
    print("Published message.mid: " + str(mid))
    print("data published \n")
    pass

client1= mqtt.Client("control1")                           #create client object
client1.on_publish = on_publish                          #assign function to callback
client1.connect(broker,port)                                 #establish connection
ret= client1.publish("alex9ufo/house/bulb1","off",qos=0, retain=False)                   #publish


>>> %Run Publish_2.py
Published message.mid: 1
data published 



'''
Python 範例程式已經根據可用 MQTT Broker 修改
程式先訂閱 house/bulb1 主題,然後發行 house/bulb1 此主題及內容
'''
import time
import paho.mqtt.client as mqtt

broker="broker.hivemq.com"
#broker_address="iot.eclipse.org"

# define callback
def on_message(client, userdata, message):
    time.sleep(1)
    print("received message =", str(message.payload.decode("utf-8")))

client = mqtt.Client("client-001")  # create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection client1.publish("house/bulb1","on")
######Bind function to callback
client.on_message = on_message
#####
print("connecting to broker ", broker)
client.connect(broker)  # connect
client.loop_start()  # start loop to process received messages
print("subscribing ")
client.subscribe("alex9ufo/house/bulb1")  # subscribe
print("publishing ")
client.publish("alex9ufo/house/bulb1", "on")  # publish
time.sleep(5)
client.publish("alex9ufo/house/bulb1", "off")  # publish
time.sleep(3)

client.disconnect()  # disconnect
client.loop_stop()  # stop loop


>>> %Run Publish_3.py
connecting to broker  broker.hivemq.com
subscribing 
publishing 
received message = on
received message = off


import paho.mqtt.client as mqtt
import time
# Define event callbacks
UserName="alex9ufo"
Password="alex9981"
hostname="broker.hivemq.com"
port=1883
RootTopic="alex9ufo/house"

def on_connect(client, userdata, rc):
    if rc == 0:
        print("on_connect --> Connected successfully.")
    else:
        print("Connection failed. rc= "+str(rc))

def on_publish(client, userdata, mid):
    print("on_publish --> Message "+str(mid)+" published.")

def on_subscribe(client, userdata, mid, granted_qos):
    print("on_subscribe --> Subscribe with mid "+str(mid)+" received.")

def on_message(client, userdata, msg):
    print("on_message --> Message received on topic "+msg.topic+" with QoS "+str(msg.qos)+" and payload "+msg.payload)

mqttclient = mqtt.Client()


# Assign event callbacks
mqttclient.on_connect = on_connect
mqttclient.on_message = on_message
mqttclient.on_publish = on_publish
mqttclient.on_subscribe = on_subscribe
# Connect
mqttclient.username_pw_set(UserName, Password)
mqttclient.connect(hostname, port)

# Start subscription
mqttclient.subscribe(RootTopic)
time.sleep(4) # wait
# Publish a message
mqttclient.publish(RootTopic, " MQTT Message --> Hello World!")

time.sleep(4) # wait
mqttclient.loop_stop() #stop the loop


>>> %Run Publish_4.py
on_publish --> Message 2 published.
>>> 

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...