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');
99 logger
.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error
);
104 _getSupervisionURL() {
105 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
107 if (Array
.isArray(supervisionUrls
)) {
108 if (Configuration
.getDistributeStationToTenantEqually()) {
109 indexUrl
= this._index
% supervisionUrls
.length
;
112 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
114 return supervisionUrls
[indexUrl
];
116 return supervisionUrls
;
119 _getStationName(stationTemplate
) {
120 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
123 _getAuthorizeRemoteTxRequests() {
124 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
125 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
128 _getLocalAuthListEnabled() {
129 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
130 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
133 _buildStationInfo() {
134 let stationTemplateFromFile
;
136 // Load template file
137 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
138 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
139 fs
.closeSync(fileDescriptor
);
141 logger
.error(this._basicFormatLog() + ' Template file loading error: ' + error
);
143 const stationTemplate
= stationTemplateFromFile
|| {};
144 if (Array
.isArray(stationTemplateFromFile
.power
)) {
145 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
147 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
149 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
150 return stationTemplate
;
154 this._url
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
155 this._wsConnection
= new WebSocket(this._url
, 'ocpp1.6');
156 logger
.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl
);
157 // Monitor authorization file
158 this._startAuthorizationFileMonitoring();
159 // Monitor station template file
160 this._startStationTemplateFileMonitoring();
161 // Handle Socket incoming messages
162 this._wsConnection
.on('message', this.onMessage
.bind(this));
163 // Handle Socket error
164 this._wsConnection
.on('error', this.onError
.bind(this));
165 // Handle Socket close
166 this._wsConnection
.on('close', this.onClose
.bind(this));
167 // Handle Socket opening connection
168 this._wsConnection
.on('open', this.onOpen
.bind(this));
169 // Handle Socket ping
170 this._wsConnection
.on('ping', this.onPing
.bind(this));
174 logger
.info(`${this._basicFormatLog()} Is connected to server through ${this._url}`);
175 if (!this._heartbeatInterval
) {
176 // Send BootNotification
178 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
180 logger
.error(this._basicFormatLog() + ' Send boot notification error: ' + error
);
183 if (this._isSocketRestart
) {
184 this._basicStartMessageSequence();
185 if (this._messageQueue
.length
> 0) {
186 this._messageQueue
.forEach((message
) => {
187 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
188 this._wsConnection
.send(message
);
193 this._autoReconnectRetryCount
= 0;
194 this._isSocketRestart
= false;
200 this._isSocketRestart
= true;
201 this._reconnect(error
);
204 logger
.error(this._basicFormatLog() + ' Socket error: ' + error
);
211 case 1000: // Normal close
213 logger
.info(this._basicFormatLog() + ' Socket normally closed ' + error
);
214 this._autoReconnectRetryCount
= 0;
216 default: // Abnormal close
217 this._isSocketRestart
= true;
218 this._reconnect(error
);
224 logger
.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
227 async
onMessage(message
) {
228 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
231 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
233 // Check the Type of message
234 switch (messageType
) {
236 case Constants
.OCPP_JSON_CALL_MESSAGE
:
238 await
this.handleRequest(messageId
, commandName
, commandPayload
);
241 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
243 // eslint-disable-next-line no-case-declarations
244 let responseCallback
; let requestPayload
;
245 if (Utils
.isIterable(this._requests
[messageId
])) {
246 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
248 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
250 if (!responseCallback
) {
252 throw new Error(`Response for unknown message id ${messageId}`);
254 delete this._requests
[messageId
];
255 responseCallback(commandName
, requestPayload
);
258 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
259 if (!this._requests
[messageId
]) {
261 throw new Error(`Error for unknown message id ${messageId}`);
263 // eslint-disable-next-line no-case-declarations
265 if (Utils
.isIterable(this._requests
[messageId
])) {
266 [, rejectCallback
] = this._requests
[messageId
];
268 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
270 delete this._requests
[messageId
];
271 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
275 throw new Error(`Wrong message type ${messageType}`);
279 logger
.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message
, error
, this._requests
[messageId
]);
281 // await this.sendError(messageId, error);
285 // eslint-disable-next-line class-methods-use-this
286 async
_startHeartbeat(self
) {
287 if (self
._heartbeatInterval
&& !self
._heartbeatSetInterval
) {
288 self
._heartbeatSetInterval
= setInterval(() => {
291 currentTime
: new Date().toISOString(),
293 self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
295 logger
.error(self
._basicFormatLog() + ' Send heartbeat error: ' + error
);
297 }, self
._heartbeatInterval
);
298 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
300 logger
.error(self
._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
305 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
307 if (this._heartbeatSetInterval
) {
308 clearInterval(this._heartbeatSetInterval
);
309 this._heartbeatSetInterval
= null;
311 // Stop the ATG if needed
312 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
313 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
314 this._automaticTransactionGeneration
&&
315 !this._automaticTransactionGeneration
.timeToStop
) {
316 this._automaticTransactionGeneration
.stop();
318 if (this._autoReconnectTimeout
!== 0 &&
319 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
320 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
321 this._autoReconnectRetryCount
++;
323 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
325 }, this._autoReconnectTimeout
);
326 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
327 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
331 sendError(messageId
, err
) {
332 // Check exception: only OCPP error are accepted
333 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
335 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
338 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
345 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
347 logger
.error(this._basicFormatLog() + ' Send status error: ' + error
);
351 async
sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
352 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
355 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
356 // Send a message through wsConnection
359 return new Promise((resolve
, reject
) => {
362 switch (messageType
) {
364 case Constants
.OCPP_JSON_CALL_MESSAGE
:
365 this._statistics
.addMessage(commandName
);
367 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
368 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
371 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
372 this._statistics
.addMessage(commandName
);
374 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
377 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
379 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
380 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
383 // Check if wsConnection is ready
384 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
386 this._wsConnection
.send(messageToSend
);
388 // Buffer message until connection is back
389 this._messageQueue
.push(messageToSend
);
392 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
395 } else if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
396 // Send timeout in case connection is open otherwise wait for ever
397 // FIXME: Handle message on timeout
398 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
401 // Function that will receive the request's response
402 function responseCallback(payload
, requestPayload
) {
403 self
._statistics
.addMessage(commandName
, true);
404 const responseCallbackFn
= 'handleResponse' + commandName
;
405 if (typeof self
[responseCallbackFn
] === 'function') {
406 self
[responseCallbackFn
](payload
, requestPayload
, self
);
408 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
414 // Function that will receive the request's rejection
415 function rejectCallback(reason
) {
416 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
418 // eslint-disable-next-line no-empty-function
419 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
420 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
427 async
_basicStartMessageSequence() {
429 this._startHeartbeat(this);
431 if (!this._connectors
) {
432 this._connectors
= {};
433 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
434 // Determine number of customized connectors
436 for (lastConnector
in connectorsConfig
) {
437 // Add connector 0, OCPP specification violation that for example KEBA have
438 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
439 connectorsConfig
[lastConnector
]) {
440 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
443 let maxConnectors
= 0;
444 if (Array
.isArray(this._stationInfo
.numberOfConnectors
)) {
445 // Generate some connectors
446 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
448 maxConnectors
= this._stationInfo
.numberOfConnectors
;
450 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
451 // Generate all connectors
452 for (let index
= 1; index
<= maxConnectors
; index
++) {
453 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
454 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
458 for (const connector
in this._connectors
) {
459 if (!this._connectors
[connector
].transactionStarted
) {
460 if (this._connectors
[connector
].bootStatus
) {
461 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
463 this.sendStatusNotificationWithTimeout(connector
, 'Available');
466 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
470 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
471 if (!this._automaticTransactionGeneration
) {
472 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
474 if (this._automaticTransactionGeneration
.timeToStop
) {
475 this._automaticTransactionGeneration
.start();
478 this._statistics
.start();
481 _resetTransactionOnConnector(connectorID
) {
482 this._connectors
[connectorID
].transactionStarted
= false;
483 this._connectors
[connectorID
].transactionId
= null;
484 this._connectors
[connectorID
].idTag
= null;
485 this._connectors
[connectorID
].lastConsumptionValue
= -1;
486 this._connectors
[connectorID
].lastSoC
= -1;
487 if (this._connectors
[connectorID
].transactionSetInterval
) {
488 clearInterval(this._connectors
[connectorID
].transactionSetInterval
);
492 handleResponseBootNotification(payload
) {
493 if (payload
.status
=== 'Accepted') {
494 this._heartbeatInterval
= payload
.interval
* 1000;
495 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
496 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
497 this._basicStartMessageSequence();
499 logger
.info(this._basicFormatLog() + ' Boot Notification rejected');
503 handleResponseStartTransaction(payload
, requestPayload
) {
504 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
505 logger
.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ' by transaction ' + this._connectors
[requestPayload
.connectorId
].transactionId
);
508 let transactionConnectorId
;
509 for (const connector
in this._connectors
) {
510 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
511 transactionConnectorId
= connector
;
515 if (!transactionConnectorId
) {
516 logger
.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
519 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
520 this._connectors
[transactionConnectorId
].transactionStarted
= true;
521 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
522 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
523 this._connectors
[transactionConnectorId
].lastConsumptionValue
= 0;
524 this._connectors
[transactionConnectorId
].lastSoC
= 0;
525 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
526 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[transactionConnectorId
].transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
527 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
528 this.startMeterValues(requestPayload
.connectorId
,
529 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
531 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
532 this._resetTransactionOnConnector(transactionConnectorId
);
533 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
537 handleResponseStopTransaction(payload
, requestPayload
) {
538 let transactionConnectorId
;
539 for (const connector
in this._connectors
) {
540 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
541 transactionConnectorId
= connector
;
545 if (!transactionConnectorId
) {
546 logger
.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
549 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
550 this.sendStatusNotification(transactionConnectorId
, 'Available');
551 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[transactionConnectorId
].transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
552 this._resetTransactionOnConnector(transactionConnectorId
);
554 logger
.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors
[transactionConnectorId
].transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
558 handleResponseStatusNotification(payload
, requestPayload
) {
559 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload
, requestPayload
);
562 handleResponseMeterValues(payload
, requestPayload
) {
563 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
566 handleResponseHeartbeat(payload
, requestPayload
) {
567 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
570 async
handleRequest(messageId
, commandName
, commandPayload
) {
572 this._statistics
.addMessage(commandName
, true);
574 if (typeof this['handle' + commandName
] === 'function') {
577 result
= await
this['handle' + commandName
](commandPayload
);
580 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
581 // Send back response to inform backend
582 await
this.sendError(messageId
, error
);
586 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
587 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
590 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
593 _getConfigurationKey(key
) {
594 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
597 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
598 const keyFound
= this._getConfigurationKey(key
);
600 this._configuration
.configurationKey
.push({
610 _setConfigurationKeyValue(key
, value
) {
611 const keyFound
= this._getConfigurationKey(key
);
613 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
614 this._configuration
.configurationKey
[keyIndex
].value
= value
;
618 async
handleGetConfiguration(commandPayload
) {
619 const configurationKey
= [];
620 const unknownKey
= [];
621 if (Utils
.isEmptyArray(commandPayload
.key
)) {
622 for (const configuration
of this._configuration
.configurationKey
) {
623 if (Utils
.isUndefined(configuration
.visible
)) {
624 configuration
.visible
= true;
626 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
628 if (!configuration
.visible
) {
631 configurationKey
.push({
632 key
: configuration
.key
,
633 readonly
: configuration
.readonly
,
634 value
: configuration
.value
,
638 for (const configurationKey
of commandPayload
.key
) {
639 const keyFound
= this._getConfigurationKey(configurationKey
);
641 if (Utils
.isUndefined(keyFound
.visible
)) {
642 keyFound
.visible
= true;
644 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
646 if (!keyFound
.visible
) {
649 configurationKey
.push({
651 readonly
: keyFound
.readonly
,
652 value
: keyFound
.value
,
655 unknownKey
.push(configurationKey
);
665 async
handleChangeConfiguration(commandPayload
) {
666 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
668 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
669 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
670 return Constants
.OCPP_RESPONSE_REJECTED
;
671 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
672 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
673 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
674 let triggerHeartbeatRestart
= false;
675 if (keyToChange
.key
=== 'HeartBeatInterval') {
676 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
677 triggerHeartbeatRestart
= true;
679 if (keyToChange
.key
=== 'HeartbeatInterval') {
680 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
681 triggerHeartbeatRestart
= true;
683 if (triggerHeartbeatRestart
) {
684 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
686 if (this._heartbeatSetInterval
) {
687 clearInterval(this._heartbeatSetInterval
);
688 this._heartbeatSetInterval
= null;
691 this._startHeartbeat(this);
693 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
694 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
696 return Constants
.OCPP_RESPONSE_ACCEPTED
;
700 async
handleRemoteStartTransaction(commandPayload
) {
701 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
702 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
703 // Check if authorized
704 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
705 // Authorization successful start transaction
706 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
707 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
708 return Constants
.OCPP_RESPONSE_ACCEPTED
;
710 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
711 return Constants
.OCPP_RESPONSE_REJECTED
;
713 // No local authorization check required => start transaction
714 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
715 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
716 return Constants
.OCPP_RESPONSE_ACCEPTED
;
719 async
handleRemoteStopTransaction(commandPayload
) {
720 for (const connector
in this._connectors
) {
721 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
722 this.sendStopTransaction(commandPayload
.transactionId
);
723 return Constants
.OCPP_RESPONSE_ACCEPTED
;
726 logger
.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
727 return Constants
.OCPP_RESPONSE_REJECTED
;
730 async
sendStartTransaction(connectorID
, idTag
) {
733 connectorId
: connectorID
,
736 timestamp
: new Date().toISOString(),
738 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
740 logger
.error(this._basicFormatLog() + ' Send start transaction error: ' + error
);
744 async
sendStartTransactionWithTimeout(connectorID
, idTag
, timeout
) {
745 setTimeout(() => this.sendStartTransaction(connectorID
, idTag
), timeout
);
748 async
sendStopTransaction(transactionId
) {
753 timestamp
: new Date().toISOString(),
755 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
757 logger
.error(this._basicFormatLog() + ' Send stop transaction error: ' + error
);
762 // eslint-disable-next-line class-methods-use-this
763 async
sendMeterValues(connectorID
, interval
, self
, debug
= false) {
765 const sampledValueLcl
= {
766 timestamp
: new Date().toISOString(),
768 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
769 if (Array
.isArray(meterValuesClone
)) {
770 sampledValueLcl
.sampledValue
= meterValuesClone
;
772 sampledValueLcl
.sampledValue
= [meterValuesClone
];
774 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
775 const connector
= self
._connectors
[connectorID
];
776 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
777 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
778 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
779 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}`);
782 // Persist previous value in connector
783 const consumption
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
784 if (connector
&& connector
.lastConsumptionValue
>= 0) {
785 connector
.lastConsumptionValue
+= consumption
;
787 connector
.lastConsumptionValue
= 0;
789 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / interval
;
790 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}`);
791 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastConsumptionValue
;
792 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
793 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}`);
799 connectorId
: connectorID
,
800 transactionId
: self
._connectors
[connectorID
].transactionId
,
801 meterValue
: [sampledValueLcl
],
803 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
805 logger
.error(self
._basicFormatLog() + ' Send MeterValues error: ' + error
);
809 async
startMeterValues(connectorID
, interval
) {
810 if (!this._connectors
[connectorID
].transactionStarted
) {
811 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
813 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
814 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
817 this._connectors
[connectorID
].transactionSetInterval
= setInterval(async () => {
818 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
819 this._performanceObserver
.observe({
820 entryTypes
: ['function'],
822 await
sendMeterValues(connectorID
, interval
, this);
826 hasAuthorizedTags() {
827 return !Utils
.isEmptyArray(this._authorizedTags
);
831 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
832 return this._authorizedTags
[index
];
835 _getConnector(number
) {
836 return this._stationInfo
.Connectors
[number
];
840 module
.exports
= ChargingStation
;