1 import { PerformanceObserver
, performance
} from
'perf_hooks';
3 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
4 import Configuration from
'../utils/Configuration';
5 import Constants from
'../utils/Constants.js';
6 import ElectricUtils from
'../utils/ElectricUtils';
7 import { MeasurandValues
} from
'../types/MeasurandValues';
8 import OCPPError from
'./OcppError.js';
9 import Statistics from
'../utils/Statistics';
10 import Utils from
'../utils/Utils';
11 import WebSocket from
'ws';
12 import crypto from
'crypto';
14 import logger from
'../utils/Logger';
16 export default class ChargingStation
{
17 private _index
: number;
18 private _stationTemplateFile
;
20 private _bootNotificationMessage
;
22 private _configuration
;
23 private _connectorsConfigurationHash
;
24 private _supervisionUrl
;
25 private _wsConnectionUrl
;
26 private _wsConnection
;
27 private _isSocketRestart
;
28 private _autoReconnectRetryCount
;
29 private _autoReconnectMaxRetries
;
30 private _autoReconnectTimeout
;
32 private _messageQueue
;
33 private _automaticTransactionGeneration
: AutomaticTransactionGenerator
;
34 private _authorizedTags
: string[];
35 private _heartbeatInterval
;
36 private _heartbeatSetInterval
;
37 private _statistics
: Statistics
;
38 private _performanceObserver
: PerformanceObserver
;
40 constructor(index
: number, stationTemplateFile
: string) {
42 this._stationTemplateFile
= stationTemplateFile
;
43 this._connectors
= {};
46 this._isSocketRestart
= false;
47 this._autoReconnectRetryCount
= 0;
48 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
49 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // Ms, zero for disabling
52 this._messageQueue
= [];
54 this._authorizedTags
= this._loadAndGetAuthorizedTags();
57 _getStationName(stationTemplate
): string {
58 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
62 let stationTemplateFromFile
;
65 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
66 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
67 fs
.closeSync(fileDescriptor
);
69 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: ' + error
);
72 const stationTemplate
= stationTemplateFromFile
|| {};
73 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
74 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
76 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
78 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
79 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
80 return stationTemplate
;
84 return this._stationInfo
;
88 this._stationInfo
= this._buildStationInfo();
89 this._bootNotificationMessage
= {
90 chargePointModel
: this._stationInfo
.chargePointModel
,
91 chargePointVendor
: this._stationInfo
.chargePointVendor
,
92 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
93 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && { firmwareVersion
: this._stationInfo
.firmwareVersion
},
95 this._configuration
= this._getConfiguration();
96 this._supervisionUrl
= this._getSupervisionURL();
97 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
98 // Build connectors if needed
99 const maxConnectors
= this._getMaxNumberOfConnectors();
100 if (maxConnectors
<= 0) {
101 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
103 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
104 if (templateMaxConnectors
<= 0) {
105 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`);
108 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !Utils
.convertToBoolean(this._stationInfo
.randomConnectors
)) {
109 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
110 this._stationInfo
.randomConnectors
= true;
112 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
113 // FIXME: Handle shrinking the number of connectors
114 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
115 this._connectorsConfigurationHash
= connectorsConfigHash
;
116 // Add connector Id 0
117 let lastConnector
= '0';
118 for (lastConnector
in this._stationInfo
.Connectors
) {
119 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) && this._stationInfo
.Connectors
[lastConnector
]) {
120 this._connectors
[lastConnector
] = Utils
.cloneObject(this._stationInfo
.Connectors
[lastConnector
]);
123 // Generate all connectors
124 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
125 for (let index
= 1; index
<= maxConnectors
; index
++) {
126 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
127 this._connectors
[index
] = Utils
.cloneObject(this._stationInfo
.Connectors
[randConnectorID
]);
131 // Avoid duplication of connectors related information
132 delete this._stationInfo
.Connectors
;
133 // Initialize transaction attributes on connectors
134 for (const connector
in this._connectors
) {
135 if (!this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
136 this._initTransactionOnConnector(connector
);
140 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors(), true);
141 if (!this._getConfigurationKey('MeterValuesSampledData')) {
142 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
144 this._stationInfo
.powerDivider
= this._getPowerDivider();
145 if (this.getEnableStatistics()) {
146 this._statistics
= Statistics
.getInstance();
147 this._statistics
.objName
= this._stationInfo
.name
;
148 this._performanceObserver
= new PerformanceObserver((list
) => {
149 const entry
= list
.getEntries()[0];
150 this._statistics
.logPerformance(entry
, 'ChargingStation');
151 this._performanceObserver
.disconnect();
157 return this._connectors
;
160 get
statistics(): Statistics
{
161 return this._statistics
;
164 _logPrefix(): string {
165 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
168 _getConfiguration() {
169 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
172 _getAuthorizationFile() {
173 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
176 _loadAndGetAuthorizedTags(): string[] {
177 let authorizedTags
= [];
178 const authorizationFile
= this._getAuthorizationFile();
179 if (authorizationFile
) {
181 // Load authorization file
182 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
183 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
184 fs
.closeSync(fileDescriptor
);
186 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: ' + error
);
190 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
192 return authorizedTags
;
196 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
197 return this._authorizedTags
[index
];
200 hasAuthorizedTags() {
201 return !Utils
.isEmptyArray(this._authorizedTags
);
204 getEnableStatistics() {
205 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? Utils
.convertToBoolean(this._stationInfo
.enableStatistics
) : true;
208 _getNumberOfPhases(): number {
209 switch (this._getPowerOutType()) {
211 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? Utils
.convertToInt(this._stationInfo
.numberOfPhases
) : 3;
217 _getNumberOfRunningTransactions() {
219 for (const connector
in this._connectors
) {
220 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
228 let powerDivider
= this._getNumberOfConnectors();
229 if (this._stationInfo
.powerSharedByConnectors
) {
230 powerDivider
= this._getNumberOfRunningTransactions();
235 getConnector(id
: number) {
236 return this._connectors
[id
];
239 _getTemplateMaxNumberOfConnectors() {
240 return Object.keys(this._stationInfo
.Connectors
).length
;
243 _getMaxNumberOfConnectors() {
244 let maxConnectors
= 0;
245 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
246 // Distribute evenly the number of connectors
247 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
248 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
249 maxConnectors
= this._stationInfo
.numberOfConnectors
;
251 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
253 return maxConnectors
;
256 _getNumberOfConnectors(): number {
257 return this._connectors
[0] ? Object.keys(this._connectors
).length
- 1 : Object.keys(this._connectors
).length
;
261 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
262 let defaultVoltageOut
;
263 switch (this._getPowerOutType()) {
265 defaultVoltageOut
= 230;
268 defaultVoltageOut
= 400;
271 logger
.error(errMsg
);
274 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? Utils
.convertToInt(this._stationInfo
.voltageOut
) : defaultVoltageOut
;
278 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: 'AC';
281 _getSupervisionURL() {
282 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
284 if (!Utils
.isEmptyArray(supervisionUrls
)) {
285 if (Configuration
.getDistributeStationToTenantEqually()) {
286 indexUrl
= this._index
% supervisionUrls
.length
;
289 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
291 return supervisionUrls
[indexUrl
];
293 return supervisionUrls
;
296 _getAuthorizeRemoteTxRequests() {
297 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
298 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
301 _getLocalAuthListEnabled() {
302 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
303 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
306 _basicStartMessageSequence(): void {
308 this._startHeartbeat();
309 // Initialize connectors status
310 for (const connector
in this._connectors
) {
311 if (!this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
312 if (this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
313 this.sendStatusNotificationWithTimeout(connector
, this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
315 this.sendStatusNotificationWithTimeout(connector
, 'Available');
318 this.sendStatusNotificationWithTimeout(connector
, 'Charging');
322 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
323 if (!this._automaticTransactionGeneration
) {
324 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
326 if (this._automaticTransactionGeneration
.timeToStop
) {
327 this._automaticTransactionGeneration
.start();
330 if (this.getEnableStatistics()) {
331 this._statistics
.start();
335 _startHeartbeat(): void {
336 if (this._heartbeatInterval
&& this._heartbeatInterval
> 0 && !this._heartbeatSetInterval
) {
337 this._heartbeatSetInterval
= setInterval(() => {
338 this.sendHeartbeat();
339 }, this._heartbeatInterval
);
340 logger
.info(this._logPrefix() + ' Heartbeat started every ' + this._heartbeatInterval
.toString() + 'ms');
342 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval}ms, not starting the heartbeat`);
347 if (this._heartbeatSetInterval
) {
348 clearInterval(this._heartbeatSetInterval
);
349 this._heartbeatSetInterval
= null;
353 _startAuthorizationFileMonitoring() {
354 // eslint-disable-next-line no-unused-vars
355 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
357 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
358 // Initialize _authorizedTags
359 this._authorizedTags
= this._loadAndGetAuthorizedTags();
361 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
366 _startStationTemplateFileMonitoring() {
367 // eslint-disable-next-line no-unused-vars
368 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
370 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
373 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0));
374 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(this._heartbeatInterval
? this._heartbeatInterval
/ 1000 : 0), false, false);
376 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
381 _startMeterValues(connectorId
: number, interval
: number): void {
382 if (!this.getConnector(connectorId
).transactionStarted
) {
383 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
385 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
386 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
390 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async () => {
391 if (this.getEnableStatistics()) {
392 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
393 this._performanceObserver
.observe({
394 entryTypes
: ['function'],
396 await sendMeterValues(connectorId
, interval
);
398 await this.sendMeterValues(connectorId
, interval
);
402 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
407 if (!this._wsConnectionUrl
) {
408 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
410 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
411 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
412 // Monitor authorization file
413 this._startAuthorizationFileMonitoring();
414 // Monitor station template file
415 this._startStationTemplateFileMonitoring();
416 // Handle Socket incoming messages
417 this._wsConnection
.on('message', this.onMessage
.bind(this));
418 // Handle Socket error
419 this._wsConnection
.on('error', this.onError
.bind(this));
420 // Handle Socket close
421 this._wsConnection
.on('close', this.onClose
.bind(this));
422 // Handle Socket opening connection
423 this._wsConnection
.on('open', this.onOpen
.bind(this));
424 // Handle Socket ping
425 this._wsConnection
.on('ping', this.onPing
.bind(this));
428 async stop(reason
= '') {
430 this._stopHeartbeat();
432 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
433 this._automaticTransactionGeneration
&&
434 !this._automaticTransactionGeneration
.timeToStop
) {
435 await this._automaticTransactionGeneration
.stop(reason
);
437 for (const connector
in this._connectors
) {
438 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
439 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
443 // eslint-disable-next-line guard-for-in
444 for (const connector
in this._connectors
) {
445 await this.sendStatusNotification(Utils
.convertToInt(connector
), 'Unavailable');
447 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
448 await this._wsConnection
.close();
453 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
454 // Stop the ATG if needed
455 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
456 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
457 this._automaticTransactionGeneration
&&
458 !this._automaticTransactionGeneration
.timeToStop
) {
459 this._automaticTransactionGeneration
.stop();
462 this._stopHeartbeat();
463 if (this._autoReconnectTimeout
!== 0 &&
464 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
465 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
466 this._autoReconnectRetryCount
++;
468 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
470 }, this._autoReconnectTimeout
);
471 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
472 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
477 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
478 if (!this._isSocketRestart
) {
479 // Send BootNotification
480 this.sendBootNotification();
482 if (this._isSocketRestart
) {
483 this._basicStartMessageSequence();
484 if (!Utils
.isEmptyArray(this._messageQueue
)) {
485 this._messageQueue
.forEach((message
) => {
486 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
487 this._wsConnection
.send(message
);
492 this._autoReconnectRetryCount
= 0;
493 this._isSocketRestart
= false;
499 this._isSocketRestart
= true;
500 this._reconnect(error
);
503 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
510 case 1000: // Normal close
512 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
513 this._autoReconnectRetryCount
= 0;
515 default: // Abnormal close
516 this._isSocketRestart
= true;
517 this._reconnect(error
);
523 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
526 async onMessage(message
) {
527 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
530 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
532 // Check the Type of message
533 switch (messageType
) {
535 case Constants
.OCPP_JSON_CALL_MESSAGE
:
537 await this.handleRequest(messageId
, commandName
, commandPayload
);
540 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
542 // eslint-disable-next-line no-case-declarations
543 let responseCallback
; let requestPayload
;
544 if (Utils
.isIterable(this._requests
[messageId
])) {
545 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
547 throw new Error(`Response request for message id ${messageId} is not iterable`);
549 if (!responseCallback
) {
551 throw new Error(`Response for unknown message id ${messageId}`);
553 delete this._requests
[messageId
];
554 responseCallback(commandName
, requestPayload
);
557 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
558 if (!this._requests
[messageId
]) {
560 throw new Error(`Error for unknown message id ${messageId}`);
562 // eslint-disable-next-line no-case-declarations
564 if (Utils
.isIterable(this._requests
[messageId
])) {
565 [, rejectCallback
] = this._requests
[messageId
];
567 throw new Error(`Error request for message id ${messageId} is not iterable`);
569 delete this._requests
[messageId
];
570 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
574 throw new Error(`Wrong message type ${messageType}`);
578 logger
.error('%s Incoming message %j processing error %s on request content %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
580 // await this.sendError(messageId, error);
587 currentTime
: new Date().toISOString(),
589 this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
591 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
596 sendBootNotification() {
598 this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
600 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
605 async sendStatusNotification(connectorId
: number, status, errorCode
= 'NoError') {
612 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
614 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
619 sendStatusNotificationWithTimeout(connectorId
, status, errorCode
= 'NoError', timeout
= Constants
.STATUS_NOTIFICATION_TIMEOUT
) {
620 setTimeout(async () => this.sendStatusNotification(connectorId
, status, errorCode
), timeout
);
623 async sendStartTransaction(connectorId
: number, idTag
?: string) {
627 ...!Utils
.isUndefined(idTag
) && { idTag
},
629 timestamp
: new Date().toISOString(),
631 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
633 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
638 sendStartTransactionWithTimeout(connectorId
: number, idTag
?: string, timeout
= Constants
.START_TRANSACTION_TIMEOUT
) {
639 setTimeout(async () => this.sendStartTransaction(connectorId
, idTag
), timeout
);
642 async sendStopTransaction(transactionId
, reason
= ''): Promise
<void> {
647 timestamp
: new Date().toISOString(),
648 ...reason
&& { reason
},
650 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
652 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
657 async sendMeterValues(connectorId
, interval
, debug
= false): Promise
<void> {
659 const sampledValues
= {
660 timestamp
: new Date().toISOString(),
663 const meterValuesTemplate
= this.getConnector(connectorId
).MeterValues
;
664 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
665 const connector
= this.getConnector(connectorId
);
667 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'SoC' && this._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
668 sampledValues
.sampledValue
.push({
669 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'Percent' },
670 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
671 measurand
: meterValuesTemplate
[index
].measurand
,
672 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: 'EV' },
673 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100) },
675 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
676 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> 100 || debug
) {
677 logger
.error(`${this._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`);
680 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Voltage' && this._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
681 sampledValues
.sampledValue
.push({
682 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'V' },
683 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
684 measurand
: meterValuesTemplate
[index
].measurand
,
685 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
686 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: this._getVoltageOut() },
688 for (let phase
= 1; this._getNumberOfPhases() === 3 && phase
<= this._getNumberOfPhases(); phase
++) {
689 const voltageValue
= sampledValues
.sampledValue
[sampledValues
.sampledValue
.length
- 1].value
;
691 if (voltageValue
>= 0 && voltageValue
<= 250) {
692 phaseValue
= `L${phase}-N`;
693 } else if (voltageValue
> 250) {
694 phaseValue
= `L${phase}-L${(phase + 1) % this._getNumberOfPhases() !== 0 ? (phase + 1) % this._getNumberOfPhases() : this._getNumberOfPhases()}`;
696 sampledValues
.sampledValue
.push({
697 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'V' },
698 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
699 measurand
: meterValuesTemplate
[index
].measurand
,
700 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
701 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: this._getVoltageOut() },
705 // Power.Active.Import measurand
706 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Power.Active.Import' && this._getConfigurationKey('MeterValuesSampledData').value
.includes('Power.Active.Import')) {
707 // FIXME: factor out powerDivider checks
708 if (Utils
.isUndefined(this._stationInfo
.powerDivider
)) {
709 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
710 logger
.error(errMsg
);
712 } else if (this._stationInfo
.powerDivider
&& this._stationInfo
.powerDivider
<= 0) {
713 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${this._stationInfo.powerDivider}`;
714 logger
.error(errMsg
);
717 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
718 const powerMeasurandValues
= {} as MeasurandValues
;
719 const maxPower
= Math.round(this._stationInfo
.maxPower
/ this._stationInfo
.powerDivider
);
720 const maxPowerPerPhase
= Math.round((this._stationInfo
.maxPower
/ this._stationInfo
.powerDivider
) / this._getNumberOfPhases());
721 switch (this._getPowerOutType()) {
723 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
724 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
725 powerMeasurandValues
.L2
= 0;
726 powerMeasurandValues
.L3
= 0;
727 if (this._getNumberOfPhases() === 3) {
728 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
729 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
731 powerMeasurandValues
.all
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
735 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
736 powerMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxPower
);
740 logger
.error(errMsg
);
743 sampledValues
.sampledValue
.push({
744 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'W' },
745 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
746 measurand
: meterValuesTemplate
[index
].measurand
,
747 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
748 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.all
},
750 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
751 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxPower
|| debug
) {
752 logger
.error(`${this._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}`);
754 for (let phase
= 1; this._getNumberOfPhases() === 3 && phase
<= this._getNumberOfPhases(); phase
++) {
755 const phaseValue
= `L${phase}-N`;
756 sampledValues
.sampledValue
.push({
757 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'W' },
758 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
759 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
760 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
761 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] },
765 // Current.Import measurand
766 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Current.Import' && this._getConfigurationKey('MeterValuesSampledData').value
.includes('Current.Import')) {
767 // FIXME: factor out powerDivider checks
768 if (Utils
.isUndefined(this._stationInfo
.powerDivider
)) {
769 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
770 logger
.error(errMsg
);
772 } else if (this._stationInfo
.powerDivider
&& this._stationInfo
.powerDivider
<= 0) {
773 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${this._stationInfo.powerDivider}`;
774 logger
.error(errMsg
);
777 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} measurand value`;
778 const currentMeasurandValues
= {} as MeasurandValues
;
780 switch (this._getPowerOutType()) {
782 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(this._getNumberOfPhases(), this._stationInfo
.maxPower
/ this._stationInfo
.powerDivider
, this._getVoltageOut());
783 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
784 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
785 currentMeasurandValues
.L2
= 0;
786 currentMeasurandValues
.L3
= 0;
787 if (this._getNumberOfPhases() === 3) {
788 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
789 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
791 currentMeasurandValues
.all
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / this._getNumberOfPhases(), 2);
795 maxAmperage
= ElectricUtils
.ampTotalFromPower(this._stationInfo
.maxPower
/ this._stationInfo
.powerDivider
, this._getVoltageOut());
796 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
797 currentMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxAmperage
);
801 logger
.error(errMsg
);
804 sampledValues
.sampledValue
.push({
805 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'A' },
806 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
807 measurand
: meterValuesTemplate
[index
].measurand
,
808 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
809 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.all
},
811 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
812 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxAmperage
|| debug
) {
813 logger
.error(`${this._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}`);
815 for (let phase
= 1; this._getNumberOfPhases() === 3 && phase
<= this._getNumberOfPhases(); phase
++) {
816 const phaseValue
= `L${phase}`;
817 sampledValues
.sampledValue
.push({
818 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'A' },
819 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
820 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
821 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
822 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] },
826 // Energy.Active.Import.Register measurand (default)
827 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== 'Energy.Active.Import.Register') {
828 // FIXME: factor out powerDivider checks
829 if (Utils
.isUndefined(this._stationInfo
.powerDivider
)) {
830 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
831 logger
.error(errMsg
);
833 } else if (this._stationInfo
.powerDivider
&& this._stationInfo
.powerDivider
<= 0) {
834 const errMsg
= `${this._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider have zero or below value ${this._stationInfo.powerDivider}`;
835 logger
.error(errMsg
);
838 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
839 const measurandValue
= Utils
.getRandomInt(this._stationInfo
.maxPower
/ (this._stationInfo
.powerDivider
* 3600000) * interval
);
840 // Persist previous value in connector
841 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
842 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
844 connector
.lastEnergyActiveImportRegisterValue
= 0;
847 sampledValues
.sampledValue
.push({
848 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'Wh' },
849 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
850 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
851 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
852 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: connector
.lastEnergyActiveImportRegisterValue
},
854 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
855 const maxConsumption
= Math.round(this._stationInfo
.maxPower
* 3600 / (this._stationInfo
.powerDivider
* interval
));
856 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxConsumption
|| debug
) {
857 logger
.error(`${this._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}`);
859 // Unsupported measurand
861 logger
.info(`${this._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
867 transactionId
: this.getConnector(connectorId
).transactionId
,
868 meterValue
: sampledValues
,
870 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
872 logger
.error(this._logPrefix() + ' Send MeterValues error: ' + error
);
877 sendError(messageId
, err
) {
878 // Check exception: only OCPP error are accepted
879 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
);
881 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
);
884 sendMessage(messageId
, command
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
= '') {
886 // Send a message through wsConnection
887 return new Promise((resolve
, reject
) => {
890 switch (messageType
) {
892 case Constants
.OCPP_JSON_CALL_MESSAGE
:
893 if (this.getEnableStatistics()) {
894 this._statistics
.addMessage(commandName
);
897 this._requests
[messageId
] = [responseCallback
, rejectCallback
, command
];
898 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, command
]);
901 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
902 if (this.getEnableStatistics()) {
903 this._statistics
.addMessage(commandName
);
906 messageToSend
= JSON
.stringify([messageType
, messageId
, command
]);
909 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
910 if (this.getEnableStatistics()) {
911 this._statistics
.addMessage(`Error ${command.code ? command.code : Constants.OCPP_ERROR_GENERIC_ERROR} on ${commandName}`);
914 messageToSend
= JSON
.stringify([messageType
, messageId
, command
.code
? command
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, command
.message
? command
.message
: '', command
.details
? command
.details
: {}]);
917 // Check if wsConnection is ready
918 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
920 this._wsConnection
.send(messageToSend
);
922 // Buffer message until connection is back
923 this._messageQueue
.push(messageToSend
);
926 if (messageType
!== Constants
.OCPP_JSON_CALL_MESSAGE
) {
929 } else if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
930 // Send timeout in case connection is open otherwise wait for ever
931 // FIXME: Handle message on timeout
932 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
);
935 // Function that will receive the request's response
936 function responseCallback(payload
, requestPayload
) {
937 self.handleResponse(commandName
, payload
, requestPayload
);
942 // Function that will receive the request's rejection
943 function rejectCallback(error
: OCPPError
) {
944 logger
.debug(`${self._logPrefix()} Error %j on commandName %s command %j`, error
, commandName
, command
);
945 if (self.getEnableStatistics()) {
946 self._statistics
.addMessage(`Error on commandName ${commandName}`, true);
949 // eslint-disable-next-line no-empty-function
950 self._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
957 handleResponse(commandName
, payload
, requestPayload
) {
958 if (this.getEnableStatistics()) {
959 this._statistics
.addMessage(commandName
, true);
961 const responseCallbackFn
= 'handleResponse' + commandName
;
962 if (typeof this[responseCallbackFn
] === 'function') {
963 this[responseCallbackFn
](payload
, requestPayload
);
965 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
969 handleResponseBootNotification(payload
, requestPayload
) {
970 if (payload
.status === 'Accepted') {
971 this._heartbeatInterval
= payload
.interval
* 1000;
972 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
973 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
974 this._basicStartMessageSequence();
975 } else if (payload
.status === 'Pending') {
976 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
978 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
982 _initTransactionOnConnector(connectorId
) {
983 this.getConnector(connectorId
).transactionStarted
= false;
984 this.getConnector(connectorId
).transactionId
= null;
985 this.getConnector(connectorId
).idTag
= null;
986 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
989 _resetTransactionOnConnector(connectorId
) {
990 this._initTransactionOnConnector(connectorId
);
991 if (this.getConnector(connectorId
).transactionSetInterval
) {
992 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
996 handleResponseStartTransaction(payload
, requestPayload
) {
997 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
998 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
1002 let transactionConnectorId
;
1003 for (const connector
in this._connectors
) {
1004 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
1005 transactionConnectorId
= connector
;
1009 if (!transactionConnectorId
) {
1010 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
1013 if (payload
.idTagInfo
&& payload
.idTagInfo
.status === 'Accepted') {
1014 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
1015 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
1016 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
1017 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1018 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
1019 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
1020 if (this._stationInfo
.powerSharedByConnectors
) {
1021 this._stationInfo
.powerDivider
++;
1023 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
1024 this._startMeterValues(requestPayload
.connectorId
,
1025 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
1027 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status + ', idTag ' + requestPayload
.idTag
);
1028 this._resetTransactionOnConnector(requestPayload
.connectorId
);
1029 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
1033 handleResponseStopTransaction(payload
, requestPayload
) {
1034 let transactionConnectorId
;
1035 for (const connector
in this._connectors
) {
1036 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== requestPayload
.transactionId
) {
1037 transactionConnectorId
= connector
;
1041 if (!transactionConnectorId
) {
1042 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
1045 if (payload
.idTagInfo
&& payload
.idTagInfo
.status === 'Accepted') {
1046 this.sendStatusNotification(transactionConnectorId
, 'Available');
1047 if (this._stationInfo
.powerSharedByConnectors
) {
1048 this._stationInfo
.powerDivider
--;
1050 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
1051 this._resetTransactionOnConnector(transactionConnectorId
);
1053 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status);
1057 handleResponseStatusNotification(payload
, requestPayload
) {
1058 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1061 handleResponseMeterValues(payload
, requestPayload
) {
1062 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1065 handleResponseHeartbeat(payload
, requestPayload
) {
1066 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1069 async handleRequest(messageId
, commandName
, commandPayload
) {
1070 if (this.getEnableStatistics()) {
1071 this._statistics
.addMessage(commandName
, true);
1075 if (typeof this['handleRequest' + commandName
] === 'function') {
1077 // Call the method to build the response
1078 response
= await this['handleRequest' + commandName
](commandPayload
);
1081 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
1082 // Send back response to inform backend
1083 await this.sendError(messageId
, error
);
1087 await this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, 'Not implemented', {}));
1088 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1091 await this.sendMessage(messageId
, response
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
);
1094 // Simulate charging station restart
1095 async handleRequestReset(commandPayload
) {
1096 setImmediate(async () => {
1097 await this.stop(commandPayload
.type + 'Reset');
1098 await Utils
.sleep(this._stationInfo
.resetTime
);
1101 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
1102 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1105 _getConfigurationKey(key
) {
1106 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
1109 _addConfigurationKey(key
, value
, readonly = false, visible
= true, reboot
= false) {
1110 const keyFound
= this._getConfigurationKey(key
);
1112 this._configuration
.configurationKey
.push({
1122 _setConfigurationKeyValue(key
, value
) {
1123 const keyFound
= this._getConfigurationKey(key
);
1125 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1126 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1130 async handleRequestGetConfiguration(commandPayload
) {
1131 const configurationKey
= [];
1132 const unknownKey
= [];
1133 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1134 for (const configuration
of this._configuration
.configurationKey
) {
1135 if (Utils
.isUndefined(configuration
.visible
)) {
1136 configuration
.visible
= true;
1138 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
1140 if (!configuration
.visible
) {
1143 configurationKey
.push({
1144 key
: configuration
.key
,
1145 readonly: configuration
.readonly,
1146 value
: configuration
.value
,
1150 for (const configurationKey
of commandPayload
.key
) {
1151 const keyFound
= this._getConfigurationKey(configurationKey
);
1153 if (Utils
.isUndefined(keyFound
.visible
)) {
1154 keyFound
.visible
= true;
1156 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
1158 if (!keyFound
.visible
) {
1161 configurationKey
.push({
1163 readonly: keyFound
.readonly,
1164 value
: keyFound
.value
,
1167 unknownKey
.push(configurationKey
);
1177 async handleRequestChangeConfiguration(commandPayload
) {
1178 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1180 return { status: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
1181 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly)) {
1182 return Constants
.OCPP_RESPONSE_REJECTED
;
1183 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly)) {
1184 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1185 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1186 let triggerHeartbeatRestart
= false;
1187 if (keyToChange
.key
=== 'HeartBeatInterval') {
1188 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1189 triggerHeartbeatRestart
= true;
1191 if (keyToChange
.key
=== 'HeartbeatInterval') {
1192 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1193 triggerHeartbeatRestart
= true;
1195 if (triggerHeartbeatRestart
) {
1196 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1198 this._stopHeartbeat();
1200 this._startHeartbeat();
1202 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
1203 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
1205 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1209 async handleRequestRemoteStartTransaction(commandPayload
) {
1210 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
1211 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1212 // Check if authorized
1213 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1214 // Authorization successful start transaction
1215 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
);
1216 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1217 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1219 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status + ', idTag ' + commandPayload
.idTag
);
1220 return Constants
.OCPP_RESPONSE_REJECTED
;
1222 // No local authorization check required => start transaction
1223 this.sendStartTransactionWithTimeout(transactionConnectorID
, commandPayload
.idTag
);
1224 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1225 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1228 async handleRequestRemoteStopTransaction(commandPayload
) {
1229 for (const connector
in this._connectors
) {
1230 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== commandPayload
.transactionId
) {
1231 this.sendStopTransaction(commandPayload
.transactionId
);
1232 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1235 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1236 return Constants
.OCPP_RESPONSE_REJECTED
;