树莓派实现MQTT通信

之前我在linux上有搭建过MQTT环境,我们也在树莓派上搭建这样的环境试试

当然你不搭建也可以,毕竟是和linux同一个道理


使用ssh登录树莓派,搭建完毕后,我们输入指令启动程序:

mosquitto -c /etc/mosquitto/mosquitto.conf -d  

我们打开两个窗口,在一个(订阅)窗口输入:

mosquitto_sub -t hello  

另一个(发布)窗口输入:

mosquitto_pub -t hello -h localhost -m "hello world!"  

程序截图:


这样我们依旧能够通过指令来实现两个服务器之间的通信,如果同一网段的IP地址不同,那么-h的后面添加IP地址就行



但是我们要怎样来通过程序进行通信呢??我们先来看一张图片:


图片参考:https://blog.csdn.net/xukai871105/article/details/39255089

其实这张图片是不完善的,树莓派在这里可以做信息发布者,也可以做代理服务器,更可以做消息订阅者


这里我们就要新介绍一个库,它就是paho-mqtt,输入:

pip install paho-mqtt


我们将图简化成只有一个发布者和订阅者,先来看看订阅者的代码:

# mqttc.py
import paho.mqtt.client as mqtt                # 导入mqtt客户端库

def on_connect(client, userdata, flags, rc):            # 连接成功回调函数
        print("Connected with result code " + str(rc))
        client.subscribe("serial")                      # 订阅serial主题

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

try:
    client.connect("localhost", 1883, 60)
    client.loop_forever()            # 循环等待消息
except KeyboardInterrupt:
    client.disconnect()              # 关闭连接
如果有哪几个参数不明白,可以浏览我上面给你的网站


我们不急着先发布者的代码,运行mqttc.py,并打开另一个树莓派窗口,输入指令:

mosquitto_pub -t serial -h localhost -m "hello world!"


确认订阅收到serial主题的消息后,我们再来看发布者的代码:

# mqttc.py
import paho.mqtt.publish as publish

publish.single("serial", payload="hello world!",
        qos=0,hostname="localhost")

其实主要的代码简洁得不行,直接就是一行


最后再来运行mqttc.py的代码,程序截图:


我们成功收到主题为serial的hello world!的信息


别以为到这里就结束了,我们还要通过之前学习的树莓派通过串口接发数据其中的serial模块,结合在一起构成一个真正从串口接收数据并将其发送至服务器的发布者的角色

我们只需在之前的serial代码中添加几句就行

程序如下:

# -*- coding: utf-8 -*
import serial
import time
import paho.mqtt.publish as publish

ser = serial.Serial('/dev/ttyAMA0',115200)
if ser.isOpen == False:
    ser.open()
ser.write(b"Raspberry pi is ready")
try:
    while True:
        size = ser.inWaiting()
        if size != 0:
            response = ser.read(size)        # 如果消息过长可以改为具体数字
          # print(response)
            publish.single("serial", payload=response,
                            qos=0,hostname="localhost")
          # ser.flushInput()                    # 不清除输入缓存区
            time.sleep(0.1)
except KeyboardInterrupt:
    print('quit')
    ser.close()


之后再打开一个树莓派窗口(服务器)输入:

mosquitto_sub -t serial


最后打开串口调试助手,运行上述python程序,成功接收到Raspberry pi is ready的消息后,我们从调试助手发送消息



作为服务器的树莓派窗口成功收到消息:





猜你喜欢

转载自blog.csdn.net/weixin_41656968/article/details/80187955