Push down more tunables in charging station template.
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
29bf6658 1import { AuthorizationStatus, StartTransactionResponse, StopTransactionReason, StopTransactionResponse } from '../types/ocpp/1.6/Transaction';
e118beaa 2import ChargingStationConfiguration, { ConfigurationKey } from '../types/ChargingStationConfiguration';
9ac86a7e 3import ChargingStationTemplate, { PowerOutType } from '../types/ChargingStationTemplate';
29bf6658 4import { ConfigurationResponse, DefaultRequestResponse, UnlockResponse } from '../types/ocpp/1.6/RequestResponses';
10570d97 5import Connectors, { Connector } from '../types/Connectors';
29bf6658 6import MeterValue, { MeterValueLocation, MeterValueMeasurand, MeterValuePhase, MeterValueUnit } from '../types/ocpp/1.6/MeterValue';
6af9012e 7import { PerformanceObserver, performance } from 'perf_hooks';
136c90ba 8import WebSocket, { MessageEvent } from 'ws';
3f40bc9c 9
6af9012e 10import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
29bf6658
JB
11import { ChargePointErrorCode } from '../types/ocpp/1.6/ChargePointErrorCode';
12import { ChargePointStatus } from '../types/ocpp/1.6/ChargePointStatus';
9ac86a7e 13import ChargingStationInfo from '../types/ChargingStationInfo';
6af9012e 14import Configuration from '../utils/Configuration';
63b48f77 15import Constants from '../utils/Constants';
6af9012e 16import ElectricUtils from '../utils/ElectricUtils';
6b0ce541 17import MeasurandValues from '../types/MeasurandValues';
63b48f77
JB
18import OCPPError from './OcppError';
19import Requests from '../types/ocpp/1.6/Requests';
6af9012e
JB
20import Statistics from '../utils/Statistics';
21import Utils from '../utils/Utils';
3f40bc9c
JB
22import crypto from 'crypto';
23import fs from 'fs';
6af9012e 24import logger from '../utils/Logger';
3f40bc9c
JB
25
26export default class ChargingStation {
6af9012e 27 private _index: number;
a4a21709 28 private _stationTemplateFile: string;
9ac86a7e 29 private _stationInfo: ChargingStationInfo;
e118beaa
JB
30 private _bootNotificationMessage: {
31 chargePointModel: string,
32 chargePointVendor: string,
33 chargeBoxSerialNumber?: string,
34 firmwareVersion?: string,
35 };
36
10570d97 37 private _connectors: Connectors;
e118beaa 38 private _configuration: ChargingStationConfiguration;
a4a21709 39 private _connectorsConfigurationHash: string;
10570d97
JB
40 private _supervisionUrl: string;
41 private _wsConnectionUrl: string;
a4a21709 42 private _wsConnection: WebSocket;
9ac86a7e
JB
43 private _hasStopped: boolean;
44 private _hasSocketRestarted: boolean;
032d6efc 45 private _connectionTimeout: number;
a4a21709
JB
46 private _autoReconnectRetryCount: number;
47 private _autoReconnectMaxRetries: number;
63b48f77
JB
48 private _requests: Requests;
49 private _messageQueue: string[];
6af9012e
JB
50 private _automaticTransactionGeneration: AutomaticTransactionGenerator;
51 private _authorizedTags: string[];
a4a21709 52 private _heartbeatInterval: number;
10570d97 53 private _heartbeatSetInterval: NodeJS.Timeout;
136c90ba 54 private _webSocketPingSetInterval: NodeJS.Timeout;
6af9012e
JB
55 private _statistics: Statistics;
56 private _performanceObserver: PerformanceObserver;
57
58 constructor(index: number, stationTemplateFile: string) {
2e6f5966
JB
59 this._index = index;
60 this._stationTemplateFile = stationTemplateFile;
63b48f77 61 this._connectors = {} as Connectors;
2e6f5966
JB
62 this._initialize();
63
9ac86a7e
JB
64 this._hasStopped = false;
65 this._hasSocketRestarted = false;
7dde0b73 66 this._autoReconnectRetryCount = 0;
2e6f5966 67
63b48f77
JB
68 this._requests = {} as Requests;
69 this._messageQueue = [] as string[];
2e6f5966 70
83045896 71 this._authorizedTags = this._loadAndGetAuthorizedTags();
2e6f5966
JB
72 }
73
9ac86a7e
JB
74 _getStationName(stationTemplate: ChargingStationTemplate): string {
75 return stationTemplate.fixedName ? stationTemplate.baseName : stationTemplate.baseName + '-' + ('000000000' + this._index.toString()).substr(('000000000' + this._index.toString()).length - 4);
5ad8570f
JB
76 }
77
9ac86a7e
JB
78 _buildStationInfo(): ChargingStationInfo {
79 let stationTemplateFromFile: ChargingStationTemplate;
5ad8570f
JB
80 try {
81 // Load template file
82 const fileDescriptor = fs.openSync(this._stationTemplateFile, 'r');
9ac86a7e 83 stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
5ad8570f
JB
84 fs.closeSync(fileDescriptor);
85 } catch (error) {
7ec46a9a 86 logger.error('Template file ' + this._stationTemplateFile + ' loading error: %j', error);
cdd9fed5 87 throw error;
5ad8570f 88 }
9ac86a7e 89 const stationInfo: ChargingStationInfo = stationTemplateFromFile || {} as ChargingStationInfo;
0a60c33c 90 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
9ac86a7e
JB
91 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
92 stationInfo.maxPower = stationTemplateFromFile.power[Math.floor(Math.random() * stationTemplateFromFile.power.length)];
5ad8570f 93 } else {
9ac86a7e 94 stationInfo.maxPower = stationTemplateFromFile.power as number;
5ad8570f 95 }
9ac86a7e
JB
96 stationInfo.name = this._getStationName(stationTemplateFromFile);
97 stationInfo.resetTime = stationTemplateFromFile.resetTime ? stationTemplateFromFile.resetTime * 1000 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
98 return stationInfo;
5ad8570f
JB
99 }
100
9ac86a7e 101 get stationInfo(): ChargingStationInfo {
6af9012e
JB
102 return this._stationInfo;
103 }
104
105 _initialize(): void {
2e6f5966
JB
106 this._stationInfo = this._buildStationInfo();
107 this._bootNotificationMessage = {
108 chargePointModel: this._stationInfo.chargePointModel,
109 chargePointVendor: this._stationInfo.chargePointVendor,
6af9012e
JB
110 ...!Utils.isUndefined(this._stationInfo.chargeBoxSerialNumberPrefix) && { chargeBoxSerialNumber: this._stationInfo.chargeBoxSerialNumberPrefix },
111 ...!Utils.isUndefined(this._stationInfo.firmwareVersion) && { firmwareVersion: this._stationInfo.firmwareVersion },
2e6f5966 112 };
136c90ba 113 this._configuration = this._getTemplateChargingStationConfiguration();
2e6f5966 114 this._supervisionUrl = this._getSupervisionURL();
0a60c33c 115 this._wsConnectionUrl = this._supervisionUrl + '/' + this._stationInfo.name;
3574dfd3
JB
116 this._connectionTimeout = this._getConnectionTimeout() * 1000; // Ms, zero for disabling
117 this._autoReconnectMaxRetries = this._getAutoReconnectMaxRetries(); // -1 for unlimited
0a60c33c 118 // Build connectors if needed
6ecb15e4
JB
119 const maxConnectors = this._getMaxNumberOfConnectors();
120 if (maxConnectors <= 0) {
3f40bc9c 121 logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with ${maxConnectors} connectors`);
7abfea5f
JB
122 }
123 const templateMaxConnectors = this._getTemplateMaxNumberOfConnectors();
124 if (templateMaxConnectors <= 0) {
3f40bc9c 125 logger.warn(`${this._logPrefix()} Charging station template ${this._stationTemplateFile} with no connector configurations`);
7abfea5f
JB
126 }
127 // Sanity check
9ac86a7e 128 if (maxConnectors > (this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) && !this._stationInfo.randomConnectors) {
7abfea5f
JB
129 logger.warn(`${this._logPrefix()} Number of connectors exceeds the number of connector configurations in template ${this._stationTemplateFile}, forcing random connector configurations affectation`);
130 this._stationInfo.randomConnectors = true;
6ecb15e4 131 }
8bce55bf 132 const connectorsConfigHash = crypto.createHash('sha256').update(JSON.stringify(this._stationInfo.Connectors) + maxConnectors.toString()).digest('hex');
de1f5008 133 // FIXME: Handle shrinking the number of connectors
5a9f5716 134 if (!this._connectors || (this._connectors && this._connectorsConfigurationHash !== connectorsConfigHash)) {
de1f5008 135 this._connectorsConfigurationHash = connectorsConfigHash;
7abfea5f 136 // Add connector Id 0
6af9012e 137 let lastConnector = '0';
8bce55bf 138 for (lastConnector in this._stationInfo.Connectors) {
9ac86a7e
JB
139 if (Utils.convertToInt(lastConnector) === 0 && this._stationInfo.useConnectorId0 && this._stationInfo.Connectors[lastConnector]) {
140 this._connectors[lastConnector] = Utils.cloneObject(this._stationInfo.Connectors[lastConnector]) as Connector;
0a60c33c
JB
141 }
142 }
0a60c33c 143 // Generate all connectors
7abfea5f
JB
144 if ((this._stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
145 for (let index = 1; index <= maxConnectors; index++) {
9ac86a7e
JB
146 const randConnectorID = this._stationInfo.randomConnectors ? Utils.getRandomInt(Utils.convertToInt(lastConnector), 1) : index;
147 this._connectors[index] = Utils.cloneObject(this._stationInfo.Connectors[randConnectorID]) as Connector;
7abfea5f 148 }
0a60c33c
JB
149 }
150 }
d4a73fb7
JB
151 // Avoid duplication of connectors related information
152 delete this._stationInfo.Connectors;
0a60c33c
JB
153 // Initialize transaction attributes on connectors
154 for (const connector in this._connectors) {
6af9012e 155 if (!this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
10570d97 156 this._initTransactionOnConnector(Utils.convertToInt(connector));
0a60c33c
JB
157 }
158 }
7abfea5f 159 // OCPP parameters
10570d97 160 this._addConfigurationKey('NumberOfConnectors', this._getNumberOfConnectors().toString(), true);
7abfea5f 161 if (!this._getConfigurationKey('MeterValuesSampledData')) {
10570d97 162 this._addConfigurationKey('MeterValuesSampledData', MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER);
7abfea5f 163 }
6ecb15e4 164 this._stationInfo.powerDivider = this._getPowerDivider();
8bce55bf
JB
165 if (this.getEnableStatistics()) {
166 this._statistics = Statistics.getInstance();
167 this._statistics.objName = this._stationInfo.name;
168 this._performanceObserver = new PerformanceObserver((list) => {
169 const entry = list.getEntries()[0];
10570d97 170 this._statistics.logPerformance(entry, Constants.ENTITY_CHARGING_STATION);
8bce55bf
JB
171 this._performanceObserver.disconnect();
172 });
173 }
7dde0b73
JB
174 }
175
10570d97 176 get connectors(): Connectors {
6af9012e
JB
177 return this._connectors;
178 }
179
180 get statistics(): Statistics {
181 return this._statistics;
182 }
183
184 _logPrefix(): string {
ead548f2 185 return Utils.logPrefix(` ${this._stationInfo.name}:`);
7dde0b73
JB
186 }
187
136c90ba 188 _getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
e118beaa 189 return this._stationInfo.Configuration ? this._stationInfo.Configuration : {} as ChargingStationConfiguration;
7dde0b73
JB
190 }
191
10570d97 192 _getAuthorizationFile(): string {
6af9012e 193 return this._stationInfo.authorizationFile && this._stationInfo.authorizationFile;
7dde0b73
JB
194 }
195
6af9012e 196 _loadAndGetAuthorizedTags(): string[] {
65c5527e 197 let authorizedTags: string[] = [];
2e6f5966
JB
198 const authorizationFile = this._getAuthorizationFile();
199 if (authorizationFile) {
200 try {
201 // Load authorization file
202 const fileDescriptor = fs.openSync(authorizationFile, 'r');
10570d97 203 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
2e6f5966
JB
204 fs.closeSync(fileDescriptor);
205 } catch (error) {
7ec46a9a 206 logger.error(this._logPrefix() + ' Authorization file ' + authorizationFile + ' loading error: %j', error);
cdd9fed5 207 throw error;
2e6f5966
JB
208 }
209 } else {
ead548f2 210 logger.info(this._logPrefix() + ' No authorization file given in template file ' + this._stationTemplateFile);
2e6f5966
JB
211 }
212 return authorizedTags;
213 }
214
65c5527e 215 getRandomTagId(): string {
5ad8570f
JB
216 const index = Math.floor(Math.random() * this._authorizedTags.length);
217 return this._authorizedTags[index];
2e6f5966
JB
218 }
219
65c5527e 220 hasAuthorizedTags(): boolean {
5ad8570f
JB
221 return !Utils.isEmptyArray(this._authorizedTags);
222 }
223
65c5527e 224 getEnableStatistics(): boolean {
9ac86a7e 225 return !Utils.isUndefined(this._stationInfo.enableStatistics) ? this._stationInfo.enableStatistics : true;
2328be1e
JB
226 }
227
6af9012e 228 _getNumberOfPhases(): number {
8c4da341 229 switch (this._getPowerOutType()) {
9ac86a7e 230 case PowerOutType.AC:
8c4da341 231 return !Utils.isUndefined(this._stationInfo.numberOfPhases) ? Utils.convertToInt(this._stationInfo.numberOfPhases) : 3;
9ac86a7e 232 case PowerOutType.DC:
8c4da341
JB
233 return 0;
234 }
8bce55bf
JB
235 }
236
65c5527e 237 _getNumberOfRunningTransactions(): number {
6ecb15e4
JB
238 let trxCount = 0;
239 for (const connector in this._connectors) {
6af9012e 240 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
6ecb15e4
JB
241 trxCount++;
242 }
243 }
244 return trxCount;
245 }
246
3574dfd3
JB
247 _getConnectionTimeout(): number {
248 if (!Utils.isUndefined(this._stationInfo.connectionTimeout)) {
249 return this._stationInfo.connectionTimeout;
250 }
251 if (!Utils.isUndefined(Configuration.getConnectionTimeout())) {
252 return Configuration.getConnectionTimeout();
253 }
254 return 30;
255 }
256
257 _getAutoReconnectMaxRetries(): number {
258 if (!Utils.isUndefined(this._stationInfo.autoReconnectMaxRetries)) {
259 return this._stationInfo.autoReconnectMaxRetries;
260 }
261 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
262 return Configuration.getAutoReconnectMaxRetries();
263 }
264 return -1;
265 }
266
65c5527e 267 _getPowerDivider(): number {
7abfea5f 268 let powerDivider = this._getNumberOfConnectors();
6ecb15e4
JB
269 if (this._stationInfo.powerSharedByConnectors) {
270 powerDivider = this._getNumberOfRunningTransactions();
271 }
272 return powerDivider;
273 }
274
10570d97 275 getConnector(id: number): Connector {
6af9012e 276 return this._connectors[id];
6ecb15e4
JB
277 }
278
65c5527e 279 _getTemplateMaxNumberOfConnectors(): number {
7abfea5f
JB
280 return Object.keys(this._stationInfo.Connectors).length;
281 }
282
65c5527e 283 _getMaxNumberOfConnectors(): number {
5ad8570f 284 let maxConnectors = 0;
0a60c33c 285 if (!Utils.isEmptyArray(this._stationInfo.numberOfConnectors)) {
9ac86a7e 286 const numberOfConnectors = this._stationInfo.numberOfConnectors as number[];
6ecb15e4 287 // Distribute evenly the number of connectors
7ec46a9a 288 maxConnectors = numberOfConnectors[(this._index - 1) % numberOfConnectors.length];
7abfea5f 289 } else if (!Utils.isUndefined(this._stationInfo.numberOfConnectors)) {
9ac86a7e 290 maxConnectors = this._stationInfo.numberOfConnectors as number;
488fd3a7 291 } else {
7abfea5f 292 maxConnectors = this._stationInfo.Connectors[0] ? this._getTemplateMaxNumberOfConnectors() - 1 : this._getTemplateMaxNumberOfConnectors();
5ad8570f
JB
293 }
294 return maxConnectors;
2e6f5966
JB
295 }
296
6af9012e 297 _getNumberOfConnectors(): number {
7abfea5f 298 return this._connectors[0] ? Object.keys(this._connectors).length - 1 : Object.keys(this._connectors).length;
6ecb15e4
JB
299 }
300
65c5527e 301 _getVoltageOut(): number {
b2acff85 302 const errMsg = `${this._logPrefix()} Unknown ${this._getPowerOutType()} powerOutType in template file ${this._stationTemplateFile}, cannot define default voltage out`;
10570d97 303 let defaultVoltageOut: number;
b2acff85 304 switch (this._getPowerOutType()) {
9ac86a7e 305 case PowerOutType.AC:
b2acff85
JB
306 defaultVoltageOut = 230;
307 break;
9ac86a7e 308 case PowerOutType.DC:
b2acff85
JB
309 defaultVoltageOut = 400;
310 break;
311 default:
312 logger.error(errMsg);
313 throw Error(errMsg);
314 }
315 return !Utils.isUndefined(this._stationInfo.voltageOut) ? Utils.convertToInt(this._stationInfo.voltageOut) : defaultVoltageOut;
316 }
317
032d6efc 318 _getTransactionIdTag(transactionId: number): string {
9ac86a7e
JB
319 for (const connector in this._connectors) {
320 if (this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
321 return this.getConnector(Utils.convertToInt(connector)).idTag;
322 }
323 }
324 }
325
326 _getPowerOutType(): PowerOutType {
327 return !Utils.isUndefined(this._stationInfo.powerOutType) ? this._stationInfo.powerOutType : PowerOutType.AC;
3f40bc9c
JB
328 }
329
65c5527e 330 _getSupervisionURL(): string {
7ec46a9a 331 const supervisionUrls = Utils.cloneObject(this._stationInfo.supervisionURL ? this._stationInfo.supervisionURL : Configuration.getSupervisionURLs()) as string | string[];
7dde0b73 332 let indexUrl = 0;
0a60c33c 333 if (!Utils.isEmptyArray(supervisionUrls)) {
524d9cb3 334 if (Configuration.getDistributeStationsToTenantsEqually()) {
2e6f5966 335 indexUrl = this._index % supervisionUrls.length;
7dde0b73
JB
336 } else {
337 // Get a random url
338 indexUrl = Math.floor(Math.random() * supervisionUrls.length);
339 }
7ec46a9a 340 return supervisionUrls[indexUrl];
7dde0b73 341 }
e118beaa 342 return supervisionUrls as string;
7dde0b73
JB
343 }
344
032d6efc
JB
345 _getReconnectExponentialDelay(): boolean {
346 return !Utils.isUndefined(this._stationInfo.reconnectExponentialDelay) ? this._stationInfo.reconnectExponentialDelay : false;
347 }
348
65c5527e 349 _getAuthorizeRemoteTxRequests(): boolean {
61c2e33d 350 const authorizeRemoteTxRequests = this._getConfigurationKey('AuthorizeRemoteTxRequests');
a6e68f34 351 return authorizeRemoteTxRequests ? Utils.convertToBoolean(authorizeRemoteTxRequests.value) : false;
7dde0b73
JB
352 }
353
65c5527e 354 _getLocalAuthListEnabled(): boolean {
61c2e33d 355 const localAuthListEnabled = this._getConfigurationKey('LocalAuthListEnabled');
def3d48e
JB
356 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
357 }
358
136c90ba
JB
359 async _startMessageSequence(): Promise<void> {
360 // Start WebSocket ping
361 this._startWebSocketPing();
5ad8570f 362 // Start heartbeat
6af9012e 363 this._startHeartbeat();
0a60c33c 364 // Initialize connectors status
5ad8570f 365 for (const connector in this._connectors) {
136c90ba
JB
366 if (!this._hasStopped && !this.getConnector(Utils.convertToInt(connector)).status && this.getConnector(Utils.convertToInt(connector)).bootStatus) {
367 // Send status in template at startup
368 await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
369 } else if (this._hasStopped && this.getConnector(Utils.convertToInt(connector)).bootStatus) {
370 // Send status in template after reset
371 await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).bootStatus);
372 } else if (!this._hasStopped && this.getConnector(Utils.convertToInt(connector)).status) {
373 // Send previous status at template reload
374 await this.sendStatusNotification(Utils.convertToInt(connector), this.getConnector(Utils.convertToInt(connector)).status);
5ad8570f 375 } else {
136c90ba
JB
376 // Send default status
377 await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.AVAILABLE);
5ad8570f
JB
378 }
379 }
0a60c33c 380 // Start the ATG
9ac86a7e 381 if (this._stationInfo.AutomaticTransactionGenerator.enable) {
5ad8570f
JB
382 if (!this._automaticTransactionGeneration) {
383 this._automaticTransactionGeneration = new AutomaticTransactionGenerator(this);
384 }
385 if (this._automaticTransactionGeneration.timeToStop) {
386 this._automaticTransactionGeneration.start();
387 }
388 }
8bce55bf
JB
389 if (this.getEnableStatistics()) {
390 this._statistics.start();
391 }
5ad8570f
JB
392 }
393
9ac86a7e 394 async _stopMessageSequence(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
136c90ba
JB
395 // Stop WebSocket ping
396 this._stopWebSocketPing();
79411696
JB
397 // Stop heartbeat
398 this._stopHeartbeat();
399 // Stop the ATG
9ac86a7e 400 if (this._stationInfo.AutomaticTransactionGenerator.enable &&
79411696
JB
401 this._automaticTransactionGeneration &&
402 !this._automaticTransactionGeneration.timeToStop) {
403 await this._automaticTransactionGeneration.stop(reason);
404 } else {
405 for (const connector in this._connectors) {
406 if (this.getConnector(Utils.convertToInt(connector)).transactionStarted) {
407 await this.sendStopTransaction(this.getConnector(Utils.convertToInt(connector)).transactionId, reason);
408 }
409 }
410 }
411 }
412
136c90ba
JB
413 _startWebSocketPing(): void {
414 const webSocketPingInterval: number = this._getConfigurationKey('WebSocketPingInterval') ? Utils.convertToInt(this._getConfigurationKey('WebSocketPingInterval').value) : 0;
415 if (webSocketPingInterval > 0 && !this._webSocketPingSetInterval) {
416 this._webSocketPingSetInterval = setInterval(() => {
417 if (this._wsConnection?.readyState === WebSocket.OPEN) {
3574dfd3 418 this._wsConnection.ping((): void => { });
136c90ba
JB
419 }
420 }, webSocketPingInterval * 1000);
421 logger.info(this._logPrefix() + ' WebSocket ping started every ' + Utils.secondsToHHMMSS(webSocketPingInterval));
422 } else if (this._webSocketPingSetInterval) {
423 logger.info(this._logPrefix() + ' WebSocket ping every ' + Utils.secondsToHHMMSS(webSocketPingInterval) + ' already started');
424 } else {
425 logger.error(`${this._logPrefix()} WebSocket ping interval set to ${webSocketPingInterval ? Utils.secondsToHHMMSS(webSocketPingInterval) : webSocketPingInterval}, not starting the WebSocket ping`);
426 }
427 }
428
429 _stopWebSocketPing(): void {
430 if (this._webSocketPingSetInterval) {
431 clearInterval(this._webSocketPingSetInterval);
432 this._webSocketPingSetInterval = null;
433 }
434 }
435
436 _restartWebSocketPing(): void {
437 // Stop WebSocket ping
438 this._stopWebSocketPing();
439 // Start WebSocket ping
440 this._startWebSocketPing();
441 }
442
6af9012e
JB
443 _startHeartbeat(): void {
444 if (this._heartbeatInterval && this._heartbeatInterval > 0 && !this._heartbeatSetInterval) {
136c90ba
JB
445 this._heartbeatSetInterval = setInterval(async () => {
446 await this.sendHeartbeat();
6af9012e 447 }, this._heartbeatInterval);
9ac86a7e 448 logger.info(this._logPrefix() + ' Heartbeat started every ' + Utils.milliSecondsToHHMMSS(this._heartbeatInterval));
136c90ba
JB
449 } else if (this._heartbeatSetInterval) {
450 logger.info(this._logPrefix() + ' Heartbeat every ' + Utils.milliSecondsToHHMMSS(this._heartbeatInterval) + ' already started');
7dde0b73 451 } else {
136c90ba 452 logger.error(`${this._logPrefix()} Heartbeat interval set to ${this._heartbeatInterval ? Utils.milliSecondsToHHMMSS(this._heartbeatInterval) : this._heartbeatInterval}, not starting the heartbeat`);
0a60c33c
JB
453 }
454 }
455
65c5527e 456 _stopHeartbeat(): void {
0a60c33c
JB
457 if (this._heartbeatSetInterval) {
458 clearInterval(this._heartbeatSetInterval);
459 this._heartbeatSetInterval = null;
7dde0b73 460 }
5ad8570f
JB
461 }
462
136c90ba
JB
463 _restartHeartbeat(): void {
464 // Stop heartbeat
465 this._stopHeartbeat();
466 // Start heartbeat
467 this._startHeartbeat();
468 }
469
65c5527e
JB
470 _startAuthorizationFileMonitoring(): void {
471 // eslint-disable-next-line @typescript-eslint/no-unused-vars
5ad8570f
JB
472 fs.watchFile(this._getAuthorizationFile(), (current, previous) => {
473 try {
ead548f2 474 logger.debug(this._logPrefix() + ' Authorization file ' + this._getAuthorizationFile() + ' have changed, reload');
5ad8570f
JB
475 // Initialize _authorizedTags
476 this._authorizedTags = this._loadAndGetAuthorizedTags();
477 } catch (error) {
7ec46a9a 478 logger.error(this._logPrefix() + ' Authorization file monitoring error: %j', error);
5ad8570f
JB
479 }
480 });
481 }
482
65c5527e
JB
483 _startStationTemplateFileMonitoring(): void {
484 // eslint-disable-next-line @typescript-eslint/no-unused-vars
5ad8570f
JB
485 fs.watchFile(this._stationTemplateFile, (current, previous) => {
486 try {
ead548f2 487 logger.debug(this._logPrefix() + ' Template file ' + this._stationTemplateFile + ' have changed, reload');
5ad8570f
JB
488 // Initialize
489 this._initialize();
9ac86a7e 490 if (!this._stationInfo.AutomaticTransactionGenerator.enable &&
10570d97
JB
491 this._automaticTransactionGeneration) {
492 this._automaticTransactionGeneration.stop().catch(() => { });
79411696 493 }
136c90ba 494 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
5ad8570f 495 } catch (error) {
7ec46a9a 496 logger.error(this._logPrefix() + ' Charging station template file monitoring error: %j', error);
5ad8570f
JB
497 }
498 });
499 }
500
6af9012e 501 _startMeterValues(connectorId: number, interval: number): void {
8bce55bf 502 if (!this.getConnector(connectorId).transactionStarted) {
6ecb15e4 503 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`);
5ad8570f 504 return;
8bce55bf 505 } else if (this.getConnector(connectorId).transactionStarted && !this.getConnector(connectorId).transactionId) {
6ecb15e4 506 logger.error(`${this._logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`);
5ad8570f
JB
507 return;
508 }
0a60c33c 509 if (interval > 0) {
10570d97 510 this.getConnector(connectorId).transactionSetInterval = setInterval(async () => {
8bce55bf
JB
511 if (this.getEnableStatistics()) {
512 const sendMeterValues = performance.timerify(this.sendMeterValues);
513 this._performanceObserver.observe({
514 entryTypes: ['function'],
515 });
65c5527e 516 await sendMeterValues(connectorId, interval, this);
8bce55bf 517 } else {
65c5527e 518 await this.sendMeterValues(connectorId, interval, this);
8bce55bf 519 }
0a60c33c
JB
520 }, interval);
521 } else {
9ac86a7e 522 logger.error(`${this._logPrefix()} Charging station MeterValueSampleInterval configuration set to ${Utils.milliSecondsToHHMMSS(interval)}, not sending MeterValues`);
0a60c33c 523 }
7dde0b73
JB
524 }
525
032d6efc
JB
526 _openWSConnection(options?: WebSocket.ClientOptions): void {
527 if (Utils.isUndefined(options)) {
528 options = {} as WebSocket.ClientOptions;
529 }
530 if (Utils.isUndefined(options.handshakeTimeout)) {
531 options.handshakeTimeout = this._connectionTimeout;
532 }
533 this._wsConnection = new WebSocket(this._wsConnectionUrl, 'ocpp' + Constants.OCPP_VERSION_16, options);
ead548f2 534 logger.info(this._logPrefix() + ' Will communicate through URL ' + this._supervisionUrl);
136c90ba
JB
535 }
536
537 start(): void {
538 this._openWSConnection();
2e6f5966
JB
539 // Monitor authorization file
540 this._startAuthorizationFileMonitoring();
541 // Monitor station template file
542 this._startStationTemplateFileMonitoring();
7dde0b73
JB
543 // Handle Socket incoming messages
544 this._wsConnection.on('message', this.onMessage.bind(this));
545 // Handle Socket error
546 this._wsConnection.on('error', this.onError.bind(this));
547 // Handle Socket close
548 this._wsConnection.on('close', this.onClose.bind(this));
549 // Handle Socket opening connection
550 this._wsConnection.on('open', this.onOpen.bind(this));
551 // Handle Socket ping
552 this._wsConnection.on('ping', this.onPing.bind(this));
136c90ba
JB
553 // Handle Socket pong
554 this._wsConnection.on('pong', this.onPong.bind(this));
7dde0b73
JB
555 }
556
9ac86a7e 557 async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
136c90ba 558 // Stop message sequence
10570d97 559 await this._stopMessageSequence(reason);
5ad8570f
JB
560 // eslint-disable-next-line guard-for-in
561 for (const connector in this._connectors) {
6b0ce541 562 await this.sendStatusNotification(Utils.convertToInt(connector), ChargePointStatus.UNAVAILABLE);
5ad8570f 563 }
136c90ba 564 if (this._wsConnection?.readyState === WebSocket.OPEN) {
65c5527e 565 this._wsConnection.close();
5ad8570f 566 }
9ac86a7e 567 this._hasStopped = true;
5ad8570f
JB
568 }
569
032d6efc 570 async _reconnect(error): Promise<void> {
6bf6769e 571 logger.error(this._logPrefix() + ' Socket: abnormally closed: %j', error);
136c90ba
JB
572 // Stop heartbeat
573 this._stopHeartbeat();
5ad8570f 574 // Stop the ATG if needed
9ac86a7e
JB
575 if (this._stationInfo.AutomaticTransactionGenerator.enable &&
576 this._stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
5ad8570f
JB
577 this._automaticTransactionGeneration &&
578 !this._automaticTransactionGeneration.timeToStop) {
7ec46a9a 579 this._automaticTransactionGeneration.stop().catch(() => { });
5ad8570f 580 }
032d6efc 581 if (this._autoReconnectRetryCount < this._autoReconnectMaxRetries || this._autoReconnectMaxRetries === -1) {
5ad8570f 582 this._autoReconnectRetryCount++;
032d6efc
JB
583 const reconnectDelay = (this._getReconnectExponentialDelay() ? Utils.exponentialDelay(this._autoReconnectRetryCount) : this._connectionTimeout);
584 logger.error(`${this._logPrefix()} Socket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectDelay - 100}ms`);
585 await Utils.sleep(reconnectDelay);
586 logger.error(this._logPrefix() + ' Socket: reconnecting try #' + this._autoReconnectRetryCount.toString());
3574dfd3 587 this._openWSConnection({ handshakeTimeout: reconnectDelay - 100 });
032d6efc
JB
588 } else if (this._autoReconnectMaxRetries !== -1) {
589 logger.error(`${this._logPrefix()} Socket: max retries reached (${this._autoReconnectRetryCount}) or retry disabled (${this._autoReconnectMaxRetries})`);
5ad8570f
JB
590 }
591 }
592
136c90ba 593 async onOpen(): Promise<void> {
ead548f2 594 logger.info(`${this._logPrefix()} Is connected to server through ${this._wsConnectionUrl}`);
136c90ba 595 if (!this._hasSocketRestarted || this._hasStopped) {
0bbcb3dc 596 // Send BootNotification
136c90ba 597 await this.sendBootNotification();
0bbcb3dc 598 }
136c90ba 599 await this._startMessageSequence();
9ac86a7e 600 if (this._hasSocketRestarted) {
546dec0f 601 if (!Utils.isEmptyArray(this._messageQueue)) {
63b48f77 602 this._messageQueue.forEach((message, index) => {
136c90ba 603 if (this._wsConnection?.readyState === WebSocket.OPEN) {
63b48f77 604 this._messageQueue.splice(index, 1);
7dde0b73
JB
605 this._wsConnection.send(message);
606 }
607 });
608 }
7dde0b73 609 }
136c90ba 610 this._autoReconnectRetryCount = 0;
032d6efc 611 this._hasSocketRestarted = false;
7dde0b73
JB
612 }
613
032d6efc 614 async onError(errorEvent): Promise<void> {
136c90ba 615 switch (errorEvent.code) {
7dde0b73 616 case 'ECONNREFUSED':
9ac86a7e 617 this._hasSocketRestarted = true;
032d6efc 618 await this._reconnect(errorEvent);
7dde0b73
JB
619 break;
620 default:
a324ad9b 621 logger.error(this._logPrefix() + ' Socket error: %j', errorEvent);
7dde0b73
JB
622 break;
623 }
624 }
625
032d6efc 626 async onClose(closeEvent): Promise<void> {
a324ad9b 627 switch (closeEvent) {
7dde0b73
JB
628 case 1000: // Normal close
629 case 1005:
6bf6769e 630 logger.info(this._logPrefix() + ' Socket normally closed: %j', closeEvent);
7dde0b73
JB
631 this._autoReconnectRetryCount = 0;
632 break;
633 default: // Abnormal close
9ac86a7e 634 this._hasSocketRestarted = true;
032d6efc 635 await this._reconnect(closeEvent);
7dde0b73
JB
636 break;
637 }
638 }
639
6b0ce541 640 onPing(): void {
ead548f2 641 logger.debug(this._logPrefix() + ' Has received a WS ping (rfc6455) from the server');
7dde0b73
JB
642 }
643
136c90ba
JB
644 onPong(): void {
645 logger.debug(this._logPrefix() + ' Has received a WS pong (rfc6455) from the server');
646 }
647
648 async onMessage(messageEvent: MessageEvent): Promise<void> {
2d8cee5a 649 let [messageType, messageId, commandName, commandPayload, errorDetails] = [0, '', Constants.ENTITY_CHARGING_STATION, '', ''];
7dde0b73 650 try {
2d8cee5a 651 // Parse the message
136c90ba 652 [messageType, messageId, commandName, commandPayload, errorDetails] = JSON.parse(messageEvent.toString());
2d8cee5a 653
7dde0b73
JB
654 // Check the Type of message
655 switch (messageType) {
656 // Incoming Message
f7869514 657 case Constants.OCPP_JSON_CALL_MESSAGE:
7f134aca
JB
658 if (this.getEnableStatistics()) {
659 this._statistics.addMessage(commandName, messageType);
660 }
7dde0b73 661 // Process the call
7dde0b73
JB
662 await this.handleRequest(messageId, commandName, commandPayload);
663 break;
664 // Outcome Message
f7869514 665 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73
JB
666 // Respond
667 // eslint-disable-next-line no-case-declarations
668 let responseCallback; let requestPayload;
669 if (Utils.isIterable(this._requests[messageId])) {
670 [responseCallback, , requestPayload] = this._requests[messageId];
671 } else {
5933cbc8 672 throw new Error(`Response request for message id ${messageId} is not iterable`);
7dde0b73
JB
673 }
674 if (!responseCallback) {
675 // Error
a979cc12 676 throw new Error(`Response request for unknown message id ${messageId}`);
7dde0b73
JB
677 }
678 delete this._requests[messageId];
7dde0b73
JB
679 responseCallback(commandName, requestPayload);
680 break;
681 // Error Message
f7869514 682 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
7dde0b73
JB
683 if (!this._requests[messageId]) {
684 // Error
a979cc12 685 throw new Error(`Error request for unknown message id ${messageId}`);
7dde0b73
JB
686 }
687 // eslint-disable-next-line no-case-declarations
688 let rejectCallback;
689 if (Utils.isIterable(this._requests[messageId])) {
690 [, rejectCallback] = this._requests[messageId];
691 } else {
5933cbc8 692 throw new Error(`Error request for message id ${messageId} is not iterable`);
7dde0b73
JB
693 }
694 delete this._requests[messageId];
695 rejectCallback(new OCPPError(commandName, commandPayload, errorDetails));
696 break;
697 // Error
698 default:
7f134aca
JB
699 // eslint-disable-next-line no-case-declarations
700 const errMsg = `${this._logPrefix()} Wrong message type ${messageType}`;
701 logger.error(errMsg);
702 throw new Error(errMsg);
7dde0b73
JB
703 }
704 } catch (error) {
705 // Log
a324ad9b 706 logger.error('%s Incoming message %j processing error %s on request content type %s', this._logPrefix(), messageEvent, error, this._requests[messageId]);
7dde0b73 707 // Send error
136c90ba 708 messageType !== Constants.OCPP_JSON_CALL_ERROR_MESSAGE && await this.sendError(messageId, error, commandName);
7dde0b73
JB
709 }
710 }
711
6b0ce541 712 async sendHeartbeat(): Promise<void> {
0a60c33c
JB
713 try {
714 const payload = {
715 currentTime: new Date().toISOString(),
716 };
65c5527e 717 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'Heartbeat');
0a60c33c 718 } catch (error) {
7ec46a9a 719 logger.error(this._logPrefix() + ' Send Heartbeat error: %j', error);
0a60c33c
JB
720 throw error;
721 }
722 }
723
6b0ce541 724 async sendBootNotification(): Promise<void> {
0a60c33c 725 try {
65c5527e 726 await this.sendMessage(Utils.generateUUID(), this._bootNotificationMessage, Constants.OCPP_JSON_CALL_MESSAGE, 'BootNotification');
0a60c33c 727 } catch (error) {
7ec46a9a 728 logger.error(this._logPrefix() + ' Send BootNotification error: %j', error);
0a60c33c
JB
729 throw error;
730 }
731 }
732
10570d97 733 async sendStatusNotification(connectorId: number, status: ChargePointStatus, errorCode: ChargePointErrorCode = ChargePointErrorCode.NO_ERROR): Promise<void> {
6b0ce541 734 this.getConnector(connectorId).status = status;
5ad8570f
JB
735 try {
736 const payload = {
737 connectorId,
738 errorCode,
739 status,
740 };
741 await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StatusNotification');
742 } catch (error) {
7ec46a9a 743 logger.error(this._logPrefix() + ' Send StatusNotification error: %j', error);
5ad8570f 744 throw error;
027b409a
JB
745 }
746 }
747
9ac86a7e 748 async sendStartTransaction(connectorId: number, idTag?: string): Promise<StartTransactionResponse> {
5ad8570f
JB
749 try {
750 const payload = {
bec64e8b 751 connectorId,
9ac86a7e 752 ...!Utils.isUndefined(idTag) ? { idTag } : { idTag: Constants.TRANSACTION_DEFAULT_IDTAG },
5ad8570f
JB
753 meterStart: 0,
754 timestamp: new Date().toISOString(),
755 };
9ac86a7e 756 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StartTransaction') as StartTransactionResponse;
5ad8570f 757 } catch (error) {
7ec46a9a 758 logger.error(this._logPrefix() + ' Send StartTransaction error: %j', error);
5ad8570f 759 throw error;
7dde0b73
JB
760 }
761 }
762
9ac86a7e 763 async sendStopTransaction(transactionId: number, reason: StopTransactionReason = StopTransactionReason.NONE): Promise<StopTransactionResponse> {
032d6efc 764 const idTag = this._getTransactionIdTag(transactionId);
027b409a 765 try {
38c8fd6c
JB
766 const payload = {
767 transactionId,
9ac86a7e 768 ...!Utils.isUndefined(idTag) && { idTag: idTag },
38c8fd6c
JB
769 meterStop: 0,
770 timestamp: new Date().toISOString(),
6af9012e 771 ...reason && { reason },
38c8fd6c 772 };
9ac86a7e 773 return await this.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'StopTransaction') as StartTransactionResponse;
027b409a 774 } catch (error) {
7ec46a9a 775 logger.error(this._logPrefix() + ' Send StopTransaction error: %j', error);
5ad8570f 776 throw error;
027b409a
JB
777 }
778 }
779
79411696 780 // eslint-disable-next-line consistent-this
65c5527e 781 async sendMeterValues(connectorId: number, interval: number, self: ChargingStation, debug = false): Promise<void> {
5ad8570f 782 try {
10570d97
JB
783 const sampledValues: {
784 timestamp: string;
785 sampledValue: MeterValue[];
786 } = {
5ad8570f 787 timestamp: new Date().toISOString(),
7abfea5f 788 sampledValue: [],
5ad8570f 789 };
79411696 790 const meterValuesTemplate = self.getConnector(connectorId).MeterValues;
7abfea5f 791 for (let index = 0; index < meterValuesTemplate.length; index++) {
79411696 792 const connector = self.getConnector(connectorId);
0a60c33c 793 // SoC measurand
10570d97 794 if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.STATE_OF_CHARGE && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.STATE_OF_CHARGE)) {
7abfea5f 795 sampledValues.sampledValue.push({
10570d97 796 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.PERCENT },
6af9012e 797 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
7abfea5f 798 measurand: meterValuesTemplate[index].measurand,
10570d97
JB
799 ...!Utils.isUndefined(meterValuesTemplate[index].location) ? { location: meterValuesTemplate[index].location } : { location: MeterValueLocation.EV },
800 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: Utils.getRandomInt(100).toString() },
7abfea5f
JB
801 });
802 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
10570d97
JB
803 if (Utils.convertToInt(sampledValues.sampledValue[sampledValuesIndex].value) > 100 || debug) {
804 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/100`);
5ad8570f 805 }
0a60c33c 806 // Voltage measurand
10570d97 807 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.VOLTAGE && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.VOLTAGE)) {
7f134aca 808 const voltageMeasurandValue = Utils.getRandomFloatRounded(self._getVoltageOut() + self._getVoltageOut() * 0.1, self._getVoltageOut() - self._getVoltageOut() * 0.1);
7abfea5f 809 sampledValues.sampledValue.push({
10570d97 810 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT },
6af9012e 811 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
7abfea5f 812 measurand: meterValuesTemplate[index].measurand,
6af9012e 813 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
10570d97 814 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() },
7abfea5f 815 });
79411696 816 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
e118beaa 817 const voltageValue = Utils.convertToFloat(sampledValues.sampledValue[sampledValues.sampledValue.length - 1].value);
10570d97 818 let phaseValue: string;
b2acff85 819 if (voltageValue >= 0 && voltageValue <= 250) {
7abfea5f 820 phaseValue = `L${phase}-N`;
b2acff85 821 } else if (voltageValue > 250) {
79411696 822 phaseValue = `L${phase}-L${(phase + 1) % self._getNumberOfPhases() !== 0 ? (phase + 1) % self._getNumberOfPhases() : self._getNumberOfPhases()}`;
7abfea5f
JB
823 }
824 sampledValues.sampledValue.push({
10570d97 825 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.VOLT },
6af9012e 826 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
7abfea5f 827 measurand: meterValuesTemplate[index].measurand,
6af9012e 828 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
10570d97
JB
829 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: voltageMeasurandValue.toString() },
830 phase: phaseValue as MeterValuePhase,
3f40bc9c
JB
831 });
832 }
fee83021 833 // Power.Active.Import measurand
e118beaa 834 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.POWER_ACTIVE_IMPORT && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.POWER_ACTIVE_IMPORT)) {
fee83021 835 // FIXME: factor out powerDivider checks
79411696 836 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
10570d97 837 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
fee83021
JB
838 logger.error(errMsg);
839 throw Error(errMsg);
79411696 840 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
10570d97 841 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
fee83021
JB
842 logger.error(errMsg);
843 throw Error(errMsg);
844 }
10570d97
JB
845 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
846 const powerMeasurandValues = {} as MeasurandValues;
79411696
JB
847 const maxPower = Math.round(self._stationInfo.maxPower / self._stationInfo.powerDivider);
848 const maxPowerPerPhase = Math.round((self._stationInfo.maxPower / self._stationInfo.powerDivider) / self._getNumberOfPhases());
849 switch (self._getPowerOutType()) {
9ac86a7e 850 case PowerOutType.AC:
fee83021
JB
851 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
852 powerMeasurandValues.L1 = Utils.getRandomFloatRounded(maxPowerPerPhase);
853 powerMeasurandValues.L2 = 0;
854 powerMeasurandValues.L3 = 0;
79411696 855 if (self._getNumberOfPhases() === 3) {
fee83021
JB
856 powerMeasurandValues.L2 = Utils.getRandomFloatRounded(maxPowerPerPhase);
857 powerMeasurandValues.L3 = Utils.getRandomFloatRounded(maxPowerPerPhase);
858 }
10570d97 859 powerMeasurandValues.allPhases = Utils.roundTo(powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, 2);
fee83021
JB
860 }
861 break;
9ac86a7e 862 case PowerOutType.DC:
fee83021 863 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
10570d97 864 powerMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxPower);
fee83021
JB
865 }
866 break;
867 default:
868 logger.error(errMsg);
869 throw Error(errMsg);
870 }
871 sampledValues.sampledValue.push({
10570d97 872 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT },
6af9012e 873 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
fee83021 874 measurand: meterValuesTemplate[index].measurand,
6af9012e 875 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
10570d97 876 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues.allPhases.toString() },
fee83021
JB
877 });
878 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
10570d97
JB
879 if (Utils.convertToFloat(sampledValues.sampledValue[sampledValuesIndex].value) > maxPower || debug) {
880 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxPower}`);
fee83021 881 }
79411696 882 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
fee83021
JB
883 const phaseValue = `L${phase}-N`;
884 sampledValues.sampledValue.push({
10570d97 885 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT },
6af9012e
JB
886 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
887 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
888 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
7ec46a9a 889 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: powerMeasurandValues[`L${phase}`] as string },
10570d97 890 phase: phaseValue as MeterValuePhase,
fee83021
JB
891 });
892 }
3f40bc9c 893 // Current.Import measurand
10570d97 894 } else if (meterValuesTemplate[index].measurand && meterValuesTemplate[index].measurand === MeterValueMeasurand.CURRENT_IMPORT && self._getConfigurationKey('MeterValuesSampledData').value.includes(MeterValueMeasurand.CURRENT_IMPORT)) {
3f40bc9c 895 // FIXME: factor out powerDivider checks
79411696 896 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
10570d97 897 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
3f40bc9c
JB
898 logger.error(errMsg);
899 throw Error(errMsg);
79411696 900 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
10570d97 901 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
3f40bc9c
JB
902 logger.error(errMsg);
903 throw Error(errMsg);
904 }
10570d97 905 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: Unknown ${self._getPowerOutType()} powerOutType in template file ${self._stationTemplateFile}, cannot calculate ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} measurand value`;
9ac86a7e 906 const currentMeasurandValues: MeasurandValues = {} as MeasurandValues;
10570d97 907 let maxAmperage: number;
79411696 908 switch (self._getPowerOutType()) {
9ac86a7e 909 case PowerOutType.AC:
79411696 910 maxAmperage = ElectricUtils.ampPerPhaseFromPower(self._getNumberOfPhases(), self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
b2acff85
JB
911 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
912 currentMeasurandValues.L1 = Utils.getRandomFloatRounded(maxAmperage);
913 currentMeasurandValues.L2 = 0;
914 currentMeasurandValues.L3 = 0;
79411696 915 if (self._getNumberOfPhases() === 3) {
b2acff85
JB
916 currentMeasurandValues.L2 = Utils.getRandomFloatRounded(maxAmperage);
917 currentMeasurandValues.L3 = Utils.getRandomFloatRounded(maxAmperage);
918 }
10570d97 919 currentMeasurandValues.allPhases = Utils.roundTo((currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / self._getNumberOfPhases(), 2);
b2acff85
JB
920 }
921 break;
9ac86a7e 922 case PowerOutType.DC:
79411696 923 maxAmperage = ElectricUtils.ampTotalFromPower(self._stationInfo.maxPower / self._stationInfo.powerDivider, self._getVoltageOut());
fee83021 924 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
10570d97 925 currentMeasurandValues.allPhases = Utils.getRandomFloatRounded(maxAmperage);
fee83021 926 }
b2acff85
JB
927 break;
928 default:
929 logger.error(errMsg);
930 throw Error(errMsg);
3f40bc9c
JB
931 }
932 sampledValues.sampledValue.push({
10570d97 933 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP },
6af9012e 934 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
3f40bc9c 935 measurand: meterValuesTemplate[index].measurand,
6af9012e 936 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
10570d97 937 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues.allPhases.toString() },
3f40bc9c
JB
938 });
939 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
10570d97
JB
940 if (Utils.convertToFloat(sampledValues.sampledValue[sampledValuesIndex].value) > maxAmperage || debug) {
941 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxAmperage}`);
3f40bc9c 942 }
79411696 943 for (let phase = 1; self._getNumberOfPhases() === 3 && phase <= self._getNumberOfPhases(); phase++) {
3f40bc9c
JB
944 const phaseValue = `L${phase}`;
945 sampledValues.sampledValue.push({
10570d97 946 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.AMP },
6af9012e
JB
947 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
948 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
949 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
7ec46a9a 950 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } : { value: currentMeasurandValues[phaseValue] as string },
10570d97 951 phase: phaseValue as MeterValuePhase,
7abfea5f
JB
952 });
953 }
0a60c33c 954 // Energy.Active.Import.Register measurand (default)
10570d97 955 } else if (!meterValuesTemplate[index].measurand || meterValuesTemplate[index].measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
38c8fd6c 956 // FIXME: factor out powerDivider checks
79411696 957 if (Utils.isUndefined(self._stationInfo.powerDivider)) {
10570d97 958 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider is undefined`;
6ecb15e4
JB
959 logger.error(errMsg);
960 throw Error(errMsg);
79411696 961 } else if (self._stationInfo.powerDivider && self._stationInfo.powerDivider <= 0) {
10570d97 962 const errMsg = `${self._logPrefix()} MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: powerDivider have zero or below value ${self._stationInfo.powerDivider}`;
6ecb15e4
JB
963 logger.error(errMsg);
964 throw Error(errMsg);
965 }
7abfea5f 966 if (Utils.isUndefined(meterValuesTemplate[index].value)) {
79411696 967 const measurandValue = Utils.getRandomInt(self._stationInfo.maxPower / (self._stationInfo.powerDivider * 3600000) * interval);
9b25a525 968 // Persist previous value in connector
3f40bc9c 969 if (connector && !Utils.isNullOrUndefined(connector.lastEnergyActiveImportRegisterValue) && connector.lastEnergyActiveImportRegisterValue >= 0) {
9b25a525
JB
970 connector.lastEnergyActiveImportRegisterValue += measurandValue;
971 } else {
972 connector.lastEnergyActiveImportRegisterValue = 0;
973 }
5ad8570f 974 }
7abfea5f 975 sampledValues.sampledValue.push({
10570d97 976 ...!Utils.isUndefined(meterValuesTemplate[index].unit) ? { unit: meterValuesTemplate[index].unit } : { unit: MeterValueUnit.WATT_HOUR },
6af9012e
JB
977 ...!Utils.isUndefined(meterValuesTemplate[index].context) && { context: meterValuesTemplate[index].context },
978 ...!Utils.isUndefined(meterValuesTemplate[index].measurand) && { measurand: meterValuesTemplate[index].measurand },
979 ...!Utils.isUndefined(meterValuesTemplate[index].location) && { location: meterValuesTemplate[index].location },
7ec46a9a
JB
980 ...!Utils.isUndefined(meterValuesTemplate[index].value) ? { value: meterValuesTemplate[index].value } :
981 { value: connector.lastEnergyActiveImportRegisterValue.toString() },
7abfea5f
JB
982 });
983 const sampledValuesIndex = sampledValues.sampledValue.length - 1;
79411696 984 const maxConsumption = Math.round(self._stationInfo.maxPower * 3600 / (self._stationInfo.powerDivider * interval));
10570d97
JB
985 if (Utils.convertToFloat(sampledValues.sampledValue[sampledValuesIndex].value) > maxConsumption || debug) {
986 logger.error(`${self._logPrefix()} MeterValues measurand ${sampledValues.sampledValue[sampledValuesIndex].measurand ? sampledValues.sampledValue[sampledValuesIndex].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER}: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${sampledValues.sampledValue[sampledValuesIndex].value}/${maxConsumption}`);
5ad8570f 987 }
0a60c33c
JB
988 // Unsupported measurand
989 } else {
10570d97 990 logger.info(`${self._logPrefix()} Unsupported MeterValues measurand ${meterValuesTemplate[index].measurand ? meterValuesTemplate[index].measurand : MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER} on connectorId ${connectorId}`);
5ad8570f
JB
991 }
992 }
993
994 const payload = {
bec64e8b 995 connectorId,
79411696 996 transactionId: self.getConnector(connectorId).transactionId,
7abfea5f 997 meterValue: sampledValues,
5ad8570f 998 };
79411696 999 await self.sendMessage(Utils.generateUUID(), payload, Constants.OCPP_JSON_CALL_MESSAGE, 'MeterValues');
5ad8570f 1000 } catch (error) {
7ec46a9a 1001 logger.error(self._logPrefix() + ' Send MeterValues error: %j', error);
0a60c33c 1002 throw error;
5ad8570f
JB
1003 }
1004 }
1005
e118beaa 1006 async sendError(messageId: string, err: Error | OCPPError, commandName: string): Promise<unknown> {
7f134aca
JB
1007 // Check exception type: only OCPP error are accepted
1008 const error = err instanceof OCPPError ? err : new OCPPError(Constants.OCPP_ERROR_INTERNAL_ERROR, err.message, err.stack && err.stack);
5ad8570f 1009 // Send error
7f134aca 1010 return this.sendMessage(messageId, error, Constants.OCPP_JSON_CALL_ERROR_MESSAGE, commandName);
027b409a
JB
1011 }
1012
9ac86a7e 1013 async sendMessage(messageId: string, commandParams, messageType = Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName: string): Promise<any> {
65c5527e 1014 // eslint-disable-next-line @typescript-eslint/no-this-alias
7dde0b73 1015 const self = this;
6af9012e 1016 // Send a message through wsConnection
7dde0b73
JB
1017 return new Promise((resolve, reject) => {
1018 let messageToSend;
1019 // Type of message
1020 switch (messageType) {
1021 // Request
f7869514 1022 case Constants.OCPP_JSON_CALL_MESSAGE:
7dde0b73 1023 // Build request
7f134aca
JB
1024 this._requests[messageId] = [responseCallback, rejectCallback, commandParams];
1025 messageToSend = JSON.stringify([messageType, messageId, commandName, commandParams]);
7dde0b73
JB
1026 break;
1027 // Response
f7869514 1028 case Constants.OCPP_JSON_CALL_RESULT_MESSAGE:
7dde0b73 1029 // Build response
7f134aca 1030 messageToSend = JSON.stringify([messageType, messageId, commandParams]);
7dde0b73
JB
1031 break;
1032 // Error Message
f7869514 1033 case Constants.OCPP_JSON_CALL_ERROR_MESSAGE:
a979cc12 1034 // Build Error Message
7f134aca 1035 messageToSend = JSON.stringify([messageType, messageId, commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : '', commandParams.details ? commandParams.details : {}]);
7dde0b73
JB
1036 break;
1037 }
2e6f5966 1038 // Check if wsConnection is ready
136c90ba 1039 if (this._wsConnection?.readyState === WebSocket.OPEN) {
7f134aca
JB
1040 if (this.getEnableStatistics()) {
1041 this._statistics.addMessage(commandName, messageType);
1042 }
7dde0b73
JB
1043 // Yes: Send Message
1044 this._wsConnection.send(messageToSend);
1045 } else {
7f134aca
JB
1046 let dups = false;
1047 // Handle dups in buffer
1048 for (const message of this._messageQueue) {
1049 // Same message
1050 if (JSON.stringify(messageToSend) === JSON.stringify(message)) {
1051 dups = true;
1052 break;
1053 }
1054 }
1055 if (!dups) {
1056 // Buffer message
1057 this._messageQueue.push(messageToSend);
1058 }
a979cc12 1059 // Reject it
136c90ba 1060 return rejectCallback(new OCPPError(commandParams.code ? commandParams.code : Constants.OCPP_ERROR_GENERIC_ERROR, commandParams.message ? commandParams.message : `WebSocket closed for message id '${messageId}' with content '${messageToSend}', message buffered`, commandParams.details ? commandParams.details : {}));
7dde0b73 1061 }
a979cc12
JB
1062 // Response?
1063 if (messageType === Constants.OCPP_JSON_CALL_RESULT_MESSAGE) {
7dde0b73
JB
1064 // Yes: send Ok
1065 resolve();
a979cc12
JB
1066 } else if (messageType === Constants.OCPP_JSON_CALL_ERROR_MESSAGE) {
1067 // Send timeout
7f134aca 1068 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);
7dde0b73
JB
1069 }
1070
1071 // Function that will receive the request's response
7f134aca
JB
1072 function responseCallback(payload, requestPayload): void {
1073 if (self.getEnableStatistics()) {
1074 self._statistics.addMessage(commandName, messageType);
1075 }
7dde0b73 1076 // Send the response
a979cc12 1077 self.handleResponse(commandName, payload, requestPayload);
7dde0b73
JB
1078 resolve(payload);
1079 }
1080
1081 // Function that will receive the request's rejection
7f134aca 1082 function rejectCallback(error: OCPPError): void {
8bce55bf 1083 if (self.getEnableStatistics()) {
7f134aca 1084 self._statistics.addMessage(commandName, messageType);
8bce55bf 1085 }
6bf6769e 1086 logger.debug(`${self._logPrefix()} Error: %j occurred when calling command %s with parameters: %j`, error, commandName, commandParams);
7dde0b73
JB
1087 // Build Exception
1088 // eslint-disable-next-line no-empty-function
e118beaa 1089 self._requests[messageId] = [() => { }, () => { }, {}]; // Properly format the request
7dde0b73
JB
1090 // Send error
1091 reject(error);
1092 }
1093 });
1094 }
1095
10570d97 1096 handleResponse(commandName: string, payload, requestPayload): void {
3f40bc9c 1097 const responseCallbackFn = 'handleResponse' + commandName;
6af9012e
JB
1098 if (typeof this[responseCallbackFn] === 'function') {
1099 this[responseCallbackFn](payload, requestPayload);
3f40bc9c 1100 } else {
6af9012e 1101 logger.error(this._logPrefix() + ' Trying to call an undefined response callback function: ' + responseCallbackFn);
3f40bc9c
JB
1102 }
1103 }
1104
10570d97 1105 handleResponseBootNotification(payload, requestPayload): void {
5ad8570f 1106 if (payload.status === 'Accepted') {
136c90ba
JB
1107 this._heartbeatInterval = Utils.convertToInt(payload.interval) * 1000;
1108 this._heartbeatSetInterval ? this._restartHeartbeat() : this._startHeartbeat();
10570d97
JB
1109 this._addConfigurationKey('HeartBeatInterval', payload.interval);
1110 this._addConfigurationKey('HeartbeatInterval', payload.interval, false, false);
9ac86a7e 1111 this._hasStopped && (this._hasStopped = false);
0a60c33c 1112 } else if (payload.status === 'Pending') {
fda4af57 1113 logger.info(this._logPrefix() + ' Charging station in pending state on the central server');
5ad8570f 1114 } else {
ead548f2 1115 logger.info(this._logPrefix() + ' Charging station rejected by the central server');
7dde0b73 1116 }
7dde0b73
JB
1117 }
1118
10570d97 1119 _initTransactionOnConnector(connectorId: number): void {
8bce55bf
JB
1120 this.getConnector(connectorId).transactionStarted = false;
1121 this.getConnector(connectorId).transactionId = null;
1122 this.getConnector(connectorId).idTag = null;
1123 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = -1;
0a60c33c
JB
1124 }
1125
10570d97 1126 _resetTransactionOnConnector(connectorId: number): void {
bec64e8b 1127 this._initTransactionOnConnector(connectorId);
8bce55bf
JB
1128 if (this.getConnector(connectorId).transactionSetInterval) {
1129 clearInterval(this.getConnector(connectorId).transactionSetInterval);
027b409a
JB
1130 }
1131 }
1132
9ac86a7e 1133 handleResponseStartTransaction(payload: StartTransactionResponse, requestPayload): void {
7ec46a9a
JB
1134 const connectorId = Utils.convertToInt(requestPayload.connectorId);
1135 if (this.getConnector(connectorId).transactionStarted) {
ab24beae 1136 logger.debug(this._logPrefix() + ' Trying to start a transaction on an already used connector ' + connectorId.toString() + ': %j', this.getConnector(connectorId));
2d0e26f5 1137 return;
d3a7883e 1138 }
84393381 1139
9ac86a7e 1140 let transactionConnectorId: number;
7de604f9 1141 for (const connector in this._connectors) {
7ec46a9a 1142 if (Utils.convertToInt(connector) === connectorId) {
9ac86a7e 1143 transactionConnectorId = Utils.convertToInt(connector);
7de604f9 1144 break;
7dde0b73 1145 }
7de604f9
JB
1146 }
1147 if (!transactionConnectorId) {
ab24beae 1148 logger.error(this._logPrefix() + ' Trying to start a transaction on a non existing connector Id ' + connectorId.toString());
7de604f9
JB
1149 return;
1150 }
9ac86a7e 1151 if (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
7ec46a9a
JB
1152 this.getConnector(connectorId).transactionStarted = true;
1153 this.getConnector(connectorId).transactionId = payload.transactionId;
1154 this.getConnector(connectorId).idTag = requestPayload.idTag;
1155 this.getConnector(connectorId).lastEnergyActiveImportRegisterValue = 0;
1156 this.sendStatusNotification(connectorId, ChargePointStatus.CHARGING).catch(() => { });
1157 logger.info(this._logPrefix() + ' Transaction ' + payload.transactionId.toString() + ' STARTED on ' + this._stationInfo.name + '#' + connectorId.toString() + ' for idTag ' + requestPayload.idTag);
6ecb15e4
JB
1158 if (this._stationInfo.powerSharedByConnectors) {
1159 this._stationInfo.powerDivider++;
1160 }
7de604f9 1161 const configuredMeterValueSampleInterval = this._getConfigurationKey('MeterValueSampleInterval');
7ec46a9a 1162 this._startMeterValues(connectorId,
e118beaa 1163 configuredMeterValueSampleInterval ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000 : 60000);
7dde0b73 1164 } else {
7ec46a9a
JB
1165 logger.error(this._logPrefix() + ' Starting transaction id ' + payload.transactionId.toString() + ' REJECTED with status ' + payload.idTagInfo?.status + ', idTag ' + requestPayload.idTag);
1166 this._resetTransactionOnConnector(connectorId);
1167 this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE).catch(() => { });
7dde0b73
JB
1168 }
1169 }
1170
9ac86a7e
JB
1171 handleResponseStopTransaction(payload: StopTransactionResponse, requestPayload): void {
1172 let transactionConnectorId: number;
d3a7883e 1173 for (const connector in this._connectors) {
7ec46a9a 1174 if (this.getConnector(Utils.convertToInt(connector)).transactionId === Utils.convertToInt(requestPayload.transactionId)) {
9ac86a7e 1175 transactionConnectorId = Utils.convertToInt(connector);
d3a7883e
JB
1176 break;
1177 }
1178 }
1179 if (!transactionConnectorId) {
ab24beae 1180 logger.error(this._logPrefix() + ' Trying to stop a non existing transaction ' + requestPayload.transactionId);
7de604f9 1181 return;
d3a7883e 1182 }
9ac86a7e 1183 if (payload.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
7ec46a9a 1184 this.sendStatusNotification(transactionConnectorId, ChargePointStatus.AVAILABLE).catch(() => { });
6ecb15e4
JB
1185 if (this._stationInfo.powerSharedByConnectors) {
1186 this._stationInfo.powerDivider--;
1187 }
9ac86a7e 1188 logger.info(this._logPrefix() + ' Transaction ' + requestPayload.transactionId + ' STOPPED on ' + this._stationInfo.name + '#' + transactionConnectorId.toString());
d3a7883e 1189 this._resetTransactionOnConnector(transactionConnectorId);
34dcb3b5 1190 } else {
9ac86a7e 1191 logger.error(this._logPrefix() + ' Stopping transaction id ' + requestPayload.transactionId + ' REJECTED with status ' + payload.idTagInfo?.status);
34dcb3b5
JB
1192 }
1193 }
1194
10570d97 1195 handleResponseStatusNotification(payload, requestPayload): void {
ead548f2 1196 logger.debug(this._logPrefix() + ' Status notification response received: %j to StatusNotification request: %j', payload, requestPayload);
7dde0b73
JB
1197 }
1198
10570d97 1199 handleResponseMeterValues(payload, requestPayload): void {
ead548f2 1200 logger.debug(this._logPrefix() + ' MeterValues response received: %j to MeterValues request: %j', payload, requestPayload);
027b409a
JB
1201 }
1202
10570d97 1203 handleResponseHeartbeat(payload, requestPayload): void {
ead548f2 1204 logger.debug(this._logPrefix() + ' Heartbeat response received: %j to Heartbeat request: %j', payload, requestPayload);
7dde0b73
JB
1205 }
1206
e118beaa 1207 async handleRequest(messageId: string, commandName: string, commandPayload): Promise<void> {
3f40bc9c 1208 let response;
7dde0b73 1209 // Call
fda4af57 1210 if (typeof this['handleRequest' + commandName] === 'function') {
7dde0b73 1211 try {
3f40bc9c 1212 // Call the method to build the response
fda4af57 1213 response = await this['handleRequest' + commandName](commandPayload);
7dde0b73
JB
1214 } catch (error) {
1215 // Log
7ec46a9a 1216 logger.error(this._logPrefix() + ' Handle request error: %j', error);
facd8ebd 1217 // Send back response to inform backend
7f134aca
JB
1218 await this.sendError(messageId, error, commandName);
1219 throw error;
7dde0b73
JB
1220 }
1221 } else {
84393381 1222 // Throw exception
64dc325e 1223 await this.sendError(messageId, new OCPPError(Constants.OCPP_ERROR_NOT_IMPLEMENTED, `${commandName} is not implemented`, {}), commandName);
7dde0b73
JB
1224 throw new Error(`${commandName} is not implemented ${JSON.stringify(commandPayload, null, ' ')}`);
1225 }
84393381 1226 // Send response
7f134aca 1227 await this.sendMessage(messageId, response, Constants.OCPP_JSON_CALL_RESULT_MESSAGE, commandName);
7dde0b73
JB
1228 }
1229
fda4af57 1230 // Simulate charging station restart
9ac86a7e 1231 handleRequestReset(commandPayload): DefaultRequestResponse {
5ad8570f 1232 setImmediate(async () => {
9ac86a7e 1233 await this.stop(commandPayload.type + 'Reset' as StopTransactionReason);
0a60c33c 1234 await Utils.sleep(this._stationInfo.resetTime);
5ad8570f
JB
1235 await this.start();
1236 });
9ac86a7e 1237 logger.info(`${this._logPrefix()} ${commandPayload.type} reset command received, simulating it. The station will be back online in ${Utils.milliSecondsToHHMMSS(this._stationInfo.resetTime)}`);
5ad8570f
JB
1238 return Constants.OCPP_RESPONSE_ACCEPTED;
1239 }
1240
9ac86a7e
JB
1241 async handleRequestUnlockConnector(commandPayload): Promise<UnlockResponse> {
1242 const connectorId = Utils.convertToInt(commandPayload.connectorId);
1243 if (connectorId === 0) {
ab24beae 1244 logger.error(this._logPrefix() + ' Trying to unlock connector ' + connectorId.toString());
9ac86a7e
JB
1245 return Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED;
1246 }
1247 if (this.getConnector(connectorId).transactionStarted) {
1248 const stopResponse = await this.sendStopTransaction(this.getConnector(connectorId).transactionId, StopTransactionReason.UNLOCK_COMMAND);
1249 if (stopResponse.idTagInfo?.status === AuthorizationStatus.ACCEPTED) {
1250 return Constants.OCPP_RESPONSE_UNLOCKED;
1251 }
1252 return Constants.OCPP_RESPONSE_UNLOCK_FAILED;
1253 }
1254 await this.sendStatusNotification(connectorId, ChargePointStatus.AVAILABLE);
1255 return Constants.OCPP_RESPONSE_UNLOCKED;
1256 }
1257
e118beaa 1258 _getConfigurationKey(key: string): ConfigurationKey {
61c2e33d
JB
1259 return this._configuration.configurationKey.find((configElement) => configElement.key === key);
1260 }
1261
10570d97 1262 _addConfigurationKey(key: string, value: string, readonly = false, visible = true, reboot = false): void {
61c2e33d
JB
1263 const keyFound = this._getConfigurationKey(key);
1264 if (!keyFound) {
1265 this._configuration.configurationKey.push({
1266 key,
1267 readonly,
1268 value,
1269 visible,
3497da01 1270 reboot,
61c2e33d
JB
1271 });
1272 }
1273 }
1274
10570d97 1275 _setConfigurationKeyValue(key: string, value: string): void {
61c2e33d
JB
1276 const keyFound = this._getConfigurationKey(key);
1277 if (keyFound) {
d3a7883e
JB
1278 const keyIndex = this._configuration.configurationKey.indexOf(keyFound);
1279 this._configuration.configurationKey[keyIndex].value = value;
61c2e33d
JB
1280 }
1281 }
1282
e118beaa
JB
1283 handleRequestGetConfiguration(commandPayload): { configurationKey: ConfigurationKey[]; unknownKey: string[] } {
1284 const configurationKey: ConfigurationKey[] = [];
1285 const unknownKey: string[] = [];
61c2e33d
JB
1286 if (Utils.isEmptyArray(commandPayload.key)) {
1287 for (const configuration of this._configuration.configurationKey) {
1288 if (Utils.isUndefined(configuration.visible)) {
1289 configuration.visible = true;
61c2e33d
JB
1290 }
1291 if (!configuration.visible) {
1292 continue;
1293 }
1294 configurationKey.push({
1295 key: configuration.key,
1296 readonly: configuration.readonly,
1297 value: configuration.value,
1298 });
facd8ebd 1299 }
61c2e33d 1300 } else {
9ac86a7e
JB
1301 for (const key of commandPayload.key as string[]) {
1302 const keyFound = this._getConfigurationKey(key);
61c2e33d
JB
1303 if (keyFound) {
1304 if (Utils.isUndefined(keyFound.visible)) {
1305 keyFound.visible = true;
61c2e33d
JB
1306 }
1307 if (!keyFound.visible) {
1308 continue;
1309 }
1310 configurationKey.push({
1311 key: keyFound.key,
1312 readonly: keyFound.readonly,
1313 value: keyFound.value,
1314 });
1315 } else {
9ac86a7e 1316 unknownKey.push(key);
61c2e33d 1317 }
facd8ebd 1318 }
facd8ebd
JB
1319 }
1320 return {
1321 configurationKey,
1322 unknownKey,
1323 };
7dde0b73
JB
1324 }
1325
9ac86a7e 1326 handleRequestChangeConfiguration(commandPayload): ConfigurationResponse {
61c2e33d 1327 const keyToChange = this._getConfigurationKey(commandPayload.key);
7d887a1b 1328 if (!keyToChange) {
9ac86a7e
JB
1329 return Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED;
1330 } else if (keyToChange && keyToChange.readonly) {
1331 return Constants.OCPP_CONFIGURATION_RESPONSE_REJECTED;
1332 } else if (keyToChange && !keyToChange.readonly) {
a6e68f34 1333 const keyIndex = this._configuration.configurationKey.indexOf(keyToChange);
136c90ba
JB
1334 let valueChanged = false;
1335 if (this._configuration.configurationKey[keyIndex].value !== commandPayload.value) {
1336 this._configuration.configurationKey[keyIndex].value = commandPayload.value as string;
1337 valueChanged = true;
1338 }
d3a7883e 1339 let triggerHeartbeatRestart = false;
136c90ba 1340 if (keyToChange.key === 'HeartBeatInterval' && valueChanged) {
d3a7883e
JB
1341 this._setConfigurationKeyValue('HeartbeatInterval', commandPayload.value);
1342 triggerHeartbeatRestart = true;
1343 }
136c90ba 1344 if (keyToChange.key === 'HeartbeatInterval' && valueChanged) {
d3a7883e
JB
1345 this._setConfigurationKeyValue('HeartBeatInterval', commandPayload.value);
1346 triggerHeartbeatRestart = true;
1347 }
1348 if (triggerHeartbeatRestart) {
5c68da4d 1349 this._heartbeatInterval = Utils.convertToInt(commandPayload.value) * 1000;
136c90ba
JB
1350 this._restartHeartbeat();
1351 }
1352 if (keyToChange.key === 'WebSocketPingInterval' && valueChanged) {
1353 this._restartWebSocketPing();
5c68da4d 1354 }
9ac86a7e
JB
1355 if (keyToChange.reboot) {
1356 return Constants.OCPP_CONFIGURATION_RESPONSE_REBOOT_REQUIRED;
7d887a1b 1357 }
9ac86a7e 1358 return Constants.OCPP_CONFIGURATION_RESPONSE_ACCEPTED;
7dde0b73 1359 }
7dde0b73
JB
1360 }
1361
9ac86a7e
JB
1362 async handleRequestRemoteStartTransaction(commandPayload): Promise<DefaultRequestResponse> {
1363 const transactionConnectorID: number = commandPayload.connectorId ? Utils.convertToInt(commandPayload.connectorId) : 1;
fda4af57 1364 if (this._getAuthorizeRemoteTxRequests() && this._getLocalAuthListEnabled() && this.hasAuthorizedTags()) {
dcab13bd 1365 // Check if authorized
2e6f5966 1366 if (this._authorizedTags.find((value) => value === commandPayload.idTag)) {
7dde0b73 1367 // Authorization successful start transaction
65c5527e 1368 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
9ac86a7e 1369 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag);
dcab13bd 1370 return Constants.OCPP_RESPONSE_ACCEPTED;
7dde0b73 1371 }
9ac86a7e 1372 logger.error(this._logPrefix() + ' Remote starting transaction REJECTED with status ' + commandPayload.idTagInfo?.status + ', idTag ' + commandPayload.idTag);
dcab13bd 1373 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 1374 }
dcab13bd 1375 // No local authorization check required => start transaction
65c5527e 1376 await this.sendStartTransaction(transactionConnectorID, commandPayload.idTag);
9ac86a7e 1377 logger.debug(this._logPrefix() + ' Transaction remotely STARTED on ' + this._stationInfo.name + '#' + transactionConnectorID.toString() + ' for idTag ' + commandPayload.idTag);
027b409a
JB
1378 return Constants.OCPP_RESPONSE_ACCEPTED;
1379 }
1380
9ac86a7e
JB
1381 async handleRequestRemoteStopTransaction(commandPayload): Promise<DefaultRequestResponse> {
1382 const transactionId = Utils.convertToInt(commandPayload.transactionId);
027b409a 1383 for (const connector in this._connectors) {
9ac86a7e
JB
1384 if (this.getConnector(Utils.convertToInt(connector)).transactionId === transactionId) {
1385 await this.sendStopTransaction(transactionId);
d3a7883e 1386 return Constants.OCPP_RESPONSE_ACCEPTED;
027b409a
JB
1387 }
1388 }
ab24beae 1389 logger.info(this._logPrefix() + ' Trying to remote stop a non existing transaction ' + transactionId.toString());
d3a7883e 1390 return Constants.OCPP_RESPONSE_REJECTED;
7dde0b73 1391 }
7dde0b73
JB
1392}
1393