前言
随着物联网技术的逐步成熟,越来越多的设备开始联网,这也带动了 MQTT 协议的发展。MQTT 协议是一种轻量级的通信协议,非常适用于物联网领域中设备之间的通信。在 Node-RED 可视化编程工具中,可以使用 node-red-contrib-sts-mqtt
这个 npm 包来实现 MQTT 协议的通信。本文旨在介绍该 npm 包的使用方法,并提供示例代码以方便读者加深理解。
安装
使用 npm 命令安装 node-red-contrib-sts-mqtt
:
npm install node-red-contrib-sts-mqtt
使用
1. 添加 MQTT 发布节点
在 Node-RED 编辑器中,将 MQTT 发布节点拖入流程画布,配置如下图所示:
其中,MQTT 服务器地址和端口号请填写自己 MQTT 服务器的地址和端口号。
2. 添加 MQTT 订阅节点
在 Node-RED 编辑器中,将 MQTT 订阅节点拖入流程画布,配置如下图所示:
其中,MQTT 服务器地址和端口号请填写自己 MQTT 服务器的地址和端口号。Topic
字段可以填写需要订阅的主题。
3. 测试
添加完 MQTT 发布节点和 MQTT 订阅节点后,就可以测试 MQTT 的发布和订阅功能了。在 MQTT 发布节点中输入需要发布的内容,节点会将内容发布到 MQTT 服务器上,同时 MQTT 订阅节点会订阅发布的内容并将其输出到 Debug 窗口中,效果如下所示:
示例代码
以下为一个简单的示例,首先发布一条消息到 MQTT 服务器上,然后再通过订阅节点将该消息输出到 Debug 窗口中:
[{"id":"f53b858.e281c18","type":"mqtt out","z":"53b154a6.dc6934","name":"","topic":"test","qos":"","retain":"","broker":"e1eb88d4.437448","x":394.5,"y":115.5,"wires":[]},{"id":"ef80aaa2.1ceb38","type":"mqtt in","z":"53b154a6.dc6934","name":"","topic":"test","broker":"e1eb88d4.437448","x":129.5,"y":116.5,"wires":[["29055783.97172c"]]},{"id":"29055783.97172c","type":"debug","z":"53b154a6.dc6934","name":"","active":true,"console":"false","complete":"false","x":385.5,"y":171,"wires":[]},{"id":"e1eb88d4.437448","type":"mqtt-broker","z":"","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""}]
总结
本篇文章详细介绍了 node-red-contrib-sts-mqtt
npm 包的使用方法,并提供了示例代码帮助读者更好地理解。希望对大家有所帮助,也希望大家能在物联网领域中有所收获。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/600559e381e8991b448d77bb