Add Reset command handling.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.js
CommitLineData
7dde0b73
JB
1const Configuration = require('../utils/Configuration');
2const logger = require('../utils/Logger');
3const WebSocket = require('ws');
f7869514 4const Constants = require('../utils/Constants');
7dde0b73
JB
5const Utils = require('../utils/Utils');
6const OCPPError = require('./OcppError');
7dde0b73
JB
7const AutomaticTransactionGenerator = require('./AutomaticTransactionGenerator');
8const Statistics = require('../utils/Statistics');
9const fs = require('fs');
10const {performance, PerformanceObserver} = require('perf_hooks');
11
12class ChargingStation {
2e6f5966
JB
13 constructor(index, stationTemplateFile) {
14 this._index = index;
15 this._stationTemplateFile = stationTemplateFile;
16 this._initialize();
17
7dde0b73
JB
18 this._autoReconnectRetryCount = 0;
19 this._autoReconnectMaxRetries = Configuration.getAutoReconnectMaxRetries(); // -1 for unlimited
20 this._autoReconnectTimeout = Configuration.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
2e6f5966
JB
21
22 this._requests = {};
23 this._messageQueue = [];
24
7dde0b73 25 this._isSocketRestart = false;
34dcb3b5 26
83045896 27 this._authorizedTags = this._loadAndGetAuthorizedTags();
2e6f5966
JB
28 }
29
5ad8570f
JB
30 _getStationName(stationTemplate) {
31 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index).substr(('000000000' + this._index).length - 4);
32 }
33
34 _buildStationInfo() {
35 let stationTemplateFromFile;
36 try {
37 // Load template file
38 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
39 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
40 fs.closeSync(fileDescriptor);
41 } catch (error) {
42 logger.error(this._basicFormatLog() + ' Template file loading error: ' + error);
43 }
44 const stationTemplate = stationTemplateFromFile || {};
45 if (Array.isArray(stationTemplateFromFile.power)) {
46 stationTemplate.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
47 } else {
48 stationTemplate.maxPower = stationTemplateFromFile.power;
49 }
50 stationTemplate.name = this._getStationName(stationTemplateFromFile);
51 return stationTemplate;
52 }
53
2e6f5966
JB
54 _initialize() {
55 this._stationInfo = this._buildStationInfo();
56 this._bootNotificationMessage = {
57 chargePointModel: this._stationInfo.chargePointModel,
58 chargePointVendor: this._stationInfo.chargePointVendor,
6958152c 59 chargePointSerialNumber: this._stationInfo.chargePointSerialNumberPrefix ? this._stationInfo.chargePointSerialNumberPrefix : '',
34dcb3b5 60 firmwareVersion: this._stationInfo.firmwareVersion ? this._stationInfo.firmwareVersion : '',
2e6f5966
JB
61 };
62 this._configuration = this._getConfiguration();
2e6f5966 63 this._supervisionUrl = this._getSupervisionURL();
5ad8570f 64 this._connectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
7dde0b73
JB
65 this._statistics = new Statistics(this._stationInfo.name);
66 this._performanceObserver = new PerformanceObserver((list) => {
67 const entry = list.getEntries()[0];
68 this._statistics.logPerformance(entry, 'ChargingStation');
69 this._performanceObserver.disconnect();
70 });
7dde0b73
JB
71 }
72
73 _basicFormatLog() {
74 return Utils.basicFormatLog(` ${this._stationInfo.name}:`);
75 }
76
2e6f5966
JB
77 _getConfiguration() {
78 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {};
7dde0b73
JB
79 }
80
2e6f5966
JB
81 _getAuthorizationFile() {
82 return this._stationInfo.authorizationFile ? this._stationInfo.authorizationFile : '';
7dde0b73
JB
83 }
84
83045896 85 _loadAndGetAuthorizedTags() {
2e6f5966
JB
86 let authorizedTags = [];
87 const authorizationFile = this._getAuthorizationFile();
88 if (authorizationFile) {
89 try {
90 // Load authorization file
91 const fileDescriptor = fs.openSync(authorizationFile, 'r');
92 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8'));
93 fs.closeSync(fileDescriptor);
94 } catch (error) {
95 logger.error(this._basicFormatLog() + ' Authorization file loading error: ' + error);
96 }
97 } else {
98 logger.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile);
99 }
100 return authorizedTags;
101 }
102
5ad8570f
JB
103 getRandomTagId() {
104 const index = Math.floor(Math.random() * this._authorizedTags.length);
105 return this._authorizedTags[index];
2e6f5966
JB
106 }
107
5ad8570f
JB
108 hasAuthorizedTags() {
109 return !Utils.isEmptyArray(this._authorizedTags);
110 }
111
112 _getConnector(number) {
113 return this._stationInfo.Connectors[number];
114 }
115
116 _getMaxConnectors() {
117 let maxConnectors = 0;
118 if (Array.isArray(this._stationInfo.numberOfConnectors)) {
119 // Generate some connectors
120 maxConnectors = this._stationInfo.numberOfConnectors[(this._index - 1) % this._stationInfo.numberOfConnectors.length];
121 } else {
122 maxConnectors = this._stationInfo.numberOfConnectors;
123 }
124 return maxConnectors;
2e6f5966
JB
125 }
126
127 _getSupervisionURL() {
128 const supervisionUrls = Utils.cloneJSonDocument(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs());
7dde0b73
JB
129 let indexUrl = 0;
130 if (Array.isArray(supervisionUrls)) {
2e6f5966
JB
131 if (Configuration.getDistributeStationToTenantEqually()) {
132 indexUrl = this._index % supervisionUrls.length;
7dde0b73
JB
133 } else {
134 // Get a random url
135 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
136 }
137 return supervisionUrls[indexUrl];
138 }
139 return supervisionUrls;
140 }
141
7dde0b73 142 _getAuthorizeRemoteTxRequests() {
61c2e33d 143 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
a6e68f34 144 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
7dde0b73
JB
145 }
146
def3d48e 147 _getLocalAuthListEnabled() {
61c2e33d 148 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
def3d48e
JB
149 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
150 }
151
5ad8570f
JB
152 async _basicStartMessageSequence() {
153 // Start heartbeat
154 this._startHeartbeat(this);
155 // Build connectors
156 if (!this._connectors) {
157 this._connectors = {};
158 const connectorsConfig = Utils.cloneJSonDocument(this._stationInfo.Connectors);
159 // Determine number of customized connectors
160 let lastConnector;
161 for (lastConnector in connectorsConfig) {
162 // Add connector 0, OCPP specification violation that for example KEBA have
163 if (Utils.convertToInt(lastConnector) === 0 && Utils.convertToBoolean(this._stationInfo.useConnectorId0) &&
164 connectorsConfig[lastConnector]) {
165 this._connectors[lastConnector] = connectorsConfig[lastConnector];
166 }
167 }
168 const maxConnectors = this._getMaxConnectors();
169 this._addConfigurationKey('NumberOfConnectors', maxConnectors, true);
170 // Generate all connectors
171 for (let index = 1; index <= maxConnectors; index++) {
172 const randConnectorID = Utils.convertToBoolean(this._stationInfo.randomConnectors) ? Utils.getRandomInt(lastConnector, 1) : index;
173 this._connectors[index] = connectorsConfig[randConnectorID];
174 }
2e6f5966 175 }
5ad8570f
JB
176
177 for (const connector in this._connectors) {
178 if (!this._connectors[connector].transactionStarted) {
179 if (this._connectors[connector].bootStatus) {
180 this.sendStatusNotificationWithTimeout(connector, this._connectors[connector].bootStatus);
181 } else {
182 this.sendStatusNotificationWithTimeout(connector, 'Available');
183 }
184 } else {
185 this.sendStatusNotificationWithTimeout(connector, 'Charging');
186 }
187 }
188
189 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable)) {
190 if (!this._automaticTransactionGeneration) {
191 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
192 }
193 if (this._automaticTransactionGeneration.timeToStop) {
194 this._automaticTransactionGeneration.start();
195 }
196 }
197 this._statistics.start();
198 }
199
200 // eslint-disable-next-line class-methods-use-this
201 async _startHeartbeat(self) {
202 if (self._heartbeatInterval && !self._heartbeatSetInterval) {
203 self._heartbeatSetInterval = setInterval(() => {
204 try {
205 const payload = {
206 currentTime: new Date().toISOString(),
207 };
208 self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
209 } catch (error) {
210 logger.error(self._basicFormatLog() + ' Send heartbeat error: ' + error);
211 }
212 }, self._heartbeatInterval);
213 logger.info(self._basicFormatLog() + ' Heartbeat started every ' + self._heartbeatInterval + 'ms');
7dde0b73 214 } else {
5ad8570f 215 logger.error(self._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
7dde0b73 216 }
5ad8570f
JB
217 }
218
219 _startAuthorizationFileMonitoring() {
220 // eslint-disable-next-line no-unused-vars
221 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
222 try {
223 logger.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
224 // Initialize _authorizedTags
225 this._authorizedTags = this._loadAndGetAuthorizedTags();
226 } catch (error) {
227 logger.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error);
228 }
229 });
230 }
231
232 _startStationTemplateFileMonitoring() {
233 // eslint-disable-next-line no-unused-vars
234 fs.watchFile(this._stationTemplateFile, (current, previous) => {
235 try {
236 logger.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
237 // Initialize
238 this._initialize();
239 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval / 1000 : 0));
240 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(this._heartbeatInterval ? this._heartbeatInterval / 1000 : 0), false, false);
241 this._addConfigurationKey('NumberOfConnectors', this._getMaxConnectors(), true);
242 } catch (error) {
243 logger.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error);
244 }
245 });
246 }
247
248 async _startMeterValues(connectorID, interval) {
249 if (!this._connectors[connectorID].transactionStarted) {
250 logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
251 return;
252 } else if (this._connectors[connectorID].transactionStarted && !this._connectors[connectorID].transactionId) {
253 logger.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
254 return;
255 }
256 this._connectors[connectorID].transactionSetInterval = setInterval(async () => {
257 const sendMeterValues = performance.timerify(this.sendMeterValues);
258 this._performanceObserver.observe({
259 entryTypes: ['function'],
260 });
261 await sendMeterValues(connectorID, interval, this);
262 }, interval);
7dde0b73
JB
263 }
264
265 async start() {
5ad8570f
JB
266 if (!this._connectionUrl) {
267 this._connectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
268 }
269 this._wsConnection = new WebSocket(this._connectionUrl, 'ocpp1.6');
7dde0b73 270 logger.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl);
2e6f5966
JB
271 // Monitor authorization file
272 this._startAuthorizationFileMonitoring();
273 // Monitor station template file
274 this._startStationTemplateFileMonitoring();
7dde0b73
JB
275 // Handle Socket incoming messages
276 this._wsConnection.on('message', this.onMessage.bind(this));
277 // Handle Socket error
278 this._wsConnection.on('error', this.onError.bind(this));
279 // Handle Socket close
280 this._wsConnection.on('close', this.onClose.bind(this));
281 // Handle Socket opening connection
282 this._wsConnection.on('open', this.onOpen.bind(this));
283 // Handle Socket ping
284 this._wsConnection.on('ping', this.onPing.bind(this));
285 }
286
5ad8570f
JB
287 async stop(type = '') {
288 // Stop heartbeat
289 if (this._heartbeatSetInterval) {
290 await clearInterval(this._heartbeatSetInterval);
291 this._heartbeatSetInterval = null;
292 }
293 // Stop the ATG
294 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
295 this._automaticTransactionGeneration &&
296 !this._automaticTransactionGeneration.timeToStop) {
297 await this._automaticTransactionGeneration.stop();
298 } else {
299 for (const connector in this._connectors) {
300 if (this._connectors[connector].transactionStarted) {
301 await this.sendStopTransaction(this._connectors[connector].transactionId, type ? type + 'Reset' : '');
302 }
303 }
304 }
305 // eslint-disable-next-line guard-for-in
306 for (const connector in this._connectors) {
307 await this.sendStatusNotification(connector, 'Unavailable');
308 }
309 if (this._wsConnection) {
310 await this._wsConnection.close();
311 }
312 }
313
314 _reconnect(error) {
315 logger.error(this._basicFormatLog() + ' Socket: abnormally closed', error);
316 // Stop the ATG if needed
317 if (Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.enable) &&
318 Utils.convertToBoolean(this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure) &&
319 this._automaticTransactionGeneration &&
320 !this._automaticTransactionGeneration.timeToStop) {
321 this._automaticTransactionGeneration.stop();
322 }
323 // Stop heartbeat
324 if (this._heartbeatSetInterval) {
325 clearInterval(this._heartbeatSetInterval);
326 this._heartbeatSetInterval = null;
327 }
328 if (this._autoReconnectTimeout !== 0 &&
329 (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1)) {
330 logger.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
331 this._autoReconnectRetryCount++;
332 setTimeout(() => {
333 logger.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount);
334 this.start();
335 }, this._autoReconnectTimeout);
336 } else if (this._autoReconnectTimeout !== 0 || this._autoReconnectMaxRetries !== -1) {
337 logger.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
338 }
339 }
340
7dde0b73 341 onOpen() {
5ad8570f
JB
342 logger.info(`${this._basicFormatLog()} Is connected to server through ${this._connectionUrl}`);
343 if (!this._isSocketRestart) {
0bbcb3dc
JB
344 // Send BootNotification
345 try {
346 this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
347 } catch (error) {
348 logger.error(this._basicFormatLog() + ' Send boot notification error: ' + error);
349 }
350 }
7dde0b73 351 if (this._isSocketRestart) {
027b409a 352 this._basicStartMessageSequence();
7dde0b73
JB
353 if (this._messageQueue.length > 0) {
354 this._messageQueue.forEach((message) => {
355 if (this._wsConnection.readyState === WebSocket.OPEN) {
356 this._wsConnection.send(message);
357 }
358 });
359 }
7dde0b73
JB
360 }
361 this._autoReconnectRetryCount = 0;
362 this._isSocketRestart = false;
363 }
364
365 onError(error) {
366 switch (error) {
367 case 'ECONNREFUSED':
368 this._isSocketRestart = true;
369 this._reconnect(error);
370 break;
371 default:
372 logger.error(this._basicFormatLog() + ' Socket error: ' + error);
373 break;
374 }
375 }
376
377 onClose(error) {
378 switch (error) {
379 case 1000: // Normal close
380 case 1005:
381 logger.info(this._basicFormatLog() + ' Socket normally closed ' + error);
382 this._autoReconnectRetryCount = 0;
383 break;
384 default: // Abnormal close
385 this._isSocketRestart = true;
386 this._reconnect(error);
387 break;
388 }
389 }
390
391 onPing() {
027b409a 392 logger.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
7dde0b73
JB
393 }
394
395 async onMessage(message) {
2d8cee5a 396 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
7dde0b73 397 try {
2d8cee5a
JB
398 // Parse the message
399 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(message);
400
7dde0b73
JB
401 // Check the Type of message
402 switch (messageType) {
403 // Incoming Message
f7869514 404 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73 405 // Process the call
7dde0b73
JB
406 await this.handleRequest(messageId, commandName, commandPayload);
407 break;
408 // Outcome Message
f7869514 409 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73
JB
410 // Respond
411 // eslint-disable-next-line no-case-declarations
412 let responseCallback; let requestPayload;
413 if (Utils.isIterable(this._requests[messageId])) {
414 [responseCallback, , requestPayload] = this._requests[messageId];
415 } else {
416 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
417 }
418 if (!responseCallback) {
419 // Error
420 throw new Error(`Response for unknown message id ${messageId}`);
421 }
422 delete this._requests[messageId];
7dde0b73
JB
423 responseCallback(commandName, requestPayload);
424 break;
425 // Error Message
f7869514 426 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73
JB
427 if (!this._requests[messageId]) {
428 // Error
429 throw new Error(`Error for unknown message id ${messageId}`);
430 }
431 // eslint-disable-next-line no-case-declarations
432 let rejectCallback;
433 if (Utils.isIterable(this._requests[messageId])) {
434 [, rejectCallback] = this._requests[messageId];
435 } else {
436 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
437 }
438 delete this._requests[messageId];
439 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
440 break;
441 // Error
442 default:
443 throw new Error(`Wrong message type ${messageType}`);
444 }
445 } catch (error) {
446 // Log
447 logger.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message, error, this._requests[messageId]);
448 // Send error
449 // await this.sendError(messageId, error);
450 }
451 }
452
5ad8570f
JB
453 async sendStatusNotification(connectorId, status, errorCode = 'NoError') {
454 try {
455 const payload = {
456 connectorId,
457 errorCode,
458 status,
459 };
460 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
461 } catch (error) {
462 logger.error(this._basicFormatLog() + ' Send status error: ' + error);
463 throw error;
027b409a
JB
464 }
465 }
466
5ad8570f
JB
467 sendStatusNotificationWithTimeout(connectorId, status, errorCode = 'NoError', timeout = Constants.STATUS_NOTIFICATION_TIMEOUT) {
468 setTimeout(() => this.sendStatusNotification(connectorId, status, errorCode), timeout);
469 }
470
471 async sendStartTransaction(connectorID, idTag) {
472 try {
473 const payload = {
474 connectorId: connectorID,
475 idTag,
476 meterStart: 0,
477 timestamp: new Date().toISOString(),
478 };
479 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction');
480 } catch (error) {
481 logger.error(this._basicFormatLog() + ' Send start transaction error: ' + error);
482 throw error;
7dde0b73
JB
483 }
484 }
485
5ad8570f
JB
486 sendStartTransactionWithTimeout(connectorID, idTag, timeout) {
487 setTimeout(() => this.sendStartTransaction(connectorID, idTag), timeout);
7dde0b73
JB
488 }
489
5ad8570f 490 async sendStopTransaction(transactionId, reason = '') {
027b409a
JB
491 try {
492 const payload = {
5ad8570f
JB
493 transactionId,
494 meterStop: 0,
495 timestamp: new Date().toISOString(),
496 reason,
027b409a 497 };
5ad8570f 498 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction');
027b409a 499 } catch (error) {
5ad8570f
JB
500 logger.error(this._basicFormatLog() + ' Send stop transaction error: ' + error);
501 throw error;
027b409a
JB
502 }
503 }
504
5ad8570f
JB
505 // eslint-disable-next-line class-methods-use-this
506 async sendMeterValues(connectorID, interval, self, debug = false) {
507 try {
508 const sampledValueLcl = {
509 timestamp: new Date().toISOString(),
510 };
511 const meterValuesClone = Utils.cloneJSonDocument(self._getConnector(connectorID).MeterValues);
512 if (Array.isArray(meterValuesClone)) {
513 sampledValueLcl.sampledValue = meterValuesClone;
514 } else {
515 sampledValueLcl.sampledValue = [meterValuesClone];
516 }
517 for (let index = 0; index < sampledValueLcl.sampledValue.length; index++) {
518 const connector = self._connectors[connectorID];
519 if (sampledValueLcl.sampledValue[index].measurand && sampledValueLcl.sampledValue[index].measurand === 'SoC') {
520 sampledValueLcl.sampledValue[index].value = Utils.getRandomInt(100);
521 if (sampledValueLcl.sampledValue[index].value > 100 || debug) {
522 logger.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}`);
523 }
524 } else {
525 // Persist previous value in connector
526 const consumption = Utils.getRandomInt(self._stationInfo.maxPower / 3600000 * interval);
527 if (connector && connector.lastConsumptionValue >= 0) {
528 connector.lastConsumptionValue += consumption;
529 } else {
530 connector.lastConsumptionValue = 0;
531 }
532 const maxConsumption = self._stationInfo.maxPower * 3600 / interval;
533 logger.info(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value ${connector.lastConsumptionValue}`);
534 sampledValueLcl.sampledValue[index].value = connector.lastConsumptionValue;
535 if (sampledValueLcl.sampledValue[index].value > maxConsumption || debug) {
536 logger.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}/${maxConsumption}`);
537 }
538 }
539 }
540
541 const payload = {
542 connectorId: connectorID,
543 transactionId: self._connectors[connectorID].transactionId,
544 meterValue: [sampledValueLcl],
545 };
546 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
547 } catch (error) {
548 logger.error(self._basicFormatLog() + ' Send MeterValues error: ' + error);
549 }
550 }
551
552 sendError(messageId, err) {
553 // Check exception: only OCPP error are accepted
554 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message);
555 // Send error
556 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE);
027b409a
JB
557 }
558
f7869514 559 sendMessage(messageId, command, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName = '') {
7dde0b73
JB
560 // Send a message through wsConnection
561 const self = this;
562 // Create a promise
563 return new Promise((resolve, reject) => {
564 let messageToSend;
565 // Type of message
566 switch (messageType) {
567 // Request
f7869514 568 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73
JB
569 this._statistics.addMessage(commandName);
570 // Build request
571 this._requests[messageId] = [responseCallback, rejectCallback, command];
572 messageToSend = JSON.stringify([messageType, messageId, commandName, command]);
573 break;
574 // Response
f7869514 575 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
d3a7883e 576 this._statistics.addMessage(commandName);
7dde0b73
JB
577 // Build response
578 messageToSend = JSON.stringify([messageType, messageId, command]);
579 break;
580 // Error Message
f7869514 581 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73 582 // Build Message
7de604f9 583 this._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
894a1780 584 messageToSend = JSON.stringify([messageType, messageId, command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR, command.message ? command.message : '', command.details ? command.details : {}]);
7dde0b73
JB
585 break;
586 }
2e6f5966 587 // Check if wsConnection is ready
7dde0b73
JB
588 if (this._wsConnection.readyState === WebSocket.OPEN) {
589 // Yes: Send Message
590 this._wsConnection.send(messageToSend);
591 } else {
592 // Buffer message until connection is back
593 this._messageQueue.push(messageToSend);
594 }
595 // Request?
f7869514 596 if (messageType !== Constants.OCPP_JSON_CALL_MESSAGE) {
7dde0b73
JB
597 // Yes: send Ok
598 resolve();
599 } else if (this._wsConnection.readyState === WebSocket.OPEN) {
600 // Send timeout in case connection is open otherwise wait for ever
601 // FIXME: Handle message on timeout
f7869514 602 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants.OCPP_SOCKET_TIMEOUT);
7dde0b73
JB
603 }
604
605 // Function that will receive the request's response
606 function responseCallback(payload, requestPayload) {
607 self._statistics.addMessage(commandName, true);
608 const responseCallbackFn = 'handleResponse' + commandName;
609 if (typeof self[responseCallbackFn] === 'function') {
610 self[responseCallbackFn](payload, requestPayload, self);
611 } else {
61c2e33d 612 logger.debug(self._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
7dde0b73
JB
613 }
614 // Send the response
615 resolve(payload);
616 }
617
618 // Function that will receive the request's rejection
619 function rejectCallback(reason) {
7de604f9 620 self._statistics.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
7dde0b73
JB
621 // Build Exception
622 // eslint-disable-next-line no-empty-function
623 self._requests[messageId] = [() => { }, () => { }, '']; // Properly format the request
624 const error = reason instanceof OCPPError ? reason : new Error(reason);
625 // Send error
626 reject(error);
627 }
628 });
629 }
630
5ad8570f
JB
631 handleResponseBootNotification(payload) {
632 if (payload.status === 'Accepted') {
633 this._heartbeatInterval = payload.interval * 1000;
634 this._addConfigurationKey('HeartBeatInterval', Utils.convertToInt(payload.interval));
635 this._addConfigurationKey('HeartbeatInterval', Utils.convertToInt(payload.interval), false, false);
636 this._basicStartMessageSequence();
637 } else {
638 logger.info(this._basicFormatLog() + ' Boot Notification rejected');
7dde0b73 639 }
7dde0b73
JB
640 }
641
027b409a
JB
642 _resetTransactionOnConnector(connectorID) {
643 this._connectors[connectorID].transactionStarted = false;
644 this._connectors[connectorID].transactionId = null;
d3a7883e 645 this._connectors[connectorID].idTag = null;
027b409a
JB
646 this._connectors[connectorID].lastConsumptionValue = -1;
647 this._connectors[connectorID].lastSoC = -1;
d3a7883e
JB
648 if (this._connectors[connectorID].transactionSetInterval) {
649 clearInterval(this._connectors[connectorID].transactionSetInterval);
027b409a
JB
650 }
651 }
652
7dde0b73 653 handleResponseStartTransaction(payload, requestPayload) {
d3a7883e
JB
654 if (this._connectors[requestPayload.connectorId].transactionStarted) {
655 logger.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload.connectorId + ' by transaction ' + this._connectors[requestPayload.connectorId].transactionId);
656 }
84393381 657
7de604f9
JB
658 let transactionConnectorId;
659 for (const connector in this._connectors) {
660 if (Utils.convertToInt(connector) === Utils.convertToInt(requestPayload.connectorId)) {
661 transactionConnectorId = connector;
662 break;
7dde0b73 663 }
7de604f9
JB
664 }
665 if (!transactionConnectorId) {
666 logger.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload.connectorId);
667 return;
668 }
669 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
670 this._connectors[transactionConnectorId].transactionStarted = true;
671 this._connectors[transactionConnectorId].transactionId = payload.transactionId;
672 this._connectors[transactionConnectorId].idTag = requestPayload.idTag;
673 this._connectors[transactionConnectorId].lastConsumptionValue = 0;
674 this._connectors[transactionConnectorId].lastSoC = 0;
675 this.sendStatusNotification(requestPayload.connectorId, 'Charging');
676 logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[transactionConnectorId].transactionId + ' STARTED on ' + this._stationInfo.name + '#' + requestPayload.connectorId + ' for idTag ' + requestPayload.idTag);
677 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
5ad8570f 678 this._startMeterValues(requestPayload.connectorId,
7de604f9 679 configuredMeterValueSampleInterval ? configuredMeterValueSampleInterval.value * 1000 : 60000);
7dde0b73
JB
680 } else {
681 logger.error(this._basicFormatLog() + ' Starting transaction id ' + payload.transactionId + ' REJECTED with status ' + payload.idTagInfo.status + ', idTag ' + requestPayload.idTag);
7de604f9 682 this._resetTransactionOnConnector(transactionConnectorId);
7dde0b73
JB
683 this.sendStatusNotification(requestPayload.connectorId, 'Available');
684 }
685 }
686
34dcb3b5 687 handleResponseStopTransaction(payload, requestPayload) {
d3a7883e
JB
688 let transactionConnectorId;
689 for (const connector in this._connectors) {
690 if (this._connectors[connector].transactionId === requestPayload.transactionId) {
691 transactionConnectorId = connector;
692 break;
693 }
694 }
695 if (!transactionConnectorId) {
7de604f9
JB
696 logger.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload.transactionId);
697 return;
d3a7883e
JB
698 }
699 if (payload.idTagInfo && payload.idTagInfo.status === 'Accepted') {
700 this.sendStatusNotification(transactionConnectorId, 'Available');
701 logger.info(this._basicFormatLog() + ' Transaction ' + this._connectors[transactionConnectorId].transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId);
702 this._resetTransactionOnConnector(transactionConnectorId);
34dcb3b5 703 } else {
d3a7883e 704 logger.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors[transactionConnectorId].transactionId + ' REJECTED with status ' + payload.idTagInfo.status);
34dcb3b5
JB
705 }
706 }
707
facd8ebd
JB
708 handleResponseStatusNotification(payload, requestPayload) {
709 logger.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload, requestPayload);
7dde0b73
JB
710 }
711
facd8ebd
JB
712 handleResponseMeterValues(payload, requestPayload) {
713 logger.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
027b409a
JB
714 }
715
facd8ebd
JB
716 handleResponseHeartbeat(payload, requestPayload) {
717 logger.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
7dde0b73
JB
718 }
719
720 async handleRequest(messageId, commandName, commandPayload) {
721 let result;
722 this._statistics.addMessage(commandName, true);
723 // Call
724 if (typeof this['handle' + commandName] === 'function') {
725 try {
726 // Call the method
727 result = await this['handle' + commandName](commandPayload);
728 } catch (error) {
729 // Log
730 logger.error(this._basicFormatLog() + ' Handle request error: ' + error);
facd8ebd 731 // Send back response to inform backend
7dde0b73
JB
732 await this.sendError(messageId, error);
733 }
734 } else {
84393381 735 // Throw exception
f7869514 736 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, 'Not implemented', {}));
7dde0b73
JB
737 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
738 }
84393381 739 // Send response
f7869514 740 await this.sendMessage(messageId, result, Constants.OCPP_JSON_CALL_RESULT_MESSAGE);
7dde0b73
JB
741 }
742
5ad8570f
JB
743 async handleReset(commandPayload) {
744 logger.info(`${this._basicFormatLog()} ${commandPayload.type} reset command received, simulating it`);
745 // Simulate charging station restart
746 setImmediate(async () => {
747 await this.stop(commandPayload.type);
748 await Utils.sleep(60000);
749 await this.start();
750 });
751 return Constants.OCPP_RESPONSE_ACCEPTED;
752 }
753
61c2e33d
JB
754 _getConfigurationKey(key) {
755 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
756 }
757
3497da01 758 _addConfigurationKey(key, value, readonly = false, visible = true, reboot = false) {
61c2e33d
JB
759 const keyFound = this._getConfigurationKey(key);
760 if (!keyFound) {
761 this._configuration.configurationKey.push({
762 key,
763 readonly,
764 value,
765 visible,
3497da01 766 reboot,
61c2e33d
JB
767 });
768 }
769 }
770
771 _setConfigurationKeyValue(key, value) {
772 const keyFound = this._getConfigurationKey(key);
773 if (keyFound) {
d3a7883e
JB
774 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
775 this._configuration.configurationKey[keyIndex].value = value;
61c2e33d
JB
776 }
777 }
778
34dcb3b5 779 async handleGetConfiguration(commandPayload) {
facd8ebd
JB
780 const configurationKey = [];
781 const unknownKey = [];
61c2e33d
JB
782 if (Utils.isEmptyArray(commandPayload.key)) {
783 for (const configuration of this._configuration.configurationKey) {
784 if (Utils.isUndefined(configuration.visible)) {
785 configuration.visible = true;
786 } else {
787 configuration.visible = Utils.convertToBoolean(configuration.visible);
788 }
789 if (!configuration.visible) {
790 continue;
791 }
792 configurationKey.push({
793 key: configuration.key,
794 readonly: configuration.readonly,
795 value: configuration.value,
796 });
facd8ebd 797 }
61c2e33d 798 } else {
d20c21a0
JB
799 for (const configurationKey of commandPayload.key) {
800 const keyFound = this._getConfigurationKey(configurationKey);
61c2e33d
JB
801 if (keyFound) {
802 if (Utils.isUndefined(keyFound.visible)) {
803 keyFound.visible = true;
804 } else {
d20c21a0 805 keyFound.visible = Utils.convertToBoolean(configurationKey.visible);
61c2e33d
JB
806 }
807 if (!keyFound.visible) {
808 continue;
809 }
810 configurationKey.push({
811 key: keyFound.key,
812 readonly: keyFound.readonly,
813 value: keyFound.value,
814 });
815 } else {
d20c21a0 816 unknownKey.push(configurationKey);
61c2e33d 817 }
facd8ebd 818 }
facd8ebd
JB
819 }
820 return {
821 configurationKey,
822 unknownKey,
823 };
7dde0b73
JB
824 }
825
826 async handleChangeConfiguration(commandPayload) {
61c2e33d 827 const keyToChange = this._getConfigurationKey(commandPayload.key);
7d887a1b
JB
828 if (!keyToChange) {
829 return {status: Constants.OCPP_ERROR_NOT_SUPPORTED};
830 } else if (keyToChange && Utils.convertToBoolean(keyToChange.readonly)) {
831 return Constants.OCPP_RESPONSE_REJECTED;
832 } else if (keyToChange && !Utils.convertToBoolean(keyToChange.readonly)) {
a6e68f34
JB
833 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
834 this._configuration.configurationKey[keyIndex].value = commandPayload.value;
d3a7883e
JB
835 let triggerHeartbeatRestart = false;
836 if (keyToChange.key === 'HeartBeatInterval') {
837 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
838 triggerHeartbeatRestart = true;
839 }
840 if (keyToChange.key === 'HeartbeatInterval') {
841 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
842 triggerHeartbeatRestart = true;
843 }
844 if (triggerHeartbeatRestart) {
5c68da4d
JB
845 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
846 // Stop heartbeat
847 if (this._heartbeatSetInterval) {
848 clearInterval(this._heartbeatSetInterval);
849 this._heartbeatSetInterval = null;
850 }
851 // Start heartbeat
852 this._startHeartbeat(this);
853 }
7d887a1b
JB
854 if (Utils.convertToBoolean(keyToChange.reboot)) {
855 return Constants.OCPP_RESPONSE_REBOOT_REQUIRED;
856 }
dcab13bd 857 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 858 }
7dde0b73
JB
859 }
860
861 async handleRemoteStartTransaction(commandPayload) {
72766a82 862 const transactionConnectorID = commandPayload.connectorId ? commandPayload.connectorId : '1';
2e6f5966 863 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
dcab13bd 864 // Check if authorized
2e6f5966 865 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
7dde0b73 866 // Authorization successful start transaction
61c2e33d 867 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
027b409a 868 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
dcab13bd 869 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 870 }
84393381 871 logger.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo.status + ', idTag ' + commandPayload.idTag);
dcab13bd 872 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 873 }
dcab13bd 874 // No local authorization check required => start transaction
61c2e33d 875 this.sendStartTransactionWithTimeout(transactionConnectorID, commandPayload.idTag, Constants.START_TRANSACTION_TIMEOUT);
027b409a
JB
876 logger.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID + ' for idTag ' + commandPayload.idTag);
877 return Constants.OCPP_RESPONSE_ACCEPTED;
878 }
879
880 async handleRemoteStopTransaction(commandPayload) {
881 for (const connector in this._connectors) {
882 if (this._connectors[connector].transactionId === commandPayload.transactionId) {
d3a7883e
JB
883 this.sendStopTransaction(commandPayload.transactionId);
884 return Constants.OCPP_RESPONSE_ACCEPTED;
027b409a
JB
885 }
886 }
d3a7883e
JB
887 logger.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload.transactionId);
888 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 889 }
7dde0b73
JB
890}
891
892module.exports = ChargingStation;