Fix local badge authorisation
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStation.ts
index dde845621781534c7d48ed366fd75b06ec9d1490..92e4a912b652d2a508c5ebb796e3aa1257b46040 100644 (file)
@@ -400,9 +400,12 @@ export default class ChargingStation {
     !cpReplaced && this.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
   }
 
-  public resetTransactionOnConnector(connectorId: number): void {
-    this.getConnectorStatus(connectorId).authorized = false;
+  public resetConnectorStatus(connectorId: number): void {
+    this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
+    this.getConnectorStatus(connectorId).idTagAuthorized = false;
+    this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
     this.getConnectorStatus(connectorId).transactionStarted = false;
+    delete this.getConnectorStatus(connectorId).localAuthorizeIdTag;
     delete this.getConnectorStatus(connectorId).authorizeIdTag;
     delete this.getConnectorStatus(connectorId).transactionId;
     delete this.getConnectorStatus(connectorId).transactionIdTag;
@@ -440,9 +443,10 @@ export default class ChargingStation {
       stationTemplateFromFile = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as ChargingStationTemplate;
       fs.closeSync(fileDescriptor);
     } catch (error) {
-      FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
+      FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
     }
     const stationInfo: ChargingStationInfo = stationTemplateFromFile ?? {} as ChargingStationInfo;
+    stationInfo.wsOptions = stationTemplateFromFile?.wsOptions ?? {};
     if (!Utils.isEmptyArray(stationTemplateFromFile.power)) {
       stationTemplateFromFile.power = stationTemplateFromFile.power as number[];
       const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplateFromFile.power.length);
@@ -474,13 +478,14 @@ 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.firmwareVersion) && { firmwareVersion: this.stationInfo.firmwareVersion },
     };
-    this.configuration = this.getTemplateChargingStationConfiguration();
     this.wsConnectionUrl = new URL(this.getSupervisionURL().href + '/' + this.stationInfo.chargingStationId);
     // Build connectors if needed
     const maxConnectors = this.getMaxNumberOfConnectors();
@@ -533,7 +538,7 @@ export default class ChargingStation {
     // Initialize transaction attributes on connectors
     for (const connectorId of this.connectors.keys()) {
       if (connectorId > 0 && !this.getConnectorStatus(connectorId)?.transactionStarted) {
-        this.initTransactionAttributesOnConnector(connectorId);
+        this.initializeConnectorStatus(connectorId);
       }
     }
     switch (this.getOCPPVersion()) {
@@ -703,9 +708,9 @@ export default class ChargingStation {
       }
     } catch (error) {
       // Log
-      logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data, this.requests.get(messageId), error);
+      logger.error('%s Incoming OCPP message %j matching cached request %j processing error %j', this.logPrefix(), data.toString(), this.requests.get(messageId), error);
       // Send error
-      messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error, commandName);
+      messageType === MessageType.CALL_MESSAGE && await this.ocppRequestService.sendError(messageId, error as OCPPError, commandName);
     }
   }
 
@@ -744,7 +749,7 @@ export default class ChargingStation {
         authorizedTags = JSON.parse(fs.readFileSync(fileDescriptor, 'utf8')) as string[];
         fs.closeSync(fileDescriptor);
       } catch (error) {
-        FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, 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);
@@ -939,8 +944,7 @@ export default class ChargingStation {
     }
   }
 
-  private openWSConnection(options?: ClientOptions & ClientRequestArgs, forceCloseOpened = false): void {
-    options = options ?? {};
+  private openWSConnection(options: ClientOptions & ClientRequestArgs = this.stationInfo.wsOptions, forceCloseOpened = false): void {
     options.handshakeTimeout = options?.handshakeTimeout ?? this.getConnectionTimeout() * 1000;
     if (!Utils.isNullOrUndefined(this.stationInfo.supervisionUser) && !Utils.isNullOrUndefined(this.stationInfo.supervisionPassword)) {
       options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}`;
@@ -948,7 +952,7 @@ export default class ChargingStation {
     if (this.isWebSocketConnectionOpened() && forceCloseOpened) {
       this.wsConnection.close();
     }
-    let protocol;
+    let protocol: string;
     switch (this.getOCPPVersion()) {
       case OCPPVersion.VERSION_16:
         protocol = 'ocpp' + OCPPVersion.VERSION_16;
@@ -983,7 +987,7 @@ export default class ChargingStation {
           }
         });
       } catch (error) {
-        FileUtils.handleFileException(this.logPrefix(), 'Authorization', authorizationFile, 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');
@@ -1016,7 +1020,7 @@ export default class ChargingStation {
         }
       });
     } catch (error) {
-      FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error);
+      FileUtils.handleFileException(this.logPrefix(), 'Template', this.stationTemplateFile, error as NodeJS.ErrnoException);
     }
   }
 
@@ -1039,19 +1043,21 @@ export default class ChargingStation {
     if (this.autoReconnectRetryCount < this.getAutoReconnectMaxRetries() || this.getAutoReconnectMaxRetries() === -1) {
       this.autoReconnectRetryCount++;
       const reconnectDelay = (this.getReconnectExponentialDelay() ? Utils.exponentialDelay(this.autoReconnectRetryCount) : this.getConnectionTimeout() * 1000);
-      const reconnectTimeout = reconnectDelay - 100;
+      const reconnectTimeout = (reconnectDelay - 100) > 0 && reconnectDelay;
       logger.error(`${this.logPrefix()} WebSocket: connection retry in ${Utils.roundTo(reconnectDelay, 2)}ms, timeout ${reconnectTimeout}ms`);
       await Utils.sleep(reconnectDelay);
       logger.error(this.logPrefix() + ' WebSocket: reconnecting try #' + this.autoReconnectRetryCount.toString());
-      this.openWSConnection({ handshakeTimeout: reconnectTimeout }, true);
+      this.openWSConnection({ ...this.stationInfo.wsOptions, handshakeTimeout: reconnectTimeout }, true);
       this.wsConnectionRestarted = true;
     } else if (this.getAutoReconnectMaxRetries() !== -1) {
       logger.error(`${this.logPrefix()} WebSocket reconnect failure: max retries reached (${this.autoReconnectRetryCount}) or retry disabled (${this.getAutoReconnectMaxRetries()})`);
     }
   }
 
-  private initTransactionAttributesOnConnector(connectorId: number): void {
-    this.getConnectorStatus(connectorId).authorized = false;
+  private initializeConnectorStatus(connectorId: number): void {
+    this.getConnectorStatus(connectorId).idTagLocalAuthorized = false;
+    this.getConnectorStatus(connectorId).idTagAuthorized = false;
+    this.getConnectorStatus(connectorId).transactionRemoteStarted = false;
     this.getConnectorStatus(connectorId).transactionStarted = false;
     this.getConnectorStatus(connectorId).energyActiveImportRegisterValue = 0;
     this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0;