1 import {PerformanceObserver
, performance
} from 'perf_hooks';
3 import AutomaticTransactionGenerator
from './AutomaticTransactionGenerator.js';
4 import Configuration
from '../utils/Configuration.js';
5 import Constants
from '../utils/Constants.js';
6 import ElectricUtils
from '../utils/ElectricUtils.js';
7 import OCPPError
from './OcppError.js';
8 import Statistics
from '../utils/Statistics.js';
9 import Utils
from '../utils/Utils.js';
10 import WebSocket
from 'ws';
11 import crypto
from 'crypto';
13 import logger
from '../utils/Logger.js';
15 export default class ChargingStation
{
16 constructor(index
, stationTemplateFile
) {
18 this._stationTemplateFile
= stationTemplateFile
;
19 this._connectors
= {};
22 this._isSocketRestart
= false;
23 this._autoReconnectRetryCount
= 0;
24 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
25 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // ms, zero for disabling
28 this._messageQueue
= [];
30 this._authorizedTags
= this._loadAndGetAuthorizedTags();
33 _getStationName(stationTemplate
) {
34 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
38 let stationTemplateFromFile
;
41 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
42 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
43 fs
.closeSync(fileDescriptor
);
45 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: ' + error
);
48 const stationTemplate
= stationTemplateFromFile
|| {};
49 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
50 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math
.floor(Math
.random() * stationTemplateFromFile
.power
.length
)];
52 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
54 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
55 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
56 return stationTemplate
;
60 this._stationInfo
= this._buildStationInfo();
61 this._bootNotificationMessage
= {
62 chargePointModel
: this._stationInfo
.chargePointModel
,
63 chargePointVendor
: this._stationInfo
.chargePointVendor
,
64 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && {chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
65 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && {firmwareVersion
: this._stationInfo
.firmwareVersion
},
67 this._configuration
= this._getConfiguration();
68 this._supervisionUrl
= this._getSupervisionURL();
69 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
70 // Build connectors if needed
71 const maxConnectors
= this._getMaxNumberOfConnectors();
72 if (maxConnectors
<= 0) {
73 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
75 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
76 if (templateMaxConnectors
<= 0) {
77 logger
.warn(`${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
;
220 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
221 let defaultVoltageOut
;
222 switch (this._getPowerOutType()) {
224 defaultVoltageOut
= 230;
227 defaultVoltageOut
= 400;
230 logger
.error(errMsg
);
233 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? Utils
.convertToInt(this._stationInfo
.voltageOut
) : defaultVoltageOut
;
237 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: 'AC';
240 _getSupervisionURL() {
241 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
243 if (!Utils
.isEmptyArray(supervisionUrls
)) {
244 if (Configuration
.getDistributeStationToTenantEqually()) {
245 indexUrl
= this._index
% supervisionUrls
.length
;
248 indexUrl
= Math
.floor(Math
.random() * supervisionUrls
.length
);
250 return supervisionUrls
[indexUrl
];
252 return supervisionUrls
;
255 _getAuthorizeRemoteTxRequests() {
256 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
257 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
260 _getLocalAuthListEnabled() {
261 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
262 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
265 async
_basicStartMessageSequence() {
267 this._startHeartbeat(this);
268 // Initialize connectors status
269 for (const connector
in this._connectors
) {
270 if (!this.getConnector(connector
).transactionStarted
) {
271 if (this.getConnector(connector
).bootStatus
) {
272 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(connector
).bootStatus
);
274 this.sendStatusNotificationWithTimeout(connector
, 'Available');
277 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
281 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
282 if (!this._automaticTransactionGeneration
) {
283 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
285 if (this._automaticTransactionGeneration
.timeToStop
) {
286 this._automaticTransactionGeneration
.start();
289 if (this.getEnableStatistics()) {
290 this._statistics
.start();
294 // eslint-disable-next-line class-methods-use-this
295 async
_startHeartbeat(self
) {
296 if (self
._heartbeatInterval
&& self
._heartbeatInterval
> 0 && !self
._heartbeatSetInterval
) {
297 self
._heartbeatSetInterval
= setInterval(() => {
298 this.sendHeartbeat();
299 }, self
._heartbeatInterval
);
300 logger
.info(self
._logPrefix() + ' Heartbeat started every ' + self
._heartbeatInterval
+ 'ms');
302 logger
.error(`${self._logPrefix()} Heartbeat interval set to ${self._heartbeatInterval}ms, not starting the heartbeat`);
306 async
_stopHeartbeat() {
307 if (this._heartbeatSetInterval
) {
308 clearInterval(this._heartbeatSetInterval
);
309 this._heartbeatSetInterval
= null;
313 _startAuthorizationFileMonitoring() {
314 // eslint-disable-next-line no-unused-vars
315 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
317 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
318 // Initialize _authorizedTags
319 this._authorizedTags
= this._loadAndGetAuthorizedTags();
321 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
326 _startStationTemplateFileMonitoring() {
327 // eslint-disable-next-line no-unused-vars
328 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
330 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
333 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
334 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
336 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
341 async
_startMeterValues(connectorId
, interval
) {
342 if (!this.getConnector(connectorId
).transactionStarted
) {
343 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
345 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
346 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
350 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
351 if (this.getEnableStatistics()) {
352 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
353 this._performanceObserver
.observe({
354 entryTypes
: ['function'],
356 await
sendMeterValues(connectorId
, interval
, this);
358 await
this.sendMeterValues(connectorId
, interval
, this);
362 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
367 if (!this._wsConnectionUrl
) {
368 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
370 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
371 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
372 // Monitor authorization file
373 this._startAuthorizationFileMonitoring();
374 // Monitor station template file
375 this._startStationTemplateFileMonitoring();
376 // Handle Socket incoming messages
377 this._wsConnection
.on('message', this.onMessage
.bind(this));
378 // Handle Socket error
379 this._wsConnection
.on('error', this.onError
.bind(this));
380 // Handle Socket close
381 this._wsConnection
.on('close', this.onClose
.bind(this));
382 // Handle Socket opening connection
383 this._wsConnection
.on('open', this.onOpen
.bind(this));
384 // Handle Socket ping
385 this._wsConnection
.on('ping', this.onPing
.bind(this));
388 async
stop(reason
= '') {
390 await
this._stopHeartbeat();
392 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
393 this._automaticTransactionGeneration
&&
394 !this._automaticTransactionGeneration
.timeToStop
) {
395 await
this._automaticTransactionGeneration
.stop(reason
);
397 for (const connector
in this._connectors
) {
398 if (this.getConnector(connector
).transactionStarted
) {
399 await
this.sendStopTransaction(this.getConnector(connector
).transactionId
, reason
);
403 // eslint-disable-next-line guard-for-in
404 for (const connector
in this._connectors
) {
405 await
this.sendStatusNotification(connector
, 'Unavailable');
407 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
408 await
this._wsConnection
.close();
413 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
414 // Stop the ATG if needed
415 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
416 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
417 this._automaticTransactionGeneration
&&
418 !this._automaticTransactionGeneration
.timeToStop
) {
419 this._automaticTransactionGeneration
.stop();
422 this._stopHeartbeat();
423 if (this._autoReconnectTimeout
!== 0 &&
424 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
425 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
426 this._autoReconnectRetryCount
++;
428 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
430 }, this._autoReconnectTimeout
);
431 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
432 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
437 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
438 if (!this._isSocketRestart
) {
439 // Send BootNotification
440 this.sendBootNotification();
442 if (this._isSocketRestart
) {
443 this._basicStartMessageSequence();
444 if (!Utils
.isEmptyArray(this._messageQueue
)) {
445 this._messageQueue
.forEach((message
) => {
446 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
447 this._wsConnection
.send(message
);
452 this._autoReconnectRetryCount
= 0;
453 this._isSocketRestart
= false;
459 this._isSocketRestart
= true;
460 this._reconnect(error
);
463 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
470 case 1000: // Normal close
472 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
473 this._autoReconnectRetryCount
= 0;
475 default: // Abnormal close
476 this._isSocketRestart
= true;
477 this._reconnect(error
);
483 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
486 async
onMessage(message
) {
487 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
490 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
492 // Check the Type of message
493 switch (messageType
) {
495 case Constants
.OCPP_JSON_CALL_MESSAGE
:
497 await
this.handleRequest(messageId
, commandName
, commandPayload
);
500 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
502 // eslint-disable-next-line no-case-declarations
503 let responseCallback
; let requestPayload
;
504 if (Utils
.isIterable(this._requests
[messageId
])) {
505 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
507 throw new Error(`Response request for message id ${messageId} is not iterable`);
509 if (!responseCallback
) {
511 throw new Error(`Response for unknown message id ${messageId}`);
513 delete this._requests
[messageId
];
514 responseCallback(commandName
, requestPayload
);
517 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
518 if (!this._requests
[messageId
]) {
520 throw new Error(`Error for unknown message id ${messageId}`);
522 // eslint-disable-next-line no-case-declarations
524 if (Utils
.isIterable(this._requests
[messageId
])) {
525 [, rejectCallback
] = this._requests
[messageId
];
527 throw new Error(`Error request for message id ${messageId} is not iterable`);
529 delete this._requests
[messageId
];
530 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
534 throw new Error(`Wrong message type ${messageType}`);
538 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
540 // await this.sendError(messageId, error);
547 currentTime
: new Date().toISOString(),
549 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
551 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
556 sendBootNotification() {
558 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
560 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
565 async
sendStatusNotification(connectorId
, status
, errorCode
= 'NoError') {
572 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
574 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
579 sendStatusNotificationWithTimeout(connectorId
, status
, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
580 setTimeout(() => this.sendStatusNotification(connectorId
, status
, errorCode
), timeout
);
583 async
sendStartTransaction(connectorId
, idTag
) {
589 timestamp
: new Date().toISOString(),
591 return await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
593 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
598 sendStartTransactionWithTimeout(connectorId
, idTag
, timeout
= Constants
.START_TRANSACTION_TIMEOUT
) {
599 setTimeout(() => this.sendStartTransaction(connectorId
, idTag
), timeout
);
602 async
sendStopTransaction(transactionId
, reason
= '') {
607 timestamp
: new Date().toISOString(),
608 ...reason
&& {reason
},
610 await
this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
612 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
617 // eslint-disable-next-line class-methods-use-this
618 async
sendMeterValues(connectorId
, interval
, self
, debug
= false) {
620 const sampledValues
= {
621 timestamp
: new Date().toISOString(),
624 const meterValuesTemplate
= self
.getConnector(connectorId
).MeterValues
;
625 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
626 const connector
= self
.getConnector(connectorId
);
628 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'SoC' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
629 sampledValues
.sampledValue
.push({
630 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'Percent'},
631 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
632 measurand
: meterValuesTemplate
[index
].measurand
,
633 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? {location
: meterValuesTemplate
[index
].location
} : {location
: 'EV'},
634 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: Utils
.getRandomInt(100)},
636 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
637 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> 100 || debug
) {
638 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}/100`);
641 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Voltage' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
642 sampledValues
.sampledValue
.push({
643 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'V'},
644 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
645 measurand
: meterValuesTemplate
[index
].measurand
,
646 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
647 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: self
._getVoltageOut()},
649 for (let phase
= 1; self
._getPowerOutType() === 'AC' && self
._getNumberOfPhases() === 3 && phase
<= self
._getNumberOfPhases(); phase
++) {
650 const voltageValue
= sampledValues
.sampledValue
[sampledValues
.sampledValue
.length
- 1].value
;
652 if (voltageValue
>= 0 && voltageValue
<= 250) {
653 phaseValue
= `L${phase}-N`;
654 } else if (voltageValue
> 250) {
655 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
657 sampledValues
.sampledValue
.push({
658 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'V'},
659 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
660 measurand
: meterValuesTemplate
[index
].measurand
,
661 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
662 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: self
._getVoltageOut()},
666 // Power.Active.Import measurand
667 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Power.Active.Import' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Power.Active.Import')) {
668 // FIXME: factor out powerDivider checks
669 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
670 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
671 logger
.error(errMsg
);
673 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
674 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}`;
675 logger
.error(errMsg
);
678 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
679 const powerMeasurandValues
= {};
680 const maxPower
= Math
.round(self
._stationInfo
.maxPower
/ self
._stationInfo
.powerDivider
);
681 const maxPowerPerPhase
= Math
.round((self
._stationInfo
.maxPower
/ self
._stationInfo
.powerDivider
) / self
._getNumberOfPhases());
682 switch (self
._getPowerOutType()) {
684 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
685 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
686 powerMeasurandValues
.L2
= 0;
687 powerMeasurandValues
.L3
= 0;
688 if (self
._getNumberOfPhases() === 3) {
689 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
690 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
692 powerMeasurandValues
.all
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
696 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
697 powerMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxPower
);
701 logger
.error(errMsg
);
704 sampledValues
.sampledValue
.push({
705 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'W'},
706 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
707 measurand
: meterValuesTemplate
[index
].measurand
,
708 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
709 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: powerMeasurandValues
.all
},
711 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
712 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxPower
|| debug
) {
713 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}/${maxPower}`);
715 for (let phase
= 1; self
._getPowerOutType() === 'AC' && self
._getNumberOfPhases() === 3 && phase
<= self
._getNumberOfPhases(); phase
++) {
716 const phaseValue
= `L${phase}-N`;
717 sampledValues
.sampledValue
.push({
718 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'W'},
719 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
720 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && {measurand
: meterValuesTemplate
[index
].measurand
},
721 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
722 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: powerMeasurandValues
[`L${phase}`]},
726 // Current.Import measurand
727 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Current.Import' && self
._getConfigurationKey('MeterValuesSampledData').value
.includes('Current.Import')) {
728 // FIXME: factor out powerDivider checks
729 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
730 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
731 logger
.error(errMsg
);
733 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
734 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}`;
735 logger
.error(errMsg
);
738 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
739 const currentMeasurandValues
= {};
741 switch (self
._getPowerOutType()) {
743 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self
._getNumberOfPhases(), self
._stationInfo
.maxPower
/ self
._stationInfo
.powerDivider
, self
._getVoltageOut());
744 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
745 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
746 currentMeasurandValues
.L2
= 0;
747 currentMeasurandValues
.L3
= 0;
748 if (self
._getNumberOfPhases() === 3) {
749 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
750 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
752 currentMeasurandValues
.all
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self
._getNumberOfPhases(), 2);
756 maxAmperage
= ElectricUtils
.ampTotalFromPower(self
._stationInfo
.maxPower
/ self
._stationInfo
.powerDivider
, self
._getVoltageOut());
757 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
758 currentMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxAmperage
);
762 logger
.error(errMsg
);
765 sampledValues
.sampledValue
.push({
766 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'A'},
767 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
768 measurand
: meterValuesTemplate
[index
].measurand
,
769 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
770 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: currentMeasurandValues
.all
},
772 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
773 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxAmperage
|| debug
) {
774 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}/${maxAmperage}`);
776 for (let phase
= 1; self
._getPowerOutType() === 'AC' && self
._getNumberOfPhases() === 3 && phase
<= self
._getNumberOfPhases(); phase
++) {
777 const phaseValue
= `L${phase}`;
778 sampledValues
.sampledValue
.push({
779 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'A'},
780 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
781 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && {measurand
: meterValuesTemplate
[index
].measurand
},
782 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
783 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: currentMeasurandValues
[phaseValue
]},
787 // Energy.Active.Import.Register measurand (default)
788 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== 'Energy.Active.Import.Register') {
789 // FIXME: factor out powerDivider checks
790 if (Utils
.isUndefined(self
._stationInfo
.powerDivider
)) {
791 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
792 logger
.error(errMsg
);
794 } else if (self
._stationInfo
.powerDivider
&& self
._stationInfo
.powerDivider
<= 0) {
795 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}`;
796 logger
.error(errMsg
);
799 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
800 const measurandValue
= Utils
.getRandomInt(self
._stationInfo
.maxPower
/ (self
._stationInfo
.powerDivider
* 3600000) * interval
);
801 // Persist previous value in connector
802 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
803 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
805 connector
.lastEnergyActiveImportRegisterValue
= 0;
808 sampledValues
.sampledValue
.push({
809 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? {unit
: meterValuesTemplate
[index
].unit
} : {unit
: 'Wh'},
810 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && {context
: meterValuesTemplate
[index
].context
},
811 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && {measurand
: meterValuesTemplate
[index
].measurand
},
812 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && {location
: meterValuesTemplate
[index
].location
},
813 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? {value
: meterValuesTemplate
[index
].value
} : {value
: connector
.lastEnergyActiveImportRegisterValue
},
815 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
816 const maxConsumption
= Math
.round(self
._stationInfo
.maxPower
* 3600 / (self
._stationInfo
.powerDivider
* interval
));
817 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxConsumption
|| debug
) {
818 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}`);
820 // Unsupported measurand
822 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
828 transactionId
: self
.getConnector(connectorId
).transactionId
,
829 meterValue
: sampledValues
,
831 await self
.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
833 logger
.error(self
._logPrefix() + ' Send MeterValues error: ' + error
);
838 sendError(messageId
, err
) {
839 // Check exception: only OCPP error are accepted
840 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
842 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
845 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
846 // Send a message through wsConnection
849 return new Promise((resolve
, reject
) => {
852 switch (messageType
) {
854 case Constants
.OCPP_JSON_CALL_MESSAGE
:
855 if (this.getEnableStatistics()) {
856 this._statistics
.addMessage(commandName
);
859 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
860 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
863 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
864 if (this.getEnableStatistics()) {
865 this._statistics
.addMessage(commandName
);
868 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
871 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
872 if (this.getEnableStatistics()) {
873 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
876 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
879 // Check if wsConnection is ready
880 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
882 this._wsConnection
.send(messageToSend
);
884 // Buffer message until connection is back
885 this._messageQueue
.push(messageToSend
);
888 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
891 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
892 // Send timeout in case connection is open otherwise wait for ever
893 // FIXME: Handle message on timeout
894 setTimeout(() => rejectCallback(new OCPPError(command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {})), Constants
.OCPP_SOCKET_TIMEOUT
);
897 // Function that will receive the request's response
898 function responseCallback(payload
, requestPayload
) {
899 self
.handleResponse(commandName
, payload
, requestPayload
, self
);
904 // Function that will receive the request's rejection
905 function rejectCallback(error
) {
906 if (!(error
instanceof OCPPError
)) {
907 const errMsg
= `${self._logPrefix()} Argument error is not an instance of OCPPError in rejectCallback call`;
908 logger
.error(errMsg
);
911 logger
.debug(`${self._logPrefix()} Error %j on commandName %s command %j`, error
, commandName
, command
);
912 if (self
.getEnableStatistics()) {
913 self
._statistics
.addMessage(`Error on commandName ${commandName}`, true);
916 // eslint-disable-next-line no-empty-function
917 self
._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
924 // eslint-disable-next-line class-methods-use-this
925 handleResponse(commandName
, payload
, requestPayload
, self
) {
926 if (self
.getEnableStatistics()) {
927 self
._statistics
.addMessage(commandName
, true);
929 const responseCallbackFn
= 'handleResponse' + commandName
;
930 if (typeof self
[responseCallbackFn
] === 'function') {
931 self
[responseCallbackFn
](payload
, requestPayload
, self
);
933 logger
.error(self
._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
937 handleResponseBootNotification(payload
) {
938 if (payload
.status
=== 'Accepted') {
939 this._heartbeatInterval
= payload
.interval
* 1000;
940 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
941 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
942 this._basicStartMessageSequence();
943 } else if (payload
.status
=== 'Pending') {
944 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
946 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
950 _initTransactionOnConnector(connectorId
) {
951 this.getConnector(connectorId
).transactionStarted
= false;
952 this.getConnector(connectorId
).transactionId
= null;
953 this.getConnector(connectorId
).idTag
= null;
954 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
957 _resetTransactionOnConnector(connectorId
) {
958 this._initTransactionOnConnector(connectorId
);
959 if (this.getConnector(connectorId
).transactionSetInterval
) {
960 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
964 handleResponseStartTransaction(payload
, requestPayload
) {
965 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
966 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
970 let transactionConnectorId
;
971 for (const connector
in this._connectors
) {
972 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
973 transactionConnectorId
= connector
;
977 if (!transactionConnectorId
) {
978 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
981 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
982 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
983 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
984 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
985 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
986 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
987 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
988 if (this._stationInfo
.powerSharedByConnectors
) {
989 this._stationInfo
.powerDivider
++;
991 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
992 this._startMeterValues(requestPayload
.connectorId
,
993 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
995 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
+ ', idTag ' + requestPayload
.idTag
);
996 this._resetTransactionOnConnector(requestPayload
.connectorId
);
997 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
1001 handleResponseStopTransaction(payload
, requestPayload
) {
1002 let transactionConnectorId
;
1003 for (const connector
in this._connectors
) {
1004 if (this.getConnector(connector
).transactionId
=== requestPayload
.transactionId
) {
1005 transactionConnectorId
= connector
;
1009 if (!transactionConnectorId
) {
1010 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
1013 if (payload
.idTagInfo
&& payload
.idTagInfo
.status
=== 'Accepted') {
1014 this.sendStatusNotification(transactionConnectorId
, 'Available');
1015 if (this._stationInfo
.powerSharedByConnectors
) {
1016 this._stationInfo
.powerDivider
--;
1018 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
1019 this._resetTransactionOnConnector(transactionConnectorId
);
1021 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status
);
1025 handleResponseStatusNotification(payload
, requestPayload
) {
1026 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1029 handleResponseMeterValues(payload
, requestPayload
) {
1030 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1033 handleResponseHeartbeat(payload
, requestPayload
) {
1034 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1037 async
handleRequest(messageId
, commandName
, commandPayload
) {
1038 if (this.getEnableStatistics()) {
1039 this._statistics
.addMessage(commandName
, true);
1043 if (typeof this['handleRequest' + commandName
] === 'function') {
1045 // Call the method to build the response
1046 response
= await
this['handleRequest' + commandName
](commandPayload
);
1049 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
1050 // Send back response to inform backend
1051 await
this.sendError(messageId
, error
);
1055 await
this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
1056 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1059 await
this.sendMessage(messageId
, response
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
1062 // Simulate charging station restart
1063 async
handleRequestReset(commandPayload
) {
1064 setImmediate(async () => {
1065 await
this.stop(commandPayload
.type
+ 'Reset');
1066 await Utils
.sleep(this._stationInfo
.resetTime
);
1069 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
1070 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1073 _getConfigurationKey(key
) {
1074 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
1077 _addConfigurationKey(key
, value
, readonly
= false, visible
= true, reboot
= false) {
1078 const keyFound
= this._getConfigurationKey(key
);
1080 this._configuration
.configurationKey
.push({
1090 _setConfigurationKeyValue(key
, value
) {
1091 const keyFound
= this._getConfigurationKey(key
);
1093 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1094 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1098 async
handleRequestGetConfiguration(commandPayload
) {
1099 const configurationKey
= [];
1100 const unknownKey
= [];
1101 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1102 for (const configuration
of this._configuration
.configurationKey
) {
1103 if (Utils
.isUndefined(configuration
.visible
)) {
1104 configuration
.visible
= true;
1106 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
1108 if (!configuration
.visible
) {
1111 configurationKey
.push({
1112 key
: configuration
.key
,
1113 readonly
: configuration
.readonly
,
1114 value
: configuration
.value
,
1118 for (const configurationKey
of commandPayload
.key
) {
1119 const keyFound
= this._getConfigurationKey(configurationKey
);
1121 if (Utils
.isUndefined(keyFound
.visible
)) {
1122 keyFound
.visible
= true;
1124 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
1126 if (!keyFound
.visible
) {
1129 configurationKey
.push({
1131 readonly
: keyFound
.readonly
,
1132 value
: keyFound
.value
,
1135 unknownKey
.push(configurationKey
);
1145 async
handleRequestChangeConfiguration(commandPayload
) {
1146 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1148 return {status
: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
1149 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly
)) {
1150 return Constants
.OCPP_RESPONSE_REJECTED
;
1151 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly
)) {
1152 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1153 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1154 let triggerHeartbeatRestart
= false;
1155 if (keyToChange
.key
=== 'HeartBeatInterval') {
1156 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1157 triggerHeartbeatRestart
= true;
1159 if (keyToChange
.key
=== 'HeartbeatInterval') {
1160 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1161 triggerHeartbeatRestart
= true;
1163 if (triggerHeartbeatRestart
) {
1164 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1166 this._stopHeartbeat();
1168 this._startHeartbeat(this);
1170 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
1171 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
1173 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1177 async
handleRequestRemoteStartTransaction(commandPayload
) {
1178 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
1179 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1180 // Check if authorized
1181 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1182 // Authorization successful start transaction
1183 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
);
1184 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1185 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1187 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status
+ ', idTag ' + commandPayload
.idTag
);
1188 return Constants
.OCPP_RESPONSE_REJECTED
;
1190 // No local authorization check required => start transaction
1191 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
);
1192 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1193 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1196 async
handleRequestRemoteStopTransaction(commandPayload
) {
1197 for (const connector
in this._connectors
) {
1198 if (this.getConnector(connector
).transactionId
=== commandPayload
.transactionId
) {
1199 this.sendStopTransaction(commandPayload
.transactionId
);
1200 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1203 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1204 return Constants
.OCPP_RESPONSE_REJECTED
;