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 crypto
= require('crypto');
11 const {performance
, PerformanceObserver
} = require('perf_hooks');
13 class ChargingStation
{
14 constructor(index
, stationTemplateFile
) {
16 this._stationTemplateFile
= stationTemplateFile
;
19 this._isSocketRestart
= false;
20 this._autoReconnectRetryCount
= 0;
21 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
22 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
25 this._messageQueue
= [];
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._logPrefix() + ' Template file loading error: ' + error
);
44 const stationTemplate
= stationTemplateFromFile
|| {};
45 if (!Utils
.isEmptyArray(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 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
52 return stationTemplate
;
56 this._stationInfo
= this._buildStationInfo();
57 this._bootNotificationMessage
= {
58 chargePointModel
: this._stationInfo
.chargePointModel
,
59 chargePointVendor
: this._stationInfo
.chargePointVendor
,
60 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
61 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
63 this._configuration
= this._getConfiguration();
64 this._supervisionUrl
= this._getSupervisionURL();
65 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
66 // Build connectors if needed
67 const maxConnectors
= this._getMaxConnectors();
68 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
69 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(connectorsConfig
) + maxConnectors
.toString()).digest('hex');
70 // FIXME: Handle shrinking the number of connectors
71 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
72 this._connectorsConfigurationHash
= connectorsConfigHash
;
73 if (!this._connectors
) {
74 this._connectors
= {};
76 // Determine number of customized connectors
78 for (lastConnector
in connectorsConfig
) {
79 // Add connector 0, OCPP specification violation that for example KEBA have
80 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
81 connectorsConfig
[lastConnector
]) {
82 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
85 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
86 // Generate all connectors
87 for (let index
= 1; index
<= maxConnectors
; index
++) {
88 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
89 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
92 // Initialize transaction attributes on connectors
93 for (const connector
in this._connectors
) {
94 if (!this._connectors
[connector
].transactionStarted
) {
95 this._initTransactionOnConnector(connector
);
98 // FIXME: Conditionally initialize or use singleton design pattern per charging station
99 this._statistics
= new Statistics(this._stationInfo
.name
);
100 this._performanceObserver
= new PerformanceObserver((list
) => {
101 const entry
= list
.getEntries()[0];
102 this._statistics
.logPerformance(entry
, 'ChargingStation');
103 this._performanceObserver
.disconnect();
108 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
111 _getConfiguration() {
112 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
115 _getAuthorizationFile() {
116 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
119 _loadAndGetAuthorizedTags() {
120 let authorizedTags
= [];
121 const authorizationFile
= this._getAuthorizationFile();
122 if (authorizationFile
) {
124 // Load authorization file
125 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
126 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
127 fs
.closeSync(fileDescriptor
);
129 logger
.error(this._logPrefix() + ' Authorization file loading error: ' + error
);
132 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
134 return authorizedTags
;
138 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
139 return this._authorizedTags
[index
];
142 hasAuthorizedTags() {
143 return !Utils
.isEmptyArray(this._authorizedTags
);
146 _getConnector(number
) {
147 return this._stationInfo
.Connectors
[number
];
150 _getMaxConnectors() {
151 let maxConnectors
= 0;
152 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
153 // Get evenly the number of connectors
154 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
156 maxConnectors
= this._stationInfo
.numberOfConnectors
;
158 return maxConnectors
;
161 _getSupervisionURL() {
162 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
164 if (!Utils
.isEmptyArray(supervisionUrls
)) {
165 if (Configuration
.getDistributeStationToTenantEqually()) {
166 indexUrl
= this._index
% supervisionUrls
.length
;
169 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
171 return supervisionUrls
[indexUrl
];
173 return supervisionUrls
;
176 _getAuthorizeRemoteTxRequests() {
177 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
178 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
181 _getLocalAuthListEnabled() {
182 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
183 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
186 async
_basicStartMessageSequence() {
188 this._startHeartbeat(this);
189 // Initialize connectors status
190 for (const connector
in this._connectors
) {
191 if (!this._connectors
[connector
].transactionStarted
) {
192 if (this._connectors
[connector
].bootStatus
) {
193 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
195 this.sendStatusNotificationWithTimeout(connector
, 'Available');
198 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
202 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
203 if (!this._automaticTransactionGeneration
) {
204 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
206 if (this._automaticTransactionGeneration
.timeToStop
) {
207 this._automaticTransactionGeneration
.start();
210 this._statistics
.start();
213 // eslint-disable-next-line class-methods-use-this
214 async
_startHeartbeat(self
) {
215 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
216 self
._heartbeatSetInterval
= setInterval(() => {
217 this.sendHeartbeat();
218 }, self
._heartbeatInterval
);
219 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
221 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
225 async
_stopHeartbeat() {
226 if (this._heartbeatSetInterval
) {
227 clearInterval(this._heartbeatSetInterval
);
228 this._heartbeatSetInterval
= null;
232 _startAuthorizationFileMonitoring() {
233 // eslint-disable-next-line no-unused-vars
234 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
236 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
237 // Initialize _authorizedTags
238 this._authorizedTags
= this._loadAndGetAuthorizedTags();
240 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
245 _startStationTemplateFileMonitoring() {
246 // eslint-disable-next-line no-unused-vars
247 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
249 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
252 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
253 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
255 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
260 async
_startMeterValues(connectorId
, interval
) {
261 if (!this._connectors
[connectorId
].transactionStarted
) {
262 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector ID ${connectorId} with no transaction started`);
264 } else if (this._connectors
[connectorId
].transactionStarted
&& !this._connectors
[connectorId
].transactionId
) {
265 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector ID ${connectorId} with no transaction id`);
269 this._connectors
[connectorId
].transactionSetInterval
= setInterval(async () => {
270 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
271 this._performanceObserver
.observe({
272 entryTypes
: ['function'],
274 await
sendMeterValues(connectorId
, interval
, this);
277 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
282 if (!this._wsConnectionUrl
) {
283 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
285 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
286 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
287 // Monitor authorization file
288 this._startAuthorizationFileMonitoring();
289 // Monitor station template file
290 this._startStationTemplateFileMonitoring();
291 // Handle Socket incoming messages
292 this._wsConnection
.on('message', this.onMessage
.bind(this));
293 // Handle Socket error
294 this._wsConnection
.on('error', this.onError
.bind(this));
295 // Handle Socket close
296 this._wsConnection
.on('close', this.onClose
.bind(this));
297 // Handle Socket opening connection
298 this._wsConnection
.on('open', this.onOpen
.bind(this));
299 // Handle Socket ping
300 this._wsConnection
.on('ping', this.onPing
.bind(this));
303 async
stop(reason
= '') {
305 await
this._stopHeartbeat();
307 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
308 this._automaticTransactionGeneration
&&
309 !this._automaticTransactionGeneration
.timeToStop
) {
310 await
this._automaticTransactionGeneration
.stop(reason
);
312 for (const connector
in this._connectors
) {
313 if (this._connectors
[connector
].transactionStarted
) {
314 await
this.sendStopTransaction(this._connectors
[connector
].transactionId
, reason
);
318 // eslint-disable-next-line guard-for-in
319 for (const connector
in this._connectors
) {
320 await
this.sendStatusNotification(connector
, 'Unavailable');
322 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
323 await
this._wsConnection
.close();
328 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
329 // Stop the ATG if needed
330 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
331 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
332 this._automaticTransactionGeneration
&&
333 !this._automaticTransactionGeneration
.timeToStop
) {
334 this._automaticTransactionGeneration
.stop();
337 this._stopHeartbeat();
338 if (this._autoReconnectTimeout
!== 0 &&
339 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
340 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
341 this._autoReconnectRetryCount
++;
343 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
345 }, this._autoReconnectTimeout
);
346 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
347 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
352 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
353 if (!this._isSocketRestart
) {
354 // Send BootNotification
355 this.sendBootNotification();
357 if (this._isSocketRestart
) {
358 this._basicStartMessageSequence();
359 if (!Utils
.isEmptyArray(this._messageQueue
)) {
360 this._messageQueue
.forEach((message
) => {
361 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
362 this._wsConnection
.send(message
);
367 this._autoReconnectRetryCount
= 0;
368 this._isSocketRestart
= false;
374 this._isSocketRestart
= true;
375 this._reconnect(error
);
378 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
385 case 1000: // Normal close
387 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
388 this._autoReconnectRetryCount
= 0;
390 default: // Abnormal close
391 this._isSocketRestart
= true;
392 this._reconnect(error
);
398 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
401 async
onMessage(message
) {
402 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
405 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
407 // Check the Type of message
408 switch (messageType
) {
410 case Constants
.OCPP_JSON_CALL_MESSAGE
:
412 await
this.handleRequest(messageId
, commandName
, commandPayload
);
415 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
417 // eslint-disable-next-line no-case-declarations
418 let responseCallback
; let requestPayload
;
419 if (Utils
.isIterable(this._requests
[messageId
])) {
420 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
422 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
424 if (!responseCallback
) {
426 throw new Error(`Response for unknown message id ${messageId}`);
428 delete this._requests
[messageId
];
429 responseCallback(commandName
, requestPayload
);
432 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
433 if (!this._requests
[messageId
]) {
435 throw new Error(`Error for unknown message id ${messageId}`);
437 // eslint-disable-next-line no-case-declarations
439 if (Utils
.isIterable(this._requests
[messageId
])) {
440 [, rejectCallback
] = this._requests
[messageId
];
442 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
444 delete this._requests
[messageId
];
445 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
449 throw new Error(`Wrong message type ${messageType}`);
453 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
455 // await this.sendError(messageId, error);
462 currentTime
: new Date().toISOString(),
464 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
466 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
471 sendBootNotification() {
473 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
475 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
480 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
487 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
489 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
494 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
495 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
498 async
sendStartTransaction(connectorId
, idTag
) {
504 timestamp
: new Date().toISOString(),
506 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
508 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
513 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
514 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
517 async
sendStopTransaction(transactionId
, reason
= '') {
524 timestamp
: new Date().toISOString(),
531 timestamp
: new Date().toISOString(),
534 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
536 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
541 // eslint-disable-next-line class-methods-use-this
542 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
544 const sampledValueLcl
= {
545 timestamp
: new Date().toISOString(),
547 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorId
).MeterValues
);
548 if (!Utils
.isEmptyArray(meterValuesClone
)) {
549 sampledValueLcl
.sampledValue
= meterValuesClone
;
551 sampledValueLcl
.sampledValue
= [meterValuesClone
];
553 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
554 const connector
= self
._connectors
[connectorId
];
556 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
557 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
558 sampledValueLcl
.sampledValue
[index
].value
:
559 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
560 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
561 logger
.error(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValueLcl.sampledValue[index].value}`);
564 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage') {
565 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
566 // Energy.Active.Import.Register measurand (default)
567 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
568 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
569 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
570 // Persist previous value in connector
571 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
572 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
574 connector
.lastEnergyActiveImportRegisterValue
= 0;
576 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
578 logger
.info(`${self._logPrefix()} MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value ${sampledValueLcl.sampledValue[index].value}`);
579 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / interval
;
580 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
581 logger
.error(`${self._logPrefix()} 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}`);
583 // Unsupported measurand
585 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
591 transactionId
: self
._connectors
[connectorId
].transactionId
,
592 meterValue
: [sampledValueLcl
],
594 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
596 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
601 sendError(messageId
, err
) {
602 // Check exception: only OCPP error are accepted
603 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
605 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
608 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
609 // Send a message through wsConnection
612 return new Promise((resolve
, reject
) => {
615 switch (messageType
) {
617 case Constants
.OCPP_JSON_CALL_MESSAGE
:
618 this._statistics
.addMessage(commandName
);
620 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
621 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
624 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
625 this._statistics
.addMessage(commandName
);
627 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
630 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
632 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
633 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
636 // Check if wsConnection is ready
637 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
639 this._wsConnection
.send(messageToSend
);
641 // Buffer message until connection is back
642 this._messageQueue
.push(messageToSend
);
645 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
648 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
649 // Send timeout in case connection is open otherwise wait for ever
650 // FIXME: Handle message on timeout
651 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
654 // Function that will receive the request's response
655 function responseCallback(payload
, requestPayload
) {
656 self
._statistics
.addMessage(commandName
, true);
657 const responseCallbackFn
= 'handleResponse' + commandName
;
658 if (typeof self
[responseCallbackFn
] === 'function') {
659 self
[responseCallbackFn
](payload
, requestPayload
, self
);
661 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
667 // Function that will receive the request's rejection
668 function rejectCallback(reason
) {
669 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
671 // eslint-disable-next-line no-empty-function
672 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
673 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
680 handleResponseBootNotification(payload
) {
681 if (payload
.status
=== 'Accepted') {
682 this._heartbeatInterval
= payload
.interval
* 1000;
683 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
684 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
685 this._basicStartMessageSequence();
686 } else if (payload
.status
=== 'Pending') {
687 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
689 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
693 _initTransactionOnConnector(connectorId
) {
694 this._connectors
[connectorId
].transactionStarted
= false;
695 this._connectors
[connectorId
].transactionId
= null;
696 this._connectors
[connectorId
].idTag
= null;
697 this._connectors
[connectorId
].lastEnergyActiveImportRegisterValue
= -1;
700 _resetTransactionOnConnector(connectorId
) {
701 this._initTransactionOnConnector(connectorId
);
702 if (this._connectors
[connectorId
].transactionSetInterval
) {
703 clearInterval(this._connectors
[connectorId
].transactionSetInterval
);
707 handleResponseStartTransaction(payload
, requestPayload
) {
708 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
709 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this._connectors
[requestPayload
.connectorId
]);
713 let transactionConnectorId
;
714 for (const connector
in this._connectors
) {
715 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
716 transactionConnectorId
= connector
;
720 if (!transactionConnectorId
) {
721 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
724 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
725 this._connectors
[transactionConnectorId
].transactionStarted
= true;
726 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
727 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
728 this._connectors
[transactionConnectorId
].lastEnergyActiveImportRegisterValue
= 0;
729 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
730 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
731 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
732 this._startMeterValues(requestPayload
.connectorId
,
733 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
735 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
736 this._resetTransactionOnConnector(transactionConnectorId
);
737 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
741 handleResponseStopTransaction(payload
, requestPayload
) {
742 let transactionConnectorId
;
743 for (const connector
in this._connectors
) {
744 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
745 transactionConnectorId
= connector
;
749 if (!transactionConnectorId
) {
750 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
753 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
754 this.sendStatusNotification(transactionConnectorId
, 'Available');
755 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
756 this._resetTransactionOnConnector(transactionConnectorId
);
758 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
762 handleResponseStatusNotification(payload
, requestPayload
) {
763 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
766 handleResponseMeterValues(payload
, requestPayload
) {
767 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
770 handleResponseHeartbeat(payload
, requestPayload
) {
771 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
774 async
handleRequest(messageId
, commandName
, commandPayload
) {
776 this._statistics
.addMessage(commandName
, true);
778 if (typeof this['handle' + commandName
] === 'function') {
781 result
= await
this['handle' + commandName
](commandPayload
);
784 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
785 // Send back response to inform backend
786 await
this.sendError(messageId
, error
);
790 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
791 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
794 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
797 async
handleReset(commandPayload
) {
798 // Simulate charging station restart
799 setImmediate(async () => {
800 await
this.stop(commandPayload
.type
+ 'Reset');
801 await Utils
.sleep(this._stationInfo
.resetTime
);
804 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
805 return Constants
.OCPP_RESPONSE_ACCEPTED
;
808 _getConfigurationKey(key
) {
809 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
812 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
813 const keyFound
= this._getConfigurationKey(key
);
815 this._configuration
.configurationKey
.push({
825 _setConfigurationKeyValue(key
, value
) {
826 const keyFound
= this._getConfigurationKey(key
);
828 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
829 this._configuration
.configurationKey
[keyIndex
].value
= value
;
833 async
handleGetConfiguration(commandPayload
) {
834 const configurationKey
= [];
835 const unknownKey
= [];
836 if (Utils
.isEmptyArray(commandPayload
.key
)) {
837 for (const configuration
of this._configuration
.configurationKey
) {
838 if (Utils
.isUndefined(configuration
.visible
)) {
839 configuration
.visible
= true;
841 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
843 if (!configuration
.visible
) {
846 configurationKey
.push({
847 key
: configuration
.key
,
848 readonly
: configuration
.readonly
,
849 value
: configuration
.value
,
853 for (const configurationKey
of commandPayload
.key
) {
854 const keyFound
= this._getConfigurationKey(configurationKey
);
856 if (Utils
.isUndefined(keyFound
.visible
)) {
857 keyFound
.visible
= true;
859 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
861 if (!keyFound
.visible
) {
864 configurationKey
.push({
866 readonly
: keyFound
.readonly
,
867 value
: keyFound
.value
,
870 unknownKey
.push(configurationKey
);
880 async
handleChangeConfiguration(commandPayload
) {
881 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
883 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
884 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
885 return Constants
.OCPP_RESPONSE_REJECTED
;
886 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
887 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
888 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
889 let triggerHeartbeatRestart
= false;
890 if (keyToChange
.key
=== 'HeartBeatInterval') {
891 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
892 triggerHeartbeatRestart
= true;
894 if (keyToChange
.key
=== 'HeartbeatInterval') {
895 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
896 triggerHeartbeatRestart
= true;
898 if (triggerHeartbeatRestart
) {
899 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
901 this._stopHeartbeat();
903 this._startHeartbeat(this);
905 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
906 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
908 return Constants
.OCPP_RESPONSE_ACCEPTED
;
912 async
handleRemoteStartTransaction(commandPayload
) {
913 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
914 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
915 // Check if authorized
916 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
917 // Authorization successful start transaction
918 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
919 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
920 return Constants
.OCPP_RESPONSE_ACCEPTED
;
922 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
923 return Constants
.OCPP_RESPONSE_REJECTED
;
925 // No local authorization check required => start transaction
926 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
927 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
928 return Constants
.OCPP_RESPONSE_ACCEPTED
;
931 async
handleRemoteStopTransaction(commandPayload
) {
932 for (const connector
in this._connectors
) {
933 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
934 this.sendStopTransaction(commandPayload
.transactionId
);
935 return Constants
.OCPP_RESPONSE_ACCEPTED
;
938 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
939 return Constants
.OCPP_RESPONSE_REJECTED
;
943 module
.exports
= ChargingStation
;