学习总结(二) node.js服务器如何使用net模块向硬件发送命令与接收数据?

服务器server.js:

const net = require("net");  //此模块用于tcp/ip通讯

当收到get请求时:

server.get("/cfjcApi/v1/SkyTempHudi", (req, res) => {

    let client = new net.Socket();

    client.connect(网络模块端口, 网络模块Ip, () => {    //此模块需要设置好波特率等通讯参数

    let cmd = dataCtl.makeCmd(0, parseInt("0XA1"), 0, []); //调用函数生成要发送的命令

    client.write(cmd);                                                             //发送命令

    client.on("data", function (data) {                                     //当收到数据时

        client.end();                                                                 //断开与485转网络模块的连接 

        return res.send({ result: Array.from(data), type: 1 })   //将收到的数据与设备类型发送至请求方

    });

});

}

浏览器:

async function MeasureselectedStore() {

    let res = await fetch(`http://192.168.0.163:3000/cfjcApi/v1/SkyTempHudi`);

    let json = await res.json();

    let skytemphudi = json;

    if (skytemphudi.type === 1) {//对应数据处理}

    else if (skytemphudi.type === 2) {//对应数据处理}

}

这是测量通用设备的方式,不涉及根据设备位置查找设备类型.

测量某个位置的设备时,

服务器在res.query.storename中得到设备位置,然后根据设备位置去查找设备类型,然后发送

浏览器则fetch(`http://192.168.0.163:3000/cfjcApi/GrainTempHudi?storename=${storename}`);

你可能感兴趣的:(学习,node.js,服务器,javascript)