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