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();
30 _getStationName(stationTemplate
) {
31 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
35 let stationTemplateFromFile
;
38 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
39 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
40 fs
.closeSync(fileDescriptor
);
42 logger
.error(this._basicFormatLog() + ' Template file loading error: ' + error
);
44 const stationTemplate
= stationTemplateFromFile
|| {};
45 if (Array
.isArray(stationTemplateFromFile
.power
)) {
46 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
48 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
50 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
51 return stationTemplate
;
55 this._stationInfo
= this._buildStationInfo();
56 this._bootNotificationMessage
= {
57 chargePointModel
: this._stationInfo
.chargePointModel
,
58 chargePointVendor
: this._stationInfo
.chargePointVendor
,
59 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
60 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
62 this._configuration
= this._getConfiguration();
63 this._supervisionUrl
= this._getSupervisionURL();
64 this._connectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
65 this._statistics
= new Statistics(this._stationInfo
.name
);
66 this._performanceObserver
= new PerformanceObserver((list
) => {
67 const entry
= list
.getEntries()[0];
68 this._statistics
.logPerformance(entry
, 'ChargingStation');
69 this._performanceObserver
.disconnect();
74 return Utils
.basicFormatLog(` ${this._stationInfo.name}:`);
78 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
81 _getAuthorizationFile() {
82 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
85 _loadAndGetAuthorizedTags() {
86 let authorizedTags
= [];
87 const authorizationFile
= this._getAuthorizationFile();
88 if (authorizationFile
) {
90 // Load authorization file
91 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
92 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
93 fs
.closeSync(fileDescriptor
);
95 logger
.error(this._basicFormatLog() + ' Authorization file loading error: ' + error
);
98 logger
.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile
);
100 return authorizedTags
;
104 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
105 return this._authorizedTags
[index
];
108 hasAuthorizedTags() {
109 return !Utils
.isEmptyArray(this._authorizedTags
);
112 _getConnector(number
) {
113 return this._stationInfo
.Connectors
[number
];
116 _getMaxConnectors() {
117 let maxConnectors
= 0;
118 if (Array
.isArray(this._stationInfo
.numberOfConnectors
)) {
119 // Generate some connectors
120 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
122 maxConnectors
= this._stationInfo
.numberOfConnectors
;
124 return maxConnectors
;
127 _getSupervisionURL() {
128 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
130 if (Array
.isArray(supervisionUrls
)) {
131 if (Configuration
.getDistributeStationToTenantEqually()) {
132 indexUrl
= this._index
% supervisionUrls
.length
;
135 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
137 return supervisionUrls
[indexUrl
];
139 return supervisionUrls
;
142 _getAuthorizeRemoteTxRequests() {
143 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
144 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
147 _getLocalAuthListEnabled() {
148 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
149 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
152 async
_basicStartMessageSequence() {
154 this._startHeartbeat(this);
156 if (!this._connectors
) {
157 this._connectors
= {};
158 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
159 // Determine number of customized connectors
161 for (lastConnector
in connectorsConfig
) {
162 // Add connector 0, OCPP specification violation that for example KEBA have
163 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
164 connectorsConfig
[lastConnector
]) {
165 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
168 const maxConnectors
= this._getMaxConnectors();
169 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
170 // Generate all connectors
171 for (let index
= 1; index
<= maxConnectors
; index
++) {
172 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
173 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
177 for (const connector
in this._connectors
) {
178 if (!this._connectors
[connector
].transactionStarted
) {
179 if (this._connectors
[connector
].bootStatus
) {
180 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
182 this.sendStatusNotificationWithTimeout(connector
, 'Available');
185 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
189 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
190 if (!this._automaticTransactionGeneration
) {
191 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
193 if (this._automaticTransactionGeneration
.timeToStop
) {
194 this._automaticTransactionGeneration
.start();
197 this._statistics
.start();
200 // eslint-disable-next-line class-methods-use-this
201 async
_startHeartbeat(self
) {
202 if (self
._heartbeatInterval
&& !self
._heartbeatSetInterval
) {
203 self
._heartbeatSetInterval
= setInterval(() => {
206 currentTime
: new Date().toISOString(),
208 self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
210 logger
.error(self
._basicFormatLog() + ' Send heartbeat error: ' + error
);
212 }, self
._heartbeatInterval
);
213 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
215 logger
.error(self
._basicFormatLog() + ' Heartbeat interval undefined, not starting the heartbeat');
219 _startAuthorizationFileMonitoring() {
220 // eslint-disable-next-line no-unused-vars
221 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
223 logger
.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
224 // Initialize _authorizedTags
225 this._authorizedTags
= this._loadAndGetAuthorizedTags();
227 logger
.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error
);
232 _startStationTemplateFileMonitoring() {
233 // eslint-disable-next-line no-unused-vars
234 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
236 logger
.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
239 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
240 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
241 this._addConfigurationKey('NumberOfConnectors', this._getMaxConnectors(), true);
243 logger
.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error
);
248 async
_startMeterValues(connectorID
, interval
) {
249 if (!this._connectors
[connectorID
].transactionStarted
) {
250 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
252 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
253 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
256 this._connectors
[connectorID
].transactionSetInterval
= setInterval(async () => {
257 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
258 this._performanceObserver
.observe({
259 entryTypes
: ['function'],
261 await
sendMeterValues(connectorID
, interval
, this);
266 if (!this._connectionUrl
) {
267 this._connectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
269 this._wsConnection
= new WebSocket(this._connectionUrl
, 'ocpp1.6');
270 logger
.info(this._basicFormatLog() + ' Will communicate with ' + this._supervisionUrl
);
271 // Monitor authorization file
272 this._startAuthorizationFileMonitoring();
273 // Monitor station template file
274 this._startStationTemplateFileMonitoring();
275 // Handle Socket incoming messages
276 this._wsConnection
.on('message', this.onMessage
.bind(this));
277 // Handle Socket error
278 this._wsConnection
.on('error', this.onError
.bind(this));
279 // Handle Socket close
280 this._wsConnection
.on('close', this.onClose
.bind(this));
281 // Handle Socket opening connection
282 this._wsConnection
.on('open', this.onOpen
.bind(this));
283 // Handle Socket ping
284 this._wsConnection
.on('ping', this.onPing
.bind(this));
287 async
stop(type
= '') {
289 if (this._heartbeatSetInterval
) {
290 await
clearInterval(this._heartbeatSetInterval
);
291 this._heartbeatSetInterval
= null;
294 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
295 this._automaticTransactionGeneration
&&
296 !this._automaticTransactionGeneration
.timeToStop
) {
297 await
this._automaticTransactionGeneration
.stop();
299 for (const connector
in this._connectors
) {
300 if (this._connectors
[connector
].transactionStarted
) {
301 await
this.sendStopTransaction(this._connectors
[connector
].transactionId
, type
? type
+ 'Reset' : '');
305 // eslint-disable-next-line guard-for-in
306 for (const connector
in this._connectors
) {
307 await
this.sendStatusNotification(connector
, 'Unavailable');
309 if (this._wsConnection
) {
310 await
this._wsConnection
.close();
315 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
316 // Stop the ATG if needed
317 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
318 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
319 this._automaticTransactionGeneration
&&
320 !this._automaticTransactionGeneration
.timeToStop
) {
321 this._automaticTransactionGeneration
.stop();
324 if (this._heartbeatSetInterval
) {
325 clearInterval(this._heartbeatSetInterval
);
326 this._heartbeatSetInterval
= null;
328 if (this._autoReconnectTimeout
!== 0 &&
329 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
330 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
331 this._autoReconnectRetryCount
++;
333 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
335 }, this._autoReconnectTimeout
);
336 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
337 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
342 logger
.info(`${this._basicFormatLog()} Is connected to server through ${this._connectionUrl}`);
343 if (!this._isSocketRestart
) {
344 // Send BootNotification
346 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
348 logger
.error(this._basicFormatLog() + ' Send boot notification error: ' + error
);
351 if (this._isSocketRestart
) {
352 this._basicStartMessageSequence();
353 if (this._messageQueue
.length
> 0) {
354 this._messageQueue
.forEach((message
) => {
355 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
356 this._wsConnection
.send(message
);
361 this._autoReconnectRetryCount
= 0;
362 this._isSocketRestart
= false;
368 this._isSocketRestart
= true;
369 this._reconnect(error
);
372 logger
.error(this._basicFormatLog() + ' Socket error: ' + error
);
379 case 1000: // Normal close
381 logger
.info(this._basicFormatLog() + ' Socket normally closed ' + error
);
382 this._autoReconnectRetryCount
= 0;
384 default: // Abnormal close
385 this._isSocketRestart
= true;
386 this._reconnect(error
);
392 logger
.debug(this._basicFormatLog() + ' Has received a WS ping (rfc6455) from the server');
395 async
onMessage(message
) {
396 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
399 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
401 // Check the Type of message
402 switch (messageType
) {
404 case Constants
.OCPP_JSON_CALL_MESSAGE
:
406 await
this.handleRequest(messageId
, commandName
, commandPayload
);
409 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
411 // eslint-disable-next-line no-case-declarations
412 let responseCallback
; let requestPayload
;
413 if (Utils
.isIterable(this._requests
[messageId
])) {
414 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
416 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
418 if (!responseCallback
) {
420 throw new Error(`Response for unknown message id ${messageId}`);
422 delete this._requests
[messageId
];
423 responseCallback(commandName
, requestPayload
);
426 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
427 if (!this._requests
[messageId
]) {
429 throw new Error(`Error for unknown message id ${messageId}`);
431 // eslint-disable-next-line no-case-declarations
433 if (Utils
.isIterable(this._requests
[messageId
])) {
434 [, rejectCallback
] = this._requests
[messageId
];
436 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
438 delete this._requests
[messageId
];
439 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
443 throw new Error(`Wrong message type ${messageType}`);
447 logger
.error('%s Incoming message %j processing error %s on request content %s', this._basicFormatLog(), message
, error
, this._requests
[messageId
]);
449 // await this.sendError(messageId, error);
453 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
460 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
462 logger
.error(this._basicFormatLog() + ' Send status error: ' + error
);
467 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
468 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
471 async
sendStartTransaction(connectorID
, idTag
) {
474 connectorId
: connectorID
,
477 timestamp
: new Date().toISOString(),
479 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
481 logger
.error(this._basicFormatLog() + ' Send start transaction error: ' + error
);
486 sendStartTransactionWithTimeout(connectorID
, idTag
, timeout
) {
487 setTimeout(() => this.sendStartTransaction(connectorID
, idTag
), timeout
);
490 async
sendStopTransaction(transactionId
, reason
= '') {
495 timestamp
: new Date().toISOString(),
498 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
500 logger
.error(this._basicFormatLog() + ' Send stop transaction error: ' + error
);
505 // eslint-disable-next-line class-methods-use-this
506 async
sendMeterValues(connectorID
, interval
, self
, debug
= false) {
508 const sampledValueLcl
= {
509 timestamp
: new Date().toISOString(),
511 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
512 if (Array
.isArray(meterValuesClone
)) {
513 sampledValueLcl
.sampledValue
= meterValuesClone
;
515 sampledValueLcl
.sampledValue
= [meterValuesClone
];
517 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
518 const connector
= self
._connectors
[connectorID
];
519 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
520 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
521 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
522 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}`);
525 // Persist previous value in connector
526 const consumption
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
527 if (connector
&& connector
.lastConsumptionValue
>= 0) {
528 connector
.lastConsumptionValue
+= consumption
;
530 connector
.lastConsumptionValue
= 0;
532 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / interval
;
533 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}`);
534 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastConsumptionValue
;
535 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
536 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}`);
542 connectorId
: connectorID
,
543 transactionId
: self
._connectors
[connectorID
].transactionId
,
544 meterValue
: [sampledValueLcl
],
546 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
548 logger
.error(self
._basicFormatLog() + ' Send MeterValues error: ' + error
);
552 sendError(messageId
, err
) {
553 // Check exception: only OCPP error are accepted
554 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
556 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
559 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
560 // Send a message through wsConnection
563 return new Promise((resolve
, reject
) => {
566 switch (messageType
) {
568 case Constants
.OCPP_JSON_CALL_MESSAGE
:
569 this._statistics
.addMessage(commandName
);
571 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
572 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
575 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
576 this._statistics
.addMessage(commandName
);
578 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
581 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
583 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
584 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
587 // Check if wsConnection is ready
588 if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
590 this._wsConnection
.send(messageToSend
);
592 // Buffer message until connection is back
593 this._messageQueue
.push(messageToSend
);
596 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
599 } else if (this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
600 // Send timeout in case connection is open otherwise wait for ever
601 // FIXME: Handle message on timeout
602 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
605 // Function that will receive the request's response
606 function responseCallback(payload
, requestPayload
) {
607 self
._statistics
.addMessage(commandName
, true);
608 const responseCallbackFn
= 'handleResponse' + commandName
;
609 if (typeof self
[responseCallbackFn
] === 'function') {
610 self
[responseCallbackFn
](payload
, requestPayload
, self
);
612 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
618 // Function that will receive the request's rejection
619 function rejectCallback(reason
) {
620 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
622 // eslint-disable-next-line no-empty-function
623 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
624 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
631 handleResponseBootNotification(payload
) {
632 if (payload
.status
=== 'Accepted') {
633 this._heartbeatInterval
= payload
.interval
* 1000;
634 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
635 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
636 this._basicStartMessageSequence();
638 logger
.info(this._basicFormatLog() + ' Boot Notification rejected');
642 _resetTransactionOnConnector(connectorID
) {
643 this._connectors
[connectorID
].transactionStarted
= false;
644 this._connectors
[connectorID
].transactionId
= null;
645 this._connectors
[connectorID
].idTag
= null;
646 this._connectors
[connectorID
].lastConsumptionValue
= -1;
647 this._connectors
[connectorID
].lastSoC
= -1;
648 if (this._connectors
[connectorID
].transactionSetInterval
) {
649 clearInterval(this._connectors
[connectorID
].transactionSetInterval
);
653 handleResponseStartTransaction(payload
, requestPayload
) {
654 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
655 logger
.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ' by transaction ' + this._connectors
[requestPayload
.connectorId
].transactionId
);
658 let transactionConnectorId
;
659 for (const connector
in this._connectors
) {
660 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
661 transactionConnectorId
= connector
;
665 if (!transactionConnectorId
) {
666 logger
.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
669 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
670 this._connectors
[transactionConnectorId
].transactionStarted
= true;
671 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
672 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
673 this._connectors
[transactionConnectorId
].lastConsumptionValue
= 0;
674 this._connectors
[transactionConnectorId
].lastSoC
= 0;
675 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
676 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[transactionConnectorId
].transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
677 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
678 this._startMeterValues(requestPayload
.connectorId
,
679 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
681 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
682 this._resetTransactionOnConnector(transactionConnectorId
);
683 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
687 handleResponseStopTransaction(payload
, requestPayload
) {
688 let transactionConnectorId
;
689 for (const connector
in this._connectors
) {
690 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
691 transactionConnectorId
= connector
;
695 if (!transactionConnectorId
) {
696 logger
.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
699 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
700 this.sendStatusNotification(transactionConnectorId
, 'Available');
701 logger
.info(this._basicFormatLog() + ' Transaction ' + this._connectors
[transactionConnectorId
].transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
702 this._resetTransactionOnConnector(transactionConnectorId
);
704 logger
.error(this._basicFormatLog() + ' Stopping transaction id ' + this._connectors
[transactionConnectorId
].transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
708 handleResponseStatusNotification(payload
, requestPayload
) {
709 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j to status notification request: %j', payload
, requestPayload
);
712 handleResponseMeterValues(payload
, requestPayload
) {
713 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
716 handleResponseHeartbeat(payload
, requestPayload
) {
717 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
720 async
handleRequest(messageId
, commandName
, commandPayload
) {
722 this._statistics
.addMessage(commandName
, true);
724 if (typeof this['handle' + commandName
] === 'function') {
727 result
= await
this['handle' + commandName
](commandPayload
);
730 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
731 // Send back response to inform backend
732 await
this.sendError(messageId
, error
);
736 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
737 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
740 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
743 async
handleReset(commandPayload
) {
744 logger
.info(`${this._basicFormatLog()} ${commandPayload.type} reset command received, simulating it`);
745 // Simulate charging station restart
746 setImmediate(async () => {
747 await
this.stop(commandPayload
.type
);
748 await Utils
.sleep(60000);
751 return Constants
.OCPP_RESPONSE_ACCEPTED
;
754 _getConfigurationKey(key
) {
755 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
758 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
759 const keyFound
= this._getConfigurationKey(key
);
761 this._configuration
.configurationKey
.push({
771 _setConfigurationKeyValue(key
, value
) {
772 const keyFound
= this._getConfigurationKey(key
);
774 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
775 this._configuration
.configurationKey
[keyIndex
].value
= value
;
779 async
handleGetConfiguration(commandPayload
) {
780 const configurationKey
= [];
781 const unknownKey
= [];
782 if (Utils
.isEmptyArray(commandPayload
.key
)) {
783 for (const configuration
of this._configuration
.configurationKey
) {
784 if (Utils
.isUndefined(configuration
.visible
)) {
785 configuration
.visible
= true;
787 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
789 if (!configuration
.visible
) {
792 configurationKey
.push({
793 key
: configuration
.key
,
794 readonly
: configuration
.readonly
,
795 value
: configuration
.value
,
799 for (const configurationKey
of commandPayload
.key
) {
800 const keyFound
= this._getConfigurationKey(configurationKey
);
802 if (Utils
.isUndefined(keyFound
.visible
)) {
803 keyFound
.visible
= true;
805 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
807 if (!keyFound
.visible
) {
810 configurationKey
.push({
812 readonly
: keyFound
.readonly
,
813 value
: keyFound
.value
,
816 unknownKey
.push(configurationKey
);
826 async
handleChangeConfiguration(commandPayload
) {
827 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
829 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
830 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
831 return Constants
.OCPP_RESPONSE_REJECTED
;
832 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
833 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
834 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
835 let triggerHeartbeatRestart
= false;
836 if (keyToChange
.key
=== 'HeartBeatInterval') {
837 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
838 triggerHeartbeatRestart
= true;
840 if (keyToChange
.key
=== 'HeartbeatInterval') {
841 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
842 triggerHeartbeatRestart
= true;
844 if (triggerHeartbeatRestart
) {
845 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
847 if (this._heartbeatSetInterval
) {
848 clearInterval(this._heartbeatSetInterval
);
849 this._heartbeatSetInterval
= null;
852 this._startHeartbeat(this);
854 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
855 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
857 return Constants
.OCPP_RESPONSE_ACCEPTED
;
861 async
handleRemoteStartTransaction(commandPayload
) {
862 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
863 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
864 // Check if authorized
865 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
866 // Authorization successful start transaction
867 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
868 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
869 return Constants
.OCPP_RESPONSE_ACCEPTED
;
871 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
872 return Constants
.OCPP_RESPONSE_REJECTED
;
874 // No local authorization check required => start transaction
875 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
876 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
877 return Constants
.OCPP_RESPONSE_ACCEPTED
;
880 async
handleRemoteStopTransaction(commandPayload
) {
881 for (const connector
in this._connectors
) {
882 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
883 this.sendStopTransaction(commandPayload
.transactionId
);
884 return Constants
.OCPP_RESPONSE_ACCEPTED
;
887 logger
.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
888 return Constants
.OCPP_RESPONSE_REJECTED
;
892 module
.exports
= ChargingStation
;