refactor: cleanup some unneeded conditions
authorJérôme Benoit <jerome.benoit@sap.com>
Thu, 4 Jan 2024 13:18:29 +0000 (14:18 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Thu, 4 Jan 2024 13:18:29 +0000 (14:18 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/ChargingStation.ts
src/charging-station/Helpers.ts
src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts
src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts
src/charging-station/ocpp/OCPPServiceUtils.ts
src/performance/PerformanceStatistics.ts

index 6513f68b19e3d8397bb999bd5f7bf0c661e8f311..a57b5bd46545057ddbbe28e3d29e0b2a781a9c9a 100644 (file)
@@ -346,10 +346,11 @@ export class ChargingStation extends EventEmitter {
 
   public getConnectorMaximumAvailablePower (connectorId: number): number {
     let connectorAmperageLimitationPowerLimit: number | undefined
+    const amperageLimitation = this.getAmperageLimitation()
     if (
-      this.getAmperageLimitation() != null &&
+      amperageLimitation != null &&
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      this.getAmperageLimitation()! < this.stationInfo!.maximumAmperage!
+      amperageLimitation < this.stationInfo!.maximumAmperage!
     ) {
       connectorAmperageLimitationPowerLimit =
         (this.stationInfo?.currentOutType === CurrentType.AC
@@ -357,12 +358,11 @@ export class ChargingStation extends EventEmitter {
             this.getNumberOfPhases(),
             // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
             this.stationInfo.voltageOut!,
-            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            this.getAmperageLimitation()! *
+            amperageLimitation *
                 (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors())
           )
           : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-          DCElectricUtils.power(this.stationInfo!.voltageOut!, this.getAmperageLimitation()!)) /
+          DCElectricUtils.power(this.stationInfo!.voltageOut!, amperageLimitation)) /
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         this.powerDivider!
     }
@@ -855,7 +855,8 @@ export class ChargingStation extends EventEmitter {
     connectorId: number,
     reason?: StopTransactionReason
   ): Promise<StopTransactionResponse> {
-    const transactionId = this.getConnectorStatus(connectorId)?.transactionId
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    const transactionId = this.getConnectorStatus(connectorId)!.transactionId!
     if (
       this.stationInfo?.beginEndMeterValues === true &&
       this.stationInfo.ocppStrictCompliance === true &&
@@ -864,8 +865,7 @@ export class ChargingStation extends EventEmitter {
       const transactionEndMeterValue = buildTransactionEndMeterValue(
         this,
         connectorId,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        this.getEnergyActiveImportRegisterByTransactionId(transactionId!)
+        this.getEnergyActiveImportRegisterByTransactionId(transactionId)
       )
       await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
         this,
@@ -882,8 +882,7 @@ export class ChargingStation extends EventEmitter {
     StopTransactionResponse
     >(this, RequestCommand.STOP_TRANSACTION, {
       transactionId,
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId!, true),
+      meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true),
       ...(reason != null && { reason })
     })
   }
@@ -1168,9 +1167,11 @@ export class ChargingStation extends EventEmitter {
     // Priority:
     // 1. charging station info from template
     // 2. charging station info from configuration file
-    if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      return { ...defaultStationInfo, ...stationInfoFromFile! }
+    if (
+      stationInfoFromFile != null &&
+      stationInfoFromFile.templateHash === stationInfoFromTemplate.templateHash
+    ) {
+      return { ...defaultStationInfo, ...stationInfoFromFile }
     }
     stationInfoFromFile != null &&
       propagateSerialNumber(
@@ -1217,7 +1218,7 @@ export class ChargingStation extends EventEmitter {
       isNotEmptyString(this.stationInfo.firmwareVersion) &&
       isNotEmptyString(this.stationInfo.firmwareVersionPattern)
     ) {
-      const patternGroup: number | undefined =
+      const patternGroup =
         this.stationInfo.firmwareUpgrade?.versionUpgrade?.patternGroup ??
         this.stationInfo.firmwareVersion?.split('.').length
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -1241,12 +1242,17 @@ export class ChargingStation extends EventEmitter {
     if (this.stationInfo.enableStatistics === true) {
       this.performanceStatistics = PerformanceStatistics.getInstance(
         this.stationInfo.hashId,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        this.stationInfo.chargingStationId!,
+        this.stationInfo.chargingStationId,
         this.configuredSupervisionUrl
       )
     }
-    this.bootNotificationRequest = createBootNotificationRequest(this.stationInfo)
+    const bootNotificationRequest = createBootNotificationRequest(this.stationInfo)
+    if (bootNotificationRequest == null) {
+      const errorMsg = 'Error while creating boot notification request'
+      logger.error(`${this.logPrefix()} ${errorMsg}`)
+      throw new BaseError(errorMsg)
+    }
+    this.bootNotificationRequest = bootNotificationRequest
     this.powerDivider = this.getPowerDivider()
     // OCPP configuration
     this.ocppConfiguration = this.getOcppConfiguration()
@@ -1322,7 +1328,7 @@ export class ChargingStation extends EventEmitter {
     if (
       isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) &&
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      getConfigurationKey(this, this.stationInfo!.amperageLimitationOcppKey!) == null
+      getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) == null
     ) {
       addConfigurationKey(
         this,
@@ -1633,10 +1639,10 @@ export class ChargingStation extends EventEmitter {
         if (!existsSync(dirname(this.configurationFile))) {
           mkdirSync(dirname(this.configurationFile), { recursive: true })
         }
+        const configurationFromFile = this.getConfigurationFromFile()
         let configurationData: ChargingStationConfiguration =
-          this.getConfigurationFromFile() != null
-            ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            cloneObject<ChargingStationConfiguration>(this.getConfigurationFromFile()!)
+          configurationFromFile != null
+            ? cloneObject<ChargingStationConfiguration>(configurationFromFile)
             : {}
         if (this.stationInfo?.stationInfoPersistentConfiguration === true) {
           configurationData.stationInfo = this.stationInfo
index 9a5eeb6ea97822f9946d36b672ea82bc1770d51b..ab3a6f6a6dd7a25c08ee4cf80e5f6232a37d3a8a 100644 (file)
@@ -390,9 +390,8 @@ export const resetConnectorStatus = (connectorStatus: ConnectorStatus): void =>
 export const createBootNotificationRequest = (
   stationInfo: ChargingStationInfo,
   bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp
-): BootNotificationRequest => {
-  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-  const ocppVersion = stationInfo.ocppVersion!
+): BootNotificationRequest | undefined => {
+  const ocppVersion = stationInfo.ocppVersion
   switch (ocppVersion) {
     case OCPPVersion.VERSION_16:
       return {
@@ -800,21 +799,21 @@ const getLimitFromChargingProfiles = (
   const connectorStatus = chargingStation.getConnectorStatus(connectorId)!
   for (const chargingProfile of chargingProfiles) {
     const chargingSchedule = chargingProfile.chargingSchedule
-    if (chargingSchedule.startSchedule == null && connectorStatus.transactionStarted === true) {
+    if (chargingSchedule.startSchedule == null) {
       logger.debug(
         `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined. Trying to set it to the connector current transaction start date`
       )
       // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
       chargingSchedule.startSchedule = connectorStatus.transactionStart
     }
-    if (chargingSchedule.startSchedule != null && !isDate(chargingSchedule.startSchedule)) {
+    if (!isDate(chargingSchedule.startSchedule)) {
       logger.warn(
         `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date instance. Trying to convert it to a Date instance`
       )
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
       chargingSchedule.startSchedule = convertToDate(chargingSchedule.startSchedule)!
     }
-    if (chargingSchedule.startSchedule != null && chargingSchedule.duration == null) {
+    if (chargingSchedule.duration == null) {
       logger.debug(
         `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined and will be set to the maximum time allowed`
       )
@@ -830,10 +829,8 @@ const getLimitFromChargingProfiles = (
     // Check if the charging profile is active
     if (
       isWithinInterval(currentDate, {
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        start: chargingSchedule.startSchedule!,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        end: addSeconds(chargingSchedule.startSchedule!, chargingSchedule.duration!)
+        start: chargingSchedule.startSchedule,
+        end: addSeconds(chargingSchedule.startSchedule, chargingSchedule.duration)
       })
     ) {
       if (isNotEmptyArray(chargingSchedule.chargingSchedulePeriod)) {
@@ -877,8 +874,7 @@ const getLimitFromChargingProfiles = (
           // Find the right schedule period
           if (
             isAfter(
-              // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-              addSeconds(chargingSchedule.startSchedule!, chargingSchedulePeriod.startPeriod),
+              addSeconds(chargingSchedule.startSchedule, chargingSchedulePeriod.startPeriod),
               currentDate
             )
           ) {
@@ -899,14 +895,11 @@ const getLimitFromChargingProfiles = (
             (index < chargingSchedule.chargingSchedulePeriod.length - 1 &&
               differenceInSeconds(
                 addSeconds(
-                  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-                  chargingSchedule.startSchedule!,
+                  chargingSchedule.startSchedule,
                   chargingSchedule.chargingSchedulePeriod[index + 1].startPeriod
                 ),
-                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-                chargingSchedule.startSchedule!
-                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-              ) > chargingSchedule.duration!)
+                chargingSchedule.startSchedule
+              ) > chargingSchedule.duration)
           ) {
             const result: ChargingProfilesLimit = {
               limit: previousChargingSchedulePeriod.limit,
index 0cd676472a1d3adf36e901d5700a383476ed3078..e0785d43e9eb265b3af00d5dcf8f6c3d1cd60fb5 100644 (file)
@@ -712,10 +712,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
     let previousCompositeSchedule: OCPP16ChargingSchedule | undefined
     let compositeSchedule: OCPP16ChargingSchedule | undefined
     for (const chargingProfile of chargingProfiles) {
-      if (
-        chargingProfile.chargingSchedule.startSchedule == null &&
-        connectorStatus.transactionStarted === true
-      ) {
+      if (chargingProfile.chargingSchedule.startSchedule == null) {
         logger.debug(
           `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
             chargingProfile.chargingProfileId
@@ -724,10 +721,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
         // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
         chargingProfile.chargingSchedule.startSchedule = connectorStatus.transactionStart
       }
-      if (
-        chargingProfile.chargingSchedule.startSchedule != null &&
-        !isDate(chargingProfile.chargingSchedule.startSchedule)
-      ) {
+      if (!isDate(chargingProfile.chargingSchedule.startSchedule)) {
         logger.warn(
           `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
             chargingProfile.chargingProfileId
@@ -738,10 +732,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
           chargingProfile.chargingSchedule.startSchedule
         )!
       }
-      if (
-        chargingProfile.chargingSchedule.startSchedule != null &&
-        chargingProfile.chargingSchedule.duration == null
-      ) {
+      if (chargingProfile.chargingSchedule.duration == null) {
         logger.debug(
           `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
             chargingProfile.chargingProfileId
index db964227a3d59324cc89dd791d14feb0652c2fce..570708b74be0ba7f30b9f243bc613ccbe25dd584 100644 (file)
@@ -166,9 +166,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
     }
     let cpReplaced = false
     if (isNotEmptyArray(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles)) {
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
       for (const [index, chargingProfile] of chargingStation
-        .getConnectorStatus(connectorId)
-        ?.chargingProfiles?.entries() ?? []) {
+        .getConnectorStatus(connectorId)!
+        .chargingProfiles!.entries()) {
         if (
           chargingProfile.chargingProfileId === cp.chargingProfileId ||
           (chargingProfile.stackLevel === cp.stackLevel &&
index cb802d12c9397b2d787e86258a598376657cb50a..51a9948eec74c033c926ac3a78556fd822b4c802 100644 (file)
@@ -20,7 +20,6 @@ import {
   type AuthorizeResponse,
   ChargePointErrorCode,
   ChargingStationEvents,
-  type ConnectorStatus,
   type ConnectorStatusEnum,
   CurrentType,
   ErrorType,
@@ -123,7 +122,7 @@ export const isIdTagAuthorized = async (
   }
   if (chargingStation.getLocalAuthListEnabled() && isIdTagLocalAuthorized(chargingStation, idTag)) {
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const connectorStatus: ConnectorStatus = chargingStation.getConnectorStatus(connectorId)!
+    const connectorStatus = chargingStation.getConnectorStatus(connectorId)!
     connectorStatus.localAuthorizeIdTag = idTag
     connectorStatus.idTagLocalAuthorized = true
     return true
index 88ea748c635bbdea9023c24819740d8184e749dc..2f10960604a8429a5a059b62d2ed46d44c2bb241 100644 (file)
@@ -6,6 +6,7 @@ import { parentPort } from 'node:worker_threads'
 
 import { secondsToMilliseconds } from 'date-fns'
 
+import { BaseError } from '../exception/index.js'
 import {
   ConfigurationSection,
   type IncomingRequestCommand,
@@ -47,9 +48,9 @@ export class PerformanceStatistics {
   private readonly statistics: Statistics
   private displayInterval?: NodeJS.Timeout
 
-  private constructor (objId: string | undefined, objName: string | undefined, uri: URL) {
-    this.objId = objId ?? 'Object id not specified'
-    this.objName = objName ?? 'Object name not specified'
+  private constructor (objId: string, objName: string, uri: URL) {
+    this.objId = objId
+    this.objName = objName
     this.initializePerformanceObserver()
     this.statistics = {
       id: this.objId,
@@ -61,10 +62,26 @@ export class PerformanceStatistics {
   }
 
   public static getInstance (
-    objId: string,
-    objName: string,
-    uri: URL
+    objId: string | undefined,
+    objName: string | undefined,
+    uri: URL | undefined
   ): PerformanceStatistics | undefined {
+    const logPfx = logPrefix(' Performance statistics')
+    if (objId == null) {
+      const errMsg = 'Cannot get performance statistics instance without specifying object id'
+      logger.error(`${logPfx} ${errMsg}`)
+      throw new BaseError(errMsg)
+    }
+    if (objName == null) {
+      const errMsg = 'Cannot get performance statistics instance without specifying object name'
+      logger.error(`${logPfx} ${errMsg}`)
+      throw new BaseError(errMsg)
+    }
+    if (uri == null) {
+      const errMsg = 'Cannot get performance statistics instance without specifying object uri'
+      logger.error(`${logPfx} ${errMsg}`)
+      throw new BaseError(errMsg)
+    }
     if (!PerformanceStatistics.instances.has(objId)) {
       PerformanceStatistics.instances.set(objId, new PerformanceStatistics(objId, objName, uri))
     }