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