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 // Avoid duplication of connectors related information
99 delete this._stationInfo
.Connectors
;
100 // Initialize transaction attributes on connectors
101 for (const connector
in this._connectors
) {
102 if (!this._connectors
[connector
].transactionStarted
) {
103 this._initTransactionOnConnector(connector
);
106 this._stationInfo
.powerDivider
= this._getPowerDivider();
107 // FIXME: Conditionally initialize or use singleton design pattern per charging station
108 this._statistics
= new Statistics(this._stationInfo
.name
);
109 this._performanceObserver
= new PerformanceObserver((list
) => {
110 const entry
= list
.getEntries()[0];
111 this._statistics
.logPerformance(entry
, 'ChargingStation');
112 this._performanceObserver
.disconnect();
117 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
120 _getConfiguration() {
121 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
124 _getAuthorizationFile() {
125 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
128 _loadAndGetAuthorizedTags() {
129 let authorizedTags
= [];
130 const authorizationFile
= this._getAuthorizationFile();
131 if (authorizationFile
) {
133 // Load authorization file
134 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
135 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
136 fs
.closeSync(fileDescriptor
);
138 logger
.error(this._logPrefix() + ' Authorization file loading error: ' + error
);
141 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
143 return authorizedTags
;
147 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
148 return this._authorizedTags
[index
];
151 hasAuthorizedTags() {
152 return !Utils
.isEmptyArray(this._authorizedTags
);
155 _getNumberOfRunningTransactions() {
157 for (const connector
in this._connectors
) {
158 if (this._getConnector(connector
).transactionStarted
) {
166 let powerDivider
= this._getNumberOfConnectors();
167 if (this._stationInfo
.powerSharedByConnectors
) {
168 powerDivider
= this._getNumberOfRunningTransactions();
173 _getConnector(number
) {
174 return this._connectors
[number
];
177 _getMaxNumberOfConnectors() {
178 let maxConnectors
= 0;
179 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
180 // Distribute evenly the number of connectors
181 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
183 maxConnectors
= this._stationInfo
.numberOfConnectors
;
185 return maxConnectors
;
188 _getNumberOfConnectors() {
189 return Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) ? Object
.keys(this._connectors
).length
- 1 : Object
.keys(this._connectors
).length
;
192 _getSupervisionURL() {
193 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
195 if (!Utils
.isEmptyArray(supervisionUrls
)) {
196 if (Configuration
.getDistributeStationToTenantEqually()) {
197 indexUrl
= this._index
% supervisionUrls
.length
;
200 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
202 return supervisionUrls
[indexUrl
];
204 return supervisionUrls
;
207 _getAuthorizeRemoteTxRequests() {
208 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
209 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
212 _getLocalAuthListEnabled() {
213 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
214 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
217 async
_basicStartMessageSequence() {
219 this._startHeartbeat(this);
220 // Initialize connectors status
221 for (const connector
in this._connectors
) {
222 if (!this._connectors
[connector
].transactionStarted
) {
223 if (this._connectors
[connector
].bootStatus
) {
224 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
226 this.sendStatusNotificationWithTimeout(connector
, 'Available');
229 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
233 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
234 if (!this._automaticTransactionGeneration
) {
235 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
237 if (this._automaticTransactionGeneration
.timeToStop
) {
238 this._automaticTransactionGeneration
.start();
241 this._statistics
.start();
244 // eslint-disable-next-line class-methods-use-this
245 async
_startHeartbeat(self
) {
246 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
247 self
._heartbeatSetInterval
= setInterval(() => {
248 this.sendHeartbeat();
249 }, self
._heartbeatInterval
);
250 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
252 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
256 async
_stopHeartbeat() {
257 if (this._heartbeatSetInterval
) {
258 clearInterval(this._heartbeatSetInterval
);
259 this._heartbeatSetInterval
= null;
263 _startAuthorizationFileMonitoring() {
264 // eslint-disable-next-line no-unused-vars
265 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
267 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
268 // Initialize _authorizedTags
269 this._authorizedTags
= this._loadAndGetAuthorizedTags();
271 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
276 _startStationTemplateFileMonitoring() {
277 // eslint-disable-next-line no-unused-vars
278 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
280 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
283 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
284 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
286 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
291 async
_startMeterValues(connectorId
, interval
) {
292 if (!this._connectors
[connectorId
].transactionStarted
) {
293 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
295 } else if (this._connectors
[connectorId
].transactionStarted
&& !this._connectors
[connectorId
].transactionId
) {
296 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
300 this._connectors
[connectorId
].transactionSetInterval
= setInterval(async () => {
301 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
302 this._performanceObserver
.observe({
303 entryTypes
: ['function'],
305 await
sendMeterValues(connectorId
, interval
, this);
308 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
313 if (!this._wsConnectionUrl
) {
314 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
316 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
317 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
318 // Monitor authorization file
319 this._startAuthorizationFileMonitoring();
320 // Monitor station template file
321 this._startStationTemplateFileMonitoring();
322 // Handle Socket incoming messages
323 this._wsConnection
.on('message', this.onMessage
.bind(this));
324 // Handle Socket error
325 this._wsConnection
.on('error', this.onError
.bind(this));
326 // Handle Socket close
327 this._wsConnection
.on('close', this.onClose
.bind(this));
328 // Handle Socket opening connection
329 this._wsConnection
.on('open', this.onOpen
.bind(this));
330 // Handle Socket ping
331 this._wsConnection
.on('ping', this.onPing
.bind(this));
334 async
stop(reason
= '') {
336 await
this._stopHeartbeat();
338 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
339 this._automaticTransactionGeneration
&&
340 !this._automaticTransactionGeneration
.timeToStop
) {
341 await
this._automaticTransactionGeneration
.stop(reason
);
343 for (const connector
in this._connectors
) {
344 if (this._connectors
[connector
].transactionStarted
) {
345 await
this.sendStopTransaction(this._connectors
[connector
].transactionId
, reason
);
349 // eslint-disable-next-line guard-for-in
350 for (const connector
in this._connectors
) {
351 await
this.sendStatusNotification(connector
, 'Unavailable');
353 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
354 await
this._wsConnection
.close();
359 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
360 // Stop the ATG if needed
361 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
362 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
363 this._automaticTransactionGeneration
&&
364 !this._automaticTransactionGeneration
.timeToStop
) {
365 this._automaticTransactionGeneration
.stop();
368 this._stopHeartbeat();
369 if (this._autoReconnectTimeout
!== 0 &&
370 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
371 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
372 this._autoReconnectRetryCount
++;
374 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
376 }, this._autoReconnectTimeout
);
377 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
378 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
383 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
384 if (!this._isSocketRestart
) {
385 // Send BootNotification
386 this.sendBootNotification();
388 if (this._isSocketRestart
) {
389 this._basicStartMessageSequence();
390 if (!Utils
.isEmptyArray(this._messageQueue
)) {
391 this._messageQueue
.forEach((message
) => {
392 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
393 this._wsConnection
.send(message
);
398 this._autoReconnectRetryCount
= 0;
399 this._isSocketRestart
= false;
405 this._isSocketRestart
= true;
406 this._reconnect(error
);
409 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
416 case 1000: // Normal close
418 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
419 this._autoReconnectRetryCount
= 0;
421 default: // Abnormal close
422 this._isSocketRestart
= true;
423 this._reconnect(error
);
429 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
432 async
onMessage(message
) {
433 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
436 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
438 // Check the Type of message
439 switch (messageType
) {
441 case Constants
.OCPP_JSON_CALL_MESSAGE
:
443 await
this.handleRequest(messageId
, commandName
, commandPayload
);
446 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
448 // eslint-disable-next-line no-case-declarations
449 let responseCallback
; let requestPayload
;
450 if (Utils
.isIterable(this._requests
[messageId
])) {
451 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
453 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
455 if (!responseCallback
) {
457 throw new Error(`Response for unknown message id ${messageId}`);
459 delete this._requests
[messageId
];
460 responseCallback(commandName
, requestPayload
);
463 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
464 if (!this._requests
[messageId
]) {
466 throw new Error(`Error for unknown message id ${messageId}`);
468 // eslint-disable-next-line no-case-declarations
470 if (Utils
.isIterable(this._requests
[messageId
])) {
471 [, rejectCallback
] = this._requests
[messageId
];
473 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
475 delete this._requests
[messageId
];
476 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
480 throw new Error(`Wrong message type ${messageType}`);
484 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
486 // await this.sendError(messageId, error);
493 currentTime
: new Date().toISOString(),
495 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
497 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
502 sendBootNotification() {
504 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
506 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
511 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
518 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
520 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
525 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
526 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
529 async
sendStartTransaction(connectorId
, idTag
) {
535 timestamp
: new Date().toISOString(),
537 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
539 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
544 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
545 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
548 async
sendStopTransaction(transactionId
, reason
= '') {
555 timestamp
: new Date().toISOString(),
562 timestamp
: new Date().toISOString(),
565 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
567 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
572 // eslint-disable-next-line class-methods-use-this
573 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
575 const sampledValueLcl
= {
576 timestamp
: new Date().toISOString(),
578 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorId
).MeterValues
);
579 if (!Utils
.isEmptyArray(meterValuesClone
)) {
580 sampledValueLcl
.sampledValue
= meterValuesClone
;
582 sampledValueLcl
.sampledValue
= [meterValuesClone
];
584 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
585 const connector
= self
._connectors
[connectorId
];
587 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
588 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
589 sampledValueLcl
.sampledValue
[index
].value
:
590 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
591 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
592 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}`);
595 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
596 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
597 // Energy.Active.Import.Register measurand (default)
598 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
599 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
600 const errMsg
= `${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
601 logger
.error(errMsg
);
603 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
604 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}`;
605 logger
.error(errMsg
);
608 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
609 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
610 // Persist previous value in connector
611 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
612 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
614 connector
.lastEnergyActiveImportRegisterValue
= 0;
616 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
618 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}`);
619 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
620 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
621 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}`);
623 // Unsupported measurand
625 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
631 transactionId
: self
._connectors
[connectorId
].transactionId
,
632 meterValue
: [sampledValueLcl
],
634 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
636 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
641 sendError(messageId
, err
) {
642 // Check exception: only OCPP error are accepted
643 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
645 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
648 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
649 // Send a message through wsConnection
652 return new Promise((resolve
, reject
) => {
655 switch (messageType
) {
657 case Constants
.OCPP_JSON_CALL_MESSAGE
:
658 this._statistics
.addMessage(commandName
);
660 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
661 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
664 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
665 this._statistics
.addMessage(commandName
);
667 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
670 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
672 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
673 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
676 // Check if wsConnection is ready
677 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
679 this._wsConnection
.send(messageToSend
);
681 // Buffer message until connection is back
682 this._messageQueue
.push(messageToSend
);
685 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
688 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
689 // Send timeout in case connection is open otherwise wait for ever
690 // FIXME: Handle message on timeout
691 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
694 // Function that will receive the request's response
695 function responseCallback(payload
, requestPayload
) {
696 self
._statistics
.addMessage(commandName
, true);
697 const responseCallbackFn
= 'handleResponse' + commandName
;
698 if (typeof self
[responseCallbackFn
] === 'function') {
699 self
[responseCallbackFn
](payload
, requestPayload
, self
);
701 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
707 // Function that will receive the request's rejection
708 function rejectCallback(reason
) {
709 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
711 // eslint-disable-next-line no-empty-function
712 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
713 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
720 handleResponseBootNotification(payload
) {
721 if (payload
.status
=== 'Accepted') {
722 this._heartbeatInterval
= payload
.interval
* 1000;
723 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
724 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
725 this._basicStartMessageSequence();
726 } else if (payload
.status
=== 'Pending') {
727 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
729 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
733 _initTransactionOnConnector(connectorId
) {
734 this._connectors
[connectorId
].transactionStarted
= false;
735 this._connectors
[connectorId
].transactionId
= null;
736 this._connectors
[connectorId
].idTag
= null;
737 this._connectors
[connectorId
].lastEnergyActiveImportRegisterValue
= -1;
740 _resetTransactionOnConnector(connectorId
) {
741 this._initTransactionOnConnector(connectorId
);
742 if (this._connectors
[connectorId
].transactionSetInterval
) {
743 clearInterval(this._connectors
[connectorId
].transactionSetInterval
);
747 handleResponseStartTransaction(payload
, requestPayload
) {
748 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
749 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this._connectors
[requestPayload
.connectorId
]);
753 let transactionConnectorId
;
754 for (const connector
in this._connectors
) {
755 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
756 transactionConnectorId
= connector
;
760 if (!transactionConnectorId
) {
761 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
764 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
765 this._connectors
[transactionConnectorId
].transactionStarted
= true;
766 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
767 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
768 this._connectors
[transactionConnectorId
].lastEnergyActiveImportRegisterValue
= 0;
769 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
770 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
771 if (this._stationInfo
.powerSharedByConnectors
) {
772 this._stationInfo
.powerDivider
++;
774 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
775 this._startMeterValues(requestPayload
.connectorId
,
776 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
778 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
779 this._resetTransactionOnConnector(transactionConnectorId
);
780 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
784 handleResponseStopTransaction(payload
, requestPayload
) {
785 let transactionConnectorId
;
786 for (const connector
in this._connectors
) {
787 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
788 transactionConnectorId
= connector
;
792 if (!transactionConnectorId
) {
793 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
796 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
797 this.sendStatusNotification(transactionConnectorId
, 'Available');
798 if (this._stationInfo
.powerSharedByConnectors
) {
799 this._stationInfo
.powerDivider
--;
801 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
802 this._resetTransactionOnConnector(transactionConnectorId
);
804 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
808 handleResponseStatusNotification(payload
, requestPayload
) {
809 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
812 handleResponseMeterValues(payload
, requestPayload
) {
813 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
816 handleResponseHeartbeat(payload
, requestPayload
) {
817 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
820 async
handleRequest(messageId
, commandName
, commandPayload
) {
822 this._statistics
.addMessage(commandName
, true);
824 if (typeof this['handle' + commandName
] === 'function') {
827 result
= await
this['handle' + commandName
](commandPayload
);
830 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
831 // Send back response to inform backend
832 await
this.sendError(messageId
, error
);
836 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
837 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
840 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
843 async
handleReset(commandPayload
) {
844 // Simulate charging station restart
845 setImmediate(async () => {
846 await
this.stop(commandPayload
.type
+ 'Reset');
847 await Utils
.sleep(this._stationInfo
.resetTime
);
850 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
851 return Constants
.OCPP_RESPONSE_ACCEPTED
;
854 _getConfigurationKey(key
) {
855 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
858 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
859 const keyFound
= this._getConfigurationKey(key
);
861 this._configuration
.configurationKey
.push({
871 _setConfigurationKeyValue(key
, value
) {
872 const keyFound
= this._getConfigurationKey(key
);
874 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
875 this._configuration
.configurationKey
[keyIndex
].value
= value
;
879 async
handleGetConfiguration(commandPayload
) {
880 const configurationKey
= [];
881 const unknownKey
= [];
882 if (Utils
.isEmptyArray(commandPayload
.key
)) {
883 for (const configuration
of this._configuration
.configurationKey
) {
884 if (Utils
.isUndefined(configuration
.visible
)) {
885 configuration
.visible
= true;
887 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
889 if (!configuration
.visible
) {
892 configurationKey
.push({
893 key
: configuration
.key
,
894 readonly
: configuration
.readonly
,
895 value
: configuration
.value
,
899 for (const configurationKey
of commandPayload
.key
) {
900 const keyFound
= this._getConfigurationKey(configurationKey
);
902 if (Utils
.isUndefined(keyFound
.visible
)) {
903 keyFound
.visible
= true;
905 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
907 if (!keyFound
.visible
) {
910 configurationKey
.push({
912 readonly
: keyFound
.readonly
,
913 value
: keyFound
.value
,
916 unknownKey
.push(configurationKey
);
926 async
handleChangeConfiguration(commandPayload
) {
927 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
929 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
930 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
931 return Constants
.OCPP_RESPONSE_REJECTED
;
932 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
933 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
934 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
935 let triggerHeartbeatRestart
= false;
936 if (keyToChange
.key
=== 'HeartBeatInterval') {
937 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
938 triggerHeartbeatRestart
= true;
940 if (keyToChange
.key
=== 'HeartbeatInterval') {
941 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
942 triggerHeartbeatRestart
= true;
944 if (triggerHeartbeatRestart
) {
945 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
947 this._stopHeartbeat();
949 this._startHeartbeat(this);
951 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
952 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
954 return Constants
.OCPP_RESPONSE_ACCEPTED
;
958 async
handleRemoteStartTransaction(commandPayload
) {
959 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
960 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
961 // Check if authorized
962 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
963 // Authorization successful start transaction
964 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
965 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
966 return Constants
.OCPP_RESPONSE_ACCEPTED
;
968 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
969 return Constants
.OCPP_RESPONSE_REJECTED
;
971 // No local authorization check required => start transaction
972 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
973 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
974 return Constants
.OCPP_RESPONSE_ACCEPTED
;
977 async
handleRemoteStopTransaction(commandPayload
) {
978 for (const connector
in this._connectors
) {
979 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
980 this.sendStopTransaction(commandPayload
.transactionId
);
981 return Constants
.OCPP_RESPONSE_ACCEPTED
;
984 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
985 return Constants
.OCPP_RESPONSE_REJECTED
;
989 module
.exports
= ChargingStation
;