Delete supervision url configuration key if the feature is disabled from
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
index 6371501a838b375031f284a81358e1e232a2dba3..01829fdf47273797aefa980824db13282cd72862 100644 (file)
@@ -38,6 +38,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';
@@ -104,9 +105,7 @@ export default class ChargingStation {
   get wsConnectionUrl(): URL {
     return this.getSupervisionUrlOcppConfiguration()
       ? new URL(
-          this.getConfigurationKey(
-            this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl
-          ).value +
+          this.getConfigurationKey(this.getSupervisionUrlOcppKey()).value +
             '/' +
             this.stationInfo.chargingStationId
         )
@@ -492,9 +491,60 @@ 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
+            );
+          }
+        }
+      }
+    );
+    // FIXME: triggered by saveConfiguration()
+    // if (this.getOcppPersistentConfiguration()) {
+    //   FileUtils.watchJsonFile<ChargingStationConfiguration>(
+    //     this.logPrefix(),
+    //     FileType.ChargingStationConfiguration,
+    //     this.configurationFile,
+    //     this.configuration
+    //   );
+    // }
     // Handle WebSocket message
     this.wsConnection.on(
       'message',
@@ -568,12 +618,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);
+    if (!options || Utils.isEmptyObject(options)) {
+      options = {
+        readonly: false,
+        visible: true,
+        reboot: false,
+      };
+    }
     const readonly = options.readonly;
     const visible = options.visible;
     const reboot = options.reboot;
+    let keyFound = this.getConfigurationKey(key);
+    if (keyFound && params?.overwrite) {
+      this.deleteConfigurationKey(keyFound.key, { save: false });
+      keyFound = undefined;
+    }
     if (!keyFound) {
       this.configuration.configurationKey.push({
         key,
@@ -582,6 +644,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`,
@@ -590,8 +653,12 @@ 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;
@@ -604,6 +671,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)) {
@@ -655,6 +737,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;
@@ -673,15 +759,13 @@ export default class ChargingStation {
     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
       );
@@ -726,6 +810,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
@@ -738,8 +826,7 @@ export default class ChargingStation {
     this.stationInfo = this.buildStationInfo();
     this.configurationFile = path.join(
       path.resolve(__dirname, '../'),
-      'assets',
-      'configurations',
+      'assets/configurations',
       this.stationInfo.chargingStationId + '.json'
     );
     this.configuration = this.getConfiguration();
@@ -884,15 +971,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(
@@ -903,7 +993,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(
@@ -957,17 +1048,19 @@ export default class ChargingStation {
 
   private getConfigurationFromFile(): ChargingStationConfiguration | null {
     let configuration: ChargingStationConfiguration = null;
-    if (this.configurationFile && fs.existsSync(this.configurationFile)) {
+    if (
+      this.getOcppPersistentConfiguration() &&
+      this.configurationFile &&
+      fs.existsSync(this.configurationFile)
+    ) {
       try {
-        const fileDescriptor = fs.openSync(this.configurationFile, 'r');
         configuration = JSON.parse(
-          fs.readFileSync(fileDescriptor, 'utf8')
+          fs.readFileSync(this.configurationFile, 'utf8')
         ) as ChargingStationConfiguration;
-        fs.closeSync(fileDescriptor);
       } catch (error) {
         FileUtils.handleFileException(
           this.logPrefix(),
-          'Configuration',
+          FileType.ChargingStationConfiguration,
           this.configurationFile,
           error as NodeJS.ErrnoException
         );
@@ -977,26 +1070,28 @@ export default class ChargingStation {
   }
 
   private saveConfiguration(): void {
-    if (this.configurationFile) {
-      try {
-        if (!fs.existsSync(path.dirname(this.configurationFile))) {
-          fs.mkdirSync(path.dirname(this.configurationFile), { recursive: true });
+    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
+          );
         }
-        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(),
-          'Configuration',
-          this.configurationFile,
-          error as NodeJS.ErrnoException
+      } else {
+        logger.error(
+          `${this.logPrefix()} Trying to save charging station configuration to undefined file`
         );
       }
-    } else {
-      logger.error(
-        `${this.logPrefix()} Trying to save charging station configuration to undefined file`
-      );
     }
   }
 
@@ -1224,13 +1319,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
         );
@@ -1616,89 +1709,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