1 const Configuration
= require('../utils/Configuration');
2 const logger
= require('../utils/Logger');
3 const WebSocket
= require('ws');
4 const Constants
= require('../utils/Constants');
5 const Utils
= require('../utils/Utils');
6 const OCPPError
= require('./OcppError');
7 const AutomaticTransactionGenerator
= require('./AutomaticTransactionGenerator');
8 const Statistics
= require('../utils/Statistics');
9 const fs
= require('fs');
10 const crypto
= require('crypto');
11 const {performance
, PerformanceObserver
} = require('perf_hooks');
13 class ChargingStation
{
14 constructor(index
, stationTemplateFile
) {
16 this._stationTemplateFile
= stationTemplateFile
;
17 this._connectors
= {};
20 this._isSocketRestart
= false;
21 this._autoReconnectRetryCount
= 0;
22 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
23 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
26 this._messageQueue
= [];
28 this._authorizedTags
= this._loadAndGetAuthorizedTags();
31 _getStationName(stationTemplate
) {
32 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
36 let stationTemplateFromFile
;
39 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
40 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
41 fs
.closeSync(fileDescriptor
);
43 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: ' + error
);
46 const stationTemplate
= stationTemplateFromFile
|| {};
47 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
48 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
50 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
52 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
53 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
54 return stationTemplate
;
58 this._stationInfo
= this._buildStationInfo();
59 this._bootNotificationMessage
= {
60 chargePointModel
: this._stationInfo
.chargePointModel
,
61 chargePointVendor
: this._stationInfo
.chargePointVendor
,
62 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
63 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
65 this._configuration
= this._getConfiguration();
66 this._supervisionUrl
= this._getSupervisionURL();
67 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
68 // Build connectors if needed
69 const maxConnectors
= this._getMaxNumberOfConnectors();
70 if (maxConnectors
<= 0) {
71 const errMsg
= `${this._logPrefix()} Charging station template with no connectors`;
75 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
76 // FIXME: Handle shrinking the number of connectors
77 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
78 this._connectorsConfigurationHash
= connectorsConfigHash
;
79 // Determine number of customized connectors
81 for (lastConnector
in this._stationInfo
.Connectors
) {
83 if (Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) && Utils
.convertToInt(lastConnector
) === 0 &&
84 this._stationInfo
.Connectors
[lastConnector
]) {
85 this._connectors
[lastConnector
] = Utils
.cloneJSonDocument(this._stationInfo
.Connectors
[lastConnector
]);
88 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
89 if (!this._getConfigurationKey('MeterValuesSampledData')) {
90 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
92 // Generate all connectors
93 for (let index
= 1; index
<= maxConnectors
; index
++) {
94 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
95 this._connectors
[index
] = Utils
.cloneJSonDocument(this._stationInfo
.Connectors
[randConnectorID
]);
98 // Avoid duplication of connectors related information
99 delete this._stationInfo
.Connectors
;
100 // Initialize transaction attributes on connectors
101 for (const connector
in this._connectors
) {
102 if (!this.getConnector(connector
).transactionStarted
) {
103 this._initTransactionOnConnector(connector
);
106 this._stationInfo
.powerDivider
= this._getPowerDivider();
107 if (this.getEnableStatistics()) {
108 this._statistics
= Statistics
.getInstance();
109 this._statistics
.objName
= this._stationInfo
.name
;
110 this._performanceObserver
= new PerformanceObserver((list
) => {
111 const entry
= list
.getEntries()[0];
112 this._statistics
.logPerformance(entry
, 'ChargingStation');
113 this._performanceObserver
.disconnect();
119 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
122 _getConfiguration() {
123 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
126 _getAuthorizationFile() {
127 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
130 _loadAndGetAuthorizedTags() {
131 let authorizedTags
= [];
132 const authorizationFile
= this._getAuthorizationFile();
133 if (authorizationFile
) {
135 // Load authorization file
136 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
137 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
138 fs
.closeSync(fileDescriptor
);
140 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: ' + error
);
144 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
146 return authorizedTags
;
150 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
151 return this._authorizedTags
[index
];
154 hasAuthorizedTags() {
155 return !Utils
.isEmptyArray(this._authorizedTags
);
158 getEnableStatistics() {
159 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? this._stationInfo
.enableStatistics
: true;
162 _getNumberOfRunningTransactions() {
164 for (const connector
in this._connectors
) {
165 if (this.getConnector(connector
).transactionStarted
) {
173 let powerDivider
= this._getNumberOfConnectors();
174 if (this._stationInfo
.powerSharedByConnectors
) {
175 powerDivider
= this._getNumberOfRunningTransactions();
181 return this._connectors
[Utils
.convertToInt(id
)];
184 _getMaxNumberOfConnectors() {
185 let maxConnectors
= 0;
186 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
187 // Distribute evenly the number of connectors
188 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
190 maxConnectors
= this._stationInfo
.numberOfConnectors
;
192 return maxConnectors
;
195 _getNumberOfConnectors() {
196 return Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) ? Object
.keys(this._connectors
).length
- 1 : Object
.keys(this._connectors
).length
;
199 _getSupervisionURL() {
200 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
202 if (!Utils
.isEmptyArray(supervisionUrls
)) {
203 if (Configuration
.getDistributeStationToTenantEqually()) {
204 indexUrl
= this._index
% supervisionUrls
.length
;
207 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
209 return supervisionUrls
[indexUrl
];
211 return supervisionUrls
;
214 _getAuthorizeRemoteTxRequests() {
215 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
216 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
219 _getLocalAuthListEnabled() {
220 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
221 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
224 async
_basicStartMessageSequence() {
226 this._startHeartbeat(this);
227 // Initialize connectors status
228 for (const connector
in this._connectors
) {
229 if (!this.getConnector(connector
).transactionStarted
) {
230 if (this.getConnector(connector
).bootStatus
) {
231 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(connector
).bootStatus
);
233 this.sendStatusNotificationWithTimeout(connector
, 'Available');
236 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
240 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
241 if (!this._automaticTransactionGeneration
) {
242 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
244 if (this._automaticTransactionGeneration
.timeToStop
) {
245 this._automaticTransactionGeneration
.start();
248 if (this.getEnableStatistics()) {
249 this._statistics
.start();
253 // eslint-disable-next-line class-methods-use-this
254 async
_startHeartbeat(self
) {
255 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
256 self
._heartbeatSetInterval
= setInterval(() => {
257 this.sendHeartbeat();
258 }, self
._heartbeatInterval
);
259 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
261 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
265 async
_stopHeartbeat() {
266 if (this._heartbeatSetInterval
) {
267 clearInterval(this._heartbeatSetInterval
);
268 this._heartbeatSetInterval
= null;
272 _startAuthorizationFileMonitoring() {
273 // eslint-disable-next-line no-unused-vars
274 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
276 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
277 // Initialize _authorizedTags
278 this._authorizedTags
= this._loadAndGetAuthorizedTags();
280 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
285 _startStationTemplateFileMonitoring() {
286 // eslint-disable-next-line no-unused-vars
287 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
289 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
292 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
293 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
295 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
300 async
_startMeterValues(connectorId
, interval
) {
301 if (!this.getConnector(connectorId
).transactionStarted
) {
302 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
304 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
305 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
309 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
310 if (this.getEnableStatistics()) {
311 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
312 this._performanceObserver
.observe({
313 entryTypes
: ['function'],
315 await
sendMeterValues(connectorId
, interval
, this);
317 await
this.sendMeterValues(connectorId
, interval
, this);
321 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
326 if (!this._wsConnectionUrl
) {
327 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
329 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
330 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
331 // Monitor authorization file
332 this._startAuthorizationFileMonitoring();
333 // Monitor station template file
334 this._startStationTemplateFileMonitoring();
335 // Handle Socket incoming messages
336 this._wsConnection
.on('message', this.onMessage
.bind(this));
337 // Handle Socket error
338 this._wsConnection
.on('error', this.onError
.bind(this));
339 // Handle Socket close
340 this._wsConnection
.on('close', this.onClose
.bind(this));
341 // Handle Socket opening connection
342 this._wsConnection
.on('open', this.onOpen
.bind(this));
343 // Handle Socket ping
344 this._wsConnection
.on('ping', this.onPing
.bind(this));
347 async
stop(reason
= '') {
349 await
this._stopHeartbeat();
351 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
352 this._automaticTransactionGeneration
&&
353 !this._automaticTransactionGeneration
.timeToStop
) {
354 await
this._automaticTransactionGeneration
.stop(reason
);
356 for (const connector
in this._connectors
) {
357 if (this.getConnector(connector
).transactionStarted
) {
358 await
this.sendStopTransaction(this.getConnector(connector
).transactionId
, reason
);
362 // eslint-disable-next-line guard-for-in
363 for (const connector
in this._connectors
) {
364 await
this.sendStatusNotification(connector
, 'Unavailable');
366 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
367 await
this._wsConnection
.close();
372 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
373 // Stop the ATG if needed
374 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
375 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
376 this._automaticTransactionGeneration
&&
377 !this._automaticTransactionGeneration
.timeToStop
) {
378 this._automaticTransactionGeneration
.stop();
381 this._stopHeartbeat();
382 if (this._autoReconnectTimeout
!== 0 &&
383 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
384 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
385 this._autoReconnectRetryCount
++;
387 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
389 }, this._autoReconnectTimeout
);
390 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
391 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
396 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
397 if (!this._isSocketRestart
) {
398 // Send BootNotification
399 this.sendBootNotification();
401 if (this._isSocketRestart
) {
402 this._basicStartMessageSequence();
403 if (!Utils
.isEmptyArray(this._messageQueue
)) {
404 this._messageQueue
.forEach((message
) => {
405 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
406 this._wsConnection
.send(message
);
411 this._autoReconnectRetryCount
= 0;
412 this._isSocketRestart
= false;
418 this._isSocketRestart
= true;
419 this._reconnect(error
);
422 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
429 case 1000: // Normal close
431 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
432 this._autoReconnectRetryCount
= 0;
434 default: // Abnormal close
435 this._isSocketRestart
= true;
436 this._reconnect(error
);
442 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
445 async
onMessage(message
) {
446 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
449 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
451 // Check the Type of message
452 switch (messageType
) {
454 case Constants
.OCPP_JSON_CALL_MESSAGE
:
456 await
this.handleRequest(messageId
, commandName
, commandPayload
);
459 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
461 // eslint-disable-next-line no-case-declarations
462 let responseCallback
; let requestPayload
;
463 if (Utils
.isIterable(this._requests
[messageId
])) {
464 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
466 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
468 if (!responseCallback
) {
470 throw new Error(`Response for unknown message id ${messageId}`);
472 delete this._requests
[messageId
];
473 responseCallback(commandName
, requestPayload
);
476 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
477 if (!this._requests
[messageId
]) {
479 throw new Error(`Error for unknown message id ${messageId}`);
481 // eslint-disable-next-line no-case-declarations
483 if (Utils
.isIterable(this._requests
[messageId
])) {
484 [, rejectCallback
] = this._requests
[messageId
];
486 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
488 delete this._requests
[messageId
];
489 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
493 throw new Error(`Wrong message type ${messageType}`);
497 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
499 // await this.sendError(messageId, error);
506 currentTime
: new Date().toISOString(),
508 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
510 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
515 sendBootNotification() {
517 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
519 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
524 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
531 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
533 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
538 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
539 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
542 async
sendStartTransaction(connectorId
, idTag
) {
548 timestamp
: new Date().toISOString(),
550 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
552 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
557 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
558 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
561 async
sendStopTransaction(transactionId
, reason
= '') {
568 timestamp
: new Date().toISOString(),
575 timestamp
: new Date().toISOString(),
578 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
580 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
585 // eslint-disable-next-line class-methods-use-this
586 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
588 const sampledValueLcl
= {
589 timestamp
: new Date().toISOString(),
591 const meterValuesClone
= Utils
.cloneJSonDocument(self
.getConnector(connectorId
).MeterValues
);
592 if (!Utils
.isEmptyArray(meterValuesClone
)) {
593 sampledValueLcl
.sampledValue
= meterValuesClone
;
595 sampledValueLcl
.sampledValue
= [meterValuesClone
];
597 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
598 const connector
= self
.getConnector(connectorId
);
600 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
601 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
602 sampledValueLcl
.sampledValue
[index
].value
:
603 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
604 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
605 logger
.error(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}`);
608 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
609 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
610 // Energy.Active.Import.Register measurand (default)
611 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
612 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
613 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
614 logger
.error(errMsg
);
616 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
617 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
618 logger
.error(errMsg
);
621 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
622 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
623 // Persist previous value in connector
624 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
625 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
627 connector
.lastEnergyActiveImportRegisterValue
= 0;
629 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
631 logger
.info(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value ${sampledValueLcl.sampledValue[index].value}`);
632 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
633 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
634 logger
.error(`${self._logPrefix()} 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}`);
636 // Unsupported measurand
638 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
644 transactionId
: self
.getConnector(connectorId
).transactionId
,
645 meterValue
: [sampledValueLcl
],
647 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
649 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
654 sendError(messageId
, err
) {
655 // Check exception: only OCPP error are accepted
656 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
658 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
661 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
662 // Send a message through wsConnection
665 return new Promise((resolve
, reject
) => {
668 switch (messageType
) {
670 case Constants
.OCPP_JSON_CALL_MESSAGE
:
671 if (this.getEnableStatistics()) {
672 this._statistics
.addMessage(commandName
);
675 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
676 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
679 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
680 if (this.getEnableStatistics()) {
681 this._statistics
.addMessage(commandName
);
684 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
687 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
688 if (this.getEnableStatistics()) {
689 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
692 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
695 // Check if wsConnection is ready
696 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
698 this._wsConnection
.send(messageToSend
);
700 // Buffer message until connection is back
701 this._messageQueue
.push(messageToSend
);
704 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
707 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
708 // Send timeout in case connection is open otherwise wait for ever
709 // FIXME: Handle message on timeout
710 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
713 // Function that will receive the request's response
714 function responseCallback(payload
, requestPayload
) {
715 if (self
.getEnableStatistics()) {
716 self
._statistics
.addMessage(commandName
, true);
718 const responseCallbackFn
= 'handleResponse' + commandName
;
719 if (typeof self
[responseCallbackFn
] === 'function') {
720 self
[responseCallbackFn
](payload
, requestPayload
, self
);
722 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
728 // Function that will receive the request's rejection
729 function rejectCallback(reason
) {
730 if (self
.getEnableStatistics()) {
731 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
734 // eslint-disable-next-line no-empty-function
735 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
736 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
743 handleResponseBootNotification(payload
) {
744 if (payload
.status
=== 'Accepted') {
745 this._heartbeatInterval
= payload
.interval
* 1000;
746 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
747 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
748 this._basicStartMessageSequence();
749 } else if (payload
.status
=== 'Pending') {
750 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
752 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
756 _initTransactionOnConnector(connectorId
) {
757 this.getConnector(connectorId
).transactionStarted
= false;
758 this.getConnector(connectorId
).transactionId
= null;
759 this.getConnector(connectorId
).idTag
= null;
760 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
763 _resetTransactionOnConnector(connectorId
) {
764 this._initTransactionOnConnector(connectorId
);
765 if (this.getConnector(connectorId
).transactionSetInterval
) {
766 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
770 handleResponseStartTransaction(payload
, requestPayload
) {
771 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
772 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
776 let transactionConnectorId
;
777 for (const connector
in this._connectors
) {
778 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
779 transactionConnectorId
= connector
;
783 if (!transactionConnectorId
) {
784 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
787 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
788 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
789 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
790 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
791 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
792 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
793 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
794 if (this._stationInfo
.powerSharedByConnectors
) {
795 this._stationInfo
.powerDivider
++;
797 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
798 this._startMeterValues(requestPayload
.connectorId
,
799 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
801 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
802 this._resetTransactionOnConnector(requestPayload
.connectorId
);
803 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
807 handleResponseStopTransaction(payload
, requestPayload
) {
808 let transactionConnectorId
;
809 for (const connector
in this._connectors
) {
810 if (this.getConnector(connector
).transactionId
=== requestPayload
.transactionId
) {
811 transactionConnectorId
= connector
;
815 if (!transactionConnectorId
) {
816 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
819 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
820 this.sendStatusNotification(transactionConnectorId
, 'Available');
821 if (this._stationInfo
.powerSharedByConnectors
) {
822 this._stationInfo
.powerDivider
--;
824 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
825 this._resetTransactionOnConnector(transactionConnectorId
);
827 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
831 handleResponseStatusNotification(payload
, requestPayload
) {
832 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
835 handleResponseMeterValues(payload
, requestPayload
) {
836 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
839 handleResponseHeartbeat(payload
, requestPayload
) {
840 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
843 async
handleRequest(messageId
, commandName
, commandPayload
) {
844 if (this.getEnableStatistics()) {
845 this._statistics
.addMessage(commandName
, true);
849 if (typeof this['handle' + commandName
] === 'function') {
852 result
= await
this['handle' + commandName
](commandPayload
);
855 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
856 // Send back response to inform backend
857 await
this.sendError(messageId
, error
);
861 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
862 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
865 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
868 async
handleReset(commandPayload
) {
869 // Simulate charging station restart
870 setImmediate(async () => {
871 await
this.stop(commandPayload
.type
+ 'Reset');
872 await Utils
.sleep(this._stationInfo
.resetTime
);
875 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
876 return Constants
.OCPP_RESPONSE_ACCEPTED
;
879 _getConfigurationKey(key
) {
880 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
883 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
884 const keyFound
= this._getConfigurationKey(key
);
886 this._configuration
.configurationKey
.push({
896 _setConfigurationKeyValue(key
, value
) {
897 const keyFound
= this._getConfigurationKey(key
);
899 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
900 this._configuration
.configurationKey
[keyIndex
].value
= value
;
904 async
handleGetConfiguration(commandPayload
) {
905 const configurationKey
= [];
906 const unknownKey
= [];
907 if (Utils
.isEmptyArray(commandPayload
.key
)) {
908 for (const configuration
of this._configuration
.configurationKey
) {
909 if (Utils
.isUndefined(configuration
.visible
)) {
910 configuration
.visible
= true;
912 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
914 if (!configuration
.visible
) {
917 configurationKey
.push({
918 key
: configuration
.key
,
919 readonly
: configuration
.readonly
,
920 value
: configuration
.value
,
924 for (const configurationKey
of commandPayload
.key
) {
925 const keyFound
= this._getConfigurationKey(configurationKey
);
927 if (Utils
.isUndefined(keyFound
.visible
)) {
928 keyFound
.visible
= true;
930 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
932 if (!keyFound
.visible
) {
935 configurationKey
.push({
937 readonly
: keyFound
.readonly
,
938 value
: keyFound
.value
,
941 unknownKey
.push(configurationKey
);
951 async
handleChangeConfiguration(commandPayload
) {
952 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
954 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
955 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
956 return Constants
.OCPP_RESPONSE_REJECTED
;
957 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
958 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
959 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
960 let triggerHeartbeatRestart
= false;
961 if (keyToChange
.key
=== 'HeartBeatInterval') {
962 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
963 triggerHeartbeatRestart
= true;
965 if (keyToChange
.key
=== 'HeartbeatInterval') {
966 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
967 triggerHeartbeatRestart
= true;
969 if (triggerHeartbeatRestart
) {
970 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
972 this._stopHeartbeat();
974 this._startHeartbeat(this);
976 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
977 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
979 return Constants
.OCPP_RESPONSE_ACCEPTED
;
983 async
handleRemoteStartTransaction(commandPayload
) {
984 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
985 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
986 // Check if authorized
987 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
988 // Authorization successful start transaction
989 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
990 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
991 return Constants
.OCPP_RESPONSE_ACCEPTED
;
993 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
994 return Constants
.OCPP_RESPONSE_REJECTED
;
996 // No local authorization check required => start transaction
997 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
998 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
999 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1002 async
handleRemoteStopTransaction(commandPayload
) {
1003 for (const connector
in this._connectors
) {
1004 if (this.getConnector(connector
).transactionId
=== commandPayload
.transactionId
) {
1005 this.sendStopTransaction(commandPayload
.transactionId
);
1006 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1009 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1010 return Constants
.OCPP_RESPONSE_REJECTED
;
1014 module
.exports
= ChargingStation
;