Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //! README
- // set charging limit
- // curl 'http://HOST:3030/limit?amps=10.4&numberPhases=3'
- // stop charging
- // curl 'http://HOST:3030/stop'
- // start charging
- // curl 'http://HOST:3030/start?amps=10&numberPhases=3'
- const express = require('express');
- const WebSocket = require('ws');
- const http = require('http');
- const app = express();
- const server = http.createServer(app);
- const wss = new WebSocket.Server({ server });
- const clients = [];
- wss.on('connection', (ws) => {
- console.log('Client connected via WebSocket');
- clients.push(ws);
- ws.on('close', (code, reason) => {
- console.log(`Connection closed. Code: ${code}, Reason: ${reason}`);
- const i = clients.indexOf(ws);
- if (i !== -1) {
- clients.splice(i, 1);
- }
- });
- ws.on('message', (message) => {
- console.log('>> Got:', JSON.stringify(JSON.parse(message.toString()), null));
- handleMessage(ws, message);
- });
- });
- function handleMessage(ws, message) {
- let parsedMessage;
- try {
- parsedMessage = JSON.parse(message);
- } catch (error) {
- console.error('Error parsing message', message);
- return;
- }
- const response = replyMessage(parsedMessage);
- if (response) {
- console.log('<< Reply:', JSON.stringify(response, null));
- ws.send(JSON.stringify(response));
- }
- console.log('-----------------------')
- }
- function replyMessage(message){
- const [messageTypeId, uniqueId, action, payload] = message;
- var replyCounter = 0;
- //initiated by Charging Station
- if (uniqueId.startsWith("xxx")) {
- // got reply not request
- return;
- }else if (action === "BootNotification") {
- return [3, uniqueId, { "status": "Accepted", "currentTime": new Date().toISOString(), "interval": 10 }]; //fixed Heartbeat Interval
- }else if (action === "StartTransaction") {
- return [3, uniqueId, {
- "transactionId": 123,
- "idTagInfo": {
- "status": "Accepted",
- },
- }];
- }else if (action === "StopTransaction") {
- return [3, uniqueId, {
- "idTagInfo": {
- "status": "Accepted",
- },
- }];
- }else if(action === "Heartbeat") {
- return [3, uniqueId, { "currentTime": new Date().toISOString() }];
- }else if(action === "StatusNotification"){
- return [3, uniqueId, {}];
- }else if(action === "MeterValues"){
- return [3, uniqueId, {}];
- }else if(action === "Authorize"){
- // Check if ID in Backend in the future, or similar
- return [3, uniqueId, { idTagInfo: { "status": "Accepted" } }];
- // Initiated by FrontEnd
- // -- Reset
- }else if(action === "Reset"){
- // Check if ID in Backend in the future, or similar
- replyCounter = replyCounter+1;
- return [2, replyCounter.toString(), "Reset", { type: "Hard" }];
- // -- Remote Start Transaction
- // }else if(action === "RemoteStartTransactionRequest"){
- // // Check if ID in Backend in the future, or similar
- // replyCounter = replyCounter+1;
- // return [2, replyCounter.toString(), "RemoteStartTransactionRequest",{"idTag":"6ac32b40","connectorId":1}];
- // // -- Remote Stop Transaction
- // }else if(action === "RemoteStopTransactionRequest"){
- // // Check if ID in Backend in the future, or similar
- // replyCounter = replyCounter+1;
- // return [2, replyCounter.toString(), "RemoteStopTransactionRequest", { "transactionId": 1}];
- }else{
- console.log("Unknown MEssage!!!!");
- console.log("*****");
- console.log(message);
- console.log("*****");
- };
- }
- app.get('/', (req, res) => {
- res.send('Hello from Express and WebSocket OCPP Server');
- });
- app.get('/limit', (req, res) => {
- const currentLimit = +req.query.amps;
- const numberPhases = +(req.query.numberPhases || 3);
- if (clients.length) {
- const message = [2, `xxx${Date.now()}`, "SetChargingProfile", {
- "connectorId": 1,
- "csChargingProfiles": {
- "chargingProfileId": 1,
- "transactionId": 123,
- "stackLevel": 0,
- "chargingProfilePurpose": "ChargePointMaxProfile",
- "chargingProfileKind": "Absolute",
- "chargingSchedule": {
- "chargingRateUnit": "A",
- "chargingSchedulePeriod": [
- {
- "startPeriod": 0,
- "limit": currentLimit,
- "numberPhases": numberPhases,
- }
- ]
- }
- }
- }];
- for (const ws of clients) {
- ws.send(JSON.stringify(message));
- }
- console.log('<< Send:', JSON.stringify(message, null));
- res.send(`Message sent\n${JSON.stringify(message, null, 2)}`);
- }else {
- res.status(400).send('No connected client');
- }
- });
- app.get('/stop', (req, res) => {
- if (clients.length) {
- const message = [2, `xxx${Date.now()}`, "RemoteStopTransaction", {
- "transactionId": 123,
- }];
- for (const ws of clients) {
- ws.send(JSON.stringify(message));
- }
- console.log('<< Send:', JSON.stringify(message, null));
- res.send(`Message sent\n${JSON.stringify(message, null, 2)}`);
- }else {
- res.status(400).send('No connected client');
- }
- });
- app.get('/start', (req, res) => {
- const currentLimit = +(req.query.amps || 10);
- const numberPhases = +(req.query.numberPhases || 3);
- if (clients.length) {
- const message = [2, `xxx${Date.now()}`, "RemoteStartTransaction", {
- "connectorId": 1,
- "idTag": "SomeIdTaggggg",
- "chargingProfile": {
- "chargingProfileId": 1,
- "transactionId": 123,
- "stackLevel": 0,
- "chargingProfilePurpose": "ChargePointMaxProfile",
- "chargingProfileKind": "Absolute",
- "chargingSchedule": {
- "chargingRateUnit": "A",
- "chargingSchedulePeriod": [
- {
- "startPeriod": 0,
- "limit": currentLimit,
- "numberPhases": numberPhases,
- }
- ]
- }
- },
- }];
- for (const ws of clients) {
- ws.send(JSON.stringify(message));
- }
- console.log('<< Send:', JSON.stringify(message, null));
- res.send(`Message sent\n${JSON.stringify(message, null, 2)}`);
- }else {
- res.status(400).send('No connected client');
- }
- });
- server.listen(3030, () => {
- console.log('HTTP and WebSocket server is running on http://localhost:3030');
- });
Add Comment
Please, Sign In to add comment