-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
270 lines (232 loc) · 6.96 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
let { app, CONNECTED_CHARGERS, connectedChargers } = require("./app");
const WebSocket = require("ws");
const logger = require("./config/logger");
const PORT = 4500;
const server = app.listen(PORT, () => {
logger.info(`Server listening on ${PORT}`);
});
const wss = new WebSocket.Server({
server,
});
wss.on("connection", (ws, req) => {
logger.info(`New charger connected: ${req.url.slice(1)}`);
/**
* Extract the charger identity from the URL. This is the unique identifier for the charger.
* .slice is used because it is come from the url.
*
* When the charger is connected to the web socket it is making a GET request which includes the /<charger_identity>.
*/
const chargerIdentity = req.url.slice(1);
// Upon the first successful connection of the charger, add to the map which is responsible for in-memory storage.
connectedChargers.set(chargerIdentity, {
ws,
unique_id: "",
transactionId: null,
});
ws.on("message", (message) => {
const request = Buffer.from(message, "base64").toString("ascii");
const data = JSON.parse(request);
const messageTypeID = data[0];
const unique_id = data[1];
const action = data[2];
const payload = data[3];
let response = [3, unique_id, {}];
connectedChargers.set(chargerIdentity, {
...connectedChargers.get(chargerIdentity),
unique_id: unique_id,
});
logger.info({
CONNECTED_CHARGERS: [
...Array.from(connectedChargers.keys()).map((key) => {
return (key = {
charger_identity: key,
transactionId: connectedChargers.get(key).transactionId,
uniqueId: connectedChargers.get(key).unique_id,
});
}),
],
});
// Make a log when it is response from the charger.
if (messageTypeID === 3) logger.info(`DATA_RECEIVED*: ${message}`);
if (action === "Authorize") {
logger.info(
`========================= AUTHORIZE =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`=========================END OF AUTHORIZE =============================`
);
response = [
3,
unique_id,
{
idTagInfo: {
status: "Accepted",
},
},
];
ws.send(JSON.stringify(response));
} else if (action === "BootNotification") {
logger.info(
`========================= BOOT NOTIFICATION =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`=========================END OF BOOT NOTIFICATION =============================`
);
const date = new Date();
const offsetDate = new Date(date.getTime() + 8 * 60 * 60 * 1000); // Add 8 hours
const isoStringWithOffset = offsetDate.toISOString();
response = [
3,
unique_id,
{
currentTime: isoStringWithOffset, // ISO 8601 date format
interval: 60, // Example interval in seconds
status: "Accepted", // RegistrationStatus value
},
];
ws.send(JSON.stringify(response));
/**
* Change Configuration
*
* IIFE
*/
(async () => {
try {
const meterValueSampleIntervalRes = await fetch(
"http://localhost:4500/ocpp/1.6/api/v1/change-configuration",
{
method: "POST",
headers: {
"Content-Type": "application/json", // Inform the server you're sending JSON
},
body: JSON.stringify({
charger_identity: req.url.slice(1),
key: "MeterValueSampleInterval",
value: "5",
}),
}
);
if (!meterValueSampleIntervalRes.ok) {
const errorText = await meterValueSampleIntervalRes.text();
throw new Error(
`HTTP API for Change Config for Meter Value Sample Interval ${meterValueSampleIntervalRes.status}: ${errorText}`
);
}
const data = await meterValueSampleIntervalRes.json();
logger.info(
`Change Config: Meter Value Sample Interval - ${
meterValueSampleIntervalRes.status
} : ${JSON.stringify(data)}`
);
} catch (error) {
logger.error(`Error occurred: ${error.message}`);
}
})();
} else if (action === "Heartbeat") {
logger.info(
`========================= HEARTBEAT =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`========================= HEARTBEAT =============================`
);
const date = new Date();
const offsetDate = new Date(date.getTime() + 8 * 60 * 60 * 1000); // Add 8 hours
const isoStringWithOffset = offsetDate.toISOString();
response = [
3,
unique_id,
{
currentTime: isoStringWithOffset,
},
];
ws.send(JSON.stringify(response));
} else if (action === "StatusNotification") {
const status = payload.status;
logger.info(
`=========================STATUS NOTIFICATION =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`=========================END OF STATUS NOTIFICATION =============================`
);
if (status === "Preparing") {
response = [3, unique_id, {}];
ws.send(JSON.stringify(response));
} else if (status === "Charging") {
logger.info({ unique_id, status });
ws.send(JSON.stringify(response));
} else {
response = [3, unique_id, {}];
ws.send(JSON.stringify(response));
}
} else if (action === "MeterValues") {
logger.info(
`========================= METER VALUES =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`========================= METER VALUES =============================`
);
response = [3, unique_id, {}];
ws.send(JSON.stringify(response));
} else if (action === "StopTransaction") {
logger.info(
`========================= STOP TRANSACTION =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`========================= END OF STOP TRANSACTION =============================`
);
response = [
3,
unique_id,
{
idTag: {
status: "Accepted",
},
},
];
connectedChargers.set(chargerIdentity, {
...connectedChargers.get(chargerIdentity),
transactionId: null,
});
ws.send(JSON.stringify(response));
} else if (action === "StartTransaction") {
logger.info(
`========================= START TRANSACTION =============================`
);
logger.info(`DATA_RECEIVED: ${message}`);
logger.info(
`========================= END OF START TRANSACTION =============================`
);
const transactionId = Math.floor(Math.random() * 100000);
logger.info(`UNIQUE ID: ${unique_id}`);
response = [
3,
unique_id,
{
idTagInfo: {
status: "Accepted",
},
transactionId,
},
];
ws.send(JSON.stringify(response));
}
});
ws.on("pong", () => {
logger.info("Pong received");
});
ws.on("close", (code, reason) => {
logger.info(
`========================= WEB SOCKET CONNECTION CLOSED =============================`
);
logger.info(code, reason);
logger.info(
`========================= END OF WEB SOCKEET CONNNECTION CLOSED =============================`
);
});
});