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
] && Utils
.convertToInt(lastConnector
) === 0) {
84 this._connectors
[lastConnector
] = Utils
.cloneObject(this._stationInfo
.Connectors
[lastConnector
]);
87 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
88 if (!this._getConfigurationKey('MeterValuesSampledData')) {
89 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
92 if (maxConnectors
> lastConnector
&& !Utils
.convertToBoolean(this._stationInfo
.randomConnectors
)) {
93 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
94 this._stationInfo
.randomConnectors
= true;
96 // Generate all connectors
97 for (let index
= 1; index
<= maxConnectors
; index
++) {
98 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
99 this._connectors
[index
] = Utils
.cloneObject(this._stationInfo
.Connectors
[randConnectorID
]);
102 // Avoid duplication of connectors related information
103 delete this._stationInfo
.Connectors
;
104 // Initialize transaction attributes on connectors
105 for (const connector
in this._connectors
) {
106 if (!this.getConnector(connector
).transactionStarted
) {
107 this._initTransactionOnConnector(connector
);
110 this._stationInfo
.powerDivider
= this._getPowerDivider();
111 if (this.getEnableStatistics()) {
112 this._statistics
= Statistics
.getInstance();
113 this._statistics
.objName
= this._stationInfo
.name
;
114 this._performanceObserver
= new PerformanceObserver((list
) => {
115 const entry
= list
.getEntries()[0];
116 this._statistics
.logPerformance(entry
, 'ChargingStation');
117 this._performanceObserver
.disconnect();
123 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
126 _getConfiguration() {
127 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
130 _getAuthorizationFile() {
131 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
134 _loadAndGetAuthorizedTags() {
135 let authorizedTags
= [];
136 const authorizationFile
= this._getAuthorizationFile();
137 if (authorizationFile
) {
139 // Load authorization file
140 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
141 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
142 fs
.closeSync(fileDescriptor
);
144 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: ' + error
);
148 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
150 return authorizedTags
;
154 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
155 return this._authorizedTags
[index
];
158 hasAuthorizedTags() {
159 return !Utils
.isEmptyArray(this._authorizedTags
);
162 getEnableStatistics() {
163 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? Utils
.convertToBoolean(this._stationInfo
.enableStatistics
) : true;
166 _getNumberOfPhases() {
167 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? Utils
.convertToInt(this._stationInfo
.numberOfPhases
) : 3;
170 _getNumberOfRunningTransactions() {
172 for (const connector
in this._connectors
) {
173 if (this.getConnector(connector
).transactionStarted
) {
181 let powerDivider
= Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) && this._connectors
[0] ? this._getNumberOfConnectors() - 1 : this._getNumberOfConnectors();
182 if (this._stationInfo
.powerSharedByConnectors
) {
183 powerDivider
= this._getNumberOfRunningTransactions();
189 return this._connectors
[Utils
.convertToInt(id
)];
192 _getMaxNumberOfConnectors() {
193 let maxConnectors
= 0;
194 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
195 // Distribute evenly the number of connectors
196 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
197 } else if (this._stationInfo
.numberOfConnectors
) {
198 maxConnectors
= this._stationInfo
.numberOfConnectors
;
200 maxConnectors
= Object
.keys(this._stationInfo
.Connectors
).length
;
202 return maxConnectors
;
205 _getNumberOfConnectors() {
206 return Object
.keys(this._connectors
).length
;
209 _getSupervisionURL() {
210 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
212 if (!Utils
.isEmptyArray(supervisionUrls
)) {
213 if (Configuration
.getDistributeStationToTenantEqually()) {
214 indexUrl
= this._index
% supervisionUrls
.length
;
217 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
219 return supervisionUrls
[indexUrl
];
221 return supervisionUrls
;
224 _getAuthorizeRemoteTxRequests() {
225 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
226 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
229 _getLocalAuthListEnabled() {
230 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
231 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
234 async
_basicStartMessageSequence() {
236 this._startHeartbeat(this);
237 // Initialize connectors status
238 for (const connector
in this._connectors
) {
239 if (!this.getConnector(connector
).transactionStarted
) {
240 if (this.getConnector(connector
).bootStatus
) {
241 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(connector
).bootStatus
);
243 this.sendStatusNotificationWithTimeout(connector
, 'Available');
246 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
250 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
251 if (!this._automaticTransactionGeneration
) {
252 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
254 if (this._automaticTransactionGeneration
.timeToStop
) {
255 this._automaticTransactionGeneration
.start();
258 if (this.getEnableStatistics()) {
259 this._statistics
.start();
263 // eslint-disable-next-line class-methods-use-this
264 async
_startHeartbeat(self
) {
265 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
266 self
._heartbeatSetInterval
= setInterval(() => {
267 this.sendHeartbeat();
268 }, self
._heartbeatInterval
);
269 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
271 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
275 async
_stopHeartbeat() {
276 if (this._heartbeatSetInterval
) {
277 clearInterval(this._heartbeatSetInterval
);
278 this._heartbeatSetInterval
= null;
282 _startAuthorizationFileMonitoring() {
283 // eslint-disable-next-line no-unused-vars
284 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
286 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
287 // Initialize _authorizedTags
288 this._authorizedTags
= this._loadAndGetAuthorizedTags();
290 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
295 _startStationTemplateFileMonitoring() {
296 // eslint-disable-next-line no-unused-vars
297 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
299 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
302 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
303 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
305 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
310 async
_startMeterValues(connectorId
, interval
) {
311 if (!this.getConnector(connectorId
).transactionStarted
) {
312 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
314 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
315 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
319 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
320 if (this.getEnableStatistics()) {
321 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
322 this._performanceObserver
.observe({
323 entryTypes
: ['function'],
325 await
sendMeterValues(connectorId
, interval
, this);
327 await
this.sendMeterValues(connectorId
, interval
, this);
331 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
336 if (!this._wsConnectionUrl
) {
337 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
339 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
340 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
341 // Monitor authorization file
342 this._startAuthorizationFileMonitoring();
343 // Monitor station template file
344 this._startStationTemplateFileMonitoring();
345 // Handle Socket incoming messages
346 this._wsConnection
.on('message', this.onMessage
.bind(this));
347 // Handle Socket error
348 this._wsConnection
.on('error', this.onError
.bind(this));
349 // Handle Socket close
350 this._wsConnection
.on('close', this.onClose
.bind(this));
351 // Handle Socket opening connection
352 this._wsConnection
.on('open', this.onOpen
.bind(this));
353 // Handle Socket ping
354 this._wsConnection
.on('ping', this.onPing
.bind(this));
357 async
stop(reason
= '') {
359 await
this._stopHeartbeat();
361 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
362 this._automaticTransactionGeneration
&&
363 !this._automaticTransactionGeneration
.timeToStop
) {
364 await
this._automaticTransactionGeneration
.stop(reason
);
366 for (const connector
in this._connectors
) {
367 if (this.getConnector(connector
).transactionStarted
) {
368 await
this.sendStopTransaction(this.getConnector(connector
).transactionId
, reason
);
372 // eslint-disable-next-line guard-for-in
373 for (const connector
in this._connectors
) {
374 await
this.sendStatusNotification(connector
, 'Unavailable');
376 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
377 await
this._wsConnection
.close();
382 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
383 // Stop the ATG if needed
384 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
385 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
386 this._automaticTransactionGeneration
&&
387 !this._automaticTransactionGeneration
.timeToStop
) {
388 this._automaticTransactionGeneration
.stop();
391 this._stopHeartbeat();
392 if (this._autoReconnectTimeout
!== 0 &&
393 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
394 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
395 this._autoReconnectRetryCount
++;
397 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
399 }, this._autoReconnectTimeout
);
400 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
401 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
406 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
407 if (!this._isSocketRestart
) {
408 // Send BootNotification
409 this.sendBootNotification();
411 if (this._isSocketRestart
) {
412 this._basicStartMessageSequence();
413 if (!Utils
.isEmptyArray(this._messageQueue
)) {
414 this._messageQueue
.forEach((message
) => {
415 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
416 this._wsConnection
.send(message
);
421 this._autoReconnectRetryCount
= 0;
422 this._isSocketRestart
= false;
428 this._isSocketRestart
= true;
429 this._reconnect(error
);
432 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
439 case 1000: // Normal close
441 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
442 this._autoReconnectRetryCount
= 0;
444 default: // Abnormal close
445 this._isSocketRestart
= true;
446 this._reconnect(error
);
452 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
455 async
onMessage(message
) {
456 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
459 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
461 // Check the Type of message
462 switch (messageType
) {
464 case Constants
.OCPP_JSON_CALL_MESSAGE
:
466 await
this.handleRequest(messageId
, commandName
, commandPayload
);
469 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
471 // eslint-disable-next-line no-case-declarations
472 let responseCallback
; let requestPayload
;
473 if (Utils
.isIterable(this._requests
[messageId
])) {
474 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
476 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
478 if (!responseCallback
) {
480 throw new Error(`Response for unknown message id ${messageId}`);
482 delete this._requests
[messageId
];
483 responseCallback(commandName
, requestPayload
);
486 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
487 if (!this._requests
[messageId
]) {
489 throw new Error(`Error for unknown message id ${messageId}`);
491 // eslint-disable-next-line no-case-declarations
493 if (Utils
.isIterable(this._requests
[messageId
])) {
494 [, rejectCallback
] = this._requests
[messageId
];
496 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
498 delete this._requests
[messageId
];
499 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
503 throw new Error(`Wrong message type ${messageType}`);
507 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
509 // await this.sendError(messageId, error);
516 currentTime
: new Date().toISOString(),
518 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
520 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
525 sendBootNotification() {
527 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
529 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
534 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
541 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
543 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
548 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
549 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
552 async
sendStartTransaction(connectorId
, idTag
) {
558 timestamp
: new Date().toISOString(),
560 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
562 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
567 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
568 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
571 async
sendStopTransaction(transactionId
, reason
= '') {
578 timestamp
: new Date().toISOString(),
585 timestamp
: new Date().toISOString(),
588 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
590 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
595 // eslint-disable-next-line class-methods-use-this
596 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
598 const sampledValueLcl
= {
599 timestamp
: new Date().toISOString(),
601 const meterValuesClone
= Utils
.cloneObject(self
.getConnector(connectorId
).MeterValues
);
602 if (!Utils
.isEmptyArray(meterValuesClone
)) {
603 sampledValueLcl
.sampledValue
= meterValuesClone
;
605 sampledValueLcl
.sampledValue
= [meterValuesClone
];
607 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
608 const connector
= self
.getConnector(connectorId
);
610 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
611 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
612 sampledValueLcl
.sampledValue
[index
].value
:
613 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
614 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
615 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}`);
618 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
619 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
620 // Energy.Active.Import.Register measurand (default)
621 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
622 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
623 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
624 logger
.error(errMsg
);
626 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
627 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}`;
628 logger
.error(errMsg
);
631 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
632 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
633 // Persist previous value in connector
634 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
635 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
637 connector
.lastEnergyActiveImportRegisterValue
= 0;
639 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
641 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}`);
642 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
643 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
644 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}`);
646 // Unsupported measurand
648 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
654 transactionId
: self
.getConnector(connectorId
).transactionId
,
655 meterValue
: [sampledValueLcl
],
657 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
659 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
664 sendError(messageId
, err
) {
665 // Check exception: only OCPP error are accepted
666 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
668 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
671 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
672 // Send a message through wsConnection
675 return new Promise((resolve
, reject
) => {
678 switch (messageType
) {
680 case Constants
.OCPP_JSON_CALL_MESSAGE
:
681 if (this.getEnableStatistics()) {
682 this._statistics
.addMessage(commandName
);
685 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
686 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
689 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
690 if (this.getEnableStatistics()) {
691 this._statistics
.addMessage(commandName
);
694 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
697 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
698 if (this.getEnableStatistics()) {
699 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
702 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
705 // Check if wsConnection is ready
706 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
708 this._wsConnection
.send(messageToSend
);
710 // Buffer message until connection is back
711 this._messageQueue
.push(messageToSend
);
714 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
717 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
718 // Send timeout in case connection is open otherwise wait for ever
719 // FIXME: Handle message on timeout
720 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
723 // Function that will receive the request's response
724 function responseCallback(payload
, requestPayload
) {
725 if (self
.getEnableStatistics()) {
726 self
._statistics
.addMessage(commandName
, true);
728 const responseCallbackFn
= 'handleResponse' + commandName
;
729 if (typeof self
[responseCallbackFn
] === 'function') {
730 self
[responseCallbackFn
](payload
, requestPayload
, self
);
732 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
738 // Function that will receive the request's rejection
739 function rejectCallback(reason
) {
740 if (self
.getEnableStatistics()) {
741 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
744 // eslint-disable-next-line no-empty-function
745 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
746 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
753 handleResponseBootNotification(payload
) {
754 if (payload
.status
=== 'Accepted') {
755 this._heartbeatInterval
= payload
.interval
* 1000;
756 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
757 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
758 this._basicStartMessageSequence();
759 } else if (payload
.status
=== 'Pending') {
760 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
762 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
766 _initTransactionOnConnector(connectorId
) {
767 this.getConnector(connectorId
).transactionStarted
= false;
768 this.getConnector(connectorId
).transactionId
= null;
769 this.getConnector(connectorId
).idTag
= null;
770 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
773 _resetTransactionOnConnector(connectorId
) {
774 this._initTransactionOnConnector(connectorId
);
775 if (this.getConnector(connectorId
).transactionSetInterval
) {
776 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
780 handleResponseStartTransaction(payload
, requestPayload
) {
781 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
782 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
786 let transactionConnectorId
;
787 for (const connector
in this._connectors
) {
788 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
789 transactionConnectorId
= connector
;
793 if (!transactionConnectorId
) {
794 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
797 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
798 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
799 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
800 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
801 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
802 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
803 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
804 if (this._stationInfo
.powerSharedByConnectors
) {
805 this._stationInfo
.powerDivider
++;
807 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
808 this._startMeterValues(requestPayload
.connectorId
,
809 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
811 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
812 this._resetTransactionOnConnector(requestPayload
.connectorId
);
813 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
817 handleResponseStopTransaction(payload
, requestPayload
) {
818 let transactionConnectorId
;
819 for (const connector
in this._connectors
) {
820 if (this.getConnector(connector
).transactionId
=== requestPayload
.transactionId
) {
821 transactionConnectorId
= connector
;
825 if (!transactionConnectorId
) {
826 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
829 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
830 this.sendStatusNotification(transactionConnectorId
, 'Available');
831 if (this._stationInfo
.powerSharedByConnectors
) {
832 this._stationInfo
.powerDivider
--;
834 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
835 this._resetTransactionOnConnector(transactionConnectorId
);
837 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
841 handleResponseStatusNotification(payload
, requestPayload
) {
842 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
845 handleResponseMeterValues(payload
, requestPayload
) {
846 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
849 handleResponseHeartbeat(payload
, requestPayload
) {
850 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
853 async
handleRequest(messageId
, commandName
, commandPayload
) {
854 if (this.getEnableStatistics()) {
855 this._statistics
.addMessage(commandName
, true);
859 if (typeof this['handle' + commandName
] === 'function') {
862 result
= await
this['handle' + commandName
](commandPayload
);
865 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
866 // Send back response to inform backend
867 await
this.sendError(messageId
, error
);
871 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
872 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
875 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
878 async
handleReset(commandPayload
) {
879 // Simulate charging station restart
880 setImmediate(async () => {
881 await
this.stop(commandPayload
.type
+ 'Reset');
882 await Utils
.sleep(this._stationInfo
.resetTime
);
885 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
886 return Constants
.OCPP_RESPONSE_ACCEPTED
;
889 _getConfigurationKey(key
) {
890 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
893 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
894 const keyFound
= this._getConfigurationKey(key
);
896 this._configuration
.configurationKey
.push({
906 _setConfigurationKeyValue(key
, value
) {
907 const keyFound
= this._getConfigurationKey(key
);
909 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
910 this._configuration
.configurationKey
[keyIndex
].value
= value
;
914 async
handleGetConfiguration(commandPayload
) {
915 const configurationKey
= [];
916 const unknownKey
= [];
917 if (Utils
.isEmptyArray(commandPayload
.key
)) {
918 for (const configuration
of this._configuration
.configurationKey
) {
919 if (Utils
.isUndefined(configuration
.visible
)) {
920 configuration
.visible
= true;
922 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
924 if (!configuration
.visible
) {
927 configurationKey
.push({
928 key
: configuration
.key
,
929 readonly
: configuration
.readonly
,
930 value
: configuration
.value
,
934 for (const configurationKey
of commandPayload
.key
) {
935 const keyFound
= this._getConfigurationKey(configurationKey
);
937 if (Utils
.isUndefined(keyFound
.visible
)) {
938 keyFound
.visible
= true;
940 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
942 if (!keyFound
.visible
) {
945 configurationKey
.push({
947 readonly
: keyFound
.readonly
,
948 value
: keyFound
.value
,
951 unknownKey
.push(configurationKey
);
961 async
handleChangeConfiguration(commandPayload
) {
962 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
964 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
965 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
966 return Constants
.OCPP_RESPONSE_REJECTED
;
967 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
968 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
969 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
970 let triggerHeartbeatRestart
= false;
971 if (keyToChange
.key
=== 'HeartBeatInterval') {
972 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
973 triggerHeartbeatRestart
= true;
975 if (keyToChange
.key
=== 'HeartbeatInterval') {
976 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
977 triggerHeartbeatRestart
= true;
979 if (triggerHeartbeatRestart
) {
980 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
982 this._stopHeartbeat();
984 this._startHeartbeat(this);
986 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
987 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
989 return Constants
.OCPP_RESPONSE_ACCEPTED
;
993 async
handleRemoteStartTransaction(commandPayload
) {
994 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
995 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
996 // Check if authorized
997 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
998 // Authorization successful start transaction
999 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
1000 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1001 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1003 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
1004 return Constants
.OCPP_RESPONSE_REJECTED
;
1006 // No local authorization check required => start transaction
1007 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
1008 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1009 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1012 async
handleRemoteStopTransaction(commandPayload
) {
1013 for (const connector
in this._connectors
) {
1014 if (this.getConnector(connector
).transactionId
=== commandPayload
.transactionId
) {
1015 this.sendStopTransaction(commandPayload
.transactionId
);
1016 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1019 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1020 return Constants
.OCPP_RESPONSE_REJECTED
;
1024 module
.exports
= ChargingStation
;