在启用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)
client.on_connect = on_connect
client.connect(broker, port)
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)
client.on_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
run()
pub.py
import time
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_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)
client.on_connect = on_connect
client.connect(broker, port)
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()