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('Template file ' + this._stationTemplateFile
+ ' loading error: ' + error
);
46 const stationTemplate
= stationTemplateFromFile
|| {};
47 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
48 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
50 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
52 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
53 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
54 return stationTemplate
;
58 this._stationInfo
= this._buildStationInfo();
59 this._bootNotificationMessage
= {
60 chargePointModel
: this._stationInfo
.chargePointModel
,
61 chargePointVendor
: this._stationInfo
.chargePointVendor
,
62 chargePointSerialNumber
: this._stationInfo
.chargePointSerialNumberPrefix
? this._stationInfo
.chargePointSerialNumberPrefix
: '',
63 firmwareVersion
: this._stationInfo
.firmwareVersion
? this._stationInfo
.firmwareVersion
: '',
65 this._configuration
= this._getConfiguration();
66 this._supervisionUrl
= this._getSupervisionURL();
67 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
68 // Build connectors if needed
69 const maxConnectors
= this._getMaxNumberOfConnectors();
70 if (maxConnectors
<= 0) {
71 const errMsg
= `${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`;
74 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
75 if (templateMaxConnectors
<= 0) {
76 const errMsg
= `${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`;
80 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !Utils
.convertToBoolean(this._stationInfo
.randomConnectors
)) {
81 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
82 this._stationInfo
.randomConnectors
= true;
84 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
85 // FIXME: Handle shrinking the number of connectors
86 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
87 this._connectorsConfigurationHash
= connectorsConfigHash
;
89 let lastConnector
= 0;
90 for (lastConnector
in this._stationInfo
.Connectors
) {
91 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) && this._stationInfo
.Connectors
[lastConnector
]) {
92 this._connectors
[lastConnector
] = Utils
.cloneObject(this._stationInfo
.Connectors
[lastConnector
]);
95 // Generate all connectors
96 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
97 for (let index
= 1; index
<= maxConnectors
; index
++) {
98 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(lastConnector
, 1) : index
;
99 this._connectors
[index
] = Utils
.cloneObject(this._stationInfo
.Connectors
[randConnectorID
]);
103 // Avoid duplication of connectors related information
104 delete this._stationInfo
.Connectors
;
105 // Initialize transaction attributes on connectors
106 for (const connector
in this._connectors
) {
107 if (!this.getConnector(connector
).transactionStarted
) {
108 this._initTransactionOnConnector(connector
);
112 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors(), true);
113 if (!this._getConfigurationKey('MeterValuesSampledData')) {
114 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
116 this._stationInfo
.powerDivider
= this._getPowerDivider();
117 if (this.getEnableStatistics()) {
118 this._statistics
= Statistics
.getInstance();
119 this._statistics
.objName
= this._stationInfo
.name
;
120 this._performanceObserver
= new PerformanceObserver((list
) => {
121 const entry
= list
.getEntries()[0];
122 this._statistics
.logPerformance(entry
, 'ChargingStation');
123 this._performanceObserver
.disconnect();
129 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
132 _getConfiguration() {
133 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
136 _getAuthorizationFile() {
137 return this._stationInfo
.authorizationFile
? this._stationInfo
.authorizationFile
: '';
140 _loadAndGetAuthorizedTags() {
141 let authorizedTags
= [];
142 const authorizationFile
= this._getAuthorizationFile();
143 if (authorizationFile
) {
145 // Load authorization file
146 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
147 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
148 fs
.closeSync(fileDescriptor
);
150 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: ' + error
);
154 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
156 return authorizedTags
;
160 const index
= Math
.floor(Math
.random() * this._authorizedTags
.length
);
161 return this._authorizedTags
[index
];
164 hasAuthorizedTags() {
165 return !Utils
.isEmptyArray(this._authorizedTags
);
168 getEnableStatistics() {
169 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? Utils
.convertToBoolean(this._stationInfo
.enableStatistics
) : true;
172 _getNumberOfPhases() {
173 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? Utils
.convertToInt(this._stationInfo
.numberOfPhases
) : 3;
176 _getNumberOfRunningTransactions() {
178 for (const connector
in this._connectors
) {
179 if (this.getConnector(connector
).transactionStarted
) {
187 let powerDivider
= this._getNumberOfConnectors();
188 if (this._stationInfo
.powerSharedByConnectors
) {
189 powerDivider
= this._getNumberOfRunningTransactions();
195 return this._connectors
[Utils
.convertToInt(id
)];
198 _getTemplateMaxNumberOfConnectors() {
199 return Object
.keys(this._stationInfo
.Connectors
).length
;
202 _getMaxNumberOfConnectors() {
203 let maxConnectors
= 0;
204 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
205 // Distribute evenly the number of connectors
206 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
207 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
208 maxConnectors
= this._stationInfo
.numberOfConnectors
;
210 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
212 return maxConnectors
;
215 _getNumberOfConnectors() {
216 return this._connectors
[0] ? Object
.keys(this._connectors
).length
- 1 : Object
.keys(this._connectors
).length
;
219 _getSupervisionURL() {
220 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
222 if (!Utils
.isEmptyArray(supervisionUrls
)) {
223 if (Configuration
.getDistributeStationToTenantEqually()) {
224 indexUrl
= this._index
% supervisionUrls
.length
;
227 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
229 return supervisionUrls
[indexUrl
];
231 return supervisionUrls
;
234 _getAuthorizeRemoteTxRequests() {
235 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
236 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
239 _getLocalAuthListEnabled() {
240 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
241 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
244 async
_basicStartMessageSequence() {
246 this._startHeartbeat(this);
247 // Initialize connectors status
248 for (const connector
in this._connectors
) {
249 if (!this.getConnector(connector
).transactionStarted
) {
250 if (this.getConnector(connector
).bootStatus
) {
251 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(connector
).bootStatus
);
253 this.sendStatusNotificationWithTimeout(connector
, 'Available');
256 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
260 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
261 if (!this._automaticTransactionGeneration
) {
262 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
264 if (this._automaticTransactionGeneration
.timeToStop
) {
265 this._automaticTransactionGeneration
.start();
268 if (this.getEnableStatistics()) {
269 this._statistics
.start();
273 // eslint-disable-next-line class-methods-use-this
274 async
_startHeartbeat(self
) {
275 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
276 self
._heartbeatSetInterval
= setInterval(() => {
277 this.sendHeartbeat();
278 }, self
._heartbeatInterval
);
279 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
281 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}, not starting the heartbeat`);
285 async
_stopHeartbeat() {
286 if (this._heartbeatSetInterval
) {
287 clearInterval(this._heartbeatSetInterval
);
288 this._heartbeatSetInterval
= null;
292 _startAuthorizationFileMonitoring() {
293 // eslint-disable-next-line no-unused-vars
294 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
296 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
297 // Initialize _authorizedTags
298 this._authorizedTags
= this._loadAndGetAuthorizedTags();
300 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
305 _startStationTemplateFileMonitoring() {
306 // eslint-disable-next-line no-unused-vars
307 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
309 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
312 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
313 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
315 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
320 async
_startMeterValues(connectorId
, interval
) {
321 if (!this.getConnector(connectorId
).transactionStarted
) {
322 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
324 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
325 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
329 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
330 if (this.getEnableStatistics()) {
331 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
332 this._performanceObserver
.observe({
333 entryTypes
: ['function'],
335 await
sendMeterValues(connectorId
, interval
, this);
337 await
this.sendMeterValues(connectorId
, interval
, this);
341 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
346 if (!this._wsConnectionUrl
) {
347 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
349 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
350 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
351 // Monitor authorization file
352 this._startAuthorizationFileMonitoring();
353 // Monitor station template file
354 this._startStationTemplateFileMonitoring();
355 // Handle Socket incoming messages
356 this._wsConnection
.on('message', this.onMessage
.bind(this));
357 // Handle Socket error
358 this._wsConnection
.on('error', this.onError
.bind(this));
359 // Handle Socket close
360 this._wsConnection
.on('close', this.onClose
.bind(this));
361 // Handle Socket opening connection
362 this._wsConnection
.on('open', this.onOpen
.bind(this));
363 // Handle Socket ping
364 this._wsConnection
.on('ping', this.onPing
.bind(this));
367 async
stop(reason
= '') {
369 await
this._stopHeartbeat();
371 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
372 this._automaticTransactionGeneration
&&
373 !this._automaticTransactionGeneration
.timeToStop
) {
374 await
this._automaticTransactionGeneration
.stop(reason
);
376 for (const connector
in this._connectors
) {
377 if (this.getConnector(connector
).transactionStarted
) {
378 await
this.sendStopTransaction(this.getConnector(connector
).transactionId
, reason
);
382 // eslint-disable-next-line guard-for-in
383 for (const connector
in this._connectors
) {
384 await
this.sendStatusNotification(connector
, 'Unavailable');
386 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
387 await
this._wsConnection
.close();
392 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
393 // Stop the ATG if needed
394 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
395 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
396 this._automaticTransactionGeneration
&&
397 !this._automaticTransactionGeneration
.timeToStop
) {
398 this._automaticTransactionGeneration
.stop();
401 this._stopHeartbeat();
402 if (this._autoReconnectTimeout
!== 0 &&
403 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
404 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
405 this._autoReconnectRetryCount
++;
407 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
409 }, this._autoReconnectTimeout
);
410 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
411 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
416 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
417 if (!this._isSocketRestart
) {
418 // Send BootNotification
419 this.sendBootNotification();
421 if (this._isSocketRestart
) {
422 this._basicStartMessageSequence();
423 if (!Utils
.isEmptyArray(this._messageQueue
)) {
424 this._messageQueue
.forEach((message
) => {
425 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
426 this._wsConnection
.send(message
);
431 this._autoReconnectRetryCount
= 0;
432 this._isSocketRestart
= false;
438 this._isSocketRestart
= true;
439 this._reconnect(error
);
442 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
449 case 1000: // Normal close
451 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
452 this._autoReconnectRetryCount
= 0;
454 default: // Abnormal close
455 this._isSocketRestart
= true;
456 this._reconnect(error
);
462 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
465 async
onMessage(message
) {
466 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
469 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
471 // Check the Type of message
472 switch (messageType
) {
474 case Constants
.OCPP_JSON_CALL_MESSAGE
:
476 await
this.handleRequest(messageId
, commandName
, commandPayload
);
479 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
481 // eslint-disable-next-line no-case-declarations
482 let responseCallback
; let requestPayload
;
483 if (Utils
.isIterable(this._requests
[messageId
])) {
484 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
486 throw new Error(`Response request for unknown message id ${messageId} is not iterable`);
488 if (!responseCallback
) {
490 throw new Error(`Response for unknown message id ${messageId}`);
492 delete this._requests
[messageId
];
493 responseCallback(commandName
, requestPayload
);
496 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
497 if (!this._requests
[messageId
]) {
499 throw new Error(`Error for unknown message id ${messageId}`);
501 // eslint-disable-next-line no-case-declarations
503 if (Utils
.isIterable(this._requests
[messageId
])) {
504 [, rejectCallback
] = this._requests
[messageId
];
506 throw new Error(`Error request for unknown message id ${messageId} is not iterable`);
508 delete this._requests
[messageId
];
509 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
513 throw new Error(`Wrong message type ${messageType}`);
517 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
519 // await this.sendError(messageId, error);
526 currentTime
: new Date().toISOString(),
528 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
530 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
535 sendBootNotification() {
537 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
539 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
544 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
551 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
553 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
558 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
559 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
562 async
sendStartTransaction(connectorId
, idTag
) {
568 timestamp
: new Date().toISOString(),
570 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
572 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
577 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
) {
578 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
581 async
sendStopTransaction(transactionId
, reason
= '') {
588 timestamp
: new Date().toISOString(),
595 timestamp
: new Date().toISOString(),
598 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
600 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
605 // eslint-disable-next-line class-methods-use-this
606 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
608 const sampledValues
= {
609 timestamp
: new Date().toISOString(),
612 const meterValuesTemplate
= self
.getConnector(connectorId
).MeterValues
;
613 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
614 const connector
= self
.getConnector(connectorId
);
616 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
617 sampledValues
.sampledValue
.push({
618 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'Percent'},
619 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
620 measurand
: meterValuesTemplate
[index
].measurand
,
621 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? {location
: meterValuesTemplate
[index
].location
} : {location
: 'EV'},
622 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: Utils
.getRandomInt(100)},
624 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
625 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> 100 || debug
) {
626 logger
.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}`);
629 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
630 sampledValues
.sampledValue
.push({
631 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'V'},
632 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
633 measurand
: meterValuesTemplate
[index
].measurand
,
634 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
635 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: 230},
637 for (let phase
= 1; self
._getNumberOfPhases() === 3 && phase
<= self
._getNumberOfPhases(); phase
++) {
638 const voltageValue
= sampledValues
.sampledValue
[sampledValues
.sampledValue
.length
- 1].value
;
640 if (voltageValue
>= 0 && voltageValue
<= 240) {
641 phaseValue
= `L${phase}-N`;
642 } else if (voltageValue
> 240) {
643 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases() }`;
645 sampledValues
.sampledValue
.push({
646 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'V'},
647 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
648 measurand
: meterValuesTemplate
[index
].measurand
,
649 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
650 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: 230},
654 // Energy.Active.Import.Register measurand (default)
655 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== 'Energy.Active.Import.Register') {
656 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
657 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
658 logger
.error(errMsg
);
660 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
661 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
662 logger
.error(errMsg
);
665 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
666 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
667 // Persist previous value in connector
668 if (connector
&& connector
.lastEnergyActiveImportRegisterValue
>= 0) {
669 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
671 connector
.lastEnergyActiveImportRegisterValue
= 0;
674 sampledValues
.sampledValue
.push({
675 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'Wh'},
676 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
677 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && {measurand
: meterValuesTemplate
[index
].measurand
},
678 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
679 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: connector
.lastEnergyActiveImportRegisterValue
},
681 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
682 // const measurandValuePerPhase = Utils.roundTo(sampledValues.sampledValue[sampledValuesIndex].value / self._getNumberOfPhases(), 2);
683 // for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
684 // const phaseValue = `L${phase}-N`;
685 // sampledValues.sampledValue.push({
686 // ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? {unit: meterValuesTemplate[index].unit} : {unit: 'Wh'},
687 // ...!Utils.isUndefined(meterValuesTemplate[index].context) && {context: meterValuesTemplate[index].context},
688 // ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && {measurand: meterValuesTemplate[index].measurand},
689 // ...!Utils.isUndefined(meterValuesTemplate[index].location) && {location: meterValuesTemplate[index].location},
690 // value: measurandValuePerPhase,
691 // phase: phaseValue,
694 logger
.info(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value ${sampledValues.sampledValue[sampledValuesIndex].value}`);
695 const maxConsumption
= self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
);
696 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxConsumption
|| debug
) {
697 logger
.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : 'Energy.Active.Import.Register'}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxConsumption}`);
699 // Unsupported measurand
701 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
707 transactionId
: self
.getConnector(connectorId
).transactionId
,
708 meterValue
: sampledValues
,
710 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
712 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
717 sendError(messageId
, err
) {
718 // Check exception: only OCPP error are accepted
719 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
721 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
724 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
725 // Send a message through wsConnection
728 return new Promise((resolve
, reject
) => {
731 switch (messageType
) {
733 case Constants
.OCPP_JSON_CALL_MESSAGE
:
734 if (this.getEnableStatistics()) {
735 this._statistics
.addMessage(commandName
);
738 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
739 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
742 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
743 if (this.getEnableStatistics()) {
744 this._statistics
.addMessage(commandName
);
747 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
750 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
751 if (this.getEnableStatistics()) {
752 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
755 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
758 // Check if wsConnection is ready
759 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
761 this._wsConnection
.send(messageToSend
);
763 // Buffer message until connection is back
764 this._messageQueue
.push(messageToSend
);
767 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
770 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
771 // Send timeout in case connection is open otherwise wait for ever
772 // FIXME: Handle message on timeout
773 setTimeout(() => rejectCallback(`Timeout for message ${messageId}`), Constants
.OCPP_SOCKET_TIMEOUT
);
776 // Function that will receive the request's response
777 function responseCallback(payload
, requestPayload
) {
778 if (self
.getEnableStatistics()) {
779 self
._statistics
.addMessage(commandName
, true);
781 const responseCallbackFn
= 'handleResponse' + commandName
;
782 if (typeof self
[responseCallbackFn
] === 'function') {
783 self
[responseCallbackFn
](payload
, requestPayload
, self
);
785 logger
.debug(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
791 // Function that will receive the request's rejection
792 function rejectCallback(reason
) {
793 if (self
.getEnableStatistics()) {
794 self
._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`, true);
797 // eslint-disable-next-line no-empty-function
798 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
799 const error
= reason
instanceof OCPPError
? reason
: new Error(reason
);
806 handleResponseBootNotification(payload
) {
807 if (payload
.status
=== 'Accepted') {
808 this._heartbeatInterval
= payload
.interval
* 1000;
809 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
810 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
811 this._basicStartMessageSequence();
812 } else if (payload
.status
=== 'Pending') {
813 logger
.info(this._logPrefix() + ' Charging station pending on the central server');
815 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
819 _initTransactionOnConnector(connectorId
) {
820 this.getConnector(connectorId
).transactionStarted
= false;
821 this.getConnector(connectorId
).transactionId
= null;
822 this.getConnector(connectorId
).idTag
= null;
823 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
826 _resetTransactionOnConnector(connectorId
) {
827 this._initTransactionOnConnector(connectorId
);
828 if (this.getConnector(connectorId
).transactionSetInterval
) {
829 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
833 handleResponseStartTransaction(payload
, requestPayload
) {
834 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
835 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
839 let transactionConnectorId
;
840 for (const connector
in this._connectors
) {
841 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
842 transactionConnectorId
= connector
;
846 if (!transactionConnectorId
) {
847 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
850 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
851 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
852 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
853 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
854 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
855 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
856 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
857 if (this._stationInfo
.powerSharedByConnectors
) {
858 this._stationInfo
.powerDivider
++;
860 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
861 this._startMeterValues(requestPayload
.connectorId
,
862 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
864 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
865 this._resetTransactionOnConnector(requestPayload
.connectorId
);
866 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
870 handleResponseStopTransaction(payload
, requestPayload
) {
871 let transactionConnectorId
;
872 for (const connector
in this._connectors
) {
873 if (this.getConnector(connector
).transactionId
=== requestPayload
.transactionId
) {
874 transactionConnectorId
= connector
;
878 if (!transactionConnectorId
) {
879 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
882 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
883 this.sendStatusNotification(transactionConnectorId
, 'Available');
884 if (this._stationInfo
.powerSharedByConnectors
) {
885 this._stationInfo
.powerDivider
--;
887 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
888 this._resetTransactionOnConnector(transactionConnectorId
);
890 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
894 handleResponseStatusNotification(payload
, requestPayload
) {
895 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
898 handleResponseMeterValues(payload
, requestPayload
) {
899 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
902 handleResponseHeartbeat(payload
, requestPayload
) {
903 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
906 async
handleRequest(messageId
, commandName
, commandPayload
) {
907 if (this.getEnableStatistics()) {
908 this._statistics
.addMessage(commandName
, true);
912 if (typeof this['handle' + commandName
] === 'function') {
915 result
= await
this['handle' + commandName
](commandPayload
);
918 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
919 // Send back response to inform backend
920 await
this.sendError(messageId
, error
);
924 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
925 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
928 await
this.sendMessage(messageId
, result
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
931 async
handleReset(commandPayload
) {
932 // Simulate charging station restart
933 setImmediate(async () => {
934 await
this.stop(commandPayload
.type
+ 'Reset');
935 await Utils
.sleep(this._stationInfo
.resetTime
);
938 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
939 return Constants
.OCPP_RESPONSE_ACCEPTED
;
942 _getConfigurationKey(key
) {
943 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
946 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
947 const keyFound
= this._getConfigurationKey(key
);
949 this._configuration
.configurationKey
.push({
959 _setConfigurationKeyValue(key
, value
) {
960 const keyFound
= this._getConfigurationKey(key
);
962 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
963 this._configuration
.configurationKey
[keyIndex
].value
= value
;
967 async
handleGetConfiguration(commandPayload
) {
968 const configurationKey
= [];
969 const unknownKey
= [];
970 if (Utils
.isEmptyArray(commandPayload
.key
)) {
971 for (const configuration
of this._configuration
.configurationKey
) {
972 if (Utils
.isUndefined(configuration
.visible
)) {
973 configuration
.visible
= true;
975 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
977 if (!configuration
.visible
) {
980 configurationKey
.push({
981 key
: configuration
.key
,
982 readonly
: configuration
.readonly
,
983 value
: configuration
.value
,
987 for (const configurationKey
of commandPayload
.key
) {
988 const keyFound
= this._getConfigurationKey(configurationKey
);
990 if (Utils
.isUndefined(keyFound
.visible
)) {
991 keyFound
.visible
= true;
993 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
995 if (!keyFound
.visible
) {
998 configurationKey
.push({
1000 readonly
: keyFound
.readonly
,
1001 value
: keyFound
.value
,
1004 unknownKey
.push(configurationKey
);
1014 async
handleChangeConfiguration(commandPayload
) {
1015 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1017 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
1018 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
1019 return Constants
.OCPP_RESPONSE_REJECTED
;
1020 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
1021 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1022 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1023 let triggerHeartbeatRestart
= false;
1024 if (keyToChange
.key
=== 'HeartBeatInterval') {
1025 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1026 triggerHeartbeatRestart
= true;
1028 if (keyToChange
.key
=== 'HeartbeatInterval') {
1029 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1030 triggerHeartbeatRestart
= true;
1032 if (triggerHeartbeatRestart
) {
1033 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1035 this._stopHeartbeat();
1037 this._startHeartbeat(this);
1039 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
1040 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
1042 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1046 async
handleRemoteStartTransaction(commandPayload
) {
1047 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
1048 if (this.hasAuthorizedTags() && this._getLocalAuthListEnabled() && this._getAuthorizeRemoteTxRequests()) {
1049 // Check if authorized
1050 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1051 // Authorization successful start transaction
1052 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
1053 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1054 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1056 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
1057 return Constants
.OCPP_RESPONSE_REJECTED
;
1059 // No local authorization check required => start transaction
1060 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
, Constants
.START_TRANSACTION_TIMEOUT
);
1061 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1062 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1065 async
handleRemoteStopTransaction(commandPayload
) {
1066 for (const connector
in this._connectors
) {
1067 if (this.getConnector(connector
).transactionId
=== commandPayload
.transactionId
) {
1068 this.sendStopTransaction(commandPayload
.transactionId
);
1069 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1072 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1073 return Constants
.OCPP_RESPONSE_REJECTED
;
1077 module
.exports
= ChargingStation
;