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(this._logPrefix() + ' Template file loading error: ' + error
);
45 const stationTemplate
= stationTemplateFromFile
|| {};
46 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
47 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
49 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
51 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
52 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
53 return stationTemplate
;
57 this._stationInfo
= this._buildStationInfo();
58 this._bootNotificationMessage
= {
59 chargePointModel
: this._stationInfo
.chargePointModel
,
60 chargePointVendor
: this._stationInfo
.chargePointVendor
,
61 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
62 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
64 this._configuration
= this._getConfiguration();
65 this._supervisionUrl
= this._getSupervisionURL();
66 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
67 // Build connectors if needed
68 const maxConnectors
= this._getMaxNumberOfConnectors();
69 if (maxConnectors
<= 0) {
70 const errMsg
= `${this._logPrefix()} Charging station template with no connectors`;
74 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
75 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(connectorsConfig
) + 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 connectorsConfig
) {
83 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
84 connectorsConfig
[lastConnector
]) {
85 this._connectors
[lastConnector
] = connectorsConfig
[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
] = connectorsConfig
[randConnectorID
];
98 // Initialize transaction attributes on connectors
99 for (const connector
in this._connectors
) {
100 if (!this._connectors
[connector
].transactionStarted
) {
101 this._initTransactionOnConnector(connector
);
104 this._stationInfo
.powerDivider
= this._getPowerDivider();
105 // FIXME: Conditionally initialize or use singleton design pattern per charging station
106 this._statistics
= new Statistics(this._stationInfo
.name
);
107 this._performanceObserver
= new PerformanceObserver((list
) => {
108 const entry
= list
.getEntries()[0];
109 this._statistics
.logPerformance(entry
, 'ChargingStation');
110 this._performanceObserver
.disconnect();
115 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
118 _getConfiguration() {
119 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
122 _getAuthorizationFile() {
123 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
126 _loadAndGetAuthorizedTags() {
127 let authorizedTags
= [];
128 const authorizationFile
= this._getAuthorizationFile();
129 if (authorizationFile
) {
131 // Load authorization file
132 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
133 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
134 fs
.closeSync(fileDescriptor
);
136 logger
.error(this._logPrefix() + ' Authorization file loading error: ' + error
);
139 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
141 return authorizedTags
;
145 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
146 return this._authorizedTags
[index
];
149 hasAuthorizedTags() {
150 return !Utils
.isEmptyArray(this._authorizedTags
);
153 _getNumberOfRunningTransactions() {
155 for (const connector
in this._connectors
) {
156 if (this._getConnector(connector
).transactionStarted
) {
164 let powerDivider
= this._getNumberOfConnectors();
165 if (this._stationInfo
.powerSharedByConnectors
) {
166 powerDivider
= this._getNumberOfRunningTransactions();
171 _getConnectorFromTemplate(number
) {
172 return this._stationInfo
.Connectors
[number
];
175 _getConnector(number
) {
176 return this._connectors
[number
];
179 _getMaxNumberOfConnectors() {
180 let maxConnectors
= 0;
181 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
182 // Distribute evenly the number of connectors
183 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
185 maxConnectors
= this._stationInfo
.numberOfConnectors
;
187 return maxConnectors
;
190 _getNumberOfConnectors() {
191 return Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) ? Object
.keys(this._connectors
).length
- 1 : Object
.keys(this._connectors
).length
;
194 _getSupervisionURL() {
195 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
197 if (!Utils
.isEmptyArray(supervisionUrls
)) {
198 if (Configuration
.getDistributeStationToTenantEqually()) {
199 indexUrl
= this._index
% supervisionUrls
.length
;
202 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
204 return supervisionUrls
[indexUrl
];
206 return supervisionUrls
;
209 _getAuthorizeRemoteTxRequests() {
210 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
211 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
214 _getLocalAuthListEnabled() {
215 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
216 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
219 async
_basicStartMessageSequence() {
221 this._startHeartbeat(this);
222 // Initialize connectors status
223 for (const connector
in this._connectors
) {
224 if (!this._connectors
[connector
].transactionStarted
) {
225 if (this._connectors
[connector
].bootStatus
) {
226 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
228 this.sendStatusNotificationWithTimeout(connector
, 'Available');
231 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
235 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
236 if (!this._automaticTransactionGeneration
) {
237 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
239 if (this._automaticTransactionGeneration
.timeToStop
) {
240 this._automaticTransactionGeneration
.start();
243 this._statistics
.start();
246 // eslint-disable-next-line class-methods-use-this
247 async
_startHeartbeat(self
) {
248 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
249 self
._heartbeatSetInterval
= setInterval(() => {
250 this.sendHeartbeat();
251 }, self
._heartbeatInterval
);
252 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
254 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
258 async
_stopHeartbeat() {
259 if (this._heartbeatSetInterval
) {
260 clearInterval(this._heartbeatSetInterval
);
261 this._heartbeatSetInterval
= null;
265 _startAuthorizationFileMonitoring() {
266 // eslint-disable-next-line no-unused-vars
267 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
269 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
270 // Initialize _authorizedTags
271 this._authorizedTags
= this._loadAndGetAuthorizedTags();
273 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
278 _startStationTemplateFileMonitoring() {
279 // eslint-disable-next-line no-unused-vars
280 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
282 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
285 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
286 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
288 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
293 async
_startMeterValues(connectorId
, interval
) {
294 if (!this._connectors
[connectorId
].transactionStarted
) {
295 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
297 } else if (this._connectors
[connectorId
].transactionStarted
&& !this._connectors
[connectorId
].transactionId
) {
298 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
302 this._connectors
[connectorId
].transactionSetInterval
= setInterval(async () => {
303 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
304 this._performanceObserver
.observe({
305 entryTypes
: ['function'],
307 await
sendMeterValues(connectorId
, interval
, this);
310 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
315 if (!this._wsConnectionUrl
) {
316 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
318 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
319 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
320 // Monitor authorization file
321 this._startAuthorizationFileMonitoring();
322 // Monitor station template file
323 this._startStationTemplateFileMonitoring();
324 // Handle Socket incoming messages
325 this._wsConnection
.on('message', this.onMessage
.bind(this));
326 // Handle Socket error
327 this._wsConnection
.on('error', this.onError
.bind(this));
328 // Handle Socket close
329 this._wsConnection
.on('close', this.onClose
.bind(this));
330 // Handle Socket opening connection
331 this._wsConnection
.on('open', this.onOpen
.bind(this));
332 // Handle Socket ping
333 this._wsConnection
.on('ping', this.onPing
.bind(this));
336 async
stop(reason
= '') {
338 await
this._stopHeartbeat();
340 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
341 this._automaticTransactionGeneration
&&
342 !this._automaticTransactionGeneration
.timeToStop
) {
343 await
this._automaticTransactionGeneration
.stop(reason
);
345 for (const connector
in this._connectors
) {
346 if (this._connectors
[connector
].transactionStarted
) {
347 await
this.sendStopTransaction(this._connectors
[connector
].transactionId
, reason
);
351 // eslint-disable-next-line guard-for-in
352 for (const connector
in this._connectors
) {
353 await
this.sendStatusNotification(connector
, 'Unavailable');
355 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
356 await
this._wsConnection
.close();
361 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
362 // Stop the ATG if needed
363 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
364 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
365 this._automaticTransactionGeneration
&&
366 !this._automaticTransactionGeneration
.timeToStop
) {
367 this._automaticTransactionGeneration
.stop();
370 this._stopHeartbeat();
371 if (this._autoReconnectTimeout
!== 0 &&
372 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
373 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
374 this._autoReconnectRetryCount
++;
376 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
378 }, this._autoReconnectTimeout
);
379 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
380 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
385 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
386 if (!this._isSocketRestart
) {
387 // Send BootNotification
388 this.sendBootNotification();
390 if (this._isSocketRestart
) {
391 this._basicStartMessageSequence();
392 if (!Utils
.isEmptyArray(this._messageQueue
)) {
393 this._messageQueue
.forEach((message
) => {
394 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
395 this._wsConnection
.send(message
);
400 this._autoReconnectRetryCount
= 0;
401 this._isSocketRestart
= false;
407 this._isSocketRestart
= true;
408 this._reconnect(error
);
411 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
418 case 1000: // Normal close
420 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
421 this._autoReconnectRetryCount
= 0;
423 default: // Abnormal close
424 this._isSocketRestart
= true;
425 this._reconnect(error
);
431 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
434 async
onMessage(message
) {
435 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
438 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
440 // Check the Type of message
441 switch (messageType
) {
443 case Constants
.OCPP_JSON_CALL_MESSAGE
:
445 await
this.handleRequest(messageId
, commandName
, commandPayload
);
448 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
450 // eslint-disable-next-line no-case-declarations
451 let responseCallback
; let requestPayload
;
452 if (Utils
.isIterable(this._requests
[messageId
])) {
453 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
455 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
457 if (!responseCallback
) {
459 throw new Error(`Response for unknown message id ${messageId}`);
461 delete this._requests
[messageId
];
462 responseCallback(commandName
, requestPayload
);
465 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
466 if (!this._requests
[messageId
]) {
468 throw new Error(`Error for unknown message id ${messageId}`);
470 // eslint-disable-next-line no-case-declarations
472 if (Utils
.isIterable(this._requests
[messageId
])) {
473 [, rejectCallback
] = this._requests
[messageId
];
475 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
477 delete this._requests
[messageId
];
478 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
482 throw new Error(`Wrong message type ${messageType}`);
486 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
488 // await this.sendError(messageId, error);
495 currentTime
: new Date().toISOString(),
497 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
499 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
504 sendBootNotification() {
506 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
508 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
513 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
520 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
522 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
527 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
528 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
531 async
sendStartTransaction(connectorId
, idTag
) {
537 timestamp
: new Date().toISOString(),
539 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
541 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
546 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
547 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
550 async
sendStopTransaction(transactionId
, reason
= '') {
557 timestamp
: new Date().toISOString(),
564 timestamp
: new Date().toISOString(),
567 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
569 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
574 // eslint-disable-next-line class-methods-use-this
575 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
577 const sampledValueLcl
= {
578 timestamp
: new Date().toISOString(),
580 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorId
).MeterValues
);
581 if (!Utils
.isEmptyArray(meterValuesClone
)) {
582 sampledValueLcl
.sampledValue
= meterValuesClone
;
584 sampledValueLcl
.sampledValue
= [meterValuesClone
];
586 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
587 const connector
= self
._connectors
[connectorId
];
589 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
590 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
591 sampledValueLcl
.sampledValue
[index
].value
:
592 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
593 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
594 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}`);
597 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
598 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
599 // Energy.Active.Import.Register measurand (default)
600 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
601 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
602 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
603 logger
.error(errMsg
);
605 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
606 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}`;
607 logger
.error(errMsg
);
610 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
611 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
612 // Persist previous value in connector
613 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
614 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
616 connector
.lastEnergyActiveImportRegisterValue
= 0;
618 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
620 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}`);
621 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
622 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
623 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}`);
625 // Unsupported measurand
627 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
633 transactionId
: self
._connectors
[connectorId
].transactionId
,
634 meterValue
: [sampledValueLcl
],
636 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
638 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
643 sendError(messageId
, err
) {
644 // Check exception: only OCPP error are accepted
645 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
647 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
650 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
651 // Send a message through wsConnection
654 return new Promise((resolve
, reject
) => {
657 switch (messageType
) {
659 case Constants
.OCPP_JSON_CALL_MESSAGE
:
660 this._statistics
.addMessage(commandName
);
662 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
663 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
666 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
667 this._statistics
.addMessage(commandName
);
669 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
672 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
674 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
675 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
678 // Check if wsConnection is ready
679 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
681 this._wsConnection
.send(messageToSend
);
683 // Buffer message until connection is back
684 this._messageQueue
.push(messageToSend
);
687 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
690 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
691 // Send timeout in case connection is open otherwise wait for ever
692 // FIXME: Handle message on timeout
693 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
696 // Function that will receive the request's response
697 function responseCallback(payload
, requestPayload
) {
698 self
._statistics
.addMessage(commandName
, true);
699 const responseCallbackFn
= 'handleResponse' + commandName
;
700 if (typeof self
[responseCallbackFn
] === 'function') {
701 self
[responseCallbackFn
](payload
, requestPayload
, self
);
703 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
709 // Function that will receive the request's rejection
710 function rejectCallback(reason
) {
711 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
713 // eslint-disable-next-line no-empty-function
714 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
715 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
722 handleResponseBootNotification(payload
) {
723 if (payload
.status
=== 'Accepted') {
724 this._heartbeatInterval
= payload
.interval
* 1000;
725 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
726 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
727 this._basicStartMessageSequence();
728 } else if (payload
.status
=== 'Pending') {
729 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
731 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
735 _initTransactionOnConnector(connectorId
) {
736 this._connectors
[connectorId
].transactionStarted
= false;
737 this._connectors
[connectorId
].transactionId
= null;
738 this._connectors
[connectorId
].idTag
= null;
739 this._connectors
[connectorId
].lastEnergyActiveImportRegisterValue
= -1;
742 _resetTransactionOnConnector(connectorId
) {
743 this._initTransactionOnConnector(connectorId
);
744 if (this._connectors
[connectorId
].transactionSetInterval
) {
745 clearInterval(this._connectors
[connectorId
].transactionSetInterval
);
749 handleResponseStartTransaction(payload
, requestPayload
) {
750 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
751 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this._connectors
[requestPayload
.connectorId
]);
755 let transactionConnectorId
;
756 for (const connector
in this._connectors
) {
757 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
758 transactionConnectorId
= connector
;
762 if (!transactionConnectorId
) {
763 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
766 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
767 this._connectors
[transactionConnectorId
].transactionStarted
= true;
768 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
769 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
770 this._connectors
[transactionConnectorId
].lastEnergyActiveImportRegisterValue
= 0;
771 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
772 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
773 if (this._stationInfo
.powerSharedByConnectors
) {
774 this._stationInfo
.powerDivider
++;
776 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
777 this._startMeterValues(requestPayload
.connectorId
,
778 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
780 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
781 this._resetTransactionOnConnector(transactionConnectorId
);
782 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
786 handleResponseStopTransaction(payload
, requestPayload
) {
787 let transactionConnectorId
;
788 for (const connector
in this._connectors
) {
789 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
790 transactionConnectorId
= connector
;
794 if (!transactionConnectorId
) {
795 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
798 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
799 this.sendStatusNotification(transactionConnectorId
, 'Available');
800 if (this._stationInfo
.powerSharedByConnectors
) {
801 this._stationInfo
.powerDivider
--;
803 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
804 this._resetTransactionOnConnector(transactionConnectorId
);
806 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
810 handleResponseStatusNotification(payload
, requestPayload
) {
811 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
814 handleResponseMeterValues(payload
, requestPayload
) {
815 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
818 handleResponseHeartbeat(payload
, requestPayload
) {
819 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
822 async
handleRequest(messageId
, commandName
, commandPayload
) {
824 this._statistics
.addMessage(commandName
, true);
826 if (typeof this['handle' + commandName
] === 'function') {
829 result
= await
this['handle' + commandName
](commandPayload
);
832 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
833 // Send back response to inform backend
834 await
this.sendError(messageId
, error
);
838 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
839 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
842 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
845 async
handleReset(commandPayload
) {
846 // Simulate charging station restart
847 setImmediate(async () => {
848 await
this.stop(commandPayload
.type
+ 'Reset');
849 await Utils
.sleep(this._stationInfo
.resetTime
);
852 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
853 return Constants
.OCPP_RESPONSE_ACCEPTED
;
856 _getConfigurationKey(key
) {
857 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
860 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
861 const keyFound
= this._getConfigurationKey(key
);
863 this._configuration
.configurationKey
.push({
873 _setConfigurationKeyValue(key
, value
) {
874 const keyFound
= this._getConfigurationKey(key
);
876 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
877 this._configuration
.configurationKey
[keyIndex
].value
= value
;
881 async
handleGetConfiguration(commandPayload
) {
882 const configurationKey
= [];
883 const unknownKey
= [];
884 if (Utils
.isEmptyArray(commandPayload
.key
)) {
885 for (const configuration
of this._configuration
.configurationKey
) {
886 if (Utils
.isUndefined(configuration
.visible
)) {
887 configuration
.visible
= true;
889 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
891 if (!configuration
.visible
) {
894 configurationKey
.push({
895 key
: configuration
.key
,
896 readonly
: configuration
.readonly
,
897 value
: configuration
.value
,
901 for (const configurationKey
of commandPayload
.key
) {
902 const keyFound
= this._getConfigurationKey(configurationKey
);
904 if (Utils
.isUndefined(keyFound
.visible
)) {
905 keyFound
.visible
= true;
907 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
909 if (!keyFound
.visible
) {
912 configurationKey
.push({
914 readonly
: keyFound
.readonly
,
915 value
: keyFound
.value
,
918 unknownKey
.push(configurationKey
);
928 async
handleChangeConfiguration(commandPayload
) {
929 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
931 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
932 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
933 return Constants
.OCPP_RESPONSE_REJECTED
;
934 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
935 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
936 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
937 let triggerHeartbeatRestart
= false;
938 if (keyToChange
.key
=== 'HeartBeatInterval') {
939 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
940 triggerHeartbeatRestart
= true;
942 if (keyToChange
.key
=== 'HeartbeatInterval') {
943 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
944 triggerHeartbeatRestart
= true;
946 if (triggerHeartbeatRestart
) {
947 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
949 this._stopHeartbeat();
951 this._startHeartbeat(this);
953 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
954 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
956 return Constants
.OCPP_RESPONSE_ACCEPTED
;
960 async
handleRemoteStartTransaction(commandPayload
) {
961 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
962 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
963 // Check if authorized
964 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
965 // Authorization successful start transaction
966 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
967 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
968 return Constants
.OCPP_RESPONSE_ACCEPTED
;
970 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
971 return Constants
.OCPP_RESPONSE_REJECTED
;
973 // No local authorization check required => start transaction
974 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
975 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
976 return Constants
.OCPP_RESPONSE_ACCEPTED
;
979 async
handleRemoteStopTransaction(commandPayload
) {
980 for (const connector
in this._connectors
) {
981 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
982 this.sendStopTransaction(commandPayload
.transactionId
);
983 return Constants
.OCPP_RESPONSE_ACCEPTED
;
986 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
987 return Constants
.OCPP_RESPONSE_REJECTED
;
991 module
.exports
= ChargingStation
;