1 import { PerformanceObserver
, performance
} from
'perf_hooks';
3 import AutomaticTransactionGenerator from
'./AutomaticTransactionGenerator';
4 import { ChargePointStatus
} from
'../types/ChargePointStatus';
5 import Configuration from
'../utils/Configuration';
6 import Constants from
'../utils/Constants.js';
7 import ElectricUtils from
'../utils/ElectricUtils';
8 import MeasurandValues from
'../types/MeasurandValues';
9 import OCPPError from
'./OcppError.js';
10 import Statistics from
'../utils/Statistics';
11 import Utils from
'../utils/Utils';
12 import WebSocket from
'ws';
13 import crypto from
'crypto';
15 import logger from
'../utils/Logger';
17 export default class ChargingStation
{
18 private _index
: number;
19 private _stationTemplateFile
: string;
21 private _bootNotificationMessage
;
23 private _configuration
;
24 private _connectorsConfigurationHash
: string;
25 private _supervisionUrl
;
26 private _wsConnectionUrl
;
27 private _wsConnection
: WebSocket
;
28 private _isSocketRestart
;
29 private _autoReconnectRetryCount
: number;
30 private _autoReconnectMaxRetries
: number;
31 private _autoReconnectTimeout
: number;
33 private _messageQueue
: any[];
34 private _automaticTransactionGeneration
: AutomaticTransactionGenerator
;
35 private _authorizedTags
: string[];
36 private _heartbeatInterval
: number;
37 private _heartbeatSetInterval
;
38 private _statistics
: Statistics
;
39 private _performanceObserver
: PerformanceObserver
;
41 constructor(index
: number, stationTemplateFile
: string) {
43 this._stationTemplateFile
= stationTemplateFile
;
44 this._connectors
= {};
47 this._isSocketRestart
= false;
48 this._autoReconnectRetryCount
= 0;
49 this._autoReconnectMaxRetries
= Configuration
.getAutoReconnectMaxRetries(); // -1 for unlimited
50 this._autoReconnectTimeout
= Configuration
.getAutoReconnectTimeout() * 1000; // Ms, zero for disabling
53 this._messageQueue
= [];
55 this._authorizedTags
= this._loadAndGetAuthorizedTags();
58 _getStationName(stationTemplate
): string {
59 return stationTemplate
.fixedName
? stationTemplate
.baseName
: stationTemplate
.baseName
+ '-' + ('000000000' + this._index
).substr(('000000000' + this._index
).length
- 4);
63 let stationTemplateFromFile
;
66 const fileDescriptor
= fs
.openSync(this._stationTemplateFile
, 'r');
67 stationTemplateFromFile
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
68 fs
.closeSync(fileDescriptor
);
70 logger
.error('Template file ' + this._stationTemplateFile
+ ' loading error: ' + error
);
73 const stationTemplate
= stationTemplateFromFile
|| {};
74 if (!Utils
.isEmptyArray(stationTemplateFromFile
.power
)) {
75 stationTemplate
.maxPower
= stationTemplateFromFile
.power
[Math.floor(Math.random() * stationTemplateFromFile
.power
.length
)];
77 stationTemplate
.maxPower
= stationTemplateFromFile
.power
;
79 stationTemplate
.name
= this._getStationName(stationTemplateFromFile
);
80 stationTemplate
.resetTime
= stationTemplateFromFile
.resetTime
? stationTemplateFromFile
.resetTime
* 1000 : Constants
.CHARGING_STATION_DEFAULT_RESET_TIME
;
81 return stationTemplate
;
85 return this._stationInfo
;
89 this._stationInfo
= this._buildStationInfo();
90 this._bootNotificationMessage
= {
91 chargePointModel
: this._stationInfo
.chargePointModel
,
92 chargePointVendor
: this._stationInfo
.chargePointVendor
,
93 ...!Utils
.isUndefined(this._stationInfo
.chargeBoxSerialNumberPrefix
) && { chargeBoxSerialNumber
: this._stationInfo
.chargeBoxSerialNumberPrefix
},
94 ...!Utils
.isUndefined(this._stationInfo
.firmwareVersion
) && { firmwareVersion
: this._stationInfo
.firmwareVersion
},
96 this._configuration
= this._getConfiguration();
97 this._supervisionUrl
= this._getSupervisionURL();
98 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
99 // Build connectors if needed
100 const maxConnectors
= this._getMaxNumberOfConnectors();
101 if (maxConnectors
<= 0) {
102 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
104 const templateMaxConnectors
= this._getTemplateMaxNumberOfConnectors();
105 if (templateMaxConnectors
<= 0) {
106 logger
.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`);
109 if (maxConnectors
> (this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) && !Utils
.convertToBoolean(this._stationInfo
.randomConnectors
)) {
110 logger
.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
111 this._stationInfo
.randomConnectors
= true;
113 const connectorsConfigHash
= crypto
.createHash('sha256').update(JSON
.stringify(this._stationInfo
.Connectors
) + maxConnectors
.toString()).digest('hex');
114 // FIXME: Handle shrinking the number of connectors
115 if (!this._connectors
|| (this._connectors
&& this._connectorsConfigurationHash
!== connectorsConfigHash
)) {
116 this._connectorsConfigurationHash
= connectorsConfigHash
;
117 // Add connector Id 0
118 let lastConnector
= '0';
119 for (lastConnector
in this._stationInfo
.Connectors
) {
120 if (Utils
.convertToInt(lastConnector
) === 0 && Utils
.convertToBoolean(this._stationInfo
.useConnectorId0
) && this._stationInfo
.Connectors
[lastConnector
]) {
121 this._connectors
[lastConnector
] = Utils
.cloneObject(this._stationInfo
.Connectors
[lastConnector
]);
124 // Generate all connectors
125 if ((this._stationInfo
.Connectors
[0] ? templateMaxConnectors
- 1 : templateMaxConnectors
) > 0) {
126 for (let index
= 1; index
<= maxConnectors
; index
++) {
127 const randConnectorID
= Utils
.convertToBoolean(this._stationInfo
.randomConnectors
) ? Utils
.getRandomInt(Utils
.convertToInt(lastConnector
), 1) : index
;
128 this._connectors
[index
] = Utils
.cloneObject(this._stationInfo
.Connectors
[randConnectorID
]);
132 // Avoid duplication of connectors related information
133 delete this._stationInfo
.Connectors
;
134 // Initialize transaction attributes on connectors
135 for (const connector
in this._connectors
) {
136 if (!this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
137 this._initTransactionOnConnector(connector
);
141 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors(), true);
142 if (!this._getConfigurationKey('MeterValuesSampledData')) {
143 this._addConfigurationKey('MeterValuesSampledData', 'Energy.Active.Import.Register');
145 this._stationInfo
.powerDivider
= this._getPowerDivider();
146 if (this.getEnableStatistics()) {
147 this._statistics
= Statistics
.getInstance();
148 this._statistics
.objName
= this._stationInfo
.name
;
149 this._performanceObserver
= new PerformanceObserver((list
) => {
150 const entry
= list
.getEntries()[0];
151 this._statistics
.logPerformance(entry
, 'ChargingStation');
152 this._performanceObserver
.disconnect();
158 return this._connectors
;
161 get
statistics(): Statistics
{
162 return this._statistics
;
165 _logPrefix(): string {
166 return Utils
.logPrefix(` ${this._stationInfo.name}:`);
169 _getConfiguration() {
170 return this._stationInfo
.Configuration
? this._stationInfo
.Configuration
: {};
173 _getAuthorizationFile() : string {
174 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
177 _loadAndGetAuthorizedTags(): string[] {
178 let authorizedTags
: string[] = [];
179 const authorizationFile
= this._getAuthorizationFile();
180 if (authorizationFile
) {
182 // Load authorization file
183 const fileDescriptor
= fs
.openSync(authorizationFile
, 'r');
184 authorizedTags
= JSON
.parse(fs
.readFileSync(fileDescriptor
, 'utf8'));
185 fs
.closeSync(fileDescriptor
);
187 logger
.error(this._logPrefix() + ' Authorization file ' + authorizationFile
+ ' loading error: ' + error
);
191 logger
.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile
);
193 return authorizedTags
;
196 getRandomTagId(): string {
197 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
198 return this._authorizedTags
[index
];
201 hasAuthorizedTags(): boolean {
202 return !Utils
.isEmptyArray(this._authorizedTags
);
205 getEnableStatistics(): boolean {
206 return !Utils
.isUndefined(this._stationInfo
.enableStatistics
) ? Utils
.convertToBoolean(this._stationInfo
.enableStatistics
) : true;
209 _getNumberOfPhases(): number {
210 switch (this._getPowerOutType()) {
212 return !Utils
.isUndefined(this._stationInfo
.numberOfPhases
) ? Utils
.convertToInt(this._stationInfo
.numberOfPhases
) : 3;
218 _getNumberOfRunningTransactions(): number {
220 for (const connector
in this._connectors
) {
221 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
228 _getPowerDivider(): number {
229 let powerDivider
= this._getNumberOfConnectors();
230 if (this._stationInfo
.powerSharedByConnectors
) {
231 powerDivider
= this._getNumberOfRunningTransactions();
236 getConnector(id
: number) {
237 return this._connectors
[id
];
240 _getTemplateMaxNumberOfConnectors(): number {
241 return Object.keys(this._stationInfo
.Connectors
).length
;
244 _getMaxNumberOfConnectors(): number {
245 let maxConnectors
= 0;
246 if (!Utils
.isEmptyArray(this._stationInfo
.numberOfConnectors
)) {
247 // Distribute evenly the number of connectors
248 maxConnectors
= this._stationInfo
.numberOfConnectors
[(this._index
- 1) % this._stationInfo
.numberOfConnectors
.length
];
249 } else if (!Utils
.isUndefined(this._stationInfo
.numberOfConnectors
)) {
250 maxConnectors
= this._stationInfo
.numberOfConnectors
;
252 maxConnectors
= this._stationInfo
.Connectors
[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
254 return maxConnectors
;
257 _getNumberOfConnectors(): number {
258 return this._connectors
[0] ? Object.keys(this._connectors
).length
- 1 : Object.keys(this._connectors
).length
;
261 _getVoltageOut(): number {
262 const errMsg
= `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
263 let defaultVoltageOut
;
264 switch (this._getPowerOutType()) {
266 defaultVoltageOut
= 230;
269 defaultVoltageOut
= 400;
272 logger
.error(errMsg
);
275 return !Utils
.isUndefined(this._stationInfo
.voltageOut
) ? Utils
.convertToInt(this._stationInfo
.voltageOut
) : defaultVoltageOut
;
278 _getPowerOutType(): string {
279 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: 'AC';
282 _getSupervisionURL(): string {
283 const supervisionUrls
= Utils
.cloneObject(this._stationInfo
.supervisionURL
? this._stationInfo
.supervisionURL
: Configuration
.getSupervisionURLs());
285 if (!Utils
.isEmptyArray(supervisionUrls
)) {
286 if (Configuration
.getDistributeStationToTenantEqually()) {
287 indexUrl
= this._index
% supervisionUrls
.length
;
290 indexUrl
= Math.floor(Math.random() * supervisionUrls
.length
);
292 return supervisionUrls
[indexUrl
];
294 return supervisionUrls
;
297 _getAuthorizeRemoteTxRequests(): boolean {
298 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
299 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
302 _getLocalAuthListEnabled(): boolean {
303 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
304 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
307 _startMessageSequence(): void {
309 this._startHeartbeat();
310 // Initialize connectors status
311 for (const connector
in this._connectors
) {
312 if (!this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
313 if (!this.getConnector(Utils
.convertToInt(connector
)).status && this.getConnector(Utils
.convertToInt(connector
)).bootStatus
) {
314 this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
315 } else if (this.getConnector(Utils
.convertToInt(connector
)).status) {
316 this.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).status);
318 this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.AVAILABLE
);
321 this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.CHARGING
);
325 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
)) {
326 if (!this._automaticTransactionGeneration
) {
327 this._automaticTransactionGeneration
= new AutomaticTransactionGenerator(this);
329 if (this._automaticTransactionGeneration
.timeToStop
) {
330 this._automaticTransactionGeneration
.start();
333 if (this.getEnableStatistics()) {
334 this._statistics
.start();
338 async _stopMessageSequence(reason
= ''): Promise
<void> {
340 this._stopHeartbeat();
342 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
343 this._automaticTransactionGeneration
&&
344 !this._automaticTransactionGeneration
.timeToStop
) {
345 await this._automaticTransactionGeneration
.stop(reason
);
347 for (const connector
in this._connectors
) {
348 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
349 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
355 _startHeartbeat(): void {
356 if (this._heartbeatInterval
&& this._heartbeatInterval
> 0 && !this._heartbeatSetInterval
) {
357 this._heartbeatSetInterval
= setInterval(() => {
358 this.sendHeartbeat();
359 }, this._heartbeatInterval
);
360 logger
.info(this._logPrefix() + ' Heartbeat started every ' + this._heartbeatInterval
.toString() + 'ms');
362 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval}ms, not starting the heartbeat`);
366 _stopHeartbeat(): void {
367 if (this._heartbeatSetInterval
) {
368 clearInterval(this._heartbeatSetInterval
);
369 this._heartbeatSetInterval
= null;
373 _startAuthorizationFileMonitoring(): void {
374 // eslint-disable-next-line @typescript-eslint/no-unused-vars
375 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
377 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
378 // Initialize _authorizedTags
379 this._authorizedTags
= this._loadAndGetAuthorizedTags();
381 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
386 _startStationTemplateFileMonitoring(): void {
387 // eslint-disable-next-line @typescript-eslint/no-unused-vars
388 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
390 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
393 if (!Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
394 this._automaticTransactionGeneration
) {
395 this._automaticTransactionGeneration
.stop().catch(() => {});
398 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
403 _startMeterValues(connectorId
: number, interval
: number): void {
404 if (!this.getConnector(connectorId
).transactionStarted
) {
405 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
407 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
408 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
412 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
413 if (this.getEnableStatistics()) {
414 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
415 this._performanceObserver
.observe({
416 entryTypes
: ['function'],
418 await sendMeterValues(connectorId
, interval
, this);
420 await this.sendMeterValues(connectorId
, interval
, this);
424 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
429 if (!this._wsConnectionUrl
) {
430 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
432 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
433 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
434 // Monitor authorization file
435 this._startAuthorizationFileMonitoring();
436 // Monitor station template file
437 this._startStationTemplateFileMonitoring();
438 // Handle Socket incoming messages
439 this._wsConnection
.on('message', this.onMessage
.bind(this));
440 // Handle Socket error
441 this._wsConnection
.on('error', this.onError
.bind(this));
442 // Handle Socket close
443 this._wsConnection
.on('close', this.onClose
.bind(this));
444 // Handle Socket opening connection
445 this._wsConnection
.on('open', this.onOpen
.bind(this));
446 // Handle Socket ping
447 this._wsConnection
.on('ping', this.onPing
.bind(this));
450 async stop(reason
= ''): Promise
<void> {
452 await this._stopMessageSequence();
453 // eslint-disable-next-line guard-for-in
454 for (const connector
in this._connectors
) {
455 await this.sendStatusNotification(Utils
.convertToInt(connector
), ChargePointStatus
.UNAVAILABLE
);
457 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
458 this._wsConnection
.close();
462 _reconnect(error
): void {
463 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
464 // Stop the ATG if needed
465 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
466 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
467 this._automaticTransactionGeneration
&&
468 !this._automaticTransactionGeneration
.timeToStop
) {
469 this._automaticTransactionGeneration
.stop();
472 this._stopHeartbeat();
473 if (this._autoReconnectTimeout
!== 0 &&
474 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
475 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
476 this._autoReconnectRetryCount
++;
478 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
480 }, this._autoReconnectTimeout
);
481 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
482 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
487 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
488 if (!this._isSocketRestart
) {
489 // Send BootNotification
490 this.sendBootNotification();
492 if (this._isSocketRestart
) {
493 this._startMessageSequence();
494 if (!Utils
.isEmptyArray(this._messageQueue
)) {
495 this._messageQueue
.forEach((message
) => {
496 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
497 this._wsConnection
.send(message
);
502 this._autoReconnectRetryCount
= 0;
503 this._isSocketRestart
= false;
506 onError(error
): void {
509 this._isSocketRestart
= true;
510 this._reconnect(error
);
513 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
518 onClose(error
): void {
520 case 1000: // Normal close
522 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
523 this._autoReconnectRetryCount
= 0;
525 default: // Abnormal close
526 this._isSocketRestart
= true;
527 this._reconnect(error
);
533 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
536 async onMessage(message
) : Promise
<void> {
537 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
540 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
542 // Check the Type of message
543 switch (messageType
) {
545 case Constants
.OCPP_JSON_CALL_MESSAGE
:
546 if (this.getEnableStatistics()) {
547 this._statistics
.addMessage(commandName
, messageType
);
550 await this.handleRequest(messageId
, commandName
, commandPayload
);
553 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
555 // eslint-disable-next-line no-case-declarations
556 let responseCallback
; let requestPayload
;
557 if (Utils
.isIterable(this._requests
[messageId
])) {
558 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
560 throw new Error(`Response request for message id ${messageId} is not iterable`);
562 if (!responseCallback
) {
564 throw new Error(`Response request for unknown message id ${messageId}`);
566 delete this._requests
[messageId
];
567 responseCallback(commandName
, requestPayload
);
570 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
571 if (!this._requests
[messageId
]) {
573 throw new Error(`Error request for unknown message id ${messageId}`);
575 // eslint-disable-next-line no-case-declarations
577 if (Utils
.isIterable(this._requests
[messageId
])) {
578 [, rejectCallback
] = this._requests
[messageId
];
580 throw new Error(`Error request for message id ${messageId} is not iterable`);
582 delete this._requests
[messageId
];
583 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
587 // eslint-disable-next-line no-case-declarations
588 const errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
589 logger
.error(errMsg
);
590 throw new Error(errMsg
);
594 logger
.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
596 await this.sendError(messageId
, error
, commandName
);
600 async sendHeartbeat(): Promise
<void> {
603 currentTime
: new Date().toISOString(),
605 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
607 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
612 async sendBootNotification(): Promise
<void> {
614 await this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
616 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
621 async sendStatusNotification(connectorId
: number, status: ChargePointStatus
, errorCode
= 'NoError'): Promise
<void> {
622 this.getConnector(connectorId
).status = status;
629 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
631 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
636 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<unknown
> {
640 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: '' },
642 timestamp
: new Date().toISOString(),
644 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
646 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
651 async sendStopTransaction(transactionId
: number, reason
= ''): Promise
<void> {
656 timestamp
: new Date().toISOString(),
657 ...reason
&& { reason
},
659 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
661 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
666 // eslint-disable-next-line consistent-this
667 async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
669 const sampledValues
= {
670 timestamp
: new Date().toISOString(),
673 const meterValuesTemplate
= self.getConnector(connectorId
).MeterValues
;
674 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
675 const connector
= self.getConnector(connectorId
);
677 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
678 sampledValues
.sampledValue
.push({
679 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'Percent' },
680 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
681 measurand
: meterValuesTemplate
[index
].measurand
,
682 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: 'EV' },
683 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100) },
685 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
686 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> 100 || debug
) {
687 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`);
690 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
691 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
692 sampledValues
.sampledValue
.push({
693 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'V' },
694 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
695 measurand
: meterValuesTemplate
[index
].measurand
,
696 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
697 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
},
699 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
700 const voltageValue
= sampledValues
.sampledValue
[sampledValues
.sampledValue
.length
- 1].value
;
702 if (voltageValue
>= 0 && voltageValue
<= 250) {
703 phaseValue
= `L${phase}-N`;
704 } else if (voltageValue
> 250) {
705 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
707 sampledValues
.sampledValue
.push({
708 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'V' },
709 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
710 measurand
: meterValuesTemplate
[index
].measurand
,
711 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
712 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
},
716 // Power.Active.Import measurand
717 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Power.Active.Import' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('Power.Active.Import')) {
718 // FIXME: factor out powerDivider checks
719 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
720 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
721 logger
.error(errMsg
);
723 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
724 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}`;
725 logger
.error(errMsg
);
728 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`;
729 const powerMeasurandValues
= {} as MeasurandValues
;
730 const maxPower
= Math.round(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
);
731 const maxPowerPerPhase
= Math.round((self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
) / self._getNumberOfPhases());
732 switch (self._getPowerOutType()) {
734 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
735 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
736 powerMeasurandValues
.L2
= 0;
737 powerMeasurandValues
.L3
= 0;
738 if (self._getNumberOfPhases() === 3) {
739 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
740 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
742 powerMeasurandValues
.all
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
746 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
747 powerMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxPower
);
751 logger
.error(errMsg
);
754 sampledValues
.sampledValue
.push({
755 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'W' },
756 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
757 measurand
: meterValuesTemplate
[index
].measurand
,
758 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
759 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.all
},
761 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
762 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxPower
|| debug
) {
763 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}`);
765 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
766 const phaseValue
= `L${phase}-N`;
767 sampledValues
.sampledValue
.push({
768 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'W' },
769 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
770 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
771 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
772 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] },
776 // Current.Import measurand
777 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Current.Import' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('Current.Import')) {
778 // FIXME: factor out powerDivider checks
779 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
780 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
781 logger
.error(errMsg
);
783 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
784 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}`;
785 logger
.error(errMsg
);
788 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`;
789 const currentMeasurandValues
= {} as MeasurandValues
;
791 switch (self._getPowerOutType()) {
793 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
794 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
795 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
796 currentMeasurandValues
.L2
= 0;
797 currentMeasurandValues
.L3
= 0;
798 if (self._getNumberOfPhases() === 3) {
799 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
800 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
802 currentMeasurandValues
.all
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
806 maxAmperage
= ElectricUtils
.ampTotalFromPower(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
807 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
808 currentMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxAmperage
);
812 logger
.error(errMsg
);
815 sampledValues
.sampledValue
.push({
816 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'A' },
817 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
818 measurand
: meterValuesTemplate
[index
].measurand
,
819 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
820 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.all
},
822 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
823 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxAmperage
|| debug
) {
824 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}`);
826 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
827 const phaseValue
= `L${phase}`;
828 sampledValues
.sampledValue
.push({
829 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'A' },
830 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
831 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
832 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
833 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] },
837 // Energy.Active.Import.Register measurand (default)
838 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== 'Energy.Active.Import.Register') {
839 // FIXME: factor out powerDivider checks
840 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
841 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
842 logger
.error(errMsg
);
844 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
845 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}`;
846 logger
.error(errMsg
);
849 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
850 const measurandValue
= Utils
.getRandomInt(self._stationInfo
.maxPower
/ (self._stationInfo
.powerDivider
* 3600000) * interval
);
851 // Persist previous value in connector
852 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
853 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
855 connector
.lastEnergyActiveImportRegisterValue
= 0;
858 sampledValues
.sampledValue
.push({
859 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'Wh' },
860 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
861 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
862 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
863 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: connector
.lastEnergyActiveImportRegisterValue
},
865 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
866 const maxConsumption
= Math.round(self._stationInfo
.maxPower
* 3600 / (self._stationInfo
.powerDivider
* interval
));
867 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxConsumption
|| debug
) {
868 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}`);
870 // Unsupported measurand
872 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
878 transactionId
: self.getConnector(connectorId
).transactionId
,
879 meterValue
: sampledValues
,
881 await self.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
883 logger
.error(self._logPrefix() + ' Send MeterValues error: ' + error
);
888 async sendError(messageId
, err
: Error|OCPPError
, commandName
) {
889 // Check exception type: only OCPP error are accepted
890 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
, err
.stack
&& err
.stack
);
892 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
, commandName
);
895 async sendMessage(messageId
, commandParams
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
: string) {
896 // eslint-disable-next-line @typescript-eslint/no-this-alias
898 // Send a message through wsConnection
899 return new Promise((resolve
, reject
) => {
902 switch (messageType
) {
904 case Constants
.OCPP_JSON_CALL_MESSAGE
:
906 this._requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
];
907 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
910 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
912 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
915 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
916 // Build Error Message
917 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
920 // Check if wsConnection is ready
921 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
922 if (this.getEnableStatistics()) {
923 this._statistics
.addMessage(commandName
, messageType
);
926 this._wsConnection
.send(messageToSend
);
929 // Handle dups in buffer
930 for (const message
of this._messageQueue
) {
932 if (JSON
.stringify(messageToSend
) === JSON
.stringify(message
)) {
939 this._messageQueue
.push(messageToSend
);
942 return rejectCallback(new OCPPError(commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: `Web socket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams
.details
? commandParams
.details
: {}));
945 if (messageType
=== Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
) {
948 } else if (messageType
=== Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
) {
950 setTimeout(() => rejectCallback(new OCPPError(commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: `Timeout for message id '${messageId}' with content '${messageToSend}'`, commandParams
.details
? commandParams
.details
: {})), Constants
.OCPP_SOCKET_TIMEOUT
);
953 // Function that will receive the request's response
954 function responseCallback(payload
, requestPayload
): void {
955 if (self.getEnableStatistics()) {
956 self._statistics
.addMessage(commandName
, messageType
);
959 self.handleResponse(commandName
, payload
, requestPayload
);
963 // Function that will receive the request's rejection
964 function rejectCallback(error
: OCPPError
): void {
965 if (self.getEnableStatistics()) {
966 self._statistics
.addMessage(commandName
, messageType
);
968 logger
.debug(`${self._logPrefix()} Error %j occurred when calling command %s with parameters %j`, error
, commandName
, commandParams
);
970 // eslint-disable-next-line no-empty-function
971 self._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
978 handleResponse(commandName
: string, payload
, requestPayload
) {
979 const responseCallbackFn
= 'handleResponse' + commandName
;
980 if (typeof this[responseCallbackFn
] === 'function') {
981 this[responseCallbackFn
](payload
, requestPayload
);
983 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
987 handleResponseBootNotification(payload
, requestPayload
) {
988 if (payload
.status === 'Accepted') {
989 this._heartbeatInterval
= payload
.interval
* 1000;
990 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
991 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
992 this._startMessageSequence();
993 } else if (payload
.status === 'Pending') {
994 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
996 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
1000 _initTransactionOnConnector(connectorId
) {
1001 this.getConnector(connectorId
).transactionStarted
= false;
1002 this.getConnector(connectorId
).transactionId
= null;
1003 this.getConnector(connectorId
).idTag
= null;
1004 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
1007 _resetTransactionOnConnector(connectorId
) {
1008 this._initTransactionOnConnector(connectorId
);
1009 if (this.getConnector(connectorId
).transactionSetInterval
) {
1010 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
1014 handleResponseStartTransaction(payload
, requestPayload
) {
1015 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
1016 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
1020 let transactionConnectorId
;
1021 for (const connector
in this._connectors
) {
1022 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
1023 transactionConnectorId
= connector
;
1027 if (!transactionConnectorId
) {
1028 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
1031 if (payload
.idTagInfo
&& payload
.idTagInfo
.status === 'Accepted') {
1032 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
1033 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
1034 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
1035 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1036 this.sendStatusNotification(requestPayload
.connectorId
, ChargePointStatus
.CHARGING
);
1037 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
1038 if (this._stationInfo
.powerSharedByConnectors
) {
1039 this._stationInfo
.powerDivider
++;
1041 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
1042 this._startMeterValues(requestPayload
.connectorId
,
1043 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
1045 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status + ', idTag ' + requestPayload
.idTag
);
1046 this._resetTransactionOnConnector(requestPayload
.connectorId
);
1047 this.sendStatusNotification(requestPayload
.connectorId
, ChargePointStatus
.AVAILABLE
);
1051 handleResponseStopTransaction(payload
, requestPayload
) {
1052 let transactionConnectorId
;
1053 for (const connector
in this._connectors
) {
1054 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== requestPayload
.transactionId
) {
1055 transactionConnectorId
= connector
;
1059 if (!transactionConnectorId
) {
1060 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
1063 if (payload
.idTagInfo
&& payload
.idTagInfo
.status === 'Accepted') {
1064 this.sendStatusNotification(transactionConnectorId
, ChargePointStatus
.AVAILABLE
);
1065 if (this._stationInfo
.powerSharedByConnectors
) {
1066 this._stationInfo
.powerDivider
--;
1068 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
1069 this._resetTransactionOnConnector(transactionConnectorId
);
1071 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status);
1075 handleResponseStatusNotification(payload
, requestPayload
) {
1076 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1079 handleResponseMeterValues(payload
, requestPayload
) {
1080 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1083 handleResponseHeartbeat(payload
, requestPayload
) {
1084 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1087 async handleRequest(messageId
, commandName
, commandPayload
) {
1090 if (typeof this['handleRequest' + commandName
] === 'function') {
1092 // Call the method to build the response
1093 response
= await this['handleRequest' + commandName
](commandPayload
);
1096 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
1097 // Send back response to inform backend
1098 await this.sendError(messageId
, error
, commandName
);
1103 await this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1104 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1107 await this.sendMessage(messageId
, response
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
);
1110 // Simulate charging station restart
1111 async handleRequestReset(commandPayload
) {
1112 setImmediate(async () => {
1113 await this.stop(commandPayload
.type + 'Reset');
1114 await Utils
.sleep(this._stationInfo
.resetTime
);
1117 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
1118 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1121 _getConfigurationKey(key
) {
1122 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
1125 _addConfigurationKey(key
, value
, readonly = false, visible
= true, reboot
= false) {
1126 const keyFound
= this._getConfigurationKey(key
);
1128 this._configuration
.configurationKey
.push({
1138 _setConfigurationKeyValue(key
, value
) {
1139 const keyFound
= this._getConfigurationKey(key
);
1141 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1142 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1146 async handleRequestGetConfiguration(commandPayload
) {
1147 const configurationKey
= [];
1148 const unknownKey
= [];
1149 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1150 for (const configuration
of this._configuration
.configurationKey
) {
1151 if (Utils
.isUndefined(configuration
.visible
)) {
1152 configuration
.visible
= true;
1154 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
1156 if (!configuration
.visible
) {
1159 configurationKey
.push({
1160 key
: configuration
.key
,
1161 readonly: configuration
.readonly,
1162 value
: configuration
.value
,
1166 for (const configurationKey
of commandPayload
.key
) {
1167 const keyFound
= this._getConfigurationKey(configurationKey
);
1169 if (Utils
.isUndefined(keyFound
.visible
)) {
1170 keyFound
.visible
= true;
1172 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
1174 if (!keyFound
.visible
) {
1177 configurationKey
.push({
1179 readonly: keyFound
.readonly,
1180 value
: keyFound
.value
,
1183 unknownKey
.push(configurationKey
);
1193 async handleRequestChangeConfiguration(commandPayload
) {
1194 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1196 return { status: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
1197 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly)) {
1198 return Constants
.OCPP_RESPONSE_REJECTED
;
1199 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly)) {
1200 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1201 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1202 let triggerHeartbeatRestart
= false;
1203 if (keyToChange
.key
=== 'HeartBeatInterval') {
1204 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1205 triggerHeartbeatRestart
= true;
1207 if (keyToChange
.key
=== 'HeartbeatInterval') {
1208 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1209 triggerHeartbeatRestart
= true;
1211 if (triggerHeartbeatRestart
) {
1212 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1214 this._stopHeartbeat();
1216 this._startHeartbeat();
1218 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
1219 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
1221 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1225 async handleRequestRemoteStartTransaction(commandPayload
) {
1226 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
1227 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1228 // Check if authorized
1229 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1230 // Authorization successful start transaction
1231 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1232 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1233 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1235 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status + ', idTag ' + commandPayload
.idTag
);
1236 return Constants
.OCPP_RESPONSE_REJECTED
;
1238 // No local authorization check required => start transaction
1239 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1240 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1241 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1244 async handleRequestRemoteStopTransaction(commandPayload
) {
1245 for (const connector
in this._connectors
) {
1246 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== commandPayload
.transactionId
) {
1247 await this.sendStopTransaction(commandPayload
.transactionId
);
1248 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1251 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1252 return Constants
.OCPP_RESPONSE_REJECTED
;