fix: ensure event listeners are always removed at simulator stop
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPServiceUtils.ts
index ee4134bb0a192f8db9f27075557f1e176ad4d58c..d9d712981c816790cb4e2b6f1c09fa6cd10e7dac 100644 (file)
@@ -15,6 +15,7 @@ import {
   type AuthorizeRequest,
   type AuthorizeResponse,
   ChargePointErrorCode,
+  ChargingStationEvents,
   type ConnectorStatus,
   type ConnectorStatusEnum,
   ErrorType,
@@ -40,6 +41,7 @@ import {
   isNotEmptyString,
   logPrefix,
   logger,
+  max,
   min,
 } from '../../utils';
 
@@ -226,6 +228,10 @@ export class OCPPServiceUtils {
       );
     }
     chargingStation.getConnectorStatus(connectorId)!.status = status;
+    chargingStation.emit(ChargingStationEvents.connectorStatusChanged, {
+      connectorId,
+      ...chargingStation.getConnectorStatus(connectorId),
+    });
   }
 
   public static async isIdTagAuthorized(
@@ -412,22 +418,27 @@ export class OCPPServiceUtils {
   }
 
   protected static getLimitFromSampledValueTemplateCustomValue(
-    value: string,
-    limit: number,
-    options?: { limitationEnabled?: boolean; unitMultiplier?: number },
+    value: string | undefined,
+    maxLimit: number,
+    minLimit: number,
+    options?: { limitationEnabled?: boolean; fallbackValue?: number; unitMultiplier?: number },
   ): number {
     options = {
       ...{
-        limitationEnabled: true,
+        limitationEnabled: false,
         unitMultiplier: 1,
+        fallbackValue: 0,
       },
       ...options,
     };
-    const parsedInt = parseInt(value);
-    const numberValue = isNaN(parsedInt) ? Infinity : parsedInt;
-    return options?.limitationEnabled
-      ? min(numberValue * options.unitMultiplier!, limit)
-      : numberValue * options.unitMultiplier!;
+    const parsedValue = parseInt(value ?? '');
+    if (options?.limitationEnabled) {
+      return max(
+        min((!isNaN(parsedValue) ? parsedValue : Infinity) * options.unitMultiplier!, maxLimit),
+        minLimit,
+      );
+    }
+    return (!isNaN(parsedValue) ? parsedValue : options.fallbackValue!) * options.unitMultiplier!;
   }
 
   private static isIdTagLocalAuthorized(chargingStation: ChargingStation, idTag: string): boolean {