mqtt_test.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from time import sleep
  5. from random import randint
  6. from paho.mqtt import client as mqtt_client
  7. broker = 'v96bb091.ala.cn-hangzhou.emqxsl.cn'
  8. port = 8883
  9. topic = 'python/mqtt'
  10. client_id = f'python-mqtt-{randint(0, 1000)}'
  11. # 如果 broker 需要鉴权,设置用户名密码
  12. username = 'test-publish'
  13. password = '12345678'
  14. def connect_mqtt():
  15. def on_connect(client, userdata, flags, rc):
  16. if rc == 0:
  17. print("Connected to MQTT Broker!")
  18. else:
  19. print("Failed to connect, return code %d\n", rc)
  20. # Set Connecting Client ID
  21. client = mqtt_client.Client(client_id)
  22. client.tls_set(ca_certs='./emqxsl-ca.crt')
  23. client.username_pw_set(username, password)
  24. client.on_connect = on_connect
  25. client.connect(broker, port)
  26. return client
  27. def subscribe(client: mqtt_client):
  28. def on_message(client, userdata, msg):
  29. print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
  30. client.subscribe(topic=topic, qos=0)
  31. client.on_message = on_message
  32. def publish(client):
  33. msg_count = 0
  34. while True:
  35. sleep(1)
  36. msg = f"messages: {msg_count}"
  37. result = client.publish(topic, msg)
  38. # result: [0, 1]
  39. status = result[0]
  40. if status == 0:
  41. print(f"Send `{msg}` to topic `{topic}`")
  42. else:
  43. print(f"Failed to send message to topic {topic} {status}")
  44. msg_count += 1
  45. def on_message(client, userdata, msg):
  46. print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
  47. def run():
  48. client = connect_mqtt()
  49. client.loop_start()
  50. publish(client)
  51. if __name__ == '__main__':
  52. run()