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