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 this._statistics
.addMessage(commandName
);
239 await
this.handleRequest(messageId
, commandName
, commandPayload
);
242 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
244 // eslint-disable-next-line no-case-declarations
245 let responseCallback
; let requestPayload
;
246 if (Utils
.isIterable(this._requests
[messageId
])) {
247 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
249 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
251 if (!responseCallback
) {
253 throw new Error(`Response for unknown message id ${messageId}`);
255 delete this._requests
[messageId
];
256 // this._statistics.addMessage(commandName)
257 responseCallback(commandName
, requestPayload
);
260 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
261 if (!this._requests
[messageId
]) {
263 throw new Error(`Error for unknown message id ${messageId}`);
265 // eslint-disable-next-line no-case-declarations
267 if (Utils
.isIterable(this._requests
[messageId
])) {
268 [, rejectCallback
] = this._requests
[messageId
];
270 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
272 delete this._requests
[messageId
];
273 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
277 throw new Error(`Wrong message type ${messageType}`);
281 logger
.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message
, error
, this._requests
[messageId
]);
283 // await this.sendError(messageId, error);
287 // eslint-disable-next-line class-methods-use-this
288 async
_startHeartbeat(self
) {
289 if (self
._heartbeatInterval
&& !self
._heartbeatSetInterval
) {
290 self
._heartbeatSetInterval
= setInterval(() => {
293 currentTime
: new Date().toISOString(),
295 self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
297 logger
.error(self
._basicFormatLog() + ' Send heartbeat error: ' + error
);
299 }, self
._heartbeatInterval
);
300 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
302 logger
.error(self
._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
307 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
308 // Stop heartbeat interval
309 if (this._heartbeatSetInterval
) {
310 clearInterval(this._heartbeatSetInterval
);
311 this._heartbeatSetInterval
= null;
313 // Stop the ATG if needed
314 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
315 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
316 this._automaticTransactionGeneration
&&
317 !this._automaticTransactionGeneration
.timeToStop
) {
318 this._automaticTransactionGeneration
.stop();
320 if (this._autoReconnectTimeout
!== 0 &&
321 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
322 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
323 this._autoReconnectRetryCount
++;
325 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
327 }, this._autoReconnectTimeout
);
328 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
329 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
333 send(command
, messageType
= Constants
.OCPP_JSON_CALL_MESSAGE
) {
335 return this.sendMessage(Utils
.generateUUID(), command
, messageType
);
338 sendError(messageId
, err
) {
339 // Check exception: only OCPP error are accepted
340 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
342 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
345 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
352 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
354 logger
.error(this._basicFormatLog() + ' Send status error: ' + error
);
358 async
sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
359 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
362 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
363 // Send a message through wsConnection
366 return new Promise((resolve
, reject
) => {
369 switch (messageType
) {
371 case Constants
.OCPP_JSON_CALL_MESSAGE
:
372 this._statistics
.addMessage(commandName
);
374 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
375 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
378 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
380 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
383 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
385 this._statistics
.addMessage(`Error ${command.code}`);
386 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
389 // Check if wsConnection is ready
390 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
392 this._wsConnection
.send(messageToSend
);
394 // Buffer message until connection is back
395 this._messageQueue
.push(messageToSend
);
398 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
401 } else if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
402 // Send timeout in case connection is open otherwise wait for ever
403 // FIXME: Handle message on timeout
404 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
407 // Function that will receive the request's response
408 function responseCallback(payload
, requestPayload
) {
409 self
._statistics
.addMessage(commandName
, true);
410 const responseCallbackFn
= 'handleResponse' + commandName
;
411 if (typeof self
[responseCallbackFn
] === 'function') {
412 self
[responseCallbackFn
](payload
, requestPayload
, self
);
414 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
420 // Function that will receive the request's rejection
421 function rejectCallback(reason
) {
423 // eslint-disable-next-line no-empty-function
424 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
425 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
432 async
_basicStartMessageSequence() {
433 this._startHeartbeat(this);
435 if (!this._connectors
) {
436 this._connectors
= {};
437 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
438 // Determine number of customized connectors
440 for (lastConnector
in connectorsConfig
) {
441 // Add connector 0, OCPP specification violation that for example KEBA have
442 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
443 connectorsConfig
[lastConnector
]) {
444 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
447 let maxConnectors
= 0;
448 if (Array
.isArray(this._stationInfo
.numberOfConnectors
)) {
449 // Generate some connectors
450 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
452 maxConnectors
= this._stationInfo
.numberOfConnectors
;
454 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
455 // Generate all connectors
456 for (let index
= 1; index
<= maxConnectors
; index
++) {
457 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
458 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
462 for (const connector
in this._connectors
) {
463 if (!this._connectors
[connector
].transactionStarted
) {
464 if (this._connectors
[connector
].bootStatus
) {
465 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
467 this.sendStatusNotificationWithTimeout(connector
, 'Available');
470 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
474 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
475 if (!this._automaticTransactionGeneration
) {
476 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
478 if (this._automaticTransactionGeneration
.timeToStop
) {
479 this._automaticTransactionGeneration
.start();
482 this._statistics
.start();
485 _resetTransactionOnConnector(connectorID
) {
486 this._connectors
[connectorID
].transactionStarted
= false;
487 this._connectors
[connectorID
].transactionId
= null;
488 this._connectors
[connectorID
].lastConsumptionValue
= -1;
489 this._connectors
[connectorID
].lastSoC
= -1;
490 if (this._connectors
[connectorID
].transactionInterval
) {
491 clearInterval(this._connectors
[connectorID
].transactionInterval
);
495 handleResponseBootNotification(payload
) {
496 if (payload
.status
=== 'Accepted') {
497 this._heartbeatInterval
= payload
.interval
* 1000;
498 this._addConfigurationKey('HeartBeatInterval', this._heartbeatInterval
/ 1000);
499 this._addConfigurationKey('HeartbeatInterval', this._heartbeatInterval
/ 1000, false, false);
500 this._basicStartMessageSequence();
502 logger
.info(this._basicFormatLog() + ' Boot Notification rejected');
506 handleResponseStartTransaction(payload
, requestPayload
) {
507 // Set connector transaction related attributes
508 this._connectors
[requestPayload
.connectorId
].transactionStarted
= false;
509 this._connectors
[requestPayload
.connectorId
].idTag
= requestPayload
.idTag
;
511 if (payload
.idTagInfo
.status
=== 'Accepted') {
512 for (const connector
in this._connectors
) {
513 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
514 this._connectors
[connector
].transactionStarted
= true;
515 this._connectors
[connector
].transactionId
= payload
.transactionId
;
516 this._connectors
[connector
].lastConsumptionValue
= 0;
517 this._connectors
[connector
].lastSoC
= 0;
518 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[connector
].transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
519 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
520 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
521 this.startMeterValues(requestPayload
.connectorId
,
522 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000,
527 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
528 for (const connector
in this._connectors
) {
529 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
530 this._resetTransactionOnConnector(connector
);
533 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
537 handleResponseStopTransaction(payload
, requestPayload
) {
538 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
) {
539 logger
.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload
.transactionId
+ ' response status: ' + payload
.idTagInfo
.status
);
541 logger
.debug(this._basicFormatLog() + ' Stop transaction ' + requestPayload
.transactionId
+ ' response status: Unknown');
545 handleResponseStatusNotification(payload
, requestPayload
) {
546 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload
, requestPayload
);
549 handleResponseMeterValues(payload
, requestPayload
) {
550 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
553 handleResponseHeartbeat(payload
, requestPayload
) {
554 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
557 async
handleRequest(messageId
, commandName
, commandPayload
) {
559 this._statistics
.addMessage(commandName
, true);
561 if (typeof this['handle' + commandName
] === 'function') {
564 result
= await
this['handle' + commandName
](commandPayload
);
567 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
568 // Send back response to inform backend
569 await
this.sendError(messageId
, error
);
573 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
574 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
577 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
580 _getConfigurationKey(key
) {
581 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
584 _addConfigurationKey(key
, value
, readonly
= false, visible
= true) {
585 const keyFound
= this._getConfigurationKey(key
);
587 this._configuration
.configurationKey
.push({
596 _setConfigurationKeyValue(key
, value
) {
597 const keyFound
= this._getConfigurationKey(key
);
599 this._configuration
.configurationKey
.key
= value
;
603 async
handleGetConfiguration(commandPayload
) {
604 const configurationKey
= [];
605 const unknownKey
= [];
606 if (Utils
.isEmptyArray(commandPayload
.key
)) {
607 for (const configuration
of this._configuration
.configurationKey
) {
608 if (Utils
.isUndefined(configuration
.visible
)) {
609 configuration
.visible
= true;
611 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
613 if (!configuration
.visible
) {
616 configurationKey
.push({
617 key
: configuration
.key
,
618 readonly
: configuration
.readonly
,
619 value
: configuration
.value
,
623 for (const configuration
of commandPayload
.key
) {
624 const keyFound
= this._getConfigurationKey(configuration
);
626 if (Utils
.isUndefined(keyFound
.visible
)) {
627 keyFound
.visible
= true;
629 keyFound
.visible
= Utils
.convertToBoolean(configuration
.visible
);
631 if (!keyFound
.visible
) {
634 configurationKey
.push({
636 readonly
: keyFound
.readonly
,
637 value
: keyFound
.value
,
640 unknownKey
.push(configuration
);
650 async
handleChangeConfiguration(commandPayload
) {
651 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
652 if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
653 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
654 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
655 return Constants
.OCPP_RESPONSE_ACCEPTED
;
657 return Constants
.OCPP_RESPONSE_REJECTED
;
660 async
handleRemoteStartTransaction(commandPayload
) {
661 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
662 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
663 // Check if authorized
664 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
665 // Authorization successful start transaction
666 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
667 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
668 return Constants
.OCPP_RESPONSE_ACCEPTED
;
670 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
671 return Constants
.OCPP_RESPONSE_REJECTED
;
673 // No local authorization check required => start transaction
674 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
675 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
676 return Constants
.OCPP_RESPONSE_ACCEPTED
;
679 async
handleRemoteStopTransaction(commandPayload
) {
680 for (const connector
in this._connectors
) {
681 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
682 this.sendStopTransaction(commandPayload
.transactionId
, connector
);
685 return Constants
.OCPP_RESPONSE_ACCEPTED
;
688 async
sendStartTransaction(connectorID
, idTag
) {
691 connectorId
: connectorID
,
694 timestamp
: new Date().toISOString(),
696 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
698 logger
.error(this._basicFormatLog() + ' Send start transaction error: ' + error
);
699 this._resetTransactionOnConnector(connectorID
);
703 async
sendStartTransactionWithTimeout(connectorID
, idTag
, timeout
) {
704 setTimeout(() => this.sendStartTransaction(connectorID
, idTag
), timeout
);
707 async
sendStopTransaction(transactionId
, connectorID
) {
712 timestamp
: new Date().toISOString(),
714 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
715 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[connectorID
].transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + connectorID
);
716 this.sendStatusNotification(connectorID
, 'Available');
718 logger
.error(this._basicFormatLog() + ' Send stop transaction error: ' + error
);
721 this._resetTransactionOnConnector(connectorID
);
725 // eslint-disable-next-line class-methods-use-this
726 async
sendMeterValues(connectorID
, interval
, self
) {
728 const sampledValueLcl
= {
729 timestamp
: new Date().toISOString(),
731 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
732 if (Array
.isArray(meterValuesClone
)) {
733 sampledValueLcl
.sampledValue
= meterValuesClone
;
735 sampledValueLcl
.sampledValue
= [meterValuesClone
];
737 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
738 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
739 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
740 if (sampledValueLcl
.sampledValue
[index
].value
> 100) {
741 logger
.info(self
._basicFormatLog() + ' MeterValues measurand: ' +
742 sampledValueLcl
.sampledValue
[index
].measurand
? sampledValueLcl
.sampledValue
[index
].measurand
: 'Energy.Active.Import.Register' +
743 ', value: ' + sampledValueLcl
.sampledValue
[index
].value
);
746 // Persist previous value in connector
747 const connector
= self
._connectors
[connectorID
];
749 consumption
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
750 if (connector
&& connector
.lastConsumptionValue
>= 0) {
751 connector
.lastConsumptionValue
+= consumption
;
753 connector
.lastConsumptionValue
= 0;
755 consumption
= Math
.round(connector
.lastConsumptionValue
* 3600 / interval
);
756 logger
.info(self
._basicFormatLog() + ' MeterValues: connectorID ' + connectorID
+ ', transaction ' + connector
.transactionId
+ ', value ' + connector
.lastConsumptionValue
);
757 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastConsumptionValue
;
758 if (sampledValueLcl
.sampledValue
[index
].value
> (self
._stationInfo
.maxPower
* 3600 / interval
) || sampledValueLcl
.sampledValue
[index
].value
< 500) {
759 logger
.info(self
._basicFormatLog() + ' MeterValues measurand: ' +
760 sampledValueLcl
.sampledValue
[index
].measurand
? sampledValueLcl
.sampledValue
[index
].measurand
: 'Energy.Active.Import.Register' +
761 ', value: ' + sampledValueLcl
.sampledValue
[index
].value
+ '/' + (self
._stationInfo
.maxPower
* 3600 / interval
));
767 connectorId
: connectorID
,
768 transactionId
: self
._connectors
[connectorID
].transactionId
,
769 meterValue
: [sampledValueLcl
],
771 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
773 logger
.error(self
._basicFormatLog() + ' Send MeterValues error: ' + error
);
777 async
startMeterValues(connectorID
, interval
, self
) {
778 if (!this._connectors
[connectorID
].transactionStarted
) {
779 logger
.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
780 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
781 logger
.debug(`${self._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
783 this._connectors
[connectorID
].transactionInterval
= setInterval(async () => {
784 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
785 this._performanceObserver
.observe({
786 entryTypes
: ['function'],
788 await
sendMeterValues(connectorID
, interval
, self
);
792 hasAuthorizedTags() {
793 return !Utils
.isEmptyArray(this._authorizedTags
);
797 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
798 return this._authorizedTags
[index
];
801 _getConnector(number
) {
802 return this._stationInfo
.Connectors
[number
];
806 module
.exports
= ChargingStation
;