Strict null check fixes
authorJérôme Benoit <jerome.benoit@sap.com>
Wed, 25 Jan 2023 16:27:47 +0000 (17:27 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Wed, 25 Jan 2023 16:27:47 +0000 (17:27 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
27 files changed:
.eslintrc.json
.prettierrc.json
src/charging-station/AutomaticTransactionGenerator.ts
src/charging-station/Bootstrap.ts
src/charging-station/ChargingStation.ts
src/charging-station/ChargingStationConfigurationUtils.ts
src/charging-station/ChargingStationWorkerBroadcastChannel.ts
src/charging-station/UIServiceWorkerBroadcastChannel.ts
src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts
src/charging-station/ocpp/1.6/OCPP16ResponseService.ts
src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts
src/charging-station/ocpp/OCPPRequestService.ts
src/charging-station/ocpp/OCPPServiceUtils.ts
src/charging-station/ui-server/UIHttpServer.ts
src/charging-station/ui-server/UIWebSocketServer.ts
src/charging-station/ui-server/ui-services/AbstractUIService.ts
src/performance/PerformanceStatistics.ts
src/performance/storage/JsonFileStorage.ts
src/performance/storage/MongoDBStorage.ts
src/start.ts
src/utils/Configuration.ts
src/utils/Utils.ts
src/worker/WorkerAbstract.ts
src/worker/WorkerDynamicPool.ts
src/worker/WorkerSet.ts
src/worker/WorkerStaticPool.ts
ui/web/src/composables/UIClient.ts

index 8b10dc67bc7b4f510e918775b1fe6fdbbc3c23e2..b9b190f5146555b6aaf54eafe21321b8b8c128c1 100644 (file)
@@ -84,8 +84,7 @@
     "space-unary-ops": "error",
     "spaced-comment": ["error", "always"],
     "switch-colon-spacing": "error",
-    "arrow-body-style": ["error", "as-needed"],
-    "arrow-parens": ["error", "as-needed"],
+    "arrow-parens": ["error", "always"],
     "arrow-spacing": "error",
     "no-duplicate-imports": "error",
     "no-var": "error",
index ef4fe83fdb37f2f48f424215683b4d32898832bc..5ac85e271d543cf99a88eddb0cd368c1002ca629 100644 (file)
@@ -1,5 +1,4 @@
 {
   "printWidth": 100,
-  "arrowParens": "avoid",
   "singleQuote": true
 }
index 2774149e8be144cfac1cf11a2b4c4748be9879fe..4603f2788f72cce2e9161b85a9e2e0ef11904ca0 100644 (file)
@@ -222,7 +222,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
           logger.info(
             `${this.logPrefix(connectorId)} transaction ${this.chargingStation
               .getConnectorStatus(connectorId)
-              .transactionId.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
+              ?.transactionId?.toString()} started and will stop in ${Utils.formatDurationMilliSeconds(
               waitTrxEnd
             )}`
           );
@@ -266,8 +266,8 @@ export default class AutomaticTransactionGenerator extends AsyncResource {
   private setStartConnectorStatus(connectorId: number): void {
     this.connectorsStatus.get(connectorId).skippedConsecutiveTransactions = 0;
     const previousRunDuration =
-      this?.connectorsStatus.get(connectorId)?.startDate &&
-      this?.connectorsStatus.get(connectorId)?.lastRunDate
+      this.connectorsStatus.get(connectorId)?.startDate &&
+      this.connectorsStatus.get(connectorId)?.lastRunDate
         ? this.connectorsStatus.get(connectorId).lastRunDate.getTime() -
           this.connectorsStatus.get(connectorId).startDate.getTime()
         : 0;
index 9f910aafd9fb15e5799f60908a780b6160c64e37..8a161e54a66e210c9fd856b3cf06295e12db9b5a 100644 (file)
@@ -41,7 +41,7 @@ export class Bootstrap {
   private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
   private readonly uiServer!: AbstractUIServer;
   private readonly storage!: Storage;
-  private numberOfChargingStationTemplates!: number;
+  private numberOfChargingStationTemplates!: number | undefined;
   private numberOfChargingStations!: number;
   private numberOfStartedChargingStations!: number;
   private readonly version: string = version;
@@ -86,7 +86,7 @@ export class Bootstrap {
         await this.workerImplementation?.start();
         this.uiServer?.start();
         const stationTemplateUrls = Configuration.getStationTemplateUrls();
-        this.numberOfChargingStationTemplates = stationTemplateUrls.length;
+        this.numberOfChargingStationTemplates = stationTemplateUrls?.length;
         // Start ChargingStation object in worker thread
         if (!Utils.isEmptyArray(stationTemplateUrls)) {
           for (const stationTemplateUrl of stationTemplateUrls) {
@@ -285,7 +285,7 @@ export class Bootstrap {
         stationTemplateUrl.file
       ),
     };
-    await this.workerImplementation.addElement(workerData);
+    await this.workerImplementation?.addElement(workerData);
     ++this.numberOfChargingStations;
   }
 
index 4a90c310ef87009e4df99f710ceb0c80afbdb2a4..639123abe9f814631de87409c7fbc7ad66c5a3b0 100644 (file)
@@ -101,8 +101,8 @@ export default class ChargingStation {
   public starting: boolean;
   public authorizedTagsCache: AuthorizedTagsCache;
   public automaticTransactionGenerator!: AutomaticTransactionGenerator;
-  public ocppConfiguration!: ChargingStationOcppConfiguration;
-  public wsConnection!: WebSocket;
+  public ocppConfiguration!: ChargingStationOcppConfiguration | null;
+  public wsConnection!: WebSocket | null;
   public readonly connectors: Map<number, ConnectorStatus>;
   public readonly requests: Map<string, CachedRequest>;
   public performanceStatistics!: PerformanceStatistics;
@@ -121,7 +121,7 @@ export default class ChargingStation {
   private configuredSupervisionUrlIndex!: number;
   private wsConnectionRestarted: boolean;
   private autoReconnectRetryCount: number;
-  private templateFileWatcher!: fs.FSWatcher;
+  private templateFileWatcher!: fs.FSWatcher | undefined;
   private readonly sharedLRUCache: SharedLRUCache;
   private webSocketPingSetInterval!: NodeJS.Timeout;
   private readonly chargingStationWorkerBroadcastChannel: ChargingStationWorkerBroadcastChannel;
@@ -151,7 +151,7 @@ export default class ChargingStation {
           ? ChargingStationConfigurationUtils.getConfigurationKey(
               this,
               this.getSupervisionUrlOcppKey()
-            ).value
+            )?.value
           : this.configuredSupervisionUrl.href
       }/${this.stationInfo.chargingStationId}`
     );
@@ -246,7 +246,7 @@ export default class ChargingStation {
   }
 
   public getCurrentOutType(stationInfo?: ChargingStationInfo): CurrentType {
-    return (stationInfo ?? this.stationInfo).currentOutType ?? CurrentType.AC;
+    return (stationInfo ?? this.stationInfo)?.currentOutType ?? CurrentType.AC;
   }
 
   public getOcppStrictCompliance(): boolean {
@@ -274,7 +274,7 @@ export default class ChargingStation {
     let connectorAmperageLimitationPowerLimit: number;
     if (
       !Utils.isNullOrUndefined(this.getAmperageLimitation()) &&
-      this.getAmperageLimitation() < this.stationInfo.maximumAmperage
+      this.getAmperageLimitation() < this.stationInfo?.maximumAmperage
     ) {
       connectorAmperageLimitationPowerLimit =
         (this.getCurrentOutType() === CurrentType.AC
@@ -304,7 +304,7 @@ export default class ChargingStation {
         connectorId > 0 &&
         this.getConnectorStatus(connectorId)?.transactionId === transactionId
       ) {
-        return this.getConnectorStatus(connectorId).transactionIdTag;
+        return this.getConnectorStatus(connectorId)?.transactionIdTag;
       }
     }
   }
@@ -389,7 +389,7 @@ export default class ChargingStation {
       this.heartbeatSetInterval = setInterval(() => {
         this.ocppRequestService
           .requestHandler<HeartbeatRequest, HeartbeatResponse>(this, RequestCommand.HEARTBEAT)
-          .catch(error => {
+          .catch((error) => {
             logger.error(
               `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`,
               error
@@ -474,11 +474,11 @@ export default class ChargingStation {
             RequestCommand.METER_VALUES,
             {
               connectorId,
-              transactionId: this.getConnectorStatus(connectorId).transactionId,
+              transactionId: this.getConnectorStatus(connectorId)?.transactionId,
               meterValue: [meterValue],
             }
           )
-          .catch(error => {
+          .catch((error) => {
             logger.error(
               `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
               error
@@ -564,7 +564,7 @@ export default class ChargingStation {
           this.performanceStatistics.stop();
         }
         this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
-        this.templateFileWatcher.close();
+        this.templateFileWatcher?.close();
         this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash);
         this.bootNotificationResponse = undefined;
         this.started = false;
@@ -606,11 +606,11 @@ export default class ChargingStation {
     parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
   }
 
-  public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean {
+  public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean | undefined {
     return ChargingStationConfigurationUtils.getConfigurationKey(
       this,
       StandardParametersKey.SupportedFeatureProfiles
-    )?.value.includes(featureProfile);
+    )?.value?.includes(featureProfile);
   }
 
   public bufferMessage(message: string): void {
@@ -696,7 +696,7 @@ export default class ChargingStation {
 
   public closeWSConnection(): void {
     if (this.isWebSocketConnectionOpened() === true) {
-      this.wsConnection.close();
+      this.wsConnection?.close();
       this.wsConnection = null;
     }
   }
@@ -735,7 +735,7 @@ export default class ChargingStation {
     connectorId: number,
     reason = StopTransactionReason.NONE
   ): Promise<StopTransactionResponse> {
-    const transactionId = this.getConnectorStatus(connectorId).transactionId;
+    const transactionId = this.getConnectorStatus(connectorId)?.transactionId;
     if (
       this.getBeginEndMeterValues() === true &&
       this.getOcppStrictCompliance() === true &&
@@ -770,7 +770,7 @@ export default class ChargingStation {
 
   private flushMessageBuffer(): void {
     if (this.messageBuffer.size > 0) {
-      this.messageBuffer.forEach(message => {
+      this.messageBuffer.forEach((message) => {
         let beginId: string;
         let commandName: RequestCommand;
         const [messageType] = JSON.parse(message) as OutgoingRequest | Response | ErrorResponse;
@@ -779,7 +779,7 @@ export default class ChargingStation {
           [, , commandName] = JSON.parse(message) as OutgoingRequest;
           beginId = PerformanceStatistics.beginMeasure(commandName);
         }
-        this.wsConnection.send(message);
+        this.wsConnection?.send(message);
         isRequest && PerformanceStatistics.endMeasure(commandName, beginId);
         logger.debug(
           `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
@@ -799,8 +799,8 @@ export default class ChargingStation {
     return this.stationInfo.supervisionUrlOcppKey ?? VendorDefaultParametersKey.ConnectionUrl;
   }
 
-  private getTemplateFromFile(): ChargingStationTemplate | null {
-    let template: ChargingStationTemplate = null;
+  private getTemplateFromFile(): ChargingStationTemplate | undefined {
+    let template: ChargingStationTemplate;
     try {
       if (this.sharedLRUCache.hasChargingStationTemplate(this.stationInfo?.templateHash)) {
         template = this.sharedLRUCache.getChargingStationTemplate(this.stationInfo.templateHash);
@@ -829,7 +829,7 @@ export default class ChargingStation {
   }
 
   private getStationInfoFromTemplate(): ChargingStationInfo {
-    const stationTemplate: ChargingStationTemplate = this.getTemplateFromFile();
+    const stationTemplate: ChargingStationTemplate | undefined = this.getTemplateFromFile();
     if (Utils.isNullOrUndefined(stationTemplate)) {
       const errorMsg = `Failed to read charging station template file ${this.templateFile}`;
       logger.error(`${this.logPrefix()} ${errorMsg}`);
@@ -860,24 +860,24 @@ export default class ChargingStation {
       this.index,
       stationTemplate
     );
-    stationInfo.ocppVersion = stationTemplate.ocppVersion ?? OCPPVersion.VERSION_16;
+    stationInfo.ocppVersion = stationTemplate?.ocppVersion ?? OCPPVersion.VERSION_16;
     ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
-    if (!Utils.isEmptyArray(stationTemplate.power)) {
-      stationTemplate.power = stationTemplate.power as number[];
+    if (!Utils.isEmptyArray(stationTemplate?.power)) {
+      stationTemplate.power = stationTemplate?.power as number[];
       const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
       stationInfo.maximumPower =
-        stationTemplate.powerUnit === PowerUnits.KILO_WATT
+        stationTemplate?.powerUnit === PowerUnits.KILO_WATT
           ? stationTemplate.power[powerArrayRandomIndex] * 1000
           : stationTemplate.power[powerArrayRandomIndex];
     } else {
       stationTemplate.power = stationTemplate.power as number;
       stationInfo.maximumPower =
-        stationTemplate.powerUnit === PowerUnits.KILO_WATT
+        stationTemplate?.powerUnit === PowerUnits.KILO_WATT
           ? stationTemplate.power * 1000
           : stationTemplate.power;
     }
     stationInfo.firmwareVersionPattern =
-      stationTemplate.firmwareVersionPattern ?? Constants.SEMVER_PATTERN;
+      stationTemplate?.firmwareVersionPattern ?? Constants.SEMVER_PATTERN;
     if (
       stationInfo.firmwareVersion &&
       new RegExp(stationInfo.firmwareVersionPattern).test(stationInfo.firmwareVersion) === false
@@ -892,9 +892,9 @@ export default class ChargingStation {
       {
         reset: true,
       },
-      stationTemplate.firmwareUpgrade ?? {}
+      stationTemplate?.firmwareUpgrade ?? {}
     );
-    stationInfo.resetTime = stationTemplate.resetTime
+    stationInfo.resetTime = stationTemplate?.resetTime
       ? stationTemplate.resetTime * 1000
       : Constants.CHARGING_STATION_DEFAULT_RESET_TIME;
     const configuredMaxConnectors =
@@ -931,7 +931,7 @@ export default class ChargingStation {
   }
 
   private getStationInfoFromFile(): ChargingStationInfo | null {
-    let stationInfo: ChargingStationInfo = null;
+    let stationInfo: ChargingStationInfo | null = null;
     this.getStationInfoPersistentConfiguration() &&
       (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
     stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
@@ -940,7 +940,7 @@ export default class ChargingStation {
 
   private getStationInfo(): ChargingStationInfo {
     const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
-    const stationInfoFromFile: ChargingStationInfo = this.getStationInfoFromFile();
+    const stationInfoFromFile: ChargingStationInfo | null = this.getStationInfoFromFile();
     // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
     if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
       if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
@@ -1038,14 +1038,14 @@ export default class ChargingStation {
       const patternGroup: number =
         this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
         this.stationInfo.firmwareVersion.split('.').length;
-      const match = this.stationInfo.firmwareVersion
-        .match(new RegExp(this.stationInfo.firmwareVersionPattern))
-        .slice(1, patternGroup + 1);
+      const match = this.stationInfo?.firmwareVersion
+        ?.match(new RegExp(this.stationInfo.firmwareVersionPattern))
+        ?.slice(1, patternGroup + 1);
       const patchLevelIndex = match.length - 1;
       match[patchLevelIndex] = (
         Utils.convertToInt(match[patchLevelIndex]) + versionStep
       ).toString();
-      this.stationInfo.firmwareVersion = match.join('.');
+      this.stationInfo.firmwareVersion = match?.join('.');
     }
   }
 
@@ -1188,7 +1188,7 @@ export default class ChargingStation {
       ChargingStationConfigurationUtils.getConfigurationKey(
         this,
         StandardParametersKey.SupportedFeatureProfiles
-      )?.value.includes(SupportedFeatureProfiles.LocalAuthListManagement)
+      )?.value?.includes(SupportedFeatureProfiles.LocalAuthListManagement)
     ) {
       ChargingStationConfigurationUtils.addConfigurationKey(
         this,
@@ -1284,17 +1284,17 @@ export default class ChargingStation {
     }
     // Initialize transaction attributes on connectors
     for (const connectorId of this.connectors.keys()) {
-      if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionStarted === true) {
+      if (connectorId > 0 && this.getConnectorStatus(connectorId)?.transactionStarted === true) {
         logger.warn(
           `${this.logPrefix()} Connector ${connectorId} at initialization has a transaction started: ${
-            this.getConnectorStatus(connectorId).transactionId
+            this.getConnectorStatus(connectorId)?.transactionId
           }`
         );
       }
       if (
         connectorId > 0 &&
-        (this.getConnectorStatus(connectorId).transactionStarted === undefined ||
-          this.getConnectorStatus(connectorId).transactionStarted === null)
+        (this.getConnectorStatus(connectorId)?.transactionStarted === undefined ||
+          this.getConnectorStatus(connectorId)?.transactionStarted === null)
       ) {
         this.initializeConnectorStatus(connectorId);
       }
@@ -1316,7 +1316,7 @@ export default class ChargingStation {
   }
 
   private getConfigurationFromFile(): ChargingStationConfiguration | null {
-    let configuration: ChargingStationConfiguration = null;
+    let configuration: ChargingStationConfiguration | null = null;
     if (this.configurationFile && fs.existsSync(this.configurationFile)) {
       try {
         if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
@@ -1399,7 +1399,7 @@ export default class ChargingStation {
   }
 
   private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
-    let configuration: ChargingStationConfiguration = null;
+    let configuration: ChargingStationConfiguration | null = null;
     if (this.getOcppPersistentConfiguration() === true) {
       const configurationFromFile = this.getConfigurationFromFile();
       configuration = configurationFromFile?.configurationKey && configurationFromFile;
@@ -1409,7 +1409,8 @@ export default class ChargingStation {
   }
 
   private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
-    let ocppConfiguration: ChargingStationOcppConfiguration = this.getOcppConfigurationFromFile();
+    let ocppConfiguration: ChargingStationOcppConfiguration | null =
+      this.getOcppConfigurationFromFile();
     if (!ocppConfiguration) {
       ocppConfiguration = this.getOcppConfigurationFromTemplate();
     }
@@ -1536,7 +1537,7 @@ export default class ChargingStation {
               throw new OCPPError(
                 ErrorType.INTERNAL_ERROR,
                 `Response for unknown message id ${messageId}`,
-                null,
+                undefined,
                 commandPayload
               );
             }
@@ -1548,7 +1549,7 @@ export default class ChargingStation {
               throw new OCPPError(
                 ErrorType.PROTOCOL_ERROR,
                 `Cached request for message id ${messageId} response is not an array`,
-                null,
+                undefined,
                 cachedRequest as unknown as JsonType
               );
             }
@@ -1567,7 +1568,7 @@ export default class ChargingStation {
               throw new OCPPError(
                 ErrorType.INTERNAL_ERROR,
                 `Error response for unknown message id ${messageId}`,
-                null,
+                undefined,
                 { errorType, errorMessage, errorDetails }
               );
             }
@@ -1578,7 +1579,7 @@ export default class ChargingStation {
               throw new OCPPError(
                 ErrorType.PROTOCOL_ERROR,
                 `Cached request for message id ${messageId} error response is not an array`,
-                null,
+                undefined,
                 cachedRequest as unknown as JsonType
               );
             }
@@ -1720,7 +1721,7 @@ export default class ChargingStation {
   }
 
   // -1 for unlimited, 0 for disabling
-  private getAutoReconnectMaxRetries(): number {
+  private getAutoReconnectMaxRetries(): number | undefined {
     if (!Utils.isUndefined(this.stationInfo.autoReconnectMaxRetries)) {
       return this.stationInfo.autoReconnectMaxRetries;
     }
@@ -1731,7 +1732,7 @@ export default class ChargingStation {
   }
 
   // 0 for disabling
-  private getRegistrationMaxRetries(): number {
+  private getRegistrationMaxRetries(): number | undefined {
     if (!Utils.isUndefined(this.stationInfo.registrationMaxRetries)) {
       return this.stationInfo.registrationMaxRetries;
     }
@@ -1773,7 +1774,7 @@ export default class ChargingStation {
           ChargingStationConfigurationUtils.getConfigurationKey(
             this,
             this.stationInfo.amperageLimitationOcppKey
-          ).value
+          )?.value
         ) / ChargingStationUtils.getAmperageLimitationUnitDivider(this.stationInfo)
       );
     }
@@ -1794,7 +1795,7 @@ export default class ChargingStation {
     this.startHeartbeat();
     // Initialize connectors status
     for (const connectorId of this.connectors.keys()) {
-      let connectorStatus: ConnectorStatusEnum;
+      let connectorStatus: ConnectorStatusEnum | undefined;
       if (connectorId === 0) {
         continue;
       } else if (
@@ -1808,10 +1809,10 @@ export default class ChargingStation {
         this.getConnectorStatus(connectorId)?.bootStatus
       ) {
         // Set boot status in template at startup
-        connectorStatus = this.getConnectorStatus(connectorId).bootStatus;
+        connectorStatus = this.getConnectorStatus(connectorId)?.bootStatus;
       } else if (this.getConnectorStatus(connectorId)?.status) {
         // Set previous status at startup
-        connectorStatus = this.getConnectorStatus(connectorId).status;
+        connectorStatus = this.getConnectorStatus(connectorId)?.status;
       } else {
         // Set default status
         connectorStatus = ConnectorStatusEnum.AVAILABLE;
@@ -1870,7 +1871,7 @@ export default class ChargingStation {
             ConnectorStatusEnum.UNAVAILABLE
           )
         );
-        this.getConnectorStatus(connectorId).status = null;
+        this.getConnectorStatus(connectorId).status = undefined;
       }
     }
   }
@@ -1884,13 +1885,13 @@ export default class ChargingStation {
           ChargingStationConfigurationUtils.getConfigurationKey(
             this,
             StandardParametersKey.WebSocketPingInterval
-          ).value
+          )?.value
         )
       : 0;
     if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) {
       this.webSocketPingSetInterval = setInterval(() => {
         if (this.isWebSocketConnectionOpened() === true) {
-          this.wsConnection.ping();
+          this.wsConnection?.ping();
         }
       }, webSocketPingInterval * 1000);
       logger.info(
@@ -1922,7 +1923,7 @@ export default class ChargingStation {
   }
 
   private getConfiguredSupervisionUrl(): URL {
-    const supervisionUrls = this.stationInfo.supervisionUrls ?? Configuration.getSupervisionUrls();
+    const supervisionUrls = this.stationInfo?.supervisionUrls ?? Configuration.getSupervisionUrls();
     if (!Utils.isEmptyArray(supervisionUrls)) {
       switch (Configuration.getSupervisionUrlDistribution()) {
         case SupervisionUrlDistribution.ROUND_ROBIN:
@@ -1983,14 +1984,14 @@ export default class ChargingStation {
 
   private terminateWSConnection(): void {
     if (this.isWebSocketConnectionOpened() === true) {
-      this.wsConnection.terminate();
+      this.wsConnection?.terminate();
       this.wsConnection = null;
     }
   }
 
   private stopMeterValues(connectorId: number) {
     if (this.getConnectorStatus(connectorId)?.transactionSetInterval) {
-      clearInterval(this.getConnectorStatus(connectorId).transactionSetInterval);
+      clearInterval(this.getConnectorStatus(connectorId)?.transactionSetInterval);
     }
   }
 
index 4bae70f2e60bd94a46f7141b5aa825bd6609917c..e31e6bfb010f44fffde1580d7a63d7ae178307c9 100644 (file)
@@ -17,7 +17,7 @@ export class ChargingStationConfigurationUtils {
     key: string | StandardParametersKey,
     caseInsensitive = false
   ): ConfigurationKey | undefined {
-    return chargingStation.ocppConfiguration.configurationKey?.find(configElement => {
+    return chargingStation.ocppConfiguration?.configurationKey?.find((configElement) => {
       if (caseInsensitive) {
         return configElement.key.toLowerCase() === key.toLowerCase();
       }
@@ -48,7 +48,7 @@ export class ChargingStationConfigurationUtils {
       keyFound = undefined;
     }
     if (!keyFound) {
-      chargingStation.ocppConfiguration.configurationKey?.push({
+      chargingStation.ocppConfiguration?.configurationKey?.push({
         key,
         readonly: options.readonly,
         value,
@@ -99,7 +99,7 @@ export class ChargingStationConfigurationUtils {
       params?.caseInsensitive
     );
     if (keyFound) {
-      const deletedConfigurationKey = chargingStation.ocppConfiguration.configurationKey.splice(
+      const deletedConfigurationKey = chargingStation.ocppConfiguration?.configurationKey?.splice(
         chargingStation.ocppConfiguration.configurationKey.indexOf(keyFound),
         1
       );
index 8d6cb1c62ac7ff647f1cbbf8a6cf6a240c1520ea..28c23cf848198c746c51ca043770e2e14c38ac99 100644 (file)
@@ -92,12 +92,12 @@ export default class ChargingStationWorkerBroadcastChannel extends WorkerBroadca
       [
         BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
         (requestPayload?: BroadcastChannelRequestPayload) =>
-          this.chargingStation.startAutomaticTransactionGenerator(requestPayload.connectorIds),
+          this.chargingStation.startAutomaticTransactionGenerator(requestPayload?.connectorIds),
       ],
       [
         BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
         (requestPayload?: BroadcastChannelRequestPayload) =>
-          this.chargingStation.stopAutomaticTransactionGenerator(requestPayload.connectorIds),
+          this.chargingStation.stopAutomaticTransactionGenerator(requestPayload?.connectorIds),
       ],
       [
         BroadcastChannelProcedureName.START_TRANSACTION,
@@ -278,7 +278,7 @@ export default class ChargingStationWorkerBroadcastChannel extends WorkerBroadca
       if (
         commandResponse === undefined ||
         commandResponse === null ||
-        Utils.isEmptyObject(commandResponse as CommandResponse)
+        Utils.isEmptyObject(commandResponse)
       ) {
         responsePayload = {
           hashId: this.chargingStation.stationInfo.hashId,
@@ -288,7 +288,7 @@ export default class ChargingStationWorkerBroadcastChannel extends WorkerBroadca
         responsePayload = this.commandResponseToResponsePayload(
           command,
           requestPayload,
-          commandResponse as CommandResponse
+          commandResponse
         );
       }
     } catch (error) {
index fa9236abad6f478c6fa043c3bf611248b2c27820..0e84b3a120af43f277445b3ed3f98327fbb90862 100644 (file)
@@ -47,7 +47,7 @@ export default class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChan
       this.responses.get(uuid)?.responsesReceived <= this.responses.get(uuid)?.responsesExpected
     ) {
       this.responses.get(uuid).responsesReceived++;
-      this.responses.get(uuid).responses.push(responsePayload);
+      this.responses.get(uuid)?.responses.push(responsePayload);
     }
     if (
       this.responses.get(uuid)?.responsesReceived === this.responses.get(uuid)?.responsesExpected
@@ -74,7 +74,7 @@ export default class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChan
             return hashId;
           }
         })
-        .filter(hashId => hashId !== undefined),
+        .filter((hashId) => hashId !== undefined),
       ...(responsesStatus === ResponseStatus.FAILURE && {
         hashIdsFailed: this.responses
           .get(uuid)
@@ -83,17 +83,17 @@ export default class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChan
               return hashId;
             }
           })
-          .filter(hashId => hashId !== undefined),
+          .filter((hashId) => hashId !== undefined),
       }),
       ...(responsesStatus === ResponseStatus.FAILURE && {
         responsesFailed: this.responses
           .get(uuid)
-          ?.responses.map(response => {
+          ?.responses.map((response) => {
             if (response.status === ResponseStatus.FAILURE) {
               return response;
             }
           })
-          .filter(response => response !== undefined),
+          .filter((response) => response !== undefined),
       }),
     };
   }
index 4deabe4f0a099157b1ea7b77020547b8f350a007..f81c27edeae3ed70cf8e71e81ee91e37443f51c2 100644 (file)
@@ -572,7 +572,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
       return OCPPConstants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN;
     }
     const connectorStatus = chargingStation.getConnectorStatus(commandPayload.connectorId);
-    if (commandPayload.connectorId && !Utils.isEmptyArray(connectorStatus.chargingProfiles)) {
+    if (commandPayload.connectorId && !Utils.isEmptyArray(connectorStatus?.chargingProfiles)) {
       connectorStatus.chargingProfiles = [];
       logger.debug(
         `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${
@@ -584,10 +584,12 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
     if (!commandPayload.connectorId) {
       let clearedCP = false;
       for (const connectorId of chargingStation.connectors.keys()) {
-        if (!Utils.isEmptyArray(chargingStation.getConnectorStatus(connectorId).chargingProfiles)) {
+        if (
+          !Utils.isEmptyArray(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles)
+        ) {
           chargingStation
             .getConnectorStatus(connectorId)
-            .chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
+            ?.chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
               let clearCurrentCP = false;
               if (chargingProfile.chargingProfileId === commandPayload.id) {
                 clearCurrentCP = true;
@@ -611,7 +613,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
                 clearCurrentCP = true;
               }
               if (clearCurrentCP) {
-                connectorStatus.chargingProfiles.splice(index, 1);
+                connectorStatus?.chargingProfiles?.splice(index, 1);
                 logger.debug(
                   `${chargingStation.logPrefix()} Matching charging profile(s) cleared: %j`,
                   chargingProfile
@@ -718,7 +720,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
               .getAuthorizedTags(
                 ChargingStationUtils.getAuthorizationFile(chargingStation.stationInfo)
               )
-              .find(idTag => idTag === commandPayload.idTag)
+              ?.find((idTag) => idTag === commandPayload.idTag)
           ) {
             connectorStatus.localAuthorizeIdTag = commandPayload.idTag;
             connectorStatus.idTagLocalAuthorized = true;
@@ -836,7 +838,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
     idTag: string
   ): Promise<GenericResponse> {
     if (
-      chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE
+      chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.AVAILABLE
     ) {
       await chargingStation.ocppRequestService.requestHandler<
         OCPP16StatusNotificationRequest,
@@ -850,8 +852,8 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
     }
     logger.warn(
       `${chargingStation.logPrefix()} Remote starting transaction REJECTED on connector Id ${connectorId.toString()}, idTag '${idTag}', availability '${
-        chargingStation.getConnectorStatus(connectorId).availability
-      }', status '${chargingStation.getConnectorStatus(connectorId).status}'`
+        chargingStation.getConnectorStatus(connectorId)?.availability
+      }', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`
     );
     return OCPPConstants.OCPP_RESPONSE_REJECTED;
   }
@@ -942,7 +944,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
     }
     const retrieveDate = Utils.convertToDate(commandPayload.retrieveDate);
     const now = Date.now();
-    if (retrieveDate.getTime() <= now) {
+    if (retrieveDate?.getTime() <= now) {
       this.asyncResource
         .runInAsyncScope(
           this.updateFirmware.bind(this) as (
@@ -960,7 +962,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
         this.updateFirmware(chargingStation).catch(() => {
           /* Intentional */
         });
-      }, retrieveDate.getTime() - now);
+      }, retrieveDate?.getTime() - now);
     }
     return OCPPConstants.OCPP_RESPONSE_EMPTY;
   }
@@ -974,7 +976,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
     for (const connectorId of chargingStation.connectors.keys()) {
       if (
         connectorId > 0 &&
-        chargingStation.getConnectorStatus(connectorId).transactionStarted === false
+        chargingStation.getConnectorStatus(connectorId)?.transactionStarted === false
       ) {
         await chargingStation.ocppRequestService.requestHandler<
           OCPP16StatusNotificationRequest,
@@ -1051,8 +1053,8 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
       try {
         const logFiles = fs
           .readdirSync(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../'))
-          .filter(file => file.endsWith('.log'))
-          .map(file => path.join('./', file));
+          .filter((file) => file.endsWith('.log'))
+          .map((file) => path.join('./', file));
         const diagnosticsArchive = `${chargingStation.stationInfo.chargingStationId}_logs.tar.gz`;
         tar.create({ gzip: true }, logFiles).pipe(fs.createWriteStream(diagnosticsArchive));
         ftpClient = new Client();
@@ -1064,7 +1066,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
         });
         let uploadResponse: FTPResponse;
         if (accessResponse.code === 220) {
-          ftpClient.trackProgress(info => {
+          ftpClient.trackProgress((info) => {
             logger.info(
               `${chargingStation.logPrefix()} ${
                 info.bytes / 1024
@@ -1077,7 +1079,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
               >(chargingStation, OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, {
                 status: OCPP16DiagnosticsStatus.Uploading,
               })
-              .catch(error => {
+              .catch((error) => {
                 logger.error(
                   `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${
                     OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION
@@ -1190,7 +1192,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
                 chargingStation.bootNotificationRequest,
                 { skipBufferingOnError: true, triggerMessage: true }
               )
-              .then(response => {
+              .then((response) => {
                 chargingStation.bootNotificationResponse = response;
               })
               .catch(() => {
@@ -1224,7 +1226,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
                   {
                     connectorId: commandPayload.connectorId,
                     errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
-                    status: chargingStation.getConnectorStatus(commandPayload.connectorId).status,
+                    status: chargingStation.getConnectorStatus(commandPayload.connectorId)?.status,
                   },
                   {
                     triggerMessage: true,
@@ -1245,7 +1247,7 @@ export default class OCPP16IncomingRequestService extends OCPPIncomingRequestSer
                     {
                       connectorId,
                       errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
-                      status: chargingStation.getConnectorStatus(connectorId).status,
+                      status: chargingStation.getConnectorStatus(connectorId)?.status,
                     },
                     {
                       triggerMessage: true,
index 330f6672542c67151d54f4666da19e0f20753ec0..2b40ad4165556f510ec83d09628ea526ea29b8fa 100644 (file)
@@ -400,65 +400,65 @@ export default class OCPP16ResponseService extends OCPPResponseService {
         break;
       }
     }
-    if (!transactionConnectorId) {
+    if (Utils.isNullOrUndefined(transactionConnectorId)) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction on a non existing connector Id ${connectorId.toString()}`
       );
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true &&
+      chargingStation.getConnectorStatus(connectorId)?.transactionRemoteStarted === true &&
       chargingStation.getAuthorizeRemoteTxRequests() === true &&
       chargingStation.getLocalAuthListEnabled() === true &&
       chargingStation.hasAuthorizedTags() &&
-      chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false
+      chargingStation.getConnectorStatus(connectorId)?.idTagLocalAuthorized === false
     ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction with a not local authorized idTag ${
-          chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag
+          chargingStation.getConnectorStatus(connectorId)?.localAuthorizeIdTag
         } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true &&
+      chargingStation.getConnectorStatus(connectorId)?.transactionRemoteStarted === true &&
       chargingStation.getAuthorizeRemoteTxRequests() === true &&
       chargingStation.getMustAuthorizeAtRemoteStart() === true &&
-      chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false &&
-      chargingStation.getConnectorStatus(connectorId).idTagAuthorized === false
+      chargingStation.getConnectorStatus(connectorId)?.idTagLocalAuthorized === false &&
+      chargingStation.getConnectorStatus(connectorId)?.idTagAuthorized === false
     ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction with a not authorized idTag ${
-          chargingStation.getConnectorStatus(connectorId).authorizeIdTag
+          chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag
         } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).idTagAuthorized &&
-      chargingStation.getConnectorStatus(connectorId).authorizeIdTag !== requestPayload.idTag
+      chargingStation.getConnectorStatus(connectorId)?.idTagAuthorized &&
+      chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag !== requestPayload.idTag
     ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${
           requestPayload.idTag
         } different from the authorize request one ${
-          chargingStation.getConnectorStatus(connectorId).authorizeIdTag
+          chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag
         } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
       return;
     }
     if (
-      chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized &&
-      chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag !== requestPayload.idTag
+      chargingStation.getConnectorStatus(connectorId)?.idTagLocalAuthorized &&
+      chargingStation.getConnectorStatus(connectorId)?.localAuthorizeIdTag !== requestPayload.idTag
     ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${
           requestPayload.idTag
         } different from the local authorized one ${
-          chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag
+          chargingStation.getConnectorStatus(connectorId)?.localAuthorizeIdTag
         } on connector Id ${connectorId.toString()}`
       );
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
@@ -558,7 +558,7 @@ export default class OCPP16ResponseService extends OCPPResponseService {
   ): Promise<void> {
     chargingStation.resetConnectorStatus(connectorId);
     if (
-      chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE
+      chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.AVAILABLE
     ) {
       await chargingStation.ocppRequestService.requestHandler<
         OCPP16StatusNotificationRequest,
index 15b914c39e36db78bb0c5915c850febe929e49b9..65fc51c527302969e3335b61533390ae415a4737 100644 (file)
@@ -84,7 +84,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
           `${chargingStation.logPrefix()} MeterValues measurand ${
             meterValue.sampledValue[sampledValuesIndex].measurand ??
             OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
-          }: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${
+          }: connectorId ${connectorId}, transaction ${connector?.transactionId}, value: ${
             meterValue.sampledValue[sampledValuesIndex].value
           }/100`
         );
@@ -145,7 +145,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
           OCPP16ServiceUtils.buildSampledValue(
             voltagePhaseLineToNeutralSampledValueTemplate ?? voltageSampledValueTemplate,
             voltagePhaseLineToNeutralMeasurandValue ?? voltageMeasurandValue,
-            null,
+            undefined,
             phaseLineToNeutralValue as OCPP16MeterValuePhase
           )
         );
@@ -184,7 +184,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
             OCPP16ServiceUtils.buildSampledValue(
               voltagePhaseLineToLineSampledValueTemplate ?? voltageSampledValueTemplate,
               voltagePhaseLineToLineMeasurandValue ?? defaultVoltagePhaseLineToLineMeasurandValue,
-              null,
+              undefined,
               phaseLineToLineValue as OCPP16MeterValuePhase
             )
           );
@@ -355,7 +355,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
           `${chargingStation.logPrefix()} MeterValues measurand ${
             meterValue.sampledValue[sampledValuesIndex].measurand ??
             OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
-          }: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${
+          }: connectorId ${connectorId}, transaction ${connector?.transactionId}, value: ${
             meterValue.sampledValue[sampledValuesIndex].value
           }/${connectorMaximumPowerRounded}`
         );
@@ -371,7 +371,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
             (powerPerPhaseSampledValueTemplates[`L${phase}`] as SampledValueTemplate) ??
               powerSampledValueTemplate,
             powerMeasurandValues[`L${phase}`] as number,
-            null,
+            undefined,
             phaseValue as OCPP16MeterValuePhase
           )
         );
@@ -391,7 +391,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
               OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
             }: phase ${
               meterValue.sampledValue[sampledValuesPerPhaseIndex].phase
-            }, connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${
+            }, connectorId ${connectorId}, transaction ${connector?.transactionId}, value: ${
               meterValue.sampledValue[sampledValuesPerPhaseIndex].value
             }/${connectorMaximumPowerPerPhaseRounded}`
           );
@@ -567,7 +567,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
           `${chargingStation.logPrefix()} MeterValues measurand ${
             meterValue.sampledValue[sampledValuesIndex].measurand ??
             OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
-          }: connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${
+          }: connectorId ${connectorId}, transaction ${connector?.transactionId}, value: ${
             meterValue.sampledValue[sampledValuesIndex].value
           }/${connectorMaximumAmperage}`
         );
@@ -583,7 +583,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
             (currentPerPhaseSampledValueTemplates[phaseValue] as SampledValueTemplate) ??
               currentSampledValueTemplate,
             currentMeasurandValues[phaseValue] as number,
-            null,
+            undefined,
             phaseValue as OCPP16MeterValuePhase
           )
         );
@@ -599,7 +599,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
               OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
             }: phase ${
               meterValue.sampledValue[sampledValuesPerPhaseIndex].phase
-            }, connectorId ${connectorId}, transaction ${connector.transactionId}, value: ${
+            }, connectorId ${connectorId}, transaction ${connector?.transactionId}, value: ${
               meterValue.sampledValue[sampledValuesPerPhaseIndex].value
             }/${connectorMaximumAmperage}`
           );
@@ -669,7 +669,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
             meterValue.sampledValue[sampledValuesIndex].measurand ??
             OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER
           }: connectorId ${connectorId}, transaction ${
-            connector.transactionId
+            connector?.transactionId
           }, value: ${energyValueRounded}/${connectorMaximumEnergyRounded}, duration: ${Utils.roundTo(
             interval / (3600 * 1000),
             4
@@ -745,23 +745,27 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
     connectorId: number,
     cp: OCPP16ChargingProfile
   ): void {
-    if (Utils.isNullOrUndefined(chargingStation.getConnectorStatus(connectorId).chargingProfiles)) {
+    if (
+      Utils.isNullOrUndefined(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles)
+    ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`
       );
       chargingStation.getConnectorStatus(connectorId).chargingProfiles = [];
     }
-    if (Array.isArray(chargingStation.getConnectorStatus(connectorId).chargingProfiles) === false) {
+    if (
+      Array.isArray(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles) === false
+    ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to set a charging profile on connectorId ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`
       );
       chargingStation.getConnectorStatus(connectorId).chargingProfiles = [];
     }
     let cpReplaced = false;
-    if (!Utils.isEmptyArray(chargingStation.getConnectorStatus(connectorId).chargingProfiles)) {
+    if (!Utils.isEmptyArray(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles)) {
       chargingStation
         .getConnectorStatus(connectorId)
-        .chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
+        ?.chargingProfiles?.forEach((chargingProfile: OCPP16ChargingProfile, index: number) => {
           if (
             chargingProfile.chargingProfileId === cp.chargingProfileId ||
             (chargingProfile.stackLevel === cp.stackLevel &&
@@ -772,7 +776,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
           }
         });
     }
-    !cpReplaced && chargingStation.getConnectorStatus(connectorId).chargingProfiles?.push(cp);
+    !cpReplaced && chargingStation.getConnectorStatus(connectorId)?.chargingProfiles?.push(cp);
   }
 
   private static buildSampledValue(
index dbf478ece1252a803c618929d05460f87313129d..fc4410f8658653b16e5305b8251441fe0577ae55 100644 (file)
@@ -68,7 +68,7 @@ export default abstract class OCPPRequestService {
     messageId: string,
     messagePayload: JsonType,
     commandName: IncomingRequestCommand
-  ): Promise<ResponseType> {
+  ): Promise<ResponseType | undefined> {
     try {
       // Send response message
       return await this.internalSendMessage(
@@ -211,7 +211,7 @@ export default abstract class OCPPRequestService {
     messageId: string,
     messagePayload: JsonType | OCPPError,
     messageType: MessageType,
-    commandName?: RequestCommand | IncomingRequestCommand,
+    commandName: RequestCommand | IncomingRequestCommand,
     params: RequestParams = {
       skipBufferingOnError: false,
       triggerMessage: false,
@@ -249,7 +249,7 @@ export default abstract class OCPPRequestService {
           if (wsOpened) {
             const beginId = PerformanceStatistics.beginMeasure(commandName);
             try {
-              chargingStation.wsConnection.send(messageToSend);
+              chargingStation.wsConnection?.send(messageToSend);
               logger.debug(
                 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString(
                   messageType
@@ -322,7 +322,7 @@ export default abstract class OCPPRequestService {
               .then(() => {
                 resolve(payload);
               })
-              .catch(error => {
+              .catch((error) => {
                 reject(error);
               })
               .finally(() => {
@@ -378,9 +378,9 @@ export default abstract class OCPPRequestService {
     messageId: string,
     messagePayload: JsonType | OCPPError,
     messageType: MessageType,
-    commandName?: RequestCommand | IncomingRequestCommand,
-    responseCallback?: ResponseCallback,
-    errorCallback?: ErrorCallback
+    commandName: RequestCommand | IncomingRequestCommand,
+    responseCallback: ResponseCallback,
+    errorCallback: ErrorCallback
   ): string {
     let messageToSend: string;
     // Type of message
index 04ca704648a0170b588faae68753ef3102e88bbc..15edd6dfef63a731370d62dfa76e466abeeeabed 100644 (file)
@@ -182,7 +182,7 @@ export class OCPPServiceUtils {
       ChargingStationConfigurationUtils.getConfigurationKey(
         chargingStation,
         StandardParametersKey.MeterValuesSampledData
-      )?.value.includes(measurand) === false
+      )?.value?.includes(measurand) === false
     ) {
       logger.debug(
         `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
@@ -192,7 +192,7 @@ export class OCPPServiceUtils {
       return;
     }
     const sampledValueTemplates: SampledValueTemplate[] =
-      chargingStation.getConnectorStatus(connectorId).MeterValues;
+      chargingStation.getConnectorStatus(connectorId)?.MeterValues;
     for (
       let index = 0;
       Utils.isEmptyArray(sampledValueTemplates) === false && index < sampledValueTemplates.length;
@@ -214,7 +214,7 @@ export class OCPPServiceUtils {
         ChargingStationConfigurationUtils.getConfigurationKey(
           chargingStation,
           StandardParametersKey.MeterValuesSampledData
-        )?.value.includes(measurand) === true
+        )?.value?.includes(measurand) === true
       ) {
         return sampledValueTemplates[index];
       } else if (
@@ -224,7 +224,7 @@ export class OCPPServiceUtils {
         ChargingStationConfigurationUtils.getConfigurationKey(
           chargingStation,
           StandardParametersKey.MeterValuesSampledData
-        )?.value.includes(measurand) === true
+        )?.value?.includes(measurand) === true
       ) {
         return sampledValueTemplates[index];
       } else if (
index da347672df86af76f8c1ce314410161b33e01b89..87f10a5eab41ef30ce19d0dd5211320900d9697e 100644 (file)
@@ -68,7 +68,7 @@ export default class UIHttpServer extends AbstractUIServer {
   }
 
   private requestListener(req: IncomingMessage, res: ServerResponse): void {
-    this.authenticate(req, err => {
+    this.authenticate(req, (err) => {
       if (err) {
         res
           .writeHead(StatusCodes.UNAUTHORIZED, {
@@ -94,7 +94,7 @@ export default class UIHttpServer extends AbstractUIServer {
         throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`);
       }
       this.registerProtocolVersionUIService(version);
-      req.on('error', error => {
+      req.on('error', (error) => {
         logger.error(
           `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
           error
@@ -103,7 +103,7 @@ export default class UIHttpServer extends AbstractUIServer {
       if (req.method === 'POST') {
         const bodyBuffer = [];
         req
-          .on('data', chunk => {
+          .on('data', (chunk) => {
             bodyBuffer.push(chunk);
           })
           .on('end', () => {
index 006c3914b8a67f6c7368345c8b747631698cdcbe..e217305f2e1e42f9644ad25f1467aceab57fa12b 100644 (file)
@@ -39,7 +39,7 @@ export default class UIWebSocketServer extends AbstractUIServer {
       }
       const [, version] = UIServerUtils.getProtocolAndVersion(ws.protocol);
       this.registerProtocolVersionUIService(version);
-      ws.on('message', rawData => {
+      ws.on('message', (rawData) => {
         const request = this.validateRawDataRequest(rawData);
         if (request === false) {
           ws.close(WebSocketCloseEventStatusCode.CLOSE_INVALID_PAYLOAD);
@@ -54,7 +54,7 @@ export default class UIWebSocketServer extends AbstractUIServer {
             /* Error caught by AbstractUIService */
           });
       });
-      ws.on('error', error => {
+      ws.on('error', (error) => {
         logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error);
       });
       ws.on('close', (code, reason) => {
@@ -78,7 +78,7 @@ export default class UIWebSocketServer extends AbstractUIServer {
     this.httpServer.on(
       'upgrade',
       (req: IncomingMessage, socket: internal.Duplex, head: Buffer): void => {
-        this.authenticate(req, err => {
+        this.authenticate(req, (err) => {
           if (err) {
             socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
             socket.destroy();
index 2b1267f35fd40b4584f29d87379782ebe3d419b7..5a418b9d4baf53cc3032efee92e808971da58626 100644 (file)
@@ -156,7 +156,7 @@ export default abstract class AbstractUIService {
   ): void {
     if (!Utils.isEmptyArray(payload.hashIds)) {
       payload.hashIds = payload.hashIds
-        .map(hashId => {
+        .map((hashId) => {
           if (this.uiServer.chargingStations.has(hashId) === true) {
             return hashId;
           }
@@ -167,7 +167,7 @@ export default abstract class AbstractUIService {
             )} Charging station with hashId '${hashId}' not found`
           );
         })
-        .filter(hashId => hashId !== undefined);
+        .filter((hashId) => hashId !== undefined);
     }
     const expectedNumberOfResponses = !Utils.isEmptyArray(payload.hashIds)
       ? payload.hashIds.length
index 6d18e212b265079e4106cfc8049232f36f2a8247..6ac54aa42c451813f22c8d2cd1fe1d6e73979064 100644 (file)
@@ -138,7 +138,7 @@ export default class PerformanceStatistics {
   }
 
   private initializePerformanceObserver(): void {
-    this.performanceObserver = new PerformanceObserver(performanceObserverList => {
+    this.performanceObserver = new PerformanceObserver((performanceObserverList) => {
       const lastPerformanceEntry = performanceObserverList.getEntries()[0];
       // logger.debug(
       //   `${this.logPrefix()} '${lastPerformanceEntry.name}' performance entry: %j`,
@@ -168,7 +168,7 @@ export default class PerformanceStatistics {
       );
     } else {
       logger.info(
-        `${this.logPrefix()} log interval is set to ${Configuration.getLogStatisticsInterval().toString()}. Not logging statistics`
+        `${this.logPrefix()} log interval is set to ${Configuration.getLogStatisticsInterval()?.toString()}. Not logging statistics`
       );
     }
   }
@@ -253,10 +253,10 @@ export default class PerformanceStatistics {
     this.statistics.statisticsData.get(entryName).avgTimeMeasurement =
       this.statistics.statisticsData.get(entryName).totalTimeMeasurement /
       this.statistics.statisticsData.get(entryName).countTimeMeasurement;
-    Array.isArray(this.statistics.statisticsData.get(entryName).timeMeasurementSeries) === true
+    Array.isArray(this.statistics.statisticsData.get(entryName)?.timeMeasurementSeries) === true
       ? this.statistics.statisticsData
           .get(entryName)
-          .timeMeasurementSeries.push({ timestamp: entry.startTime, value: entry.duration })
+          ?.timeMeasurementSeries?.push({ timestamp: entry.startTime, value: entry.duration })
       : (this.statistics.statisticsData.get(entryName).timeMeasurementSeries =
           new CircularArray<TimeSeries>(DEFAULT_CIRCULAR_ARRAY_SIZE, {
             timestamp: entry.startTime,
@@ -287,7 +287,7 @@ export default class PerformanceStatistics {
   }
 
   private extractTimeSeriesValues(timeSeries: CircularArray<TimeSeries>): number[] {
-    return timeSeries.map(timeSeriesItem => timeSeriesItem.value);
+    return timeSeries.map((timeSeriesItem) => timeSeriesItem.value);
   }
 
   private logPrefix(): string {
index 94c36eddac1ea5012d81d22d314f52dfa8edc12f..63d12a439a0aa6a54283b4717ce93ce0e1ba596a 100644 (file)
@@ -22,7 +22,7 @@ export class JsonFileStorage extends Storage {
     this.checkPerformanceRecordsFile();
     lockfile
       .lock(this.dbName, { stale: 5000, retries: 3 })
-      .then(async release => {
+      .then(async (release) => {
         try {
           const fileData = fs.readFileSync(this.dbName, 'utf8');
           const performanceRecords: Statistics[] = fileData
index 54fc43349b2f3cbe8dbabc36ec3cd53dbc692936..9e5c06623830e3328979f88637ecc55571a012c7 100644 (file)
@@ -24,7 +24,7 @@ export class MongoDBStorage extends Storage {
     try {
       this.checkDBConnection();
       await this.client
-        .db(this.dbName)
+        ?.db(this.dbName)
         .collection<Statistics>(Constants.PERFORMANCE_RECORDS_TABLE)
         .insertOne(performanceStatistics);
     } catch (error) {
index a21f7fcf07b59c80e341c1f864b3124d74d4ce31..8eca3a4a11e093983b7ab8f499b2c6406175a2fa 100644 (file)
@@ -6,6 +6,6 @@ import { Bootstrap } from './internal';
 
 Bootstrap.getInstance()
   .start()
-  .catch(error => {
+  .catch((error) => {
     console.error(chalk.red(error));
   });
index a67c70c25908c196019f7a344ac7cf34467a6c2f..1c51bbfd0d4fc0c681c8b76c165413a43b4b9d20 100644 (file)
@@ -72,7 +72,7 @@ export default class Configuration {
       uiServerConfiguration = merge(uiServerConfiguration, Configuration.getConfig()?.uiServer);
     }
     if (Configuration.isCFEnvironment() === true) {
-      delete uiServerConfiguration.options.host;
+      delete uiServerConfiguration.options?.host;
       uiServerConfiguration.options.port = parseInt(process.env.PORT);
     }
     return uiServerConfiguration;
@@ -377,7 +377,7 @@ export default class Configuration {
           // Nullify to force configuration file reading
           Configuration.configuration = null;
           if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
-            Configuration.configurationChangeCallback().catch(error => {
+            Configuration.configurationChangeCallback().catch((error) => {
               throw typeof error === 'string' ? new Error(error) : error;
             });
           }
index 5fb5f62573448fb3bab45174e4b1afb14f4acc90..6557a588446455506656c7f7133e8fe85c5881f0 100644 (file)
@@ -26,7 +26,7 @@ export default class Utils {
   }
 
   public static async sleep(milliSeconds: number): Promise<NodeJS.Timeout> {
-    return new Promise(resolve => setTimeout(resolve as () => void, milliSeconds));
+    return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds));
   }
 
   public static formatDurationMilliSeconds(duration: number): string {
@@ -197,7 +197,7 @@ export default class Utils {
   }
 
   public static isUndefined(value: unknown): boolean {
-    return typeof value === 'undefined';
+    return value === undefined;
   }
 
   public static isNullOrUndefined(value: unknown): boolean {
index 0fccdb812d7ed4c2a40b28596a3cfc883ed606e3..aeb1b86afec93810ed825243e738b96bf05d1700 100644 (file)
@@ -7,7 +7,7 @@ export default abstract class WorkerAbstract<T extends WorkerData> {
   protected readonly workerScript: string;
   protected readonly workerOptions: WorkerOptions;
   public abstract readonly size: number;
-  public abstract readonly maxElementsPerWorker: number | null;
+  public abstract readonly maxElementsPerWorker: number | undefined;
 
   /**
    * `WorkerAbstract` constructor.
index f842614f82b20e6476e949f22bda5d797404f5a3..9926a09eab4e7162af72285bde4d6eec7af9e6de 100644 (file)
@@ -37,8 +37,8 @@ export default class WorkerDynamicPool extends WorkerAbstract<WorkerData> {
     return this.pool.workers.length;
   }
 
-  get maxElementsPerWorker(): number | null {
-    return null;
+  get maxElementsPerWorker(): number | undefined {
+    return undefined;
   }
 
   /**
index 76d759a2c33ee7d21b553179ab479e6ffecb38cd..c5b2d84a7797bbc12ccb6dfe3c0bfc635ebc031f 100644 (file)
@@ -31,7 +31,7 @@ export default class WorkerSet extends WorkerAbstract<WorkerData> {
     return this.workerSet.size;
   }
 
-  get maxElementsPerWorker(): number | null {
+  get maxElementsPerWorker(): number | undefined {
     return this.workerOptions.elementsPerWorker;
   }
 
@@ -98,7 +98,7 @@ export default class WorkerSet extends WorkerAbstract<WorkerData> {
       ).bind(this) as MessageHandler<Worker>
     );
     worker.on('error', WorkerUtils.defaultErrorHandler.bind(this) as (err: Error) => void);
-    worker.on('exit', code => {
+    worker.on('exit', (code) => {
       WorkerUtils.defaultExitHandler(code);
       this.workerSet.delete(this.getWorkerSetElementByWorker(worker));
     });
index 2dd2bc8095dd15c8ccf399df2eaee695cbc14190..2ec049e15514d356fbb0b787c43f48e3efd9d1ff 100644 (file)
@@ -36,8 +36,8 @@ export default class WorkerStaticPool extends WorkerAbstract<WorkerData> {
     return this.pool.workers.length;
   }
 
-  get maxElementsPerWorker(): number | null {
-    return null;
+  get maxElementsPerWorker(): number | undefined {
+    return undefined;
   }
 
   /**
index 056e2ce27cef9ddfb051ece83ee2266acc66339d..e78836fd51b7b18cdefa36b3f73c5a94e76ca191 100644 (file)
@@ -112,10 +112,10 @@ export default class UIClient {
       config.uiServer.protocol
     );
     this._ws.onmessage = this.responseHandler.bind(this);
-    this._ws.onerror = errorEvent => {
+    this._ws.onerror = (errorEvent) => {
       console.error('WebSocket error: ', errorEvent);
     };
-    this._ws.onclose = closeEvent => {
+    this._ws.onclose = (closeEvent) => {
       console.info('WebSocket closed: ', closeEvent);
     };
   }