Merge pull request #813 from SAP/combined-prs-branch
[e-mobility-charging-stations-simulator.git] / src / charging-station / broadcast-channel / ChargingStationWorkerBroadcastChannel.ts
index b2828305625a3de2428cfedc23b150c2549511ff..fff823c09b22989f441c6b88968018a6acc933a6 100644 (file)
@@ -1,3 +1,5 @@
+import { secondsToMilliseconds } from 'date-fns';
+
 import { WorkerBroadcastChannel } from './WorkerBroadcastChannel';
 import { BaseError, type OCPPError } from '../../exception';
 import {
@@ -15,6 +17,7 @@ import {
   DataTransferStatus,
   type DiagnosticsStatusNotificationRequest,
   type DiagnosticsStatusNotificationResponse,
+  type EmptyObject,
   type FirmwareStatusNotificationRequest,
   type FirmwareStatusNotificationResponse,
   type HeartbeatRequest,
@@ -34,27 +37,24 @@ import {
   type StopTransactionRequest,
   type StopTransactionResponse,
 } from '../../types';
-import { Constants, Utils, logger } from '../../utils';
+import { Constants, convertToInt, isEmptyObject, isNullOrUndefined, logger } from '../../utils';
 import type { ChargingStation } from '../ChargingStation';
-import { ChargingStationConfigurationUtils } from '../ChargingStationConfigurationUtils';
+import { getConfigurationKey } from '../ConfigurationKeyUtils';
 import { OCPP16ServiceUtils } from '../ocpp';
 
 const moduleName = 'ChargingStationWorkerBroadcastChannel';
 
 type CommandResponse =
+  | EmptyObject
   | StartTransactionResponse
   | StopTransactionResponse
   | AuthorizeResponse
   | BootNotificationResponse
-  | StatusNotificationResponse
   | HeartbeatResponse
-  | MeterValuesResponse
-  | DataTransferResponse
-  | DiagnosticsStatusNotificationResponse
-  | FirmwareStatusNotificationResponse;
+  | DataTransferResponse;
 
 type CommandHandler = (
-  requestPayload?: BroadcastChannelRequestPayload
+  requestPayload?: BroadcastChannelRequestPayload,
 ) => Promise<CommandResponse | void> | void;
 
 export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChannel {
@@ -114,12 +114,12 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
             RequestCommand.STOP_TRANSACTION,
             {
               meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId(
-                requestPayload.transactionId,
-                true
+                requestPayload!.transactionId!,
+                true,
               ),
               ...requestPayload,
             },
-            requestParams
+            requestParams,
           ),
       ],
       [
@@ -147,7 +147,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
               {
                 skipBufferingOnError: true,
                 throwError: true,
-              }
+              },
             );
           return this.chargingStation.bootNotificationResponse;
         },
@@ -162,7 +162,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
             this.chargingStation,
             RequestCommand.STATUS_NOTIFICATION,
             requestPayload,
-            requestParams
+            requestParams,
           ),
       ],
       [
@@ -176,11 +176,10 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
       [
         BroadcastChannelProcedureName.METER_VALUES,
         async (requestPayload?: BroadcastChannelRequestPayload) => {
-          const configuredMeterValueSampleInterval =
-            ChargingStationConfigurationUtils.getConfigurationKey(
-              chargingStation,
-              StandardParametersKey.MeterValueSampleInterval
-            );
+          const configuredMeterValueSampleInterval = getConfigurationKey(
+            chargingStation,
+            StandardParametersKey.MeterValueSampleInterval,
+          );
           return this.chargingStation.ocppRequestService.requestHandler<
             MeterValuesRequest,
             MeterValuesResponse
@@ -192,17 +191,17 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
                 // FIXME: Implement OCPP version agnostic helpers
                 OCPP16ServiceUtils.buildMeterValue(
                   this.chargingStation,
-                  requestPayload.connectorId,
-                  this.chargingStation.getConnectorStatus(requestPayload.connectorId)
-                    ?.transactionId,
+                  requestPayload!.connectorId!,
+                  this.chargingStation.getConnectorStatus(requestPayload!.connectorId!)!
+                    .transactionId!,
                   configuredMeterValueSampleInterval
-                    ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000
-                    : Constants.DEFAULT_METER_VALUES_INTERVAL
+                    ? secondsToMilliseconds(convertToInt(configuredMeterValueSampleInterval.value))
+                    : Constants.DEFAULT_METER_VALUES_INTERVAL,
                 ),
               ],
               ...requestPayload,
             },
-            requestParams
+            requestParams,
           );
         },
       ],
@@ -224,7 +223,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
             this.chargingStation,
             RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
             requestPayload,
-            requestParams
+            requestParams,
           ),
       ],
       [
@@ -237,13 +236,13 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
             this.chargingStation,
             RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
             requestPayload,
-            requestParams
+            requestParams,
           ),
       ],
     ]);
     this.chargingStation = chargingStation;
-    this.onmessage = this.requestHandler.bind(this) as (message: MessageEvent) => void;
-    this.onmessageerror = this.messageErrorHandler.bind(this) as (message: MessageEvent) => void;
+    this.onmessage = this.requestHandler.bind(this) as (message: unknown) => void;
+    this.onmessageerror = this.messageErrorHandler.bind(this) as (message: unknown) => void;
   }
 
   private async requestHandler(messageEvent: MessageEvent): Promise<void> {
@@ -256,25 +255,22 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
     }
     const [uuid, command, requestPayload] = validatedMessageEvent.data as BroadcastChannelRequest;
     if (
-      !Utils.isNullOrUndefined(requestPayload?.hashIds) &&
-      requestPayload?.hashIds?.includes(this.chargingStation.stationInfo.hashId) === false
+      !isNullOrUndefined(requestPayload.hashIds) &&
+      requestPayload.hashIds?.includes(this.chargingStation.stationInfo.hashId) === false
     ) {
       return;
     }
-    if (!Utils.isNullOrUndefined(requestPayload?.hashId)) {
+    if (!isNullOrUndefined(requestPayload.hashId)) {
       logger.error(
-        `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: 'hashId' field usage in PDU is deprecated, use 'hashIds' array instead`
+        `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: 'hashId' field usage in PDU is deprecated, use 'hashIds' array instead`,
       );
       return;
     }
-    let responsePayload: BroadcastChannelResponsePayload;
-    let commandResponse: CommandResponse | void;
+    let responsePayload: BroadcastChannelResponsePayload | undefined;
+    let commandResponse: CommandResponse | void | undefined;
     try {
       commandResponse = await this.commandHandler(command, requestPayload);
-      if (
-        Utils.isNullOrUndefined(commandResponse) ||
-        Utils.isEmptyObject(commandResponse as CommandResponse)
-      ) {
+      if (isNullOrUndefined(commandResponse) || isEmptyObject(commandResponse as CommandResponse)) {
         responsePayload = {
           hashId: this.chargingStation.stationInfo.hashId,
           status: ResponseStatus.SUCCESS,
@@ -283,13 +279,13 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
         responsePayload = this.commandResponseToResponsePayload(
           command,
           requestPayload,
-          commandResponse as CommandResponse
+          commandResponse as CommandResponse,
         );
       }
     } catch (error) {
       logger.error(
         `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: Handle request error:`,
-        error
+        error,
       );
       responsePayload = {
         hashId: this.chargingStation.stationInfo.hashId,
@@ -302,31 +298,31 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
         errorDetails: (error as OCPPError).details,
       };
     } finally {
-      this.sendResponse([uuid, responsePayload]);
+      this.sendResponse([uuid, responsePayload!]);
     }
   }
 
   private messageErrorHandler(messageEvent: MessageEvent): void {
     logger.error(
       `${this.chargingStation.logPrefix()} ${moduleName}.messageErrorHandler: Error at handling message:`,
-      messageEvent
+      messageEvent,
     );
   }
 
   private async commandHandler(
     command: BroadcastChannelProcedureName,
-    requestPayload: BroadcastChannelRequestPayload
+    requestPayload: BroadcastChannelRequestPayload,
   ): Promise<CommandResponse | void> {
     if (this.commandHandlers.has(command) === true) {
       this.cleanRequestPayload(command, requestPayload);
-      return this.commandHandlers.get(command)(requestPayload);
+      return this.commandHandlers.get(command)!(requestPayload);
     }
-    throw new BaseError(`Unknown worker broadcast channel command: ${command}`);
+    throw new BaseError(`Unknown worker broadcast channel command: '${command}'`);
   }
 
   private cleanRequestPayload(
     command: BroadcastChannelProcedureName,
-    requestPayload: BroadcastChannelRequestPayload
+    requestPayload: BroadcastChannelRequestPayload,
   ): void {
     delete requestPayload.hashId;
     delete requestPayload.hashIds;
@@ -339,7 +335,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
   private commandResponseToResponsePayload(
     command: BroadcastChannelProcedureName,
     requestPayload: BroadcastChannelRequestPayload,
-    commandResponse: CommandResponse
+    commandResponse: CommandResponse,
   ): BroadcastChannelResponsePayload {
     const responseStatus = this.commandResponseToResponseStatus(command, commandResponse);
     if (responseStatus === ResponseStatus.SUCCESS) {
@@ -359,7 +355,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
 
   private commandResponseToResponseStatus(
     command: BroadcastChannelProcedureName,
-    commandResponse: CommandResponse
+    commandResponse: CommandResponse,
   ): ResponseStatus {
     switch (command) {
       case BroadcastChannelProcedureName.START_TRANSACTION:
@@ -388,7 +384,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
         return ResponseStatus.FAILURE;
       case BroadcastChannelProcedureName.STATUS_NOTIFICATION:
       case BroadcastChannelProcedureName.METER_VALUES:
-        if (Utils.isEmptyObject(commandResponse) === true) {
+        if (isEmptyObject(commandResponse) === true) {
           return ResponseStatus.SUCCESS;
         }
         return ResponseStatus.FAILURE;