fix: send preparing connector status before `StartTransaction`
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16ResponseService.ts
index d7d9ce0aab94c2b65496083dca3d0342bd9667d9..e6c3b43472c8ef0975f3e855deebf51b7c013919 100644 (file)
@@ -1,12 +1,11 @@
-// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
+// Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
 
-import type { JSONSchemaType } from 'ajv'
+import type { ValidateFunction } from 'ajv'
 import { secondsToMilliseconds } from 'date-fns'
 
-import { OCPP16ServiceUtils } from './OCPP16ServiceUtils.js'
 import {
-  type ChargingStation,
   addConfigurationKey,
+  type ChargingStation,
   getConfigurationKey,
   hasReservationExpired,
   resetConnectorStatus
@@ -51,23 +50,24 @@ import {
   type SetChargingProfileResponse,
   type UnlockConnectorResponse
 } from '../../../types/index.js'
-import { Constants, convertToInt, isNullOrUndefined, logger } from '../../../utils/index.js'
+import { Constants, convertToInt, isAsyncFunction, logger } from '../../../utils/index.js'
 import { OCPPResponseService } from '../OCPPResponseService.js'
+import { OCPP16ServiceUtils } from './OCPP16ServiceUtils.js'
 
 const moduleName = 'OCPP16ResponseService'
 
 export class OCPP16ResponseService extends OCPPResponseService {
-  public jsonIncomingRequestResponseSchemas: Map<
+  public incomingRequestResponsePayloadValidateFunctions: Map<
   OCPP16IncomingRequestCommand,
-  JSONSchemaType<JsonType>
+  ValidateFunction<JsonType>
   >
 
+  protected payloadValidateFunctions: Map<OCPP16RequestCommand, ValidateFunction<JsonType>>
   private readonly responseHandlers: Map<OCPP16RequestCommand, ResponseHandler>
-  private readonly jsonSchemas: Map<OCPP16RequestCommand, JSONSchemaType<JsonType>>
 
   public constructor () {
-    // if (new.target?.name === moduleName) {
-    //   throw new TypeError(`Cannot construct ${new.target?.name} instances directly`)
+    // if (new.target.name === moduleName) {
+    //   throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
     // }
     super(OCPPVersion.VERSION_16)
     this.responseHandlers = new Map<OCPP16RequestCommand, ResponseHandler>([
@@ -75,7 +75,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
         OCPP16RequestCommand.BOOT_NOTIFICATION,
         this.handleResponseBootNotification.bind(this) as ResponseHandler
       ],
-      [OCPP16RequestCommand.HEARTBEAT, this.emptyResponseHandler.bind(this) as ResponseHandler],
+      [OCPP16RequestCommand.HEARTBEAT, this.emptyResponseHandler],
       [OCPP16RequestCommand.AUTHORIZE, this.handleResponseAuthorize.bind(this) as ResponseHandler],
       [
         OCPP16RequestCommand.START_TRANSACTION,
@@ -89,242 +89,346 @@ export class OCPP16ResponseService extends OCPPResponseService {
         OCPP16RequestCommand.STATUS_NOTIFICATION,
         this.emptyResponseHandler.bind(this) as ResponseHandler
       ],
-      [OCPP16RequestCommand.METER_VALUES, this.emptyResponseHandler.bind(this) as ResponseHandler],
+      [OCPP16RequestCommand.METER_VALUES, this.emptyResponseHandler],
       [
         OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
         this.emptyResponseHandler.bind(this) as ResponseHandler
       ],
-      [OCPP16RequestCommand.DATA_TRANSFER, this.emptyResponseHandler.bind(this) as ResponseHandler],
-      [
-        OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
-        this.emptyResponseHandler.bind(this) as ResponseHandler
-      ]
+      [OCPP16RequestCommand.DATA_TRANSFER, this.emptyResponseHandler],
+      [OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION, this.emptyResponseHandler]
     ])
-    this.jsonSchemas = new Map<OCPP16RequestCommand, JSONSchemaType<JsonType>>([
+    this.payloadValidateFunctions = new Map<OCPP16RequestCommand, ValidateFunction<JsonType>>([
       [
         OCPP16RequestCommand.BOOT_NOTIFICATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16BootNotificationResponse>(
-          'assets/json-schemas/ocpp/1.6/BootNotificationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16BootNotificationResponse>(
+              'assets/json-schemas/ocpp/1.6/BootNotificationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.HEARTBEAT,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16HeartbeatResponse>(
-          'assets/json-schemas/ocpp/1.6/HeartbeatResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16HeartbeatResponse>(
+              'assets/json-schemas/ocpp/1.6/HeartbeatResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.AUTHORIZE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16AuthorizeResponse>(
-          'assets/json-schemas/ocpp/1.6/AuthorizeResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16AuthorizeResponse>(
+              'assets/json-schemas/ocpp/1.6/AuthorizeResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.START_TRANSACTION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StartTransactionResponse>(
-          'assets/json-schemas/ocpp/1.6/StartTransactionResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StartTransactionResponse>(
+              'assets/json-schemas/ocpp/1.6/StartTransactionResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.STOP_TRANSACTION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StopTransactionResponse>(
-          'assets/json-schemas/ocpp/1.6/StopTransactionResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StopTransactionResponse>(
+              'assets/json-schemas/ocpp/1.6/StopTransactionResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.STATUS_NOTIFICATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StatusNotificationResponse>(
-          'assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StatusNotificationResponse>(
+              'assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.METER_VALUES,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16MeterValuesResponse>(
-          'assets/json-schemas/ocpp/1.6/MeterValuesResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16MeterValuesResponse>(
+              'assets/json-schemas/ocpp/1.6/MeterValuesResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationResponse>(
-          'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationResponse>(
+              'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.DATA_TRANSFER,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
-          'assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
+              'assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationResponse>(
-          'assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajv
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationResponse>(
+              'assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ]
     ])
-    this.jsonIncomingRequestResponseSchemas = new Map([
+    this.incomingRequestResponsePayloadValidateFunctions = new Map<
+    OCPP16IncomingRequestCommand,
+    ValidateFunction<JsonType>
+    >([
       [
         OCPP16IncomingRequestCommand.RESET,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
-          'assets/json-schemas/ocpp/1.6/ResetResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+              'assets/json-schemas/ocpp/1.6/ResetResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.CLEAR_CACHE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
-          'assets/json-schemas/ocpp/1.6/ClearCacheResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+              'assets/json-schemas/ocpp/1.6/ClearCacheResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.CHANGE_AVAILABILITY,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ChangeAvailabilityResponse>(
-          'assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ChangeAvailabilityResponse>(
+              'assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.UNLOCK_CONNECTOR,
-        OCPP16ServiceUtils.parseJsonSchemaFile<UnlockConnectorResponse>(
-          'assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<UnlockConnectorResponse>(
+              'assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.GET_CONFIGURATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GetConfigurationResponse>(
-          'assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GetConfigurationResponse>(
+              'assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.CHANGE_CONFIGURATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<ChangeConfigurationResponse>(
-          'assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<ChangeConfigurationResponse>(
+              'assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.GET_COMPOSITE_SCHEDULE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16GetCompositeScheduleResponse>(
-          'assets/json-schemas/ocpp/1.6/GetCompositeScheduleResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16GetCompositeScheduleResponse>(
+              'assets/json-schemas/ocpp/1.6/GetCompositeScheduleResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<SetChargingProfileResponse>(
-          'assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<SetChargingProfileResponse>(
+              'assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ClearChargingProfileResponse>(
-          'assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ClearChargingProfileResponse>(
+              'assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.REMOTE_START_TRANSACTION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
-          'assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+              'assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.REMOTE_STOP_TRANSACTION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
-          'assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+              'assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GetDiagnosticsResponse>(
-          'assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GetDiagnosticsResponse>(
+              'assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16TriggerMessageResponse>(
-          'assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16TriggerMessageResponse>(
+              'assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.DATA_TRANSFER,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
-          'assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
+              'assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.UPDATE_FIRMWARE,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16UpdateFirmwareResponse>(
-          'assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16UpdateFirmwareResponse>(
+              'assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.RESERVE_NOW,
-        OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ReserveNowResponse>(
-          'assets/json-schemas/ocpp/1.6/ReserveNowResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ReserveNowResponse>(
+              'assets/json-schemas/ocpp/1.6/ReserveNowResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ],
       [
         OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
-        OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
-          'assets/json-schemas/ocpp/1.6/CancelReservationResponse.json',
-          moduleName,
-          'constructor'
-        )
+        this.ajvIncomingRequest
+          .compile(
+            OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
+              'assets/json-schemas/ocpp/1.6/CancelReservationResponse.json',
+              moduleName,
+              'constructor'
+            )
+          )
+          .bind(this)
       ]
     ])
-    this.validatePayload = this.validatePayload.bind(this) as (
-      chargingStation: ChargingStation,
-      commandName: OCPP16RequestCommand,
-      payload: JsonType
-    ) => boolean
+    this.validatePayload = this.validatePayload.bind(this)
   }
 
   public async responseHandler<ReqType extends JsonType, ResType extends JsonType>(
@@ -341,7 +445,18 @@ export class OCPP16ResponseService extends OCPPResponseService {
         try {
           this.validatePayload(chargingStation, commandName, payload)
           // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-          await this.responseHandlers.get(commandName)!(chargingStation, payload, requestPayload)
+          const responseHandler = this.responseHandlers.get(commandName)!
+          if (isAsyncFunction(responseHandler)) {
+            await responseHandler(chargingStation, payload, requestPayload)
+          } else {
+            (
+              responseHandler as (
+                chargingStation: ChargingStation,
+                payload: JsonType,
+                requestPayload?: JsonType
+              ) => void
+            )(chargingStation, payload, requestPayload)
+          }
         } catch (error) {
           logger.error(
             `${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`,
@@ -353,7 +468,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
         // Throw exception
         throw new OCPPError(
           ErrorType.NOT_IMPLEMENTED,
-          `${commandName} is not implemented to handle response PDU ${JSON.stringify(
+          `'${commandName}' is not implemented to handle response PDU ${JSON.stringify(
             payload,
             undefined,
             2
@@ -369,7 +484,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
           payload,
           undefined,
           2
-        )} while the charging station is not registered on the central server.`,
+        )} while the charging station is not registered on the central server`,
         commandName,
         payload
       )
@@ -381,17 +496,11 @@ export class OCPP16ResponseService extends OCPPResponseService {
     commandName: OCPP16RequestCommand,
     payload: JsonType
   ): boolean {
-    if (this.jsonSchemas.has(commandName)) {
-      return this.validateResponsePayload(
-        chargingStation,
-        commandName,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        this.jsonSchemas.get(commandName)!,
-        payload
-      )
+    if (this.payloadValidateFunctions.has(commandName)) {
+      return this.validateResponsePayload(chargingStation, commandName, payload)
     }
     logger.warn(
-      `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`
+      `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
     )
     return false
   }
@@ -442,7 +551,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
       for (const [evseId, evseStatus] of chargingStation.evses) {
         if (evseId > 0) {
           for (const [connectorId, connectorStatus] of evseStatus.connectors) {
-            if (connectorStatus?.authorizeIdTag === requestPayload.idTag) {
+            if (connectorStatus.authorizeIdTag === requestPayload.idTag) {
               authorizeConnectorId = connectorId
               break
             }
@@ -460,29 +569,30 @@ export class OCPP16ResponseService extends OCPPResponseService {
         }
       }
     }
-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    const authorizeConnectorStatus = chargingStation.getConnectorStatus(authorizeConnectorId!)
-    const authorizeConnectorIdDefined = !isNullOrUndefined(authorizeConnectorId)
-    if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
-      if (authorizeConnectorIdDefined) {
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        authorizeConnectorStatus!.idTagAuthorized = true
+    if (authorizeConnectorId != null) {
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      const authorizeConnectorStatus = chargingStation.getConnectorStatus(authorizeConnectorId)!
+      if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
+        authorizeConnectorStatus.idTagAuthorized = true
+        logger.debug(
+          `${chargingStation.logPrefix()} idTag '${
+            requestPayload.idTag
+          }' accepted on connector id ${authorizeConnectorId}`
+        )
+      } else {
+        authorizeConnectorStatus.idTagAuthorized = false
+        delete authorizeConnectorStatus.authorizeIdTag
+        logger.debug(
+          `${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' rejected with status '${
+            payload.idTagInfo.status
+          }'`
+        )
       }
-      logger.debug(
-        `${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' accepted${
-          authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''
-        }`
-      )
     } else {
-      if (authorizeConnectorIdDefined) {
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        authorizeConnectorStatus!.idTagAuthorized = false
-        delete authorizeConnectorStatus?.authorizeIdTag
-      }
-      logger.debug(
-        `${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' rejected with status '${
-          payload.idTagInfo.status
-        }'${authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''}`
+      logger.error(
+        `${chargingStation.logPrefix()} idTag '${
+          requestPayload.idTag
+        }' has no authorize request pending`
       )
     }
   }
@@ -505,10 +615,12 @@ export class OCPP16ResponseService extends OCPPResponseService {
       chargingStation.getAuthorizeRemoteTxRequests() &&
       chargingStation.getLocalAuthListEnabled() &&
       chargingStation.hasIdTags() &&
-      connectorStatus?.idTagLocalAuthorized === false
+      connectorStatus.idTagLocalAuthorized === false
     ) {
       logger.error(
-        `${chargingStation.logPrefix()} Trying to start a transaction with a not local authorized idTag ${connectorStatus?.localAuthorizeIdTag} on connector id ${connectorId}`
+        `${chargingStation.logPrefix()} Trying to start a transaction with a not local authorized idTag ${
+          connectorStatus.localAuthorizeIdTag
+        } on connector id ${connectorId}`
       )
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId)
       return
@@ -517,42 +629,50 @@ export class OCPP16ResponseService extends OCPPResponseService {
       connectorStatus?.transactionRemoteStarted === true &&
       chargingStation.getAuthorizeRemoteTxRequests() &&
       chargingStation.stationInfo?.remoteAuthorization === true &&
-      connectorStatus?.idTagLocalAuthorized === false &&
-      connectorStatus?.idTagAuthorized === false
+      connectorStatus.idTagLocalAuthorized === false &&
+      connectorStatus.idTagAuthorized === false
     ) {
       logger.error(
-        `${chargingStation.logPrefix()} Trying to start a transaction with a not authorized idTag ${connectorStatus?.authorizeIdTag} on connector id ${connectorId}`
+        `${chargingStation.logPrefix()} Trying to start a transaction with a not authorized idTag ${
+          connectorStatus.authorizeIdTag
+        } on connector id ${connectorId}`
       )
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId)
       return
     }
     if (
       connectorStatus?.idTagAuthorized === true &&
-      connectorStatus?.authorizeIdTag !== requestPayload.idTag
+      connectorStatus.authorizeIdTag !== requestPayload.idTag
     ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${
           requestPayload.idTag
-        } different from the authorize request one ${connectorStatus?.authorizeIdTag} on connector id ${connectorId}`
+        } different from the authorize request one ${
+          connectorStatus.authorizeIdTag
+        } on connector id ${connectorId}`
       )
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId)
       return
     }
     if (
       connectorStatus?.idTagLocalAuthorized === true &&
-      connectorStatus?.localAuthorizeIdTag !== requestPayload.idTag
+      connectorStatus.localAuthorizeIdTag !== requestPayload.idTag
     ) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${
           requestPayload.idTag
-        } different from the local authorized one ${connectorStatus?.localAuthorizeIdTag} on connector id ${connectorId}`
+        } different from the local authorized one ${
+          connectorStatus.localAuthorizeIdTag
+        } on connector id ${connectorId}`
       )
       await this.resetConnectorOnStartTransactionError(chargingStation, connectorId)
       return
     }
     if (connectorStatus?.transactionStarted === true) {
       logger.error(
-        `${chargingStation.logPrefix()} Trying to start a transaction on an already used connector id ${connectorId} by idTag ${connectorStatus?.transactionIdTag}`
+        `${chargingStation.logPrefix()} Trying to start a transaction on an already used connector id ${connectorId} by idTag ${
+          connectorStatus.transactionIdTag
+        }`
       )
       return
     }
@@ -560,9 +680,11 @@ export class OCPP16ResponseService extends OCPPResponseService {
       for (const [evseId, evseStatus] of chargingStation.evses) {
         if (evseStatus.connectors.size > 1) {
           for (const [id, status] of evseStatus.connectors) {
-            if (id !== connectorId && status?.transactionStarted === true) {
+            if (id !== connectorId && status.transactionStarted === true) {
               logger.error(
-                `${chargingStation.logPrefix()} Trying to start a transaction on an already used evse id ${evseId} by connector id ${id} with idTag ${status?.transactionIdTag}`
+                `${chargingStation.logPrefix()} Trying to start a transaction on an already used evse id ${evseId} by connector id ${id} with idTag ${
+                  status.transactionIdTag
+                }`
               )
               await this.resetConnectorOnStartTransactionError(chargingStation, connectorId)
               return
@@ -589,7 +711,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
       payload.transactionId = convertToInt(payload.transactionId)
     }
 
-    if (payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
+    if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
       connectorStatus.transactionStarted = true
       connectorStatus.transactionStart = requestPayload.timestamp
       connectorStatus.transactionId = payload.transactionId
@@ -602,33 +724,40 @@ export class OCPP16ResponseService extends OCPPResponseService {
           requestPayload.meterStart
         )
       if (requestPayload.reservationId != null) {
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         const reservation = chargingStation.getReservationBy(
           'reservationId',
           requestPayload.reservationId
-        )!
-        if (reservation.idTag !== requestPayload.idTag) {
-          logger.warn(
-            `${chargingStation.logPrefix()} Reserved transaction ${
-              payload.transactionId
-            } started with a different idTag ${requestPayload.idTag} than the reservation one ${
-              reservation.idTag
-            }`
+        )
+        if (reservation != null) {
+          if (reservation.idTag !== requestPayload.idTag) {
+            logger.warn(
+              `${chargingStation.logPrefix()} Reserved transaction ${
+                payload.transactionId
+              } started with a different idTag ${requestPayload.idTag} than the reservation one ${
+                reservation.idTag
+              }`
+            )
+          }
+          if (hasReservationExpired(reservation)) {
+            logger.warn(
+              `${chargingStation.logPrefix()} Reserved transaction ${
+                payload.transactionId
+              } started with expired reservation ${
+                requestPayload.reservationId
+              } (expiry date: ${reservation.expiryDate.toISOString()}))`
+            )
+          }
+          await chargingStation.removeReservation(
+            reservation,
+            ReservationTerminationReason.TRANSACTION_STARTED
           )
-        }
-        if (hasReservationExpired(reservation)) {
+        } else {
           logger.warn(
             `${chargingStation.logPrefix()} Reserved transaction ${
               payload.transactionId
-            } started with expired reservation ${
-              requestPayload.reservationId
-            } (expiry date: ${reservation.expiryDate.toISOString()}))`
+            } started with unknown reservation ${requestPayload.reservationId}`
           )
         }
-        await chargingStation.removeReservation(
-          reservation,
-          ReservationTerminationReason.TRANSACTION_STARTED
-        )
       }
       chargingStation.stationInfo?.beginEndMeterValues === true &&
         (await chargingStation.ocppRequestService.requestHandler<
@@ -645,12 +774,15 @@ export class OCPP16ResponseService extends OCPPResponseService {
         OCPP16ChargePointStatus.Charging
       )
       logger.info(
-        `${chargingStation.logPrefix()} Transaction with id ${payload.transactionId} STARTED on ${
-          chargingStation.stationInfo.chargingStationId
-        }#${connectorId} for idTag '${requestPayload.idTag}'`
+        `${chargingStation.logPrefix()} Transaction with id ${
+          payload.transactionId
+        } STARTED on ${chargingStation.stationInfo?.chargingStationId}#${connectorId} for idTag '${
+          requestPayload.idTag
+        }'`
       )
-      if (chargingStation.stationInfo.powerSharedByConnectors === true) {
-        ++chargingStation.powerDivider
+      if (chargingStation.stationInfo?.powerSharedByConnectors === true) {
+        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+        ++chargingStation.powerDivider!
       }
       const configuredMeterValueSampleInterval = getConfigurationKey(
         chargingStation,
@@ -667,8 +799,8 @@ export class OCPP16ResponseService extends OCPPResponseService {
         `${chargingStation.logPrefix()} Starting transaction with id ${
           payload.transactionId
         } REJECTED on ${
-          chargingStation.stationInfo.chargingStationId
-        }#${connectorId} with status '${payload.idTagInfo?.status}', idTag '${
+          chargingStation.stationInfo?.chargingStationId
+        }#${connectorId} with status '${payload.idTagInfo.status}', idTag '${
           requestPayload.idTag
         }'${
           OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, requestPayload.idTag)
@@ -684,17 +816,10 @@ export class OCPP16ResponseService extends OCPPResponseService {
     chargingStation: ChargingStation,
     connectorId: number
   ): Promise<void> {
-    const connectorStatus = chargingStation.getConnectorStatus(connectorId)
-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    resetConnectorStatus(connectorStatus!)
     chargingStation.stopMeterValues(connectorId)
-    if (connectorStatus?.status !== OCPP16ChargePointStatus.Available) {
-      await OCPP16ServiceUtils.sendAndSetConnectorStatus(
-        chargingStation,
-        connectorId,
-        OCPP16ChargePointStatus.Available
-      )
-    }
+    const connectorStatus = chargingStation.getConnectorStatus(connectorId)
+    resetConnectorStatus(connectorStatus)
+    await OCPP16ServiceUtils.restoreConnectorStatus(chargingStation, connectorId, connectorStatus)
   }
 
   private async handleResponseStopTransaction (
@@ -705,7 +830,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
     const transactionConnectorId = chargingStation.getConnectorIdByTransactionId(
       requestPayload.transactionId
     )
-    if (isNullOrUndefined(transactionConnectorId)) {
+    if (transactionConnectorId == null) {
       logger.error(
         `${chargingStation.logPrefix()} Trying to stop a non existing transaction with id ${
           requestPayload.transactionId
@@ -714,8 +839,8 @@ export class OCPP16ResponseService extends OCPPResponseService {
       return
     }
     chargingStation.stationInfo?.beginEndMeterValues === true &&
-      chargingStation.stationInfo?.ocppStrictCompliance === false &&
-      chargingStation.stationInfo?.outOfOrderEndMeterValues === true &&
+      chargingStation.stationInfo.ocppStrictCompliance === false &&
+      chargingStation.stationInfo.outOfOrderEndMeterValues === true &&
       (await chargingStation.ocppRequestService.requestHandler<
       OCPP16MeterValuesRequest,
       OCPP16MeterValuesResponse
@@ -725,46 +850,41 @@ export class OCPP16ResponseService extends OCPPResponseService {
         meterValue: [
           OCPP16ServiceUtils.buildTransactionEndMeterValue(
             chargingStation,
-            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            transactionConnectorId!,
+            transactionConnectorId,
             requestPayload.meterStop
           )
         ]
       }))
     if (
       !chargingStation.isChargingStationAvailable() ||
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      !chargingStation.isConnectorAvailable(transactionConnectorId!)
+      !chargingStation.isConnectorAvailable(transactionConnectorId)
     ) {
       await OCPP16ServiceUtils.sendAndSetConnectorStatus(
         chargingStation,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        transactionConnectorId!,
+        transactionConnectorId,
         OCPP16ChargePointStatus.Unavailable
       )
     } else {
       await OCPP16ServiceUtils.sendAndSetConnectorStatus(
         chargingStation,
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        transactionConnectorId!,
+        transactionConnectorId,
         OCPP16ChargePointStatus.Available
       )
     }
-    if (chargingStation.stationInfo.powerSharedByConnectors === true) {
-      chargingStation.powerDivider--
+    if (chargingStation.stationInfo?.powerSharedByConnectors === true) {
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      chargingStation.powerDivider!--
     }
-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    resetConnectorStatus(chargingStation.getConnectorStatus(transactionConnectorId!)!)
-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    chargingStation.stopMeterValues(transactionConnectorId!)
+    resetConnectorStatus(chargingStation.getConnectorStatus(transactionConnectorId))
+    chargingStation.stopMeterValues(transactionConnectorId)
     const logMsg = `${chargingStation.logPrefix()} Transaction with id ${
       requestPayload.transactionId
     } STOPPED on ${
-      chargingStation.stationInfo.chargingStationId
+      chargingStation.stationInfo?.chargingStationId
     }#${transactionConnectorId} with status '${payload.idTagInfo?.status}'`
     if (
-      isNullOrUndefined(payload.idTagInfo) ||
-      payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED
+      payload.idTagInfo == null ||
+      payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED
     ) {
       logger.info(logMsg)
     } else {