From: Jérôme Benoit Date: Wed, 25 Jan 2023 16:27:47 +0000 (+0100) Subject: Strict null check fixes X-Git-Tag: v1.1.92~17 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=72092cfcf8a31c06e4592b25e060e2d74d2ed99c;p=e-mobility-charging-stations-simulator.git Strict null check fixes Signed-off-by: Jérôme Benoit --- diff --git a/.eslintrc.json b/.eslintrc.json index 8b10dc67..b9b190f5 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -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", diff --git a/.prettierrc.json b/.prettierrc.json index ef4fe83f..5ac85e27 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,5 +1,4 @@ { "printWidth": 100, - "arrowParens": "avoid", "singleQuote": true } diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index 2774149e..4603f278 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -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; diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index 9f910aaf..8a161e54 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -41,7 +41,7 @@ export class Bootstrap { private workerImplementation: WorkerAbstract | 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; } diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 4a90c310..639123ab 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -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; public readonly requests: Map; 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(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 { - 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); } } diff --git a/src/charging-station/ChargingStationConfigurationUtils.ts b/src/charging-station/ChargingStationConfigurationUtils.ts index 4bae70f2..e31e6bfb 100644 --- a/src/charging-station/ChargingStationConfigurationUtils.ts +++ b/src/charging-station/ChargingStationConfigurationUtils.ts @@ -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 ); diff --git a/src/charging-station/ChargingStationWorkerBroadcastChannel.ts b/src/charging-station/ChargingStationWorkerBroadcastChannel.ts index 8d6cb1c6..28c23cf8 100644 --- a/src/charging-station/ChargingStationWorkerBroadcastChannel.ts +++ b/src/charging-station/ChargingStationWorkerBroadcastChannel.ts @@ -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) { diff --git a/src/charging-station/UIServiceWorkerBroadcastChannel.ts b/src/charging-station/UIServiceWorkerBroadcastChannel.ts index fa9236ab..0e84b3a1 100644 --- a/src/charging-station/UIServiceWorkerBroadcastChannel.ts +++ b/src/charging-station/UIServiceWorkerBroadcastChannel.ts @@ -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), }), }; } diff --git a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts index 4deabe4f..f81c27ed 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -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 { 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, diff --git a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts index 330f6672..2b40ad41 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts @@ -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 { chargingStation.resetConnectorStatus(connectorId); if ( - chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE + chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.AVAILABLE ) { await chargingStation.ocppRequestService.requestHandler< OCPP16StatusNotificationRequest, diff --git a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts index 15b914c3..65fc51c5 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts @@ -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( diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index dbf478ec..fc4410f8 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -68,7 +68,7 @@ export default abstract class OCPPRequestService { messageId: string, messagePayload: JsonType, commandName: IncomingRequestCommand - ): Promise { + ): Promise { 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 diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index 04ca7046..15edd6df 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -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 ( diff --git a/src/charging-station/ui-server/UIHttpServer.ts b/src/charging-station/ui-server/UIHttpServer.ts index da347672..87f10a5e 100644 --- a/src/charging-station/ui-server/UIHttpServer.ts +++ b/src/charging-station/ui-server/UIHttpServer.ts @@ -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', () => { diff --git a/src/charging-station/ui-server/UIWebSocketServer.ts b/src/charging-station/ui-server/UIWebSocketServer.ts index 006c3914..e217305f 100644 --- a/src/charging-station/ui-server/UIWebSocketServer.ts +++ b/src/charging-station/ui-server/UIWebSocketServer.ts @@ -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(); diff --git a/src/charging-station/ui-server/ui-services/AbstractUIService.ts b/src/charging-station/ui-server/ui-services/AbstractUIService.ts index 2b1267f3..5a418b9d 100644 --- a/src/charging-station/ui-server/ui-services/AbstractUIService.ts +++ b/src/charging-station/ui-server/ui-services/AbstractUIService.ts @@ -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 diff --git a/src/performance/PerformanceStatistics.ts b/src/performance/PerformanceStatistics.ts index 6d18e212..6ac54aa4 100644 --- a/src/performance/PerformanceStatistics.ts +++ b/src/performance/PerformanceStatistics.ts @@ -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(DEFAULT_CIRCULAR_ARRAY_SIZE, { timestamp: entry.startTime, @@ -287,7 +287,7 @@ export default class PerformanceStatistics { } private extractTimeSeriesValues(timeSeries: CircularArray): number[] { - return timeSeries.map(timeSeriesItem => timeSeriesItem.value); + return timeSeries.map((timeSeriesItem) => timeSeriesItem.value); } private logPrefix(): string { diff --git a/src/performance/storage/JsonFileStorage.ts b/src/performance/storage/JsonFileStorage.ts index 94c36edd..63d12a43 100644 --- a/src/performance/storage/JsonFileStorage.ts +++ b/src/performance/storage/JsonFileStorage.ts @@ -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 diff --git a/src/performance/storage/MongoDBStorage.ts b/src/performance/storage/MongoDBStorage.ts index 54fc4334..9e5c0662 100644 --- a/src/performance/storage/MongoDBStorage.ts +++ b/src/performance/storage/MongoDBStorage.ts @@ -24,7 +24,7 @@ export class MongoDBStorage extends Storage { try { this.checkDBConnection(); await this.client - .db(this.dbName) + ?.db(this.dbName) .collection(Constants.PERFORMANCE_RECORDS_TABLE) .insertOne(performanceStatistics); } catch (error) { diff --git a/src/start.ts b/src/start.ts index a21f7fcf..8eca3a4a 100644 --- a/src/start.ts +++ b/src/start.ts @@ -6,6 +6,6 @@ import { Bootstrap } from './internal'; Bootstrap.getInstance() .start() - .catch(error => { + .catch((error) => { console.error(chalk.red(error)); }); diff --git a/src/utils/Configuration.ts b/src/utils/Configuration.ts index a67c70c2..1c51bbfd 100644 --- a/src/utils/Configuration.ts +++ b/src/utils/Configuration.ts @@ -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; }); } diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 5fb5f625..6557a588 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -26,7 +26,7 @@ export default class Utils { } public static async sleep(milliSeconds: number): Promise { - 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 { diff --git a/src/worker/WorkerAbstract.ts b/src/worker/WorkerAbstract.ts index 0fccdb81..aeb1b86a 100644 --- a/src/worker/WorkerAbstract.ts +++ b/src/worker/WorkerAbstract.ts @@ -7,7 +7,7 @@ export default abstract class WorkerAbstract { 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. diff --git a/src/worker/WorkerDynamicPool.ts b/src/worker/WorkerDynamicPool.ts index f842614f..9926a09e 100644 --- a/src/worker/WorkerDynamicPool.ts +++ b/src/worker/WorkerDynamicPool.ts @@ -37,8 +37,8 @@ export default class WorkerDynamicPool extends WorkerAbstract { return this.pool.workers.length; } - get maxElementsPerWorker(): number | null { - return null; + get maxElementsPerWorker(): number | undefined { + return undefined; } /** diff --git a/src/worker/WorkerSet.ts b/src/worker/WorkerSet.ts index 76d759a2..c5b2d84a 100644 --- a/src/worker/WorkerSet.ts +++ b/src/worker/WorkerSet.ts @@ -31,7 +31,7 @@ export default class WorkerSet extends WorkerAbstract { 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 { ).bind(this) as MessageHandler ); 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)); }); diff --git a/src/worker/WorkerStaticPool.ts b/src/worker/WorkerStaticPool.ts index 2dd2bc80..2ec049e1 100644 --- a/src/worker/WorkerStaticPool.ts +++ b/src/worker/WorkerStaticPool.ts @@ -36,8 +36,8 @@ export default class WorkerStaticPool extends WorkerAbstract { return this.pool.workers.length; } - get maxElementsPerWorker(): number | null { - return null; + get maxElementsPerWorker(): number | undefined { + return undefined; } /** diff --git a/ui/web/src/composables/UIClient.ts b/ui/web/src/composables/UIClient.ts index 056e2ce2..e78836fd 100644 --- a/ui/web/src/composables/UIClient.ts +++ b/ui/web/src/composables/UIClient.ts @@ -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); }; }