徐高翔的个人网站

python3使用paho-mqtt

2018-08-25

软硬件环境

  • 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
'''

:param client:
:param userdata:
:param flags:
:param rc:
:return:
'''

print('connect with rc: {}'.format(rc))

if rc != 0:
print('pub connect failed.')
client.disconnect()

def on_disconnect(client, userdata, rc=0):
'''

:param client:
:param userdata:
:param rc:
:return:
'''

print('disconnect with rc: {}'.format(rc))

client.loop_stop()

def on_publish(client, userdata, mid):
'''

:param client:
:param userdata:
:param mid:
:return:
'''

print('publish success.')

def do_publish(topic, message):

'''
:param topic:
:param message:
:return: publish message via mqtt
'''

client = mqtt.Client()
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish

client.connect(host='127.0.0.1', port=1883, keepalive=60)
client.loop_start()

try:
client.publish('{}'.format(topic), '{}'.format(message))
except:
print('publish {} exception.'.format(message))
finally:
client.disconnect()

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

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

参考资料

本文链接 https://xugaoxiang.com/2018/08/25/python3使用paho-mqtt/

推荐文章(由hexo文章推荐插件驱动)

使用支付宝打赏
使用微信打赏

请博主喝咖啡!