65.9K
CodeProject 正在变化。 阅读更多。
Home

Raspberry Pi 2,n中的第2篇 - Pi作为IoT消息代理

starIconstarIconstarIconstarIconstarIcon

5.00/5 (17投票s)

2016年6月17日

CPOL

9分钟阅读

viewsIcon

34129

使用Mosquitto将Raspberry Pi配置为MQTT消息代理。

引言

在本篇系列文章的第二篇中,我们将介绍令人惊叹的Raspberry Pi,并将使用Mosquitto将其配置为MQTT消息代理。Mosquitto是一个轻量级但功能强大的发布/订阅模式消息系统,可以安装在各种平台上。本教程的目标是在Raspberry Pi 2上安装、配置和测试该软件,使其能够不仅在Pi上,还在其他计算机上发布和订阅消息。

1107378/pi2-mqtt_spy-3.png

如果您尚未阅读介绍如何加载和配置操作系统的第一篇文章,可以在 Raspberry Pi 2, 1 of n - Initial setup Code Project 上找到。虽然不是必读内容,但我鼓励您在刚开始接触Linux或Pi时阅读它。

本文或多或少是我用于使用Mosquitto将Raspberry Pi配置为MQTT消息代理的步骤的记录。我参考了SwitchDoc Labs[3]的教程,并对其进行了修改以适应我的特定需求。在未来的文章中,我计划连接各种设备,例如:ESP8266-12E WiFi模块、Arduino UNO等嵌入式处理器板,以及可能还有其他设备,并希望在夏天天气太热不适合徒步露营时完成。

环境

我为此项目设置的开发环境是:

  • 运行64位Windows 7操作系统的Windows桌面,配备AMD-FX-8350 8核处理器和32GB内存。
  • Raspberry Pi 2, BCM2709 ARMv7 4核,1GB RAM,运行Raspian Jesse操作系统。我最初加载和配置此项目的版本是新的Raspbian Jessie Lite版本,但它没有GUI,我计划在未来的文章中使用NginX和WebSockets为控制各种设备提供前端,因此我恢复使用完整版本,并从中删除了不必要的内容。Pi上的WiFi由 edimax dongle 提供。
  • 运行Ubuntu 12.04 LTS的VirtualBox虚拟机,我将其配置得与Pi几乎相同,但修改了一些特定于Ubuntu的项。虽然我已经为自己设置好了,但我不会深入介绍我是如何做到的,我会将其留给您作为额外的练习。祝您好运,学徒!

先决条件 - 设置静态IP地址

尽管此步骤是可选的,但我强烈建议您在Pi[8,11]上设置静态IP地址。如果不这样做,Pi在启动时可能会选择不同的IP地址,每次启动Pi时编辑配置文件将非常麻烦。对我来说,使用便宜的 edimax dongle是一个轻松的过程。如果您愿意等待,可以通过eBay购买802.11 dongle,价格约为2美元/个。我订购了几个,它们效果相当不错,尽管我还没有确定是否会在生产环境中使用它们。

此处描述的程序使用edimax dongle,但应适用于Pi支持的任何兼容WiFi dongle。在编辑配置我们的网络所需的系统文件之前,我们需要收集一些信息。

 
#To display current network info type;
ifconfig
    

输出应与此类似;

wlan0   Link encap:Ethernet HWaddr b8:27:eb:a8:cf:a4
        inet addr:192.168.254.20 Bcast:192.168.254.255 Mask:255.255.255.0
        UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
        RX packets:161 errors:0 dropped:0 overruns:0 frame:0
        TX packets:227 errors:0 dropped:0 overruns:0 carrier:0
        collisions:0 txqueuelen:1000
        RX bytes:26075 (25.4 KiB) TX bytes:46356 (45.2 KiB)
    

我们正在寻找的是inet addr和Mask值,对我来说,地址是192.168.254.20掩码是255.255.255.0,在大多数情况下都是如此。接下来,我们需要找到网关地址。

#To display network gateway address type;            
netstat -n -r
    

输出应类似于此;

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.254.254   0.0.0.0         UG        0 0          0 eth0
192.168.254.0     0.0.0.0         255.255.255.0   U         0 0          0 eth0
    

从中我们得到目标或网络地址是192.168.254.0网关地址是192.168.254.254,现在我们已准备好配置我们的网络。

我们需要修改的第一个文件是wpa_supplicant[12]文件。wpa_supplicant[13]实现了无线网络的安全协议。[13]

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
    ssid="Your SSID Here"
    psk="YourPresharedKeyHere"
}
    

请注意,“network={”中没有空格,这是故意的。将ssid和psk值替换为您的无线网络值,然后保存并关闭文件。我使用nano编辑这些文件,保存和退出的过程是按ctrl+X,然后在询问是否保存文件时按"Y"

接下来,我们将继续编辑网络接口文件,在那里我们将配置wlan0无线网络适配器。使用您在前面步骤中收集的值,并将它们插入文件中的相应位置,如下所示。

allow-hotplug wlan0
iface default inet static
    wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
    address 192.168.254.20
    netmask 255.255.255.0
    network 192.168.254.0
    gateway 192.168.254.254
    

重启Pi,然后尝试从另一台机器ping,或使用您选择的浏览器访问网站。IceWeasel,即Firefox,是Jessie预装的。如果一切顺利,您应该已上线并准备继续,否则请重新访问前面的步骤或搜索适合您特定硬件配置的解决方案。

安装Mosquitto

安装Mosquitto相当直接,我们将配置代理在端口1883上监听以进行测试,它默认是端口80。

在Pi上打开一个终端,一次输入以下命令。

sudo wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients
    
  1. wget[4]代表“web get”,它是一个实用程序,可以递归地从网站下载文件和目录结构。在这种情况下,我们正在获取一个GPG,Gnu Privacy Guard密钥,它允许提供者使用多功能密钥系统加密和签名您的数据和通信。
  2. apt-key[3]用于管理apt(高级打包工具)用于身份验证软件包的密钥列表。
  3. 更改目录并使存储库可供apt使用。
  4. 获取存储库文件,其中包含指向要下载包的URL的链接。
  5. 使用apt-get[5]更新apt信息
  6. 最后安装Mosquitto和客户端。客户端提供mosquitto_pub和mosquitto_sub实用程序。我们将在稍后的测试阶段使用它们!

如果一切顺利,Mosquitto应该已经安装并且默认已启动。由于我们需要配置它,因此需要停止它。请参阅下一节了解如何停止Mosquitto。

启动/停止Mosquitto

当Pi启动时,它会自动启动Mosquitto,所以我们要学习如何启动、停止和重启该应用程序。

#To start the Mosquitto service
sudo /etc/init.d/mosquitto start
#To stop the Mosquitto service
sudo /etc/init.d/mosquitto stop
#To restart the Mosquitto service
sudo /etc/init.d/mosquitto restart
    

配置先决条件 - 安装mqtt_spy

这也不是一个强制步骤,但在配置/测试阶段,我发现mqtt_spy[7]实用程序非常宝贵。mqtt-spy是一个JavaFX应用程序,因此理论上,只要安装了适当版本的Java 8,它应该可以在任何操作系统上运行。

当mqtt_spy首次启动时,用户会看到以下窗口,敏锐的观察者会注意到应用程序认为我拥有的版本不是最新的,但它确实是?无论如何,显示已配置连接的部分是我们主要关注的。该应用程序预装了几个常见的配置,如localhost等。

1107378/pi2-mqtt_spy-0.png

为了我们的目的配置连接,请从主菜单中选择Connections=>New Connection菜单项。这将显示如下所示的窗口,输入与您的配置相关的信息,并以适当的名称保存。

1107378/pi2-mqtt_spy-1.png

一旦建立连接,我们就可以开始工作了。如本教程前面所述,MQTT协议是发布/订阅模式,因此下面的窗口分为2个部分;上面是发布部分,下面是订阅部分。

首先,通过单击New按钮创建一个新的订阅,并在弹出的对话框中输入主题信息。输入主题后,单击subscribe按钮。

接下来,我们将向刚刚配置的主题发布消息。在发布部分,输入主题、消息,然后单击Publish按钮。消息应显示在订阅部分的Data文本框中。看,就是这么简单,是不是很酷?

1107378/pi2-mqtt_spy-2.png

在教程的其余部分,我将引用mqtt_spy实用程序。如果您没有安装它,请忽略它,因为我还会提供Mosquitto客户端命令行命令,以便从Linux终端测试配置。配置mqtt_spy时,请单击主窗口中的连接按钮断开连接,这将导致按钮变为红色,进行适当的更改,然后再次单击连接按钮。如果连接成功,按钮将变为绿色。

配置Mosquitto

在接下来的部分中,我们将讨论Mosquitto的各种配置运行方式以及我们将用于测试配置的技术。当Mosquitto启动时,它会在/etc/mosquitto/conf.d目录中查找所有以.conf为扩展名的文件[10],如果找到,则使用它们来配置Mosquitto。我们将创建一个文件/etc/mosquitto/conf.d/mosquitto.conf,并输入以下代码段中概述的数据。

配置Mosquitto - 无安全

这是基本配置,没有安全措施,监听IP地址localhost上的端口80。使用您选择的编辑器编辑/etc/mosquitto/conf.d/mosquitto.conf文件,保存并重启Mosquitto。

# Boolean value that determines whether clients that connect without providing a username are 
# allowed to connect. If set to false then another means of connection should be created to 
# control authenticated client access. Defaults to true. 
allow_anonymous true
#
# Listen for incoming network connection on the specified port. A second optional argument 
# allows the listener to be bound to a specific ip address/hostname. If this variable is used 
# and neither the global bind_address nor port options are used then the default listener will 
# not be started.
# listener port [bind address/host]
listener 1883 192.168.254.20
    

测试Mosquitto配置 - 无安全

使用mqtt_spy实用程序,只需在Server URI文本框中输入IP地址,应用并连接。然后转到pub/sub窗口并输入相应的信息。

从命令行测试时,您需要打开2个窗口;一个用于发布,一个用于订阅。输入以下内容,其中topic = 'hello/world',端口为1883。

#In the publish terminal window
sudo mosquitto_pub -d -t hello/world -m 'The message'
                
#In the subscribeterminal window
sudo mosquitto_sub -d -t hello/world
    

配置Mosquitto - 带密码认证

为了使用密码认证,我们需要编辑mosquitto.conf文件,并添加password_file指令,指向pwfile的路径。

# Boolean value that determines whether clients that connect without providing a username are 
# allowed to connect. If set to false then another means of connection should be created to 
# control authenticated client access. Defaults to true. 
allow_anonymous false
#
# Listen for incoming network connection on the specified port. A second optional argument 
# allows the listener to be bound to a specific ip address/hostname. If this variable is used 
# and neither the global bind_address nor port options are used then the default listener will 
# not be started.
#listener port [bind address/host]
listener 1883 192.168.254.20
#
# Set the path to a password file. If defined, the contents of the file are used to control 
# client access to the broker. The file can be created using the mosquitto_passwd(1) utility.
# If mosquitto is compiled without TLS support (it is recommended that TLS support is 
# included), then the password file should be a text file with each line in the format 
# "username:password", where the colon and password are optional but recommended. 
# If allow_anonymous is set to false, only users defined in this file will be able to connect. 
# Setting allow_anonymous to true when password_fileis defined is valid and could be used with 
# acl_file to have e.g. read only guest/anonymous accounts and defined users that can publish.
#password_file file path
password_file /etc/mosquitto/pwfile
    

接下来,我们需要使用mosquitto_passwd实用程序创建pwfile,方法是在终端窗口中输入以下命令。

sudo mosquitto_passwd -c /etc/mosquitto/pwfile username
    

系统会提示您输入一次密码,然后再次确认。

Mosquitto测试 - 带密码认证

使用mqtt_spy,选择菜单选项Connections=>Manage Connections,然后选择Security选项卡,然后选择User auth.选项卡。勾选Enable User authentication复选框,并输入配置pwfile时使用的用户名和密码。然后连接并配置pub/sub信息。

使用pub/sub终端输入以下命令;

#In the publish terminal window
sudo mosquitto_pub -d -t hello/world -p 1883 -u 'username' -P 'password' -m 'The message'
                
#In the subscribeterminal window
sudo mosquitto_sub -d -t hello/world -p 1883 -u 'username' -P 'password'
    

摘要

我发现Mosquitto易于使用,功能强大,文档和教程充足,足以让我入门,并且足够直观,我可以在短时间内安装和配置它。为本教程做了几次,都很容易,因此我的意图是在未来的文章和本系列最终目标的家庭IoT项目中将其投入使用。

参考文献

© . All rights reserved.