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