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

相关推荐
李游Leo17 小时前
Node.js 多版本管理与 nvm/nvs 使用全流程(含国内镜像加速与常见坑)
node.js
Q_Q196328847518 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
陈随易1 天前
适合中国宝宝的AI编程神器,文心快码
前端·后端·node.js
Q_Q19632884751 天前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php
EndingCoder1 天前
Electron 新特性:2025 版本更新解读
前端·javascript·缓存·electron·前端框架·node.js·桌面端
machinecat1 天前
node,小程序合成音频的方式
前端·node.js
草木红1 天前
express 框架基础和 EJS 模板
arcgis·node.js·express
亮子AI2 天前
【npm】npm 包更新工具 npm-check-updates (ncu)
前端·npm·node.js
Yvonne爱编码2 天前
构建高效协作的桥梁:前后端衔接实践与接口文档规范详解
前端·git·ajax·webpack·node.js
Juchecar2 天前
AI教你常识之 ESM + Express + Vue3 + CSV文件 + Pinia + CRUD
node.js