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