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._isSocketRestart
= false;
19 this._autoReconnectRetryCount
= 0;
20 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
21 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
24 this._messageQueue
= [];
26 this._authorizedTags
= this._loadAndGetAuthorizedTags();
29 _getStationName(stationTemplate
) {
30 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
34 let stationTemplateFromFile
;
37 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
38 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
39 fs
.closeSync(fileDescriptor
);
41 logger
.error(this._basicFormatLog() + ' Template file loading error: ' + error
);
43 const stationTemplate
= stationTemplateFromFile
|| {};
44 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
45 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
47 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
49 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
50 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
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._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
65 // Build connectors if needed
66 const maxConnectors
= this._getMaxConnectors();
67 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
68 const connectorsConfigLength
= Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) && Object
.keys(connectorsConfig
).includes('0') ? Object
.keys(connectorsConfig
).length
: Object
.keys(connectorsConfig
).length
- 1;
69 if (!this._connectors
|| (this._connectors
&& Object
.keys(this._connectors
).length
!== connectorsConfigLength
)) {
70 this._connectors
= {};
71 // Determine number of customized connectors
73 for (lastConnector
in connectorsConfig
) {
74 // Add connector 0, OCPP specification violation that for example KEBA have
75 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
76 connectorsConfig
[lastConnector
]) {
77 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
80 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
81 // Generate all connectors
82 for (let index
= 1; index
<= maxConnectors
; index
++) {
83 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
84 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
87 // Initialize transaction attributes on connectors
88 for (const connector
in this._connectors
) {
89 if (!this._connectors
[connector
].transactionStarted
) {
90 this._initTransactionOnConnector(connector
);
93 this._statistics
= new Statistics(this._stationInfo
.name
);
94 this._performanceObserver
= new PerformanceObserver((list
) => {
95 const entry
= list
.getEntries()[0];
96 this._statistics
.logPerformance(entry
, 'ChargingStation');
97 this._performanceObserver
.disconnect();
102 return Utils
.basicFormatLog(` ${this._stationInfo.name}:`);
105 _getConfiguration() {
106 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
109 _getAuthorizationFile() {
110 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
113 _loadAndGetAuthorizedTags() {
114 let authorizedTags
= [];
115 const authorizationFile
= this._getAuthorizationFile();
116 if (authorizationFile
) {
118 // Load authorization file
119 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
120 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
121 fs
.closeSync(fileDescriptor
);
123 logger
.error(this._basicFormatLog() + ' Authorization file loading error: ' + error
);
126 logger
.info(this._basicFormatLog() + ' No authorization file given in template file ' + this._stationTemplateFile
);
128 return authorizedTags
;
132 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
133 return this._authorizedTags
[index
];
136 hasAuthorizedTags() {
137 return !Utils
.isEmptyArray(this._authorizedTags
);
140 _getConnector(number
) {
141 return this._stationInfo
.Connectors
[number
];
144 _getMaxConnectors() {
145 let maxConnectors
= 0;
146 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
147 // Get evenly the number of connectors
148 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
150 maxConnectors
= this._stationInfo
.numberOfConnectors
;
152 return maxConnectors
;
155 _getSupervisionURL() {
156 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
158 if (!Utils
.isEmptyArray(supervisionUrls
)) {
159 if (Configuration
.getDistributeStationToTenantEqually()) {
160 indexUrl
= this._index
% supervisionUrls
.length
;
163 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
165 return supervisionUrls
[indexUrl
];
167 return supervisionUrls
;
170 _getAuthorizeRemoteTxRequests() {
171 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
172 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
175 _getLocalAuthListEnabled() {
176 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
177 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
180 async
_basicStartMessageSequence() {
182 this._startHeartbeat(this);
183 // Initialize connectors status
184 for (const connector
in this._connectors
) {
185 if (!this._connectors
[connector
].transactionStarted
) {
186 if (this._connectors
[connector
].bootStatus
) {
187 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
189 this.sendStatusNotificationWithTimeout(connector
, 'Available');
192 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
196 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
197 if (!this._automaticTransactionGeneration
) {
198 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
200 if (this._automaticTransactionGeneration
.timeToStop
) {
201 this._automaticTransactionGeneration
.start();
204 this._statistics
.start();
207 // eslint-disable-next-line class-methods-use-this
208 async
_startHeartbeat(self
) {
209 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
210 self
._heartbeatSetInterval
= setInterval(() => {
211 this.sendHeartbeat();
212 }, self
._heartbeatInterval
);
213 logger
.info(self
._basicFormatLog() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
215 logger
.error(`${self._basicFormatLog()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
219 async
_stopHeartbeat() {
220 if (this._heartbeatSetInterval
) {
221 clearInterval(this._heartbeatSetInterval
);
222 this._heartbeatSetInterval
= null;
226 _startAuthorizationFileMonitoring() {
227 // eslint-disable-next-line no-unused-vars
228 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
230 logger
.debug(this._basicFormatLog() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
231 // Initialize _authorizedTags
232 this._authorizedTags
= this._loadAndGetAuthorizedTags();
234 logger
.error(this._basicFormatLog() + ' Authorization file monitoring error: ' + error
);
239 _startStationTemplateFileMonitoring() {
240 // eslint-disable-next-line no-unused-vars
241 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
243 logger
.debug(this._basicFormatLog() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
246 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
247 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
249 logger
.error(this._basicFormatLog() + ' Charging station template file monitoring error: ' + error
);
254 async
_startMeterValues(connectorID
, interval
) {
255 if (!this._connectors
[connectorID
].transactionStarted
) {
256 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction started`);
258 } else if (this._connectors
[connectorID
].transactionStarted
&& !this._connectors
[connectorID
].transactionId
) {
259 logger
.error(`${this._basicFormatLog()} Trying to start MeterValues on connector ID ${connectorID} with no transaction id`);
263 this._connectors
[connectorID
].transactionSetInterval
= setInterval(async () => {
264 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
265 this._performanceObserver
.observe({
266 entryTypes
: ['function'],
268 await
sendMeterValues(connectorID
, interval
, this);
271 logger
.error(`${this._basicFormatLog()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
276 if (!this._wsConnectionUrl
) {
277 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
279 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
280 logger
.info(this._basicFormatLog() + ' Will communicate through URL ' + this._supervisionUrl
);
281 // Monitor authorization file
282 this._startAuthorizationFileMonitoring();
283 // Monitor station template file
284 this._startStationTemplateFileMonitoring();
285 // Handle Socket incoming messages
286 this._wsConnection
.on('message', this.onMessage
.bind(this));
287 // Handle Socket error
288 this._wsConnection
.on('error', this.onError
.bind(this));
289 // Handle Socket close
290 this._wsConnection
.on('close', this.onClose
.bind(this));
291 // Handle Socket opening connection
292 this._wsConnection
.on('open', this.onOpen
.bind(this));
293 // Handle Socket ping
294 this._wsConnection
.on('ping', this.onPing
.bind(this));
297 async
stop(reason
= '') {
299 await
this._stopHeartbeat();
301 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
302 this._automaticTransactionGeneration
&&
303 !this._automaticTransactionGeneration
.timeToStop
) {
304 await
this._automaticTransactionGeneration
.stop(reason
);
306 for (const connector
in this._connectors
) {
307 if (this._connectors
[connector
].transactionStarted
) {
308 await
this.sendStopTransaction(this._connectors
[connector
].transactionId
, reason
);
312 // eslint-disable-next-line guard-for-in
313 for (const connector
in this._connectors
) {
314 await
this.sendStatusNotification(connector
, 'Unavailable');
316 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
317 await
this._wsConnection
.close();
322 logger
.error(this._basicFormatLog() + ' Socket: abnormally closed', error
);
323 // Stop the ATG if needed
324 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
325 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
326 this._automaticTransactionGeneration
&&
327 !this._automaticTransactionGeneration
.timeToStop
) {
328 this._automaticTransactionGeneration
.stop();
331 this._stopHeartbeat();
332 if (this._autoReconnectTimeout
!== 0 &&
333 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
334 logger
.error(`${this._basicFormatLog()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
335 this._autoReconnectRetryCount
++;
337 logger
.error(this._basicFormatLog() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
339 }, this._autoReconnectTimeout
);
340 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
341 logger
.error(`${this._basicFormatLog()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
346 logger
.info(`${this._basicFormatLog()} Is connected to server through ${this._wsConnectionUrl}`);
347 if (!this._isSocketRestart
) {
348 // Send BootNotification
349 this.sendBootNotification();
351 if (this._isSocketRestart
) {
352 this._basicStartMessageSequence();
353 if (!Utils
.isEmptyArray(this._messageQueue
)) {
354 this._messageQueue
.forEach((message
) => {
355 if (this._wsConnection
&& 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);
456 currentTime
: new Date().toISOString(),
458 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
460 logger
.error(this._basicFormatLog() + ' Send Heartbeat error: ' + error
);
465 sendBootNotification() {
467 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
469 logger
.error(this._basicFormatLog() + ' Send BootNotification error: ' + error
);
474 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
481 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
483 logger
.error(this._basicFormatLog() + ' Send StatusNotification error: ' + error
);
488 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
489 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
492 async
sendStartTransaction(connectorID
, idTag
) {
495 connectorId
: connectorID
,
498 timestamp
: new Date().toISOString(),
500 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
502 logger
.error(this._basicFormatLog() + ' Send StartTransaction error: ' + error
);
507 sendStartTransactionWithTimeout(connectorID
, idTag
, timeout
) {
508 setTimeout(() => this.sendStartTransaction(connectorID
, idTag
), timeout
);
511 async
sendStopTransaction(transactionId
, reason
= '') {
518 timestamp
: new Date().toISOString(),
525 timestamp
: new Date().toISOString(),
528 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
530 logger
.error(this._basicFormatLog() + ' Send StopTransaction error: ' + error
);
535 // eslint-disable-next-line class-methods-use-this
536 async
sendMeterValues(connectorID
, interval
, self
, debug
= false) {
538 const sampledValueLcl
= {
539 timestamp
: new Date().toISOString(),
541 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorID
).MeterValues
);
542 if (!Utils
.isEmptyArray(meterValuesClone
)) {
543 sampledValueLcl
.sampledValue
= meterValuesClone
;
545 sampledValueLcl
.sampledValue
= [meterValuesClone
];
547 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
548 const connector
= self
._connectors
[connectorID
];
550 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
551 sampledValueLcl
.sampledValue
[index
].value
= sampledValueLcl
.sampledValue
[index
].value
?
552 sampledValueLcl
.sampledValue
[index
].value
:
553 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
554 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
555 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}`);
558 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage') {
559 sampledValueLcl
.sampledValue
[index
].value
= sampledValueLcl
.sampledValue
[index
].value
? sampledValueLcl
.sampledValue
[index
].value
: 230;
560 // Energy.Active.Import.Register measurand (default)
561 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
562 if (!sampledValueLcl
.sampledValue
[index
].value
) {
563 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
564 // Persist previous value in connector
565 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
566 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
568 connector
.lastEnergyActiveImportRegisterValue
= 0;
570 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
572 logger
.info(`${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}`);
573 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / interval
;
574 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
575 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}`);
577 // Unsupported measurand
579 logger
.info(`${self._basicFormatLog()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorID ${connectorID}`);
584 connectorId
: connectorID
,
585 transactionId
: self
._connectors
[connectorID
].transactionId
,
586 meterValue
: [sampledValueLcl
],
588 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
590 logger
.error(self
._basicFormatLog() + ' Send MeterValues error: ' + error
);
595 sendError(messageId
, err
) {
596 // Check exception: only OCPP error are accepted
597 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
599 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
602 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
603 // Send a message through wsConnection
606 return new Promise((resolve
, reject
) => {
609 switch (messageType
) {
611 case Constants
.OCPP_JSON_CALL_MESSAGE
:
612 this._statistics
.addMessage(commandName
);
614 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
615 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
618 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
619 this._statistics
.addMessage(commandName
);
621 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
624 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
626 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`);
627 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
630 // Check if wsConnection is ready
631 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
633 this._wsConnection
.send(messageToSend
);
635 // Buffer message until connection is back
636 this._messageQueue
.push(messageToSend
);
639 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
642 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
643 // Send timeout in case connection is open otherwise wait for ever
644 // FIXME: Handle message on timeout
645 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
648 // Function that will receive the request's response
649 function responseCallback(payload
, requestPayload
) {
650 self
._statistics
.addMessage(commandName
, true);
651 const responseCallbackFn
= 'handleResponse' + commandName
;
652 if (typeof self
[responseCallbackFn
] === 'function') {
653 self
[responseCallbackFn
](payload
, requestPayload
, self
);
655 logger
.debug(self
._basicFormatLog() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
661 // Function that will receive the request's rejection
662 function rejectCallback(reason
) {
663 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName || ''}`, true);
665 // eslint-disable-next-line no-empty-function
666 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
667 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
674 handleResponseBootNotification(payload
) {
675 if (payload
.status
=== 'Accepted') {
676 this._heartbeatInterval
= payload
.interval
* 1000;
677 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
678 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
679 this._basicStartMessageSequence();
680 } else if (payload
.status
=== 'Pending') {
681 logger
.info(this._basicFormatLog() + ' Charging station pending on the central server');
683 logger
.info(this._basicFormatLog() + ' Charging station rejected by the central server');
687 _initTransactionOnConnector(connectorID
) {
688 this._connectors
[connectorID
].transactionStarted
= false;
689 this._connectors
[connectorID
].transactionId
= null;
690 this._connectors
[connectorID
].idTag
= null;
691 this._connectors
[connectorID
].lastEnergyActiveImportRegisterValue
= -1;
694 _resetTransactionOnConnector(connectorID
) {
695 this._initTransactionOnConnector(connectorID
);
696 if (this._connectors
[connectorID
].transactionSetInterval
) {
697 clearInterval(this._connectors
[connectorID
].transactionSetInterval
);
701 handleResponseStartTransaction(payload
, requestPayload
) {
702 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
703 logger
.debug(this._basicFormatLog() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this._connectors
[requestPayload
.connectorId
]);
707 let transactionConnectorId
;
708 for (const connector
in this._connectors
) {
709 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
710 transactionConnectorId
= connector
;
714 if (!transactionConnectorId
) {
715 logger
.error(this._basicFormatLog() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
718 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
719 this._connectors
[transactionConnectorId
].transactionStarted
= true;
720 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
721 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
722 this._connectors
[transactionConnectorId
].lastEnergyActiveImportRegisterValue
= 0;
723 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
724 logger
.info(this._basicFormatLog() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
725 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
726 this._startMeterValues(requestPayload
.connectorId
,
727 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
729 logger
.error(this._basicFormatLog() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
730 this._resetTransactionOnConnector(transactionConnectorId
);
731 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
735 handleResponseStopTransaction(payload
, requestPayload
) {
736 let transactionConnectorId
;
737 for (const connector
in this._connectors
) {
738 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
739 transactionConnectorId
= connector
;
743 if (!transactionConnectorId
) {
744 logger
.error(this._basicFormatLog() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
747 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
748 this.sendStatusNotification(transactionConnectorId
, 'Available');
749 logger
.info(this._basicFormatLog() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
750 this._resetTransactionOnConnector(transactionConnectorId
);
752 logger
.error(this._basicFormatLog() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
756 handleResponseStatusNotification(payload
, requestPayload
) {
757 logger
.debug(this._basicFormatLog() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
760 handleResponseMeterValues(payload
, requestPayload
) {
761 logger
.debug(this._basicFormatLog() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
764 handleResponseHeartbeat(payload
, requestPayload
) {
765 logger
.debug(this._basicFormatLog() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
768 async
handleRequest(messageId
, commandName
, commandPayload
) {
770 this._statistics
.addMessage(commandName
, true);
772 if (typeof this['handle' + commandName
] === 'function') {
775 result
= await
this['handle' + commandName
](commandPayload
);
778 logger
.error(this._basicFormatLog() + ' Handle request error: ' + error
);
779 // Send back response to inform backend
780 await
this.sendError(messageId
, error
);
784 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
785 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
788 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
791 async
handleReset(commandPayload
) {
792 // Simulate charging station restart
793 setImmediate(async () => {
794 await
this.stop(commandPayload
.type
+ 'Reset');
795 await Utils
.sleep(this._stationInfo
.resetTime
);
798 logger
.info(`${this._basicFormatLog()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
799 return Constants
.OCPP_RESPONSE_ACCEPTED
;
802 _getConfigurationKey(key
) {
803 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
806 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
807 const keyFound
= this._getConfigurationKey(key
);
809 this._configuration
.configurationKey
.push({
819 _setConfigurationKeyValue(key
, value
) {
820 const keyFound
= this._getConfigurationKey(key
);
822 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
823 this._configuration
.configurationKey
[keyIndex
].value
= value
;
827 async
handleGetConfiguration(commandPayload
) {
828 const configurationKey
= [];
829 const unknownKey
= [];
830 if (Utils
.isEmptyArray(commandPayload
.key
)) {
831 for (const configuration
of this._configuration
.configurationKey
) {
832 if (Utils
.isUndefined(configuration
.visible
)) {
833 configuration
.visible
= true;
835 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
837 if (!configuration
.visible
) {
840 configurationKey
.push({
841 key
: configuration
.key
,
842 readonly
: configuration
.readonly
,
843 value
: configuration
.value
,
847 for (const configurationKey
of commandPayload
.key
) {
848 const keyFound
= this._getConfigurationKey(configurationKey
);
850 if (Utils
.isUndefined(keyFound
.visible
)) {
851 keyFound
.visible
= true;
853 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
855 if (!keyFound
.visible
) {
858 configurationKey
.push({
860 readonly
: keyFound
.readonly
,
861 value
: keyFound
.value
,
864 unknownKey
.push(configurationKey
);
874 async
handleChangeConfiguration(commandPayload
) {
875 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
877 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
878 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
879 return Constants
.OCPP_RESPONSE_REJECTED
;
880 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
881 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
882 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
883 let triggerHeartbeatRestart
= false;
884 if (keyToChange
.key
=== 'HeartBeatInterval') {
885 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
886 triggerHeartbeatRestart
= true;
888 if (keyToChange
.key
=== 'HeartbeatInterval') {
889 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
890 triggerHeartbeatRestart
= true;
892 if (triggerHeartbeatRestart
) {
893 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
895 this._stopHeartbeat();
897 this._startHeartbeat(this);
899 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
900 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
902 return Constants
.OCPP_RESPONSE_ACCEPTED
;
906 async
handleRemoteStartTransaction(commandPayload
) {
907 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
908 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
909 // Check if authorized
910 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
911 // Authorization successful start transaction
912 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
913 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
914 return Constants
.OCPP_RESPONSE_ACCEPTED
;
916 logger
.error(this._basicFormatLog() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
917 return Constants
.OCPP_RESPONSE_REJECTED
;
919 // No local authorization check required => start transaction
920 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
921 logger
.debug(this._basicFormatLog() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
922 return Constants
.OCPP_RESPONSE_ACCEPTED
;
925 async
handleRemoteStopTransaction(commandPayload
) {
926 for (const connector
in this._connectors
) {
927 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
928 this.sendStopTransaction(commandPayload
.transactionId
);
929 return Constants
.OCPP_RESPONSE_ACCEPTED
;
932 logger
.info(this._basicFormatLog() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
933 return Constants
.OCPP_RESPONSE_REJECTED
;
937 module
.exports
= ChargingStation
;