树莓派做mqtt服务器(三部曲之三)用Python访问MQTT服务器

基于树莓派构建物联网系统的搭建,前文介绍了其的前两个部分,分别是在树莓派上安装和测试mqtt服务器软件,以及在线的嵌入式系统ESP8266(Node MCU)与树莓派服务器之间的通讯。是不是还缺少了什么?是的,还缺少了服务器端的数据处理。服务器端还需要将接收的数据进行分析存储,或给前端(不准确的称呼)发出相应的数据或指令,例如发出给继电器的控制信号,通过前端的Node MCU去执行。今天介绍的就是这个部分的初步实现。

首先给树莓派之python安装相应的依赖。
我用的是树莓派4B,在安装系统时已经自带了python3.7.

pi@raspberrypi:~ $ sudo apt-get install python-pip
省去安装中提示部分,最后显示:Successfully installed

然后下载安装paho-mqtt,这一部我在前文中省略了,现在补上:
$ pip install paho-mqtt

获得了这些代码后,你就可以把它安装在你的仓库中:
pi@raspberrypi:~ $ cd paho.mqtt.python
pi@raspberrypi:~/paho.mqtt.python $ python setup.py install
安装中系统提示如下错误,也就是目标文件访问权的问题。
running install
error: can't create or remove files in install directory

需要改变目标文件夹访问权:
pi@raspberrypi:~/paho.mqtt.python $ sudo chmod 777 /usr/local/lib/python2.7/dist-packages
pi@raspberrypi:~/paho.mqtt.python $ python setup.py install

然后重新安装
pi@raspberrypi:~/paho.mqtt.python $ python setup.py install

为了完成全部的测试(包括MQTT v5),你还需要把paho.mqtt.testing克隆到你的paho.mqtt.python文件夹中:
pi@raspberrypi:~/paho.mqtt.python $ git clone https://github.com/eclipse/paho.mqtt.testing.git

到此安装成功,可以开始下面简单的测试程序的运行了。不过对于我的Pi4B来所,我用的python IDE Thonny用的是python3.7,但注意库被安装到了python2.7下。这样下面的例题就不能被执行,第一行就不对了。
解决方法比较简单粗暴:把
/usr/local/lib/python2.7/dist-packages 的全部内容拷贝到
/usr/local/lib/python3.7/dist-packages 之中。注意如果你没有这个文件夹的写权,需要设置之。
$ sudo chmod 777 /usr/local/lib/python3.7/dist-packages

至此,例题顺利通过。
当然mqtt在python中的应用远不止这么简单,这里只是开个头。

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("$SYS/#")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqtt.eclipse.org", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
 

参考:https://pypi.org/project/paho-mqtt/

 

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值