Fix cut&paste typo
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
cc6e8ab5 3import { ACElectricUtils, DCElectricUtils } from '../utils/ElectricUtils';
e7aeea18
JB
4import {
5 AvailabilityType,
6 BootNotificationRequest,
7 CachedRequest,
ef6fa3fb 8 HeartbeatRequest,
e7aeea18
JB
9 IncomingRequest,
10 IncomingRequestCommand,
ef6fa3fb 11 MeterValuesRequest,
e7aeea18 12 RequestCommand,
ef6fa3fb 13 StatusNotificationRequest,
e7aeea18 14} from '../types/ocpp/Requests';
f22266fd
JB
15import {
16 BootNotificationResponse,
b3ec7bc1 17 ErrorResponse,
f22266fd
JB
18 HeartbeatResponse,
19 MeterValuesResponse,
20 RegistrationStatus,
b3ec7bc1 21 Response,
f22266fd
JB
22 StatusNotificationResponse,
23} from '../types/ocpp/Responses';
17ac262c 24import { ChargingProfile, ChargingRateUnitType } from '../types/ocpp/ChargingProfile';
e7aeea18
JB
25import ChargingStationTemplate, {
26 CurrentType,
27 PowerUnits,
2484ac1e 28 WsOptions,
e7aeea18
JB
29} from '../types/ChargingStationTemplate';
30import {
31 ConnectorPhaseRotation,
32 StandardParametersKey,
33 SupportedFeatureProfiles,
34 VendorDefaultParametersKey,
35} from '../types/ocpp/Configuration';
492cf6ab 36import { MeterValue, MeterValueMeasurand } from '../types/ocpp/MeterValues';
ef6fa3fb
JB
37import {
38 StopTransactionReason,
39 StopTransactionRequest,
40 StopTransactionResponse,
41} from '../types/ocpp/Transaction';
16b0d4e7 42import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
2484ac1e 43import WebSocket, { Data, OPEN, RawData } from 'ws';
3f40bc9c 44
6af9012e 45import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
fa7bccf4 46import { AutomaticTransactionGeneratorConfiguration } from '../types/AutomaticTransactionGenerator';
94ec7e96 47import BaseError from '../exception/BaseError';
93b4a429 48import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
c0560973 49import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
7c72977b
JB
50import { ChargingStationCache } from './ChargingStationCache';
51import ChargingStationConfiguration from '../types/ChargingStationConfiguration';
17ac262c 52import { ChargingStationConfigurationUtils } from './ChargingStationConfigurationUtils';
9ac86a7e 53import ChargingStationInfo from '../types/ChargingStationInfo';
17ac262c
JB
54import ChargingStationOcppConfiguration from '../types/ChargingStationOcppConfiguration';
55import { ChargingStationUtils } from './ChargingStationUtils';
ee0f106b 56import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
6af9012e 57import Configuration from '../utils/Configuration';
057e2042 58import { ConnectorStatus } from '../types/ConnectorStatus';
63b48f77 59import Constants from '../utils/Constants';
14763b46 60import { ErrorType } from '../types/ocpp/ErrorType';
a95873d8 61import { FileType } from '../types/FileType';
23132a44 62import FileUtils from '../utils/FileUtils';
d1888640 63import { JsonType } from '../types/JsonType';
d2a64eb5 64import { MessageType } from '../types/ocpp/MessageType';
e7171280 65import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
c0560973
JB
66import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
67import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
68c993d5 68import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
e58068fd 69import OCPPError from '../exception/OCPPError';
c0560973
JB
70import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
71import OCPPRequestService from './ocpp/OCPPRequestService';
72import { OCPPVersion } from '../types/ocpp/OCPPVersion';
a6b3c6c3 73import PerformanceStatistics from '../performance/PerformanceStatistics';
2dcfe98e 74import { SupervisionUrlDistribution } from '../types/ConfigurationData';
57939a9d 75import { URL } from 'url';
6af9012e 76import Utils from '../utils/Utils';
3f40bc9c
JB
77import crypto from 'crypto';
78import fs from 'fs';
9f2e3130 79import logger from '../utils/Logger';
ee0f106b 80import { parentPort } from 'worker_threads';
bf1866b2 81import path from 'path';
3f40bc9c
JB
82
83export default class ChargingStation {
3f94cab5 84 public hashId!: string;
2484ac1e 85 public readonly templateFile: string;
c0560973 86 public authorizedTags: string[];
6e0964c8 87 public stationInfo!: ChargingStationInfo;
9e23580d 88 public readonly connectors: Map<number, ConnectorStatus>;
2484ac1e 89 public ocppConfiguration!: ChargingStationOcppConfiguration;
6e0964c8 90 public wsConnection!: WebSocket;
9e23580d 91 public readonly requests: Map<string, CachedRequest>;
6e0964c8
JB
92 public performanceStatistics!: PerformanceStatistics;
93 public heartbeatSetInterval!: NodeJS.Timeout;
6e0964c8 94 public ocppRequestService!: OCPPRequestService;
ae711c83 95 public bootNotificationResponse!: BootNotificationResponse | null;
fa7bccf4 96 public powerDivider!: number;
9e23580d 97 private readonly index: number;
073bd098 98 private configurationFile!: string;
7c72977b 99 private configurationFileHash!: string;
6e0964c8 100 private bootNotificationRequest!: BootNotificationRequest;
6e0964c8 101 private connectorsConfigurationHash!: string;
a472cf2b 102 private ocppIncomingRequestService!: OCPPIncomingRequestService;
8e242273 103 private readonly messageBuffer: Set<string>;
fa7bccf4 104 private configuredSupervisionUrl!: URL;
265e4266 105 private wsConnectionRestarted: boolean;
ad2f27c3 106 private autoReconnectRetryCount: number;
fa7bccf4 107 private stopped: boolean;
7c72977b 108 private readonly cache: ChargingStationCache;
265e4266 109 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
6e0964c8 110 private webSocketPingSetInterval!: NodeJS.Timeout;
6af9012e 111
2484ac1e 112 constructor(index: number, templateFile: string) {
ad2f27c3 113 this.index = index;
2484ac1e 114 this.templateFile = templateFile;
265e4266
JB
115 this.stopped = false;
116 this.wsConnectionRestarted = false;
ad2f27c3 117 this.autoReconnectRetryCount = 0;
7c72977b 118 this.cache = ChargingStationCache.getInstance();
9f2e3130 119 this.connectors = new Map<number, ConnectorStatus>();
32b02249 120 this.requests = new Map<string, CachedRequest>();
8e242273 121 this.messageBuffer = new Set<string>();
9f2e3130 122 this.initialize();
c0560973
JB
123 }
124
25f5a959 125 private get wsConnectionUrl(): URL {
fa7bccf4
JB
126 return new URL(
127 (this.getSupervisionUrlOcppConfiguration()
128 ? ChargingStationConfigurationUtils.getConfigurationKey(
17ac262c
JB
129 this,
130 this.getSupervisionUrlOcppKey()
fa7bccf4
JB
131 ).value
132 : this.configuredSupervisionUrl.href) +
133 '/' +
134 this.stationInfo.chargingStationId
135 );
12fc74d6
JB
136 }
137
c0560973 138 public logPrefix(): string {
ccb1d6e9
JB
139 return Utils.logPrefix(
140 ` ${
141 this?.stationInfo?.chargingStationId ??
142 ChargingStationUtils.getChargingStationId(this.index, this.getTemplateFromFile())
143 } |`
144 );
c0560973
JB
145 }
146
802cfa13
JB
147 public getBootNotificationRequest(): BootNotificationRequest {
148 return this.bootNotificationRequest;
149 }
150
f4bf2abd 151 public getRandomIdTag(): string {
c37528f1 152 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
c0560973
JB
153 return this.authorizedTags[index];
154 }
155
156 public hasAuthorizedTags(): boolean {
157 return !Utils.isEmptyArray(this.authorizedTags);
158 }
159
6e0964c8 160 public getEnableStatistics(): boolean | undefined {
e7aeea18
JB
161 return !Utils.isUndefined(this.stationInfo.enableStatistics)
162 ? this.stationInfo.enableStatistics
163 : true;
c0560973
JB
164 }
165
a7fc8211
JB
166 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
167 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
168 }
169
fa7bccf4
JB
170 public getNumberOfPhases(stationInfo?: ChargingStationInfo): number | undefined {
171 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
172 switch (this.getCurrentOutType(stationInfo)) {
4c2b4904 173 case CurrentType.AC:
fa7bccf4
JB
174 return !Utils.isUndefined(localStationInfo.numberOfPhases)
175 ? localStationInfo.numberOfPhases
e7aeea18 176 : 3;
4c2b4904 177 case CurrentType.DC:
c0560973
JB
178 return 0;
179 }
180 }
181
d5bff457 182 public isWebSocketConnectionOpened(): boolean {
e58068fd 183 return this?.wsConnection?.readyState === OPEN;
c0560973
JB
184 }
185
672fed6e
JB
186 public getRegistrationStatus(): RegistrationStatus {
187 return this?.bootNotificationResponse?.status;
188 }
189
73c4266d
JB
190 public isInUnknownState(): boolean {
191 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
192 }
193
16cd35ad
JB
194 public isInPendingState(): boolean {
195 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
196 }
197
198 public isInAcceptedState(): boolean {
e58068fd 199 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
c0560973
JB
200 }
201
16cd35ad
JB
202 public isInRejectedState(): boolean {
203 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
204 }
205
206 public isRegistered(): boolean {
73c4266d 207 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
16cd35ad
JB
208 }
209
c0560973 210 public isChargingStationAvailable(): boolean {
734d790d 211 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
c0560973
JB
212 }
213
214 public isConnectorAvailable(id: number): boolean {
9f2e3130 215 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
c0560973
JB
216 }
217
54544ef1
JB
218 public getNumberOfConnectors(): number {
219 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
220 }
221
734d790d
JB
222 public getConnectorStatus(id: number): ConnectorStatus {
223 return this.connectors.get(id);
c0560973
JB
224 }
225
fa7bccf4
JB
226 public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType {
227 return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC;
c0560973
JB
228 }
229
672fed6e 230 public getOcppStrictCompliance(): boolean {
ccb1d6e9 231 return this.stationInfo?.ocppStrictCompliance ?? false;
672fed6e
JB
232 }
233
fa7bccf4 234 public getVoltageOut(stationInfo?: ChargingStationInfo): number | undefined {
492cf6ab 235 const defaultVoltageOut = ChargingStationUtils.getDefaultVoltageOut(
fa7bccf4 236 this.getCurrentOutType(stationInfo),
492cf6ab
JB
237 this.templateFile,
238 this.logPrefix()
239 );
fa7bccf4
JB
240 const localStationInfo: ChargingStationInfo = stationInfo ?? this.stationInfo;
241 return !Utils.isUndefined(localStationInfo.voltageOut)
242 ? localStationInfo.voltageOut
e7aeea18 243 : defaultVoltageOut;
c0560973
JB
244 }
245
ad8537a7 246 public getConnectorMaximumAvailablePower(connectorId: number): number {
d20f43b5 247 let connectorAmperageLimitationPowerLimit: number;
b47d68d7
JB
248 if (
249 !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
250 this.getAmperageLimitation() < this.stationInfo.maximumAmperage
251 ) {
4160ae28
JB
252 connectorAmperageLimitationPowerLimit =
253 (this.getCurrentOutType() === CurrentType.AC
cc6e8ab5
JB
254 ? ACElectricUtils.powerTotal(
255 this.getNumberOfPhases(),
256 this.getVoltageOut(),
da57964c 257 this.getAmperageLimitation() * this.getNumberOfConnectors()
cc6e8ab5 258 )
4160ae28 259 : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) /
fa7bccf4 260 this.powerDivider;
cc6e8ab5 261 }
fa7bccf4 262 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
7b872eaa 263 const connectorChargingProfilePowerLimit = this.getChargingProfilePowerLimit(connectorId);
ad8537a7
JB
264 return Math.min(
265 isNaN(connectorMaximumPower) ? Infinity : connectorMaximumPower,
266 isNaN(connectorAmperageLimitationPowerLimit)
267 ? Infinity
268 : connectorAmperageLimitationPowerLimit,
269 isNaN(connectorChargingProfilePowerLimit) ? Infinity : connectorChargingProfilePowerLimit
270 );
cc6e8ab5
JB
271 }
272
6e0964c8 273 public getTransactionIdTag(transactionId: number): string | undefined {
734d790d
JB
274 for (const connectorId of this.connectors.keys()) {
275 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
276 return this.getConnectorStatus(connectorId).transactionIdTag;
c0560973
JB
277 }
278 }
279 }
280
6ed92bc1 281 public getOutOfOrderEndMeterValues(): boolean {
ccb1d6e9 282 return this.stationInfo?.outOfOrderEndMeterValues ?? false;
6ed92bc1
JB
283 }
284
285 public getBeginEndMeterValues(): boolean {
ccb1d6e9 286 return this.stationInfo?.beginEndMeterValues ?? false;
6ed92bc1
JB
287 }
288
289 public getMeteringPerTransaction(): boolean {
ccb1d6e9 290 return this.stationInfo?.meteringPerTransaction ?? true;
6ed92bc1
JB
291 }
292
fd0c36fa 293 public getTransactionDataMeterValues(): boolean {
ccb1d6e9 294 return this.stationInfo?.transactionDataMeterValues ?? false;
fd0c36fa
JB
295 }
296
9ccca265 297 public getMainVoltageMeterValues(): boolean {
ccb1d6e9 298 return this.stationInfo?.mainVoltageMeterValues ?? true;
9ccca265
JB
299 }
300
6b10669b 301 public getPhaseLineToLineVoltageMeterValues(): boolean {
ccb1d6e9 302 return this.stationInfo?.phaseLineToLineVoltageMeterValues ?? false;
9bd87386
JB
303 }
304
7bc31f9c 305 public getCustomValueLimitationMeterValues(): boolean {
ccb1d6e9 306 return this.stationInfo?.customValueLimitationMeterValues ?? true;
7bc31f9c
JB
307 }
308
f479a792 309 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
734d790d 310 for (const connectorId of this.connectors.keys()) {
f479a792
JB
311 if (
312 connectorId > 0 &&
313 this.getConnectorStatus(connectorId)?.transactionId === transactionId
314 ) {
315 return connectorId;
c0560973
JB
316 }
317 }
318 }
319
cbad1217
JB
320 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
321 const transactionConnectorStatus = this.getConnectorStatus(
322 this.getConnectorIdByTransactionId(transactionId)
323 );
324 if (this.getMeteringPerTransaction()) {
325 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
326 }
327 return transactionConnectorStatus?.energyActiveImportRegisterValue;
328 }
329
6ed92bc1 330 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
cbad1217 331 const connectorStatus = this.getConnectorStatus(connectorId);
6ed92bc1 332 if (this.getMeteringPerTransaction()) {
cbad1217 333 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
6ed92bc1 334 }
cbad1217 335 return connectorStatus?.energyActiveImportRegisterValue;
6ed92bc1
JB
336 }
337
c0560973 338 public getAuthorizeRemoteTxRequests(): boolean {
17ac262c
JB
339 const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey(
340 this,
e7aeea18
JB
341 StandardParametersKey.AuthorizeRemoteTxRequests
342 );
343 return authorizeRemoteTxRequests
344 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
345 : false;
c0560973
JB
346 }
347
348 public getLocalAuthListEnabled(): boolean {
17ac262c
JB
349 const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey(
350 this,
e7aeea18
JB
351 StandardParametersKey.LocalAuthListEnabled
352 );
c0560973
JB
353 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
354 }
355
c0560973 356 public startHeartbeat(): void {
e7aeea18
JB
357 if (
358 this.getHeartbeatInterval() &&
359 this.getHeartbeatInterval() > 0 &&
360 !this.heartbeatSetInterval
361 ) {
71623267
JB
362 // eslint-disable-next-line @typescript-eslint/no-misused-promises
363 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
f7f98c68 364 await this.ocppRequestService.requestHandler<HeartbeatRequest, HeartbeatResponse>(
08f130a0 365 this,
f22266fd
JB
366 RequestCommand.HEARTBEAT
367 );
c0560973 368 }, this.getHeartbeatInterval());
e7aeea18
JB
369 logger.info(
370 this.logPrefix() +
371 ' Heartbeat started every ' +
372 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
373 );
c0560973 374 } else if (this.heartbeatSetInterval) {
e7aeea18
JB
375 logger.info(
376 this.logPrefix() +
377 ' Heartbeat already started every ' +
378 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
379 );
c0560973 380 } else {
e7aeea18
JB
381 logger.error(
382 `${this.logPrefix()} Heartbeat interval set to ${
383 this.getHeartbeatInterval()
384 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
385 : this.getHeartbeatInterval()
386 }, not starting the heartbeat`
387 );
c0560973
JB
388 }
389 }
390
391 public restartHeartbeat(): void {
392 // Stop heartbeat
393 this.stopHeartbeat();
394 // Start heartbeat
395 this.startHeartbeat();
396 }
397
17ac262c
JB
398 public restartWebSocketPing(): void {
399 // Stop WebSocket ping
400 this.stopWebSocketPing();
401 // Start WebSocket ping
402 this.startWebSocketPing();
403 }
404
c0560973
JB
405 public startMeterValues(connectorId: number, interval: number): void {
406 if (connectorId === 0) {
e7aeea18
JB
407 logger.error(
408 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
409 );
c0560973
JB
410 return;
411 }
734d790d 412 if (!this.getConnectorStatus(connectorId)) {
e7aeea18
JB
413 logger.error(
414 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
415 );
c0560973
JB
416 return;
417 }
734d790d 418 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
e7aeea18
JB
419 logger.error(
420 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
421 );
c0560973 422 return;
e7aeea18
JB
423 } else if (
424 this.getConnectorStatus(connectorId)?.transactionStarted &&
425 !this.getConnectorStatus(connectorId)?.transactionId
426 ) {
427 logger.error(
428 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
429 );
c0560973
JB
430 return;
431 }
432 if (interval > 0) {
71623267 433 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e7aeea18 434 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
9534e74e 435 // eslint-disable-next-line @typescript-eslint/no-misused-promises
e7aeea18 436 async (): Promise<void> => {
0f3d5941
JB
437 // FIXME: Implement OCPP version agnostic helpers
438 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
439 this,
e7aeea18
JB
440 connectorId,
441 this.getConnectorStatus(connectorId).transactionId,
442 interval
443 );
f7f98c68 444 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
08f130a0 445 this,
f22266fd
JB
446 RequestCommand.METER_VALUES,
447 {
448 connectorId,
449 transactionId: this.getConnectorStatus(connectorId).transactionId,
450 meterValue: [meterValue],
451 }
452 );
e7aeea18
JB
453 },
454 interval
455 );
c0560973 456 } else {
e7aeea18
JB
457 logger.error(
458 `${this.logPrefix()} Charging station ${
459 StandardParametersKey.MeterValueSampleInterval
460 } configuration set to ${
461 interval ? Utils.formatDurationMilliSeconds(interval) : interval
462 }, not sending MeterValues`
463 );
c0560973
JB
464 }
465 }
466
467 public start(): void {
7874b0b1
JB
468 if (this.getEnableStatistics()) {
469 this.performanceStatistics.start();
470 }
c0560973 471 this.openWSConnection();
94bb24d5
JB
472 // Handle WebSocket message
473 this.wsConnection.on(
474 'message',
475 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
476 );
477 // Handle WebSocket error
478 this.wsConnection.on(
479 'error',
480 this.onError.bind(this) as (this: WebSocket, error: Error) => void
481 );
482 // Handle WebSocket close
483 this.wsConnection.on(
484 'close',
485 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
486 );
487 // Handle WebSocket open
488 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
489 // Handle WebSocket ping
490 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
491 // Handle WebSocket pong
492 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
c0560973 493 // Monitor authorization file
a95873d8
JB
494 FileUtils.watchJsonFile<string[]>(
495 this.logPrefix(),
496 FileType.Authorization,
fa7bccf4 497 ChargingStationUtils.getAuthorizationFile(this.stationInfo),
a95873d8
JB
498 this.authorizedTags
499 );
500 // Monitor charging station template file
501 FileUtils.watchJsonFile(
502 this.logPrefix(),
503 FileType.ChargingStationTemplate,
2484ac1e 504 this.templateFile,
a95873d8
JB
505 null,
506 (event, filename): void => {
507 if (filename && event === 'change') {
508 try {
509 logger.debug(
510 `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
2484ac1e 511 this.templateFile
a95873d8
JB
512 } file have changed, reload`
513 );
7c72977b 514 this.cache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
a95873d8
JB
515 // Initialize
516 this.initialize();
517 // Restart the ATG
fa7bccf4 518 this.stopAutomaticTransactionGenerator();
a95873d8
JB
519 this.startAutomaticTransactionGenerator();
520 if (this.getEnableStatistics()) {
521 this.performanceStatistics.restart();
522 } else {
523 this.performanceStatistics.stop();
524 }
525 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
526 } catch (error) {
527 logger.error(
528 `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
529 error
530 );
531 }
532 }
533 }
534 );
e7aeea18
JB
535 parentPort.postMessage({
536 id: ChargingStationWorkerMessageEvents.STARTED,
537 data: { id: this.stationInfo.chargingStationId },
538 });
c0560973
JB
539 }
540
541 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
542 // Stop message sequence
543 await this.stopMessageSequence(reason);
734d790d
JB
544 for (const connectorId of this.connectors.keys()) {
545 if (connectorId > 0) {
f7f98c68 546 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
547 StatusNotificationRequest,
548 StatusNotificationResponse
08f130a0 549 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
550 connectorId,
551 status: ChargePointStatus.UNAVAILABLE,
552 errorCode: ChargePointErrorCode.NO_ERROR,
553 });
734d790d 554 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
c0560973
JB
555 }
556 }
d5bff457 557 if (this.isWebSocketConnectionOpened()) {
c0560973
JB
558 this.wsConnection.close();
559 }
7874b0b1
JB
560 if (this.getEnableStatistics()) {
561 this.performanceStatistics.stop();
562 }
7c72977b
JB
563 this.cache.deleteChargingStationConfiguration(this.configurationFileHash);
564 this.cache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
c0560973 565 this.bootNotificationResponse = null;
e7aeea18
JB
566 parentPort.postMessage({
567 id: ChargingStationWorkerMessageEvents.STOPPED,
568 data: { id: this.stationInfo.chargingStationId },
569 });
265e4266 570 this.stopped = true;
c0560973
JB
571 }
572
94ec7e96
JB
573 public async reset(reason?: StopTransactionReason): Promise<void> {
574 await this.stop(reason);
575 await Utils.sleep(this.stationInfo.resetTime);
fa7bccf4 576 this.initialize();
94ec7e96
JB
577 this.start();
578 }
579
17ac262c
JB
580 public saveOcppConfiguration(): void {
581 if (this.getOcppPersistentConfiguration()) {
7c72977b 582 this.saveConfiguration();
e6895390
JB
583 }
584 }
585
ad8537a7 586 public getChargingProfilePowerLimit(connectorId: number): number | undefined {
0bb3ee61 587 let limit: number, matchingChargingProfile: ChargingProfile;
1e5bbb96 588 let chargingProfiles: ChargingProfile[] = [];
0bb3ee61 589 // Get charging profiles for connector and sort by stack level
1e5bbb96
O
590 chargingProfiles = this.getConnectorStatus(connectorId).chargingProfiles.sort(
591 (a, b) => b.stackLevel - a.stackLevel
592 );
593 // Get profiles on connector 0
594 if (this.getConnectorStatus(0).chargingProfiles) {
595 chargingProfiles.push(
596 ...this.getConnectorStatus(0).chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel)
cfa9539e 597 );
cfa9539e 598 }
1e5bbb96 599 if (!Utils.isEmptyArray(chargingProfiles)) {
17ac262c
JB
600 const result = ChargingStationUtils.getLimitFromChargingProfiles(
601 chargingProfiles,
602 Utils.logPrefix()
603 );
1e5bbb96
O
604 if (!Utils.isNullOrUndefined(result)) {
605 limit = result.limit;
606 matchingChargingProfile = result.matchingChargingProfile;
607 switch (this.getCurrentOutType()) {
608 case CurrentType.AC:
609 limit =
610 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
611 ChargingRateUnitType.WATT
612 ? limit
613 : ACElectricUtils.powerTotal(this.getNumberOfPhases(), this.getVoltageOut(), limit);
614 break;
615 case CurrentType.DC:
616 limit =
617 matchingChargingProfile.chargingSchedule.chargingRateUnit ===
618 ChargingRateUnitType.WATT
619 ? limit
620 : DCElectricUtils.power(this.getVoltageOut(), limit);
621 }
622
fa7bccf4 623 const connectorMaximumPower = this.getMaximumPower() / this.powerDivider;
1e5bbb96
O
624 if (limit > connectorMaximumPower) {
625 logger.error(
626 `${this.logPrefix()} Charging profile id ${
627 matchingChargingProfile.chargingProfileId
628 } limit is greater than connector id ${connectorId} maximum, dump charging profiles' stack: %j`,
629 this.getConnectorStatus(connectorId).chargingProfiles
630 );
631 limit = connectorMaximumPower;
632 }
cfa9539e 633 }
ad8537a7 634 }
ad8537a7 635 return limit;
cfa9539e
JB
636 }
637
a7fc8211 638 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
0bb3ee61
JB
639 if (Utils.isNullOrUndefined(this.getConnectorStatus(connectorId).chargingProfiles)) {
640 logger.error(
641 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
642 );
643 this.getConnectorStatus(connectorId).chargingProfiles = [];
644 }
1e5bbb96 645 if (!Array.isArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
0bb3ee61
JB
646 logger.error(
647 `${this.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
648 );
1e5bbb96
O
649 this.getConnectorStatus(connectorId).chargingProfiles = [];
650 }
a7fc8211 651 let cpReplaced = false;
734d790d 652 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
e7aeea18
JB
653 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
654 (chargingProfile: ChargingProfile, index: number) => {
655 if (
656 chargingProfile.chargingProfileId === cp.chargingProfileId ||
657 (chargingProfile.stackLevel === cp.stackLevel &&
658 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
659 ) {
660 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
661 cpReplaced = true;
662 }
c0560973 663 }
e7aeea18 664 );
c0560973 665 }
734d790d 666 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
c0560973
JB
667 }
668
a2653482
JB
669 public resetConnectorStatus(connectorId: number): void {
670 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
671 this.getConnectorStatus(connectorId).idTagAuthorized = false;
672 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d 673 this.getConnectorStatus(connectorId).transactionStarted = false;
a2653482 674 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
734d790d
JB
675 delete this.getConnectorStatus(connectorId).authorizeIdTag;
676 delete this.getConnectorStatus(connectorId).transactionId;
677 delete this.getConnectorStatus(connectorId).transactionIdTag;
678 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
679 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
dd119a6b 680 this.stopMeterValues(connectorId);
2e6f5966
JB
681 }
682
68cb8b91 683 public hasFeatureProfile(featureProfile: SupportedFeatureProfiles) {
17ac262c
JB
684 return ChargingStationConfigurationUtils.getConfigurationKey(
685 this,
686 StandardParametersKey.SupportedFeatureProfiles
687 )?.value.includes(featureProfile);
68cb8b91
JB
688 }
689
8e242273
JB
690 public bufferMessage(message: string): void {
691 this.messageBuffer.add(message);
3ba2381e
JB
692 }
693
8e242273
JB
694 private flushMessageBuffer() {
695 if (this.messageBuffer.size > 0) {
696 this.messageBuffer.forEach((message) => {
aef1b33a 697 // TODO: evaluate the need to track performance
77f00f84 698 this.wsConnection.send(message);
8e242273 699 this.messageBuffer.delete(message);
77f00f84
JB
700 });
701 }
702 }
703
1f5df42a
JB
704 private getSupervisionUrlOcppConfiguration(): boolean {
705 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
12fc74d6
JB
706 }
707
e8e865ea
JB
708 private getSupervisionUrlOcppKey(): string {
709 return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
710 }
711
9214b603 712 private getTemplateFromFile(): ChargingStationTemplate | null {
2484ac1e 713 let template: ChargingStationTemplate = null;
5ad8570f 714 try {
7c72977b
JB
715 if (this.cache.hasChargingStationTemplate(this.stationInfo?.templateHash)) {
716 template = this.cache.getChargingStationTemplate(this.stationInfo.templateHash);
717 } else {
718 const measureId = `${FileType.ChargingStationTemplate} read`;
719 const beginId = PerformanceStatistics.beginMeasure(measureId);
720 template = JSON.parse(
721 fs.readFileSync(this.templateFile, 'utf8')
722 ) as ChargingStationTemplate;
723 PerformanceStatistics.endMeasure(measureId, beginId);
724 template.templateHash = crypto
725 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
726 .update(JSON.stringify(template))
727 .digest('hex');
728 this.cache.setChargingStationTemplate(template);
729 }
5ad8570f 730 } catch (error) {
e7aeea18
JB
731 FileUtils.handleFileException(
732 this.logPrefix(),
a95873d8 733 FileType.ChargingStationTemplate,
2484ac1e 734 this.templateFile,
e7aeea18
JB
735 error as NodeJS.ErrnoException
736 );
5ad8570f 737 }
2484ac1e
JB
738 return template;
739 }
740
7a3a2ebb 741 private getStationInfoFromTemplate(): ChargingStationInfo {
fa7bccf4
JB
742 const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile();
743 if (Utils.isNullOrUndefined(stationTemplate)) {
ccb1d6e9
JB
744 const errorMsg = 'Failed to read charging station template file';
745 logger.error(`${this.logPrefix()} ${errorMsg}`);
746 throw new BaseError(errorMsg);
94ec7e96 747 }
fa7bccf4 748 if (Utils.isEmptyObject(stationTemplate)) {
ccb1d6e9
JB
749 const errorMsg = `Empty charging station information from template file ${this.templateFile}`;
750 logger.error(`${this.logPrefix()} ${errorMsg}`);
751 throw new BaseError(errorMsg);
94ec7e96 752 }
2dcfe98e 753 // Deprecation template keys section
17ac262c 754 ChargingStationUtils.warnDeprecatedTemplateKey(
fa7bccf4 755 stationTemplate,
e7aeea18 756 'supervisionUrl',
17ac262c 757 this.templateFile,
ccb1d6e9 758 this.logPrefix(),
e7aeea18
JB
759 "Use 'supervisionUrls' instead"
760 );
17ac262c 761 ChargingStationUtils.convertDeprecatedTemplateKey(
fa7bccf4 762 stationTemplate,
17ac262c
JB
763 'supervisionUrl',
764 'supervisionUrls'
765 );
fa7bccf4
JB
766 const stationInfo: ChargingStationInfo =
767 ChargingStationUtils.stationTemplateToStationInfo(stationTemplate);
768 stationInfo.chargingStationId = ChargingStationUtils.getChargingStationId(
769 this.index,
770 stationTemplate
771 );
772 ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
773 if (!Utils.isEmptyArray(stationTemplate.power)) {
774 stationTemplate.power = stationTemplate.power as number[];
775 const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
cc6e8ab5 776 stationInfo.maximumPower =
fa7bccf4
JB
777 stationTemplate.powerUnit === PowerUnits.KILO_WATT
778 ? stationTemplate.power[powerArrayRandomIndex] * 1000
779 : stationTemplate.power[powerArrayRandomIndex];
5ad8570f 780 } else {
fa7bccf4 781 stationTemplate.power = stationTemplate.power as number;
cc6e8ab5 782 stationInfo.maximumPower =
fa7bccf4
JB
783 stationTemplate.powerUnit === PowerUnits.KILO_WATT
784 ? stationTemplate.power * 1000
785 : stationTemplate.power;
786 }
787 stationInfo.resetTime = stationTemplate.resetTime
788 ? stationTemplate.resetTime * 1000
e7aeea18 789 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
fa7bccf4
JB
790 const configuredMaxConnectors = ChargingStationUtils.getConfiguredNumberOfConnectors(
791 this.index,
792 stationTemplate
793 );
794 ChargingStationUtils.checkConfiguredMaxConnectors(
795 configuredMaxConnectors,
796 this.templateFile,
797 Utils.logPrefix()
798 );
799 const templateMaxConnectors =
800 ChargingStationUtils.getTemplateMaxNumberOfConnectors(stationTemplate);
801 ChargingStationUtils.checkTemplateMaxConnectors(
802 templateMaxConnectors,
803 this.templateFile,
804 Utils.logPrefix()
805 );
806 if (
807 configuredMaxConnectors >
808 (stationTemplate?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
809 !stationTemplate?.randomConnectors
810 ) {
811 logger.warn(
812 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
813 this.templateFile
814 }, forcing random connector configurations affectation`
815 );
816 stationInfo.randomConnectors = true;
817 }
818 // Build connectors if needed (FIXME: should be factored out)
819 this.initializeConnectors(stationInfo, configuredMaxConnectors, templateMaxConnectors);
820 stationInfo.maximumAmperage = this.getMaximumAmperage(stationInfo);
821 ChargingStationUtils.createStationInfoHash(stationInfo);
9ac86a7e 822 return stationInfo;
5ad8570f
JB
823 }
824
ccb1d6e9
JB
825 private getStationInfoFromFile(): ChargingStationInfo | null {
826 let stationInfo: ChargingStationInfo = null;
fa7bccf4
JB
827 this.getStationInfoPersistentConfiguration() &&
828 (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
829 stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
f765beaa 830 return stationInfo;
2484ac1e
JB
831 }
832
833 private getStationInfo(): ChargingStationInfo {
834 const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
2484ac1e 835 const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
aca53a1a 836 // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
f765beaa 837 if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
01efc60a
JB
838 if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
839 return this.stationInfo;
840 }
2484ac1e 841 return stationInfoFromFile;
f765beaa 842 }
fec4d204
JB
843 stationInfoFromFile &&
844 ChargingStationUtils.propagateSerialNumber(
845 this.getTemplateFromFile(),
846 stationInfoFromFile,
847 stationInfoFromTemplate
848 );
01efc60a 849 return stationInfoFromTemplate;
2484ac1e
JB
850 }
851
852 private saveStationInfo(): void {
ccb1d6e9 853 if (this.getStationInfoPersistentConfiguration()) {
7c72977b 854 this.saveConfiguration();
ccb1d6e9 855 }
2484ac1e
JB
856 }
857
1f5df42a 858 private getOcppVersion(): OCPPVersion {
aba95196 859 return this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
c0560973
JB
860 }
861
e8e865ea 862 private getOcppPersistentConfiguration(): boolean {
ccb1d6e9
JB
863 return this.stationInfo?.ocppPersistentConfiguration ?? true;
864 }
865
866 private getStationInfoPersistentConfiguration(): boolean {
867 return this.stationInfo?.stationInfoPersistentConfiguration ?? true;
e8e865ea
JB
868 }
869
c0560973 870 private handleUnsupportedVersion(version: OCPPVersion) {
e7aeea18 871 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
2484ac1e 872 this.templateFile
e7aeea18 873 }`;
9f2e3130 874 logger.error(errMsg);
c0560973
JB
875 throw new Error(errMsg);
876 }
877
2484ac1e 878 private initialize(): void {
fa7bccf4 879 this.hashId = ChargingStationUtils.getHashId(this.index, this.getTemplateFromFile());
3f94cab5 880 logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
fa7bccf4
JB
881 this.configurationFile = path.join(
882 path.resolve(__dirname, '../'),
883 'assets',
884 'configurations',
885 this.hashId + '.json'
0642c3d2 886 );
fa7bccf4 887 this.stationInfo = this.getStationInfo();
cc6e8ab5 888 this.saveStationInfo();
7a3a2ebb 889 // Avoid duplication of connectors related information in RAM
94ec7e96 890 this.stationInfo?.Connectors && delete this.stationInfo.Connectors;
fa7bccf4 891 this.configuredSupervisionUrl = this.getConfiguredSupervisionUrl();
0642c3d2
JB
892 if (this.getEnableStatistics()) {
893 this.performanceStatistics = PerformanceStatistics.getInstance(
894 this.hashId,
895 this.stationInfo.chargingStationId,
fa7bccf4 896 this.configuredSupervisionUrl
0642c3d2
JB
897 );
898 }
fa7bccf4
JB
899 this.bootNotificationRequest = ChargingStationUtils.createBootNotificationRequest(
900 this.stationInfo
901 );
902 this.authorizedTags = ChargingStationUtils.getAuthorizedTags(
903 this.stationInfo,
904 this.templateFile,
905 this.logPrefix()
906 );
907 this.powerDivider = this.getPowerDivider();
908 // OCPP configuration
909 this.ocppConfiguration = this.getOcppConfiguration();
910 this.initializeOcppConfiguration();
1f5df42a 911 switch (this.getOcppVersion()) {
c0560973 912 case OCPPVersion.VERSION_16:
e7aeea18 913 this.ocppIncomingRequestService =
08f130a0 914 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
e7aeea18 915 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
08f130a0 916 OCPP16ResponseService.getInstance<OCPP16ResponseService>()
e7aeea18 917 );
c0560973
JB
918 break;
919 default:
1f5df42a 920 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
921 break;
922 }
7c72977b 923 if (this.stationInfo?.autoRegister) {
47e22477
JB
924 this.bootNotificationResponse = {
925 currentTime: new Date().toISOString(),
926 interval: this.getHeartbeatInterval() / 1000,
e7aeea18 927 status: RegistrationStatus.ACCEPTED,
47e22477
JB
928 };
929 }
147d0e0f
JB
930 }
931
2484ac1e 932 private initializeOcppConfiguration(): void {
17ac262c
JB
933 if (
934 !ChargingStationConfigurationUtils.getConfigurationKey(
935 this,
936 StandardParametersKey.HeartbeatInterval
937 )
938 ) {
939 ChargingStationConfigurationUtils.addConfigurationKey(
940 this,
941 StandardParametersKey.HeartbeatInterval,
942 '0'
943 );
f0f65a62 944 }
17ac262c
JB
945 if (
946 !ChargingStationConfigurationUtils.getConfigurationKey(
947 this,
948 StandardParametersKey.HeartBeatInterval
949 )
950 ) {
951 ChargingStationConfigurationUtils.addConfigurationKey(
952 this,
953 StandardParametersKey.HeartBeatInterval,
954 '0',
955 { visible: false }
956 );
f0f65a62 957 }
e7aeea18
JB
958 if (
959 this.getSupervisionUrlOcppConfiguration() &&
17ac262c 960 !ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e7aeea18 961 ) {
17ac262c
JB
962 ChargingStationConfigurationUtils.addConfigurationKey(
963 this,
a59737e3 964 this.getSupervisionUrlOcppKey(),
fa7bccf4 965 this.configuredSupervisionUrl.href,
e7aeea18
JB
966 { reboot: true }
967 );
e6895390
JB
968 } else if (
969 !this.getSupervisionUrlOcppConfiguration() &&
17ac262c 970 ChargingStationConfigurationUtils.getConfigurationKey(this, this.getSupervisionUrlOcppKey())
e6895390 971 ) {
17ac262c
JB
972 ChargingStationConfigurationUtils.deleteConfigurationKey(
973 this,
974 this.getSupervisionUrlOcppKey(),
975 { save: false }
976 );
12fc74d6 977 }
cc6e8ab5
JB
978 if (
979 this.stationInfo.amperageLimitationOcppKey &&
17ac262c
JB
980 !ChargingStationConfigurationUtils.getConfigurationKey(
981 this,
982 this.stationInfo.amperageLimitationOcppKey
983 )
cc6e8ab5 984 ) {
17ac262c
JB
985 ChargingStationConfigurationUtils.addConfigurationKey(
986 this,
cc6e8ab5 987 this.stationInfo.amperageLimitationOcppKey,
17ac262c
JB
988 (
989 this.stationInfo.maximumAmperage *
990 ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
991 ).toString()
cc6e8ab5
JB
992 );
993 }
17ac262c
JB
994 if (
995 !ChargingStationConfigurationUtils.getConfigurationKey(
996 this,
997 StandardParametersKey.SupportedFeatureProfiles
998 )
999 ) {
1000 ChargingStationConfigurationUtils.addConfigurationKey(
1001 this,
e7aeea18 1002 StandardParametersKey.SupportedFeatureProfiles,
b22787b4 1003 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`
e7aeea18
JB
1004 );
1005 }
17ac262c
JB
1006 ChargingStationConfigurationUtils.addConfigurationKey(
1007 this,
e7aeea18
JB
1008 StandardParametersKey.NumberOfConnectors,
1009 this.getNumberOfConnectors().toString(),
a95873d8
JB
1010 { readonly: true },
1011 { overwrite: true }
e7aeea18 1012 );
17ac262c
JB
1013 if (
1014 !ChargingStationConfigurationUtils.getConfigurationKey(
1015 this,
1016 StandardParametersKey.MeterValuesSampledData
1017 )
1018 ) {
1019 ChargingStationConfigurationUtils.addConfigurationKey(
1020 this,
e7aeea18
JB
1021 StandardParametersKey.MeterValuesSampledData,
1022 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
1023 );
7abfea5f 1024 }
17ac262c
JB
1025 if (
1026 !ChargingStationConfigurationUtils.getConfigurationKey(
1027 this,
1028 StandardParametersKey.ConnectorPhaseRotation
1029 )
1030 ) {
7e1dc878 1031 const connectorPhaseRotation = [];
734d790d 1032 for (const connectorId of this.connectors.keys()) {
7e1dc878 1033 // AC/DC
734d790d
JB
1034 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
1035 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
1036 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
1037 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
e7aeea18 1038 // AC
734d790d
JB
1039 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
1040 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
1041 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
1042 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
7e1dc878
JB
1043 }
1044 }
17ac262c
JB
1045 ChargingStationConfigurationUtils.addConfigurationKey(
1046 this,
e7aeea18
JB
1047 StandardParametersKey.ConnectorPhaseRotation,
1048 connectorPhaseRotation.toString()
1049 );
7e1dc878 1050 }
e7aeea18 1051 if (
17ac262c
JB
1052 !ChargingStationConfigurationUtils.getConfigurationKey(
1053 this,
1054 StandardParametersKey.AuthorizeRemoteTxRequests
e7aeea18
JB
1055 )
1056 ) {
17ac262c
JB
1057 ChargingStationConfigurationUtils.addConfigurationKey(
1058 this,
1059 StandardParametersKey.AuthorizeRemoteTxRequests,
1060 'true'
1061 );
36f6a92e 1062 }
17ac262c
JB
1063 if (
1064 !ChargingStationConfigurationUtils.getConfigurationKey(
1065 this,
1066 StandardParametersKey.LocalAuthListEnabled
1067 ) &&
1068 ChargingStationConfigurationUtils.getConfigurationKey(
1069 this,
1070 StandardParametersKey.SupportedFeatureProfiles
1071 )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
1072 ) {
1073 ChargingStationConfigurationUtils.addConfigurationKey(
1074 this,
1075 StandardParametersKey.LocalAuthListEnabled,
1076 'false'
1077 );
1078 }
1079 if (
1080 !ChargingStationConfigurationUtils.getConfigurationKey(
1081 this,
1082 StandardParametersKey.ConnectionTimeOut
1083 )
1084 ) {
1085 ChargingStationConfigurationUtils.addConfigurationKey(
1086 this,
e7aeea18
JB
1087 StandardParametersKey.ConnectionTimeOut,
1088 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
1089 );
8bce55bf 1090 }
2484ac1e 1091 this.saveOcppConfiguration();
073bd098
JB
1092 }
1093
3d25cc86
JB
1094 private initializeConnectors(
1095 stationInfo: ChargingStationInfo,
fa7bccf4 1096 configuredMaxConnectors: number,
3d25cc86
JB
1097 templateMaxConnectors: number
1098 ): void {
1099 if (!stationInfo?.Connectors && this.connectors.size === 0) {
1100 const logMsg = `${this.logPrefix()} No already defined connectors and charging station information from template ${
1101 this.templateFile
1102 } with no connectors configuration defined`;
1103 logger.error(logMsg);
1104 throw new BaseError(logMsg);
1105 }
1106 if (!stationInfo?.Connectors[0]) {
1107 logger.warn(
1108 `${this.logPrefix()} Charging station information from template ${
1109 this.templateFile
1110 } with no connector Id 0 configuration`
1111 );
1112 }
1113 if (stationInfo?.Connectors) {
1114 const connectorsConfigHash = crypto
1115 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
fa7bccf4 1116 .update(JSON.stringify(stationInfo?.Connectors) + configuredMaxConnectors.toString())
3d25cc86
JB
1117 .digest('hex');
1118 const connectorsConfigChanged =
1119 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
1120 if (this.connectors?.size === 0 || connectorsConfigChanged) {
1121 connectorsConfigChanged && this.connectors.clear();
1122 this.connectorsConfigurationHash = connectorsConfigHash;
1123 // Add connector Id 0
1124 let lastConnector = '0';
1125 for (lastConnector in stationInfo?.Connectors) {
1126 const lastConnectorId = Utils.convertToInt(lastConnector);
1127 if (
1128 lastConnectorId === 0 &&
fa7bccf4 1129 this.getUseConnectorId0(stationInfo) &&
3d25cc86
JB
1130 stationInfo?.Connectors[lastConnector]
1131 ) {
1132 this.connectors.set(
1133 lastConnectorId,
1134 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[lastConnector])
1135 );
1136 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
1137 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
1138 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
1139 }
1140 }
1141 }
1142 // Generate all connectors
1143 if ((stationInfo?.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0) {
fa7bccf4 1144 for (let index = 1; index <= configuredMaxConnectors; index++) {
ccb1d6e9 1145 const randConnectorId = stationInfo?.randomConnectors
3d25cc86
JB
1146 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
1147 : index;
1148 this.connectors.set(
1149 index,
1150 Utils.cloneObject<ConnectorStatus>(stationInfo?.Connectors[randConnectorId])
1151 );
1152 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
1153 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
1154 this.getConnectorStatus(index).chargingProfiles = [];
1155 }
1156 }
1157 }
1158 }
1159 } else {
1160 logger.warn(
1161 `${this.logPrefix()} Charging station information from template ${
1162 this.templateFile
1163 } with no connectors configuration defined, using already defined connectors`
1164 );
1165 }
1166 // Initialize transaction attributes on connectors
1167 for (const connectorId of this.connectors.keys()) {
1168 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
1169 this.initializeConnectorStatus(connectorId);
1170 }
1171 }
1172 }
1173
7f7b65ca 1174 private getConfigurationFromFile(): ChargingStationConfiguration | null {
073bd098 1175 let configuration: ChargingStationConfiguration = null;
2484ac1e 1176 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
073bd098 1177 try {
7c72977b
JB
1178 if (this.cache.hasChargingStationConfiguration(this.configurationFileHash)) {
1179 configuration = this.cache.getChargingStationConfiguration(this.configurationFileHash);
1180 } else {
1181 const measureId = `${FileType.ChargingStationConfiguration} read`;
1182 const beginId = PerformanceStatistics.beginMeasure(measureId);
1183 configuration = JSON.parse(
1184 fs.readFileSync(this.configurationFile, 'utf8')
1185 ) as ChargingStationConfiguration;
1186 PerformanceStatistics.endMeasure(measureId, beginId);
1187 this.configurationFileHash = configuration.configurationHash;
1188 this.cache.setChargingStationConfiguration(configuration);
1189 }
073bd098
JB
1190 } catch (error) {
1191 FileUtils.handleFileException(
1192 this.logPrefix(),
a95873d8 1193 FileType.ChargingStationConfiguration,
073bd098
JB
1194 this.configurationFile,
1195 error as NodeJS.ErrnoException
1196 );
1197 }
1198 }
1199 return configuration;
1200 }
1201
7c72977b 1202 private saveConfiguration(): void {
2484ac1e
JB
1203 if (this.configurationFile) {
1204 try {
2484ac1e
JB
1205 if (!fs.existsSync(path.dirname(this.configurationFile))) {
1206 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
073bd098 1207 }
ccb1d6e9
JB
1208 const configurationData: ChargingStationConfiguration =
1209 this.getConfigurationFromFile() ?? {};
7c72977b
JB
1210 this.ocppConfiguration?.configurationKey &&
1211 (configurationData.configurationKey = this.ocppConfiguration.configurationKey);
1212 this.stationInfo && (configurationData.stationInfo = this.stationInfo);
1213 delete configurationData.configurationHash;
1214 const configurationHash = crypto
1215 .createHash(Constants.DEFAULT_HASH_ALGORITHM)
1216 .update(JSON.stringify(configurationData))
1217 .digest('hex');
1218 if (this.configurationFileHash !== configurationHash) {
1219 configurationData.configurationHash = configurationHash;
1220 const measureId = `${FileType.ChargingStationConfiguration} write`;
1221 const beginId = PerformanceStatistics.beginMeasure(measureId);
1222 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
1223 fs.writeFileSync(fileDescriptor, JSON.stringify(configurationData, null, 2), 'utf8');
1224 fs.closeSync(fileDescriptor);
1225 PerformanceStatistics.endMeasure(measureId, beginId);
1226 this.cache.deleteChargingStationConfiguration(this.configurationFileHash);
1227 this.configurationFileHash = configurationHash;
1228 this.cache.setChargingStationConfiguration(configurationData);
1229 } else {
1230 logger.debug(
1231 `${this.logPrefix()} Not saving unchanged charging station configuration file ${
1232 this.configurationFile
1233 }`
1234 );
2484ac1e 1235 }
2484ac1e
JB
1236 } catch (error) {
1237 FileUtils.handleFileException(
1238 this.logPrefix(),
1239 FileType.ChargingStationConfiguration,
1240 this.configurationFile,
1241 error as NodeJS.ErrnoException
073bd098
JB
1242 );
1243 }
2484ac1e
JB
1244 } else {
1245 logger.error(
01efc60a 1246 `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`
2484ac1e 1247 );
073bd098
JB
1248 }
1249 }
1250
ccb1d6e9
JB
1251 private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null {
1252 return this.getTemplateFromFile()?.Configuration ?? null;
2484ac1e
JB
1253 }
1254
1255 private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
1256 let configuration: ChargingStationConfiguration = null;
1257 if (this.getOcppPersistentConfiguration()) {
7a3a2ebb
JB
1258 const configurationFromFile = this.getConfigurationFromFile();
1259 configuration = configurationFromFile?.configurationKey && configurationFromFile;
073bd098 1260 }
2484ac1e 1261 configuration && delete configuration.stationInfo;
073bd098 1262 return configuration;
7dde0b73
JB
1263 }
1264
ccb1d6e9 1265 private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
2484ac1e
JB
1266 let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
1267 if (!ocppConfiguration) {
1268 ocppConfiguration = this.getOcppConfigurationFromTemplate();
1269 }
1270 return ocppConfiguration;
1271 }
1272
c0560973 1273 private async onOpen(): Promise<void> {
5144f4d1
JB
1274 if (this.isWebSocketConnectionOpened()) {
1275 logger.info(
1276 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`
1277 );
94bb24d5 1278 if (!this.isRegistered()) {
5144f4d1
JB
1279 // Send BootNotification
1280 let registrationRetryCount = 0;
1281 do {
f7f98c68 1282 this.bootNotificationResponse = await this.ocppRequestService.requestHandler<
5144f4d1
JB
1283 BootNotificationRequest,
1284 BootNotificationResponse
1285 >(
08f130a0 1286 this,
f22266fd
JB
1287 RequestCommand.BOOT_NOTIFICATION,
1288 {
1289 chargePointModel: this.bootNotificationRequest.chargePointModel,
1290 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1291 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1292 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1293 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1294 iccid: this.bootNotificationRequest.iccid,
1295 imsi: this.bootNotificationRequest.imsi,
1296 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1297 meterType: this.bootNotificationRequest.meterType,
1298 },
1299 { skipBufferingOnError: true }
1300 );
94bb24d5 1301 if (!this.isRegistered()) {
5144f4d1
JB
1302 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1303 await Utils.sleep(
1304 this.bootNotificationResponse?.interval
1305 ? this.bootNotificationResponse.interval * 1000
1306 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1307 );
1308 }
1309 } while (
94bb24d5 1310 !this.isRegistered() &&
5144f4d1
JB
1311 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1312 this.getRegistrationMaxRetries() === -1)
1313 );
1314 }
94bb24d5
JB
1315 if (this.isRegistered()) {
1316 if (this.isInAcceptedState()) {
1317 await this.startMessageSequence();
1318 this.wsConnectionRestarted && this.flushMessageBuffer();
c0560973 1319 }
5144f4d1
JB
1320 } else {
1321 logger.error(
1322 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1323 );
caad9d6b 1324 }
94bb24d5 1325 this.stopped && (this.stopped = false);
5144f4d1
JB
1326 this.autoReconnectRetryCount = 0;
1327 this.wsConnectionRestarted = false;
2e6f5966 1328 } else {
5144f4d1
JB
1329 logger.warn(
1330 `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`
e7aeea18 1331 );
2e6f5966 1332 }
2e6f5966
JB
1333 }
1334
6c65a295 1335 private async onClose(code: number, reason: string): Promise<void> {
d09085e9 1336 switch (code) {
6c65a295
JB
1337 // Normal close
1338 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
c0560973 1339 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
e7aeea18 1340 logger.info(
17ac262c 1341 `${this.logPrefix()} WebSocket normally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
e7aeea18
JB
1342 code
1343 )}' and reason '${reason}'`
1344 );
c0560973
JB
1345 this.autoReconnectRetryCount = 0;
1346 break;
6c65a295
JB
1347 // Abnormal close
1348 default:
e7aeea18 1349 logger.error(
17ac262c 1350 `${this.logPrefix()} WebSocket abnormally closed with status '${ChargingStationUtils.getWebSocketCloseEventStatusString(
e7aeea18
JB
1351 code
1352 )}' and reason '${reason}'`
1353 );
d09085e9 1354 await this.reconnect(code);
c0560973
JB
1355 break;
1356 }
2e6f5966
JB
1357 }
1358
16b0d4e7 1359 private async onMessage(data: Data): Promise<void> {
b3ec7bc1
JB
1360 let messageType: number;
1361 let messageId: string;
1362 let commandName: IncomingRequestCommand;
1363 let commandPayload: JsonType;
1364 let errorType: ErrorType;
1365 let errorMessage: string;
1366 let errorDetails: JsonType;
1367 let responseCallback: (payload: JsonType, requestPayload: JsonType) => void;
a2d1c0f1 1368 let errorCallback: (error: OCPPError, requestStatistic?: boolean) => void;
32b02249 1369 let requestCommandName: RequestCommand | IncomingRequestCommand;
b3ec7bc1 1370 let requestPayload: JsonType;
32b02249 1371 let cachedRequest: CachedRequest;
c0560973
JB
1372 let errMsg: string;
1373 try {
b3ec7bc1 1374 const request = JSON.parse(data.toString()) as IncomingRequest | Response | ErrorResponse;
47e22477 1375 if (Utils.isIterable(request)) {
9934652c 1376 [messageType, messageId] = request;
b3ec7bc1
JB
1377 // Check the type of message
1378 switch (messageType) {
1379 // Incoming Message
1380 case MessageType.CALL_MESSAGE:
9934652c 1381 [, , commandName, commandPayload] = request as IncomingRequest;
b3ec7bc1
JB
1382 if (this.getEnableStatistics()) {
1383 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1384 }
1385 logger.debug(
1386 `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
1387 request
1388 )}`
1389 );
1390 // Process the message
1391 await this.ocppIncomingRequestService.incomingRequestHandler(
08f130a0 1392 this,
b3ec7bc1
JB
1393 messageId,
1394 commandName,
1395 commandPayload
1396 );
1397 break;
1398 // Outcome Message
1399 case MessageType.CALL_RESULT_MESSAGE:
9934652c 1400 [, , commandPayload] = request as Response;
a2d1c0f1
JB
1401 if (!this.requests.has(messageId)) {
1402 // Error
1403 throw new OCPPError(
1404 ErrorType.INTERNAL_ERROR,
1405 `Response for unknown message id ${messageId}`,
1406 null,
1407 commandPayload
1408 );
1409 }
b3ec7bc1
JB
1410 // Respond
1411 cachedRequest = this.requests.get(messageId);
1412 if (Utils.isIterable(cachedRequest)) {
1413 [responseCallback, , requestCommandName, requestPayload] = cachedRequest;
1414 } else {
1415 throw new OCPPError(
1416 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1417 `Cached request for message id ${messageId} response is not iterable`,
1418 null,
1419 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1420 );
1421 }
1422 logger.debug(
7ec6c5c9
JB
1423 `${this.logPrefix()} << Command '${
1424 requestCommandName ?? ''
1425 }' received response payload: ${JSON.stringify(request)}`
b3ec7bc1 1426 );
a2d1c0f1
JB
1427 responseCallback(commandPayload, requestPayload);
1428 break;
1429 // Error Message
1430 case MessageType.CALL_ERROR_MESSAGE:
1431 [, , errorType, errorMessage, errorDetails] = request as ErrorResponse;
1432 if (!this.requests.has(messageId)) {
b3ec7bc1
JB
1433 // Error
1434 throw new OCPPError(
1435 ErrorType.INTERNAL_ERROR,
a2d1c0f1 1436 `Error response for unknown message id ${messageId}`,
c2bc716f 1437 null,
a2d1c0f1 1438 { errorType, errorMessage, errorDetails }
b3ec7bc1
JB
1439 );
1440 }
b3ec7bc1
JB
1441 cachedRequest = this.requests.get(messageId);
1442 if (Utils.isIterable(cachedRequest)) {
a2d1c0f1 1443 [, errorCallback, requestCommandName] = cachedRequest;
b3ec7bc1
JB
1444 } else {
1445 throw new OCPPError(
1446 ErrorType.PROTOCOL_ERROR,
c2bc716f
JB
1447 `Cached request for message id ${messageId} error response is not iterable`,
1448 null,
1449 cachedRequest as unknown as JsonType
b3ec7bc1
JB
1450 );
1451 }
1452 logger.debug(
7ec6c5c9
JB
1453 `${this.logPrefix()} << Command '${
1454 requestCommandName ?? ''
1455 }' received error payload: ${JSON.stringify(request)}`
b3ec7bc1 1456 );
a2d1c0f1 1457 errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails));
b3ec7bc1
JB
1458 break;
1459 // Error
1460 default:
1461 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1462 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1463 logger.error(errMsg);
1464 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1465 }
47e22477 1466 } else {
ac54a9bb
JB
1467 throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not iterable', null, {
1468 payload: request,
1469 });
47e22477 1470 }
c0560973
JB
1471 } catch (error) {
1472 // Log
e7aeea18
JB
1473 logger.error(
1474 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1475 this.logPrefix(),
1476 data.toString(),
1477 this.requests.get(messageId),
1478 error
1479 );
c0560973 1480 // Send error
e7aeea18 1481 messageType === MessageType.CALL_MESSAGE &&
b3ec7bc1 1482 (await this.ocppRequestService.sendError(
08f130a0 1483 this,
b3ec7bc1
JB
1484 messageId,
1485 error as OCPPError,
a2d1c0f1 1486 commandName ?? requestCommandName ?? null
b3ec7bc1 1487 ));
c0560973 1488 }
2328be1e
JB
1489 }
1490
c0560973 1491 private onPing(): void {
9f2e3130 1492 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
c0560973
JB
1493 }
1494
1495 private onPong(): void {
9f2e3130 1496 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
c0560973
JB
1497 }
1498
9534e74e 1499 private onError(error: WSError): void {
9f2e3130 1500 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
c0560973
JB
1501 }
1502
fa7bccf4
JB
1503 private getUseConnectorId0(stationInfo?: ChargingStationInfo): boolean | undefined {
1504 const localStationInfo = stationInfo ?? this.stationInfo;
1505 return !Utils.isUndefined(localStationInfo.useConnectorId0)
1506 ? localStationInfo.useConnectorId0
e7aeea18 1507 : true;
8bce55bf
JB
1508 }
1509
c0560973 1510 private getNumberOfRunningTransactions(): number {
6ecb15e4 1511 let trxCount = 0;
734d790d
JB
1512 for (const connectorId of this.connectors.keys()) {
1513 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
6ecb15e4
JB
1514 trxCount++;
1515 }
1516 }
1517 return trxCount;
1518 }
1519
1f761b9a 1520 // 0 for disabling
6e0964c8 1521 private getConnectionTimeout(): number | undefined {
17ac262c
JB
1522 if (
1523 ChargingStationConfigurationUtils.getConfigurationKey(
1524 this,
1525 StandardParametersKey.ConnectionTimeOut
1526 )
1527 ) {
e7aeea18 1528 return (
17ac262c
JB
1529 parseInt(
1530 ChargingStationConfigurationUtils.getConfigurationKey(
1531 this,
1532 StandardParametersKey.ConnectionTimeOut
1533 ).value
1534 ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
e7aeea18 1535 );
291cb255 1536 }
291cb255 1537 return Constants.DEFAULT_CONNECTION_TIMEOUT;
3574dfd3
JB
1538 }
1539
1f761b9a 1540 // -1 for unlimited, 0 for disabling
6e0964c8 1541 private getAutoReconnectMaxRetries(): number | undefined {
ad2f27c3
JB
1542 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1543 return this.stationInfo.autoReconnectMaxRetries;
3574dfd3
JB
1544 }
1545 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1546 return Configuration.getAutoReconnectMaxRetries();
1547 }
1548 return -1;
1549 }
1550
ec977daf 1551 // 0 for disabling
6e0964c8 1552 private getRegistrationMaxRetries(): number | undefined {
ad2f27c3
JB
1553 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1554 return this.stationInfo.registrationMaxRetries;
32a1eb7a
JB
1555 }
1556 return -1;
1557 }
1558
c0560973
JB
1559 private getPowerDivider(): number {
1560 let powerDivider = this.getNumberOfConnectors();
fa7bccf4 1561 if (this.stationInfo?.powerSharedByConnectors) {
c0560973 1562 powerDivider = this.getNumberOfRunningTransactions();
6ecb15e4
JB
1563 }
1564 return powerDivider;
1565 }
1566
fa7bccf4
JB
1567 private getMaximumPower(stationInfo?: ChargingStationInfo): number {
1568 const localStationInfo = stationInfo ?? this.stationInfo;
1569 return (localStationInfo['maxPower'] as number) ?? localStationInfo.maximumPower;
0642c3d2
JB
1570 }
1571
fa7bccf4
JB
1572 private getMaximumAmperage(stationInfo: ChargingStationInfo): number | undefined {
1573 const maximumPower = this.getMaximumPower(stationInfo);
1574 switch (this.getCurrentOutType(stationInfo)) {
cc6e8ab5
JB
1575 case CurrentType.AC:
1576 return ACElectricUtils.amperagePerPhaseFromPower(
fa7bccf4 1577 this.getNumberOfPhases(stationInfo),
ad8537a7 1578 maximumPower / this.getNumberOfConnectors(),
fa7bccf4 1579 this.getVoltageOut(stationInfo)
cc6e8ab5
JB
1580 );
1581 case CurrentType.DC:
fa7bccf4 1582 return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo));
cc6e8ab5
JB
1583 }
1584 }
1585
cc6e8ab5
JB
1586 private getAmperageLimitation(): number | undefined {
1587 if (
1588 this.stationInfo.amperageLimitationOcppKey &&
17ac262c
JB
1589 ChargingStationConfigurationUtils.getConfigurationKey(
1590 this,
1591 this.stationInfo.amperageLimitationOcppKey
1592 )
cc6e8ab5
JB
1593 ) {
1594 return (
1595 Utils.convertToInt(
17ac262c
JB
1596 ChargingStationConfigurationUtils.getConfigurationKey(
1597 this,
1598 this.stationInfo.amperageLimitationOcppKey
1599 ).value
1600 ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
cc6e8ab5
JB
1601 );
1602 }
1603 }
1604
c0560973 1605 private async startMessageSequence(): Promise<void> {
7c72977b 1606 if (this.stationInfo?.autoRegister) {
f7f98c68 1607 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1608 BootNotificationRequest,
1609 BootNotificationResponse
1610 >(
08f130a0 1611 this,
6a8b180d
JB
1612 RequestCommand.BOOT_NOTIFICATION,
1613 {
1614 chargePointModel: this.bootNotificationRequest.chargePointModel,
1615 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1616 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1617 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
29d1e2e7
JB
1618 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1619 iccid: this.bootNotificationRequest.iccid,
1620 imsi: this.bootNotificationRequest.imsi,
1621 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1622 meterType: this.bootNotificationRequest.meterType,
6a8b180d
JB
1623 },
1624 { skipBufferingOnError: true }
e7aeea18 1625 );
6114e6f1 1626 }
136c90ba 1627 // Start WebSocket ping
c0560973 1628 this.startWebSocketPing();
5ad8570f 1629 // Start heartbeat
c0560973 1630 this.startHeartbeat();
0a60c33c 1631 // Initialize connectors status
734d790d
JB
1632 for (const connectorId of this.connectors.keys()) {
1633 if (connectorId === 0) {
593cf3f9 1634 continue;
e7aeea18
JB
1635 } else if (
1636 !this.stopped &&
1637 !this.getConnectorStatus(connectorId)?.status &&
1638 this.getConnectorStatus(connectorId)?.bootStatus
1639 ) {
136c90ba 1640 // Send status in template at startup
f7f98c68 1641 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1642 StatusNotificationRequest,
1643 StatusNotificationResponse
08f130a0 1644 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1645 connectorId,
1646 status: this.getConnectorStatus(connectorId).bootStatus,
1647 errorCode: ChargePointErrorCode.NO_ERROR,
1648 });
e7aeea18
JB
1649 this.getConnectorStatus(connectorId).status =
1650 this.getConnectorStatus(connectorId).bootStatus;
1651 } else if (
1652 this.stopped &&
1653 this.getConnectorStatus(connectorId)?.status &&
1654 this.getConnectorStatus(connectorId)?.bootStatus
1655 ) {
136c90ba 1656 // Send status in template after reset
f7f98c68 1657 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1658 StatusNotificationRequest,
1659 StatusNotificationResponse
08f130a0 1660 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1661 connectorId,
1662 status: this.getConnectorStatus(connectorId).bootStatus,
1663 errorCode: ChargePointErrorCode.NO_ERROR,
1664 });
e7aeea18
JB
1665 this.getConnectorStatus(connectorId).status =
1666 this.getConnectorStatus(connectorId).bootStatus;
734d790d 1667 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
136c90ba 1668 // Send previous status at template reload
f7f98c68 1669 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1670 StatusNotificationRequest,
1671 StatusNotificationResponse
08f130a0 1672 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1673 connectorId,
1674 status: this.getConnectorStatus(connectorId).status,
1675 errorCode: ChargePointErrorCode.NO_ERROR,
1676 });
5ad8570f 1677 } else {
136c90ba 1678 // Send default status
f7f98c68 1679 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1680 StatusNotificationRequest,
1681 StatusNotificationResponse
08f130a0 1682 >(this, RequestCommand.STATUS_NOTIFICATION, {
ef6fa3fb
JB
1683 connectorId,
1684 status: ChargePointStatus.AVAILABLE,
1685 errorCode: ChargePointErrorCode.NO_ERROR,
1686 });
734d790d 1687 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
5ad8570f
JB
1688 }
1689 }
0a60c33c 1690 // Start the ATG
dd119a6b 1691 this.startAutomaticTransactionGenerator();
dd119a6b
JB
1692 }
1693
1694 private startAutomaticTransactionGenerator() {
fa7bccf4 1695 if (this.getAutomaticTransactionGeneratorConfigurationFromTemplate()?.enable) {
265e4266 1696 if (!this.automaticTransactionGenerator) {
fa7bccf4
JB
1697 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(
1698 this.getAutomaticTransactionGeneratorConfigurationFromTemplate(),
1699 this
1700 );
5ad8570f 1701 }
265e4266
JB
1702 if (!this.automaticTransactionGenerator.started) {
1703 this.automaticTransactionGenerator.start();
5ad8570f
JB
1704 }
1705 }
5ad8570f
JB
1706 }
1707
fa7bccf4
JB
1708 private stopAutomaticTransactionGenerator(): void {
1709 if (this.automaticTransactionGenerator?.started) {
1710 this.automaticTransactionGenerator.stop();
1711 this.automaticTransactionGenerator = null;
1712 }
1713 }
1714
e7aeea18
JB
1715 private async stopMessageSequence(
1716 reason: StopTransactionReason = StopTransactionReason.NONE
1717 ): Promise<void> {
136c90ba 1718 // Stop WebSocket ping
c0560973 1719 this.stopWebSocketPing();
79411696 1720 // Stop heartbeat
c0560973 1721 this.stopHeartbeat();
fa7bccf4
JB
1722 // Stop ongoing transactions
1723 if (this.automaticTransactionGenerator?.configuration?.enable) {
1724 this.stopAutomaticTransactionGenerator();
79411696 1725 } else {
734d790d
JB
1726 for (const connectorId of this.connectors.keys()) {
1727 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1728 const transactionId = this.getConnectorStatus(connectorId).transactionId;
68c993d5
JB
1729 if (
1730 this.getBeginEndMeterValues() &&
1731 this.getOcppStrictCompliance() &&
1732 !this.getOutOfOrderEndMeterValues()
1733 ) {
1734 // FIXME: Implement OCPP version agnostic helpers
1735 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1736 this,
1737 connectorId,
1738 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1739 );
f7f98c68 1740 await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
08f130a0 1741 this,
f7f98c68
JB
1742 RequestCommand.METER_VALUES,
1743 {
1744 connectorId,
1745 transactionId,
1746 meterValue: transactionEndMeterValue,
1747 }
1748 );
ef6fa3fb 1749 }
f7f98c68 1750 await this.ocppRequestService.requestHandler<
ef6fa3fb
JB
1751 StopTransactionRequest,
1752 StopTransactionResponse
08f130a0 1753 >(this, RequestCommand.STOP_TRANSACTION, {
ef6fa3fb
JB
1754 transactionId,
1755 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1756 idTag: this.getTransactionIdTag(transactionId),
1757 reason,
1758 });
79411696
JB
1759 }
1760 }
1761 }
1762 }
1763
c0560973 1764 private startWebSocketPing(): void {
17ac262c
JB
1765 const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey(
1766 this,
e7aeea18
JB
1767 StandardParametersKey.WebSocketPingInterval
1768 )
1769 ? Utils.convertToInt(
17ac262c
JB
1770 ChargingStationConfigurationUtils.getConfigurationKey(
1771 this,
1772 StandardParametersKey.WebSocketPingInterval
1773 ).value
e7aeea18 1774 )
9cd3dfb0 1775 : 0;
ad2f27c3
JB
1776 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1777 this.webSocketPingSetInterval = setInterval(() => {
d5bff457 1778 if (this.isWebSocketConnectionOpened()) {
e7aeea18
JB
1779 this.wsConnection.ping((): void => {
1780 /* This is intentional */
1781 });
136c90ba
JB
1782 }
1783 }, webSocketPingInterval * 1000);
e7aeea18
JB
1784 logger.info(
1785 this.logPrefix() +
1786 ' WebSocket ping started every ' +
1787 Utils.formatDurationSeconds(webSocketPingInterval)
1788 );
ad2f27c3 1789 } else if (this.webSocketPingSetInterval) {
e7aeea18
JB
1790 logger.info(
1791 this.logPrefix() +
1792 ' WebSocket ping every ' +
1793 Utils.formatDurationSeconds(webSocketPingInterval) +
1794 ' already started'
1795 );
136c90ba 1796 } else {
e7aeea18
JB
1797 logger.error(
1798 `${this.logPrefix()} WebSocket ping interval set to ${
1799 webSocketPingInterval
1800 ? Utils.formatDurationSeconds(webSocketPingInterval)
1801 : webSocketPingInterval
1802 }, not starting the WebSocket ping`
1803 );
136c90ba
JB
1804 }
1805 }
1806
c0560973 1807 private stopWebSocketPing(): void {
ad2f27c3
JB
1808 if (this.webSocketPingSetInterval) {
1809 clearInterval(this.webSocketPingSetInterval);
136c90ba
JB
1810 }
1811 }
1812
1f5df42a 1813 private getConfiguredSupervisionUrl(): URL {
e7aeea18
JB
1814 const supervisionUrls = Utils.cloneObject<string | string[]>(
1815 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1816 );
c0560973 1817 if (!Utils.isEmptyArray(supervisionUrls)) {
2dcfe98e
JB
1818 let urlIndex = 0;
1819 switch (Configuration.getSupervisionUrlDistribution()) {
1820 case SupervisionUrlDistribution.ROUND_ROBIN:
1821 urlIndex = (this.index - 1) % supervisionUrls.length;
1822 break;
1823 case SupervisionUrlDistribution.RANDOM:
1824 // Get a random url
1825 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1826 break;
1827 case SupervisionUrlDistribution.SEQUENTIAL:
1828 if (this.index <= supervisionUrls.length) {
1829 urlIndex = this.index - 1;
1830 } else {
e7aeea18
JB
1831 logger.warn(
1832 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1833 );
2dcfe98e
JB
1834 }
1835 break;
1836 default:
e7aeea18
JB
1837 logger.error(
1838 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1839 SupervisionUrlDistribution.ROUND_ROBIN
1840 }`
1841 );
2dcfe98e
JB
1842 urlIndex = (this.index - 1) % supervisionUrls.length;
1843 break;
c0560973 1844 }
2dcfe98e 1845 return new URL(supervisionUrls[urlIndex]);
c0560973 1846 }
57939a9d 1847 return new URL(supervisionUrls as string);
136c90ba
JB
1848 }
1849
6e0964c8 1850 private getHeartbeatInterval(): number | undefined {
17ac262c
JB
1851 const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1852 this,
1853 StandardParametersKey.HeartbeatInterval
1854 );
c0560973
JB
1855 if (HeartbeatInterval) {
1856 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1857 }
17ac262c
JB
1858 const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey(
1859 this,
1860 StandardParametersKey.HeartBeatInterval
1861 );
c0560973
JB
1862 if (HeartBeatInterval) {
1863 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
0a60c33c 1864 }
7c72977b 1865 !this.stationInfo?.autoRegister &&
e7aeea18
JB
1866 logger.warn(
1867 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1868 Constants.DEFAULT_HEARTBEAT_INTERVAL
1869 }`
1870 );
47e22477 1871 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
0a60c33c
JB
1872 }
1873
c0560973 1874 private stopHeartbeat(): void {
ad2f27c3
JB
1875 if (this.heartbeatSetInterval) {
1876 clearInterval(this.heartbeatSetInterval);
7dde0b73 1877 }
5ad8570f
JB
1878 }
1879
e7aeea18 1880 private openWSConnection(
ccb1d6e9 1881 options: WsOptions = this.stationInfo?.wsOptions ?? {},
1e080116
JB
1882 params: { closeOpened?: boolean; terminateOpened?: boolean } = {
1883 closeOpened: false,
1884 terminateOpened: false,
1885 }
e7aeea18 1886 ): void {
37486900 1887 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1e080116 1888 params.closeOpened = params?.closeOpened ?? false;
d86d12d2 1889 params.terminateOpened = params?.terminateOpened ?? false;
e7aeea18
JB
1890 if (
1891 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
1892 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
1893 ) {
15042c5f
JB
1894 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1895 }
1e080116 1896 if (this.isWebSocketConnectionOpened() && params?.closeOpened) {
c0560973
JB
1897 this.wsConnection.close();
1898 }
1e080116
JB
1899 if (this.isWebSocketConnectionOpened() && params?.terminateOpened) {
1900 this.wsConnection.terminate();
1901 }
88184022 1902 let protocol: string;
1f5df42a 1903 switch (this.getOcppVersion()) {
c0560973
JB
1904 case OCPPVersion.VERSION_16:
1905 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1906 break;
1907 default:
1f5df42a 1908 this.handleUnsupportedVersion(this.getOcppVersion());
c0560973
JB
1909 break;
1910 }
1911 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
e7aeea18
JB
1912 logger.info(
1913 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
1914 );
136c90ba
JB
1915 }
1916
dd119a6b 1917 private stopMeterValues(connectorId: number) {
734d790d
JB
1918 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1919 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
dd119a6b
JB
1920 }
1921 }
1922
6e0964c8 1923 private getReconnectExponentialDelay(): boolean | undefined {
e7aeea18
JB
1924 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1925 ? this.stationInfo.reconnectExponentialDelay
1926 : false;
5ad8570f
JB
1927 }
1928
d09085e9 1929 private async reconnect(code: number): Promise<void> {
7874b0b1
JB
1930 // Stop WebSocket ping
1931 this.stopWebSocketPing();
136c90ba 1932 // Stop heartbeat
c0560973 1933 this.stopHeartbeat();
5ad8570f 1934 // Stop the ATG if needed
fa7bccf4
JB
1935 if (this.automaticTransactionGenerator?.configuration?.stopOnConnectionFailure) {
1936 this.stopAutomaticTransactionGenerator();
ad2f27c3 1937 }
e7aeea18
JB
1938 if (
1939 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1940 this.getAutoReconnectMaxRetries() === -1
1941 ) {
ad2f27c3 1942 this.autoReconnectRetryCount++;
e7aeea18
JB
1943 const reconnectDelay = this.getReconnectExponentialDelay()
1944 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1945 : this.getConnectionTimeout() * 1000;
1e080116
JB
1946 const reconnectDelayWithdraw = 1000;
1947 const reconnectTimeout =
1948 reconnectDelay && reconnectDelay - reconnectDelayWithdraw > 0
1949 ? reconnectDelay - reconnectDelayWithdraw
1950 : 0;
e7aeea18
JB
1951 logger.error(
1952 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1953 reconnectDelay,
1954 2
1955 )}ms, timeout ${reconnectTimeout}ms`
1956 );
032d6efc 1957 await Utils.sleep(reconnectDelay);
e7aeea18
JB
1958 logger.error(
1959 this.logPrefix() +
1960 ' WebSocket: reconnecting try #' +
1961 this.autoReconnectRetryCount.toString()
1962 );
1963 this.openWSConnection(
ccb1d6e9 1964 { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout },
1e080116 1965 { closeOpened: true }
e7aeea18 1966 );
265e4266 1967 this.wsConnectionRestarted = true;
c0560973 1968 } else if (this.getAutoReconnectMaxRetries() !== -1) {
e7aeea18 1969 logger.error(
71a77ac2 1970 `${this.logPrefix()} WebSocket reconnect failure: maximum retries reached (${
e7aeea18
JB
1971 this.autoReconnectRetryCount
1972 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1973 );
5ad8570f
JB
1974 }
1975 }
1976
fa7bccf4
JB
1977 private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null {
1978 return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null;
1979 }
1980
a2653482
JB
1981 private initializeConnectorStatus(connectorId: number): void {
1982 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1983 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1984 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
734d790d
JB
1985 this.getConnectorStatus(connectorId).transactionStarted = false;
1986 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1987 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
0a60c33c 1988 }
7dde0b73 1989}