Add persistent OCPP parameters key/value support by CS generated name
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import {
4 AvailabilityType,
5 BootNotificationRequest,
6 CachedRequest,
7 IncomingRequest,
8 IncomingRequestCommand,
9 RequestCommand,
10 } from '../types/ocpp/Requests';
11 import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
12 import ChargingStationConfiguration, {
13 ConfigurationKey,
14 } from '../types/ChargingStationConfiguration';
15 import ChargingStationTemplate, {
16 CurrentType,
17 PowerUnits,
18 Voltage,
19 } from '../types/ChargingStationTemplate';
20 import {
21 ConnectorPhaseRotation,
22 StandardParametersKey,
23 SupportedFeatureProfiles,
24 VendorDefaultParametersKey,
25 } from '../types/ocpp/Configuration';
26 import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
27 import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
28 import WebSocket, { ClientOptions, Data, OPEN, RawData } from 'ws';
29
30 import AutomaticTransactionGenerator from './AutomaticTransactionGenerator';
31 import { ChargePointErrorCode } from '../types/ocpp/ChargePointErrorCode';
32 import { ChargePointStatus } from '../types/ocpp/ChargePointStatus';
33 import { ChargingProfile } from '../types/ocpp/ChargingProfile';
34 import ChargingStationInfo from '../types/ChargingStationInfo';
35 import { ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
36 import { ClientRequestArgs } from 'http';
37 import Configuration from '../utils/Configuration';
38 import { ConnectorStatus } from '../types/ConnectorStatus';
39 import Constants from '../utils/Constants';
40 import { ErrorType } from '../types/ocpp/ErrorType';
41 import FileUtils from '../utils/FileUtils';
42 import { JsonType } from '../types/JsonType';
43 import { MessageType } from '../types/ocpp/MessageType';
44 import OCPP16IncomingRequestService from './ocpp/1.6/OCPP16IncomingRequestService';
45 import OCPP16RequestService from './ocpp/1.6/OCPP16RequestService';
46 import OCPP16ResponseService from './ocpp/1.6/OCPP16ResponseService';
47 import { OCPP16ServiceUtils } from './ocpp/1.6/OCPP16ServiceUtils';
48 import OCPPError from '../exception/OCPPError';
49 import OCPPIncomingRequestService from './ocpp/OCPPIncomingRequestService';
50 import OCPPRequestService from './ocpp/OCPPRequestService';
51 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
52 import PerformanceStatistics from '../performance/PerformanceStatistics';
53 import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
54 import { StopTransactionReason } from '../types/ocpp/Transaction';
55 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
56 import { URL } from 'url';
57 import Utils from '../utils/Utils';
58 import crypto from 'crypto';
59 import fs from 'fs';
60 import logger from '../utils/Logger';
61 import { parentPort } from 'worker_threads';
62 import path from 'path';
63
64 export default class ChargingStation {
65 public readonly id: string;
66 public readonly stationTemplateFile: string;
67 public authorizedTags: string[];
68 public stationInfo!: ChargingStationInfo;
69 public readonly connectors: Map<number, ConnectorStatus>;
70 public configuration!: ChargingStationConfiguration;
71 public wsConnection!: WebSocket;
72 public readonly requests: Map<string, CachedRequest>;
73 public performanceStatistics!: PerformanceStatistics;
74 public heartbeatSetInterval!: NodeJS.Timeout;
75 public ocppRequestService!: OCPPRequestService;
76 private readonly index: number;
77 private configurationFile!: string;
78 private bootNotificationRequest!: BootNotificationRequest;
79 private bootNotificationResponse!: BootNotificationResponse | null;
80 private connectorsConfigurationHash!: string;
81 private ocppIncomingRequestService!: OCPPIncomingRequestService;
82 private readonly messageBuffer: Set<string>;
83 private wsConfiguredConnectionUrl!: URL;
84 private wsConnectionRestarted: boolean;
85 private stopped: boolean;
86 private autoReconnectRetryCount: number;
87 private automaticTransactionGenerator!: AutomaticTransactionGenerator;
88 private webSocketPingSetInterval!: NodeJS.Timeout;
89
90 constructor(index: number, stationTemplateFile: string) {
91 this.id = Utils.generateUUID();
92 this.index = index;
93 this.stationTemplateFile = stationTemplateFile;
94 this.stopped = false;
95 this.wsConnectionRestarted = false;
96 this.autoReconnectRetryCount = 0;
97 this.connectors = new Map<number, ConnectorStatus>();
98 this.requests = new Map<string, CachedRequest>();
99 this.messageBuffer = new Set<string>();
100 this.initialize();
101 this.authorizedTags = this.getAuthorizedTags();
102 }
103
104 get wsConnectionUrl(): URL {
105 return this.getSupervisionUrlOcppConfiguration()
106 ? new URL(
107 this.getConfigurationKey(
108 this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
109 ).value +
110 '/' +
111 this.stationInfo.chargingStationId
112 )
113 : this.wsConfiguredConnectionUrl;
114 }
115
116 public logPrefix(): string {
117 return Utils.logPrefix(` ${this.stationInfo.chargingStationId} |`);
118 }
119
120 public getBootNotificationRequest(): BootNotificationRequest {
121 return this.bootNotificationRequest;
122 }
123
124 public getRandomIdTag(): string {
125 const index = Math.floor(Utils.secureRandom() * this.authorizedTags.length);
126 return this.authorizedTags[index];
127 }
128
129 public hasAuthorizedTags(): boolean {
130 return !Utils.isEmptyArray(this.authorizedTags);
131 }
132
133 public getEnableStatistics(): boolean | undefined {
134 return !Utils.isUndefined(this.stationInfo.enableStatistics)
135 ? this.stationInfo.enableStatistics
136 : true;
137 }
138
139 public getMayAuthorizeAtRemoteStart(): boolean | undefined {
140 return this.stationInfo.mayAuthorizeAtRemoteStart ?? true;
141 }
142
143 public getNumberOfPhases(): number | undefined {
144 switch (this.getCurrentOutType()) {
145 case CurrentType.AC:
146 return !Utils.isUndefined(this.stationInfo.numberOfPhases)
147 ? this.stationInfo.numberOfPhases
148 : 3;
149 case CurrentType.DC:
150 return 0;
151 }
152 }
153
154 public isWebSocketConnectionOpened(): boolean {
155 return this?.wsConnection?.readyState === OPEN;
156 }
157
158 public getRegistrationStatus(): RegistrationStatus {
159 return this?.bootNotificationResponse?.status;
160 }
161
162 public isInUnknownState(): boolean {
163 return Utils.isNullOrUndefined(this?.bootNotificationResponse?.status);
164 }
165
166 public isInPendingState(): boolean {
167 return this?.bootNotificationResponse?.status === RegistrationStatus.PENDING;
168 }
169
170 public isInAcceptedState(): boolean {
171 return this?.bootNotificationResponse?.status === RegistrationStatus.ACCEPTED;
172 }
173
174 public isInRejectedState(): boolean {
175 return this?.bootNotificationResponse?.status === RegistrationStatus.REJECTED;
176 }
177
178 public isRegistered(): boolean {
179 return !this.isInUnknownState() && (this.isInAcceptedState() || this.isInPendingState());
180 }
181
182 public isChargingStationAvailable(): boolean {
183 return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE;
184 }
185
186 public isConnectorAvailable(id: number): boolean {
187 return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE;
188 }
189
190 public getNumberOfConnectors(): number {
191 return this.connectors.get(0) ? this.connectors.size - 1 : this.connectors.size;
192 }
193
194 public getConnectorStatus(id: number): ConnectorStatus {
195 return this.connectors.get(id);
196 }
197
198 public getCurrentOutType(): CurrentType | undefined {
199 return this.stationInfo.currentOutType ?? CurrentType.AC;
200 }
201
202 public getOcppStrictCompliance(): boolean {
203 return this.stationInfo.ocppStrictCompliance ?? false;
204 }
205
206 public getVoltageOut(): number | undefined {
207 const errMsg = `${this.logPrefix()} Unknown ${this.getCurrentOutType()} currentOutType in template file ${
208 this.stationTemplateFile
209 }, cannot define default voltage out`;
210 let defaultVoltageOut: number;
211 switch (this.getCurrentOutType()) {
212 case CurrentType.AC:
213 defaultVoltageOut = Voltage.VOLTAGE_230;
214 break;
215 case CurrentType.DC:
216 defaultVoltageOut = Voltage.VOLTAGE_400;
217 break;
218 default:
219 logger.error(errMsg);
220 throw new Error(errMsg);
221 }
222 return !Utils.isUndefined(this.stationInfo.voltageOut)
223 ? this.stationInfo.voltageOut
224 : defaultVoltageOut;
225 }
226
227 public getTransactionIdTag(transactionId: number): string | undefined {
228 for (const connectorId of this.connectors.keys()) {
229 if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
230 return this.getConnectorStatus(connectorId).transactionIdTag;
231 }
232 }
233 }
234
235 public getOutOfOrderEndMeterValues(): boolean {
236 return this.stationInfo.outOfOrderEndMeterValues ?? false;
237 }
238
239 public getBeginEndMeterValues(): boolean {
240 return this.stationInfo.beginEndMeterValues ?? false;
241 }
242
243 public getMeteringPerTransaction(): boolean {
244 return this.stationInfo.meteringPerTransaction ?? true;
245 }
246
247 public getTransactionDataMeterValues(): boolean {
248 return this.stationInfo.transactionDataMeterValues ?? false;
249 }
250
251 public getMainVoltageMeterValues(): boolean {
252 return this.stationInfo.mainVoltageMeterValues ?? true;
253 }
254
255 public getPhaseLineToLineVoltageMeterValues(): boolean {
256 return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
257 }
258
259 public getConnectorIdByTransactionId(transactionId: number): number | undefined {
260 for (const connectorId of this.connectors.keys()) {
261 if (
262 connectorId > 0 &&
263 this.getConnectorStatus(connectorId)?.transactionId === transactionId
264 ) {
265 return connectorId;
266 }
267 }
268 }
269
270 public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
271 const transactionConnectorStatus = this.getConnectorStatus(
272 this.getConnectorIdByTransactionId(transactionId)
273 );
274 if (this.getMeteringPerTransaction()) {
275 return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
276 }
277 return transactionConnectorStatus?.energyActiveImportRegisterValue;
278 }
279
280 public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
281 const connectorStatus = this.getConnectorStatus(connectorId);
282 if (this.getMeteringPerTransaction()) {
283 return connectorStatus?.transactionEnergyActiveImportRegisterValue;
284 }
285 return connectorStatus?.energyActiveImportRegisterValue;
286 }
287
288 public getAuthorizeRemoteTxRequests(): boolean {
289 const authorizeRemoteTxRequests = this.getConfigurationKey(
290 StandardParametersKey.AuthorizeRemoteTxRequests
291 );
292 return authorizeRemoteTxRequests
293 ? Utils.convertToBoolean(authorizeRemoteTxRequests.value)
294 : false;
295 }
296
297 public getLocalAuthListEnabled(): boolean {
298 const localAuthListEnabled = this.getConfigurationKey(
299 StandardParametersKey.LocalAuthListEnabled
300 );
301 return localAuthListEnabled ? Utils.convertToBoolean(localAuthListEnabled.value) : false;
302 }
303
304 public restartWebSocketPing(): void {
305 // Stop WebSocket ping
306 this.stopWebSocketPing();
307 // Start WebSocket ping
308 this.startWebSocketPing();
309 }
310
311 public getSampledValueTemplate(
312 connectorId: number,
313 measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER,
314 phase?: MeterValuePhase
315 ): SampledValueTemplate | undefined {
316 const onPhaseStr = phase ? `on phase ${phase} ` : '';
317 if (!Constants.SUPPORTED_MEASURANDS.includes(measurand)) {
318 logger.warn(
319 `${this.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
320 );
321 return;
322 }
323 if (
324 measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
325 !this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
326 measurand
327 )
328 ) {
329 logger.debug(
330 `${this.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
331 StandardParametersKey.MeterValuesSampledData
332 }' OCPP parameter`
333 );
334 return;
335 }
336 const sampledValueTemplates: SampledValueTemplate[] =
337 this.getConnectorStatus(connectorId).MeterValues;
338 for (
339 let index = 0;
340 !Utils.isEmptyArray(sampledValueTemplates) && index < sampledValueTemplates.length;
341 index++
342 ) {
343 if (
344 !Constants.SUPPORTED_MEASURANDS.includes(
345 sampledValueTemplates[index]?.measurand ??
346 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
347 )
348 ) {
349 logger.warn(
350 `${this.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
351 );
352 } else if (
353 phase &&
354 sampledValueTemplates[index]?.phase === phase &&
355 sampledValueTemplates[index]?.measurand === measurand &&
356 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
357 measurand
358 )
359 ) {
360 return sampledValueTemplates[index];
361 } else if (
362 !phase &&
363 !sampledValueTemplates[index].phase &&
364 sampledValueTemplates[index]?.measurand === measurand &&
365 this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData).value.includes(
366 measurand
367 )
368 ) {
369 return sampledValueTemplates[index];
370 } else if (
371 measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
372 (!sampledValueTemplates[index].measurand ||
373 sampledValueTemplates[index].measurand === measurand)
374 ) {
375 return sampledValueTemplates[index];
376 }
377 }
378 if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) {
379 const errorMsg = `${this.logPrefix()} Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
380 logger.error(errorMsg);
381 throw new Error(errorMsg);
382 }
383 logger.debug(
384 `${this.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
385 );
386 }
387
388 public getAutomaticTransactionGeneratorRequireAuthorize(): boolean {
389 return this.stationInfo.AutomaticTransactionGenerator.requireAuthorize ?? true;
390 }
391
392 public startHeartbeat(): void {
393 if (
394 this.getHeartbeatInterval() &&
395 this.getHeartbeatInterval() > 0 &&
396 !this.heartbeatSetInterval
397 ) {
398 // eslint-disable-next-line @typescript-eslint/no-misused-promises
399 this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
400 await this.ocppRequestService.sendMessageHandler(RequestCommand.HEARTBEAT);
401 }, this.getHeartbeatInterval());
402 logger.info(
403 this.logPrefix() +
404 ' Heartbeat started every ' +
405 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
406 );
407 } else if (this.heartbeatSetInterval) {
408 logger.info(
409 this.logPrefix() +
410 ' Heartbeat already started every ' +
411 Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
412 );
413 } else {
414 logger.error(
415 `${this.logPrefix()} Heartbeat interval set to ${
416 this.getHeartbeatInterval()
417 ? Utils.formatDurationMilliSeconds(this.getHeartbeatInterval())
418 : this.getHeartbeatInterval()
419 }, not starting the heartbeat`
420 );
421 }
422 }
423
424 public restartHeartbeat(): void {
425 // Stop heartbeat
426 this.stopHeartbeat();
427 // Start heartbeat
428 this.startHeartbeat();
429 }
430
431 public startMeterValues(connectorId: number, interval: number): void {
432 if (connectorId === 0) {
433 logger.error(
434 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId.toString()}`
435 );
436 return;
437 }
438 if (!this.getConnectorStatus(connectorId)) {
439 logger.error(
440 `${this.logPrefix()} Trying to start MeterValues on non existing connector Id ${connectorId.toString()}`
441 );
442 return;
443 }
444 if (!this.getConnectorStatus(connectorId)?.transactionStarted) {
445 logger.error(
446 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction started`
447 );
448 return;
449 } else if (
450 this.getConnectorStatus(connectorId)?.transactionStarted &&
451 !this.getConnectorStatus(connectorId)?.transactionId
452 ) {
453 logger.error(
454 `${this.logPrefix()} Trying to start MeterValues on connector Id ${connectorId} with no transaction id`
455 );
456 return;
457 }
458 if (interval > 0) {
459 // eslint-disable-next-line @typescript-eslint/no-misused-promises
460 this.getConnectorStatus(connectorId).transactionSetInterval = setInterval(
461 // eslint-disable-next-line @typescript-eslint/no-misused-promises
462 async (): Promise<void> => {
463 // FIXME: Implement OCPP version agnostic helpers
464 const meterValue: MeterValue = OCPP16ServiceUtils.buildMeterValue(
465 this,
466 connectorId,
467 this.getConnectorStatus(connectorId).transactionId,
468 interval
469 );
470 await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, {
471 connectorId,
472 transactionId: this.getConnectorStatus(connectorId).transactionId,
473 meterValue: [meterValue],
474 });
475 },
476 interval
477 );
478 } else {
479 logger.error(
480 `${this.logPrefix()} Charging station ${
481 StandardParametersKey.MeterValueSampleInterval
482 } configuration set to ${
483 interval ? Utils.formatDurationMilliSeconds(interval) : interval
484 }, not sending MeterValues`
485 );
486 }
487 }
488
489 public start(): void {
490 if (this.getEnableStatistics()) {
491 this.performanceStatistics.start();
492 }
493 this.openWSConnection();
494 // Monitor authorization file
495 this.startAuthorizationFileMonitoring();
496 // Monitor station template file
497 this.startStationTemplateFileMonitoring();
498 // Handle WebSocket message
499 this.wsConnection.on(
500 'message',
501 this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
502 );
503 // Handle WebSocket error
504 this.wsConnection.on(
505 'error',
506 this.onError.bind(this) as (this: WebSocket, error: Error) => void
507 );
508 // Handle WebSocket close
509 this.wsConnection.on(
510 'close',
511 this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
512 );
513 // Handle WebSocket open
514 this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void);
515 // Handle WebSocket ping
516 this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void);
517 // Handle WebSocket pong
518 this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void);
519 parentPort.postMessage({
520 id: ChargingStationWorkerMessageEvents.STARTED,
521 data: { id: this.stationInfo.chargingStationId },
522 });
523 }
524
525 public async stop(reason: StopTransactionReason = StopTransactionReason.NONE): Promise<void> {
526 // Stop message sequence
527 await this.stopMessageSequence(reason);
528 for (const connectorId of this.connectors.keys()) {
529 if (connectorId > 0) {
530 await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
531 connectorId,
532 status: ChargePointStatus.UNAVAILABLE,
533 errorCode: ChargePointErrorCode.NO_ERROR,
534 });
535 this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
536 }
537 }
538 if (this.isWebSocketConnectionOpened()) {
539 this.wsConnection.close();
540 }
541 if (this.getEnableStatistics()) {
542 this.performanceStatistics.stop();
543 }
544 this.bootNotificationResponse = null;
545 parentPort.postMessage({
546 id: ChargingStationWorkerMessageEvents.STOPPED,
547 data: { id: this.stationInfo.chargingStationId },
548 });
549 this.stopped = true;
550 }
551
552 public getConfigurationKey(
553 key: string | StandardParametersKey,
554 caseInsensitive = false
555 ): ConfigurationKey | undefined {
556 return this.configuration.configurationKey.find((configElement) => {
557 if (caseInsensitive) {
558 return configElement.key.toLowerCase() === key.toLowerCase();
559 }
560 return configElement.key === key;
561 });
562 }
563
564 public addConfigurationKey(
565 key: string | StandardParametersKey,
566 value: string,
567 options: { readonly?: boolean; visible?: boolean; reboot?: boolean } = {
568 readonly: false,
569 visible: true,
570 reboot: false,
571 }
572 ): void {
573 const keyFound = this.getConfigurationKey(key);
574 const readonly = options.readonly;
575 const visible = options.visible;
576 const reboot = options.reboot;
577 if (!keyFound) {
578 this.configuration.configurationKey.push({
579 key,
580 readonly,
581 value,
582 visible,
583 reboot,
584 });
585 } else {
586 logger.error(
587 `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
588 keyFound
589 );
590 }
591 }
592
593 public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
594 const keyFound = this.getConfigurationKey(key);
595 if (keyFound) {
596 const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
597 this.configuration.configurationKey[keyIndex].value = value;
598 this.saveConfiguration();
599 } else {
600 logger.error(
601 `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
602 { key, value }
603 );
604 }
605 }
606
607 public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
608 let cpReplaced = false;
609 if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
610 this.getConnectorStatus(connectorId).chargingProfiles?.forEach(
611 (chargingProfile: ChargingProfile, index: number) => {
612 if (
613 chargingProfile.chargingProfileId === cp.chargingProfileId ||
614 (chargingProfile.stackLevel === cp.stackLevel &&
615 chargingProfile.chargingProfilePurpose === cp.chargingProfilePurpose)
616 ) {
617 this.getConnectorStatus(connectorId).chargingProfiles[index] = cp;
618 cpReplaced = true;
619 }
620 }
621 );
622 }
623 !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
624 }
625
626 public resetConnectorStatus(connectorId: number): void {
627 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
628 this.getConnectorStatus(connectorId).idTagAuthorized = false;
629 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
630 this.getConnectorStatus(connectorId).transactionStarted = false;
631 delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
632 delete this.getConnectorStatus(connectorId).authorizeIdTag;
633 delete this.getConnectorStatus(connectorId).transactionId;
634 delete this.getConnectorStatus(connectorId).transactionIdTag;
635 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
636 delete this.getConnectorStatus(connectorId).transactionBeginMeterValue;
637 this.stopMeterValues(connectorId);
638 }
639
640 public bufferMessage(message: string): void {
641 this.messageBuffer.add(message);
642 }
643
644 private flushMessageBuffer() {
645 if (this.messageBuffer.size > 0) {
646 this.messageBuffer.forEach((message) => {
647 // TODO: evaluate the need to track performance
648 this.wsConnection.send(message);
649 this.messageBuffer.delete(message);
650 });
651 }
652 }
653
654 private getSupervisionUrlOcppConfiguration(): boolean {
655 return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
656 }
657
658 private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
659 // In case of multiple instances: add instance index to charging station id
660 const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
661 const idSuffix = stationTemplate.nameSuffix ?? '';
662 const idStr = '000000000' + this.index.toString();
663 return stationTemplate.fixedName
664 ? stationTemplate.baseName
665 : stationTemplate.baseName +
666 '-' +
667 instanceIndex.toString() +
668 idStr.substring(idStr.length - 4) +
669 idSuffix;
670 }
671
672 private buildStationInfo(): ChargingStationInfo {
673 let stationTemplateFromFile: ChargingStationTemplate;
674 try {
675 // Load template file
676 const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
677 stationTemplateFromFile = JSON.parse(
678 fs.readFileSync(fileDescriptor, 'utf8')
679 ) as ChargingStationTemplate;
680 fs.closeSync(fileDescriptor);
681 } catch (error) {
682 FileUtils.handleFileException(
683 this.logPrefix(),
684 'Template',
685 this.stationTemplateFile,
686 error as NodeJS.ErrnoException
687 );
688 }
689 const chargingStationId = this.getChargingStationId(stationTemplateFromFile);
690 // Deprecation template keys section
691 this.warnDeprecatedTemplateKey(
692 stationTemplateFromFile,
693 'supervisionUrl',
694 chargingStationId,
695 "Use 'supervisionUrls' instead"
696 );
697 this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
698 const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? ({} as ChargingStationInfo);
699 stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
700 if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
701 stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
702 const powerArrayRandomIndex = Math.floor(
703 Utils.secureRandom() * stationTemplateFromFile.power.length
704 );
705 stationInfo.maxPower =
706 stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
707 ? stationTemplateFromFile.power[powerArrayRandomIndex] * 1000
708 : stationTemplateFromFile.power[powerArrayRandomIndex];
709 } else {
710 stationTemplateFromFile.power = stationTemplateFromFile.power as number;
711 stationInfo.maxPower =
712 stationTemplateFromFile.powerUnit === PowerUnits.KILO_WATT
713 ? stationTemplateFromFile.power * 1000
714 : stationTemplateFromFile.power;
715 }
716 delete stationInfo.power;
717 delete stationInfo.powerUnit;
718 stationInfo.chargingStationId = chargingStationId;
719 stationInfo.resetTime = stationTemplateFromFile.resetTime
720 ? stationTemplateFromFile.resetTime * 1000
721 : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
722 return stationInfo;
723 }
724
725 private getOcppVersion(): OCPPVersion {
726 return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
727 }
728
729 private handleUnsupportedVersion(version: OCPPVersion) {
730 const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
731 this.stationTemplateFile
732 }`;
733 logger.error(errMsg);
734 throw new Error(errMsg);
735 }
736
737 private initialize(): void {
738 this.stationInfo = this.buildStationInfo();
739 this.configurationFile = path.join(
740 path.resolve(__dirname, '../'),
741 'assets',
742 'configurations',
743 this.stationInfo.chargingStationId + '.json'
744 );
745 this.configuration = this.getConfiguration();
746 delete this.stationInfo.Configuration;
747 this.bootNotificationRequest = {
748 chargePointModel: this.stationInfo.chargePointModel,
749 chargePointVendor: this.stationInfo.chargePointVendor,
750 ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && {
751 chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix,
752 }),
753 ...(!Utils.isUndefined(this.stationInfo.firmwareVersion) && {
754 firmwareVersion: this.stationInfo.firmwareVersion,
755 }),
756 };
757 // Build connectors if needed
758 const maxConnectors = this.getMaxNumberOfConnectors();
759 if (maxConnectors <= 0) {
760 logger.warn(
761 `${this.logPrefix()} Charging station template ${
762 this.stationTemplateFile
763 } with ${maxConnectors} connectors`
764 );
765 }
766 const templateMaxConnectors = this.getTemplateMaxNumberOfConnectors();
767 if (templateMaxConnectors <= 0) {
768 logger.warn(
769 `${this.logPrefix()} Charging station template ${
770 this.stationTemplateFile
771 } with no connector configuration`
772 );
773 }
774 if (!this.stationInfo.Connectors[0]) {
775 logger.warn(
776 `${this.logPrefix()} Charging station template ${
777 this.stationTemplateFile
778 } with no connector Id 0 configuration`
779 );
780 }
781 // Sanity check
782 if (
783 maxConnectors >
784 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) &&
785 !this.stationInfo.randomConnectors
786 ) {
787 logger.warn(
788 `${this.logPrefix()} Number of connectors exceeds the number of connector configurations in template ${
789 this.stationTemplateFile
790 }, forcing random connector configurations affectation`
791 );
792 this.stationInfo.randomConnectors = true;
793 }
794 const connectorsConfigHash = crypto
795 .createHash('sha256')
796 .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
797 .digest('hex');
798 const connectorsConfigChanged =
799 this.connectors?.size !== 0 && this.connectorsConfigurationHash !== connectorsConfigHash;
800 if (this.connectors?.size === 0 || connectorsConfigChanged) {
801 connectorsConfigChanged && this.connectors.clear();
802 this.connectorsConfigurationHash = connectorsConfigHash;
803 // Add connector Id 0
804 let lastConnector = '0';
805 for (lastConnector in this.stationInfo.Connectors) {
806 const lastConnectorId = Utils.convertToInt(lastConnector);
807 if (
808 lastConnectorId === 0 &&
809 this.getUseConnectorId0() &&
810 this.stationInfo.Connectors[lastConnector]
811 ) {
812 this.connectors.set(
813 lastConnectorId,
814 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[lastConnector])
815 );
816 this.getConnectorStatus(lastConnectorId).availability = AvailabilityType.OPERATIVE;
817 if (Utils.isUndefined(this.getConnectorStatus(lastConnectorId)?.chargingProfiles)) {
818 this.getConnectorStatus(lastConnectorId).chargingProfiles = [];
819 }
820 }
821 }
822 // Generate all connectors
823 if (
824 (this.stationInfo.Connectors[0] ? templateMaxConnectors - 1 : templateMaxConnectors) > 0
825 ) {
826 for (let index = 1; index <= maxConnectors; index++) {
827 const randConnectorId = this.stationInfo.randomConnectors
828 ? Utils.getRandomInteger(Utils.convertToInt(lastConnector), 1)
829 : index;
830 this.connectors.set(
831 index,
832 Utils.cloneObject<ConnectorStatus>(this.stationInfo.Connectors[randConnectorId])
833 );
834 this.getConnectorStatus(index).availability = AvailabilityType.OPERATIVE;
835 if (Utils.isUndefined(this.getConnectorStatus(index)?.chargingProfiles)) {
836 this.getConnectorStatus(index).chargingProfiles = [];
837 }
838 }
839 }
840 }
841 // Avoid duplication of connectors related information
842 delete this.stationInfo.Connectors;
843 // Initialize transaction attributes on connectors
844 for (const connectorId of this.connectors.keys()) {
845 if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
846 this.initializeConnectorStatus(connectorId);
847 }
848 }
849 this.wsConfiguredConnectionUrl = new URL(
850 this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
851 );
852 switch (this.getOcppVersion()) {
853 case OCPPVersion.VERSION_16:
854 this.ocppIncomingRequestService =
855 OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>(this);
856 this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
857 this,
858 OCPP16ResponseService.getInstance<OCPP16ResponseService>(this)
859 );
860 break;
861 default:
862 this.handleUnsupportedVersion(this.getOcppVersion());
863 break;
864 }
865 // OCPP parameters
866 this.initOcppParameters();
867 if (this.stationInfo.autoRegister) {
868 this.bootNotificationResponse = {
869 currentTime: new Date().toISOString(),
870 interval: this.getHeartbeatInterval() / 1000,
871 status: RegistrationStatus.ACCEPTED,
872 };
873 }
874 this.stationInfo.powerDivider = this.getPowerDivider();
875 if (this.getEnableStatistics()) {
876 this.performanceStatistics = PerformanceStatistics.getInstance(
877 this.id,
878 this.stationInfo.chargingStationId,
879 this.wsConnectionUrl
880 );
881 }
882 }
883
884 private initOcppParameters(): void {
885 if (
886 this.getSupervisionUrlOcppConfiguration() &&
887 !this.getConfigurationKey(
888 this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
889 )
890 ) {
891 this.addConfigurationKey(
892 VendorDefaultParametersKey.ConnectionUrl,
893 this.getConfiguredSupervisionUrl().href,
894 { reboot: true }
895 );
896 }
897 if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
898 this.addConfigurationKey(
899 StandardParametersKey.SupportedFeatureProfiles,
900 `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.Local_Auth_List_Management},${SupportedFeatureProfiles.Smart_Charging}`
901 );
902 }
903 this.addConfigurationKey(
904 StandardParametersKey.NumberOfConnectors,
905 this.getNumberOfConnectors().toString(),
906 { readonly: true }
907 );
908 if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
909 this.addConfigurationKey(
910 StandardParametersKey.MeterValuesSampledData,
911 MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
912 );
913 }
914 if (!this.getConfigurationKey(StandardParametersKey.ConnectorPhaseRotation)) {
915 const connectorPhaseRotation = [];
916 for (const connectorId of this.connectors.keys()) {
917 // AC/DC
918 if (connectorId === 0 && this.getNumberOfPhases() === 0) {
919 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
920 } else if (connectorId > 0 && this.getNumberOfPhases() === 0) {
921 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
922 // AC
923 } else if (connectorId > 0 && this.getNumberOfPhases() === 1) {
924 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.NotApplicable}`);
925 } else if (connectorId > 0 && this.getNumberOfPhases() === 3) {
926 connectorPhaseRotation.push(`${connectorId}.${ConnectorPhaseRotation.RST}`);
927 }
928 }
929 this.addConfigurationKey(
930 StandardParametersKey.ConnectorPhaseRotation,
931 connectorPhaseRotation.toString()
932 );
933 }
934 if (!this.getConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests)) {
935 this.addConfigurationKey(StandardParametersKey.AuthorizeRemoteTxRequests, 'true');
936 }
937 if (
938 !this.getConfigurationKey(StandardParametersKey.LocalAuthListEnabled) &&
939 this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles).value.includes(
940 SupportedFeatureProfiles.Local_Auth_List_Management
941 )
942 ) {
943 this.addConfigurationKey(StandardParametersKey.LocalAuthListEnabled, 'false');
944 }
945 if (!this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
946 this.addConfigurationKey(
947 StandardParametersKey.ConnectionTimeOut,
948 Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
949 );
950 }
951 this.saveConfiguration();
952 }
953
954 private getConfigurationFromTemplate(): ChargingStationConfiguration {
955 return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration);
956 }
957
958 private getConfigurationFromFile(): ChargingStationConfiguration | null {
959 let configuration: ChargingStationConfiguration = null;
960 if (this.configurationFile && fs.existsSync(this.configurationFile)) {
961 try {
962 const fileDescriptor = fs.openSync(this.configurationFile, 'r');
963 configuration = JSON.parse(
964 fs.readFileSync(fileDescriptor, 'utf8')
965 ) as ChargingStationConfiguration;
966 fs.closeSync(fileDescriptor);
967 } catch (error) {
968 FileUtils.handleFileException(
969 this.logPrefix(),
970 'Configuration',
971 this.configurationFile,
972 error as NodeJS.ErrnoException
973 );
974 }
975 }
976 return configuration;
977 }
978
979 private saveConfiguration(): void {
980 if (this.configurationFile) {
981 try {
982 if (!fs.existsSync(path.dirname(this.configurationFile))) {
983 fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
984 }
985 const fileDescriptor = fs.openSync(this.configurationFile, 'w');
986 fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2));
987 fs.closeSync(fileDescriptor);
988 } catch (error) {
989 FileUtils.handleFileException(
990 this.logPrefix(),
991 'Configuration',
992 this.configurationFile,
993 error as NodeJS.ErrnoException
994 );
995 }
996 } else {
997 logger.error(
998 `${this.logPrefix()} Trying to save charging station configuration to undefined file`
999 );
1000 }
1001 }
1002
1003 private getConfiguration(): ChargingStationConfiguration {
1004 let configuration: ChargingStationConfiguration = this.getConfigurationFromFile();
1005 if (!configuration) {
1006 configuration = this.getConfigurationFromTemplate();
1007 }
1008 return configuration;
1009 }
1010
1011 private async onOpen(): Promise<void> {
1012 logger.info(
1013 `${this.logPrefix()} Connected to OCPP server through ${this.wsConnectionUrl.toString()}`
1014 );
1015 if (!this.isInAcceptedState()) {
1016 // Send BootNotification
1017 let registrationRetryCount = 0;
1018 do {
1019 this.bootNotificationResponse = (await this.ocppRequestService.sendMessageHandler(
1020 RequestCommand.BOOT_NOTIFICATION,
1021 {
1022 chargePointModel: this.bootNotificationRequest.chargePointModel,
1023 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1024 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1025 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1026 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1027 iccid: this.bootNotificationRequest.iccid,
1028 imsi: this.bootNotificationRequest.imsi,
1029 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1030 meterType: this.bootNotificationRequest.meterType,
1031 },
1032 { skipBufferingOnError: true }
1033 )) as BootNotificationResponse;
1034 if (!this.isInAcceptedState()) {
1035 this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
1036 await Utils.sleep(
1037 this.bootNotificationResponse?.interval
1038 ? this.bootNotificationResponse.interval * 1000
1039 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL
1040 );
1041 }
1042 } while (
1043 !this.isInAcceptedState() &&
1044 (registrationRetryCount <= this.getRegistrationMaxRetries() ||
1045 this.getRegistrationMaxRetries() === -1)
1046 );
1047 }
1048 if (this.isInAcceptedState()) {
1049 await this.startMessageSequence();
1050 this.stopped && (this.stopped = false);
1051 if (this.wsConnectionRestarted && this.isWebSocketConnectionOpened()) {
1052 this.flushMessageBuffer();
1053 }
1054 } else {
1055 logger.error(
1056 `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`
1057 );
1058 }
1059 this.autoReconnectRetryCount = 0;
1060 this.wsConnectionRestarted = false;
1061 }
1062
1063 private async onClose(code: number, reason: string): Promise<void> {
1064 switch (code) {
1065 // Normal close
1066 case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
1067 case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS:
1068 logger.info(
1069 `${this.logPrefix()} WebSocket normally closed with status '${Utils.getWebSocketCloseEventStatusString(
1070 code
1071 )}' and reason '${reason}'`
1072 );
1073 this.autoReconnectRetryCount = 0;
1074 break;
1075 // Abnormal close
1076 default:
1077 logger.error(
1078 `${this.logPrefix()} WebSocket abnormally closed with status '${Utils.getWebSocketCloseEventStatusString(
1079 code
1080 )}' and reason '${reason}'`
1081 );
1082 await this.reconnect(code);
1083 break;
1084 }
1085 }
1086
1087 private async onMessage(data: Data): Promise<void> {
1088 let [messageType, messageId, commandName, commandPayload, errorDetails]: IncomingRequest = [
1089 0,
1090 '',
1091 '' as IncomingRequestCommand,
1092 {},
1093 {},
1094 ];
1095 let responseCallback: (
1096 payload: JsonType | string,
1097 requestPayload: JsonType | OCPPError
1098 ) => void;
1099 let rejectCallback: (error: OCPPError, requestStatistic?: boolean) => void;
1100 let requestCommandName: RequestCommand | IncomingRequestCommand;
1101 let requestPayload: JsonType | OCPPError;
1102 let cachedRequest: CachedRequest;
1103 let errMsg: string;
1104 try {
1105 const request = JSON.parse(data.toString()) as IncomingRequest;
1106 if (Utils.isIterable(request)) {
1107 // Parse the message
1108 [messageType, messageId, commandName, commandPayload, errorDetails] = request;
1109 } else {
1110 throw new OCPPError(
1111 ErrorType.PROTOCOL_ERROR,
1112 'Incoming request is not iterable',
1113 commandName
1114 );
1115 }
1116 // Check the Type of message
1117 switch (messageType) {
1118 // Incoming Message
1119 case MessageType.CALL_MESSAGE:
1120 if (this.getEnableStatistics()) {
1121 this.performanceStatistics.addRequestStatistic(commandName, messageType);
1122 }
1123 // Process the call
1124 await this.ocppIncomingRequestService.handleRequest(
1125 messageId,
1126 commandName,
1127 commandPayload
1128 );
1129 break;
1130 // Outcome Message
1131 case MessageType.CALL_RESULT_MESSAGE:
1132 // Respond
1133 cachedRequest = this.requests.get(messageId);
1134 if (Utils.isIterable(cachedRequest)) {
1135 [responseCallback, , , requestPayload] = cachedRequest;
1136 } else {
1137 throw new OCPPError(
1138 ErrorType.PROTOCOL_ERROR,
1139 `Cached request for message id ${messageId} response is not iterable`,
1140 commandName
1141 );
1142 }
1143 if (!responseCallback) {
1144 // Error
1145 throw new OCPPError(
1146 ErrorType.INTERNAL_ERROR,
1147 `Response for unknown message id ${messageId}`,
1148 commandName
1149 );
1150 }
1151 responseCallback(commandName, requestPayload);
1152 break;
1153 // Error Message
1154 case MessageType.CALL_ERROR_MESSAGE:
1155 cachedRequest = this.requests.get(messageId);
1156 if (Utils.isIterable(cachedRequest)) {
1157 [, rejectCallback, requestCommandName] = cachedRequest;
1158 } else {
1159 throw new OCPPError(
1160 ErrorType.PROTOCOL_ERROR,
1161 `Cached request for message id ${messageId} error response is not iterable`
1162 );
1163 }
1164 if (!rejectCallback) {
1165 // Error
1166 throw new OCPPError(
1167 ErrorType.INTERNAL_ERROR,
1168 `Error response for unknown message id ${messageId}`,
1169 requestCommandName
1170 );
1171 }
1172 rejectCallback(
1173 new OCPPError(commandName, commandPayload.toString(), requestCommandName, errorDetails)
1174 );
1175 break;
1176 // Error
1177 default:
1178 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1179 errMsg = `${this.logPrefix()} Wrong message type ${messageType}`;
1180 logger.error(errMsg);
1181 throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg);
1182 }
1183 } catch (error) {
1184 // Log
1185 logger.error(
1186 '%s Incoming OCPP message %j matching cached request %j processing error %j',
1187 this.logPrefix(),
1188 data.toString(),
1189 this.requests.get(messageId),
1190 error
1191 );
1192 // Send error
1193 messageType === MessageType.CALL_MESSAGE &&
1194 (await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName));
1195 }
1196 }
1197
1198 private onPing(): void {
1199 logger.debug(this.logPrefix() + ' Received a WS ping (rfc6455) from the server');
1200 }
1201
1202 private onPong(): void {
1203 logger.debug(this.logPrefix() + ' Received a WS pong (rfc6455) from the server');
1204 }
1205
1206 private onError(error: WSError): void {
1207 logger.error(this.logPrefix() + ' WebSocket error: %j', error);
1208 }
1209
1210 private getAuthorizationFile(): string | undefined {
1211 return (
1212 this.stationInfo.authorizationFile &&
1213 path.join(
1214 path.resolve(__dirname, '../'),
1215 'assets',
1216 path.basename(this.stationInfo.authorizationFile)
1217 )
1218 );
1219 }
1220
1221 private getAuthorizedTags(): string[] {
1222 let authorizedTags: string[] = [];
1223 const authorizationFile = this.getAuthorizationFile();
1224 if (authorizationFile) {
1225 try {
1226 // Load authorization file
1227 const fileDescriptor = fs.openSync(authorizationFile, 'r');
1228 authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
1229 fs.closeSync(fileDescriptor);
1230 } catch (error) {
1231 FileUtils.handleFileException(
1232 this.logPrefix(),
1233 'Authorization',
1234 authorizationFile,
1235 error as NodeJS.ErrnoException
1236 );
1237 }
1238 } else {
1239 logger.info(
1240 this.logPrefix() +
1241 ' No authorization file given in template file ' +
1242 this.stationTemplateFile
1243 );
1244 }
1245 return authorizedTags;
1246 }
1247
1248 private getUseConnectorId0(): boolean | undefined {
1249 return !Utils.isUndefined(this.stationInfo.useConnectorId0)
1250 ? this.stationInfo.useConnectorId0
1251 : true;
1252 }
1253
1254 private getNumberOfRunningTransactions(): number {
1255 let trxCount = 0;
1256 for (const connectorId of this.connectors.keys()) {
1257 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1258 trxCount++;
1259 }
1260 }
1261 return trxCount;
1262 }
1263
1264 // 0 for disabling
1265 private getConnectionTimeout(): number | undefined {
1266 if (this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut)) {
1267 return (
1268 parseInt(this.getConfigurationKey(StandardParametersKey.ConnectionTimeOut).value) ??
1269 Constants.DEFAULT_CONNECTION_TIMEOUT
1270 );
1271 }
1272 return Constants.DEFAULT_CONNECTION_TIMEOUT;
1273 }
1274
1275 // -1 for unlimited, 0 for disabling
1276 private getAutoReconnectMaxRetries(): number | undefined {
1277 if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
1278 return this.stationInfo.autoReconnectMaxRetries;
1279 }
1280 if (!Utils.isUndefined(Configuration.getAutoReconnectMaxRetries())) {
1281 return Configuration.getAutoReconnectMaxRetries();
1282 }
1283 return -1;
1284 }
1285
1286 // 0 for disabling
1287 private getRegistrationMaxRetries(): number | undefined {
1288 if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
1289 return this.stationInfo.registrationMaxRetries;
1290 }
1291 return -1;
1292 }
1293
1294 private getPowerDivider(): number {
1295 let powerDivider = this.getNumberOfConnectors();
1296 if (this.stationInfo.powerSharedByConnectors) {
1297 powerDivider = this.getNumberOfRunningTransactions();
1298 }
1299 return powerDivider;
1300 }
1301
1302 private getTemplateMaxNumberOfConnectors(): number {
1303 return Object.keys(this.stationInfo.Connectors).length;
1304 }
1305
1306 private getMaxNumberOfConnectors(): number {
1307 let maxConnectors: number;
1308 if (!Utils.isEmptyArray(this.stationInfo.numberOfConnectors)) {
1309 const numberOfConnectors = this.stationInfo.numberOfConnectors as number[];
1310 // Distribute evenly the number of connectors
1311 maxConnectors = numberOfConnectors[(this.index - 1) % numberOfConnectors.length];
1312 } else if (!Utils.isUndefined(this.stationInfo.numberOfConnectors)) {
1313 maxConnectors = this.stationInfo.numberOfConnectors as number;
1314 } else {
1315 maxConnectors = this.stationInfo.Connectors[0]
1316 ? this.getTemplateMaxNumberOfConnectors() - 1
1317 : this.getTemplateMaxNumberOfConnectors();
1318 }
1319 return maxConnectors;
1320 }
1321
1322 private async startMessageSequence(): Promise<void> {
1323 if (this.stationInfo.autoRegister) {
1324 await this.ocppRequestService.sendMessageHandler(
1325 RequestCommand.BOOT_NOTIFICATION,
1326 {
1327 chargePointModel: this.bootNotificationRequest.chargePointModel,
1328 chargePointVendor: this.bootNotificationRequest.chargePointVendor,
1329 chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
1330 firmwareVersion: this.bootNotificationRequest.firmwareVersion,
1331 chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
1332 iccid: this.bootNotificationRequest.iccid,
1333 imsi: this.bootNotificationRequest.imsi,
1334 meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
1335 meterType: this.bootNotificationRequest.meterType,
1336 },
1337 { skipBufferingOnError: true }
1338 );
1339 }
1340 // Start WebSocket ping
1341 this.startWebSocketPing();
1342 // Start heartbeat
1343 this.startHeartbeat();
1344 // Initialize connectors status
1345 for (const connectorId of this.connectors.keys()) {
1346 if (connectorId === 0) {
1347 continue;
1348 } else if (
1349 !this.stopped &&
1350 !this.getConnectorStatus(connectorId)?.status &&
1351 this.getConnectorStatus(connectorId)?.bootStatus
1352 ) {
1353 // Send status in template at startup
1354 await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
1355 connectorId,
1356 status: this.getConnectorStatus(connectorId).bootStatus,
1357 errorCode: ChargePointErrorCode.NO_ERROR,
1358 });
1359 this.getConnectorStatus(connectorId).status =
1360 this.getConnectorStatus(connectorId).bootStatus;
1361 } else if (
1362 this.stopped &&
1363 this.getConnectorStatus(connectorId)?.status &&
1364 this.getConnectorStatus(connectorId)?.bootStatus
1365 ) {
1366 // Send status in template after reset
1367 await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
1368 connectorId,
1369 status: this.getConnectorStatus(connectorId).bootStatus,
1370 errorCode: ChargePointErrorCode.NO_ERROR,
1371 });
1372 this.getConnectorStatus(connectorId).status =
1373 this.getConnectorStatus(connectorId).bootStatus;
1374 } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
1375 // Send previous status at template reload
1376 await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
1377 connectorId,
1378 status: this.getConnectorStatus(connectorId).status,
1379 errorCode: ChargePointErrorCode.NO_ERROR,
1380 });
1381 } else {
1382 // Send default status
1383 await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
1384 connectorId,
1385 status: ChargePointStatus.AVAILABLE,
1386 errorCode: ChargePointErrorCode.NO_ERROR,
1387 });
1388 this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
1389 }
1390 }
1391 // Start the ATG
1392 this.startAutomaticTransactionGenerator();
1393 }
1394
1395 private startAutomaticTransactionGenerator() {
1396 if (this.stationInfo.AutomaticTransactionGenerator.enable) {
1397 if (!this.automaticTransactionGenerator) {
1398 this.automaticTransactionGenerator = AutomaticTransactionGenerator.getInstance(this);
1399 }
1400 if (!this.automaticTransactionGenerator.started) {
1401 this.automaticTransactionGenerator.start();
1402 }
1403 }
1404 }
1405
1406 private async stopMessageSequence(
1407 reason: StopTransactionReason = StopTransactionReason.NONE
1408 ): Promise<void> {
1409 // Stop WebSocket ping
1410 this.stopWebSocketPing();
1411 // Stop heartbeat
1412 this.stopHeartbeat();
1413 // Stop the ATG
1414 if (
1415 this.stationInfo.AutomaticTransactionGenerator.enable &&
1416 this.automaticTransactionGenerator?.started
1417 ) {
1418 this.automaticTransactionGenerator.stop();
1419 } else {
1420 for (const connectorId of this.connectors.keys()) {
1421 if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted) {
1422 const transactionId = this.getConnectorStatus(connectorId).transactionId;
1423 if (
1424 this.getBeginEndMeterValues() &&
1425 this.getOcppStrictCompliance() &&
1426 !this.getOutOfOrderEndMeterValues()
1427 ) {
1428 // FIXME: Implement OCPP version agnostic helpers
1429 const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
1430 this,
1431 connectorId,
1432 this.getEnergyActiveImportRegisterByTransactionId(transactionId)
1433 );
1434 await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, {
1435 connectorId,
1436 transactionId,
1437 meterValue: transactionEndMeterValue,
1438 });
1439 }
1440 await this.ocppRequestService.sendMessageHandler(RequestCommand.STOP_TRANSACTION, {
1441 transactionId,
1442 meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
1443 idTag: this.getTransactionIdTag(transactionId),
1444 reason,
1445 });
1446 }
1447 }
1448 }
1449 }
1450
1451 private startWebSocketPing(): void {
1452 const webSocketPingInterval: number = this.getConfigurationKey(
1453 StandardParametersKey.WebSocketPingInterval
1454 )
1455 ? Utils.convertToInt(
1456 this.getConfigurationKey(StandardParametersKey.WebSocketPingInterval).value
1457 )
1458 : 0;
1459 if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
1460 this.webSocketPingSetInterval = setInterval(() => {
1461 if (this.isWebSocketConnectionOpened()) {
1462 this.wsConnection.ping((): void => {
1463 /* This is intentional */
1464 });
1465 }
1466 }, webSocketPingInterval * 1000);
1467 logger.info(
1468 this.logPrefix() +
1469 ' WebSocket ping started every ' +
1470 Utils.formatDurationSeconds(webSocketPingInterval)
1471 );
1472 } else if (this.webSocketPingSetInterval) {
1473 logger.info(
1474 this.logPrefix() +
1475 ' WebSocket ping every ' +
1476 Utils.formatDurationSeconds(webSocketPingInterval) +
1477 ' already started'
1478 );
1479 } else {
1480 logger.error(
1481 `${this.logPrefix()} WebSocket ping interval set to ${
1482 webSocketPingInterval
1483 ? Utils.formatDurationSeconds(webSocketPingInterval)
1484 : webSocketPingInterval
1485 }, not starting the WebSocket ping`
1486 );
1487 }
1488 }
1489
1490 private stopWebSocketPing(): void {
1491 if (this.webSocketPingSetInterval) {
1492 clearInterval(this.webSocketPingSetInterval);
1493 }
1494 }
1495
1496 private warnDeprecatedTemplateKey(
1497 template: ChargingStationTemplate,
1498 key: string,
1499 chargingStationId: string,
1500 logMsgToAppend = ''
1501 ): void {
1502 if (!Utils.isUndefined(template[key])) {
1503 const logPrefixStr = ` ${chargingStationId} |`;
1504 logger.warn(
1505 `${Utils.logPrefix(logPrefixStr)} Deprecated template key '${key}' usage in file '${
1506 this.stationTemplateFile
1507 }'${logMsgToAppend && '. ' + logMsgToAppend}`
1508 );
1509 }
1510 }
1511
1512 private convertDeprecatedTemplateKey(
1513 template: ChargingStationTemplate,
1514 deprecatedKey: string,
1515 key: string
1516 ): void {
1517 if (!Utils.isUndefined(template[deprecatedKey])) {
1518 template[key] = template[deprecatedKey] as unknown;
1519 delete template[deprecatedKey];
1520 }
1521 }
1522
1523 private getConfiguredSupervisionUrl(): URL {
1524 const supervisionUrls = Utils.cloneObject<string | string[]>(
1525 this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls()
1526 );
1527 if (!Utils.isEmptyArray(supervisionUrls)) {
1528 let urlIndex = 0;
1529 switch (Configuration.getSupervisionUrlDistribution()) {
1530 case SupervisionUrlDistribution.ROUND_ROBIN:
1531 urlIndex = (this.index - 1) % supervisionUrls.length;
1532 break;
1533 case SupervisionUrlDistribution.RANDOM:
1534 // Get a random url
1535 urlIndex = Math.floor(Utils.secureRandom() * supervisionUrls.length);
1536 break;
1537 case SupervisionUrlDistribution.SEQUENTIAL:
1538 if (this.index <= supervisionUrls.length) {
1539 urlIndex = this.index - 1;
1540 } else {
1541 logger.warn(
1542 `${this.logPrefix()} No more configured supervision urls available, using the first one`
1543 );
1544 }
1545 break;
1546 default:
1547 logger.error(
1548 `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${
1549 SupervisionUrlDistribution.ROUND_ROBIN
1550 }`
1551 );
1552 urlIndex = (this.index - 1) % supervisionUrls.length;
1553 break;
1554 }
1555 return new URL(supervisionUrls[urlIndex]);
1556 }
1557 return new URL(supervisionUrls as string);
1558 }
1559
1560 private getHeartbeatInterval(): number | undefined {
1561 const HeartbeatInterval = this.getConfigurationKey(StandardParametersKey.HeartbeatInterval);
1562 if (HeartbeatInterval) {
1563 return Utils.convertToInt(HeartbeatInterval.value) * 1000;
1564 }
1565 const HeartBeatInterval = this.getConfigurationKey(StandardParametersKey.HeartBeatInterval);
1566 if (HeartBeatInterval) {
1567 return Utils.convertToInt(HeartBeatInterval.value) * 1000;
1568 }
1569 !this.stationInfo.autoRegister &&
1570 logger.warn(
1571 `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
1572 Constants.DEFAULT_HEARTBEAT_INTERVAL
1573 }`
1574 );
1575 return Constants.DEFAULT_HEARTBEAT_INTERVAL;
1576 }
1577
1578 private stopHeartbeat(): void {
1579 if (this.heartbeatSetInterval) {
1580 clearInterval(this.heartbeatSetInterval);
1581 }
1582 }
1583
1584 private openWSConnection(
1585 options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions,
1586 forceCloseOpened = false
1587 ): void {
1588 options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
1589 if (
1590 !Utils.isNullOrUndefined(this.stationInfo.supervisionUser) &&
1591 !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)
1592 ) {
1593 options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
1594 }
1595 if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
1596 this.wsConnection.close();
1597 }
1598 let protocol: string;
1599 switch (this.getOcppVersion()) {
1600 case OCPPVersion.VERSION_16:
1601 protocol = 'ocpp' + OCPPVersion.VERSION_16;
1602 break;
1603 default:
1604 this.handleUnsupportedVersion(this.getOcppVersion());
1605 break;
1606 }
1607 this.wsConnection = new WebSocket(this.wsConnectionUrl, protocol, options);
1608 logger.info(
1609 this.logPrefix() + ' Open OCPP connection to URL ' + this.wsConnectionUrl.toString()
1610 );
1611 }
1612
1613 private stopMeterValues(connectorId: number) {
1614 if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
1615 clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
1616 }
1617 }
1618
1619 private startAuthorizationFileMonitoring(): void {
1620 const authorizationFile = this.getAuthorizationFile();
1621 if (authorizationFile) {
1622 try {
1623 fs.watch(authorizationFile, (event, filename) => {
1624 if (filename && event === 'change') {
1625 try {
1626 logger.debug(
1627 this.logPrefix() +
1628 ' Authorization file ' +
1629 authorizationFile +
1630 ' have changed, reload'
1631 );
1632 // Initialize authorizedTags
1633 this.authorizedTags = this.getAuthorizedTags();
1634 } catch (error) {
1635 logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
1636 }
1637 }
1638 });
1639 } catch (error) {
1640 FileUtils.handleFileException(
1641 this.logPrefix(),
1642 'Authorization',
1643 authorizationFile,
1644 error as NodeJS.ErrnoException
1645 );
1646 }
1647 } else {
1648 logger.info(
1649 this.logPrefix() +
1650 ' No authorization file given in template file ' +
1651 this.stationTemplateFile +
1652 '. Not monitoring changes'
1653 );
1654 }
1655 }
1656
1657 private startStationTemplateFileMonitoring(): void {
1658 try {
1659 fs.watch(this.stationTemplateFile, (event, filename): void => {
1660 if (filename && event === 'change') {
1661 try {
1662 logger.debug(
1663 this.logPrefix() +
1664 ' Template file ' +
1665 this.stationTemplateFile +
1666 ' have changed, reload'
1667 );
1668 // Initialize
1669 this.initialize();
1670 // Restart the ATG
1671 if (
1672 !this.stationInfo.AutomaticTransactionGenerator.enable &&
1673 this.automaticTransactionGenerator
1674 ) {
1675 this.automaticTransactionGenerator.stop();
1676 }
1677 this.startAutomaticTransactionGenerator();
1678 if (this.getEnableStatistics()) {
1679 this.performanceStatistics.restart();
1680 } else {
1681 this.performanceStatistics.stop();
1682 }
1683 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
1684 } catch (error) {
1685 logger.error(
1686 this.logPrefix() + ' Charging station template file monitoring error: %j',
1687 error
1688 );
1689 }
1690 }
1691 });
1692 } catch (error) {
1693 FileUtils.handleFileException(
1694 this.logPrefix(),
1695 'Template',
1696 this.stationTemplateFile,
1697 error as NodeJS.ErrnoException
1698 );
1699 }
1700 }
1701
1702 private getReconnectExponentialDelay(): boolean | undefined {
1703 return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
1704 ? this.stationInfo.reconnectExponentialDelay
1705 : false;
1706 }
1707
1708 private async reconnect(code: number): Promise<void> {
1709 // Stop WebSocket ping
1710 this.stopWebSocketPing();
1711 // Stop heartbeat
1712 this.stopHeartbeat();
1713 // Stop the ATG if needed
1714 if (
1715 this.stationInfo.AutomaticTransactionGenerator.enable &&
1716 this.stationInfo.AutomaticTransactionGenerator.stopOnConnectionFailure &&
1717 this.automaticTransactionGenerator?.started
1718 ) {
1719 this.automaticTransactionGenerator.stop();
1720 }
1721 if (
1722 this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() ||
1723 this.getAutoReconnectMaxRetries() === -1
1724 ) {
1725 this.autoReconnectRetryCount++;
1726 const reconnectDelay = this.getReconnectExponentialDelay()
1727 ? Utils.exponentialDelay(this.autoReconnectRetryCount)
1728 : this.getConnectionTimeout() * 1000;
1729 const reconnectTimeout = reconnectDelay - 100 > 0 && reconnectDelay;
1730 logger.error(
1731 `${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(
1732 reconnectDelay,
1733 2
1734 )}ms, timeout ${reconnectTimeout}ms`
1735 );
1736 await Utils.sleep(reconnectDelay);
1737 logger.error(
1738 this.logPrefix() +
1739 ' WebSocket: reconnecting try #' +
1740 this.autoReconnectRetryCount.toString()
1741 );
1742 this.openWSConnection(
1743 { ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout },
1744 true
1745 );
1746 this.wsConnectionRestarted = true;
1747 } else if (this.getAutoReconnectMaxRetries() !== -1) {
1748 logger.error(
1749 `${this.logPrefix()} WebSocket reconnect failure: max retries reached (${
1750 this.autoReconnectRetryCount
1751 }) or retry disabled (${this.getAutoReconnectMaxRetries()})`
1752 );
1753 }
1754 }
1755
1756 private initializeConnectorStatus(connectorId: number): void {
1757 this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
1758 this.getConnectorStatus(connectorId).idTagAuthorized = false;
1759 this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
1760 this.getConnectorStatus(connectorId).transactionStarted = false;
1761 this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
1762 this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;
1763 }
1764 }