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 {performance
, PerformanceObserver
} = require('perf_hooks');
12 class ChargingStation
{
13 constructor(index
, stationTemplateFile
) {
15 this._stationTemplateFile
= stationTemplateFile
;
18 this._autoReconnectRetryCount
= 0;
19 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
20 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
23 this._messageQueue
= [];
25 this._isSocketRestart
= false;
27 this._authorizedTags
= this._loadAndGetAuthorizedTags();
31 this._stationInfo
= this._buildStationInfo();
32 this._bootNotificationMessage
= {
33 chargePointModel
: this._stationInfo
.chargePointModel
,
34 chargePointVendor
: this._stationInfo
.chargePointVendor
,
35 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
36 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
38 this._configuration
= this._getConfiguration();
39 this._supervisionUrl
= this._getSupervisionURL();
40 this._statistics
= new Statistics(this._stationInfo
.name
);
41 this._performanceObserver
= new PerformanceObserver((list
) => {
42 const entry
= list
.getEntries()[0];
43 this._statistics
.logPerformance(entry
, 'ChargingStation');
44 this._performanceObserver
.disconnect();
49 return Utils
.basicFormatLog(` ${this._stationInfo.name}:`);
53 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
56 _getAuthorizationFile() {
57 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
60 _loadAndGetAuthorizedTags() {
61 let authorizedTags
= [];
62 const authorizationFile
= this._getAuthorizationFile();
63 if (authorizationFile
) {
65 // Load authorization file
66 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
67 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
68 fs
.closeSync(fileDescriptor
);
70 logger
.error(this._basicFormatLog() + ' Authorization file loading error: ' + error
);
73 logger
.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile
);
75 return authorizedTags
;
78 _startAuthorizationFileMonitoring() {
79 // eslint-disable-next-line no-unused-vars
80 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
82 logger
.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
83 // Initialize _authorizedTags
84 this._authorizedTags
= this._loadAndGetAuthorizedTags();
86 logger
.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error
);
91 _startStationTemplateFileMonitoring() {
92 // eslint-disable-next-line no-unused-vars
93 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
95 logger
.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
98 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
: 0));
99 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
: 0), false, false);
100 this._addConfigurationKey('NumberOfConnectors', this._getMaxConnectors(), true);
102 logger
.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error
);
107 _getSupervisionURL() {
108 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
110 if (Array
.isArray(supervisionUrls
)) {
111 if (Configuration
.getDistributeStationToTenantEqually()) {
112 indexUrl
= this._index
% supervisionUrls
.length
;
115 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
117 return supervisionUrls
[indexUrl
];
119 return supervisionUrls
;
122 _getStationName(stationTemplate
) {
123 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
126 _getAuthorizeRemoteTxRequests() {
127 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
128 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
131 _getLocalAuthListEnabled() {
132 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
133 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
136 _buildStationInfo() {
137 let stationTemplateFromFile
;
139 // Load template file
140 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
141 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
142 fs
.closeSync(fileDescriptor
);
144 logger
.error(this._basicFormatLog() + ' Template file loading error: ' + error
);
146 const stationTemplate
= stationTemplateFromFile
|| {};
147 if (Array
.isArray(stationTemplateFromFile
.power
)) {
148 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
150 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
152 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
153 return stationTemplate
;
157 this._url
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
158 this._wsConnection
= new WebSocket(this._url
, 'ocpp1.6');
159 logger
.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl
);
160 // Monitor authorization file
161 this._startAuthorizationFileMonitoring();
162 // Monitor station template file
163 this._startStationTemplateFileMonitoring();
164 // Handle Socket incoming messages
165 this._wsConnection
.on('message', this.onMessage
.bind(this));
166 // Handle Socket error
167 this._wsConnection
.on('error', this.onError
.bind(this));
168 // Handle Socket close
169 this._wsConnection
.on('close', this.onClose
.bind(this));
170 // Handle Socket opening connection
171 this._wsConnection
.on('open', this.onOpen
.bind(this));
172 // Handle Socket ping
173 this._wsConnection
.on('ping', this.onPing
.bind(this));
177 logger
.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`);
178 if (!this._heartbeatInterval
) {
179 // Send BootNotification
181 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
183 logger
.error(this._basicFormatLog() + ' Send boot notification error: ' + error
);
186 if (this._isSocketRestart
) {
187 this._basicStartMessageSequence();
188 if (this._messageQueue
.length
> 0) {
189 this._messageQueue
.forEach((message
) => {
190 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
191 this._wsConnection
.send(message
);
196 this._autoReconnectRetryCount
= 0;
197 this._isSocketRestart
= false;
203 this._isSocketRestart
= true;
204 this._reconnect(error
);
207 logger
.error(this._basicFormatLog() + ' Socket error: ' + error
);
214 case 1000: // Normal close
216 logger
.info(this._basicFormatLog() + ' Socket normally closed ' + error
);
217 this._autoReconnectRetryCount
= 0;
219 default: // Abnormal close
220 this._isSocketRestart
= true;
221 this._reconnect(error
);
227 logger
.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
230 async
onMessage(message
) {
231 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
234 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
236 // Check the Type of message
237 switch (messageType
) {
239 case Constants
.OCPP_JSON_CALL_MESSAGE
:
241 await
this.handleRequest(messageId
, commandName
, commandPayload
);
244 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
246 // eslint-disable-next-line no-case-declarations
247 let responseCallback
; let requestPayload
;
248 if (Utils
.isIterable(this._requests
[messageId
])) {
249 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
251 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
253 if (!responseCallback
) {
255 throw new Error(`Response for unknown message id ${messageId}`);
257 delete this._requests
[messageId
];
258 responseCallback(commandName
, requestPayload
);
261 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
262 if (!this._requests
[messageId
]) {
264 throw new Error(`Error for unknown message id ${messageId}`);
266 // eslint-disable-next-line no-case-declarations
268 if (Utils
.isIterable(this._requests
[messageId
])) {
269 [, rejectCallback
] = this._requests
[messageId
];
271 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
273 delete this._requests
[messageId
];
274 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
278 throw new Error(`Wrong message type ${messageType}`);
282 logger
.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message
, error
, this._requests
[messageId
]);
284 // await this.sendError(messageId, error);
288 // eslint-disable-next-line class-methods-use-this
289 async
_startHeartbeat(self
) {
290 if (self
._heartbeatInterval
&& !self
._heartbeatSetInterval
) {
291 self
._heartbeatSetInterval
= setInterval(() => {
294 currentTime
: new Date().toISOString(),
296 self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
298 logger
.error(self
._basicFormatLog() + ' Send heartbeat error: ' + error
);
300 }, self
._heartbeatInterval
);
301 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
303 logger
.error(self
._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
308 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
310 if (this._heartbeatSetInterval
) {
311 clearInterval(this._heartbeatSetInterval
);
312 this._heartbeatSetInterval
= null;
314 // Stop the ATG if needed
315 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
316 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
317 this._automaticTransactionGeneration
&&
318 !this._automaticTransactionGeneration
.timeToStop
) {
319 this._automaticTransactionGeneration
.stop();
321 if (this._autoReconnectTimeout
!== 0 &&
322 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
323 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
324 this._autoReconnectRetryCount
++;
326 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
328 }, this._autoReconnectTimeout
);
329 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
330 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
334 sendError(messageId
, err
) {
335 // Check exception: only OCPP error are accepted
336 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
338 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
341 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
348 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
350 logger
.error(this._basicFormatLog() + ' Send status error: ' + error
);
354 async
sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
355 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
358 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
359 // Send a message through wsConnection
362 return new Promise((resolve
, reject
) => {
365 switch (messageType
) {
367 case Constants
.OCPP_JSON_CALL_MESSAGE
:
368 this._statistics
.addMessage(commandName
);
370 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
371 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
374 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
375 this._statistics
.addMessage(commandName
);
377 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
380 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
382 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
383 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
386 // Check if wsConnection is ready
387 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
389 this._wsConnection
.send(messageToSend
);
391 // Buffer message until connection is back
392 this._messageQueue
.push(messageToSend
);
395 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
398 } else if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
399 // Send timeout in case connection is open otherwise wait for ever
400 // FIXME: Handle message on timeout
401 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
404 // Function that will receive the request's response
405 function responseCallback(payload
, requestPayload
) {
406 self
._statistics
.addMessage(commandName
, true);
407 const responseCallbackFn
= 'handleResponse' + commandName
;
408 if (typeof self
[responseCallbackFn
] === 'function') {
409 self
[responseCallbackFn
](payload
, requestPayload
, self
);
411 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
417 // Function that will receive the request's rejection
418 function rejectCallback(reason
) {
419 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
421 // eslint-disable-next-line no-empty-function
422 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
423 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
430 async
_basicStartMessageSequence() {
432 this._startHeartbeat(this);
434 if (!this._connectors
) {
435 this._connectors
= {};
436 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
437 // Determine number of customized connectors
439 for (lastConnector
in connectorsConfig
) {
440 // Add connector 0, OCPP specification violation that for example KEBA have
441 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
442 connectorsConfig
[lastConnector
]) {
443 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
446 const maxConnectors
= this._getMaxConnectors();
447 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
448 // Generate all connectors
449 for (let index
= 1; index
<= maxConnectors
; index
++) {
450 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
451 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
455 for (const connector
in this._connectors
) {
456 if (!this._connectors
[connector
].transactionStarted
) {
457 if (this._connectors
[connector
].bootStatus
) {
458 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
460 this.sendStatusNotificationWithTimeout(connector
, 'Available');
463 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
467 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
468 if (!this._automaticTransactionGeneration
) {
469 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
471 if (this._automaticTransactionGeneration
.timeToStop
) {
472 this._automaticTransactionGeneration
.start();
475 this._statistics
.start();
478 _resetTransactionOnConnector(connectorID
) {
479 this._connectors
[connectorID
].transactionStarted
= false;
480 this._connectors
[connectorID
].transactionId
= null;
481 this._connectors
[connectorID
].idTag
= null;
482 this._connectors
[connectorID
].lastConsumptionValue
= -1;
483 this._connectors
[connectorID
].lastSoC
= -1;
484 if (this._connectors
[connectorID
].transactionSetInterval
) {
485 clearInterval(this._connectors
[connectorID
].transactionSetInterval
);
489 handleResponseBootNotification(payload
) {
490 if (payload
.status
=== 'Accepted') {
491 this._heartbeatInterval
= payload
.interval
* 1000;
492 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
493 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
494 this._basicStartMessageSequence();
496 logger
.info(this._basicFormatLog() + ' Boot Notification rejected');
500 handleResponseStartTransaction(payload
, requestPayload
) {
501 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
502 logger
.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ' by transaction ' + this._connectors
[requestPayload
.connectorId
].transactionId
);
505 let transactionConnectorId
;
506 for (const connector
in this._connectors
) {
507 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
508 transactionConnectorId
= connector
;
512 if (!transactionConnectorId
) {
513 logger
.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
516 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
517 this._connectors
[transactionConnectorId
].transactionStarted
= true;
518 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
519 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
520 this._connectors
[transactionConnectorId
].lastConsumptionValue
= 0;
521 this._connectors
[transactionConnectorId
].lastSoC
= 0;
522 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
523 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[transactionConnectorId
].transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
524 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
525 this.startMeterValues(requestPayload
.connectorId
,
526 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
528 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
529 this._resetTransactionOnConnector(transactionConnectorId
);
530 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
534 handleResponseStopTransaction(payload
, requestPayload
) {
535 let transactionConnectorId
;
536 for (const connector
in this._connectors
) {
537 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
538 transactionConnectorId
= connector
;
542 if (!transactionConnectorId
) {
543 logger
.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
546 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
547 this.sendStatusNotification(transactionConnectorId
, 'Available');
548 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[transactionConnectorId
].transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
549 this._resetTransactionOnConnector(transactionConnectorId
);
551 logger
.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors
[transactionConnectorId
].transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
555 handleResponseStatusNotification(payload
, requestPayload
) {
556 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload
, requestPayload
);
559 handleResponseMeterValues(payload
, requestPayload
) {
560 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
563 handleResponseHeartbeat(payload
, requestPayload
) {
564 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
567 async
handleRequest(messageId
, commandName
, commandPayload
) {
569 this._statistics
.addMessage(commandName
, true);
571 if (typeof this['handle' + commandName
] === 'function') {
574 result
= await
this['handle' + commandName
](commandPayload
);
577 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
578 // Send back response to inform backend
579 await
this.sendError(messageId
, error
);
583 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
584 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
587 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
590 _getConfigurationKey(key
) {
591 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
594 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
595 const keyFound
= this._getConfigurationKey(key
);
597 this._configuration
.configurationKey
.push({
607 _setConfigurationKeyValue(key
, value
) {
608 const keyFound
= this._getConfigurationKey(key
);
610 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
611 this._configuration
.configurationKey
[keyIndex
].value
= value
;
615 async
handleGetConfiguration(commandPayload
) {
616 const configurationKey
= [];
617 const unknownKey
= [];
618 if (Utils
.isEmptyArray(commandPayload
.key
)) {
619 for (const configuration
of this._configuration
.configurationKey
) {
620 if (Utils
.isUndefined(configuration
.visible
)) {
621 configuration
.visible
= true;
623 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
625 if (!configuration
.visible
) {
628 configurationKey
.push({
629 key
: configuration
.key
,
630 readonly
: configuration
.readonly
,
631 value
: configuration
.value
,
635 for (const configurationKey
of commandPayload
.key
) {
636 const keyFound
= this._getConfigurationKey(configurationKey
);
638 if (Utils
.isUndefined(keyFound
.visible
)) {
639 keyFound
.visible
= true;
641 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
643 if (!keyFound
.visible
) {
646 configurationKey
.push({
648 readonly
: keyFound
.readonly
,
649 value
: keyFound
.value
,
652 unknownKey
.push(configurationKey
);
662 async
handleChangeConfiguration(commandPayload
) {
663 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
665 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
666 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
667 return Constants
.OCPP_RESPONSE_REJECTED
;
668 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
669 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
670 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
671 let triggerHeartbeatRestart
= false;
672 if (keyToChange
.key
=== 'HeartBeatInterval') {
673 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
674 triggerHeartbeatRestart
= true;
676 if (keyToChange
.key
=== 'HeartbeatInterval') {
677 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
678 triggerHeartbeatRestart
= true;
680 if (triggerHeartbeatRestart
) {
681 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
683 if (this._heartbeatSetInterval
) {
684 clearInterval(this._heartbeatSetInterval
);
685 this._heartbeatSetInterval
= null;
688 this._startHeartbeat(this);
690 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
691 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
693 return Constants
.OCPP_RESPONSE_ACCEPTED
;
697 async
handleRemoteStartTransaction(commandPayload
) {
698 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
699 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
700 // Check if authorized
701 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
702 // Authorization successful start transaction
703 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
704 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
705 return Constants
.OCPP_RESPONSE_ACCEPTED
;
707 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
708 return Constants
.OCPP_RESPONSE_REJECTED
;
710 // No local authorization check required => start transaction
711 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
712 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
713 return Constants
.OCPP_RESPONSE_ACCEPTED
;
716 async
handleRemoteStopTransaction(commandPayload
) {
717 for (const connector
in this._connectors
) {
718 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
719 this.sendStopTransaction(commandPayload
.transactionId
);
720 return Constants
.OCPP_RESPONSE_ACCEPTED
;
723 logger
.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
724 return Constants
.OCPP_RESPONSE_REJECTED
;
727 async
sendStartTransaction(connectorID
, idTag
) {
730 connectorId
: connectorID
,
733 timestamp
: new Date().toISOString(),
735 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
737 logger
.error(this._basicFormatLog() + ' Send start transaction error: ' + error
);
741 async
sendStartTransactionWithTimeout(connectorID
, idTag
, timeout
) {
742 setTimeout(() => this.sendStartTransaction(connectorID
, idTag
), timeout
);
745 async
sendStopTransaction(transactionId
) {
750 timestamp
: new Date().toISOString(),
752 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
754 logger
.error(this._basicFormatLog() + ' Send stop transaction error: ' + error
);
759 // eslint-disable-next-line class-methods-use-this
760 async
sendMeterValues(connectorID
, interval
, self
, debug
= false) {
762 const sampledValueLcl
= {
763 timestamp
: new Date().toISOString(),
765 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
766 if (Array
.isArray(meterValuesClone
)) {
767 sampledValueLcl
.sampledValue
= meterValuesClone
;
769 sampledValueLcl
.sampledValue
= [meterValuesClone
];
771 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
772 const connector
= self
._connectors
[connectorID
];
773 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
774 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
775 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
776 logger
.error(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}`);
779 // Persist previous value in connector
780 const consumption
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
781 if (connector
&& connector
.lastConsumptionValue
>= 0) {
782 connector
.lastConsumptionValue
+= consumption
;
784 connector
.lastConsumptionValue
= 0;
786 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / interval
;
787 logger
.info(`${self._basicFormatLog()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorID ${connectorID}, transaction ${connector.transactionId}, value ${connector.lastConsumptionValue}`);
788 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastConsumptionValue
;
789 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
790 logger
.error(`${self._basicFormatLog()} 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}`);
796 connectorId
: connectorID
,
797 transactionId
: self
._connectors
[connectorID
].transactionId
,
798 meterValue
: [sampledValueLcl
],
800 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
802 logger
.error(self
._basicFormatLog() + ' Send MeterValues error: ' + error
);
806 async
startMeterValues(connectorID
, interval
) {
807 if (!this._connectors
[connectorID
].transactionStarted
) {
808 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
810 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
811 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
814 this._connectors
[connectorID
].transactionSetInterval
= setInterval(async () => {
815 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
816 this._performanceObserver
.observe({
817 entryTypes
: ['function'],
819 await
sendMeterValues(connectorID
, interval
, this);
823 hasAuthorizedTags() {
824 return !Utils
.isEmptyArray(this._authorizedTags
);
828 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
829 return this._authorizedTags
[index
];
832 _getConnector(number
) {
833 return this._stationInfo
.Connectors
[number
];
836 _getMaxConnectors() {
837 let maxConnectors
= 0;
838 if (Array
.isArray(this._stationInfo
.numberOfConnectors
)) {
839 // Generate some connectors
840 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
842 maxConnectors
= this._stationInfo
.numberOfConnectors
;
844 return maxConnectors
;
848 module
.exports
= ChargingStation
;