So I am receiving JSON over a websocket from a chargepoint using OCPP 1.6 JSON. I am trying to parse the message and respond appropriately, depending on what the message is, using Node.js
Here is the message that I recieve:
[ 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' } ]
In this case it is the 'BootNotification' message, to which I need to respond with an 'Accepted' message.
Here is my code:
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
});
});
With this I get the message type printed to the console as a string:
Message type: BootNotification
So my question is that is this the correct way to get the type of the message? I am new to this so I want to make sure.
The specification for OCPP 1.6 JSON is available here: OpenChargeAlliance website
I guess YES. JSON.parse
is the built-in to, well, pares JSON strings. In case that goes wrong it throws an error, so you might try/catch
this.
Since the response you get is an array, there is no other way as to access its items with a numeric index.
In such cases I personally prefer to have something like that:
const handlers = {
'BootNotification': request => { 'msg': 'what a request' }
};
Than you can:
let respone = {'msg': 'Cannot handle this'}
if (handlers.hasOwnProperty(msg[2])) {
response = handlers[msg[2]](msg);
}
But that is just the way I would go.