首页 > 解决方案 > 这是通过 websocket 解析传入 JSON 并根据消息类型进行响应的正确方法吗?

问题描述

因此,我使用 OCPP 1.6 JSON 通过 websocket 从充电点接收 JSON。我正在尝试使用 Node.js 解析消息并根据消息的内容做出适当的响应

这是我收到的消息:

[ 2,
  'bc7MRxWrWFnfQzepuhKSsevqXEqheQSqMcu3',
  'BootNotification',
  { chargePointVendor: 'AVT-Company',
    chargePointModel: 'AVT-Express',
    chargePointSerialNumber: 'avt.001.13.1',
    chargeBoxSerialNumber: 'avt.001.13.1.01',
    firmwareVersion: '0.9.87',
    iccid: '',
    imsi: '',
    meterType: 'AVT NQC-ACDC',
    meterSerialNumber: 'avt.001.13.1.01' } ]

在这种情况下,它是“BootNotification”消息,我需要用“Accepted”消息对其进行响应。

这是我的代码:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {

    //Make incoming JSON into javascript object
    var msg = JSON.parse(message)

    // Print whole message to console
    console.log(msg)

    // Print only message type to console. For example BootNotification, Heartbeat etc...
   console.log("Message type: " + msg[2])

    // Send response depending on what the message type is
    if (msg[2] === "BootNotification") {
      //Send correct response

    } // Add all the message types

  });


});

有了这个,我将消息类型作为字符串打印到控制台:

Message type: BootNotification

所以我的问题是这是获取消息类型的正确方法吗?我是新手,所以我想确定一下。

OCPP 1.6 JSON 规范可在此处获得:OpenChargeAlliance 网站

标签: javascriptnode.jsjson

解决方案


我猜是。JSON.parse是内置的,很好,解析 JSON 字符串。如果出现问题,它会引发错误,因此您可能try/catch会这样做。

由于您得到的响应是一个数组,因此没有其他方法可以使用数字索引访问其项目。


在这种情况下,我个人更喜欢这样的东西:

const handlers = {
  'BootNotification': request => { 'msg': 'what a request' }
};

比你可以:

let respone = {'msg': 'Cannot handle this'}

if (handlers.hasOwnProperty(msg[2])) {
  response = handlers[msg[2]](msg);

}

但这正是我要走的路。


推荐阅读