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 ${this._stationTemplateFile} 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
) && this._stationInfo
.Connectors
[lastConnector
] &&
84 lastConnector
=== 0) {
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');
93 if (maxConnectors
> lastConnector
&& !Utils
.convertToBoolean(this._stationInfo
.randomConnectors
)) {
94 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
95 this._stationInfo
.randomConnectors
= true;
97 // Generate all connectors
98 for (let index
= 1; index
<= maxConnectors
; index
++) {
99 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
100 this._connectors
[index
] = Utils
.cloneJSonDocument(this._stationInfo
.Connectors
[randConnectorID
]);
103 // Avoid duplication of connectors related information
104 delete this._stationInfo
.Connectors
;
105 // Initialize transaction attributes on connectors
106 for (const connector
in this._connectors
) {
107 if (!this.getConnector(connector
).transactionStarted
) {
108 this._initTransactionOnConnector(connector
);
111 this._stationInfo
.powerDivider
= this._getPowerDivider();
112 if (this.getEnableStatistics()) {
113 this._statistics
= Statistics
.getInstance();
114 this._statistics
.objName
= this._stationInfo
.name
;
115 this._performanceObserver
= new PerformanceObserver((list
) => {
116 const entry
= list
.getEntries()[0];
117 this._statistics
.logPerformance(entry
, 'ChargingStation');
118 this._performanceObserver
.disconnect();
124 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
127 _getConfiguration() {
128 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
131 _getAuthorizationFile() {
132 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
135 _loadAndGetAuthorizedTags() {
136 let authorizedTags
= [];
137 const authorizationFile
= this._getAuthorizationFile();
138 if (authorizationFile
) {
140 // Load authorization file
141 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
142 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
143 fs
.closeSync(fileDescriptor
);
145 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: ' + error
);
149 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
151 return authorizedTags
;
155 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
156 return this._authorizedTags
[index
];
159 hasAuthorizedTags() {
160 return !Utils
.isEmptyArray(this._authorizedTags
);
163 getEnableStatistics() {
164 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? this._stationInfo
.enableStatistics
: true;
167 _getNumberOfRunningTransactions() {
169 for (const connector
in this._connectors
) {
170 if (this.getConnector(connector
).transactionStarted
) {
178 let powerDivider
= this._getNumberOfConnectors();
179 if (this._stationInfo
.powerSharedByConnectors
) {
180 powerDivider
= this._getNumberOfRunningTransactions();
186 return this._connectors
[Utils
.convertToInt(id
)];
189 _getMaxNumberOfConnectors() {
190 let maxConnectors
= 0;
191 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
192 // Distribute evenly the number of connectors
193 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
194 } else if (this._stationInfo
.numberOfConnectors
) {
195 maxConnectors
= this._stationInfo
.numberOfConnectors
;
197 maxConnectors
= Object
.keys(this._stationInfo
.Connectors
).length
;
199 return maxConnectors
;
202 _getNumberOfConnectors() {
203 return Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) ? Object
.keys(this._connectors
).length
- 1 : Object
.keys(this._connectors
).length
;
206 _getSupervisionURL() {
207 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
209 if (!Utils
.isEmptyArray(supervisionUrls
)) {
210 if (Configuration
.getDistributeStationToTenantEqually()) {
211 indexUrl
= this._index
% supervisionUrls
.length
;
214 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
216 return supervisionUrls
[indexUrl
];
218 return supervisionUrls
;
221 _getAuthorizeRemoteTxRequests() {
222 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
223 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
226 _getLocalAuthListEnabled() {
227 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
228 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
231 async
_basicStartMessageSequence() {
233 this._startHeartbeat(this);
234 // Initialize connectors status
235 for (const connector
in this._connectors
) {
236 if (!this.getConnector(connector
).transactionStarted
) {
237 if (this.getConnector(connector
).bootStatus
) {
238 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(connector
).bootStatus
);
240 this.sendStatusNotificationWithTimeout(connector
, 'Available');
243 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
247 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
248 if (!this._automaticTransactionGeneration
) {
249 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
251 if (this._automaticTransactionGeneration
.timeToStop
) {
252 this._automaticTransactionGeneration
.start();
255 if (this.getEnableStatistics()) {
256 this._statistics
.start();
260 // eslint-disable-next-line class-methods-use-this
261 async
_startHeartbeat(self
) {
262 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
263 self
._heartbeatSetInterval
= setInterval(() => {
264 this.sendHeartbeat();
265 }, self
._heartbeatInterval
);
266 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
268 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
272 async
_stopHeartbeat() {
273 if (this._heartbeatSetInterval
) {
274 clearInterval(this._heartbeatSetInterval
);
275 this._heartbeatSetInterval
= null;
279 _startAuthorizationFileMonitoring() {
280 // eslint-disable-next-line no-unused-vars
281 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
283 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
284 // Initialize _authorizedTags
285 this._authorizedTags
= this._loadAndGetAuthorizedTags();
287 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
292 _startStationTemplateFileMonitoring() {
293 // eslint-disable-next-line no-unused-vars
294 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
296 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
299 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
300 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
302 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
307 async
_startMeterValues(connectorId
, interval
) {
308 if (!this.getConnector(connectorId
).transactionStarted
) {
309 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
311 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
312 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
316 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
317 if (this.getEnableStatistics()) {
318 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
319 this._performanceObserver
.observe({
320 entryTypes
: ['function'],
322 await
sendMeterValues(connectorId
, interval
, this);
324 await
this.sendMeterValues(connectorId
, interval
, this);
328 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
333 if (!this._wsConnectionUrl
) {
334 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
336 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
337 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
338 // Monitor authorization file
339 this._startAuthorizationFileMonitoring();
340 // Monitor station template file
341 this._startStationTemplateFileMonitoring();
342 // Handle Socket incoming messages
343 this._wsConnection
.on('message', this.onMessage
.bind(this));
344 // Handle Socket error
345 this._wsConnection
.on('error', this.onError
.bind(this));
346 // Handle Socket close
347 this._wsConnection
.on('close', this.onClose
.bind(this));
348 // Handle Socket opening connection
349 this._wsConnection
.on('open', this.onOpen
.bind(this));
350 // Handle Socket ping
351 this._wsConnection
.on('ping', this.onPing
.bind(this));
354 async
stop(reason
= '') {
356 await
this._stopHeartbeat();
358 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
359 this._automaticTransactionGeneration
&&
360 !this._automaticTransactionGeneration
.timeToStop
) {
361 await
this._automaticTransactionGeneration
.stop(reason
);
363 for (const connector
in this._connectors
) {
364 if (this.getConnector(connector
).transactionStarted
) {
365 await
this.sendStopTransaction(this.getConnector(connector
).transactionId
, reason
);
369 // eslint-disable-next-line guard-for-in
370 for (const connector
in this._connectors
) {
371 await
this.sendStatusNotification(connector
, 'Unavailable');
373 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
374 await
this._wsConnection
.close();
379 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
380 // Stop the ATG if needed
381 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
382 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
383 this._automaticTransactionGeneration
&&
384 !this._automaticTransactionGeneration
.timeToStop
) {
385 this._automaticTransactionGeneration
.stop();
388 this._stopHeartbeat();
389 if (this._autoReconnectTimeout
!== 0 &&
390 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
391 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
392 this._autoReconnectRetryCount
++;
394 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
396 }, this._autoReconnectTimeout
);
397 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
398 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
403 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
404 if (!this._isSocketRestart
) {
405 // Send BootNotification
406 this.sendBootNotification();
408 if (this._isSocketRestart
) {
409 this._basicStartMessageSequence();
410 if (!Utils
.isEmptyArray(this._messageQueue
)) {
411 this._messageQueue
.forEach((message
) => {
412 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
413 this._wsConnection
.send(message
);
418 this._autoReconnectRetryCount
= 0;
419 this._isSocketRestart
= false;
425 this._isSocketRestart
= true;
426 this._reconnect(error
);
429 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
436 case 1000: // Normal close
438 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
439 this._autoReconnectRetryCount
= 0;
441 default: // Abnormal close
442 this._isSocketRestart
= true;
443 this._reconnect(error
);
449 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
452 async
onMessage(message
) {
453 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
456 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
458 // Check the Type of message
459 switch (messageType
) {
461 case Constants
.OCPP_JSON_CALL_MESSAGE
:
463 await
this.handleRequest(messageId
, commandName
, commandPayload
);
466 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
468 // eslint-disable-next-line no-case-declarations
469 let responseCallback
; let requestPayload
;
470 if (Utils
.isIterable(this._requests
[messageId
])) {
471 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
473 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
475 if (!responseCallback
) {
477 throw new Error(`Response for unknown message id ${messageId}`);
479 delete this._requests
[messageId
];
480 responseCallback(commandName
, requestPayload
);
483 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
484 if (!this._requests
[messageId
]) {
486 throw new Error(`Error for unknown message id ${messageId}`);
488 // eslint-disable-next-line no-case-declarations
490 if (Utils
.isIterable(this._requests
[messageId
])) {
491 [, rejectCallback
] = this._requests
[messageId
];
493 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
495 delete this._requests
[messageId
];
496 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
500 throw new Error(`Wrong message type ${messageType}`);
504 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
506 // await this.sendError(messageId, error);
513 currentTime
: new Date().toISOString(),
515 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
517 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
522 sendBootNotification() {
524 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
526 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
531 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
538 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
540 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
545 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
546 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
549 async
sendStartTransaction(connectorId
, idTag
) {
555 timestamp
: new Date().toISOString(),
557 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
559 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
564 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
565 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
568 async
sendStopTransaction(transactionId
, reason
= '') {
575 timestamp
: new Date().toISOString(),
582 timestamp
: new Date().toISOString(),
585 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
587 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
592 // eslint-disable-next-line class-methods-use-this
593 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
595 const sampledValueLcl
= {
596 timestamp
: new Date().toISOString(),
598 const meterValuesClone
= Utils
.cloneJSonDocument(self
.getConnector(connectorId
).MeterValues
);
599 if (!Utils
.isEmptyArray(meterValuesClone
)) {
600 sampledValueLcl
.sampledValue
= meterValuesClone
;
602 sampledValueLcl
.sampledValue
= [meterValuesClone
];
604 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
605 const connector
= self
.getConnector(connectorId
);
607 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
608 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
609 sampledValueLcl
.sampledValue
[index
].value
:
610 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
611 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
612 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}`);
615 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
616 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
617 // Energy.Active.Import.Register measurand (default)
618 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
619 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
620 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
621 logger
.error(errMsg
);
623 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
624 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}`;
625 logger
.error(errMsg
);
628 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
629 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
630 // Persist previous value in connector
631 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
632 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
634 connector
.lastEnergyActiveImportRegisterValue
= 0;
636 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
638 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}`);
639 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
640 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
641 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}`);
643 // Unsupported measurand
645 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
651 transactionId
: self
.getConnector(connectorId
).transactionId
,
652 meterValue
: [sampledValueLcl
],
654 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
656 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
661 sendError(messageId
, err
) {
662 // Check exception: only OCPP error are accepted
663 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
665 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
668 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
669 // Send a message through wsConnection
672 return new Promise((resolve
, reject
) => {
675 switch (messageType
) {
677 case Constants
.OCPP_JSON_CALL_MESSAGE
:
678 if (this.getEnableStatistics()) {
679 this._statistics
.addMessage(commandName
);
682 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
683 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
686 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
687 if (this.getEnableStatistics()) {
688 this._statistics
.addMessage(commandName
);
691 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
694 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
695 if (this.getEnableStatistics()) {
696 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
699 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
702 // Check if wsConnection is ready
703 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
705 this._wsConnection
.send(messageToSend
);
707 // Buffer message until connection is back
708 this._messageQueue
.push(messageToSend
);
711 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
714 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
715 // Send timeout in case connection is open otherwise wait for ever
716 // FIXME: Handle message on timeout
717 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
720 // Function that will receive the request's response
721 function responseCallback(payload
, requestPayload
) {
722 if (self
.getEnableStatistics()) {
723 self
._statistics
.addMessage(commandName
, true);
725 const responseCallbackFn
= 'handleResponse' + commandName
;
726 if (typeof self
[responseCallbackFn
] === 'function') {
727 self
[responseCallbackFn
](payload
, requestPayload
, self
);
729 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
735 // Function that will receive the request's rejection
736 function rejectCallback(reason
) {
737 if (self
.getEnableStatistics()) {
738 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
741 // eslint-disable-next-line no-empty-function
742 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
743 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
750 handleResponseBootNotification(payload
) {
751 if (payload
.status
=== 'Accepted') {
752 this._heartbeatInterval
= payload
.interval
* 1000;
753 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
754 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
755 this._basicStartMessageSequence();
756 } else if (payload
.status
=== 'Pending') {
757 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
759 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
763 _initTransactionOnConnector(connectorId
) {
764 this.getConnector(connectorId
).transactionStarted
= false;
765 this.getConnector(connectorId
).transactionId
= null;
766 this.getConnector(connectorId
).idTag
= null;
767 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
770 _resetTransactionOnConnector(connectorId
) {
771 this._initTransactionOnConnector(connectorId
);
772 if (this.getConnector(connectorId
).transactionSetInterval
) {
773 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
777 handleResponseStartTransaction(payload
, requestPayload
) {
778 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
779 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
783 let transactionConnectorId
;
784 for (const connector
in this._connectors
) {
785 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
786 transactionConnectorId
= connector
;
790 if (!transactionConnectorId
) {
791 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
794 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
795 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
796 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
797 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
798 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
799 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
800 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
801 if (this._stationInfo
.powerSharedByConnectors
) {
802 this._stationInfo
.powerDivider
++;
804 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
805 this._startMeterValues(requestPayload
.connectorId
,
806 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
808 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
809 this._resetTransactionOnConnector(requestPayload
.connectorId
);
810 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
814 handleResponseStopTransaction(payload
, requestPayload
) {
815 let transactionConnectorId
;
816 for (const connector
in this._connectors
) {
817 if (this.getConnector(connector
).transactionId
=== requestPayload
.transactionId
) {
818 transactionConnectorId
= connector
;
822 if (!transactionConnectorId
) {
823 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
826 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
827 this.sendStatusNotification(transactionConnectorId
, 'Available');
828 if (this._stationInfo
.powerSharedByConnectors
) {
829 this._stationInfo
.powerDivider
--;
831 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
832 this._resetTransactionOnConnector(transactionConnectorId
);
834 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
838 handleResponseStatusNotification(payload
, requestPayload
) {
839 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
842 handleResponseMeterValues(payload
, requestPayload
) {
843 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
846 handleResponseHeartbeat(payload
, requestPayload
) {
847 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
850 async
handleRequest(messageId
, commandName
, commandPayload
) {
851 if (this.getEnableStatistics()) {
852 this._statistics
.addMessage(commandName
, true);
856 if (typeof this['handle' + commandName
] === 'function') {
859 result
= await
this['handle' + commandName
](commandPayload
);
862 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
863 // Send back response to inform backend
864 await
this.sendError(messageId
, error
);
868 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
869 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
872 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
875 async
handleReset(commandPayload
) {
876 // Simulate charging station restart
877 setImmediate(async () => {
878 await
this.stop(commandPayload
.type
+ 'Reset');
879 await Utils
.sleep(this._stationInfo
.resetTime
);
882 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
883 return Constants
.OCPP_RESPONSE_ACCEPTED
;
886 _getConfigurationKey(key
) {
887 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
890 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
891 const keyFound
= this._getConfigurationKey(key
);
893 this._configuration
.configurationKey
.push({
903 _setConfigurationKeyValue(key
, value
) {
904 const keyFound
= this._getConfigurationKey(key
);
906 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
907 this._configuration
.configurationKey
[keyIndex
].value
= value
;
911 async
handleGetConfiguration(commandPayload
) {
912 const configurationKey
= [];
913 const unknownKey
= [];
914 if (Utils
.isEmptyArray(commandPayload
.key
)) {
915 for (const configuration
of this._configuration
.configurationKey
) {
916 if (Utils
.isUndefined(configuration
.visible
)) {
917 configuration
.visible
= true;
919 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
921 if (!configuration
.visible
) {
924 configurationKey
.push({
925 key
: configuration
.key
,
926 readonly
: configuration
.readonly
,
927 value
: configuration
.value
,
931 for (const configurationKey
of commandPayload
.key
) {
932 const keyFound
= this._getConfigurationKey(configurationKey
);
934 if (Utils
.isUndefined(keyFound
.visible
)) {
935 keyFound
.visible
= true;
937 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
939 if (!keyFound
.visible
) {
942 configurationKey
.push({
944 readonly
: keyFound
.readonly
,
945 value
: keyFound
.value
,
948 unknownKey
.push(configurationKey
);
958 async
handleChangeConfiguration(commandPayload
) {
959 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
961 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
962 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
963 return Constants
.OCPP_RESPONSE_REJECTED
;
964 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
965 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
966 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
967 let triggerHeartbeatRestart
= false;
968 if (keyToChange
.key
=== 'HeartBeatInterval') {
969 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
970 triggerHeartbeatRestart
= true;
972 if (keyToChange
.key
=== 'HeartbeatInterval') {
973 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
974 triggerHeartbeatRestart
= true;
976 if (triggerHeartbeatRestart
) {
977 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
979 this._stopHeartbeat();
981 this._startHeartbeat(this);
983 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
984 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
986 return Constants
.OCPP_RESPONSE_ACCEPTED
;
990 async
handleRemoteStartTransaction(commandPayload
) {
991 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
992 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
993 // Check if authorized
994 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
995 // Authorization successful start transaction
996 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
997 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
998 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1000 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
1001 return Constants
.OCPP_RESPONSE_REJECTED
;
1003 // No local authorization check required => start transaction
1004 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
1005 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1006 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1009 async
handleRemoteStopTransaction(commandPayload
) {
1010 for (const connector
in this._connectors
) {
1011 if (this.getConnector(connector
).transactionId
=== commandPayload
.transactionId
) {
1012 this.sendStopTransaction(commandPayload
.transactionId
);
1013 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1016 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1017 return Constants
.OCPP_RESPONSE_REJECTED
;
1021 module
.exports
= ChargingStation
;