传感器mqtt树莓派

TL;DR: You can use MQTT and its pub/sub architecture to share data from multiple devices and sensors without much overhead. Here are some starter publisher and subscriber JavaScript clients to help you get started: https://github.com/rdeprey/mqtt-starter.

TL; DR:您可以使用MQTT及其发布/订阅体系结构来共享来自多个设备和传感器的数据,而不会产生太多开销。 以下是一些入门发布者和订阅者JavaScript客户端,可帮助您入门: https : //github.com/rdeprey/mqtt-starter

Over the past few years, I’ve accumulated a fair number of Raspberry Pis and have sensors set up to monitor various things around my home. As the number of sensors has grown, I’ve found myself wanting to create my own “home hub” similar to the Google Nest Hub or Amazon Echo, allowing me to see data from multiple devices at a glance.

在过去的几年中,我已经积累了相当多的Raspberry Pis,并且设置了传感器来监视我家周围的各种事物。 随着传感器数量的增加,我发现自己想要创建自己的类似于Google Nest Hub或Amazon Echo的“家庭中心”,从而使我能够一目了然地查看来自多个设备的数据。

I recently decided to do just that and initially thought that Bluetooth would be the easiest way to simultaneously get data from each device. After all, Bluetooth is a common way to connect commercially produced smart devices. While that is a valid option, I found it required a fair amount of setup though because you need to create custom GATT services for each device and the sensor data that you want to share from it.

我最近决定这样做,并且最初认为蓝牙是同时从每个设备获取数据的最简单方法。 毕竟,蓝牙是连接商业生产的智能设备的常用方法。 尽管这是一个有效的选项,但我发现它需要大量的设置,因为您需要为每个设备以及要与之共享的传感器数据创建自定义GATT服务。

As I was researching my options, I came across MQTT (short for Message Queuing Telemetry Transport), which is an OASIS standard messaging protocol for the Internet of Things (IoT). It’s a publish/subscribe (also known as pub/sub) messaging protocol that’s primary use is to connect remote devices. It has a small codebase, uses minimal network bandwidth, and is very lightweight. In order for MQTT to work, all of the devices have to be on the same network, but this wasn’t a problem given my device configuration.

在研究选项时,我遇到了MQTT(消息队列遥测传输的缩写) ,它是用于物联网(IoT)的OASIS标准消息协议。 这是一种发布/订阅(也称为pub / sub)消息传递协议,其主要用途是连接远程设备。 它具有小的代码库,使用最小的网络带宽,并且非常轻巧。 为了使MQTT正常工作,所有设备都必须位于同一网络上,但是考虑到我的设备配置,这不是问题。

In short, it was perfect for my needs! It might be a great fit for your next project too, so I wanted to share a guide on how to get started with using MQTT.

简而言之,它非常适合我的需求! 这也可能非常适合您的下一个项目,因此我想分享一个有关如何开始使用MQTT的指南。

This guide explains how to implement MQTT in JavaScript, but you can use the protocol in other languages as well. There’s a thorough list of MQTT implementations, tools, and resources available from hobbyquaker on Github that I recommend checking out for further information.

本指南说明了如何在JavaScript中实现MQTT,但是您也可以在其他语言中使用该协议。 Github上的hobbyquaker提供了MQTT实现,工具和资源的完整列表 ,我建议您查看更多信息。

MQTT的基础 (Basics of MQTT)

Before we dive into writing code, let’s first discuss how MQTT works.

在开始编写代码之前,让我们首先讨论MQTT的工作原理。

MQTT的主要功能 (Key Features of MQTT)

MQTT implements the following main tenets of the pub/sub model:

MQTT实现了pub / sub模型的以下主要原则:

  • Clients don’t need to know that other clients exist. To publish or subscribe to messages, clients only need to know the hostname/IP address and the port of the broker.

    客户不需要知道其他客户的存在。 要发布或订阅消息,客户端只需要知道主机名/ IP地址和代理的端口即可。
  • It’s not time dependent. In most cases, MQTT is used to share messages in real-time, but it’s possible for the broker to store messages for clients that aren’t online.

    它与时间无关。 在大多数情况下,MQTT用于实时共享消息,但是代理可以为不在线的客户端存储消息。
  • It works asynchronously, so it doesn’t block client-side rendering.

    它异步工作,因此不会阻止客户端渲染。

发布/订阅体系结构 (Publish/Subscribe Architecture)

At its core, MQTT implements the publish/subscribe architecture to allow multiple devices to publish and subscribe to messages from other devices. It’s different from the client-server model that defines typical website interactions in that instead of clients communicating directly with an endpoint on a server, clients publish messages and other clients subscribe/receive those messages.

MQTT的核心实现了发布/订阅体系结构,以允许多个设备发布和订阅来自其他设备的消息。 它与定义典型的网站交互的客户端-服务器模型的不同之处在于,客户端发布消息,而其他客户端订阅/接收这些消息,而不是客户端直接与服务器上的端点进行通信。

The publishers and subscribers never communicate with each other directly though. A client is never even aware that the other clients exist. Instead, there’s a component called a broker that sits between them and filters all incoming messages, making sure that they’re distributed correctly to subscribers.

但是,发布者和订阅者之间永远不会直接进行通信。 一个客户端甚至从未意识到其他客户端的存在。 相反,有一个称为代理的组件位于它们之间,并过滤所有传入消息,以确保将它们正确分发给订阅者。

Image for post
Example of MQTT Data Flow Between Publishers and Subscribers1
发布者和订阅者之间的MQTT数据流示例1

In the diagram above, the plant moisture sensors and the webpage are clients. Each client publishes data and subscribes to data, which is filtered by the broker and shared with the other clients who are subscribed. In this example, the website is used to render data from messages it subscribes to, but you could also have a backend API or database as a subscriber and persist message data as well.

在上图中,植物湿度传感器和网页是客户端。 每个客户端发布数据并订阅数据,这些数据由代理过滤并与其他订阅的客户端共享。 在此示例中,网站用于呈现其订阅消息中的数据,但是您也可以将后端API或数据库作为订阅者,并保留消息数据。

MQTT代理:如何过滤消息? (The MQTT Broker: How Does it Filter Messages?)

The MQTT broker is integral to the pub/sub architecture of the protocol. It ensures that subscribers only get the messages that they are interested in. It does this using one of the following filtering methods:

MQTT代理是协议的pub / sub体系结构不可或缺的一部分。 它确保订阅者仅获得他们感兴趣的消息。它使用以下过滤方法之一进行此操作:

  • Subject-based

    基于主题
  • Content-based

    基于内容
  • Type-based

    基于类型

Subject-based FilteringWith subject-based filtering, the broker filters messages based on their topic. The subscriber subscribes to the broker for messages on particular topics. Then, the broker makes sure to only forward messages on that topic to that subscriber. The topics are strings that can be filtered on with a limited number of expressions.

基于主题的过滤使用基于主题的过滤,代理可以根据邮件的主题过滤邮件。 订户订阅代理以获取有关特定主题的消息。 然后,代理确保只将有关该主题的消息转发给该订户。 主题是可以使用有限数量的表达式进行过滤的字符串。

Content-based FilteringWith content-based filtering, the broker filters messages based on a specific content filter-language. This requires the content of the message to be known in advance though and can’t be easily changed or encrypted.

基于内容的过滤使用基于内容的过滤,代理可以根据特定的内容过滤器语言过滤邮件。 这要求消息的内容是事先已知的,并且不能轻易更改或加密。

Type-based FilteringType-based filtering allows the broker to filter messages based on their type or class. This is common when using object-oriented languages.

基于类型的筛选基于类型的筛选使代理可以根据消息的类型或类来对其进行筛选。 在使用面向对象的语言时,这很常见。

For our starter setup, we’ll be using subject-based filtering to filter our messages.

对于我们的入门设置,我们将使用基于主题的过滤来过滤消息。

为设备设置MQTT (Setting Up MQTT for Devices)

For this guide, we’re going to get an MQTT broker running and create two MQTT clients: one that behaves as a publisher and one that behaves as a subscriber. In practice, the same client can do both though.

对于本指南,我们将运行一个MQTT代理,并创建两个MQTT客户端:一个充当发布者,另一个充当订阅者。 实际上,同一客户可以同时做这两个事情。

We’ll run the broker and clients in three separate instances of Terminal/Command Prompt on a single computer. You can then use this setup as a starting point to implement MQTT in your own applications so that your microcontrollers can share data with each other.

我们将在一台计算机上的终端/命令提示符的三个独立实例中运行代理和客户端。 然后,您可以将该设置用作在自己的应用程序中实施MQTT的起点,以便您的微控制器可以彼此共享数据。

设置MQTT代理 (Setting Up the MQTT Broker)

There are a number of open source MQTT brokers, but Mosquitto is one of the most popular. To configure a Mosquitto MQTT broker on your computer, follow these steps:

有许多开源MQTT经纪人,但Mosquitto是最受欢迎的经纪人之一。 要在您的计算机上配置Mosquitto MQTT代理,请按照下列步骤操作:

Installing Mosquitto on Windows:

在Windows上安装Mosquitto:

  1. Go to https://mosquitto.org/download/ and download the appropriate .exe file for your computer.

    转到https://mosquitto.org/download/并为您的计算机下载适当的.exe文件。

  2. Install the download by following the prompts.

    按照提示安装下载。

Installing Mosquitto on Mac and Linux:

在Mac和Linux上安装Mosquitto:

  1. Open your Terminal.

    打开您的终端。
  2. If you don’t have Homebrew installed, follow the instructions on the Homebrew website to install it.

    如果未安装Homebrew,请按照Homebrew网站说明进行安装。

  3. After installing Homebrew, use it to install Mosquitto: brew install mosquitto. (If Terminal gives you an error about brew not being a recognized command, then close Terminal, re-open it, and try the command again.)

    安装Homebrew之后,使用它来安装Mosquitto: brew install mosquitto 。 (如果终端机给您一个错误信息,那就是brew不能被识别,请关闭终端机,重新打开它,然后重试该命令。)

  4. When Homebrew is finished installing Mosquitto, you should see a message indicating that it’s been installed with a default configuration file.

    当Homebrew完成Mosquitto的安装时,您应该看到一条消息,指示已使用默认配置文件进行安装。

Running MosquittoMosquitto uses a configuration file to determine security settings, persistence settings, and more. For our starter project, we’ll use the default file, but you can learn more about the available settings through the Mosquitto website. The default file will be located in a different place depending on your operating system:

运行Mosquitto Mosquitto使用配置文件来确定安全设置,持久性设置等。 对于我们的入门项目,我们将使用默认文件,但您可以通过Mosquitto网站了解有关可用设置的更多信息 。 根据您的操作系统,默认文件将位于其他位置:

  • Windows: c:\mosquitto\mosquitto.conf

    Windows: c:\mosquitto\mosquitto.conf

  • Mac: /usr/local/etc/mosquitto/mosquitto.conf

    Mac: /usr/local/etc/mosquitto/mosquitto.conf

  • Linux: /etc/mosquitto/mosquitto.conf

    Linux: /etc/mosquitto/mosquitto.conf

To start Mosquitto with the default configuration, run the following command and substitute the location of the configuration file based on your operating system:

要使用默认配置启动Mosquitto,请运行以下命令并根据您的操作系统替换配置文件的位置:

mosquitto -c [configuration file location, such as 

When Mosquitto runs, you should see something like this in your Terminal or Command Prompt:

当Mosquitto运行时,您应该在终端或命令提示符中看到以下内容:

Image for post
Mosquitto running in a Terminal on a Mac
Mosquitto在Mac的终端中运行

The third and fourth lines of the output show that there’s an IPv4 and IPv6 listen socket open on port 1883. We’ll need this information when we configure our clients, so keep it handy.

输出的第三和第四行显示在端口1883上有一个IPv4和IPv6侦听套接字打开。在配置客户端时,我们将需要此信息,因此请随时使用。

Leave this Terminal/Command Prompt window open because Mosquitto needs to be running in order for the clients to work.

使此“终端/命令提示符”窗口保持打开状态,因为Mosquitto需要运行才能使客户端正常工作。

创建一个MQTT Publisher客户端 (Creating an MQTT Publisher Client)

For the MQTT publisher client, return to your Terminal/Command Prompt and create a new sub-folder within mqtt-starter called publisher-client. Then, do the following in your new folder:

对于MQTT发布者客户端,返回到终端/命令提示符,并在mqtt-starter创建一个名为publisher-client的新子文件夹。 然后,在新文件夹中执行以下操作:

  1. Enter npm init and follow the prompt to create a package.json file for your publisher client. You can set the values in this file to anything you want. The primary purpose for this step is to create a package.json file that can be used to manage the libraries installed for the project.

    输入npm init并按照提示为发布者客户端创建package.json文件。 您可以将此文件中的值设置为所需的任何值。 此步骤的主要目的是创建一个package.json文件,该文件可用于管理为项目安装的库。

  2. Enter npm install --save mqtt to install the MQTT library from npm.

    输入npm install --save mqtt以从npm安装MQTT库。

Next, open your favorite code editor and create a new file in the publisher-client folder called index.js (this file name should match what’s in your package.json file as the “entry point”).

接下来,打开您喜欢的代码编辑器,并在名为index.jspublisher-client文件夹中创建一个新文件(此文件名应与package.json文件中的文件名匹配为“入口点”)。

Then, in the index.js file, add the following code. The second line tells the client which broker to connect to. Use the port that you have Mosquitto running on after localhost: .

然后,在index.js文件中,添加以下代码。 第二行告诉客户端要连接到哪个代理。 使用在localhost:之后运行Mosquitto的端口。

const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://localhost:1883');

Next, add a connection event handler that will run with the client connects to the broker. Our broker will filter messages using the subject-based filtering approach and for our example, we’ll use sensor as the topic. You can choose any string for your topic though.

接下来,添加将与客户端一起运行的connection事件处理程序连接到代理。 我们的经纪人将使用基于主题的过滤方法来过滤邮件,对于我们的示例,我们将使用sensor作为主题。 您可以为主题选择任何字符串。

client.on('connect', function () {
client.publish('sensor', 'I am connected!');
});

The code snippet above uses the client.publish function to publish the message “I am connected!” to the sensor topic when the client first connects to the broker.

上面的代码段使用client.publish函数发布消息“我已连接!”。 客户端首次连接到代理时,转到sensor主题。

That’s great and all, but it’s not very interesting is it? Let’s add something a little more dynamic to the mix so that we can see the client regularly publish updates. Add the following to your index.js file to publish a random number to the sensor topic every 15 seconds:

太好了,但不是很有趣吗? 让我们为混合添加更多动态的东西,以便我们可以看到客户端定期发布更新。 将以下内容添加到index.js文件中,以每15秒向sensor主题发布一个随机数:

setInterval(function() {
client.publish('sensor', Math.random().toString()); // published message must be a string
}, 15000); // every 15 seconds

One thing to note is that the message you publish has to be a string. That’s why the random number generated by Math.random() in the example above is cast to a string.

需要注意的一件事是您发布的消息必须是字符串。 这就是在 上面的示例中 Math.random() 生成的随机数被 Math.random() 转换为字符串的原因。

To make our task easy to run, let’s add the following to the scripts section of our package.json file: "start": "node index.js" . Then, run npm start in your Terminal/Command Prompt in the publisher-client directory to start your client. You won’t see anything happening in the console for the publisher client; you’ll see the output in the subscriber client console after the next set of steps.

为了使我们的任务易于运行,我们将以下内容添加到package.json文件的scripts部分: "start": "node index.js" 。 然后,在publisher-client目录的终端/命令提示符中运行npm start以启动客户端。 您不会在发布者客户端的控制台中看到任何事件; 在下一组步骤之后,您将在订户客户端控制台中看到输出。

Let’s now create an MQTT subscriber client that can subscribe to the sensor topic using our MQTT broker.

现在,让我们创建一个可以使用我们的MQTT代理订阅sensor主题的MQTT订阅者客户端。

Creating an MQTT Subscriber ClientFor the MQTT subscriber client, return to your Terminal/Command Prompt and create a new sub-folder within mqtt-starter called subscriber-client. Then, do the following in your new folder:

创建MQTT订户客户端对于MQTT订户客户端,返回到终端/命令提示符,并在mqtt-starter创建一个名为subscriber-client的新子文件夹。 然后,在新文件夹中执行以下操作:

  1. Enter npm init and follow the prompt to create a package.json file for your subscriber client, similar to the one you created for your publisher client.

    输入npm init并按照提示为订户客户端创建package.json文件,类似于为发布者客户端创建的package.json文件。

  2. Enter npm install --save mqtt to install the MQTT library from npm.

    输入npm install --save mqtt以从npm安装MQTT库。

Next, open your favorite code editor and create a new file in the subscriber-client folder called index.js.

接下来,打开您喜欢的代码编辑器,并在名为index.jssubscriber-client文件夹中创建一个新文件。

In the index.js file, add the following code. The second line tells the client which broker to connect to. Use the port that you have Mosquitto running on after localhost: . We’re connecting our subscriber client to the same broker that the publisher client is connected to.

index.js文件中,添加以下代码。 第二行告诉客户端要连接到哪个代理。 使用在localhost:之后运行Mosquitto的端口。 我们正在将订阅者客户端连接到发布者客户端连接到的同一代理。

const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://localhost:1883');

Next, add a connection event handler that will subscribe the client to a topic. Since our publisher client is publishing messages to the sensor topic, let’s subscribe to the sensor topic so that we can get the messages it sends. When the client subscribes, it will log a message to the console.

接下来,添加一个connection事件处理程序,该处理程序将使客户端订阅主题。 由于我们的发布者客户端正在将消息发布到sensor主题,因此让我们订阅sensor主题,以便我们可以获取它发送的消息。 客户端订阅后,它将在控制台中记录一条消息。

client.on('connect', function () {
client.subscribe('sensor', function (err) {
if (!err) {
console.log('I am subscribed to the sensor topic!');
}
});
});

Let’s also add a message event handler that will log the messages that our subscriber client receives on the sensor topic.

我们还添加一个message事件处理程序,该事件处理程序将记录我们的订户客户端在sensor主题上收到的消息。

client.on('message', function (topic, message) {
console.log(message.toString());
});

Similar to the publisher client, let’s add the following to the scripts section of our package.json file for the subscriber client: "start": "node index.js" . Then, run npm start in your Terminal/Command Prompt in the subscriber-client directory to start your client.

与发布者客户端类似,让我们在订阅者客户端的package.json文件的scripts部分中添加以下内容: "start": "node index.js" 。 然后,在“ subscriber-client目录下的“终端/命令提示符”中运行npm start以启动客户端。

You should now have Mosquitto running in one Terminal/Command Prompt window, your publisher client in another, and your subscriber client in a third. If you wait 15 seconds, you should start to see random numbers printed to the console in the subscriber client window!

现在,您应该使Mosquitto在一个“终端/命令提示符”窗口中运行,您的发布者客户端在另一个窗口中,而您的订户客户端在第三个窗口中运行。 如果等待15秒,您应该开始在订户客户端窗口中看到随机数字打印到控制台!

Image for post
MQTT Subscriber Example
MQTT订阅者示例

We now have a working MQTT configuration with a broker and two clients. You could extend this to more clients with many publishing messages to the sensor topic and many subscribing to receive those messages. You can also configure additional topics, add security so that only certain applications can subscribe or publish to a topic, and have different devices on the same network connected as clients to a single broker. It’s a pretty flexible way to share data among multiple devices.

现在,我们有了带有代理和两个客户端的有效MQTT配置。 您可以将其扩展到更多的客户端,向sensor主题发布许多消息,并进行许多订阅以接收这些消息。 您还可以配置其他主题,增加安全性,以便只有某些应用程序可以订阅或发布该主题,并且可以将与客户端相同的同一网络上的不同设备连接到单个代理。 这是在多个设备之间共享数据的一种非常灵活的方式。

Hopefully, this guide will help you start using MQTT in your projects! Here’s a full example of the publisher and subscriber clients in Github.

希望本指南将帮助您开始在项目中使用MQTT! 这是Github中发布者和订阅者客户的完整示例。

Icon CreditsThe icons used in the diagram for this guide are from Flaticon: plant pot, chip free, and code.

图标信用本指南的图表中使用的图标来自Flaticon: 花盆 ,无代码

翻译自: https://medium.com/@rdeprey/use-mqtt-to-share-sensor-data-among-multiple-devices-bc82d1a44ea4

传感器mqtt树莓派

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐