mqtt_sub_ctn_meter.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Dec 28 11:41:03 2023
  4. @author: husts
  5. """
  6. import random
  7. from paho.mqtt import client as mqtt_client
  8. broker = '119.45.101.222'
  9. port = 1883
  10. topic = "zh_testarea_m"
  11. # generate client ID with pub prefix randomly
  12. client_id = f'python-mqtt-{random.randint(0, 100)}'
  13. def connect_mqtt() -> mqtt_client:
  14. def on_connect(client, userdata, flags, rc):
  15. if rc == 0:
  16. print("Connected to MQTT Broker!")
  17. else:
  18. print("Failed to connect, return code %d\n", rc)
  19. client = mqtt_client.Client(client_id)
  20. client.on_connect = on_connect
  21. client.connect(broker, port)
  22. return client
  23. def subscribe(client: mqtt_client):
  24. def on_message(client, userdata, msg):
  25. print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
  26. client.subscribe(topic)
  27. client.on_message = on_message
  28. def run():
  29. client = connect_mqtt()
  30. subscribe(client)
  31. client.loop_forever()
  32. if __name__ == '__main__':
  33. run()