Fixlet to configuration tunable deprecation
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
index 1be6e335d63c196f2d42d7a501db04de62770bb5..dc679b84603838cc14366780a4699ea73ffc94af 100644 (file)
@@ -8,7 +8,13 @@ import {
   IncomingRequestCommand,
   RequestCommand,
 } from '../types/ocpp/Requests';
-import { BootNotificationResponse, RegistrationStatus } from '../types/ocpp/Responses';
+import {
+  BootNotificationResponse,
+  HeartbeatResponse,
+  MeterValuesResponse,
+  RegistrationStatus,
+  StatusNotificationResponse,
+} from '../types/ocpp/Responses';
 import ChargingStationConfiguration, {
   ConfigurationKey,
 } from '../types/ChargingStationConfiguration';
@@ -24,6 +30,7 @@ import {
   VendorDefaultParametersKey,
 } from '../types/ocpp/Configuration';
 import { MeterValue, MeterValueMeasurand, MeterValuePhase } from '../types/ocpp/MeterValues';
+import { StopTransactionReason, StopTransactionResponse } from '../types/ocpp/Transaction';
 import { WSError, WebSocketCloseEventStatusCode } from '../types/WebSocket';
 import WebSocket, { ClientOptions, Data, OPEN, RawData } from 'ws';
 
@@ -38,6 +45,7 @@ import Configuration from '../utils/Configuration';
 import { ConnectorStatus } from '../types/ConnectorStatus';
 import Constants from '../utils/Constants';
 import { ErrorType } from '../types/ocpp/ErrorType';
+import { FileType } from '../types/FileType';
 import FileUtils from '../utils/FileUtils';
 import { JsonType } from '../types/JsonType';
 import { MessageType } from '../types/ocpp/MessageType';
@@ -51,7 +59,6 @@ import OCPPRequestService from './ocpp/OCPPRequestService';
 import { OCPPVersion } from '../types/ocpp/OCPPVersion';
 import PerformanceStatistics from '../performance/PerformanceStatistics';
 import { SampledValueTemplate } from '../types/MeasurandPerPhaseSampledValueTemplates';
-import { StopTransactionReason } from '../types/ocpp/Transaction';
 import { SupervisionUrlDistribution } from '../types/ConfigurationData';
 import { URL } from 'url';
 import Utils from '../utils/Utils';
@@ -62,7 +69,7 @@ import { parentPort } from 'worker_threads';
 import path from 'path';
 
 export default class ChargingStation {
-  public readonly id: string;
+  public hashId!: string;
   public readonly stationTemplateFile: string;
   public authorizedTags: string[];
   public stationInfo!: ChargingStationInfo;
@@ -73,9 +80,10 @@ export default class ChargingStation {
   public performanceStatistics!: PerformanceStatistics;
   public heartbeatSetInterval!: NodeJS.Timeout;
   public ocppRequestService!: OCPPRequestService;
+  public bootNotificationResponse!: BootNotificationResponse | null;
   private readonly index: number;
+  private configurationFile!: string;
   private bootNotificationRequest!: BootNotificationRequest;
-  private bootNotificationResponse!: BootNotificationResponse | null;
   private connectorsConfigurationHash!: string;
   private ocppIncomingRequestService!: OCPPIncomingRequestService;
   private readonly messageBuffer: Set<string>;
@@ -87,7 +95,6 @@ export default class ChargingStation {
   private webSocketPingSetInterval!: NodeJS.Timeout;
 
   constructor(index: number, stationTemplateFile: string) {
-    this.id = Utils.generateUUID();
     this.index = index;
     this.stationTemplateFile = stationTemplateFile;
     this.stopped = false;
@@ -100,12 +107,10 @@ export default class ChargingStation {
     this.authorizedTags = this.getAuthorizedTags();
   }
 
-  get wsConnectionUrl(): URL {
+  private get wsConnectionUrl(): URL {
     return this.getSupervisionUrlOcppConfiguration()
       ? new URL(
-          this.getConfigurationKey(
-            this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
-          ).value +
+          this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value +
             '/' +
             this.stationInfo.chargingStationId
         )
@@ -255,29 +260,33 @@ export default class ChargingStation {
     return this.stationInfo.phaseLineToLineVoltageMeterValues ?? false;
   }
 
-  public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
-    if (this.getMeteringPerTransaction()) {
-      for (const connectorId of this.connectors.keys()) {
-        if (
-          connectorId > 0 &&
-          this.getConnectorStatus(connectorId).transactionId === transactionId
-        ) {
-          return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
-        }
-      }
-    }
+  public getConnectorIdByTransactionId(transactionId: number): number | undefined {
     for (const connectorId of this.connectors.keys()) {
-      if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) {
-        return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
+      if (
+        connectorId > 0 &&
+        this.getConnectorStatus(connectorId)?.transactionId === transactionId
+      ) {
+        return connectorId;
       }
     }
   }
 
+  public getEnergyActiveImportRegisterByTransactionId(transactionId: number): number | undefined {
+    const transactionConnectorStatus = this.getConnectorStatus(
+      this.getConnectorIdByTransactionId(transactionId)
+    );
+    if (this.getMeteringPerTransaction()) {
+      return transactionConnectorStatus?.transactionEnergyActiveImportRegisterValue;
+    }
+    return transactionConnectorStatus?.energyActiveImportRegisterValue;
+  }
+
   public getEnergyActiveImportRegisterByConnectorId(connectorId: number): number | undefined {
+    const connectorStatus = this.getConnectorStatus(connectorId);
     if (this.getMeteringPerTransaction()) {
-      return this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue;
+      return connectorStatus?.transactionEnergyActiveImportRegisterValue;
     }
-    return this.getConnectorStatus(connectorId).energyActiveImportRegisterValue;
+    return connectorStatus?.energyActiveImportRegisterValue;
   }
 
   public getAuthorizeRemoteTxRequests(): boolean {
@@ -392,7 +401,9 @@ export default class ChargingStation {
     ) {
       // eslint-disable-next-line @typescript-eslint/no-misused-promises
       this.heartbeatSetInterval = setInterval(async (): Promise<void> => {
-        await this.ocppRequestService.sendMessageHandler(RequestCommand.HEARTBEAT);
+        await this.ocppRequestService.sendMessageHandler<HeartbeatResponse>(
+          RequestCommand.HEARTBEAT
+        );
       }, this.getHeartbeatInterval());
       logger.info(
         this.logPrefix() +
@@ -462,11 +473,14 @@ export default class ChargingStation {
             this.getConnectorStatus(connectorId).transactionId,
             interval
           );
-          await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, {
-            connectorId,
-            transactionId: this.getConnectorStatus(connectorId).transactionId,
-            meterValue: [meterValue],
-          });
+          await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
+            RequestCommand.METER_VALUES,
+            {
+              connectorId,
+              transactionId: this.getConnectorStatus(connectorId).transactionId,
+              meterValue: [meterValue],
+            }
+          );
         },
         interval
       );
@@ -487,9 +501,51 @@ export default class ChargingStation {
     }
     this.openWSConnection();
     // Monitor authorization file
-    this.startAuthorizationFileMonitoring();
-    // Monitor station template file
-    this.startStationTemplateFileMonitoring();
+    FileUtils.watchJsonFile<string[]>(
+      this.logPrefix(),
+      FileType.Authorization,
+      this.getAuthorizationFile(),
+      this.authorizedTags
+    );
+    // Monitor charging station template file
+    FileUtils.watchJsonFile(
+      this.logPrefix(),
+      FileType.ChargingStationTemplate,
+      this.stationTemplateFile,
+      null,
+      (event, filename): void => {
+        if (filename && event === 'change') {
+          try {
+            logger.debug(
+              `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
+                this.stationTemplateFile
+              } file have changed, reload`
+            );
+            // Initialize
+            this.initialize();
+            // Restart the ATG
+            if (
+              !this.stationInfo.AutomaticTransactionGenerator.enable &&
+              this.automaticTransactionGenerator
+            ) {
+              this.automaticTransactionGenerator.stop();
+            }
+            this.startAutomaticTransactionGenerator();
+            if (this.getEnableStatistics()) {
+              this.performanceStatistics.restart();
+            } else {
+              this.performanceStatistics.stop();
+            }
+            // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
+          } catch (error) {
+            logger.error(
+              `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error: %j`,
+              error
+            );
+          }
+        }
+      }
+    );
     // Handle WebSocket message
     this.wsConnection.on(
       'message',
@@ -522,11 +578,14 @@ export default class ChargingStation {
     await this.stopMessageSequence(reason);
     for (const connectorId of this.connectors.keys()) {
       if (connectorId > 0) {
-        await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
-          connectorId,
-          status: ChargePointStatus.UNAVAILABLE,
-          errorCode: ChargePointErrorCode.NO_ERROR,
-        });
+        await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+          RequestCommand.STATUS_NOTIFICATION,
+          {
+            connectorId,
+            status: ChargePointStatus.UNAVAILABLE,
+            errorCode: ChargePointErrorCode.NO_ERROR,
+          }
+        );
         this.getConnectorStatus(connectorId).status = ChargePointStatus.UNAVAILABLE;
       }
     }
@@ -563,12 +622,24 @@ export default class ChargingStation {
       readonly: false,
       visible: true,
       reboot: false,
-    }
+    },
+    params: { overwrite?: boolean; save?: boolean } = { overwrite: false, save: false }
   ): void {
-    const keyFound = this.getConfigurationKey(key);
-    const readonly = options.readonly;
-    const visible = options.visible;
-    const reboot = options.reboot;
+    if (!options || Utils.isEmptyObject(options)) {
+      options = {
+        readonly: false,
+        visible: true,
+        reboot: false,
+      };
+    }
+    const readonly = options.readonly ?? false;
+    const visible = options.visible ?? true;
+    const reboot = options.reboot ?? false;
+    let keyFound = this.getConfigurationKey(key);
+    if (keyFound && params?.overwrite) {
+      this.deleteConfigurationKey(keyFound.key, { save: false });
+      keyFound = undefined;
+    }
     if (!keyFound) {
       this.configuration.configurationKey.push({
         key,
@@ -577,6 +648,7 @@ export default class ChargingStation {
         visible,
         reboot,
       });
+      params?.save && this.saveConfiguration();
     } else {
       logger.error(
         `${this.logPrefix()} Trying to add an already existing configuration key: %j`,
@@ -585,11 +657,16 @@ export default class ChargingStation {
     }
   }
 
-  public setConfigurationKeyValue(key: string | StandardParametersKey, value: string): void {
-    const keyFound = this.getConfigurationKey(key);
+  public setConfigurationKeyValue(
+    key: string | StandardParametersKey,
+    value: string,
+    caseInsensitive = false
+  ): void {
+    const keyFound = this.getConfigurationKey(key, caseInsensitive);
     if (keyFound) {
       const keyIndex = this.configuration.configurationKey.indexOf(keyFound);
       this.configuration.configurationKey[keyIndex].value = value;
+      this.saveConfiguration();
     } else {
       logger.error(
         `${this.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
@@ -598,6 +675,21 @@ export default class ChargingStation {
     }
   }
 
+  public deleteConfigurationKey(
+    key: string | StandardParametersKey,
+    params: { save?: boolean; caseInsensitive?: boolean } = { save: true, caseInsensitive: false }
+  ): ConfigurationKey[] {
+    const keyFound = this.getConfigurationKey(key, params?.caseInsensitive);
+    if (keyFound) {
+      const deletedConfigurationKey = this.configuration.configurationKey.splice(
+        this.configuration.configurationKey.indexOf(keyFound),
+        1
+      );
+      params?.save && this.saveConfiguration();
+      return deletedConfigurationKey;
+    }
+  }
+
   public setChargingProfile(connectorId: number, cp: ChargingProfile): void {
     let cpReplaced = false;
     if (!Utils.isEmptyArray(this.getConnectorStatus(connectorId).chargingProfiles)) {
@@ -649,6 +741,10 @@ export default class ChargingStation {
     return this.stationInfo.supervisionUrlOcppConfiguration ?? false;
   }
 
+  private getSupervisionUrlOcppKey(): string {
+    return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
+  }
+
   private getChargingStationId(stationTemplate: ChargingStationTemplate): string {
     // In case of multiple instances: add instance index to charging station id
     const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0;
@@ -663,19 +759,30 @@ export default class ChargingStation {
           idSuffix;
   }
 
+  private getRandomSerialNumberSuffix(params?: {
+    randomBytesLength?: number;
+    upperCase?: boolean;
+  }): string {
+    const randomSerialNumberSuffix = crypto
+      .randomBytes(params?.randomBytesLength ?? 16)
+      .toString('hex');
+    if (params?.upperCase) {
+      return randomSerialNumberSuffix.toUpperCase();
+    }
+    return randomSerialNumberSuffix;
+  }
+
   private buildStationInfo(): ChargingStationInfo {
     let stationTemplateFromFile: ChargingStationTemplate;
     try {
       // Load template file
-      const fileDescriptor = fs.openSync(this.stationTemplateFile, 'r');
       stationTemplateFromFile = JSON.parse(
-        fs.readFileSync(fileDescriptor, 'utf8')
+        fs.readFileSync(this.stationTemplateFile, 'utf8')
       ) as ChargingStationTemplate;
-      fs.closeSync(fileDescriptor);
     } catch (error) {
       FileUtils.handleFileException(
         this.logPrefix(),
-        'Template',
+        FileType.ChargingStationTemplate,
         this.stationTemplateFile,
         error as NodeJS.ErrnoException
       );
@@ -690,6 +797,10 @@ export default class ChargingStation {
     );
     this.convertDeprecatedTemplateKey(stationTemplateFromFile, 'supervisionUrl', 'supervisionUrls');
     const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? ({} as ChargingStationInfo);
+    stationInfo.chargePointSerialNumber = stationTemplateFromFile?.chargePointSerialNumberPrefix;
+    delete stationInfo.chargePointSerialNumberPrefix;
+    stationInfo.chargeBoxSerialNumber = stationTemplateFromFile?.chargeBoxSerialNumberPrefix;
+    delete stationInfo.chargeBoxSerialNumberPrefix;
     stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
     if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
       stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
@@ -720,6 +831,10 @@ export default class ChargingStation {
     return this.stationInfo.ocppVersion ? this.stationInfo.ocppVersion : OCPPVersion.VERSION_16;
   }
 
+  private getOcppPersistentConfiguration(): boolean {
+    return this.stationInfo.ocppPersistentConfiguration ?? true;
+  }
+
   private handleUnsupportedVersion(version: OCPPVersion) {
     const errMsg = `${this.logPrefix()} Unsupported protocol version '${version}' configured in template file ${
       this.stationTemplateFile
@@ -730,18 +845,41 @@ export default class ChargingStation {
 
   private initialize(): void {
     this.stationInfo = this.buildStationInfo();
-    this.configuration = this.getTemplateChargingStationConfiguration();
-    delete this.stationInfo.Configuration;
     this.bootNotificationRequest = {
       chargePointModel: this.stationInfo.chargePointModel,
       chargePointVendor: this.stationInfo.chargePointVendor,
-      ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumberPrefix) && {
-        chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumberPrefix,
+      ...(!Utils.isUndefined(this.stationInfo.chargeBoxSerialNumber) && {
+        chargeBoxSerialNumber: this.stationInfo.chargeBoxSerialNumber,
+      }),
+      ...(!Utils.isUndefined(this.stationInfo.chargePointSerialNumber) && {
+        chargePointSerialNumber: this.stationInfo.chargePointSerialNumber,
       }),
       ...(!Utils.isUndefined(this.stationInfo.firmwareVersion) && {
         firmwareVersion: this.stationInfo.firmwareVersion,
       }),
+      ...(!Utils.isUndefined(this.stationInfo.iccid) && { iccid: this.stationInfo.iccid }),
+      ...(!Utils.isUndefined(this.stationInfo.imsi) && { imsi: this.stationInfo.imsi }),
+      ...(!Utils.isUndefined(this.stationInfo.meterSerialNumber) && {
+        meterSerialNumber: this.stationInfo.meterSerialNumber,
+      }),
+      ...(!Utils.isUndefined(this.stationInfo.meterType) && {
+        meterType: this.stationInfo.meterType,
+      }),
     };
+
+    this.hashId = crypto
+      .createHash(Constants.DEFAULT_HASH_ALGORITHM)
+      .update(JSON.stringify(this.bootNotificationRequest) + this.stationInfo.chargingStationId)
+      .digest('hex');
+    logger.info(`${this.logPrefix()} Charging station hashId '${this.hashId}'`);
+    this.configurationFile = path.join(
+      path.resolve(__dirname, '../'),
+      'assets',
+      'configurations',
+      this.hashId + '.json'
+    );
+    this.configuration = this.getConfiguration();
+    delete this.stationInfo.Configuration;
     // Build connectors if needed
     const maxConnectors = this.getMaxNumberOfConnectors();
     if (maxConnectors <= 0) {
@@ -780,7 +918,7 @@ export default class ChargingStation {
       this.stationInfo.randomConnectors = true;
     }
     const connectorsConfigHash = crypto
-      .createHash('sha256')
+      .createHash(Constants.DEFAULT_HASH_ALGORITHM)
       .update(JSON.stringify(this.stationInfo.Connectors) + maxConnectors.toString())
       .digest('hex');
     const connectorsConfigChanged =
@@ -837,6 +975,8 @@ export default class ChargingStation {
     this.wsConfiguredConnectionUrl = new URL(
       this.getConfiguredSupervisionUrl().href + '/' + this.stationInfo.chargingStationId
     );
+    // OCPP parameters
+    this.initOcppParameters();
     switch (this.getOcppVersion()) {
       case OCPPVersion.VERSION_16:
         this.ocppIncomingRequestService =
@@ -850,8 +990,6 @@ export default class ChargingStation {
         this.handleUnsupportedVersion(this.getOcppVersion());
         break;
     }
-    // OCPP parameters
-    this.initOcppParameters();
     if (this.stationInfo.autoRegister) {
       this.bootNotificationResponse = {
         currentTime: new Date().toISOString(),
@@ -862,7 +1000,7 @@ export default class ChargingStation {
     this.stationInfo.powerDivider = this.getPowerDivider();
     if (this.getEnableStatistics()) {
       this.performanceStatistics = PerformanceStatistics.getInstance(
-        this.id,
+        this.hashId,
         this.stationInfo.chargingStationId,
         this.wsConnectionUrl
       );
@@ -872,15 +1010,18 @@ export default class ChargingStation {
   private initOcppParameters(): void {
     if (
       this.getSupervisionUrlOcppConfiguration() &&
-      !this.getConfigurationKey(
-        this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
-      )
+      !this.getConfigurationKey(this.getSupervisionUrlOcppKey())
     ) {
       this.addConfigurationKey(
-        VendorDefaultParametersKey.ConnectionUrl,
+        this.getSupervisionUrlOcppKey(),
         this.getConfiguredSupervisionUrl().href,
         { reboot: true }
       );
+    } else if (
+      !this.getSupervisionUrlOcppConfiguration() &&
+      this.getConfigurationKey(this.getSupervisionUrlOcppKey())
+    ) {
+      this.deleteConfigurationKey(this.getSupervisionUrlOcppKey(), { save: false });
     }
     if (!this.getConfigurationKey(StandardParametersKey.SupportedFeatureProfiles)) {
       this.addConfigurationKey(
@@ -891,7 +1032,8 @@ export default class ChargingStation {
     this.addConfigurationKey(
       StandardParametersKey.NumberOfConnectors,
       this.getNumberOfConnectors().toString(),
-      { readonly: true }
+      { readonly: true },
+      { overwrite: true }
     );
     if (!this.getConfigurationKey(StandardParametersKey.MeterValuesSampledData)) {
       this.addConfigurationKey(
@@ -936,6 +1078,68 @@ export default class ChargingStation {
         Constants.DEFAULT_CONNECTION_TIMEOUT.toString()
       );
     }
+    this.saveConfiguration();
+  }
+
+  private getConfigurationFromTemplate(): ChargingStationConfiguration {
+    return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration);
+  }
+
+  private getConfigurationFromFile(): ChargingStationConfiguration | null {
+    let configuration: ChargingStationConfiguration = null;
+    if (
+      this.getOcppPersistentConfiguration() &&
+      this.configurationFile &&
+      fs.existsSync(this.configurationFile)
+    ) {
+      try {
+        configuration = JSON.parse(
+          fs.readFileSync(this.configurationFile, 'utf8')
+        ) as ChargingStationConfiguration;
+      } catch (error) {
+        FileUtils.handleFileException(
+          this.logPrefix(),
+          FileType.ChargingStationConfiguration,
+          this.configurationFile,
+          error as NodeJS.ErrnoException
+        );
+      }
+    }
+    return configuration;
+  }
+
+  private saveConfiguration(): void {
+    if (this.getOcppPersistentConfiguration()) {
+      if (this.configurationFile) {
+        try {
+          if (!fs.existsSync(path.dirname(this.configurationFile))) {
+            fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
+          }
+          const fileDescriptor = fs.openSync(this.configurationFile, 'w');
+          fs.writeFileSync(fileDescriptor, JSON.stringify(this.configuration, null, 2));
+          fs.closeSync(fileDescriptor);
+        } catch (error) {
+          FileUtils.handleFileException(
+            this.logPrefix(),
+            FileType.ChargingStationConfiguration,
+            this.configurationFile,
+            error as NodeJS.ErrnoException
+          );
+        }
+      } else {
+        logger.error(
+          `${this.logPrefix()} Trying to save charging station configuration to undefined file`
+        );
+      }
+    }
+  }
+
+  private getConfiguration(): ChargingStationConfiguration {
+    let configuration: ChargingStationConfiguration = this.getConfigurationFromFile();
+    if (!configuration) {
+      configuration = this.getConfigurationFromTemplate();
+    }
+    return configuration;
   }
 
   private async onOpen(): Promise<void> {
@@ -946,21 +1150,22 @@ export default class ChargingStation {
       // Send BootNotification
       let registrationRetryCount = 0;
       do {
-        this.bootNotificationResponse = (await this.ocppRequestService.sendMessageHandler(
-          RequestCommand.BOOT_NOTIFICATION,
-          {
-            chargePointModel: this.bootNotificationRequest.chargePointModel,
-            chargePointVendor: this.bootNotificationRequest.chargePointVendor,
-            chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
-            firmwareVersion: this.bootNotificationRequest.firmwareVersion,
-            chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
-            iccid: this.bootNotificationRequest.iccid,
-            imsi: this.bootNotificationRequest.imsi,
-            meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
-            meterType: this.bootNotificationRequest.meterType,
-          },
-          { skipBufferingOnError: true }
-        )) as BootNotificationResponse;
+        this.bootNotificationResponse =
+          await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
+            RequestCommand.BOOT_NOTIFICATION,
+            {
+              chargePointModel: this.bootNotificationRequest.chargePointModel,
+              chargePointVendor: this.bootNotificationRequest.chargePointVendor,
+              chargeBoxSerialNumber: this.bootNotificationRequest.chargeBoxSerialNumber,
+              firmwareVersion: this.bootNotificationRequest.firmwareVersion,
+              chargePointSerialNumber: this.bootNotificationRequest.chargePointSerialNumber,
+              iccid: this.bootNotificationRequest.iccid,
+              imsi: this.bootNotificationRequest.imsi,
+              meterSerialNumber: this.bootNotificationRequest.meterSerialNumber,
+              meterType: this.bootNotificationRequest.meterType,
+            },
+            { skipBufferingOnError: true }
+          );
         if (!this.isInAcceptedState()) {
           this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++;
           await Utils.sleep(
@@ -1137,10 +1342,6 @@ export default class ChargingStation {
     logger.error(this.logPrefix() + ' WebSocket error: %j', error);
   }
 
-  private getTemplateChargingStationConfiguration(): ChargingStationConfiguration {
-    return this.stationInfo.Configuration ?? ({} as ChargingStationConfiguration);
-  }
-
   private getAuthorizationFile(): string | undefined {
     return (
       this.stationInfo.authorizationFile &&
@@ -1158,13 +1359,11 @@ export default class ChargingStation {
     if (authorizationFile) {
       try {
         // Load authorization file
-        const fileDescriptor = fs.openSync(authorizationFile, 'r');
-        authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
-        fs.closeSync(fileDescriptor);
+        authorizedTags = JSON.parse(fs.readFileSync(authorizationFile, 'utf8')) as string[];
       } catch (error) {
         FileUtils.handleFileException(
           this.logPrefix(),
-          'Authorization',
+          FileType.Authorization,
           authorizationFile,
           error as NodeJS.ErrnoException
         );
@@ -1255,7 +1454,7 @@ export default class ChargingStation {
 
   private async startMessageSequence(): Promise<void> {
     if (this.stationInfo.autoRegister) {
-      await this.ocppRequestService.sendMessageHandler(
+      await this.ocppRequestService.sendMessageHandler<BootNotificationResponse>(
         RequestCommand.BOOT_NOTIFICATION,
         {
           chargePointModel: this.bootNotificationRequest.chargePointModel,
@@ -1285,11 +1484,14 @@ export default class ChargingStation {
         this.getConnectorStatus(connectorId)?.bootStatus
       ) {
         // Send status in template at startup
-        await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
-          connectorId,
-          status: this.getConnectorStatus(connectorId).bootStatus,
-          errorCode: ChargePointErrorCode.NO_ERROR,
-        });
+        await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+          RequestCommand.STATUS_NOTIFICATION,
+          {
+            connectorId,
+            status: this.getConnectorStatus(connectorId).bootStatus,
+            errorCode: ChargePointErrorCode.NO_ERROR,
+          }
+        );
         this.getConnectorStatus(connectorId).status =
           this.getConnectorStatus(connectorId).bootStatus;
       } else if (
@@ -1298,27 +1500,36 @@ export default class ChargingStation {
         this.getConnectorStatus(connectorId)?.bootStatus
       ) {
         // Send status in template after reset
-        await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
-          connectorId,
-          status: this.getConnectorStatus(connectorId).bootStatus,
-          errorCode: ChargePointErrorCode.NO_ERROR,
-        });
+        await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+          RequestCommand.STATUS_NOTIFICATION,
+          {
+            connectorId,
+            status: this.getConnectorStatus(connectorId).bootStatus,
+            errorCode: ChargePointErrorCode.NO_ERROR,
+          }
+        );
         this.getConnectorStatus(connectorId).status =
           this.getConnectorStatus(connectorId).bootStatus;
       } else if (!this.stopped && this.getConnectorStatus(connectorId)?.status) {
         // Send previous status at template reload
-        await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
-          connectorId,
-          status: this.getConnectorStatus(connectorId).status,
-          errorCode: ChargePointErrorCode.NO_ERROR,
-        });
+        await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+          RequestCommand.STATUS_NOTIFICATION,
+          {
+            connectorId,
+            status: this.getConnectorStatus(connectorId).status,
+            errorCode: ChargePointErrorCode.NO_ERROR,
+          }
+        );
       } else {
         // Send default status
-        await this.ocppRequestService.sendMessageHandler(RequestCommand.STATUS_NOTIFICATION, {
-          connectorId,
-          status: ChargePointStatus.AVAILABLE,
-          errorCode: ChargePointErrorCode.NO_ERROR,
-        });
+        await this.ocppRequestService.sendMessageHandler<StatusNotificationResponse>(
+          RequestCommand.STATUS_NOTIFICATION,
+          {
+            connectorId,
+            status: ChargePointStatus.AVAILABLE,
+            errorCode: ChargePointErrorCode.NO_ERROR,
+          }
+        );
         this.getConnectorStatus(connectorId).status = ChargePointStatus.AVAILABLE;
       }
     }
@@ -1365,18 +1576,24 @@ export default class ChargingStation {
               connectorId,
               this.getEnergyActiveImportRegisterByTransactionId(transactionId)
             );
-            await this.ocppRequestService.sendMessageHandler(RequestCommand.METER_VALUES, {
-              connectorId,
-              transactionId,
-              meterValue: transactionEndMeterValue,
-            });
+            await this.ocppRequestService.sendMessageHandler<MeterValuesResponse>(
+              RequestCommand.METER_VALUES,
+              {
+                connectorId,
+                transactionId,
+                meterValue: transactionEndMeterValue,
+              }
+            );
           }
-          await this.ocppRequestService.sendMessageHandler(RequestCommand.STOP_TRANSACTION, {
-            transactionId,
-            meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
-            idTag: this.getTransactionIdTag(transactionId),
-            reason,
-          });
+          await this.ocppRequestService.sendMessageHandler<StopTransactionResponse>(
+            RequestCommand.STOP_TRANSACTION,
+            {
+              transactionId,
+              meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId),
+              idTag: this.getTransactionIdTag(transactionId),
+              reason,
+            }
+          );
         }
       }
     }
@@ -1550,89 +1767,6 @@ export default class ChargingStation {
     }
   }
 
-  private startAuthorizationFileMonitoring(): void {
-    const authorizationFile = this.getAuthorizationFile();
-    if (authorizationFile) {
-      try {
-        fs.watch(authorizationFile, (event, filename) => {
-          if (filename && event === 'change') {
-            try {
-              logger.debug(
-                this.logPrefix() +
-                  ' Authorization file ' +
-                  authorizationFile +
-                  ' have changed, reload'
-              );
-              // Initialize authorizedTags
-              this.authorizedTags = this.getAuthorizedTags();
-            } catch (error) {
-              logger.error(this.logPrefix() + ' Authorization file monitoring error: %j', error);
-            }
-          }
-        });
-      } catch (error) {
-        FileUtils.handleFileException(
-          this.logPrefix(),
-          'Authorization',
-          authorizationFile,
-          error as NodeJS.ErrnoException
-        );
-      }
-    } else {
-      logger.info(
-        this.logPrefix() +
-          ' No authorization file given in template file ' +
-          this.stationTemplateFile +
-          '. Not monitoring changes'
-      );
-    }
-  }
-
-  private startStationTemplateFileMonitoring(): void {
-    try {
-      fs.watch(this.stationTemplateFile, (event, filename): void => {
-        if (filename && event === 'change') {
-          try {
-            logger.debug(
-              this.logPrefix() +
-                ' Template file ' +
-                this.stationTemplateFile +
-                ' have changed, reload'
-            );
-            // Initialize
-            this.initialize();
-            // Restart the ATG
-            if (
-              !this.stationInfo.AutomaticTransactionGenerator.enable &&
-              this.automaticTransactionGenerator
-            ) {
-              this.automaticTransactionGenerator.stop();
-            }
-            this.startAutomaticTransactionGenerator();
-            if (this.getEnableStatistics()) {
-              this.performanceStatistics.restart();
-            } else {
-              this.performanceStatistics.stop();
-            }
-            // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
-          } catch (error) {
-            logger.error(
-              this.logPrefix() + ' Charging station template file monitoring error: %j',
-              error
-            );
-          }
-        }
-      });
-    } catch (error) {
-      FileUtils.handleFileException(
-        this.logPrefix(),
-        'Template',
-        this.stationTemplateFile,
-        error as NodeJS.ErrnoException
-      );
-    }
-  }
-
   private getReconnectExponentialDelay(): boolean | undefined {
     return !Utils.isUndefined(this.stationInfo.reconnectExponentialDelay)
       ? this.stationInfo.reconnectExponentialDelay