MQTT到串口的转发(node.js)

本文针对以下应用场景:已有通过串口通信的设备或软件,想要实现跨网的远程控制。

node.js安装

Node.js --- Run JavaScript Everywhere下载LTS版本安装包,运行安装程序。(傻瓜安装,按提示点击即可)

设置环境变量,在path新增node.js安装路径

此时从命令提示符中输入npm -v和node -v可以看到版本表示安装成功

因为要用到mqtt和串口,所以需要安装对应的模块

复制代码
npm install mqtt
npm install serialport

接下来就是源码,我们的配置文件名为config.json,里面包含了连接mqtt服务器相关的信息,订阅及发布的主题等。

首先读取配置文件,如果不存在则创建文件并写入配置参数。如果配置文件存在则读取数据,并使用读到的配置信息去连接mqtt服务器以及订阅和发布消息。在这里我使用了固定串口,如果有需要调整串口也可以放到配置文件中。

整个程序的功能是连接mqtt服务器并订阅一个主题,如果从该主题收到数据则从串口发出,如果串口收到数据则从另一个主题发布出去。

复制代码
const mqtt = require('mqtt');
const {SerialPort} = require('serialport');
const fs=require('fs');
const filepath='config.json';

var config=null;
fs.readFile(filepath, 'utf8', (err, data) => {
    if (err) {
      console.error('Error reading configuration:', err);
      config={
        mqtt_config:{
            url:'mqtt://39.105.166.225:1883',
            options:{
                username: 'admin',
                password: '123456',
                clientid: 'mushike',
                keepalive:60,
                qos:1, 
            },
        },
         sub_config:{
            subtopic1:'test111',
            subtopic2:'test333',
        },
        pub_config:{
            pubtopic1:'test222',
            pubtopic2:'test444',
        },    
    };
    fs.writeFile(filepath,JSON.stringify(config,null,2),(err)=>{
        if(err)
        {
            console.error('Error creating file:', err);
        }
        else
        {
            console.log('File created successfully!');
        }
    });
    } else {
      const storedConfig = JSON.parse(data);
      config=storedConfig;
    };
    // 连接 MQTT Broker 并订阅主题
    const client = mqtt.connect(config.mqtt_config.url,config.mqtt_config.options);

    client.on('connect', function () {
        console.log('Connected to MQTT broker');
        client.subscribe(config.sub_config.subtopic1);
      });
      
      // 监听 MQTT 消息
      client.on('message', function (topic, message) {
        console.log('Received message from MQTT:', message);
        port.write(message.toString() + '\n'); // 将收到的消息写入串口
      });

      client.on('error', function (err) {
        console.error('Error connecting to MQTT broker:', err);
      });
  });

const portSettings = {
    path:'COM6',
    baudRate: 9600,
    dataBits: 8, // 数据位
    stopBits: 1, // 停止位
    parity: 'none', // 奇偶校验位
    autoOpen:true
  };

// 串口设置
const port = new SerialPort(portSettings);

port.on('open',function(){
    console.log('serial is open');
    port.on('data', function(data) {
        console.log('Data received:', data);
        client.publish(config.pub_config.pubtopic1,data);
      });
});

运行程序使用node test.js

相关推荐
labixiong1 天前
理解pnpm的本质,如何通过高效管理提升项目效率
前端·javascript·node.js
良木林2 天前
Node.js基础:模块化与包
开发语言·前端·node.js
q***49862 天前
Node.js卸载超详细步骤(附图文讲解)
node.js
極光未晚2 天前
Node.js的"老伙计":Express框架入门记
前端·node.js
WindrunnerMax2 天前
基于 NodeJs 的分布式任务队列与容器优雅停机
javascript·后端·node.js
yifengyiyufjq2 天前
Docker 镜像制作教程
java·docker·node.js
要加油哦~2 天前
nrm | npm 的镜像管理工具
前端·npm·node.js·nrm
e***28292 天前
Windows 上彻底卸载 Node.js
windows·node.js
d***9353 天前
Webpack、Vite区别知多少?
前端·webpack·node.js
q***06293 天前
Node.js使用教程
node.js·编辑器·vim