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
;
17 this._connectors
= {};
20 this._isSocketRestart
= false;
21 this._autoReconnectRetryCount
= 0;
22 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
23 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
26 this._messageQueue
= [];
28 this._authorizedTags
= this._loadAndGetAuthorizedTags();
31 _getStationName(stationTemplate
) {
32 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
36 let stationTemplateFromFile
;
39 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
40 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
41 fs
.closeSync(fileDescriptor
);
43 logger
.error(this._logPrefix() + ' Template file loading error: ' + error
);
45 const stationTemplate
= stationTemplateFromFile
|| {};
46 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
47 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
49 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
51 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
52 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
53 return stationTemplate
;
57 this._stationInfo
= this._buildStationInfo();
58 this._bootNotificationMessage
= {
59 chargePointModel
: this._stationInfo
.chargePointModel
,
60 chargePointVendor
: this._stationInfo
.chargePointVendor
,
61 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
62 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
64 this._configuration
= this._getConfiguration();
65 this._supervisionUrl
= this._getSupervisionURL();
66 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
67 // Build connectors if needed
68 const maxConnectors
= this._getMaxConnectors();
69 const connectorsConfig
= Utils
.cloneJSonDocument(this._stationInfo
.Connectors
);
70 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(connectorsConfig
) + maxConnectors
.toString()).digest('hex');
71 // FIXME: Handle shrinking the number of connectors
72 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
73 this._connectorsConfigurationHash
= connectorsConfigHash
;
74 // Determine number of customized connectors
76 for (lastConnector
in connectorsConfig
) {
77 // Add connector 0, OCPP specification violation that for example KEBA have
78 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) &&
79 connectorsConfig
[lastConnector
]) {
80 this._connectors
[lastConnector
] = connectorsConfig
[lastConnector
];
83 this._addConfigurationKey('NumberOfConnectors', maxConnectors
, true);
84 // Generate all connectors
85 for (let index
= 1; index
<= maxConnectors
; index
++) {
86 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
87 this._connectors
[index
] = connectorsConfig
[randConnectorID
];
90 // Initialize transaction attributes on connectors
91 for (const connector
in this._connectors
) {
92 if (!this._connectors
[connector
].transactionStarted
) {
93 this._initTransactionOnConnector(connector
);
96 // FIXME: Conditionally initialize or use singleton design pattern per charging station
97 this._statistics
= new Statistics(this._stationInfo
.name
);
98 this._performanceObserver
= new PerformanceObserver((list
) => {
99 const entry
= list
.getEntries()[0];
100 this._statistics
.logPerformance(entry
, 'ChargingStation');
101 this._performanceObserver
.disconnect();
106 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
109 _getConfiguration() {
110 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
113 _getAuthorizationFile() {
114 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
117 _loadAndGetAuthorizedTags() {
118 let authorizedTags
= [];
119 const authorizationFile
= this._getAuthorizationFile();
120 if (authorizationFile
) {
122 // Load authorization file
123 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
124 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
125 fs
.closeSync(fileDescriptor
);
127 logger
.error(this._logPrefix() + ' Authorization file loading error: ' + error
);
130 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
132 return authorizedTags
;
136 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
137 return this._authorizedTags
[index
];
140 hasAuthorizedTags() {
141 return !Utils
.isEmptyArray(this._authorizedTags
);
144 _getConnector(number
) {
145 return this._stationInfo
.Connectors
[number
];
148 _getMaxConnectors() {
149 let maxConnectors
= 0;
150 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
151 // Get evenly the number of connectors
152 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
154 maxConnectors
= this._stationInfo
.numberOfConnectors
;
156 return maxConnectors
;
159 _getSupervisionURL() {
160 const supervisionUrls
= Utils
.cloneJSonDocument(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
162 if (!Utils
.isEmptyArray(supervisionUrls
)) {
163 if (Configuration
.getDistributeStationToTenantEqually()) {
164 indexUrl
= this._index
% supervisionUrls
.length
;
167 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
169 return supervisionUrls
[indexUrl
];
171 return supervisionUrls
;
174 _getAuthorizeRemoteTxRequests() {
175 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
176 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
179 _getLocalAuthListEnabled() {
180 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
181 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
184 async
_basicStartMessageSequence() {
186 this._startHeartbeat(this);
187 // Initialize connectors status
188 for (const connector
in this._connectors
) {
189 if (!this._connectors
[connector
].transactionStarted
) {
190 if (this._connectors
[connector
].bootStatus
) {
191 this.sendStatusNotificationWithTimeout(connector
, this._connectors
[connector
].bootStatus
);
193 this.sendStatusNotificationWithTimeout(connector
, 'Available');
196 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
200 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
201 if (!this._automaticTransactionGeneration
) {
202 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
204 if (this._automaticTransactionGeneration
.timeToStop
) {
205 this._automaticTransactionGeneration
.start();
208 this._statistics
.start();
211 // eslint-disable-next-line class-methods-use-this
212 async
_startHeartbeat(self
) {
213 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
214 self
._heartbeatSetInterval
= setInterval(() => {
215 this.sendHeartbeat();
216 }, self
._heartbeatInterval
);
217 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
219 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
223 async
_stopHeartbeat() {
224 if (this._heartbeatSetInterval
) {
225 clearInterval(this._heartbeatSetInterval
);
226 this._heartbeatSetInterval
= null;
230 _startAuthorizationFileMonitoring() {
231 // eslint-disable-next-line no-unused-vars
232 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
234 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
235 // Initialize _authorizedTags
236 this._authorizedTags
= this._loadAndGetAuthorizedTags();
238 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
243 _startStationTemplateFileMonitoring() {
244 // eslint-disable-next-line no-unused-vars
245 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
247 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
250 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
251 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
253 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
258 async
_startMeterValues(connectorId
, interval
) {
259 if (!this._connectors
[connectorId
].transactionStarted
) {
260 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector ID ${connectorId} with no transaction started`);
262 } else if (this._connectors
[connectorId
].transactionStarted
&& !this._connectors
[connectorId
].transactionId
) {
263 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector ID ${connectorId} with no transaction id`);
267 this._connectors
[connectorId
].transactionSetInterval
= setInterval(async () => {
268 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
269 this._performanceObserver
.observe({
270 entryTypes
: ['function'],
272 await
sendMeterValues(connectorId
, interval
, this);
275 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
280 if (!this._wsConnectionUrl
) {
281 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
283 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
284 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
285 // Monitor authorization file
286 this._startAuthorizationFileMonitoring();
287 // Monitor station template file
288 this._startStationTemplateFileMonitoring();
289 // Handle Socket incoming messages
290 this._wsConnection
.on('message', this.onMessage
.bind(this));
291 // Handle Socket error
292 this._wsConnection
.on('error', this.onError
.bind(this));
293 // Handle Socket close
294 this._wsConnection
.on('close', this.onClose
.bind(this));
295 // Handle Socket opening connection
296 this._wsConnection
.on('open', this.onOpen
.bind(this));
297 // Handle Socket ping
298 this._wsConnection
.on('ping', this.onPing
.bind(this));
301 async
stop(reason
= '') {
303 await
this._stopHeartbeat();
305 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
306 this._automaticTransactionGeneration
&&
307 !this._automaticTransactionGeneration
.timeToStop
) {
308 await
this._automaticTransactionGeneration
.stop(reason
);
310 for (const connector
in this._connectors
) {
311 if (this._connectors
[connector
].transactionStarted
) {
312 await
this.sendStopTransaction(this._connectors
[connector
].transactionId
, reason
);
316 // eslint-disable-next-line guard-for-in
317 for (const connector
in this._connectors
) {
318 await
this.sendStatusNotification(connector
, 'Unavailable');
320 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
321 await
this._wsConnection
.close();
326 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
327 // Stop the ATG if needed
328 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
329 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
330 this._automaticTransactionGeneration
&&
331 !this._automaticTransactionGeneration
.timeToStop
) {
332 this._automaticTransactionGeneration
.stop();
335 this._stopHeartbeat();
336 if (this._autoReconnectTimeout
!== 0 &&
337 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
338 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
339 this._autoReconnectRetryCount
++;
341 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
343 }, this._autoReconnectTimeout
);
344 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
345 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
350 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
351 if (!this._isSocketRestart
) {
352 // Send BootNotification
353 this.sendBootNotification();
355 if (this._isSocketRestart
) {
356 this._basicStartMessageSequence();
357 if (!Utils
.isEmptyArray(this._messageQueue
)) {
358 this._messageQueue
.forEach((message
) => {
359 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
360 this._wsConnection
.send(message
);
365 this._autoReconnectRetryCount
= 0;
366 this._isSocketRestart
= false;
372 this._isSocketRestart
= true;
373 this._reconnect(error
);
376 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
383 case 1000: // Normal close
385 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
386 this._autoReconnectRetryCount
= 0;
388 default: // Abnormal close
389 this._isSocketRestart
= true;
390 this._reconnect(error
);
396 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
399 async
onMessage(message
) {
400 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
403 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
405 // Check the Type of message
406 switch (messageType
) {
408 case Constants
.OCPP_JSON_CALL_MESSAGE
:
410 await
this.handleRequest(messageId
, commandName
, commandPayload
);
413 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
415 // eslint-disable-next-line no-case-declarations
416 let responseCallback
; let requestPayload
;
417 if (Utils
.isIterable(this._requests
[messageId
])) {
418 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
420 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
422 if (!responseCallback
) {
424 throw new Error(`Response for unknown message id ${messageId}`);
426 delete this._requests
[messageId
];
427 responseCallback(commandName
, requestPayload
);
430 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
431 if (!this._requests
[messageId
]) {
433 throw new Error(`Error for unknown message id ${messageId}`);
435 // eslint-disable-next-line no-case-declarations
437 if (Utils
.isIterable(this._requests
[messageId
])) {
438 [, rejectCallback
] = this._requests
[messageId
];
440 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
442 delete this._requests
[messageId
];
443 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
447 throw new Error(`Wrong message type ${messageType}`);
451 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
453 // await this.sendError(messageId, error);
460 currentTime
: new Date().toISOString(),
462 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
464 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
469 sendBootNotification() {
471 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
473 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
478 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
485 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
487 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
492 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
493 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
496 async
sendStartTransaction(connectorId
, idTag
) {
502 timestamp
: new Date().toISOString(),
504 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
506 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
511 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
512 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
515 async
sendStopTransaction(transactionId
, reason
= '') {
522 timestamp
: new Date().toISOString(),
529 timestamp
: new Date().toISOString(),
532 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
534 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
539 // eslint-disable-next-line class-methods-use-this
540 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
542 const sampledValueLcl
= {
543 timestamp
: new Date().toISOString(),
545 const meterValuesClone
= Utils
.cloneJSonDocument(self
._getConnector(connectorId
).MeterValues
);
546 if (!Utils
.isEmptyArray(meterValuesClone
)) {
547 sampledValueLcl
.sampledValue
= meterValuesClone
;
549 sampledValueLcl
.sampledValue
= [meterValuesClone
];
551 for (let index
= 0; index
< sampledValueLcl
.sampledValue
.length
; index
++) {
552 const connector
= self
._connectors
[connectorId
];
554 if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'SoC') {
555 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ?
556 sampledValueLcl
.sampledValue
[index
].value
:
557 sampledValueLcl
.sampledValue
[index
].value
= Utils
.getRandomInt(100);
558 if (sampledValueLcl
.sampledValue
[index
].value
> 100 || debug
) {
559 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}`);
562 } else if (sampledValueLcl
.sampledValue
[index
].measurand
&& sampledValueLcl
.sampledValue
[index
].measurand
=== 'Voltage') {
563 sampledValueLcl
.sampledValue
[index
].value
= !Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
) ? sampledValueLcl
.sampledValue
[index
].value
: 230;
564 // Energy.Active.Import.Register measurand (default)
565 } else if (!sampledValueLcl
.sampledValue
[index
].measurand
|| sampledValueLcl
.sampledValue
[index
].measurand
=== 'Energy.Active.Import.Register') {
566 if (Utils
.isUndefined(sampledValueLcl
.sampledValue
[index
].value
)) {
567 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ 3600000 * interval
);
568 // Persist previous value in connector
569 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
570 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
572 connector
.lastEnergyActiveImportRegisterValue
= 0;
574 sampledValueLcl
.sampledValue
[index
].value
= connector
.lastEnergyActiveImportRegisterValue
;
576 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}`);
577 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / interval
;
578 if (sampledValueLcl
.sampledValue
[index
].value
> maxConsumption
|| debug
) {
579 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}`);
581 // Unsupported measurand
583 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${sampledValueLcl.sampledValue[index].measurand ? sampledValueLcl.sampledValue[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
589 transactionId
: self
._connectors
[connectorId
].transactionId
,
590 meterValue
: [sampledValueLcl
],
592 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
594 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
599 sendError(messageId
, err
) {
600 // Check exception: only OCPP error are accepted
601 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
603 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
606 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
607 // Send a message through wsConnection
610 return new Promise((resolve
, reject
) => {
613 switch (messageType
) {
615 case Constants
.OCPP_JSON_CALL_MESSAGE
:
616 this._statistics
.addMessage(commandName
);
618 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
619 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
622 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
623 this._statistics
.addMessage(commandName
);
625 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
628 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
630 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
631 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
634 // Check if wsConnection is ready
635 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
637 this._wsConnection
.send(messageToSend
);
639 // Buffer message until connection is back
640 this._messageQueue
.push(messageToSend
);
643 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
646 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
647 // Send timeout in case connection is open otherwise wait for ever
648 // FIXME: Handle message on timeout
649 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
652 // Function that will receive the request's response
653 function responseCallback(payload
, requestPayload
) {
654 self
._statistics
.addMessage(commandName
, true);
655 const responseCallbackFn
= 'handleResponse' + commandName
;
656 if (typeof self
[responseCallbackFn
] === 'function') {
657 self
[responseCallbackFn
](payload
, requestPayload
, self
);
659 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
665 // Function that will receive the request's rejection
666 function rejectCallback(reason
) {
667 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
669 // eslint-disable-next-line no-empty-function
670 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
671 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
678 handleResponseBootNotification(payload
) {
679 if (payload
.status
=== 'Accepted') {
680 this._heartbeatInterval
= payload
.interval
* 1000;
681 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
682 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
683 this._basicStartMessageSequence();
684 } else if (payload
.status
=== 'Pending') {
685 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
687 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
691 _initTransactionOnConnector(connectorId
) {
692 this._connectors
[connectorId
].transactionStarted
= false;
693 this._connectors
[connectorId
].transactionId
= null;
694 this._connectors
[connectorId
].idTag
= null;
695 this._connectors
[connectorId
].lastEnergyActiveImportRegisterValue
= -1;
698 _resetTransactionOnConnector(connectorId
) {
699 this._initTransactionOnConnector(connectorId
);
700 if (this._connectors
[connectorId
].transactionSetInterval
) {
701 clearInterval(this._connectors
[connectorId
].transactionSetInterval
);
705 handleResponseStartTransaction(payload
, requestPayload
) {
706 if (this._connectors
[requestPayload
.connectorId
].transactionStarted
) {
707 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this._connectors
[requestPayload
.connectorId
]);
711 let transactionConnectorId
;
712 for (const connector
in this._connectors
) {
713 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
714 transactionConnectorId
= connector
;
718 if (!transactionConnectorId
) {
719 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
722 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
723 this._connectors
[transactionConnectorId
].transactionStarted
= true;
724 this._connectors
[transactionConnectorId
].transactionId
= payload
.transactionId
;
725 this._connectors
[transactionConnectorId
].idTag
= requestPayload
.idTag
;
726 this._connectors
[transactionConnectorId
].lastEnergyActiveImportRegisterValue
= 0;
727 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
728 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
729 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
730 this._startMeterValues(requestPayload
.connectorId
,
731 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
733 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
734 this._resetTransactionOnConnector(transactionConnectorId
);
735 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
739 handleResponseStopTransaction(payload
, requestPayload
) {
740 let transactionConnectorId
;
741 for (const connector
in this._connectors
) {
742 if (this._connectors
[connector
].transactionId
=== requestPayload
.transactionId
) {
743 transactionConnectorId
= connector
;
747 if (!transactionConnectorId
) {
748 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
751 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
752 this.sendStatusNotification(transactionConnectorId
, 'Available');
753 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
754 this._resetTransactionOnConnector(transactionConnectorId
);
756 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
760 handleResponseStatusNotification(payload
, requestPayload
) {
761 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
764 handleResponseMeterValues(payload
, requestPayload
) {
765 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
768 handleResponseHeartbeat(payload
, requestPayload
) {
769 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
772 async
handleRequest(messageId
, commandName
, commandPayload
) {
774 this._statistics
.addMessage(commandName
, true);
776 if (typeof this['handle' + commandName
] === 'function') {
779 result
= await
this['handle' + commandName
](commandPayload
);
782 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
783 // Send back response to inform backend
784 await
this.sendError(messageId
, error
);
788 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
789 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
792 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
795 async
handleReset(commandPayload
) {
796 // Simulate charging station restart
797 setImmediate(async () => {
798 await
this.stop(commandPayload
.type
+ 'Reset');
799 await Utils
.sleep(this._stationInfo
.resetTime
);
802 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
803 return Constants
.OCPP_RESPONSE_ACCEPTED
;
806 _getConfigurationKey(key
) {
807 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
810 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
811 const keyFound
= this._getConfigurationKey(key
);
813 this._configuration
.configurationKey
.push({
823 _setConfigurationKeyValue(key
, value
) {
824 const keyFound
= this._getConfigurationKey(key
);
826 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
827 this._configuration
.configurationKey
[keyIndex
].value
= value
;
831 async
handleGetConfiguration(commandPayload
) {
832 const configurationKey
= [];
833 const unknownKey
= [];
834 if (Utils
.isEmptyArray(commandPayload
.key
)) {
835 for (const configuration
of this._configuration
.configurationKey
) {
836 if (Utils
.isUndefined(configuration
.visible
)) {
837 configuration
.visible
= true;
839 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
841 if (!configuration
.visible
) {
844 configurationKey
.push({
845 key
: configuration
.key
,
846 readonly
: configuration
.readonly
,
847 value
: configuration
.value
,
851 for (const configurationKey
of commandPayload
.key
) {
852 const keyFound
= this._getConfigurationKey(configurationKey
);
854 if (Utils
.isUndefined(keyFound
.visible
)) {
855 keyFound
.visible
= true;
857 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
859 if (!keyFound
.visible
) {
862 configurationKey
.push({
864 readonly
: keyFound
.readonly
,
865 value
: keyFound
.value
,
868 unknownKey
.push(configurationKey
);
878 async
handleChangeConfiguration(commandPayload
) {
879 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
881 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
882 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
883 return Constants
.OCPP_RESPONSE_REJECTED
;
884 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
885 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
886 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
887 let triggerHeartbeatRestart
= false;
888 if (keyToChange
.key
=== 'HeartBeatInterval') {
889 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
890 triggerHeartbeatRestart
= true;
892 if (keyToChange
.key
=== 'HeartbeatInterval') {
893 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
894 triggerHeartbeatRestart
= true;
896 if (triggerHeartbeatRestart
) {
897 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
899 this._stopHeartbeat();
901 this._startHeartbeat(this);
903 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
904 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
906 return Constants
.OCPP_RESPONSE_ACCEPTED
;
910 async
handleRemoteStartTransaction(commandPayload
) {
911 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
912 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
913 // Check if authorized
914 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
915 // Authorization successful start transaction
916 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
917 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
918 return Constants
.OCPP_RESPONSE_ACCEPTED
;
920 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
921 return Constants
.OCPP_RESPONSE_REJECTED
;
923 // No local authorization check required => start transaction
924 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
925 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
926 return Constants
.OCPP_RESPONSE_ACCEPTED
;
929 async
handleRemoteStopTransaction(commandPayload
) {
930 for (const connector
in this._connectors
) {
931 if (this._connectors
[connector
].transactionId
=== commandPayload
.transactionId
) {
932 this.sendStopTransaction(commandPayload
.transactionId
);
933 return Constants
.OCPP_RESPONSE_ACCEPTED
;
936 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
937 return Constants
.OCPP_RESPONSE_REJECTED
;
941 module
.exports
= ChargingStation
;