python-mqtt(emqx)连接实例demo 在启⽤client_id认证后
sub.py
from paho.mqtt import client as mqtt_client
broker ='192.168.1.176'
port =1883
topic ="/python/mqtt"
# generate client ID with pub prefix randomly
client_id ='mq_ldc'
user ='mq_ldc'
pwd ='1L2d3c456'
def connect_mqtt()-> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc ==0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set(user, pwd)
<_connect = on_connect
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
print("Received {} from {} topic".format(msg.payload.decode(), topic))
client.subscribe(topic)
<_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ =='__main__':
run()
pub.py
import time
emqx brokerfrom paho.mqtt import client as mqtt_client
broker ='192.168.1.176'
port =1883
topic ="/python/mqtt"
# generate client ID with pub prefix randomly
client_id ='mq_ldcTest'
user ='mq_ldcTest'
pwd ='1L2d3c456'
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc ==0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id=client_id, clean_session=False)
client.username_pw_set(user, pwd)
<_connect = on_connect
return client
def publish(client):
msg_count =0
while True:
time.sleep(1)
msg ="messages: {msg_count}".format(msg_count=msg_count)
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status ==0:
print("Send {msg} to topic {topic}".format(msg=msg, topic=topic)) else:
print("Failed to send message to topic {topic}".format(topic=topic)) msg_count +=1
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ =='__main__':
run()
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论