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
= Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) ? Object
.keys(this._stationInfo
.Connectors
).length
- 1 :
198 Object
.keys(this._stationInfo
.Connectors
).length
;
200 return maxConnectors
;
203 _getNumberOfConnectors() {
204 return Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) ? Object
.keys(this._connectors
).length
- 1 : Object
.keys(this._connectors
).length
;
207 _getSupervisionURL() {
208 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
210 if (!Utils
.isEmptyArray(supervisionUrls
)) {
211 if (Configuration
.getDistributeStationToTenantEqually()) {
212 indexUrl
= this._index
% supervisionUrls
.length
;
215 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
217 return supervisionUrls
[indexUrl
];
219 return supervisionUrls
;
222 _getAuthorizeRemoteTxRequests() {
223 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
224 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
227 _getLocalAuthListEnabled() {
228 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
229 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
232 async
_basicStartMessageSequence() {
234 this._startHeartbeat(this);
235 // Initialize connectors status
236 for (const connector
in this._connectors
) {
237 if (!this.getConnector(connector
).transactionStarted
) {
238 if (this.getConnector(connector
).bootStatus
) {
239 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(connector
).bootStatus
);
241 this.sendStatusNotificationWithTimeout(connector
, 'Available');
244 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
248 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
249 if (!this._automaticTransactionGeneration
) {
250 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
252 if (this._automaticTransactionGeneration
.timeToStop
) {
253 this._automaticTransactionGeneration
.start();
256 if (this.getEnableStatistics()) {
257 this._statistics
.start();
261 // eslint-disable-next-line class-methods-use-this
262 async
_startHeartbeat(self
) {
263 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
264 self
._heartbeatSetInterval
= setInterval(() => {
265 this.sendHeartbeat();
266 }, self
._heartbeatInterval
);
267 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
269 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
273 async
_stopHeartbeat() {
274 if (this._heartbeatSetInterval
) {
275 clearInterval(this._heartbeatSetInterval
);
276 this._heartbeatSetInterval
= null;
280 _startAuthorizationFileMonitoring() {
281 // eslint-disable-next-line no-unused-vars
282 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
284 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
285 // Initialize _authorizedTags
286 this._authorizedTags
= this._loadAndGetAuthorizedTags();
288 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
293 _startStationTemplateFileMonitoring() {
294 // eslint-disable-next-line no-unused-vars
295 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
297 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
300 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
301 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
303 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
308 async
_startMeterValues(connectorId
, interval
) {
309 if (!this.getConnector(connectorId
).transactionStarted
) {
310 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
312 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
313 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
317 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
318 if (this.getEnableStatistics()) {
319 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
320 this._performanceObserver
.observe({
321 entryTypes
: ['function'],
323 await
sendMeterValues(connectorId
, interval
, this);
325 await
this.sendMeterValues(connectorId
, interval
, this);
329 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
334 if (!this._wsConnectionUrl
) {
335 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
337 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
338 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
339 // Monitor authorization file
340 this._startAuthorizationFileMonitoring();
341 // Monitor station template file
342 this._startStationTemplateFileMonitoring();
343 // Handle Socket incoming messages
344 this._wsConnection
.on('message', this.onMessage
.bind(this));
345 // Handle Socket error
346 this._wsConnection
.on('error', this.onError
.bind(this));
347 // Handle Socket close
348 this._wsConnection
.on('close', this.onClose
.bind(this));
349 // Handle Socket opening connection
350 this._wsConnection
.on('open', this.onOpen
.bind(this));
351 // Handle Socket ping
352 this._wsConnection
.on('ping', this.onPing
.bind(this));
355 async
stop(reason
= '') {
357 await
this._stopHeartbeat();
359 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
360 this._automaticTransactionGeneration
&&
361 !this._automaticTransactionGeneration
.timeToStop
) {
362 await
this._automaticTransactionGeneration
.stop(reason
);
364 for (const connector
in this._connectors
) {
365 if (this.getConnector(connector
).transactionStarted
) {
366 await
this.sendStopTransaction(this.getConnector(connector
).transactionId
, reason
);
370 // eslint-disable-next-line guard-for-in
371 for (const connector
in this._connectors
) {
372 await
this.sendStatusNotification(connector
, 'Unavailable');
374 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
375 await
this._wsConnection
.close();
380 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
381 // Stop the ATG if needed
382 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
383 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
384 this._automaticTransactionGeneration
&&
385 !this._automaticTransactionGeneration
.timeToStop
) {
386 this._automaticTransactionGeneration
.stop();
389 this._stopHeartbeat();
390 if (this._autoReconnectTimeout
!== 0 &&
391 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
392 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
393 this._autoReconnectRetryCount
++;
395 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
397 }, this._autoReconnectTimeout
);
398 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
399 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
404 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
405 if (!this._isSocketRestart
) {
406 // Send BootNotification
407 this.sendBootNotification();
409 if (this._isSocketRestart
) {
410 this._basicStartMessageSequence();
411 if (!Utils
.isEmptyArray(this._messageQueue
)) {
412 this._messageQueue
.forEach((message
) => {
413 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
414 this._wsConnection
.send(message
);
419 this._autoReconnectRetryCount
= 0;
420 this._isSocketRestart
= false;
426 this._isSocketRestart
= true;
427 this._reconnect(error
);
430 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
437 case 1000: // Normal close
439 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
440 this._autoReconnectRetryCount
= 0;
442 default: // Abnormal close
443 this._isSocketRestart
= true;
444 this._reconnect(error
);
450 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
453 async
onMessage(message
) {
454 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
457 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
459 // Check the Type of message
460 switch (messageType
) {
462 case Constants
.OCPP_JSON_CALL_MESSAGE
:
464 await
this.handleRequest(messageId
, commandName
, commandPayload
);
467 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
469 // eslint-disable-next-line no-case-declarations
470 let responseCallback
; let requestPayload
;
471 if (Utils
.isIterable(this._requests
[messageId
])) {
472 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
474 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
476 if (!responseCallback
) {
478 throw new Error(`Response for unknown message id ${messageId}`);
480 delete this._requests
[messageId
];
481 responseCallback(commandName
, requestPayload
);
484 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
485 if (!this._requests
[messageId
]) {
487 throw new Error(`Error for unknown message id ${messageId}`);
489 // eslint-disable-next-line no-case-declarations
491 if (Utils
.isIterable(this._requests
[messageId
])) {
492 [, rejectCallback
] = this._requests
[messageId
];
494 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
496 delete this._requests
[messageId
];
497 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
501 throw new Error(`Wrong message type ${messageType}`);
505 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
507 // await this.sendError(messageId, error);
514 currentTime
: new Date().toISOString(),
516 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
518 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
523 sendBootNotification() {
525 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
527 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
532 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
539 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
541 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
546 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
547 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
550 async
sendStartTransaction(connectorId
, idTag
) {
556 timestamp
: new Date().toISOString(),
558 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
560 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
565 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
566 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
569 async
sendStopTransaction(transactionId
, reason
= '') {
576 timestamp
: new Date().toISOString(),
583 timestamp
: new Date().toISOString(),
586 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
588 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
593 // eslint-disable-next-line class-methods-use-this
594 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
596 const sampledValueLcl
= {
597 timestamp
: new Date().toISOString(),
599 const meterValuesClone
= Utils
.cloneJSonDocument(self
.getConnector(connectorId
).MeterValues
);
600 if (!Utils
.isEmptyArray(meterValuesClone
)) {
601 sampledValueLcl
.sampledValue
= meterValuesClone
;
603 sampledValueLcl
.sampledValue
= [meterValuesClone
];
605 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
606 const connector
= self
.getConnector(connectorId
);
608 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
609 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
610 sampledValueLcl
.sampledValue
[index
].value
:
611 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
612 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
613 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}`);
616 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
617 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
618 // Energy.Active.Import.Register measurand (default)
619 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
620 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
621 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
622 logger
.error(errMsg
);
624 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
625 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}`;
626 logger
.error(errMsg
);
629 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
630 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
631 // Persist previous value in connector
632 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
633 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
635 connector
.lastEnergyActiveImportRegisterValue
= 0;
637 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
639 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}`);
640 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
641 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
642 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}`);
644 // Unsupported measurand
646 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
652 transactionId
: self
.getConnector(connectorId
).transactionId
,
653 meterValue
: [sampledValueLcl
],
655 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
657 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
662 sendError(messageId
, err
) {
663 // Check exception: only OCPP error are accepted
664 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
666 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
669 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
670 // Send a message through wsConnection
673 return new Promise((resolve
, reject
) => {
676 switch (messageType
) {
678 case Constants
.OCPP_JSON_CALL_MESSAGE
:
679 if (this.getEnableStatistics()) {
680 this._statistics
.addMessage(commandName
);
683 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
684 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
687 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
688 if (this.getEnableStatistics()) {
689 this._statistics
.addMessage(commandName
);
692 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
695 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
696 if (this.getEnableStatistics()) {
697 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
700 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
703 // Check if wsConnection is ready
704 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
706 this._wsConnection
.send(messageToSend
);
708 // Buffer message until connection is back
709 this._messageQueue
.push(messageToSend
);
712 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
715 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
716 // Send timeout in case connection is open otherwise wait for ever
717 // FIXME: Handle message on timeout
718 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
721 // Function that will receive the request's response
722 function responseCallback(payload
, requestPayload
) {
723 if (self
.getEnableStatistics()) {
724 self
._statistics
.addMessage(commandName
, true);
726 const responseCallbackFn
= 'handleResponse' + commandName
;
727 if (typeof self
[responseCallbackFn
] === 'function') {
728 self
[responseCallbackFn
](payload
, requestPayload
, self
);
730 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
736 // Function that will receive the request's rejection
737 function rejectCallback(reason
) {
738 if (self
.getEnableStatistics()) {
739 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
742 // eslint-disable-next-line no-empty-function
743 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
744 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
751 handleResponseBootNotification(payload
) {
752 if (payload
.status
=== 'Accepted') {
753 this._heartbeatInterval
= payload
.interval
* 1000;
754 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
755 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
756 this._basicStartMessageSequence();
757 } else if (payload
.status
=== 'Pending') {
758 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
760 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
764 _initTransactionOnConnector(connectorId
) {
765 this.getConnector(connectorId
).transactionStarted
= false;
766 this.getConnector(connectorId
).transactionId
= null;
767 this.getConnector(connectorId
).idTag
= null;
768 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
771 _resetTransactionOnConnector(connectorId
) {
772 this._initTransactionOnConnector(connectorId
);
773 if (this.getConnector(connectorId
).transactionSetInterval
) {
774 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
778 handleResponseStartTransaction(payload
, requestPayload
) {
779 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
780 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
784 let transactionConnectorId
;
785 for (const connector
in this._connectors
) {
786 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
787 transactionConnectorId
= connector
;
791 if (!transactionConnectorId
) {
792 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
795 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
796 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
797 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
798 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
799 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
800 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
801 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
802 if (this._stationInfo
.powerSharedByConnectors
) {
803 this._stationInfo
.powerDivider
++;
805 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
806 this._startMeterValues(requestPayload
.connectorId
,
807 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
809 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
810 this._resetTransactionOnConnector(requestPayload
.connectorId
);
811 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
815 handleResponseStopTransaction(payload
, requestPayload
) {
816 let transactionConnectorId
;
817 for (const connector
in this._connectors
) {
818 if (this.getConnector(connector
).transactionId
=== requestPayload
.transactionId
) {
819 transactionConnectorId
= connector
;
823 if (!transactionConnectorId
) {
824 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
827 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
828 this.sendStatusNotification(transactionConnectorId
, 'Available');
829 if (this._stationInfo
.powerSharedByConnectors
) {
830 this._stationInfo
.powerDivider
--;
832 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
833 this._resetTransactionOnConnector(transactionConnectorId
);
835 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
839 handleResponseStatusNotification(payload
, requestPayload
) {
840 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
843 handleResponseMeterValues(payload
, requestPayload
) {
844 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
847 handleResponseHeartbeat(payload
, requestPayload
) {
848 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
851 async
handleRequest(messageId
, commandName
, commandPayload
) {
852 if (this.getEnableStatistics()) {
853 this._statistics
.addMessage(commandName
, true);
857 if (typeof this['handle' + commandName
] === 'function') {
860 result
= await
this['handle' + commandName
](commandPayload
);
863 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
864 // Send back response to inform backend
865 await
this.sendError(messageId
, error
);
869 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
870 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
873 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
876 async
handleReset(commandPayload
) {
877 // Simulate charging station restart
878 setImmediate(async () => {
879 await
this.stop(commandPayload
.type
+ 'Reset');
880 await Utils
.sleep(this._stationInfo
.resetTime
);
883 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
884 return Constants
.OCPP_RESPONSE_ACCEPTED
;
887 _getConfigurationKey(key
) {
888 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
891 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
892 const keyFound
= this._getConfigurationKey(key
);
894 this._configuration
.configurationKey
.push({
904 _setConfigurationKeyValue(key
, value
) {
905 const keyFound
= this._getConfigurationKey(key
);
907 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
908 this._configuration
.configurationKey
[keyIndex
].value
= value
;
912 async
handleGetConfiguration(commandPayload
) {
913 const configurationKey
= [];
914 const unknownKey
= [];
915 if (Utils
.isEmptyArray(commandPayload
.key
)) {
916 for (const configuration
of this._configuration
.configurationKey
) {
917 if (Utils
.isUndefined(configuration
.visible
)) {
918 configuration
.visible
= true;
920 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
922 if (!configuration
.visible
) {
925 configurationKey
.push({
926 key
: configuration
.key
,
927 readonly
: configuration
.readonly
,
928 value
: configuration
.value
,
932 for (const configurationKey
of commandPayload
.key
) {
933 const keyFound
= this._getConfigurationKey(configurationKey
);
935 if (Utils
.isUndefined(keyFound
.visible
)) {
936 keyFound
.visible
= true;
938 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
940 if (!keyFound
.visible
) {
943 configurationKey
.push({
945 readonly
: keyFound
.readonly
,
946 value
: keyFound
.value
,
949 unknownKey
.push(configurationKey
);
959 async
handleChangeConfiguration(commandPayload
) {
960 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
962 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
963 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
964 return Constants
.OCPP_RESPONSE_REJECTED
;
965 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
966 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
967 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
968 let triggerHeartbeatRestart
= false;
969 if (keyToChange
.key
=== 'HeartBeatInterval') {
970 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
971 triggerHeartbeatRestart
= true;
973 if (keyToChange
.key
=== 'HeartbeatInterval') {
974 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
975 triggerHeartbeatRestart
= true;
977 if (triggerHeartbeatRestart
) {
978 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
980 this._stopHeartbeat();
982 this._startHeartbeat(this);
984 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
985 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
987 return Constants
.OCPP_RESPONSE_ACCEPTED
;
991 async
handleRemoteStartTransaction(commandPayload
) {
992 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
993 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
994 // Check if authorized
995 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
996 // Authorization successful 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
;
1001 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
1002 return Constants
.OCPP_RESPONSE_REJECTED
;
1004 // No local authorization check required => start transaction
1005 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
1006 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1007 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1010 async
handleRemoteStopTransaction(commandPayload
) {
1011 for (const connector
in this._connectors
) {
1012 if (this.getConnector(connector
).transactionId
=== commandPayload
.transactionId
) {
1013 this.sendStopTransaction(commandPayload
.transactionId
);
1014 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1017 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1018 return Constants
.OCPP_RESPONSE_REJECTED
;
1022 module
.exports
= ChargingStation
;