2022年12月27日 星期二

MQTT and Python For Beginners -Troubleshoot using Logging

MQTT and Python For Beginners -Troubleshoot using Logging 

源自於 http://www.steves-internet-guide.com/mqtt-python-beginners-course/

Troubleshoot using Logging (使用日誌記錄進行故障排除)

To help troubleshoot your applications you can use the built in client logging callback.


import paho.mqtt.client as mqtt #import the client1

import time

############

def on_message(client, userdata, message):

    print("callback functions to Process any Messages Start a loop to check for callback messages.")

    print("message received -->" ,str(message.payload.decode("utf-8")))

    print("message topic=",message.topic)

    print("message qos=",message.qos)

    print("message retain flag=",message.retain)

    

########################################    

def on_log(client, userdata, level, buf):

    print("log: ",buf)    

########################################

broker_address="broker.hivemq.com"

#broker_address="iot.eclipse.org"

print("creating new instance")

client = mqtt.Client("P1") #create new instance

client.on_message=on_message #attach function to callback

client.on_log=on_log


print("connecting to broker")

client.connect(broker_address) #connect to broker


client.loop_start() #start the loop

print("Subscribing to topic","house/bulbs/bulb1")

client.subscribe("house/bulbs/bulb1")

print("Publishing message to topic","house/bulbs/bulb1")

client.publish("house/bulbs/bulb1","OFF")

time.sleep(4) # wait

client.loop_stop() #stop the loop


>>> %Run -c $EDITOR_CONTENT

creating new instance

connecting to broker

log:  Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b'P1'

Subscribing to topic house/bulbs/bulb1

log:  Sending SUBSCRIBE (d0, m1) [(b'house/bulbs/bulb1', 0)]

Publishing message to topic house/bulbs/bulb1

log:  Sending PUBLISH (d0, q0, r0, m2), 'b'house/bulbs/bulb1'', ... (3 bytes)

log:  Received CONNACK (0, 0)

log:  Received SUBACK

log:  Received PUBLISH (d0, q0, r0, m0), 'house/bulbs/bulb1', ...  (3 bytes)

callback functions to Process any Messages Start a loop to check for callback messages.

message received --> OFF

message topic= house/bulbs/bulb1

message qos= 0

message retain flag= 0

>>> 

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...