python3使用paho-mqtt

/

软硬件环境

  • ubuntu 18.04 64bit
  • anaconda3 & python3.6.2
  • paho-mqtt

预备知识

参考之前写的一篇博文 http://xugaoxiang.com/post/93,博文测试时mqtt broker采用的是mosquitto,同时在测试发送和接收时采用mosquitto_sub和mosquitto_pub命令行工具。

安装paho-mqtt

  1. conda install paho-mqtt

代码实践

  1. import paho.mqtt.client as mqtt
  2. def on_connect(client, userdata, flags, rc):
  3. '''
  4. :param client:
  5. :param userdata:
  6. :param flags:
  7. :param rc:
  8. :return:
  9. '''
  10. print('connect with rc: {}'.format(rc))
  11. if rc != 0:
  12. print('pub connect failed.')
  13. client.disconnect()
  14. def on_disconnect(client, userdata, rc=0):
  15. '''
  16. :param client:
  17. :param userdata:
  18. :param rc:
  19. :return:
  20. '''
  21. print('disconnect with rc: {}'.format(rc))
  22. client.loop_stop()
  23. def on_publish(client, userdata, mid):
  24. '''
  25. :param client:
  26. :param userdata:
  27. :param mid:
  28. :return:
  29. '''
  30. print('publish success.')
  31. def do_publish(topic, message):
  32. '''
  33. :param topic:
  34. :param message:
  35. :return: publish message via mqtt
  36. '''
  37. client = mqtt.Client()
  38. client.on_connect = on_connect
  39. client.on_disconnect = on_disconnect
  40. client.on_publish = on_publish
  41. client.connect(host='127.0.0.1', port=1883, keepalive=60)
  42. client.loop_start()
  43. try:
  44. client.publish('{}'.format(topic), '{}'.format(message))
  45. except:
  46. print('publish {} exception.'.format(message))
  47. finally:
  48. client.disconnect()

上述代码完成的是信息发布,分别实现了客户端连接、发布、断开的回调,在connect之后调用loop_start(),其作用是开启新的后台线程,防止主线程被阻塞,在client断开后要loop_stop杀掉线程。

信息的订阅寄接收的过程跟发布是一样的,publish换成subscribe,接收在on_message回调里进行处理。

参考资料

转载请注明作者和出处,并添加本页链接。
原文链接: http://xugaoxiang.com/post/122

给我留言