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
: string;
20 private _bootNotificationMessage
;
22 private _configuration
;
23 private _connectorsConfigurationHash
: string;
24 private _supervisionUrl
;
25 private _wsConnectionUrl
;
26 private _wsConnection
: WebSocket
;
27 private _isSocketRestart
;
28 private _autoReconnectRetryCount
: number;
29 private _autoReconnectMaxRetries
: number;
30 private _autoReconnectTimeout
: number;
32 private _messageQueue
: any[];
33 private _automaticTransactionGeneration
: AutomaticTransactionGenerator
;
34 private _authorizedTags
: string[];
35 private _heartbeatInterval
: number;
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() : string {
173 return this._stationInfo
.authorizationFile
&& this._stationInfo
.authorizationFile
;
176 _loadAndGetAuthorizedTags(): string[] {
177 let authorizedTags
: string[] = [];
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
;
195 getRandomTagId(): string {
196 const index
= Math.floor(Math.random() * this._authorizedTags
.length
);
197 return this._authorizedTags
[index
];
200 hasAuthorizedTags(): boolean {
201 return !Utils
.isEmptyArray(this._authorizedTags
);
204 getEnableStatistics(): boolean {
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(): number {
219 for (const connector
in this._connectors
) {
220 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
227 _getPowerDivider(): number {
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(): number {
240 return Object.keys(this._stationInfo
.Connectors
).length
;
243 _getMaxNumberOfConnectors(): number {
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
;
260 _getVoltageOut(): number {
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
;
277 _getPowerOutType(): string {
278 return !Utils
.isUndefined(this._stationInfo
.powerOutType
) ? this._stationInfo
.powerOutType
: 'AC';
281 _getSupervisionURL(): string {
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(): boolean {
297 const authorizeRemoteTxRequests
= this._getConfigurationKey('AuthorizeRemoteTxRequests');
298 return authorizeRemoteTxRequests
? Utils
.convertToBoolean(authorizeRemoteTxRequests
.value
) : false;
301 _getLocalAuthListEnabled(): boolean {
302 const localAuthListEnabled
= this._getConfigurationKey('LocalAuthListEnabled');
303 return localAuthListEnabled
? Utils
.convertToBoolean(localAuthListEnabled
.value
) : false;
306 _startMessageSequence(): 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.sendStatusNotification(Utils
.convertToInt(connector
), this.getConnector(Utils
.convertToInt(connector
)).bootStatus
);
315 this.sendStatusNotification(Utils
.convertToInt(connector
), 'Available');
318 this.sendStatusNotification(Utils
.convertToInt(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 async _stopMessageSequence(reason
= ''): Promise
<void> {
337 this._stopHeartbeat();
339 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
340 this._automaticTransactionGeneration
&&
341 !this._automaticTransactionGeneration
.timeToStop
) {
342 await this._automaticTransactionGeneration
.stop(reason
);
344 for (const connector
in this._connectors
) {
345 if (this.getConnector(Utils
.convertToInt(connector
)).transactionStarted
) {
346 await this.sendStopTransaction(this.getConnector(Utils
.convertToInt(connector
)).transactionId
, reason
);
352 _startHeartbeat(): void {
353 if (this._heartbeatInterval
&& this._heartbeatInterval
> 0 && !this._heartbeatSetInterval
) {
354 this._heartbeatSetInterval
= setInterval(() => {
355 this.sendHeartbeat();
356 }, this._heartbeatInterval
);
357 logger
.info(this._logPrefix() + ' Heartbeat started every ' + this._heartbeatInterval
.toString() + 'ms');
359 logger
.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval}ms, not starting the heartbeat`);
363 _stopHeartbeat(): void {
364 if (this._heartbeatSetInterval
) {
365 clearInterval(this._heartbeatSetInterval
);
366 this._heartbeatSetInterval
= null;
370 _startAuthorizationFileMonitoring(): void {
371 // eslint-disable-next-line @typescript-eslint/no-unused-vars
372 fs
.watchFile(this._getAuthorizationFile(), (current
, previous
) => {
374 logger
.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
375 // Initialize _authorizedTags
376 this._authorizedTags
= this._loadAndGetAuthorizedTags();
378 logger
.error(this._logPrefix() + ' Authorization file monitoring error: ' + error
);
383 _startStationTemplateFileMonitoring(): void {
384 // eslint-disable-next-line @typescript-eslint/no-unused-vars
385 fs
.watchFile(this._stationTemplateFile
, (current
, previous
) => {
387 logger
.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile
+ ' have changed, reload');
390 if (!Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
391 this._automaticTransactionGeneration
) {
392 this._automaticTransactionGeneration
.stop().catch(() => {});
395 logger
.error(this._logPrefix() + ' Charging station template file monitoring error: ' + error
);
400 _startMeterValues(connectorId
: number, interval
: number): void {
401 if (!this.getConnector(connectorId
).transactionStarted
) {
402 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
404 } else if (this.getConnector(connectorId
).transactionStarted
&& !this.getConnector(connectorId
).transactionId
) {
405 logger
.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
409 this.getConnector(connectorId
).transactionSetInterval
= setInterval(async (): Promise
<void> => {
410 if (this.getEnableStatistics()) {
411 const sendMeterValues
= performance
.timerify(this.sendMeterValues
);
412 this._performanceObserver
.observe({
413 entryTypes
: ['function'],
415 await sendMeterValues(connectorId
, interval
, this);
417 await this.sendMeterValues(connectorId
, interval
, this);
421 logger
.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${interval}ms, not sending MeterValues`);
426 if (!this._wsConnectionUrl
) {
427 this._wsConnectionUrl
= this._supervisionUrl
+ '/' + this._stationInfo
.name
;
429 this._wsConnection
= new WebSocket(this._wsConnectionUrl
, 'ocpp' + Constants
.OCPP_VERSION_16
);
430 logger
.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl
);
431 // Monitor authorization file
432 this._startAuthorizationFileMonitoring();
433 // Monitor station template file
434 this._startStationTemplateFileMonitoring();
435 // Handle Socket incoming messages
436 this._wsConnection
.on('message', this.onMessage
.bind(this));
437 // Handle Socket error
438 this._wsConnection
.on('error', this.onError
.bind(this));
439 // Handle Socket close
440 this._wsConnection
.on('close', this.onClose
.bind(this));
441 // Handle Socket opening connection
442 this._wsConnection
.on('open', this.onOpen
.bind(this));
443 // Handle Socket ping
444 this._wsConnection
.on('ping', this.onPing
.bind(this));
447 async stop(reason
= ''): Promise
<void> {
449 await this._stopMessageSequence();
450 // eslint-disable-next-line guard-for-in
451 for (const connector
in this._connectors
) {
452 await this.sendStatusNotification(Utils
.convertToInt(connector
), 'Unavailable');
454 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
455 this._wsConnection
.close();
459 _reconnect(error
): void {
460 logger
.error(this._logPrefix() + ' Socket: abnormally closed', error
);
461 // Stop the ATG if needed
462 if (Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.enable
) &&
463 Utils
.convertToBoolean(this._stationInfo
.AutomaticTransactionGenerator
.stopOnConnectionFailure
) &&
464 this._automaticTransactionGeneration
&&
465 !this._automaticTransactionGeneration
.timeToStop
) {
466 this._automaticTransactionGeneration
.stop();
469 this._stopHeartbeat();
470 if (this._autoReconnectTimeout
!== 0 &&
471 (this._autoReconnectRetryCount
< this._autoReconnectMaxRetries
|| this._autoReconnectMaxRetries
=== -1)) {
472 logger
.error(`${this._logPrefix()} Socket: connection retry with timeout ${this._autoReconnectTimeout}ms`);
473 this._autoReconnectRetryCount
++;
475 logger
.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount
);
477 }, this._autoReconnectTimeout
);
478 } else if (this._autoReconnectTimeout
!== 0 || this._autoReconnectMaxRetries
!== -1) {
479 logger
.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectTimeout})`);
484 logger
.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
485 if (!this._isSocketRestart
) {
486 // Send BootNotification
487 this.sendBootNotification();
489 if (this._isSocketRestart
) {
490 this._startMessageSequence();
491 if (!Utils
.isEmptyArray(this._messageQueue
)) {
492 this._messageQueue
.forEach((message
) => {
493 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
494 this._wsConnection
.send(message
);
499 this._autoReconnectRetryCount
= 0;
500 this._isSocketRestart
= false;
506 this._isSocketRestart
= true;
507 this._reconnect(error
);
510 logger
.error(this._logPrefix() + ' Socket error: ' + error
);
517 case 1000: // Normal close
519 logger
.info(this._logPrefix() + ' Socket normally closed ' + error
);
520 this._autoReconnectRetryCount
= 0;
522 default: // Abnormal close
523 this._isSocketRestart
= true;
524 this._reconnect(error
);
530 logger
.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
533 async onMessage(message
) {
534 let [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = [0, '', Constants
.ENTITY_CHARGING_STATION
, '', ''];
537 [messageType
, messageId
, commandName
, commandPayload
, errorDetails
] = JSON
.parse(message
);
539 // Check the Type of message
540 switch (messageType
) {
542 case Constants
.OCPP_JSON_CALL_MESSAGE
:
543 if (this.getEnableStatistics()) {
544 this._statistics
.addMessage(commandName
, messageType
);
547 await this.handleRequest(messageId
, commandName
, commandPayload
);
550 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
552 // eslint-disable-next-line no-case-declarations
553 let responseCallback
; let requestPayload
;
554 if (Utils
.isIterable(this._requests
[messageId
])) {
555 [responseCallback
, , requestPayload
] = this._requests
[messageId
];
557 throw new Error(`Response request for message id ${messageId} is not iterable`);
559 if (!responseCallback
) {
561 throw new Error(`Response request for unknown message id ${messageId}`);
563 delete this._requests
[messageId
];
564 responseCallback(commandName
, requestPayload
);
567 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
568 if (!this._requests
[messageId
]) {
570 throw new Error(`Error request for unknown message id ${messageId}`);
572 // eslint-disable-next-line no-case-declarations
574 if (Utils
.isIterable(this._requests
[messageId
])) {
575 [, rejectCallback
] = this._requests
[messageId
];
577 throw new Error(`Error request for message id ${messageId} is not iterable`);
579 delete this._requests
[messageId
];
580 rejectCallback(new OCPPError(commandName
, commandPayload
, errorDetails
));
584 // eslint-disable-next-line no-case-declarations
585 const errMsg
= `${this._logPrefix()} Wrong message type ${messageType}`;
586 logger
.error(errMsg
);
587 throw new Error(errMsg
);
591 logger
.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), message
, error
, this._requests
[messageId
]);
593 await this.sendError(messageId
, error
, commandName
);
597 async sendHeartbeat() {
600 currentTime
: new Date().toISOString(),
602 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'Heartbeat');
604 logger
.error(this._logPrefix() + ' Send Heartbeat error: ' + error
);
609 async sendBootNotification() {
611 await this.sendMessage(Utils
.generateUUID(), this._bootNotificationMessage
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'BootNotification');
613 logger
.error(this._logPrefix() + ' Send BootNotification error: ' + error
);
618 async sendStatusNotification(connectorId
: number, status: string, errorCode
= 'NoError') {
625 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StatusNotification');
627 logger
.error(this._logPrefix() + ' Send StatusNotification error: ' + error
);
632 async sendStartTransaction(connectorId
: number, idTag
?: string): Promise
<unknown
> {
636 ...!Utils
.isUndefined(idTag
) ? { idTag
} : { idTag
: '' },
638 timestamp
: new Date().toISOString(),
640 return await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StartTransaction');
642 logger
.error(this._logPrefix() + ' Send StartTransaction error: ' + error
);
647 async sendStopTransaction(transactionId
: number, reason
= ''): Promise
<void> {
652 timestamp
: new Date().toISOString(),
653 ...reason
&& { reason
},
655 await this.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'StopTransaction');
657 logger
.error(this._logPrefix() + ' Send StopTransaction error: ' + error
);
662 // eslint-disable-next-line consistent-this
663 async sendMeterValues(connectorId
: number, interval
: number, self: ChargingStation
, debug
= false): Promise
<void> {
665 const sampledValues
= {
666 timestamp
: new Date().toISOString(),
669 const meterValuesTemplate
= self.getConnector(connectorId
).MeterValues
;
670 for (let index
= 0; index
< meterValuesTemplate
.length
; index
++) {
671 const connector
= self.getConnector(connectorId
);
673 if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'SoC' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('SoC')) {
674 sampledValues
.sampledValue
.push({
675 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'Percent' },
676 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
677 measurand
: meterValuesTemplate
[index
].measurand
,
678 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) ? { location
: meterValuesTemplate
[index
].location
} : { location
: 'EV' },
679 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: Utils
.getRandomInt(100) },
681 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
682 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> 100 || debug
) {
683 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`);
686 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Voltage' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('Voltage')) {
687 const voltageMeasurandValue
= Utils
.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
688 sampledValues
.sampledValue
.push({
689 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'V' },
690 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
691 measurand
: meterValuesTemplate
[index
].measurand
,
692 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
693 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
},
695 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
696 const voltageValue
= sampledValues
.sampledValue
[sampledValues
.sampledValue
.length
- 1].value
;
698 if (voltageValue
>= 0 && voltageValue
<= 250) {
699 phaseValue
= `L${phase}-N`;
700 } else if (voltageValue
> 250) {
701 phaseValue
= `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
703 sampledValues
.sampledValue
.push({
704 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'V' },
705 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
706 measurand
: meterValuesTemplate
[index
].measurand
,
707 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
708 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: voltageMeasurandValue
},
712 // Power.Active.Import measurand
713 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Power.Active.Import' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('Power.Active.Import')) {
714 // FIXME: factor out powerDivider checks
715 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
716 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
717 logger
.error(errMsg
);
719 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
720 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}`;
721 logger
.error(errMsg
);
724 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`;
725 const powerMeasurandValues
= {} as MeasurandValues
;
726 const maxPower
= Math.round(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
);
727 const maxPowerPerPhase
= Math.round((self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
) / self._getNumberOfPhases());
728 switch (self._getPowerOutType()) {
730 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
731 powerMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
732 powerMeasurandValues
.L2
= 0;
733 powerMeasurandValues
.L3
= 0;
734 if (self._getNumberOfPhases() === 3) {
735 powerMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
736 powerMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxPowerPerPhase
);
738 powerMeasurandValues
.all
= Utils
.roundTo(powerMeasurandValues
.L1
+ powerMeasurandValues
.L2
+ powerMeasurandValues
.L3
, 2);
742 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
743 powerMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxPower
);
747 logger
.error(errMsg
);
750 sampledValues
.sampledValue
.push({
751 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'W' },
752 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
753 measurand
: meterValuesTemplate
[index
].measurand
,
754 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
755 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
.all
},
757 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
758 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxPower
|| debug
) {
759 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}`);
761 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
762 const phaseValue
= `L${phase}-N`;
763 sampledValues
.sampledValue
.push({
764 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'W' },
765 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
766 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
767 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
768 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: powerMeasurandValues
[`L${phase}`] },
772 // Current.Import measurand
773 } else if (meterValuesTemplate
[index
].measurand
&& meterValuesTemplate
[index
].measurand
=== 'Current.Import' && self._getConfigurationKey('MeterValuesSampledData').value
.includes('Current.Import')) {
774 // FIXME: factor out powerDivider checks
775 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
776 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
777 logger
.error(errMsg
);
779 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
780 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}`;
781 logger
.error(errMsg
);
784 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`;
785 const currentMeasurandValues
= {} as MeasurandValues
;
787 switch (self._getPowerOutType()) {
789 maxAmperage
= ElectricUtils
.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
790 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
791 currentMeasurandValues
.L1
= Utils
.getRandomFloatRounded(maxAmperage
);
792 currentMeasurandValues
.L2
= 0;
793 currentMeasurandValues
.L3
= 0;
794 if (self._getNumberOfPhases() === 3) {
795 currentMeasurandValues
.L2
= Utils
.getRandomFloatRounded(maxAmperage
);
796 currentMeasurandValues
.L3
= Utils
.getRandomFloatRounded(maxAmperage
);
798 currentMeasurandValues
.all
= Utils
.roundTo((currentMeasurandValues
.L1
+ currentMeasurandValues
.L2
+ currentMeasurandValues
.L3
) / self._getNumberOfPhases(), 2);
802 maxAmperage
= ElectricUtils
.ampTotalFromPower(self._stationInfo
.maxPower
/ self._stationInfo
.powerDivider
, self._getVoltageOut());
803 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
804 currentMeasurandValues
.all
= Utils
.getRandomFloatRounded(maxAmperage
);
808 logger
.error(errMsg
);
811 sampledValues
.sampledValue
.push({
812 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'A' },
813 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
814 measurand
: meterValuesTemplate
[index
].measurand
,
815 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
816 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
.all
},
818 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
819 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxAmperage
|| debug
) {
820 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}`);
822 for (let phase
= 1; self._getNumberOfPhases() === 3 && phase
<= self._getNumberOfPhases(); phase
++) {
823 const phaseValue
= `L${phase}`;
824 sampledValues
.sampledValue
.push({
825 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'A' },
826 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
827 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
828 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
829 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: currentMeasurandValues
[phaseValue
] },
833 // Energy.Active.Import.Register measurand (default)
834 } else if (!meterValuesTemplate
[index
].measurand
|| meterValuesTemplate
[index
].measurand
=== 'Energy.Active.Import.Register') {
835 // FIXME: factor out powerDivider checks
836 if (Utils
.isUndefined(self._stationInfo
.powerDivider
)) {
837 const errMsg
= `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'}: powerDivider is undefined`;
838 logger
.error(errMsg
);
840 } else if (self._stationInfo
.powerDivider
&& self._stationInfo
.powerDivider
<= 0) {
841 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}`;
842 logger
.error(errMsg
);
845 if (Utils
.isUndefined(meterValuesTemplate
[index
].value
)) {
846 const measurandValue
= Utils
.getRandomInt(self._stationInfo
.maxPower
/ (self._stationInfo
.powerDivider
* 3600000) * interval
);
847 // Persist previous value in connector
848 if (connector
&& !Utils
.isNullOrUndefined(connector
.lastEnergyActiveImportRegisterValue
) && connector
.lastEnergyActiveImportRegisterValue
>= 0) {
849 connector
.lastEnergyActiveImportRegisterValue
+= measurandValue
;
851 connector
.lastEnergyActiveImportRegisterValue
= 0;
854 sampledValues
.sampledValue
.push({
855 ...!Utils
.isUndefined(meterValuesTemplate
[index
].unit
) ? { unit
: meterValuesTemplate
[index
].unit
} : { unit
: 'Wh' },
856 ...!Utils
.isUndefined(meterValuesTemplate
[index
].context
) && { context
: meterValuesTemplate
[index
].context
},
857 ...!Utils
.isUndefined(meterValuesTemplate
[index
].measurand
) && { measurand
: meterValuesTemplate
[index
].measurand
},
858 ...!Utils
.isUndefined(meterValuesTemplate
[index
].location
) && { location
: meterValuesTemplate
[index
].location
},
859 ...!Utils
.isUndefined(meterValuesTemplate
[index
].value
) ? { value
: meterValuesTemplate
[index
].value
} : { value
: connector
.lastEnergyActiveImportRegisterValue
},
861 const sampledValuesIndex
= sampledValues
.sampledValue
.length
- 1;
862 const maxConsumption
= Math.round(self._stationInfo
.maxPower
* 3600 / (self._stationInfo
.powerDivider
* interval
));
863 if (sampledValues
.sampledValue
[sampledValuesIndex
].value
> maxConsumption
|| debug
) {
864 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}`);
866 // Unsupported measurand
868 logger
.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : 'Energy.Active.Import.Register'} on connectorId ${connectorId}`);
874 transactionId
: self.getConnector(connectorId
).transactionId
,
875 meterValue
: sampledValues
,
877 await self.sendMessage(Utils
.generateUUID(), payload
, Constants
.OCPP_JSON_CALL_MESSAGE
, 'MeterValues');
879 logger
.error(self._logPrefix() + ' Send MeterValues error: ' + error
);
884 async sendError(messageId
, err
: Error|OCPPError
, commandName
) {
885 // Check exception type: only OCPP error are accepted
886 const error
= err
instanceof OCPPError
? err
: new OCPPError(Constants
.OCPP_ERROR_INTERNAL_ERROR
, err
.message
, err
.stack
&& err
.stack
);
888 return this.sendMessage(messageId
, error
, Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
, commandName
);
891 async sendMessage(messageId
, commandParams
, messageType
= Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
: string) {
892 // eslint-disable-next-line @typescript-eslint/no-this-alias
894 // Send a message through wsConnection
895 return new Promise((resolve
, reject
) => {
898 switch (messageType
) {
900 case Constants
.OCPP_JSON_CALL_MESSAGE
:
902 this._requests
[messageId
] = [responseCallback
, rejectCallback
, commandParams
];
903 messageToSend
= JSON
.stringify([messageType
, messageId
, commandName
, commandParams
]);
906 case Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
:
908 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
]);
911 case Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
:
912 // Build Error Message
913 messageToSend
= JSON
.stringify([messageType
, messageId
, commandParams
.code
? commandParams
.code
: Constants
.OCPP_ERROR_GENERIC_ERROR
, commandParams
.message
? commandParams
.message
: '', commandParams
.details
? commandParams
.details
: {}]);
916 // Check if wsConnection is ready
917 if (this._wsConnection
&& this._wsConnection
.readyState
=== WebSocket
.OPEN
) {
918 if (this.getEnableStatistics()) {
919 this._statistics
.addMessage(commandName
, messageType
);
922 this._wsConnection
.send(messageToSend
);
925 // Handle dups in buffer
926 for (const message
of this._messageQueue
) {
928 if (JSON
.stringify(messageToSend
) === JSON
.stringify(message
)) {
935 this._messageQueue
.push(messageToSend
);
938 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
: {}));
941 if (messageType
=== Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
) {
944 } else if (messageType
=== Constants
.OCPP_JSON_CALL_ERROR_MESSAGE
) {
946 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
);
949 // Function that will receive the request's response
950 function responseCallback(payload
, requestPayload
): void {
951 if (self.getEnableStatistics()) {
952 self._statistics
.addMessage(commandName
, messageType
);
955 self.handleResponse(commandName
, payload
, requestPayload
);
959 // Function that will receive the request's rejection
960 function rejectCallback(error
: OCPPError
): void {
961 if (self.getEnableStatistics()) {
962 self._statistics
.addMessage(commandName
, messageType
);
964 logger
.debug(`${self._logPrefix()} Error %j occurred when calling command %s with parameters %j`, error
, commandName
, commandParams
);
966 // eslint-disable-next-line no-empty-function
967 self._requests
[messageId
] = [() => { }, () => { }, '']; // Properly format the request
974 handleResponse(commandName
: string, payload
, requestPayload
) {
975 const responseCallbackFn
= 'handleResponse' + commandName
;
976 if (typeof this[responseCallbackFn
] === 'function') {
977 this[responseCallbackFn
](payload
, requestPayload
);
979 logger
.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn
);
983 handleResponseBootNotification(payload
, requestPayload
) {
984 if (payload
.status === 'Accepted') {
985 this._heartbeatInterval
= payload
.interval
* 1000;
986 this._addConfigurationKey('HeartBeatInterval', Utils
.convertToInt(payload
.interval
));
987 this._addConfigurationKey('HeartbeatInterval', Utils
.convertToInt(payload
.interval
), false, false);
988 this._startMessageSequence();
989 } else if (payload
.status === 'Pending') {
990 logger
.info(this._logPrefix() + ' Charging station in pending state on the central server');
992 logger
.info(this._logPrefix() + ' Charging station rejected by the central server');
996 _initTransactionOnConnector(connectorId
) {
997 this.getConnector(connectorId
).transactionStarted
= false;
998 this.getConnector(connectorId
).transactionId
= null;
999 this.getConnector(connectorId
).idTag
= null;
1000 this.getConnector(connectorId
).lastEnergyActiveImportRegisterValue
= -1;
1003 _resetTransactionOnConnector(connectorId
) {
1004 this._initTransactionOnConnector(connectorId
);
1005 if (this.getConnector(connectorId
).transactionSetInterval
) {
1006 clearInterval(this.getConnector(connectorId
).transactionSetInterval
);
1010 handleResponseStartTransaction(payload
, requestPayload
) {
1011 if (this.getConnector(requestPayload
.connectorId
).transactionStarted
) {
1012 logger
.debug(this._logPrefix() + ' Try to start a transaction on an already used connector ' + requestPayload
.connectorId
+ ': %s', this.getConnector(requestPayload
.connectorId
));
1016 let transactionConnectorId
;
1017 for (const connector
in this._connectors
) {
1018 if (Utils
.convertToInt(connector
) === Utils
.convertToInt(requestPayload
.connectorId
)) {
1019 transactionConnectorId
= connector
;
1023 if (!transactionConnectorId
) {
1024 logger
.error(this._logPrefix() + ' Try to start a transaction on a non existing connector Id ' + requestPayload
.connectorId
);
1027 if (payload
.idTagInfo
&& payload
.idTagInfo
.status === 'Accepted') {
1028 this.getConnector(requestPayload
.connectorId
).transactionStarted
= true;
1029 this.getConnector(requestPayload
.connectorId
).transactionId
= payload
.transactionId
;
1030 this.getConnector(requestPayload
.connectorId
).idTag
= requestPayload
.idTag
;
1031 this.getConnector(requestPayload
.connectorId
).lastEnergyActiveImportRegisterValue
= 0;
1032 this.sendStatusNotification(requestPayload
.connectorId
, 'Charging');
1033 logger
.info(this._logPrefix() + ' Transaction ' + payload
.transactionId
+ ' STARTED on ' + this._stationInfo
.name
+ '#' + requestPayload
.connectorId
+ ' for idTag ' + requestPayload
.idTag
);
1034 if (this._stationInfo
.powerSharedByConnectors
) {
1035 this._stationInfo
.powerDivider
++;
1037 const configuredMeterValueSampleInterval
= this._getConfigurationKey('MeterValueSampleInterval');
1038 this._startMeterValues(requestPayload
.connectorId
,
1039 configuredMeterValueSampleInterval
? configuredMeterValueSampleInterval
.value
* 1000 : 60000);
1041 logger
.error(this._logPrefix() + ' Starting transaction id ' + payload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status + ', idTag ' + requestPayload
.idTag
);
1042 this._resetTransactionOnConnector(requestPayload
.connectorId
);
1043 this.sendStatusNotification(requestPayload
.connectorId
, 'Available');
1047 handleResponseStopTransaction(payload
, requestPayload
) {
1048 let transactionConnectorId
;
1049 for (const connector
in this._connectors
) {
1050 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== requestPayload
.transactionId
) {
1051 transactionConnectorId
= connector
;
1055 if (!transactionConnectorId
) {
1056 logger
.error(this._logPrefix() + ' Try to stop a non existing transaction ' + requestPayload
.transactionId
);
1059 if (payload
.idTagInfo
&& payload
.idTagInfo
.status === 'Accepted') {
1060 this.sendStatusNotification(transactionConnectorId
, 'Available');
1061 if (this._stationInfo
.powerSharedByConnectors
) {
1062 this._stationInfo
.powerDivider
--;
1064 logger
.info(this._logPrefix() + ' Transaction ' + requestPayload
.transactionId
+ ' STOPPED on ' + this._stationInfo
.name
+ '#' + transactionConnectorId
);
1065 this._resetTransactionOnConnector(transactionConnectorId
);
1067 logger
.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload
.transactionId
+ ' REJECTED with status ' + payload
.idTagInfo
.status);
1071 handleResponseStatusNotification(payload
, requestPayload
) {
1072 logger
.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload
, requestPayload
);
1075 handleResponseMeterValues(payload
, requestPayload
) {
1076 logger
.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload
, requestPayload
);
1079 handleResponseHeartbeat(payload
, requestPayload
) {
1080 logger
.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload
, requestPayload
);
1083 async handleRequest(messageId
, commandName
, commandPayload
) {
1086 if (typeof this['handleRequest' + commandName
] === 'function') {
1088 // Call the method to build the response
1089 response
= await this['handleRequest' + commandName
](commandPayload
);
1092 logger
.error(this._logPrefix() + ' Handle request error: ' + error
);
1093 // Send back response to inform backend
1094 await this.sendError(messageId
, error
, commandName
);
1099 await this.sendError(messageId
, new OCPPError(Constants
.OCPP_ERROR_NOT_IMPLEMENTED
, `${commandName} is not implemented`, {}), commandName
);
1100 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1103 await this.sendMessage(messageId
, response
, Constants
.OCPP_JSON_CALL_RESULT_MESSAGE
, commandName
);
1106 // Simulate charging station restart
1107 async handleRequestReset(commandPayload
) {
1108 setImmediate(async () => {
1109 await this.stop(commandPayload
.type + 'Reset');
1110 await Utils
.sleep(this._stationInfo
.resetTime
);
1113 logger
.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${this._stationInfo.resetTime}ms`);
1114 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1117 _getConfigurationKey(key
) {
1118 return this._configuration
.configurationKey
.find((configElement
) => configElement
.key
=== key
);
1121 _addConfigurationKey(key
, value
, readonly = false, visible
= true, reboot
= false) {
1122 const keyFound
= this._getConfigurationKey(key
);
1124 this._configuration
.configurationKey
.push({
1134 _setConfigurationKeyValue(key
, value
) {
1135 const keyFound
= this._getConfigurationKey(key
);
1137 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyFound
);
1138 this._configuration
.configurationKey
[keyIndex
].value
= value
;
1142 async handleRequestGetConfiguration(commandPayload
) {
1143 const configurationKey
= [];
1144 const unknownKey
= [];
1145 if (Utils
.isEmptyArray(commandPayload
.key
)) {
1146 for (const configuration
of this._configuration
.configurationKey
) {
1147 if (Utils
.isUndefined(configuration
.visible
)) {
1148 configuration
.visible
= true;
1150 configuration
.visible
= Utils
.convertToBoolean(configuration
.visible
);
1152 if (!configuration
.visible
) {
1155 configurationKey
.push({
1156 key
: configuration
.key
,
1157 readonly: configuration
.readonly,
1158 value
: configuration
.value
,
1162 for (const configurationKey
of commandPayload
.key
) {
1163 const keyFound
= this._getConfigurationKey(configurationKey
);
1165 if (Utils
.isUndefined(keyFound
.visible
)) {
1166 keyFound
.visible
= true;
1168 keyFound
.visible
= Utils
.convertToBoolean(configurationKey
.visible
);
1170 if (!keyFound
.visible
) {
1173 configurationKey
.push({
1175 readonly: keyFound
.readonly,
1176 value
: keyFound
.value
,
1179 unknownKey
.push(configurationKey
);
1189 async handleRequestChangeConfiguration(commandPayload
) {
1190 const keyToChange
= this._getConfigurationKey(commandPayload
.key
);
1192 return { status: Constants
.OCPP_ERROR_NOT_SUPPORTED
};
1193 } else if (keyToChange
&& Utils
.convertToBoolean(keyToChange
.readonly)) {
1194 return Constants
.OCPP_RESPONSE_REJECTED
;
1195 } else if (keyToChange
&& !Utils
.convertToBoolean(keyToChange
.readonly)) {
1196 const keyIndex
= this._configuration
.configurationKey
.indexOf(keyToChange
);
1197 this._configuration
.configurationKey
[keyIndex
].value
= commandPayload
.value
;
1198 let triggerHeartbeatRestart
= false;
1199 if (keyToChange
.key
=== 'HeartBeatInterval') {
1200 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload
.value
);
1201 triggerHeartbeatRestart
= true;
1203 if (keyToChange
.key
=== 'HeartbeatInterval') {
1204 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload
.value
);
1205 triggerHeartbeatRestart
= true;
1207 if (triggerHeartbeatRestart
) {
1208 this._heartbeatInterval
= Utils
.convertToInt(commandPayload
.value
) * 1000;
1210 this._stopHeartbeat();
1212 this._startHeartbeat();
1214 if (Utils
.convertToBoolean(keyToChange
.reboot
)) {
1215 return Constants
.OCPP_RESPONSE_REBOOT_REQUIRED
;
1217 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1221 async handleRequestRemoteStartTransaction(commandPayload
) {
1222 const transactionConnectorID
= commandPayload
.connectorId
? commandPayload
.connectorId
: '1';
1223 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
1224 // Check if authorized
1225 if (this._authorizedTags
.find((value
) => value
=== commandPayload
.idTag
)) {
1226 // Authorization successful start transaction
1227 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1228 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1229 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1231 logger
.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload
.idTagInfo
.status + ', idTag ' + commandPayload
.idTag
);
1232 return Constants
.OCPP_RESPONSE_REJECTED
;
1234 // No local authorization check required => start transaction
1235 await this.sendStartTransaction(transactionConnectorID
, commandPayload
.idTag
);
1236 logger
.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo
.name
+ '#' + transactionConnectorID
+ ' for idTag ' + commandPayload
.idTag
);
1237 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1240 async handleRequestRemoteStopTransaction(commandPayload
) {
1241 for (const connector
in this._connectors
) {
1242 if (this.getConnector(Utils
.convertToInt(connector
)).transactionId
=== commandPayload
.transactionId
) {
1243 await this.sendStopTransaction(commandPayload
.transactionId
);
1244 return Constants
.OCPP_RESPONSE_ACCEPTED
;
1247 logger
.info(this._logPrefix() + ' Try to stop remotely a non existing transaction ' + commandPayload
.transactionId
);
1248 return Constants
.OCPP_RESPONSE_REJECTED
;