javascript - 这是通过 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 网站
解决方案
我猜是。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);
}
但这正是我要走的路。
推荐阅读
- javascript - 筹码值得到 [object Object]
- python - 我们如何使列表中的元素在python中多次倒退?
- django - 我在哪里可以在 django 中存储刷新和访问令牌
- python-3.x - 403 客户端错误:禁止访问 url:https://ropsten.infura.io/v3/PROJECT_ID
- java - 如何解决这个保证金差距?
- kernel - (内核)关于 OpenBSD 的开发人员级别文档
- html - 在 Angular 中以编程方式转换(旋转)元素
- javascript - 如何在反应传单上添加比例?
- github - 如何为 github 操作设置环境变量?
- c++ - 将 Q_GADGET 存储在 ListModel 中,它会“忘记”它的方法