From: Jérôme Benoit Date: Tue, 11 Jul 2023 18:58:35 +0000 (+0200) Subject: build(deps-dev): apply updates X-Git-Tag: v1.2.18~52 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=5edd8ba0f8978cfb3ca9d80f299d9748c6c5970e;p=e-mobility-charging-stations-simulator.git build(deps-dev): apply updates Signed-off-by: Jérôme Benoit --- diff --git a/build-requirements.mjs b/build-requirements.mjs index 167f3656..44de1932 100644 --- a/build-requirements.mjs +++ b/build-requirements.mjs @@ -10,8 +10,8 @@ export function checkNodeVersion() { if (semVer.satisfies(process.version, enginesNodeVersion) === false) { console.error( chalk.red( - `Required node version ${enginesNodeVersion} not satisfied with current version ${process.version}.` - ) + `Required node version ${enginesNodeVersion} not satisfied with current version ${process.version}.`, + ), ); // eslint-disable-next-line n/no-process-exit process.exit(1); diff --git a/mikro-orm.config-template.ts b/mikro-orm.config-template.ts index ff08b534..4ef43dff 100644 --- a/mikro-orm.config-template.ts +++ b/mikro-orm.config-template.ts @@ -12,6 +12,6 @@ export default { type: 'sqlite', clientUrl: `file://${join( dirname(fileURLToPath(import.meta.url)), - `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db` + `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`, )}`, }; diff --git a/package.json b/package.json index 6e0bde85..fb5bc2fb 100644 --- a/package.json +++ b/package.json @@ -142,14 +142,14 @@ "eslint-plugin-import": "^2.27.5", "eslint-plugin-jsdoc": "^46.4.3", "eslint-plugin-n": "^16.0.1", - "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-tsdoc": "^0.2.17", "expect": "^29.6.1", "husky": "^8.0.3", "lint-staged": "^13.2.3", "mocha": "^10.2.0", "mochawesome": "^7.1.3", - "prettier": "^2.8.8", + "prettier": "^3.0.0", "release-it": "^16.1.0", "rimraf": "^5.0.1", "robohydra": "^0.6.9", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f7c476f2..1a5d4f90 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -167,8 +167,8 @@ devDependencies: specifier: ^16.0.1 version: 16.0.1(eslint@8.44.0) eslint-plugin-prettier: - specifier: ^4.2.1 - version: 4.2.1(eslint-config-prettier@8.8.0)(eslint@8.44.0)(prettier@2.8.8) + specifier: ^5.0.0 + version: 5.0.0(eslint-config-prettier@8.8.0)(eslint@8.44.0)(prettier@3.0.0) eslint-plugin-tsdoc: specifier: ^0.2.17 version: 0.2.17 @@ -188,8 +188,8 @@ devDependencies: specifier: ^7.1.3 version: 7.1.3(mocha@10.2.0) prettier: - specifier: ^2.8.8 - version: 2.8.8 + specifier: ^3.0.0 + version: 3.0.0 release-it: specifier: ^16.1.0 version: 16.1.0 @@ -4056,21 +4056,25 @@ packages: semver: 7.5.4 dev: true - /eslint-plugin-prettier@4.2.1(eslint-config-prettier@8.8.0)(eslint@8.44.0)(prettier@2.8.8): - resolution: {integrity: sha512-f/0rXLXUt0oFYs8ra4w49wYZBG5GKZpAYsJSm6rnYL5uVDjd+zowwMwVZHnAjf4edNrKpCDYfXDgmRE/Ak7QyQ==} - engines: {node: '>=12.0.0'} + /eslint-plugin-prettier@5.0.0(eslint-config-prettier@8.8.0)(eslint@8.44.0)(prettier@3.0.0): + resolution: {integrity: sha512-AgaZCVuYDXHUGxj/ZGu1u8H8CYgDY3iG6w5kUFw4AzMVXzB7VvbKgYR4nATIN+OvUrghMbiDLeimVjVY5ilq3w==} + engines: {node: ^14.18.0 || >=16.0.0} peerDependencies: - eslint: '>=7.28.0' + '@types/eslint': '>=8.0.0' + eslint: '>=8.0.0' eslint-config-prettier: '*' - prettier: '>=2.0.0' + prettier: '>=3.0.0' peerDependenciesMeta: + '@types/eslint': + optional: true eslint-config-prettier: optional: true dependencies: eslint: 8.44.0 eslint-config-prettier: 8.8.0(eslint@8.44.0) - prettier: 2.8.8 + prettier: 3.0.0 prettier-linter-helpers: 1.0.0 + synckit: 0.8.5 dev: true /eslint-plugin-tsdoc@0.2.17: @@ -7688,9 +7692,9 @@ packages: fast-diff: 1.3.0 dev: true - /prettier@2.8.8: - resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} - engines: {node: '>=10.13.0'} + /prettier@3.0.0: + resolution: {integrity: sha512-zBf5eHpwHOGPC47h0zrPyNn+eAEIdEzfywMoYn2XPi0P44Zp0tSq64rq0xAREh4auw2cJZHo9QUob+NqCQky4g==} + engines: {node: '>=14'} hasBin: true dev: true diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index 3c2a2c38..2b21d2ea 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -56,12 +56,12 @@ export class AutomaticTransactionGenerator extends AsyncResource { } public static getInstance( - chargingStation: ChargingStation + chargingStation: ChargingStation, ): AutomaticTransactionGenerator | undefined { if (AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId) === false) { AutomaticTransactionGenerator.instances.set( chargingStation.stationInfo.hashId, - new AutomaticTransactionGenerator(chargingStation) + new AutomaticTransactionGenerator(chargingStation), ); } return AutomaticTransactionGenerator.instances.get(chargingStation.stationInfo.hashId); @@ -115,7 +115,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { ...args: any[] ) => Promise, this, - connectorId + connectorId, ).catch(Constants.EMPTY_FUNCTION); } else if (this.connectorsStatus.get(connectorId)?.start === true) { logger.warn(`${this.logPrefix(connectorId)} is already started on connector`); @@ -181,11 +181,11 @@ export class AutomaticTransactionGenerator extends AsyncResource { this.setStartConnectorStatus(connectorId); logger.info( `${this.logPrefix( - connectorId + connectorId, )} started on connector and will run for ${formatDurationMilliSeconds( this.connectorsStatus.get(connectorId).stopDate.getTime() - - this.connectorsStatus.get(connectorId).startDate.getTime() - )}` + this.connectorsStatus.get(connectorId).startDate.getTime(), + )}`, ); while (this.connectorsStatus.get(connectorId)?.start === true) { if (new Date() > this.connectorsStatus.get(connectorId).stopDate) { @@ -195,8 +195,8 @@ export class AutomaticTransactionGenerator extends AsyncResource { if (this.chargingStation.inAcceptedState() === false) { logger.error( `${this.logPrefix( - connectorId - )} entered in transaction loop while the charging station is not in accepted state` + connectorId, + )} entered in transaction loop while the charging station is not in accepted state`, ); this.stopConnector(connectorId); break; @@ -204,8 +204,8 @@ export class AutomaticTransactionGenerator extends AsyncResource { if (this.chargingStation.isChargingStationAvailable() === false) { logger.info( `${this.logPrefix( - connectorId - )} entered in transaction loop while the charging station is unavailable` + connectorId, + )} entered in transaction loop while the charging station is unavailable`, ); this.stopConnector(connectorId); break; @@ -213,8 +213,8 @@ export class AutomaticTransactionGenerator extends AsyncResource { if (this.chargingStation.isConnectorAvailable(connectorId) === false) { logger.info( `${this.logPrefix( - connectorId - )} entered in transaction loop while the connector ${connectorId} is unavailable` + connectorId, + )} entered in transaction loop while the connector ${connectorId} is unavailable`, ); this.stopConnector(connectorId); break; @@ -225,8 +225,8 @@ export class AutomaticTransactionGenerator extends AsyncResource { ) { logger.info( `${this.logPrefix( - connectorId - )} entered in transaction loop while the connector ${connectorId} status is unavailable` + connectorId, + )} entered in transaction loop while the connector ${connectorId} status is unavailable`, ); this.stopConnector(connectorId); break; @@ -234,8 +234,8 @@ export class AutomaticTransactionGenerator extends AsyncResource { if (!this.chargingStation?.ocppRequestService) { logger.info( `${this.logPrefix( - connectorId - )} transaction loop waiting for charging station service to be initialized` + connectorId, + )} transaction loop waiting for charging station service to be initialized`, ); do { await sleep(Constants.CHARGING_STATION_ATG_INITIALIZATION_TIME); @@ -246,7 +246,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { this.chargingStation.getAutomaticTransactionGeneratorConfiguration() .maxDelayBetweenTwoTransactions, this.chargingStation.getAutomaticTransactionGeneratorConfiguration() - .minDelayBetweenTwoTransactions + .minDelayBetweenTwoTransactions, ) * 1000; logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`); await sleep(wait); @@ -263,21 +263,21 @@ export class AutomaticTransactionGenerator extends AsyncResource { const waitTrxEnd = getRandomInteger( this.chargingStation.getAutomaticTransactionGeneratorConfiguration().maxDuration, - this.chargingStation.getAutomaticTransactionGeneratorConfiguration().minDuration + this.chargingStation.getAutomaticTransactionGeneratorConfiguration().minDuration, ) * 1000; logger.info( `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation .getConnectorStatus(connectorId) ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds( - waitTrxEnd - )}` + waitTrxEnd, + )}`, ); await sleep(waitTrxEnd); // Stop transaction logger.info( `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation .getConnectorStatus(connectorId) - ?.transactionId?.toString()}` + ?.transactionId?.toString()}`, ); await this.stopTransaction(connectorId); } @@ -289,7 +289,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { .get(connectorId) ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus .get(connectorId) - ?.skippedTransactions?.toString()} transaction(s)` + ?.skippedTransactions?.toString()} transaction(s)`, ); } this.connectorsStatus.get(connectorId).lastRunDate = new Date(); @@ -297,15 +297,15 @@ export class AutomaticTransactionGenerator extends AsyncResource { this.connectorsStatus.get(connectorId).stoppedDate = new Date(); logger.info( `${this.logPrefix( - connectorId + connectorId, )} stopped on connector and lasted for ${formatDurationMilliSeconds( this.connectorsStatus.get(connectorId).stoppedDate.getTime() - - this.connectorsStatus.get(connectorId).startDate.getTime() - )}` + this.connectorsStatus.get(connectorId).startDate.getTime(), + )}`, ); logger.debug( `${this.logPrefix(connectorId)} connector status: %j`, - this.connectorsStatus.get(connectorId) + this.connectorsStatus.get(connectorId), ); } @@ -323,7 +323,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { this.chargingStation.getAutomaticTransactionGeneratorConfiguration().stopAfterHours * 3600 * 1000 - - previousRunDuration + previousRunDuration, ); this.connectorsStatus.get(connectorId).start = true; } @@ -348,7 +348,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { private getConnectorStatus(connectorId: number): Status { const connectorStatus = cloneObject( - this.chargingStation.getAutomaticTransactionGeneratorStatuses() + this.chargingStation.getAutomaticTransactionGeneratorStatuses(), )[connectorId]; delete connectorStatus?.startDate; delete connectorStatus?.lastRunDate; @@ -373,7 +373,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { } private async startTransaction( - connectorId: number + connectorId: number, ): Promise { const measureId = 'StartTransaction with ATG'; const beginId = PerformanceStatistics.beginMeasure(measureId); @@ -382,10 +382,10 @@ export class AutomaticTransactionGenerator extends AsyncResource { const idTag = IdTagsCache.getInstance().getIdTag( this.chargingStation.getAutomaticTransactionGeneratorConfiguration()?.idTagDistribution, this.chargingStation, - connectorId + connectorId, ); const startTransactionLogMsg = `${this.logPrefix( - connectorId + connectorId, )} start transaction with an idTag '${idTag}'`; if (this.getRequireAuthorize()) { this.chargingStation.getConnectorStatus(connectorId).authorizeIdTag = idTag; @@ -442,7 +442,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { private async stopTransaction( connectorId: number, - reason: StopTransactionReason = StopTransactionReason.LOCAL + reason: StopTransactionReason = StopTransactionReason.LOCAL, ): Promise { const measureId = 'StopTransaction with ATG'; const beginId = PerformanceStatistics.beginMeasure(measureId); @@ -460,7 +460,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { logger.warn( `${this.logPrefix(connectorId)} stopping a not started transaction${ !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : '' - }` + }`, ); } PerformanceStatistics.endMeasure(measureId, beginId); @@ -477,13 +477,13 @@ export class AutomaticTransactionGenerator extends AsyncResource { return logPrefix( ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${ !isNullOrUndefined(connectorId) ? ` on connector #${connectorId.toString()}` : '' - }:` + }:`, ); }; private handleStartTransactionResponse( connectorId: number, - startResponse: StartTransactionResponse + startResponse: StartTransactionResponse, ): void { ++this.connectorsStatus.get(connectorId).startTransactionRequests; if (startResponse?.idTagInfo?.status === AuthorizationStatus.ACCEPTED) { diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index ba4d14a8..9741fc25 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -75,7 +75,7 @@ export class Bootstrap extends EventEmitter { this.workerImplementation = null; this.workerScript = join( dirname(fileURLToPath(import.meta.url)), - `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}` + `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`, ); Configuration.getUIServer().enabled === true && (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer())); @@ -83,7 +83,7 @@ export class Bootstrap extends EventEmitter { (this.storage = StorageFactory.getStorage( Configuration.getPerformanceStorage().type, Configuration.getPerformanceStorage().uri, - this.logPrefix() + this.logPrefix(), )); Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart()); } @@ -117,9 +117,9 @@ export class Bootstrap extends EventEmitter { } catch (error) { console.error( chalk.red( - `Error at starting charging station with template file ${stationTemplateUrl.file}: ` + `Error at starting charging station with template file ${stationTemplateUrl.file}: `, ), - error + error, ); } } @@ -139,14 +139,14 @@ export class Bootstrap extends EventEmitter { !isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker) ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)` : '' - }` - ) + }`, + ), ); Configuration.workerDynamicPoolInUse() && console.warn( chalk.yellow( - 'Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using static pool or worker set mode instead' - ) + 'Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using static pool or worker set mode instead', + ), ); console.info(chalk.green('Worker set/pool information:'), this.workerImplementation?.info); this.started = true; @@ -170,19 +170,19 @@ export class Bootstrap extends EventEmitter { this.uiServer.buildProtocolRequest( generateUUID(), ProcedureName.STOP_CHARGING_STATION, - Constants.EMPTY_FREEZED_OBJECT - ) + Constants.EMPTY_FREEZED_OBJECT, + ), ); await Promise.race([ waitChargingStationEvents( this, ChargingStationWorkerMessageEvents.stopped, - this.numberOfChargingStations + this.numberOfChargingStations, ), new Promise((resolve) => { setTimeout(() => { const message = `Timeout reached ${formatDurationMilliSeconds( - Constants.STOP_SIMULATOR_TIMEOUT + Constants.STOP_SIMULATOR_TIMEOUT, )} at stopping charging stations simulator`; console.warn(chalk.yellow(message)); resolve(message); @@ -225,12 +225,12 @@ export class Bootstrap extends EventEmitter { workerChoiceStrategy: Configuration.getWorker().poolStrategy, messageHandler: this.messageHandler.bind(this) as (message: unknown) => void, }, - } + }, )); } private messageHandler( - msg: ChargingStationWorkerMessage + msg: ChargingStationWorkerMessage, ): void { // logger.debug( // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify( @@ -257,12 +257,12 @@ export class Bootstrap extends EventEmitter { this.workerEventPerformanceStatistics(msg.data as Statistics); this.emit( ChargingStationWorkerMessageEvents.performanceStatistics, - msg.data as Statistics + msg.data as Statistics, ); break; default: throw new BaseError( - `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}` + `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`, ); } } catch (error) { @@ -270,7 +270,7 @@ export class Bootstrap extends EventEmitter { `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${ msg.id }' event:`, - error + error, ); } } @@ -283,7 +283,7 @@ export class Bootstrap extends EventEmitter { data.stationInfo.chargingStationId } (hashId: ${data.stationInfo.hashId}) started (${ this.numberOfStartedChargingStations - } started from ${this.numberOfChargingStations})` + } started from ${this.numberOfChargingStations})`, ); }; @@ -295,7 +295,7 @@ export class Bootstrap extends EventEmitter { data.stationInfo.chargingStationId } (hashId: ${data.stationInfo.hashId}) stopped (${ this.numberOfStartedChargingStations - } started from ${this.numberOfChargingStations})` + } started from ${this.numberOfChargingStations})`, ); }; @@ -318,13 +318,13 @@ export class Bootstrap extends EventEmitter { } } else { console.warn( - chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting") + chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting"), ); process.exit(exitCodes.missingChargingStationsConfiguration); } if (this.numberOfChargingStations === 0) { console.warn( - chalk.yellow('No charging station template enabled in configuration, exiting') + chalk.yellow('No charging station template enabled in configuration, exiting'), ); process.exit(exitCodes.noChargingStationTemplates); } @@ -340,7 +340,7 @@ export class Bootstrap extends EventEmitter { private async startChargingStation( index: number, - stationTemplateUrl: StationTemplateUrl + stationTemplateUrl: StationTemplateUrl, ): Promise { await this.workerImplementation?.addElement({ index, @@ -348,7 +348,7 @@ export class Bootstrap extends EventEmitter { dirname(fileURLToPath(import.meta.url)), 'assets', 'station-templates', - stationTemplateUrl.file + stationTemplateUrl.file, ), }); } diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 1494cc56..a966037d 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -215,15 +215,15 @@ export class ChargingStation { isNotEmptyString( ChargingStationConfigurationUtils.getConfigurationKey( this, - this.getSupervisionUrlOcppKey() - )?.value + this.getSupervisionUrlOcppKey(), + )?.value, ) ? ChargingStationConfigurationUtils.getConfigurationKey( this, - this.getSupervisionUrlOcppKey() + this.getSupervisionUrlOcppKey(), ).value : this.configuredSupervisionUrl.href - }/${this.stationInfo.chargingStationId}` + }/${this.stationInfo.chargingStationId}`, ); } @@ -234,7 +234,7 @@ export class ChargingStation { ? this?.stationInfo?.chargingStationId : getChargingStationId(this.index, this.getTemplateFromFile())) ?? 'Error at building log prefix' - } |` + } |`, ); }; @@ -355,7 +355,7 @@ export class ChargingStation { const defaultVoltageOut = getDefaultVoltageOut( this.getCurrentOutType(stationInfo), this.logPrefix(), - this.templateFile + this.templateFile, ); return (stationInfo ?? this.stationInfo).voltageOut ?? defaultVoltageOut; } @@ -377,7 +377,7 @@ export class ChargingStation { this.getNumberOfPhases(), this.getVoltageOut(), this.getAmperageLimitation() * - (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()) + (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()), ) : DCElectricUtils.power(this.getVoltageOut(), this.getAmperageLimitation())) / this.powerDivider; @@ -390,7 +390,7 @@ export class ChargingStation { isNaN(connectorAmperageLimitationPowerLimit) ? Infinity : connectorAmperageLimitationPowerLimit, - isNaN(connectorChargingProfilesPowerLimit) ? Infinity : connectorChargingProfilesPowerLimit + isNaN(connectorChargingProfilesPowerLimit) ? Infinity : connectorChargingProfilesPowerLimit, ); } @@ -483,11 +483,11 @@ export class ChargingStation { public getEnergyActiveImportRegisterByTransactionId( transactionId: number, - rounded = false + rounded = false, ): number { return this.getEnergyActiveImportRegister( this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId)), - rounded + rounded, ); } @@ -498,7 +498,7 @@ export class ChargingStation { public getAuthorizeRemoteTxRequests(): boolean { const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.AuthorizeRemoteTxRequests + StandardParametersKey.AuthorizeRemoteTxRequests, ); return authorizeRemoteTxRequests ? convertToBoolean(authorizeRemoteTxRequests.value) : false; } @@ -506,7 +506,7 @@ export class ChargingStation { public getLocalAuthListEnabled(): boolean { const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.LocalAuthListEnabled + StandardParametersKey.LocalAuthListEnabled, ); return localAuthListEnabled ? convertToBoolean(localAuthListEnabled.value) : false; } @@ -514,14 +514,14 @@ export class ChargingStation { public getHeartbeatInterval(): number { const HeartbeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.HeartbeatInterval + StandardParametersKey.HeartbeatInterval, ); if (HeartbeatInterval) { return convertToInt(HeartbeatInterval.value) * 1000; } const HeartBeatInterval = ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.HeartBeatInterval + StandardParametersKey.HeartBeatInterval, ); if (HeartBeatInterval) { return convertToInt(HeartBeatInterval.value) * 1000; @@ -530,7 +530,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${ Constants.DEFAULT_HEARTBEAT_INTERVAL - }` + }`, ); return Constants.DEFAULT_HEARTBEAT_INTERVAL; } @@ -543,7 +543,7 @@ export class ChargingStation { ChargingStationConfigurationUtils.setConfigurationKeyValue( this, this.getSupervisionUrlOcppKey(), - url + url, ); } else { this.stationInfo.supervisionUrls = url; @@ -560,25 +560,25 @@ export class ChargingStation { .catch((error) => { logger.error( `${this.logPrefix()} Error while sending '${RequestCommand.HEARTBEAT}':`, - error + error, ); }); }, this.getHeartbeatInterval()); logger.info( `${this.logPrefix()} Heartbeat started every ${formatDurationMilliSeconds( - this.getHeartbeatInterval() - )}` + this.getHeartbeatInterval(), + )}`, ); } else if (this.heartbeatSetInterval) { logger.info( `${this.logPrefix()} Heartbeat already started every ${formatDurationMilliSeconds( - this.getHeartbeatInterval() - )}` + this.getHeartbeatInterval(), + )}`, ); } else { logger.error( `${this.logPrefix()} Heartbeat interval set to ${this.getHeartbeatInterval()}, - not starting the heartbeat` + not starting the heartbeat`, ); } } @@ -600,21 +600,21 @@ export class ChargingStation { public startMeterValues(connectorId: number, interval: number): void { if (connectorId === 0) { logger.error( - `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}` + `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId.toString()}`, ); return; } if (!this.getConnectorStatus(connectorId)) { logger.error( `${this.logPrefix()} Trying to start MeterValues on non existing connector id - ${connectorId.toString()}` + ${connectorId.toString()}`, ); return; } if (this.getConnectorStatus(connectorId)?.transactionStarted === false) { logger.error( `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} - with no transaction started` + with no transaction started`, ); return; } else if ( @@ -623,7 +623,7 @@ export class ChargingStation { ) { logger.error( `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} - with no transaction id` + with no transaction id`, ); return; } @@ -634,7 +634,7 @@ export class ChargingStation { this, connectorId, this.getConnectorStatus(connectorId).transactionId, - interval + interval, ); this.ocppRequestService .requestHandler( @@ -644,12 +644,12 @@ export class ChargingStation { connectorId, transactionId: this.getConnectorStatus(connectorId)?.transactionId, meterValue: [meterValue], - } + }, ) .catch((error) => { logger.error( `${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`, - error + error, ); }); }, interval); @@ -657,7 +657,7 @@ export class ChargingStation { logger.error( `${this.logPrefix()} Charging station ${ StandardParametersKey.MeterValueSampleInterval - } configuration set to ${interval}, not sending MeterValues` + } configuration set to ${interval}, not sending MeterValues`, ); } } @@ -691,7 +691,7 @@ export class ChargingStation { logger.debug( `${this.logPrefix()} ${FileType.ChargingStationTemplate} ${ this.templateFile - } file have changed, reload` + } file have changed, reload`, ); this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash); // Initialize @@ -711,11 +711,11 @@ export class ChargingStation { } catch (error) { logger.error( `${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`, - error + error, ); } } - } + }, ); this.started = true; parentPort?.postMessage(buildStartedMessage(this)); @@ -769,7 +769,7 @@ export class ChargingStation { public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean | undefined { return ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.SupportedFeatureProfiles + StandardParametersKey.SupportedFeatureProfiles, )?.value?.includes(featureProfile); } @@ -782,14 +782,14 @@ export class ChargingStation { params: { closeOpened?: boolean; terminateOpened?: boolean } = { closeOpened: false, terminateOpened: false, - } + }, ): void { options = { handshakeTimeout: this.getConnectionTimeout() * 1000, ...options }; params = { ...{ closeOpened: false, terminateOpened: false }, ...params }; if (this.started === false && this.starting === false) { logger.warn( `${this.logPrefix()} Cannot open OCPP connection to URL ${this.wsConnectionUrl.toString()} - on stopped charging station` + on stopped charging station`, ); return; } @@ -809,35 +809,35 @@ export class ChargingStation { if (this.isWebSocketConnectionOpened() === true) { logger.warn( `${this.logPrefix()} OCPP connection to URL ${this.wsConnectionUrl.toString()} - is already opened` + is already opened`, ); return; } logger.info( - `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}` + `${this.logPrefix()} Open OCPP connection to URL ${this.wsConnectionUrl.toString()}`, ); this.wsConnection = new WebSocket( this.wsConnectionUrl, `ocpp${this.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16}`, - options + options, ); // Handle WebSocket message this.wsConnection.on( 'message', - this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void + this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void, ); // Handle WebSocket error this.wsConnection.on( 'error', - this.onError.bind(this) as (this: WebSocket, error: Error) => void + this.onError.bind(this) as (this: WebSocket, error: Error) => void, ); // Handle WebSocket close this.wsConnection.on( 'close', - this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void + this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void, ); // Handle WebSocket open this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void); @@ -909,7 +909,7 @@ export class ChargingStation { public async stopTransactionOnConnector( connectorId: number, - reason = StopTransactionReason.NONE + reason = StopTransactionReason.NONE, ): Promise { const transactionId = this.getConnectorStatus(connectorId)?.transactionId; if ( @@ -921,7 +921,7 @@ export class ChargingStation { const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue( this, connectorId, - this.getEnergyActiveImportRegisterByTransactionId(transactionId) + this.getEnergyActiveImportRegisterByTransactionId(transactionId), ); await this.ocppRequestService.requestHandler( this, @@ -930,7 +930,7 @@ export class ChargingStation { connectorId, transactionId, meterValue: [transactionEndMeterValue], - } + }, ); } return this.ocppRequestService.requestHandler( @@ -940,7 +940,7 @@ export class ChargingStation { transactionId, meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true), reason, - } + }, ); } @@ -948,8 +948,8 @@ export class ChargingStation { return convertToBoolean( ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.ReserveConnectorZeroSupported - ).value + StandardParametersKey.ReserveConnectorZeroSupported, + ).value, ); } @@ -964,13 +964,13 @@ export class ChargingStation { reservation.connectorId, ConnectorStatusEnum.Reserved, null, - { send: reservation.connectorId !== 0 } + { send: reservation.connectorId !== 0 }, ); } public async removeReservation( reservation: Reservation, - reason?: ReservationTerminationReason + reason?: ReservationTerminationReason, ): Promise { const connector = this.getConnectorStatus(reservation.connectorId); switch (reason) { @@ -988,7 +988,7 @@ export class ChargingStation { reservation.connectorId, ConnectorStatusEnum.Available, null, - { send: reservation.connectorId !== 0 } + { send: reservation.connectorId !== 0 }, ); delete connector.reservation; break; @@ -999,7 +999,7 @@ export class ChargingStation { public getReservationBy( filterKey: ReservationFilterKey, - value: number | string + value: number | string, ): Reservation | undefined { if (this.hasEvses) { for (const evseStatus of this.evses.values()) { @@ -1021,7 +1021,7 @@ export class ChargingStation { public doesReservationExists(reservation: Partial): [boolean, Reservation] { const foundReservation = this.getReservationBy( ReservationFilterKey.RESERVATION_ID, - reservation?.id + reservation?.id, ); return isUndefined(foundReservation) ? [false, null] : [true, foundReservation]; } @@ -1031,7 +1031,7 @@ export class ChargingStation { customInterval ?? Constants.DEFAULT_RESERVATION_EXPIRATION_OBSERVATION_INTERVAL; logger.info( `${this.logPrefix()} Reservation expiration date interval is set to ${interval} - and starts on charging station now` + and starts on charging station now`, ); // eslint-disable-next-line @typescript-eslint/no-misused-promises this.reservationExpirationSetInterval = setInterval(async (): Promise => { @@ -1042,7 +1042,7 @@ export class ChargingStation { if (connectorStatus?.reservation?.expiryDate < now) { await this.removeReservation( connectorStatus.reservation, - ReservationTerminationReason.EXPIRED + ReservationTerminationReason.EXPIRED, ); } } @@ -1052,7 +1052,7 @@ export class ChargingStation { if (connectorStatus?.reservation?.expiryDate < now) { await this.removeReservation( connectorStatus.reservation, - ReservationTerminationReason.EXPIRED + ReservationTerminationReason.EXPIRED, ); } } @@ -1072,14 +1072,14 @@ export class ChargingStation { public isConnectorReservable( reservationId: number, idTag?: string, - connectorId?: number + connectorId?: number, ): boolean { const [alreadyExists] = this.doesReservationExists({ id: reservationId }); if (alreadyExists) { return alreadyExists; } const userReservedAlready = isUndefined( - this.getReservationBy(ReservationFilterKey.ID_TAG, idTag) + this.getReservationBy(ReservationFilterKey.ID_TAG, idTag), ) ? false : true; @@ -1125,8 +1125,8 @@ export class ChargingStation { isRequest && PerformanceStatistics.endMeasure(commandName, beginId); logger.debug( `${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString( - messageType - )} payload sent: ${message}` + messageType, + )} payload sent: ${message}`, ); this.messageBuffer.delete(message); } @@ -1168,7 +1168,7 @@ export class ChargingStation { this.templateFile, FileType.ChargingStationTemplate, error as NodeJS.ErrnoException, - this.logPrefix() + this.logPrefix(), ); } return template; @@ -1209,7 +1209,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Firmware version '${stationInfo.firmwareVersion}' in template file ${ this.templateFile - } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'` + } does not match firmware version pattern '${stationInfo.firmwareVersionPattern}'`, ); } stationInfo.firmwareUpgrade = merge( @@ -1219,7 +1219,7 @@ export class ChargingStation { }, reset: true, }, - stationTemplate?.firmwareUpgrade ?? {} + stationTemplate?.firmwareUpgrade ?? {}, ); stationInfo.resetTime = !isNullOrUndefined(stationTemplate?.resetTime) ? stationTemplate.resetTime * 1000 @@ -1252,7 +1252,7 @@ export class ChargingStation { propagateSerialNumber( this.getTemplateFromFile(), stationInfoFromFile, - stationInfoFromTemplate + stationInfoFromTemplate, ); return stationInfoFromTemplate; } @@ -1287,7 +1287,7 @@ export class ChargingStation { checkTemplate(stationTemplate, this.logPrefix(), this.templateFile); this.configurationFile = join( dirname(this.templateFile.replace('station-templates', 'configurations')), - `${getHashId(this.index, stationTemplate)}.json` + `${getHashId(this.index, stationTemplate)}.json`, ); const chargingStationConfiguration = this.getConfigurationFromFile(); if ( @@ -1323,7 +1323,7 @@ export class ChargingStation { this.performanceStatistics = PerformanceStatistics.getInstance( this.stationInfo.hashId, this.stationInfo.chargingStationId, - this.configuredSupervisionUrl + this.configuredSupervisionUrl, ); } this.bootNotificationRequest = createBootNotificationRequest(this.stationInfo); @@ -1348,7 +1348,7 @@ export class ChargingStation { this.ocppIncomingRequestService = OCPP16IncomingRequestService.getInstance(); this.ocppRequestService = OCPP16RequestService.getInstance( - OCPP16ResponseService.getInstance() + OCPP16ResponseService.getInstance(), ); break; case OCPPVersion.VERSION_20: @@ -1356,7 +1356,7 @@ export class ChargingStation { this.ocppIncomingRequestService = OCPP20IncomingRequestService.getInstance(); this.ocppRequestService = OCPP20RequestService.getInstance( - OCPP20ResponseService.getInstance() + OCPP20ResponseService.getInstance(), ); break; default: @@ -1369,26 +1369,26 @@ export class ChargingStation { if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.HeartbeatInterval + StandardParametersKey.HeartbeatInterval, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.HeartbeatInterval, - '0' + '0', ); } if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.HeartBeatInterval + StandardParametersKey.HeartBeatInterval, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.HeartBeatInterval, '0', - { visible: false } + { visible: false }, ); } if ( @@ -1400,7 +1400,7 @@ export class ChargingStation { this, this.getSupervisionUrlOcppKey(), this.configuredSupervisionUrl.href, - { reboot: true } + { reboot: true }, ); } else if ( !this.getSupervisionUrlOcppConfiguration() && @@ -1410,14 +1410,14 @@ export class ChargingStation { ChargingStationConfigurationUtils.deleteConfigurationKey( this, this.getSupervisionUrlOcppKey(), - { save: false } + { save: false }, ); } if ( isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && !ChargingStationConfigurationUtils.getConfigurationKey( this, - this.stationInfo.amperageLimitationOcppKey + this.stationInfo.amperageLimitationOcppKey, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( @@ -1425,19 +1425,19 @@ export class ChargingStation { this.stationInfo.amperageLimitationOcppKey, ( this.stationInfo.maximumAmperage * getAmperageLimitationUnitDivider(this.stationInfo) - ).toString() + ).toString(), ); } if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.SupportedFeatureProfiles + StandardParametersKey.SupportedFeatureProfiles, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.SupportedFeatureProfiles, - `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}` + `${SupportedFeatureProfiles.Core},${SupportedFeatureProfiles.FirmwareManagement},${SupportedFeatureProfiles.LocalAuthListManagement},${SupportedFeatureProfiles.SmartCharging},${SupportedFeatureProfiles.RemoteTrigger}`, ); } ChargingStationConfigurationUtils.addConfigurationKey( @@ -1445,24 +1445,24 @@ export class ChargingStation { StandardParametersKey.NumberOfConnectors, this.getNumberOfConnectors().toString(), { readonly: true }, - { overwrite: true } + { overwrite: true }, ); if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.MeterValuesSampledData + StandardParametersKey.MeterValuesSampledData, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.MeterValuesSampledData, - MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER + MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, ); } if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.ConnectorPhaseRotation + StandardParametersKey.ConnectorPhaseRotation, ) ) { const connectorsPhaseRotation: string[] = []; @@ -1470,61 +1470,61 @@ export class ChargingStation { for (const evseStatus of this.evses.values()) { for (const connectorId of evseStatus.connectors.keys()) { connectorsPhaseRotation.push( - getPhaseRotationValue(connectorId, this.getNumberOfPhases()) + getPhaseRotationValue(connectorId, this.getNumberOfPhases()), ); } } } else { for (const connectorId of this.connectors.keys()) { connectorsPhaseRotation.push( - getPhaseRotationValue(connectorId, this.getNumberOfPhases()) + getPhaseRotationValue(connectorId, this.getNumberOfPhases()), ); } } ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.ConnectorPhaseRotation, - connectorsPhaseRotation.toString() + connectorsPhaseRotation.toString(), ); } if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.AuthorizeRemoteTxRequests + StandardParametersKey.AuthorizeRemoteTxRequests, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.AuthorizeRemoteTxRequests, - 'true' + 'true', ); } if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.LocalAuthListEnabled + StandardParametersKey.LocalAuthListEnabled, ) && ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.SupportedFeatureProfiles + StandardParametersKey.SupportedFeatureProfiles, )?.value?.includes(SupportedFeatureProfiles.LocalAuthListManagement) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.LocalAuthListEnabled, - 'false' + 'false', ); } if ( !ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.ConnectionTimeOut + StandardParametersKey.ConnectionTimeOut, ) ) { ChargingStationConfigurationUtils.addConfigurationKey( this, StandardParametersKey.ConnectionTimeOut, - Constants.DEFAULT_CONNECTION_TIMEOUT.toString() + Constants.DEFAULT_CONNECTION_TIMEOUT.toString(), ); } this.saveOcppConfiguration(); @@ -1545,7 +1545,7 @@ export class ChargingStation { evseStatusConfiguration.connectorsStatus.map((connectorStatus, connectorId) => [ connectorId, connectorStatus, - ]) + ]), ), }); } @@ -1586,7 +1586,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no connector id 0 configuration` + } with no connector id 0 configuration`, ); } if (stationTemplate?.Connectors) { @@ -1594,7 +1594,7 @@ export class ChargingStation { checkConnectorsConfiguration(stationTemplate, this.logPrefix(), this.templateFile); const connectorsConfigHash = createHash(Constants.DEFAULT_HASH_ALGORITHM) .update( - `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}` + `${JSON.stringify(stationTemplate?.Connectors)}${configuredMaxConnectors.toString()}`, ) .digest('hex'); const connectorsConfigChanged = @@ -1620,7 +1620,7 @@ export class ChargingStation { templateConnectorId, connectorStatus, this.logPrefix(), - this.templateFile + this.templateFile, ); this.connectors.set(connectorId, cloneObject(connectorStatus)); } @@ -1630,7 +1630,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no connectors configuration defined, cannot create connectors` + } with no connectors configuration defined, cannot create connectors`, ); } } @@ -1638,7 +1638,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no connectors configuration defined, using already defined connectors` + } with no connectors configuration defined, using already defined connectors`, ); } } @@ -1653,14 +1653,14 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no evse id 0 configuration` + } with no evse id 0 configuration`, ); } if (!stationTemplate?.Evses[0]?.Connectors[0]) { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with evse id 0 with no connector id 0 configuration` + } with evse id 0 with no connector id 0 configuration`, ); } if (stationTemplate?.Evses) { @@ -1680,7 +1680,7 @@ export class ChargingStation { connectors: buildConnectorsMap( stationTemplate?.Evses[evse]?.Connectors, this.logPrefix(), - this.templateFile + this.templateFile, ), availability: AvailabilityType.Operative, }); @@ -1691,7 +1691,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no evses configuration defined, cannot create evses` + } with no evses configuration defined, cannot create evses`, ); } } @@ -1699,7 +1699,7 @@ export class ChargingStation { logger.warn( `${this.logPrefix()} Charging station information from template ${ this.templateFile - } with no evses configuration defined, using already defined evses` + } with no evses configuration defined, using already defined evses`, ); } } @@ -1710,13 +1710,13 @@ export class ChargingStation { try { if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) { configuration = this.sharedLRUCache.getChargingStationConfiguration( - this.configurationFileHash + this.configurationFileHash, ); } else { const measureId = `${FileType.ChargingStationConfiguration} read`; const beginId = PerformanceStatistics.beginMeasure(measureId); configuration = JSON.parse( - readFileSync(this.configurationFile, 'utf8') + readFileSync(this.configurationFile, 'utf8'), ) as ChargingStationConfiguration; PerformanceStatistics.endMeasure(measureId, beginId); this.sharedLRUCache.setChargingStationConfiguration(configuration); @@ -1727,7 +1727,7 @@ export class ChargingStation { this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, - this.logPrefix() + this.logPrefix(), ); } } @@ -1768,7 +1768,7 @@ export class ChargingStation { } configurationData = merge( configurationData, - buildChargingStationAutomaticTransactionGeneratorConfiguration(this) + buildChargingStationAutomaticTransactionGeneratorConfiguration(this), ); if ( !this.getAutomaticTransactionGeneratorPersistentConfiguration() || @@ -1793,7 +1793,7 @@ export class ChargingStation { stationInfo: configurationData.stationInfo, configurationKey: configurationData.configurationKey, automaticTransactionGenerator: configurationData.automaticTransactionGenerator, - } as ChargingStationConfiguration) + } as ChargingStationConfiguration), ) .digest('hex'); if (this.configurationFileHash !== configurationHash) { @@ -1815,7 +1815,7 @@ export class ChargingStation { this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, - this.logPrefix() + this.logPrefix(), ); }) .finally(() => { @@ -1825,7 +1825,7 @@ export class ChargingStation { logger.debug( `${this.logPrefix()} Not saving unchanged charging station configuration file ${ this.configurationFile - }` + }`, ); } } catch (error) { @@ -1833,12 +1833,12 @@ export class ChargingStation { this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, - this.logPrefix() + this.logPrefix(), ); } } else { logger.error( - `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file` + `${this.logPrefix()} Trying to save charging station configuration to undefined configuration file`, ); } } @@ -1867,7 +1867,7 @@ export class ChargingStation { private async onOpen(): Promise { if (this.isWebSocketConnectionOpened() === true) { logger.info( - `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded` + `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} succeeded`, ); if (this.isRegistered() === false) { // Send BootNotification @@ -1884,7 +1884,7 @@ export class ChargingStation { await sleep( this?.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 - : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL + : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL, ); } } while ( @@ -1899,7 +1899,7 @@ export class ChargingStation { } } else { logger.error( - `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})` + `${this.logPrefix()} Registration failure: max retries reached (${this.getRegistrationMaxRetries()}) or retry disabled (${this.getRegistrationMaxRetries()})`, ); } this.wsConnectionRestarted = false; @@ -1907,7 +1907,7 @@ export class ChargingStation { parentPort?.postMessage(buildUpdatedMessage(this)); } else { logger.warn( - `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` + `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed`, ); } } @@ -1919,8 +1919,8 @@ export class ChargingStation { case WebSocketCloseEventStatusCode.CLOSE_NO_STATUS: logger.info( `${this.logPrefix()} WebSocket normally closed with status '${getWebSocketCloseEventStatusString( - code - )}' and reason '${reason.toString()}'` + code, + )}' and reason '${reason.toString()}'`, ); this.autoReconnectRetryCount = 0; break; @@ -1928,8 +1928,8 @@ export class ChargingStation { default: logger.error( `${this.logPrefix()} WebSocket abnormally closed with status '${getWebSocketCloseEventStatusString( - code - )}' and reason '${reason.toString()}'` + code, + )}' and reason '${reason.toString()}'`, ); this.started === true && (await this.reconnect()); break; @@ -1945,10 +1945,10 @@ export class ChargingStation { throw new OCPPError( ErrorType.PROTOCOL_ERROR, `Cached request for message id ${messageId} ${OCPPServiceUtils.getMessageTypeString( - messageType + messageType, )} is not an array`, undefined, - cachedRequest as JsonType + cachedRequest as JsonType, ); } @@ -1959,15 +1959,15 @@ export class ChargingStation { } logger.debug( `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify( - request - )}` + request, + )}`, ); // Process the message await this.ocppIncomingRequestService.incomingRequestHandler( this, messageId, commandName, - commandPayload + commandPayload, ); } @@ -1979,18 +1979,18 @@ export class ChargingStation { ErrorType.INTERNAL_ERROR, `Response for unknown message id ${messageId}`, undefined, - commandPayload + commandPayload, ); } // Respond const [responseCallback, , requestCommandName, requestPayload] = this.getCachedRequest( messageType, - messageId + messageId, ); logger.debug( `${this.logPrefix()} << Command '${ requestCommandName ?? Constants.UNKNOWN_COMMAND - }' received response payload: ${JSON.stringify(response)}` + }' received response payload: ${JSON.stringify(response)}`, ); responseCallback(commandPayload, requestPayload); } @@ -2003,14 +2003,14 @@ export class ChargingStation { ErrorType.INTERNAL_ERROR, `Error response for unknown message id ${messageId}`, undefined, - { errorType, errorMessage, errorDetails } + { errorType, errorMessage, errorDetails }, ); } const [, errorCallback, requestCommandName] = this.getCachedRequest(messageType, messageId); logger.debug( `${this.logPrefix()} << Command '${ requestCommandName ?? Constants.UNKNOWN_COMMAND - }' received error response payload: ${JSON.stringify(errorResponse)}` + }' received error response payload: ${JSON.stringify(errorResponse)}`, ); errorCallback(new OCPPError(errorType, errorMessage, requestCommandName, errorDetails)); } @@ -2078,7 +2078,7 @@ export class ChargingStation { `${this.logPrefix()} Error thrown at incoming OCPP command '${ commandName ?? requestCommandName ?? Constants.UNKNOWN_COMMAND }' message '${data.toString()}' handling is not an OCPPError:`, - error + error, ); } logger.error( @@ -2089,7 +2089,7 @@ export class ChargingStation { ? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'` : '' } processing error:`, - error + error, ); } } @@ -2152,15 +2152,15 @@ export class ChargingStation { if ( ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.ConnectionTimeOut + StandardParametersKey.ConnectionTimeOut, ) ) { return ( parseInt( ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.ConnectionTimeOut - ).value + StandardParametersKey.ConnectionTimeOut, + ).value, ) ?? Constants.DEFAULT_CONNECTION_TIMEOUT ); } @@ -2194,7 +2194,7 @@ export class ChargingStation { return ACElectricUtils.amperagePerPhaseFromPower( this.getNumberOfPhases(stationInfo), maximumPower / (this.hasEvses ? this.getNumberOfEvses() : this.getNumberOfConnectors()), - this.getVoltageOut(stationInfo) + this.getVoltageOut(stationInfo), ); case CurrentType.DC: return DCElectricUtils.amperage(maximumPower, this.getVoltageOut(stationInfo)); @@ -2206,15 +2206,15 @@ export class ChargingStation { isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && ChargingStationConfigurationUtils.getConfigurationKey( this, - this.stationInfo.amperageLimitationOcppKey + this.stationInfo.amperageLimitationOcppKey, ) ) { return ( convertToInt( ChargingStationConfigurationUtils.getConfigurationKey( this, - this.stationInfo.amperageLimitationOcppKey - )?.value + this.stationInfo.amperageLimitationOcppKey, + )?.value, ) / getAmperageLimitationUnitDivider(this.stationInfo) ); } @@ -2243,7 +2243,7 @@ export class ChargingStation { this, connectorId, connectorBootStatus, - evseId + evseId, ); } } @@ -2254,7 +2254,7 @@ export class ChargingStation { const connectorBootStatus = getBootConnectorStatus( this, connectorId, - this.getConnectorStatus(connectorId) + this.getConnectorStatus(connectorId), ); await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorBootStatus); } @@ -2278,7 +2278,7 @@ export class ChargingStation { } private async stopMessageSequence( - reason: StopTransactionReason = StopTransactionReason.NONE + reason: StopTransactionReason = StopTransactionReason.NONE, ): Promise { // Stop WebSocket ping this.stopWebSocketPing(); @@ -2304,8 +2304,8 @@ export class ChargingStation { this, connectorId, ConnectorStatusEnum.Unavailable, - evseId - ) + evseId, + ), ); delete connectorStatus?.status; } @@ -2323,8 +2323,8 @@ export class ChargingStation { OCPPServiceUtils.buildStatusNotificationRequest( this, connectorId, - ConnectorStatusEnum.Unavailable - ) + ConnectorStatusEnum.Unavailable, + ), ); delete this.getConnectorStatus(connectorId)?.status; } @@ -2335,13 +2335,13 @@ export class ChargingStation { private startWebSocketPing(): void { const webSocketPingInterval: number = ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.WebSocketPingInterval + StandardParametersKey.WebSocketPingInterval, ) ? convertToInt( ChargingStationConfigurationUtils.getConfigurationKey( this, - StandardParametersKey.WebSocketPingInterval - )?.value + StandardParametersKey.WebSocketPingInterval, + )?.value, ) : 0; if (webSocketPingInterval > 0 && !this.webSocketPingSetInterval) { @@ -2352,18 +2352,18 @@ export class ChargingStation { }, webSocketPingInterval * 1000); logger.info( `${this.logPrefix()} WebSocket ping started every ${formatDurationSeconds( - webSocketPingInterval - )}` + webSocketPingInterval, + )}`, ); } else if (this.webSocketPingSetInterval) { logger.info( `${this.logPrefix()} WebSocket ping already started every ${formatDurationSeconds( - webSocketPingInterval - )}` + webSocketPingInterval, + )}`, ); } else { logger.error( - `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping` + `${this.logPrefix()} WebSocket ping interval set to ${webSocketPingInterval}, not starting the WebSocket ping`, ); } } @@ -2388,12 +2388,12 @@ export class ChargingStation { case SupervisionUrlDistribution.CHARGING_STATION_AFFINITY: default: Object.values(SupervisionUrlDistribution).includes( - Configuration.getSupervisionUrlDistribution() + Configuration.getSupervisionUrlDistribution(), ) === false && logger.error( `${this.logPrefix()} Unknown supervision url distribution '${Configuration.getSupervisionUrlDistribution()}' from values '${SupervisionUrlDistribution.toString()}', defaulting to ${ SupervisionUrlDistribution.CHARGING_STATION_AFFINITY - }` + }`, ); configuredSupervisionUrlIndex = (this.index - 1) % supervisionUrls.length; break; @@ -2453,26 +2453,26 @@ export class ChargingStation { logger.error( `${this.logPrefix()} WebSocket connection retry in ${roundTo( reconnectDelay, - 2 - )}ms, timeout ${reconnectTimeout}ms` + 2, + )}ms, timeout ${reconnectTimeout}ms`, ); await sleep(reconnectDelay); logger.error( - `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}` + `${this.logPrefix()} WebSocket connection retry #${this.autoReconnectRetryCount.toString()}`, ); this.openWSConnection( { ...(this.stationInfo?.wsOptions ?? {}), handshakeTimeout: reconnectTimeout, }, - { closeOpened: true } + { closeOpened: true }, ); this.wsConnectionRestarted = true; } else if (this.getAutoReconnectMaxRetries() !== -1) { logger.error( `${this.logPrefix()} WebSocket connection retries failure: maximum retries reached (${ this.autoReconnectRetryCount - }) or retries disabled (${this.getAutoReconnectMaxRetries()})` + }) or retries disabled (${this.getAutoReconnectMaxRetries()})`, ); } } diff --git a/src/charging-station/ChargingStationConfigurationUtils.ts b/src/charging-station/ChargingStationConfigurationUtils.ts index 7ffb4e21..59e39300 100644 --- a/src/charging-station/ChargingStationConfigurationUtils.ts +++ b/src/charging-station/ChargingStationConfigurationUtils.ts @@ -14,7 +14,7 @@ export class ChargingStationConfigurationUtils { public static getConfigurationKey( chargingStation: ChargingStation, key: ConfigurationKeyType, - caseInsensitive = false + caseInsensitive = false, ): ConfigurationKey | undefined { return chargingStation.ocppConfiguration?.configurationKey?.find((configElement) => { if (caseInsensitive) { @@ -33,7 +33,7 @@ export class ChargingStationConfigurationUtils { visible: true, reboot: false, }, - params: AddConfigurationKeyParams = { overwrite: false, save: false } + params: AddConfigurationKeyParams = { overwrite: false, save: false }, ): void { options = { ...{ @@ -63,7 +63,7 @@ export class ChargingStationConfigurationUtils { } else { logger.error( `${chargingStation.logPrefix()} Trying to add an already existing configuration key: %j`, - keyFound + keyFound, ); } } @@ -72,12 +72,12 @@ export class ChargingStationConfigurationUtils { chargingStation: ChargingStation, key: ConfigurationKeyType, value: string, - caseInsensitive = false + caseInsensitive = false, ): void { const keyFound = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, key, - caseInsensitive + caseInsensitive, ); if (keyFound) { chargingStation.ocppConfiguration.configurationKey[ @@ -87,7 +87,7 @@ export class ChargingStationConfigurationUtils { } else { logger.error( `${chargingStation.logPrefix()} Trying to set a value on a non existing configuration key: %j`, - { key, value } + { key, value }, ); } } @@ -95,18 +95,18 @@ export class ChargingStationConfigurationUtils { public static deleteConfigurationKey( chargingStation: ChargingStation, key: ConfigurationKeyType, - params: DeleteConfigurationKeyParams = { save: true, caseInsensitive: false } + params: DeleteConfigurationKeyParams = { save: true, caseInsensitive: false }, ): ConfigurationKey[] | undefined { params = { ...{ save: true, caseInsensitive: false }, ...params }; const keyFound = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, key, - params?.caseInsensitive + params?.caseInsensitive, ); if (keyFound) { const deletedConfigurationKey = chargingStation.ocppConfiguration?.configurationKey?.splice( chargingStation.ocppConfiguration.configurationKey.indexOf(keyFound), - 1 + 1, ); params?.save && chargingStation.saveOcppConfiguration(); return deletedConfigurationKey; diff --git a/src/charging-station/ChargingStationUtils.ts b/src/charging-station/ChargingStationUtils.ts index d0d99c0b..3e6e578b 100644 --- a/src/charging-station/ChargingStationUtils.ts +++ b/src/charging-station/ChargingStationUtils.ts @@ -51,7 +51,7 @@ const moduleName = 'ChargingStationUtils'; export const getChargingStationId = ( index: number, - stationTemplate: ChargingStationTemplate + stationTemplate: ChargingStationTemplate, ): string => { // In case of multiple instances: add instance index to charging station id const instanceIndex = process.env.CF_INSTANCE_INDEX ?? 0; @@ -60,7 +60,7 @@ export const getChargingStationId = ( return stationTemplate?.fixedName ? stationTemplate.baseName : `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring( - idStr.length - 4 + idStr.length - 4, )}${idSuffix}`; }; @@ -101,7 +101,7 @@ export const getHashId = (index: number, stationTemplate: ChargingStationTemplat export const checkChargingStation = ( chargingStation: ChargingStation, - logPrefix: string + logPrefix: string, ): boolean => { if (chargingStation.started === false && chargingStation.starting === false) { logger.warn(`${logPrefix} charging station is stopped, cannot proceed`); @@ -112,7 +112,7 @@ export const checkChargingStation = ( export const getPhaseRotationValue = ( connectorId: number, - numberOfPhases: number + numberOfPhases: number, ): string | undefined => { // AC/DC if (connectorId === 0 && numberOfPhases === 0) { @@ -144,7 +144,7 @@ const getMaxNumberOfConnectors = (connectors: Record): export const getBootConnectorStatus = ( chargingStation: ChargingStation, connectorId: number, - connectorStatus: ConnectorStatus + connectorStatus: ConnectorStatus, ): ConnectorStatusEnum => { let connectorBootStatus: ConnectorStatusEnum; if ( @@ -169,7 +169,7 @@ export const getBootConnectorStatus = ( export const checkTemplate = ( stationTemplate: ChargingStationTemplate, logPrefix: string, - templateFile: string + templateFile: string, ): void => { if (isNullOrUndefined(stationTemplate)) { const errorMsg = `Failed to read charging station template file ${templateFile}`; @@ -185,12 +185,12 @@ export const checkTemplate = ( stationTemplate.AutomaticTransactionGenerator = Constants.DEFAULT_ATG_CONFIGURATION; logger.warn( `${logPrefix} Empty automatic transaction generator configuration from template file ${templateFile}, set to default: %j`, - Constants.DEFAULT_ATG_CONFIGURATION + Constants.DEFAULT_ATG_CONFIGURATION, ); } if (isNullOrUndefined(stationTemplate.idTagsFile) || isEmptyString(stationTemplate.idTagsFile)) { logger.warn( - `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator` + `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator`, ); } }; @@ -198,7 +198,7 @@ export const checkTemplate = ( export const checkConnectorsConfiguration = ( stationTemplate: ChargingStationTemplate, logPrefix: string, - templateFile: string + templateFile: string, ): { configuredMaxConnectors: number; templateMaxConnectors: number; @@ -216,7 +216,7 @@ export const checkConnectorsConfiguration = ( !stationTemplate?.randomConnectors ) { logger.warn( - `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation` + `${logPrefix} Number of connectors exceeds the number of connector configurations in template ${templateFile}, forcing random connector configurations affectation`, ); stationTemplate.randomConnectors = true; } @@ -227,11 +227,11 @@ export const checkStationInfoConnectorStatus = ( connectorId: number, connectorStatus: ConnectorStatus, logPrefix: string, - templateFile: string + templateFile: string, ): void => { if (!isNullOrUndefined(connectorStatus?.status)) { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId} status configuration defined, undefine it` + `${logPrefix} Charging station information from template ${templateFile} with connector id ${connectorId} status configuration defined, undefine it`, ); delete connectorStatus.status; } @@ -240,7 +240,7 @@ export const checkStationInfoConnectorStatus = ( export const buildConnectorsMap = ( connectors: Record, logPrefix: string, - templateFile: string + templateFile: string, ): Map => { const connectorsMap = new Map(); if (getMaxNumberOfConnectors(connectors) > 0) { @@ -252,7 +252,7 @@ export const buildConnectorsMap = ( } } else { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map` + `${logPrefix} Charging station information from template ${templateFile} with no connectors, cannot build connectors map`, ); } return connectorsMap; @@ -260,14 +260,14 @@ export const buildConnectorsMap = ( export const initializeConnectorsMapStatus = ( connectors: Map, - logPrefix: string + logPrefix: string, ): void => { for (const connectorId of connectors.keys()) { if (connectorId > 0 && connectors.get(connectorId)?.transactionStarted === true) { logger.warn( - `${logPrefix} Connector id ${connectorId} at initialization has a transaction started with id ${ - connectors.get(connectorId)?.transactionId - }` + `${logPrefix} Connector id ${connectorId} at initialization has a transaction started with id ${connectors.get( + connectorId, + )?.transactionId}`, ); } if (connectorId === 0) { @@ -299,7 +299,7 @@ export const resetConnectorStatus = (connectorStatus: ConnectorStatus): void => export const createBootNotificationRequest = ( stationInfo: ChargingStationInfo, - bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp + bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp, ): BootNotificationRequest => { const ocppVersion = stationInfo.ocppVersion ?? OCPPVersion.VERSION_16; switch (ocppVersion) { @@ -352,7 +352,7 @@ export const createBootNotificationRequest = ( export const warnTemplateKeysDeprecation = ( stationTemplate: ChargingStationTemplate, logPrefix: string, - templateFile: string + templateFile: string, ) => { const templateKeys: { key: string; deprecatedKey: string }[] = [ { key: 'supervisionUrls', deprecatedKey: 'supervisionUrl' }, @@ -364,14 +364,14 @@ export const warnTemplateKeysDeprecation = ( templateKey.deprecatedKey, logPrefix, templateFile, - `Use '${templateKey.key}' instead` + `Use '${templateKey.key}' instead`, ); convertDeprecatedTemplateKey(stationTemplate, templateKey.deprecatedKey, templateKey.key); } }; export const stationTemplateToStationInfo = ( - stationTemplate: ChargingStationTemplate + stationTemplate: ChargingStationTemplate, ): ChargingStationInfo => { stationTemplate = cloneObject(stationTemplate); delete stationTemplate.power; @@ -395,7 +395,7 @@ export const createSerialNumber = ( } = { randomSerialNumberUpperCase: true, randomSerialNumber: true, - } + }, ): void => { params = { ...{ randomSerialNumberUpperCase: true, randomSerialNumber: true }, ...params }; const serialNumberSuffix = params?.randomSerialNumber @@ -414,11 +414,11 @@ export const createSerialNumber = ( export const propagateSerialNumber = ( stationTemplate: ChargingStationTemplate, stationInfoSrc: ChargingStationInfo, - stationInfoDst: ChargingStationInfo + stationInfoDst: ChargingStationInfo, ) => { if (!stationInfoSrc || !stationTemplate) { throw new BaseError( - 'Missing charging station template or existing configuration to propagate serial number' + 'Missing charging station template or existing configuration to propagate serial number', ); } stationTemplate?.chargePointSerialNumberPrefix && stationInfoSrc?.chargePointSerialNumber @@ -450,20 +450,20 @@ export const getAmperageLimitationUnitDivider = (stationInfo: ChargingStationInf export const getChargingStationConnectorChargingProfilesPowerLimit = ( chargingStation: ChargingStation, - connectorId: number + connectorId: number, ): number | undefined => { let limit: number, matchingChargingProfile: ChargingProfile; // Get charging profiles for connector and sort by stack level const chargingProfiles = cloneObject( - chargingStation.getConnectorStatus(connectorId)?.chargingProfiles + chargingStation.getConnectorStatus(connectorId)?.chargingProfiles, )?.sort((a, b) => b.stackLevel - a.stackLevel) ?? []; // Get profiles on connector 0 if (chargingStation.getConnectorStatus(0)?.chargingProfiles) { chargingProfiles.push( ...cloneObject( - chargingStation.getConnectorStatus(0).chargingProfiles - ).sort((a, b) => b.stackLevel - a.stackLevel) + chargingStation.getConnectorStatus(0).chargingProfiles, + ).sort((a, b) => b.stackLevel - a.stackLevel), ); } if (isNotEmptyArray(chargingProfiles)) { @@ -479,7 +479,7 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = ( : ACElectricUtils.powerTotal( chargingStation.getNumberOfPhases(), chargingStation.getVoltageOut(), - limit + limit, ); break; case CurrentType.DC: @@ -495,7 +495,7 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = ( `${chargingStation.logPrefix()} Charging profile id ${ matchingChargingProfile.chargingProfileId } limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`, - result + result, ); limit = connectorMaximumPower; } @@ -507,7 +507,7 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = ( export const getDefaultVoltageOut = ( currentType: CurrentType, logPrefix: string, - templateFile: string + templateFile: string, ): Voltage => { const errorMsg = `Unknown ${currentType} currentOutType in template file ${templateFile}, cannot define default voltage out`; let defaultVoltageOut: number; @@ -535,7 +535,7 @@ export const getIdTagsFile = (stationInfo: ChargingStationInfo): string | undefi export const waitChargingStationEvents = async ( emitter: EventEmitter, event: ChargingStationWorkerMessageEvents, - eventsToWait: number + eventsToWait: number, ): Promise => { return new Promise((resolve) => { let events = 0; @@ -578,11 +578,11 @@ const getConfiguredNumberOfConnectors = (stationTemplate: ChargingStationTemplat const checkConfiguredMaxConnectors = ( configuredMaxConnectors: number, logPrefix: string, - templateFile: string + templateFile: string, ): void => { if (configuredMaxConnectors <= 0) { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors` + `${logPrefix} Charging station information from template ${templateFile} with ${configuredMaxConnectors} connectors`, ); } }; @@ -590,15 +590,15 @@ const checkConfiguredMaxConnectors = ( const checkTemplateMaxConnectors = ( templateMaxConnectors: number, logPrefix: string, - templateFile: string + templateFile: string, ): void => { if (templateMaxConnectors === 0) { logger.warn( - `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration` + `${logPrefix} Charging station information from template ${templateFile} with empty connectors configuration`, ); } else if (templateMaxConnectors < 0) { logger.error( - `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined` + `${logPrefix} Charging station information from template ${templateFile} with no connectors configuration defined`, ); } }; @@ -621,7 +621,7 @@ const warnDeprecatedTemplateKey = ( key: string, logPrefix: string, templateFile: string, - logMsgToAppend = '' + logMsgToAppend = '', ): void => { if (!isUndefined(template[key])) { const logMsg = `Deprecated template key '${key}' usage in file '${templateFile}'${ @@ -635,7 +635,7 @@ const warnDeprecatedTemplateKey = ( const convertDeprecatedTemplateKey = ( template: ChargingStationTemplate, deprecatedKey: string, - key: string + key: string, ): void => { if (!isUndefined(template[deprecatedKey])) { template[key] = template[deprecatedKey] as unknown; @@ -652,7 +652,7 @@ const convertDeprecatedTemplateKey = ( */ const getLimitFromChargingProfiles = ( chargingProfiles: ChargingProfile[], - logPrefix: string + logPrefix: string, ): { limit: number; matchingChargingProfile: ChargingProfile; @@ -665,7 +665,7 @@ const getLimitFromChargingProfiles = ( const chargingSchedule = chargingProfile.chargingSchedule; if (!chargingSchedule?.startSchedule) { logger.warn( - `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not defined in charging profile id ${chargingProfile.chargingProfileId}` + `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not defined in charging profile id ${chargingProfile.chargingProfileId}`, ); } // Check type (recurring) and if it is already active @@ -677,14 +677,14 @@ const getLimitFromChargingProfiles = ( ) { if (!(chargingSchedule?.startSchedule instanceof Date)) { logger.warn( - `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not a Date object in charging profile id ${chargingProfile.chargingProfileId}. Trying to convert it to a Date object` + `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: startSchedule is not a Date object in charging profile id ${chargingProfile.chargingProfileId}. Trying to convert it to a Date object`, ); chargingSchedule.startSchedule = new Date(chargingSchedule.startSchedule); } chargingSchedule.startSchedule.setFullYear( currentDate.getFullYear(), currentDate.getMonth(), - currentDate.getDate() + currentDate.getDate(), ); // Check if the start of the schedule is yesterday if (moment(chargingSchedule.startSchedule).isAfter(currentMoment)) { diff --git a/src/charging-station/ChargingStationWorker.ts b/src/charging-station/ChargingStationWorker.ts index 19f760e7..70d96011 100644 --- a/src/charging-station/ChargingStationWorker.ts +++ b/src/charging-station/ChargingStationWorker.ts @@ -30,7 +30,7 @@ class ChargingStationWorker extends AsyncResource { this.runInAsyncScope( startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, this, - message.data + message.data, ); } }); diff --git a/src/charging-station/IdTagsCache.ts b/src/charging-station/IdTagsCache.ts index bf0838e9..26ef7131 100644 --- a/src/charging-station/IdTagsCache.ts +++ b/src/charging-station/IdTagsCache.ts @@ -46,7 +46,7 @@ export class IdTagsCache { public getIdTag( distribution: IdTagDistribution, chargingStation: ChargingStation, - connectorId: number + connectorId: number, ): string { const hashId = chargingStation.stationInfo.hashId; const idTagsFile = getIdTagsFile(chargingStation.stationInfo); @@ -85,7 +85,7 @@ export class IdTagsCache { const addressableKey = this.getIdTagsCacheIndexesAddressableKey(file, hashId); this.idTagsCachesAddressableIndexes.set( addressableKey, - Math.floor(secureRandom() * idTags.length) + Math.floor(secureRandom() * idTags.length), ); return idTags[this.idTagsCachesAddressableIndexes.get(addressableKey)]; } @@ -97,7 +97,7 @@ export class IdTagsCache { const idTag = idTags[idTagIndex]; this.idTagsCachesAddressableIndexes.set( addressableKey, - idTagIndex === idTags.length - 1 ? 0 : idTagIndex + 1 + idTagIndex === idTags.length - 1 ? 0 : idTagIndex + 1, ); return idTag; } @@ -107,11 +107,11 @@ export class IdTagsCache { const idTags = this.getIdTags(file); const addressableKey = this.getIdTagsCacheIndexesAddressableKey( file, - chargingStation.stationInfo.hashId + chargingStation.stationInfo.hashId, ); this.idTagsCachesAddressableIndexes.set( addressableKey, - (chargingStation.index - 1 + (connectorId - 1)) % idTags.length + (chargingStation.index - 1 + (connectorId - 1)) % idTags.length, ); return idTags[this.idTagsCachesAddressableIndexes.get(addressableKey)]; } @@ -132,7 +132,7 @@ export class IdTagsCache { if (isNotEmptyString(filename) && event === 'change') { try { logger.debug( - `${this.logPrefix(file)} ${FileType.Authorization} file have changed, reload` + `${this.logPrefix(file)} ${FileType.Authorization} file have changed, reload`, ); this.deleteIdTagsCache(file); this.deleteIdTagsCacheIndexes(file); @@ -144,11 +144,11 @@ export class IdTagsCache { this.logPrefix(file), { throwError: false, - } + }, ); } } - } + }, ), }); } @@ -185,7 +185,7 @@ export class IdTagsCache { file, FileType.Authorization, error as NodeJS.ErrnoException, - this.logPrefix(file) + this.logPrefix(file), ); } } diff --git a/src/charging-station/SharedLRUCache.ts b/src/charging-station/SharedLRUCache.ts index 57845313..9fd94079 100644 --- a/src/charging-station/SharedLRUCache.ts +++ b/src/charging-station/SharedLRUCache.ts @@ -18,7 +18,7 @@ export class SharedLRUCache { private constructor() { this.lruCache = new LRUCache( Bootstrap.getInstance().numberOfChargingStationTemplates + - Bootstrap.getInstance().numberOfChargingStations + Bootstrap.getInstance().numberOfChargingStations, ); } @@ -34,21 +34,21 @@ export class SharedLRUCache { } public setChargingStationConfiguration( - chargingStationConfiguration: ChargingStationConfiguration + chargingStationConfiguration: ChargingStationConfiguration, ): void { if (this.isChargingStationConfigurationCacheable(chargingStationConfiguration)) { this.set( this.getChargingStationConfigurationKey(chargingStationConfiguration.configurationHash), - chargingStationConfiguration + chargingStationConfiguration, ); } } public getChargingStationConfiguration( - chargingStationConfigurationHash: string + chargingStationConfigurationHash: string, ): ChargingStationConfiguration { return this.get( - this.getChargingStationConfigurationKey(chargingStationConfigurationHash) + this.getChargingStationConfigurationKey(chargingStationConfigurationHash), ) as ChargingStationConfiguration; } @@ -63,13 +63,13 @@ export class SharedLRUCache { public setChargingStationTemplate(chargingStationTemplate: ChargingStationTemplate): void { this.set( this.getChargingStationTemplateKey(chargingStationTemplate.templateHash), - chargingStationTemplate + chargingStationTemplate, ); } public getChargingStationTemplate(chargingStationTemplateHash: string): ChargingStationTemplate { return this.get( - this.getChargingStationTemplateKey(chargingStationTemplateHash) + this.getChargingStationTemplateKey(chargingStationTemplateHash), ) as ChargingStationTemplate; } @@ -106,7 +106,7 @@ export class SharedLRUCache { } private isChargingStationConfigurationCacheable( - chargingStationConfiguration: ChargingStationConfiguration + chargingStationConfiguration: ChargingStationConfiguration, ): boolean { return ( isNullOrUndefined(chargingStationConfiguration?.configurationKey) === false && diff --git a/src/charging-station/broadcast-channel/ChargingStationWorkerBroadcastChannel.ts b/src/charging-station/broadcast-channel/ChargingStationWorkerBroadcastChannel.ts index 9eb69cd3..a7c6e4ad 100644 --- a/src/charging-station/broadcast-channel/ChargingStationWorkerBroadcastChannel.ts +++ b/src/charging-station/broadcast-channel/ChargingStationWorkerBroadcastChannel.ts @@ -54,7 +54,7 @@ type CommandResponse = | FirmwareStatusNotificationResponse; type CommandHandler = ( - requestPayload?: BroadcastChannelRequestPayload + requestPayload?: BroadcastChannelRequestPayload, ) => Promise | void; export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChannel { @@ -115,11 +115,11 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne { meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId( requestPayload.transactionId, - true + true, ), ...requestPayload, }, - requestParams + requestParams, ), ], [ @@ -147,7 +147,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne { skipBufferingOnError: true, throwError: true, - } + }, ); return this.chargingStation.bootNotificationResponse; }, @@ -162,7 +162,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne this.chargingStation, RequestCommand.STATUS_NOTIFICATION, requestPayload, - requestParams + requestParams, ), ], [ @@ -179,7 +179,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne const configuredMeterValueSampleInterval = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, - StandardParametersKey.MeterValueSampleInterval + StandardParametersKey.MeterValueSampleInterval, ); return this.chargingStation.ocppRequestService.requestHandler< MeterValuesRequest, @@ -197,12 +197,12 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne ?.transactionId, configuredMeterValueSampleInterval ? convertToInt(configuredMeterValueSampleInterval.value) * 1000 - : Constants.DEFAULT_METER_VALUES_INTERVAL + : Constants.DEFAULT_METER_VALUES_INTERVAL, ), ], ...requestPayload, }, - requestParams + requestParams, ); }, ], @@ -224,7 +224,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne this.chargingStation, RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, requestPayload, - requestParams + requestParams, ), ], [ @@ -237,7 +237,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne this.chargingStation, RequestCommand.FIRMWARE_STATUS_NOTIFICATION, requestPayload, - requestParams + requestParams, ), ], ]); @@ -263,7 +263,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne } if (!isNullOrUndefined(requestPayload?.hashId)) { logger.error( - `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: 'hashId' field usage in PDU is deprecated, use 'hashIds' array instead` + `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: 'hashId' field usage in PDU is deprecated, use 'hashIds' array instead`, ); return; } @@ -280,13 +280,13 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne responsePayload = this.commandResponseToResponsePayload( command, requestPayload, - commandResponse as CommandResponse + commandResponse as CommandResponse, ); } } catch (error) { logger.error( `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: Handle request error:`, - error + error, ); responsePayload = { hashId: this.chargingStation.stationInfo.hashId, @@ -306,13 +306,13 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne private messageErrorHandler(messageEvent: MessageEvent): void { logger.error( `${this.chargingStation.logPrefix()} ${moduleName}.messageErrorHandler: Error at handling message:`, - messageEvent + messageEvent, ); } private async commandHandler( command: BroadcastChannelProcedureName, - requestPayload: BroadcastChannelRequestPayload + requestPayload: BroadcastChannelRequestPayload, ): Promise { if (this.commandHandlers.has(command) === true) { this.cleanRequestPayload(command, requestPayload); @@ -323,7 +323,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne private cleanRequestPayload( command: BroadcastChannelProcedureName, - requestPayload: BroadcastChannelRequestPayload + requestPayload: BroadcastChannelRequestPayload, ): void { delete requestPayload.hashId; delete requestPayload.hashIds; @@ -336,7 +336,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne private commandResponseToResponsePayload( command: BroadcastChannelProcedureName, requestPayload: BroadcastChannelRequestPayload, - commandResponse: CommandResponse + commandResponse: CommandResponse, ): BroadcastChannelResponsePayload { const responseStatus = this.commandResponseToResponseStatus(command, commandResponse); if (responseStatus === ResponseStatus.SUCCESS) { @@ -356,7 +356,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne private commandResponseToResponseStatus( command: BroadcastChannelProcedureName, - commandResponse: CommandResponse + commandResponse: CommandResponse, ): ResponseStatus { switch (command) { case BroadcastChannelProcedureName.START_TRANSACTION: diff --git a/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts b/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts index 548b3147..89058ceb 100644 --- a/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts +++ b/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts @@ -102,7 +102,7 @@ export class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChannel { private messageErrorHandler(messageEvent: MessageEvent): void { logger.error( `${this.uiService.logPrefix(moduleName, 'messageErrorHandler')} Error at handling message:`, - messageEvent + messageEvent, ); } } diff --git a/src/charging-station/broadcast-channel/WorkerBroadcastChannel.ts b/src/charging-station/broadcast-channel/WorkerBroadcastChannel.ts index 9168764d..9102b100 100644 --- a/src/charging-station/broadcast-channel/WorkerBroadcastChannel.ts +++ b/src/charging-station/broadcast-channel/WorkerBroadcastChannel.ts @@ -36,8 +36,8 @@ export abstract class WorkerBroadcastChannel extends BroadcastChannel { logger.error( `${this.logPrefix( moduleName, - 'validateMessageEvent' - )} Worker broadcast channel protocol message event data is not an array` + 'validateMessageEvent', + )} Worker broadcast channel protocol message event data is not an array`, ); return false; } @@ -45,8 +45,8 @@ export abstract class WorkerBroadcastChannel extends BroadcastChannel { logger.error( `${this.logPrefix( moduleName, - 'validateMessageEvent' - )} Worker broadcast channel protocol message event data UUID field is invalid` + 'validateMessageEvent', + )} Worker broadcast channel protocol message event data UUID field is invalid`, ); return false; } diff --git a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts index 218f97ea..50c46f29 100644 --- a/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts @@ -166,7 +166,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/Reset.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -174,7 +174,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ClearCache.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -182,7 +182,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/UnlockConnector.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -190,7 +190,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/GetConfiguration.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -198,7 +198,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -206,7 +206,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/GetDiagnostics.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -214,7 +214,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -222,7 +222,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/SetChargingProfile.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -230,7 +230,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -238,7 +238,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ChangeAvailability.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -246,7 +246,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -254,7 +254,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -262,7 +262,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/TriggerMessage.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -270,7 +270,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/DataTransfer.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -278,7 +278,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/UpdateFirmware.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -286,7 +286,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ReserveNow.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -294,14 +294,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/CancelReservation.json', moduleName, - 'constructor' + 'constructor', ), ], ]); this.validatePayload = this.validatePayload.bind(this) as ( chargingStation: ChargingStation, commandName: OCPP16IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ) => boolean; } @@ -309,7 +309,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation: ChargingStation, messageId: string, commandName: OCPP16IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ): Promise { let response: JsonType; if ( @@ -323,10 +323,10 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { `${commandName} cannot be issued to handle request PDU ${JSON.stringify( commandPayload, null, - 2 + 2, )} while the charging station is in pending state on the central server`, commandName, - commandPayload + commandPayload, ); } if ( @@ -343,14 +343,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { // Call the method to build the response response = await this.incomingRequestHandlers.get(commandName)( chargingStation, - commandPayload + commandPayload, ); } catch (error) { // Log logger.error( `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`, - error + error, ); throw error; } @@ -361,10 +361,10 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { `${commandName} is not implemented to handle request PDU ${JSON.stringify( commandPayload, null, - 2 + 2, )}`, commandName, - commandPayload + commandPayload, ); } } else { @@ -373,10 +373,10 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { `${commandName} cannot be issued to handle request PDU ${JSON.stringify( commandPayload, null, - 2 + 2, )} while the charging station is not registered on the central server.`, commandName, - commandPayload + commandPayload, ); } // Send the built response @@ -384,26 +384,26 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, messageId, response, - commandName + commandName, ); } private validatePayload( chargingStation: ChargingStation, commandName: OCPP16IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ): boolean { if (this.jsonSchemas.has(commandName) === true) { return this.validateIncomingRequestPayload( chargingStation, commandName, this.jsonSchemas.get(commandName), - commandPayload + commandPayload, ); } logger.warn( `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found - for command '${commandName}' PDU validation` + for command '${commandName}' PDU validation`, ); return false; } @@ -411,7 +411,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { // Simulate charging station restart private handleRequestReset( chargingStation: ChargingStation, - commandPayload: ResetRequest + commandPayload: ResetRequest, ): GenericResponse { this.runInAsyncScope( chargingStation.reset.bind(chargingStation) as ( @@ -419,39 +419,39 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ...args: any[] ) => Promise, chargingStation, - `${commandPayload.type}Reset` as OCPP16StopTransactionReason + `${commandPayload.type}Reset` as OCPP16StopTransactionReason, ).catch(Constants.EMPTY_FUNCTION); logger.info( `${chargingStation.logPrefix()} ${ commandPayload.type } reset command received, simulating it. The station will be - back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime)}` + back online in ${formatDurationMilliSeconds(chargingStation.stationInfo.resetTime)}`, ); return OCPP16Constants.OCPP_RESPONSE_ACCEPTED; } private async handleRequestUnlockConnector( chargingStation: ChargingStation, - commandPayload: UnlockConnectorRequest + commandPayload: UnlockConnectorRequest, ): Promise { const connectorId = commandPayload.connectorId; if (chargingStation.hasConnector(connectorId) === false) { logger.error( `${chargingStation.logPrefix()} Trying to unlock a non existing - connector id ${connectorId.toString()}` + connector id ${connectorId.toString()}`, ); return OCPP16Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED; } if (connectorId === 0) { logger.error( - `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}` + `${chargingStation.logPrefix()} Trying to unlock connector id ${connectorId.toString()}`, ); return OCPP16Constants.OCPP_RESPONSE_UNLOCK_NOT_SUPPORTED; } if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) { const stopResponse = await chargingStation.stopTransactionOnConnector( connectorId, - OCPP16StopTransactionReason.UNLOCK_COMMAND + OCPP16StopTransactionReason.UNLOCK_COMMAND, ); if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) { return OCPP16Constants.OCPP_RESPONSE_UNLOCKED; @@ -461,14 +461,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Available + OCPP16ChargePointStatus.Available, ); return OCPP16Constants.OCPP_RESPONSE_UNLOCKED; } private handleRequestGetConfiguration( chargingStation: ChargingStation, - commandPayload: GetConfigurationRequest + commandPayload: GetConfigurationRequest, ): GetConfigurationResponse { const configurationKey: OCPPConfigurationKey[] = []; const unknownKey: string[] = []; @@ -491,7 +491,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { const keyFound = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, key, - true + true, ); if (keyFound) { if (isUndefined(keyFound.visible) === true) { @@ -518,12 +518,12 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private handleRequestChangeConfiguration( chargingStation: ChargingStation, - commandPayload: ChangeConfigurationRequest + commandPayload: ChangeConfigurationRequest, ): ChangeConfigurationResponse { const keyToChange = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, commandPayload.key, - true + true, ); if (!keyToChange) { return OCPP16Constants.OCPP_CONFIGURATION_RESPONSE_NOT_SUPPORTED; @@ -536,7 +536,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, commandPayload.key, commandPayload.value, - true + true, ); valueChanged = true; } @@ -545,7 +545,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ChargingStationConfigurationUtils.setConfigurationKeyValue( chargingStation, OCPP16StandardParametersKey.HeartbeatInterval, - commandPayload.value + commandPayload.value, ); triggerHeartbeatRestart = true; } @@ -553,7 +553,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ChargingStationConfigurationUtils.setConfigurationKeyValue( chargingStation, OCPP16StandardParametersKey.HeartBeatInterval, - commandPayload.value + commandPayload.value, ); triggerHeartbeatRestart = true; } @@ -572,13 +572,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private handleRequestSetChargingProfile( chargingStation: ChargingStation, - commandPayload: SetChargingProfileRequest + commandPayload: SetChargingProfileRequest, ): SetChargingProfileResponse { if ( OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.SmartCharging, - OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE + OCPP16IncomingRequestCommand.SET_CHARGING_PROFILE, ) === false ) { return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_NOT_SUPPORTED; @@ -586,7 +586,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (chargingStation.hasConnector(commandPayload.connectorId) === false) { logger.error( `${chargingStation.logPrefix()} Trying to set charging profile(s) to a - non existing connector id ${commandPayload.connectorId}` + non existing connector id ${commandPayload.connectorId}`, ); return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED; } @@ -606,33 +606,33 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ) { logger.error( `${chargingStation.logPrefix()} Trying to set transaction charging profile(s) - on connector ${commandPayload.connectorId} without a started transaction` + on connector ${commandPayload.connectorId} without a started transaction`, ); return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_REJECTED; } OCPP16ServiceUtils.setChargingProfile( chargingStation, commandPayload.connectorId, - commandPayload.csChargingProfiles + commandPayload.csChargingProfiles, ); logger.debug( `${chargingStation.logPrefix()} Charging profile(s) set on connector id ${ commandPayload.connectorId }: %j`, - commandPayload.csChargingProfiles + commandPayload.csChargingProfiles, ); return OCPP16Constants.OCPP_SET_CHARGING_PROFILE_RESPONSE_ACCEPTED; } private handleRequestGetCompositeSchedule( chargingStation: ChargingStation, - commandPayload: OCPP16GetCompositeScheduleRequest + commandPayload: OCPP16GetCompositeScheduleRequest, ): OCPP16GetCompositeScheduleResponse { if ( OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.SmartCharging, - OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE + OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE, ) === false ) { return OCPP16Constants.OCPP_RESPONSE_REJECTED; @@ -640,7 +640,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (chargingStation.hasConnector(commandPayload.connectorId) === false) { logger.error( `${chargingStation.logPrefix()} Trying to get composite schedule to a - non existing connector id ${commandPayload.connectorId}` + non existing connector id ${commandPayload.connectorId}`, ); return OCPP16Constants.OCPP_RESPONSE_REJECTED; } @@ -673,13 +673,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private handleRequestClearChargingProfile( chargingStation: ChargingStation, - commandPayload: ClearChargingProfileRequest + commandPayload: ClearChargingProfileRequest, ): ClearChargingProfileResponse { if ( OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.SmartCharging, - OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE + OCPP16IncomingRequestCommand.CLEAR_CHARGING_PROFILE, ) === false ) { return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN; @@ -687,21 +687,21 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (chargingStation.hasConnector(commandPayload.connectorId) === false) { logger.error( `${chargingStation.logPrefix()} Trying to clear a charging profile(s) to - a non existing connector id ${commandPayload.connectorId}` + a non existing connector id ${commandPayload.connectorId}`, ); return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_UNKNOWN; } if ( !isNullOrUndefined(commandPayload.connectorId) && isNotEmptyArray( - chargingStation.getConnectorStatus(commandPayload.connectorId)?.chargingProfiles + chargingStation.getConnectorStatus(commandPayload.connectorId)?.chargingProfiles, ) ) { chargingStation.getConnectorStatus(commandPayload.connectorId).chargingProfiles = []; logger.debug( `${chargingStation.logPrefix()} Charging profile(s) cleared on connector id ${ commandPayload.connectorId - }` + }`, ); return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED; } @@ -737,11 +737,11 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { connectorStatus?.chargingProfiles?.splice(index, 1); logger.debug( `${chargingStation.logPrefix()} Matching charging profile(s) cleared: %j`, - chargingProfile + chargingProfile, ); clearedCP = true; } - } + }, ); } }; @@ -765,13 +765,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private async handleRequestChangeAvailability( chargingStation: ChargingStation, - commandPayload: ChangeAvailabilityRequest + commandPayload: ChangeAvailabilityRequest, ): Promise { const connectorId: number = commandPayload.connectorId; if (chargingStation.hasConnector(connectorId) === false) { logger.error( `${chargingStation.logPrefix()} Trying to change the availability of a - non existing connector id ${connectorId.toString()}` + non existing connector id ${connectorId.toString()}`, ); return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_REJECTED; } @@ -791,7 +791,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, id, - chargePointStatus + chargePointStatus, ); } }; @@ -821,7 +821,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - chargePointStatus + chargePointStatus, ); return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED; } @@ -830,7 +830,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private async handleRequestRemoteStartTransaction( chargingStation: ChargingStation, - commandPayload: RemoteStartTransactionRequest + commandPayload: RemoteStartTransactionRequest, ): Promise { const { connectorId: transactionConnectorId, idTag, chargingProfile } = commandPayload; const reserved = @@ -849,7 +849,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { return this.notifyRemoteStartTransactionRejected( chargingStation, transactionConnectorId, - idTag + idTag, ); } if ( @@ -859,17 +859,17 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { return this.notifyRemoteStartTransactionRejected( chargingStation, transactionConnectorId, - idTag + idTag, ); } const remoteStartTransactionLogMsg = ` ${chargingStation.logPrefix()} Transaction remotely STARTED on ${ - chargingStation.stationInfo.chargingStationId - }#${transactionConnectorId.toString()} for idTag '${idTag}'`; + chargingStation.stationInfo.chargingStationId + }#${transactionConnectorId.toString()} for idTag '${idTag}'`; await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, transactionConnectorId, - OCPP16ChargePointStatus.Preparing + OCPP16ChargePointStatus.Preparing, ); const connectorStatus = chargingStation.getConnectorStatus(transactionConnectorId); // Check if authorized @@ -882,7 +882,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { this.setRemoteStartTransactionChargingProfile( chargingStation, transactionConnectorId, - chargingProfile + chargingProfile, ) === true ) { connectorStatus.transactionRemoteStarted = true; @@ -893,12 +893,12 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (reserved || reservedOnConnectorZero) { const reservation = chargingStation.getReservationBy( ReservationFilterKey.CONNECTOR_ID, - reservedOnConnectorZero ? 0 : transactionConnectorId + reservedOnConnectorZero ? 0 : transactionConnectorId, ); startTransactionPayload.reservationId = reservation.id; await chargingStation.removeReservation( reservation, - ReservationTerminationReason.TRANSACTION_STARTED + ReservationTerminationReason.TRANSACTION_STARTED, ); } if ( @@ -915,13 +915,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { return this.notifyRemoteStartTransactionRejected( chargingStation, transactionConnectorId, - idTag + idTag, ); } return this.notifyRemoteStartTransactionRejected( chargingStation, transactionConnectorId, - idTag + idTag, ); } // No authorization check required, start transaction @@ -929,7 +929,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { this.setRemoteStartTransactionChargingProfile( chargingStation, transactionConnectorId, - chargingProfile + chargingProfile, ) === true ) { connectorStatus.transactionRemoteStarted = true; @@ -950,20 +950,20 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { return this.notifyRemoteStartTransactionRejected( chargingStation, transactionConnectorId, - idTag + idTag, ); } return this.notifyRemoteStartTransactionRejected( chargingStation, transactionConnectorId, - idTag + idTag, ); } private async notifyRemoteStartTransactionRejected( chargingStation: ChargingStation, connectorId: number, - idTag: string + idTag: string, ): Promise { if ( chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.Available @@ -971,14 +971,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Available + OCPP16ChargePointStatus.Available, ); } 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}'` + ${connectorId.toString()}, idTag '${idTag}', availability '${chargingStation.getConnectorStatus( + connectorId, + )?.availability}', status '${chargingStation.getConnectorStatus(connectorId)?.status}'`, ); return OCPP16Constants.OCPP_RESPONSE_REJECTED; } @@ -986,21 +986,21 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private setRemoteStartTransactionChargingProfile( chargingStation: ChargingStation, connectorId: number, - cp: OCPP16ChargingProfile + cp: OCPP16ChargingProfile, ): boolean { if (cp && cp.chargingProfilePurpose === OCPP16ChargingProfilePurposeType.TX_PROFILE) { OCPP16ServiceUtils.setChargingProfile(chargingStation, connectorId, cp); logger.debug( `${chargingStation.logPrefix()} Charging profile(s) set at remote start transaction on connector id ${connectorId}: %j`, - cp + cp, ); return true; } else if (cp && cp.chargingProfilePurpose !== OCPP16ChargingProfilePurposeType.TX_PROFILE) { logger.warn( `${chargingStation.logPrefix()} Not allowed to set ${ cp.chargingProfilePurpose - } charging profile(s) at remote start transaction` + } charging profile(s) at remote start transaction`, ); return false; } else if (!cp) { @@ -1010,18 +1010,18 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private async handleRequestRemoteStopTransaction( chargingStation: ChargingStation, - commandPayload: RemoteStopTransactionRequest + commandPayload: RemoteStopTransactionRequest, ): Promise { const transactionId = commandPayload.transactionId; const remoteStopTransaction = async (connectorId: number): Promise => { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Finishing + OCPP16ChargePointStatus.Finishing, ); const stopResponse = await chargingStation.stopTransactionOnConnector( connectorId, - OCPP16StopTransactionReason.REMOTE + OCPP16StopTransactionReason.REMOTE, ); if (stopResponse.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) { return OCPP16Constants.OCPP_RESPONSE_ACCEPTED; @@ -1050,25 +1050,25 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { } logger.warn( `${chargingStation.logPrefix()} Trying to remote stop a non existing transaction with id: - ${transactionId.toString()}` + ${transactionId.toString()}`, ); return OCPP16Constants.OCPP_RESPONSE_REJECTED; } private handleRequestUpdateFirmware( chargingStation: ChargingStation, - commandPayload: OCPP16UpdateFirmwareRequest + commandPayload: OCPP16UpdateFirmwareRequest, ): OCPP16UpdateFirmwareResponse { if ( OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.FirmwareManagement, - OCPP16IncomingRequestCommand.UPDATE_FIRMWARE + OCPP16IncomingRequestCommand.UPDATE_FIRMWARE, ) === false ) { logger.warn( `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: - Cannot simulate firmware update: feature profile not supported` + Cannot simulate firmware update: feature profile not supported`, ); return OCPP16Constants.OCPP_RESPONSE_EMPTY; } @@ -1078,7 +1078,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ) { logger.warn( `${chargingStation.logPrefix()} ${moduleName}.handleRequestUpdateFirmware: - Cannot simulate firmware update: firmware update is already in progress` + Cannot simulate firmware update: firmware update is already in progress`, ); return OCPP16Constants.OCPP_RESPONSE_EMPTY; } @@ -1091,19 +1091,22 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { ...args: any[] ) => Promise, this, - chargingStation + chargingStation, ).catch(Constants.EMPTY_FUNCTION); } else { - setTimeout(() => { - this.runInAsyncScope( - this.updateFirmwareSimulation.bind(this) as ( - this: OCPP16IncomingRequestService, - ...args: any[] - ) => Promise, - this, - chargingStation - ).catch(Constants.EMPTY_FUNCTION); - }, retrieveDate?.getTime() - now); + setTimeout( + () => { + this.runInAsyncScope( + this.updateFirmwareSimulation.bind(this) as ( + this: OCPP16IncomingRequestService, + ...args: any[] + ) => Promise, + this, + chargingStation, + ).catch(Constants.EMPTY_FUNCTION); + }, + retrieveDate?.getTime() - now, + ); } return OCPP16Constants.OCPP_RESPONSE_EMPTY; } @@ -1111,7 +1114,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private async updateFirmwareSimulation( chargingStation: ChargingStation, maxDelay = 30, - minDelay = 15 + minDelay = 15, ): Promise { if (checkChargingStation(chargingStation, chargingStation.logPrefix()) === false) { return; @@ -1124,7 +1127,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Unavailable + OCPP16ChargePointStatus.Unavailable, ); } } @@ -1139,7 +1142,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Unavailable + OCPP16ChargePointStatus.Unavailable, ); } } @@ -1183,8 +1186,8 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { logger.debug( `${chargingStation.logPrefix()} ${moduleName}.updateFirmwareSimulation: ${runningTransactions} transaction(s) in progress, waiting ${ - waitTime / 1000 - } seconds before continuing firmware update simulation` + waitTime / 1000 + } seconds before continuing firmware update simulation`, ); await sleep(waitTime); transactionsStarted = true; @@ -1198,7 +1201,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Unavailable + OCPP16ChargePointStatus.Unavailable, ); } } @@ -1214,7 +1217,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Unavailable + OCPP16ChargePointStatus.Unavailable, ); } } @@ -1256,18 +1259,18 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private async handleRequestGetDiagnostics( chargingStation: ChargingStation, - commandPayload: GetDiagnosticsRequest + commandPayload: GetDiagnosticsRequest, ): Promise { if ( OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.FirmwareManagement, - OCPP16IncomingRequestCommand.GET_DIAGNOSTICS + OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, ) === false ) { logger.warn( `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: - Cannot get diagnostics: feature profile not supported` + Cannot get diagnostics: feature profile not supported`, ); return OCPP16Constants.OCPP_RESPONSE_EMPTY; } @@ -1293,7 +1296,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { logger.info( `${chargingStation.logPrefix()} ${ info.bytes / 1024 - } bytes transferred from diagnostics archive ${info.name}` + } bytes transferred from diagnostics archive ${info.name}`, ); chargingStation.ocppRequestService .requestHandler< @@ -1306,13 +1309,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { logger.error( `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetDiagnostics: Error while sending '${OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION}'`, - error + error, ); }); }); uploadResponse = await ftpClient.uploadFrom( join(resolve(dirname(fileURLToPath(import.meta.url)), '../'), diagnosticsArchive), - `${uri.pathname}${diagnosticsArchive}` + `${uri.pathname}${diagnosticsArchive}`, ); if (uploadResponse.code === 226) { await chargingStation.ocppRequestService.requestHandler< @@ -1331,7 +1334,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${ uploadResponse?.code && `|${uploadResponse?.code.toString()}` }`, - OCPP16IncomingRequestCommand.GET_DIAGNOSTICS + OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, ); } throw new OCPPError( @@ -1339,7 +1342,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { `Diagnostics transfer failed with error code ${accessResponse.code.toString()}${ uploadResponse?.code && `|${uploadResponse?.code.toString()}` }`, - OCPP16IncomingRequestCommand.GET_DIAGNOSTICS + OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, ); } catch (error) { await chargingStation.ocppRequestService.requestHandler< @@ -1355,14 +1358,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, OCPP16IncomingRequestCommand.GET_DIAGNOSTICS, error as Error, - { errorResponse: OCPP16Constants.OCPP_RESPONSE_EMPTY } + { errorResponse: OCPP16Constants.OCPP_RESPONSE_EMPTY }, ); } } else { logger.error( `${chargingStation.logPrefix()} Unsupported protocol ${ uri.protocol - } to transfer the diagnostic logs archive` + } to transfer the diagnostic logs archive`, ); await chargingStation.ocppRequestService.requestHandler< OCPP16DiagnosticsStatusNotificationRequest, @@ -1376,17 +1379,17 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { private handleRequestTriggerMessage( chargingStation: ChargingStation, - commandPayload: OCPP16TriggerMessageRequest + commandPayload: OCPP16TriggerMessageRequest, ): OCPP16TriggerMessageResponse { if ( !OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.RemoteTrigger, - OCPP16IncomingRequestCommand.TRIGGER_MESSAGE + OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, ) || !OCPP16ServiceUtils.isMessageTriggerSupported( chargingStation, - commandPayload.requestedMessage + commandPayload.requestedMessage, ) ) { return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_NOT_IMPLEMENTED; @@ -1395,7 +1398,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { !OCPP16ServiceUtils.isConnectorIdValid( chargingStation, OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, - commandPayload.connectorId + commandPayload.connectorId, ) ) { return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED; @@ -1409,7 +1412,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, OCPP16RequestCommand.BOOT_NOTIFICATION, chargingStation.bootNotificationRequest, - { skipBufferingOnError: true, triggerMessage: true } + { skipBufferingOnError: true, triggerMessage: true }, ) .then((response) => { chargingStation.bootNotificationResponse = response; @@ -1426,7 +1429,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { null, { triggerMessage: true, - } + }, ) .catch(Constants.EMPTY_FUNCTION); }, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY); @@ -1445,7 +1448,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { }, { triggerMessage: true, - } + }, ) .catch(Constants.EMPTY_FUNCTION); } else { @@ -1467,7 +1470,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { }, { triggerMessage: true, - } + }, ) .catch(Constants.EMPTY_FUNCTION); } @@ -1488,7 +1491,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { }, { triggerMessage: true, - } + }, ) .catch(Constants.EMPTY_FUNCTION); } @@ -1504,14 +1507,14 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, OCPP16IncomingRequestCommand.TRIGGER_MESSAGE, error as Error, - { errorResponse: OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED } + { errorResponse: OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED }, ); } } private handleRequestDataTransfer( chargingStation: ChargingStation, - commandPayload: OCPP16DataTransferRequest + commandPayload: OCPP16DataTransferRequest, ): OCPP16DataTransferResponse { try { if (Object.values(OCPP16DataTransferVendorId).includes(commandPayload.vendorId)) { @@ -1523,20 +1526,20 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, OCPP16IncomingRequestCommand.DATA_TRANSFER, error as Error, - { errorResponse: OCPP16Constants.OCPP_DATA_TRANSFER_RESPONSE_REJECTED } + { errorResponse: OCPP16Constants.OCPP_DATA_TRANSFER_RESPONSE_REJECTED }, ); } } private async handleRequestReserveNow( chargingStation: ChargingStation, - commandPayload: OCPP16ReserveNowRequest + commandPayload: OCPP16ReserveNowRequest, ): Promise { if ( !OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.Reservation, - OCPP16IncomingRequestCommand.RESERVE_NOW + OCPP16IncomingRequestCommand.RESERVE_NOW, ) ) { return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED; @@ -1592,20 +1595,20 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, OCPP16IncomingRequestCommand.RESERVE_NOW, error as Error, - { errorResponse: OCPP16Constants.OCPP_RESERVATION_RESPONSE_FAULTED } + { errorResponse: OCPP16Constants.OCPP_RESERVATION_RESPONSE_FAULTED }, ); } } private async handleRequestCancelReservation( chargingStation: ChargingStation, - commandPayload: OCPP16CancelReservationRequest + commandPayload: OCPP16CancelReservationRequest, ): Promise { if ( !OCPP16ServiceUtils.checkFeatureProfile( chargingStation, OCPP16SupportedFeatureProfiles.Reservation, - OCPP16IncomingRequestCommand.CANCEL_RESERVATION + OCPP16IncomingRequestCommand.CANCEL_RESERVATION, ) ) { return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED; @@ -1616,13 +1619,13 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { if (!exists) { logger.error( `${chargingStation.logPrefix()} Reservation with ID ${reservationId} - does not exist on charging station` + does not exist on charging station`, ); return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED; } await chargingStation.removeReservation( reservation, - ReservationTerminationReason.RESERVATION_CANCELED + ReservationTerminationReason.RESERVATION_CANCELED, ); return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_ACCEPTED; } catch (error) { @@ -1630,7 +1633,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService { chargingStation, OCPP16IncomingRequestCommand.CANCEL_RESERVATION, error as Error, - { errorResponse: OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED } + { errorResponse: OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED }, ); } } diff --git a/src/charging-station/ocpp/1.6/OCPP16RequestService.ts b/src/charging-station/ocpp/1.6/OCPP16RequestService.ts index fb500724..c601b85d 100644 --- a/src/charging-station/ocpp/1.6/OCPP16RequestService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16RequestService.ts @@ -44,7 +44,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/Authorize.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -52,7 +52,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/BootNotification.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -60,7 +60,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotification.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -68,7 +68,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/Heartbeat.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -76,7 +76,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/MeterValues.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -84,7 +84,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/StatusNotification.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -92,7 +92,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/StartTransaction.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -100,7 +100,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/StopTransaction.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -108,7 +108,7 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/DataTransfer.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -116,14 +116,14 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/FirmwareStatusNotification.json', moduleName, - 'constructor' + 'constructor', ), ], ]); this.buildRequestPayload = this.buildRequestPayload.bind(this) as ( chargingStation: ChargingStation, commandName: OCPP16RequestCommand, - commandParams?: JsonType + commandParams?: JsonType, ) => Request; } @@ -131,7 +131,7 @@ export class OCPP16RequestService extends OCPPRequestService { chargingStation: ChargingStation, commandName: OCPP16RequestCommand, commandParams?: JsonType, - params?: RequestParams + params?: RequestParams, ): Promise { // FIXME?: add sanity checks on charging station availability, connector availability, connector status, etc. if (OCPP16ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) { @@ -140,7 +140,7 @@ export class OCPP16RequestService extends OCPPRequestService { generateUUID(), this.buildRequestPayload(chargingStation, commandName, commandParams), commandName, - params + params, )) as ResponseType; } // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError(). @@ -148,14 +148,14 @@ export class OCPP16RequestService extends OCPPRequestService { ErrorType.NOT_SUPPORTED, `Unsupported OCPP command '${commandName}'`, commandName, - commandParams + commandParams, ); } private buildRequestPayload( chargingStation: ChargingStation, commandName: OCPP16RequestCommand, - commandParams?: JsonType + commandParams?: JsonType, ): Request { let connectorId: number; let energyActiveImportRegister: number; @@ -180,7 +180,7 @@ export class OCPP16RequestService extends OCPPRequestService { idTag: Constants.DEFAULT_IDTAG, meterStart: chargingStation.getEnergyActiveImportRegisterByConnectorId( commandParams?.connectorId as number, - true + true, ), timestamp: new Date(), ...commandParams, @@ -188,11 +188,11 @@ export class OCPP16RequestService extends OCPPRequestService { case OCPP16RequestCommand.STOP_TRANSACTION: chargingStation.getTransactionDataMeterValues() && (connectorId = chargingStation.getConnectorIdByTransactionId( - commandParams?.transactionId as number + commandParams?.transactionId as number, )); energyActiveImportRegister = chargingStation.getEnergyActiveImportRegisterByTransactionId( commandParams?.transactionId as number, - true + true, ); return { idTag: chargingStation.getTransactionIdTag(commandParams?.transactionId as number), @@ -204,8 +204,8 @@ export class OCPP16RequestService extends OCPPRequestService { OCPP16ServiceUtils.buildTransactionEndMeterValue( chargingStation, connectorId, - energyActiveImportRegister - ) + energyActiveImportRegister, + ), ), }), ...commandParams, @@ -217,7 +217,7 @@ export class OCPP16RequestService extends OCPPRequestService { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Unsupported OCPP command '${commandName}'`, commandName, - commandParams + commandParams, ); } } diff --git a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts index 372c4d72..2550dde9 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts @@ -93,7 +93,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/BootNotificationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -101,7 +101,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/HeartbeatResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -109,7 +109,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/AuthorizeResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -117,7 +117,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/StartTransactionResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -125,7 +125,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/StopTransactionResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -133,7 +133,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -141,7 +141,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/MeterValuesResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -149,7 +149,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -157,7 +157,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/DataTransferResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -165,7 +165,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], ]); @@ -175,7 +175,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ResetResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -183,7 +183,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ClearCacheResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -191,7 +191,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -199,7 +199,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -207,7 +207,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -215,7 +215,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -223,7 +223,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/GetCompositeScheduleResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -231,7 +231,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -239,7 +239,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -247,7 +247,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -255,7 +255,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -263,7 +263,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -271,7 +271,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -279,7 +279,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/DataTransferResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -287,7 +287,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -295,7 +295,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/ReserveNowResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -303,14 +303,14 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/1.6/CancelReservationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], ]); this.validatePayload = this.validatePayload.bind(this) as ( chargingStation: ChargingStation, commandName: OCPP16RequestCommand, - payload: JsonType + payload: JsonType, ) => boolean; } @@ -318,7 +318,7 @@ export class OCPP16ResponseService extends OCPPResponseService { chargingStation: ChargingStation, commandName: OCPP16RequestCommand, payload: JsonType, - requestPayload: JsonType + requestPayload: JsonType, ): Promise { if ( chargingStation.isRegistered() === true || @@ -334,7 +334,7 @@ export class OCPP16ResponseService extends OCPPResponseService { } catch (error) { logger.error( `${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`, - error + error, ); throw error; } @@ -345,10 +345,10 @@ export class OCPP16ResponseService extends OCPPResponseService { `${commandName} is not implemented to handle response PDU ${JSON.stringify( payload, null, - 2 + 2, )}`, commandName, - payload + payload, ); } } else { @@ -357,10 +357,10 @@ export class OCPP16ResponseService extends OCPPResponseService { `${commandName} cannot be issued to handle response PDU ${JSON.stringify( payload, null, - 2 + 2, )} while the charging station is not registered on the central server.`, commandName, - payload + payload, ); } } @@ -368,25 +368,25 @@ export class OCPP16ResponseService extends OCPPResponseService { private validatePayload( chargingStation: ChargingStation, commandName: OCPP16RequestCommand, - payload: JsonType + payload: JsonType, ): boolean { if (this.jsonSchemas.has(commandName) === true) { return this.validateResponsePayload( chargingStation, commandName, this.jsonSchemas.get(commandName), - payload + payload, ); } logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation` + `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`, ); return false; } private handleResponseBootNotification( chargingStation: ChargingStation, - payload: OCPP16BootNotificationResponse + payload: OCPP16BootNotificationResponse, ): void { if (payload.status === RegistrationStatusEnumType.ACCEPTED) { ChargingStationConfigurationUtils.addConfigurationKey( @@ -394,14 +394,14 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16StandardParametersKey.HeartbeatInterval, payload.interval.toString(), {}, - { overwrite: true, save: true } + { overwrite: true, save: true }, ); ChargingStationConfigurationUtils.addConfigurationKey( chargingStation, OCPP16StandardParametersKey.HeartBeatInterval, payload.interval.toString(), { visible: false }, - { overwrite: true, save: true } + { overwrite: true, save: true }, ); OCPP16ServiceUtils.startHeartbeatInterval(chargingStation, payload.interval); } @@ -415,7 +415,7 @@ export class OCPP16ResponseService extends OCPPResponseService { } else { logger.error( `${chargingStation.logPrefix()} Charging station boot notification response received: %j with undefined registration status`, - payload + payload, ); } } @@ -423,7 +423,7 @@ export class OCPP16ResponseService extends OCPPResponseService { private handleResponseAuthorize( chargingStation: ChargingStation, payload: OCPP16AuthorizeResponse, - requestPayload: OCPP16AuthorizeRequest + requestPayload: OCPP16AuthorizeRequest, ): void { let authorizeConnectorId: number; if (chargingStation.hasEvses) { @@ -455,7 +455,7 @@ export class OCPP16ResponseService extends OCPPResponseService { logger.debug( `${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' accepted${ authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : '' - }` + }`, ); } else { if (authorizeConnectorIdDefined) { @@ -465,7 +465,7 @@ export class OCPP16ResponseService extends OCPPResponseService { logger.debug( `${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' rejected with status '${ payload.idTagInfo.status - }'${authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''}` + }'${authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''}`, ); } } @@ -473,7 +473,7 @@ export class OCPP16ResponseService extends OCPPResponseService { private async handleResponseStartTransaction( chargingStation: ChargingStation, payload: OCPP16StartTransactionResponse, - requestPayload: OCPP16StartTransactionRequest + requestPayload: OCPP16StartTransactionRequest, ): Promise { const transactionConnectorId = requestPayload.connectorId; if ( @@ -481,7 +481,7 @@ export class OCPP16ResponseService extends OCPPResponseService { chargingStation.hasConnector(transactionConnectorId) === false ) { logger.error( - `${chargingStation.logPrefix()} Trying to start a transaction on a non existing connector id ${transactionConnectorId.toString()}` + `${chargingStation.logPrefix()} Trying to start a transaction on a non existing connector id ${transactionConnectorId.toString()}`, ); return; } @@ -494,9 +494,9 @@ export class OCPP16ResponseService extends OCPPResponseService { chargingStation.getConnectorStatus(transactionConnectorId)?.idTagLocalAuthorized === false ) { logger.error( - `${chargingStation.logPrefix()} Trying to start a transaction with a not local authorized idTag ${ - chargingStation.getConnectorStatus(transactionConnectorId)?.localAuthorizeIdTag - } on connector id ${transactionConnectorId.toString()}` + `${chargingStation.logPrefix()} Trying to start a transaction with a not local authorized idTag ${chargingStation.getConnectorStatus( + transactionConnectorId, + )?.localAuthorizeIdTag} on connector id ${transactionConnectorId.toString()}`, ); await this.resetConnectorOnStartTransactionError(chargingStation, transactionConnectorId); return; @@ -510,9 +510,9 @@ export class OCPP16ResponseService extends OCPPResponseService { chargingStation.getConnectorStatus(transactionConnectorId)?.idTagAuthorized === false ) { logger.error( - `${chargingStation.logPrefix()} Trying to start a transaction with a not authorized idTag ${ - chargingStation.getConnectorStatus(transactionConnectorId)?.authorizeIdTag - } on connector id ${transactionConnectorId.toString()}` + `${chargingStation.logPrefix()} Trying to start a transaction with a not authorized idTag ${chargingStation.getConnectorStatus( + transactionConnectorId, + )?.authorizeIdTag} on connector id ${transactionConnectorId.toString()}`, ); await this.resetConnectorOnStartTransactionError(chargingStation, transactionConnectorId); return; @@ -525,9 +525,9 @@ export class OCPP16ResponseService extends OCPPResponseService { logger.error( `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${ requestPayload.idTag - } different from the authorize request one ${ - chargingStation.getConnectorStatus(transactionConnectorId)?.authorizeIdTag - } on connector id ${transactionConnectorId.toString()}` + } different from the authorize request one ${chargingStation.getConnectorStatus( + transactionConnectorId, + )?.authorizeIdTag} on connector id ${transactionConnectorId.toString()}`, ); await this.resetConnectorOnStartTransactionError(chargingStation, transactionConnectorId); return; @@ -540,9 +540,9 @@ export class OCPP16ResponseService extends OCPPResponseService { logger.error( `${chargingStation.logPrefix()} Trying to start a transaction with an idTag ${ requestPayload.idTag - } different from the local authorized one ${ - chargingStation.getConnectorStatus(transactionConnectorId)?.localAuthorizeIdTag - } on connector id ${transactionConnectorId.toString()}` + } different from the local authorized one ${chargingStation.getConnectorStatus( + transactionConnectorId, + )?.localAuthorizeIdTag} on connector id ${transactionConnectorId.toString()}`, ); await this.resetConnectorOnStartTransactionError(chargingStation, transactionConnectorId); return; @@ -550,7 +550,7 @@ export class OCPP16ResponseService extends OCPPResponseService { if (chargingStation.getConnectorStatus(transactionConnectorId)?.transactionStarted === true) { logger.error( `${chargingStation.logPrefix()} Trying to start a transaction on an already used connector id ${transactionConnectorId.toString()}:`, - chargingStation.getConnectorStatus(transactionConnectorId) + chargingStation.getConnectorStatus(transactionConnectorId), ); return; } @@ -564,11 +564,11 @@ export class OCPP16ResponseService extends OCPPResponseService { ) { logger.error( `${chargingStation.logPrefix()} Trying to start a transaction on an already used evse id ${evseId.toString()}:`, - evseStatus + evseStatus, ); await this.resetConnectorOnStartTransactionError( chargingStation, - transactionConnectorId + transactionConnectorId, ); return; } @@ -583,9 +583,9 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ChargePointStatus.Preparing ) { logger.error( - `${chargingStation.logPrefix()} Trying to start a transaction on connector id ${transactionConnectorId.toString()} with status ${ - chargingStation.getConnectorStatus(transactionConnectorId)?.status - }` + `${chargingStation.logPrefix()} Trying to start a transaction on connector id ${transactionConnectorId.toString()} with status ${chargingStation.getConnectorStatus( + transactionConnectorId, + )?.status}`, ); return; } @@ -593,7 +593,7 @@ export class OCPP16ResponseService extends OCPPResponseService { logger.warn( `${chargingStation.logPrefix()} Trying to start a transaction on connector id ${transactionConnectorId.toString()} with a non integer transaction id ${ payload.transactionId - }, converting to integer` + }, converting to integer`, ); payload.transactionId = convertToInt(payload.transactionId); } @@ -605,13 +605,13 @@ export class OCPP16ResponseService extends OCPPResponseService { chargingStation.getConnectorStatus(transactionConnectorId).transactionIdTag = requestPayload.idTag; chargingStation.getConnectorStatus( - transactionConnectorId + transactionConnectorId, ).transactionEnergyActiveImportRegisterValue = 0; chargingStation.getConnectorStatus(transactionConnectorId).transactionBeginMeterValue = OCPP16ServiceUtils.buildTransactionBeginMeterValue( chargingStation, transactionConnectorId, - requestPayload.meterStart + requestPayload.meterStart, ); chargingStation.getBeginEndMeterValues() && (await chargingStation.ocppRequestService.requestHandler< @@ -627,12 +627,12 @@ export class OCPP16ResponseService extends OCPPResponseService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, transactionConnectorId, - OCPP16ChargePointStatus.Charging + OCPP16ChargePointStatus.Charging, ); logger.info( `${chargingStation.logPrefix()} Transaction with id ${payload.transactionId.toString()} STARTED on ${ chargingStation.stationInfo.chargingStationId - }#${transactionConnectorId.toString()} for idTag '${requestPayload.idTag}'` + }#${transactionConnectorId.toString()} for idTag '${requestPayload.idTag}'`, ); if (chargingStation.stationInfo.powerSharedByConnectors) { ++chargingStation.powerDivider; @@ -640,19 +640,18 @@ export class OCPP16ResponseService extends OCPPResponseService { const configuredMeterValueSampleInterval = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, - OCPP16StandardParametersKey.MeterValueSampleInterval + OCPP16StandardParametersKey.MeterValueSampleInterval, ); chargingStation.startMeterValues( transactionConnectorId, configuredMeterValueSampleInterval ? convertToInt(configuredMeterValueSampleInterval.value) * 1000 - : Constants.DEFAULT_METER_VALUES_INTERVAL + : Constants.DEFAULT_METER_VALUES_INTERVAL, ); } else { logger.warn( - `${chargingStation.logPrefix()} Starting transaction with id ${payload.transactionId.toString()} REJECTED with status '${ - payload.idTagInfo?.status - }', idTag '${requestPayload.idTag}'` + `${chargingStation.logPrefix()} Starting transaction with id ${payload.transactionId.toString()} REJECTED with status '${payload + .idTagInfo?.status}', idTag '${requestPayload.idTag}'`, ); await this.resetConnectorOnStartTransactionError(chargingStation, transactionConnectorId); } @@ -660,7 +659,7 @@ export class OCPP16ResponseService extends OCPPResponseService { private async resetConnectorOnStartTransactionError( chargingStation: ChargingStation, - connectorId: number + connectorId: number, ): Promise { resetConnectorStatus(chargingStation.getConnectorStatus(connectorId)); chargingStation.stopMeterValues(connectorId); @@ -671,7 +670,7 @@ export class OCPP16ResponseService extends OCPPResponseService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, connectorId, - OCPP16ChargePointStatus.Available + OCPP16ChargePointStatus.Available, ); } } @@ -679,14 +678,14 @@ export class OCPP16ResponseService extends OCPPResponseService { private async handleResponseStopTransaction( chargingStation: ChargingStation, payload: OCPP16StopTransactionResponse, - requestPayload: OCPP16StopTransactionRequest + requestPayload: OCPP16StopTransactionRequest, ): Promise { const transactionConnectorId = chargingStation.getConnectorIdByTransactionId( - requestPayload.transactionId + requestPayload.transactionId, ); if (isNullOrUndefined(transactionConnectorId)) { logger.error( - `${chargingStation.logPrefix()} Trying to stop a non existing transaction with id ${requestPayload.transactionId.toString()}` + `${chargingStation.logPrefix()} Trying to stop a non existing transaction with id ${requestPayload.transactionId.toString()}`, ); return; } @@ -703,7 +702,7 @@ export class OCPP16ResponseService extends OCPPResponseService { OCPP16ServiceUtils.buildTransactionEndMeterValue( chargingStation, transactionConnectorId, - requestPayload.meterStop + requestPayload.meterStop, ), ], })); @@ -714,13 +713,13 @@ export class OCPP16ResponseService extends OCPPResponseService { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, transactionConnectorId, - OCPP16ChargePointStatus.Unavailable + OCPP16ChargePointStatus.Unavailable, ); } else { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, transactionConnectorId, - OCPP16ChargePointStatus.Available + OCPP16ChargePointStatus.Available, ); } if (chargingStation.stationInfo.powerSharedByConnectors) { diff --git a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts index c5345950..c85ecdd3 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts @@ -51,13 +51,13 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { public static checkFeatureProfile( chargingStation: ChargingStation, featureProfile: OCPP16SupportedFeatureProfiles, - command: OCPP16RequestCommand | OCPP16IncomingRequestCommand + command: OCPP16RequestCommand | OCPP16IncomingRequestCommand, ): boolean { if (!chargingStation.hasFeatureProfile(featureProfile)) { logger.warn( `${chargingStation.logPrefix()} Trying to '${command}' without '${featureProfile}' feature enabled in ${ OCPP16StandardParametersKey.SupportedFeatureProfiles - } in configuration` + } in configuration`, ); return false; } @@ -69,7 +69,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { connectorId: number, transactionId: number, interval: number, - debug = false + debug = false, ): OCPP16MeterValue { const meterValue: OCPP16MeterValue = { timestamp: new Date(), @@ -80,7 +80,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { const socSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, - OCPP16MeterValueMeasurand.STATE_OF_CHARGE + OCPP16MeterValueMeasurand.STATE_OF_CHARGE, ); if (socSampledValueTemplate) { const socMaximumValue = 100; @@ -88,11 +88,11 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { const socSampledValueTemplateValue = socSampledValueTemplate.value ? getRandomFloatFluctuatedRounded( parseInt(socSampledValueTemplate.value), - socSampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT + socSampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT, ) : getRandomInteger(socMaximumValue, socMinimumValue); meterValue.sampledValue.push( - OCPP16ServiceUtils.buildSampledValue(socSampledValueTemplate, socSampledValueTemplateValue) + OCPP16ServiceUtils.buildSampledValue(socSampledValueTemplate, socSampledValueTemplateValue), ); const sampledValuesIndex = meterValue.sampledValue.length - 1; if ( @@ -104,11 +104,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { `${chargingStation.logPrefix()} MeterValues measurand ${ meterValue.sampledValue[sampledValuesIndex].measurand ?? OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER - }: connector id ${connectorId}, transaction id ${ - connector?.transactionId - }, value: ${socMinimumValue}/${ + }: connector id ${connectorId}, transaction id ${connector?.transactionId}, value: ${socMinimumValue}/${ meterValue.sampledValue[sampledValuesIndex].value - }/${socMaximumValue}}` + }/${socMaximumValue}}`, ); } } @@ -116,7 +114,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { const voltageSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, - OCPP16MeterValueMeasurand.VOLTAGE + OCPP16MeterValueMeasurand.VOLTAGE, ); if (voltageSampledValueTemplate) { const voltageSampledValueTemplateValue = voltageSampledValueTemplate.value @@ -126,14 +124,14 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { voltageSampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT; const voltageMeasurandValue = getRandomFloatFluctuatedRounded( voltageSampledValueTemplateValue, - fluctuationPercent + fluctuationPercent, ); if ( chargingStation.getNumberOfPhases() !== 3 || (chargingStation.getNumberOfPhases() === 3 && chargingStation.getMainVoltageMeterValues()) ) { meterValue.sampledValue.push( - OCPP16ServiceUtils.buildSampledValue(voltageSampledValueTemplate, voltageMeasurandValue) + OCPP16ServiceUtils.buildSampledValue(voltageSampledValueTemplate, voltageMeasurandValue), ); } for ( @@ -147,7 +145,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { chargingStation, connectorId, OCPP16MeterValueMeasurand.VOLTAGE, - phaseLineToNeutralValue as OCPP16MeterValuePhase + phaseLineToNeutralValue as OCPP16MeterValuePhase, ); let voltagePhaseLineToNeutralMeasurandValue: number; if (voltagePhaseLineToNeutralSampledValueTemplate) { @@ -160,7 +158,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { Constants.DEFAULT_FLUCTUATION_PERCENT; voltagePhaseLineToNeutralMeasurandValue = getRandomFloatFluctuatedRounded( voltagePhaseLineToNeutralSampledValueTemplateValue, - fluctuationPhaseToNeutralPercent + fluctuationPhaseToNeutralPercent, ); } meterValue.sampledValue.push( @@ -168,8 +166,8 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { voltagePhaseLineToNeutralSampledValueTemplate ?? voltageSampledValueTemplate, voltagePhaseLineToNeutralMeasurandValue ?? voltageMeasurandValue, undefined, - phaseLineToNeutralValue as OCPP16MeterValuePhase - ) + phaseLineToNeutralValue as OCPP16MeterValuePhase, + ), ); if (chargingStation.getPhaseLineToLineVoltageMeterValues()) { const phaseLineToLineValue = `L${phase}-L${ @@ -182,7 +180,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { chargingStation, connectorId, OCPP16MeterValueMeasurand.VOLTAGE, - phaseLineToLineValue as OCPP16MeterValuePhase + phaseLineToLineValue as OCPP16MeterValuePhase, ); let voltagePhaseLineToLineMeasurandValue: number; if (voltagePhaseLineToLineSampledValueTemplate) { @@ -195,20 +193,20 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { Constants.DEFAULT_FLUCTUATION_PERCENT; voltagePhaseLineToLineMeasurandValue = getRandomFloatFluctuatedRounded( voltagePhaseLineToLineSampledValueTemplateValue, - fluctuationPhaseLineToLinePercent + fluctuationPhaseLineToLinePercent, ); } const defaultVoltagePhaseLineToLineMeasurandValue = getRandomFloatFluctuatedRounded( Voltage.VOLTAGE_400, - fluctuationPercent + fluctuationPercent, ); meterValue.sampledValue.push( OCPP16ServiceUtils.buildSampledValue( voltagePhaseLineToLineSampledValueTemplate ?? voltageSampledValueTemplate, voltagePhaseLineToLineMeasurandValue ?? defaultVoltagePhaseLineToLineMeasurandValue, undefined, - phaseLineToLineValue as OCPP16MeterValuePhase - ) + phaseLineToLineValue as OCPP16MeterValuePhase, + ), ); } } @@ -217,7 +215,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { const powerSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, - OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT + OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT, ); let powerPerPhaseSampledValueTemplates: MeasurandPerPhaseSampledValueTemplates = {}; if (chargingStation.getNumberOfPhases() === 3) { @@ -226,26 +224,26 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { chargingStation, connectorId, OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT, - OCPP16MeterValuePhase.L1_N + OCPP16MeterValuePhase.L1_N, ), L2: OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT, - OCPP16MeterValuePhase.L2_N + OCPP16MeterValuePhase.L2_N, ), L3: OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT, - OCPP16MeterValuePhase.L3_N + OCPP16MeterValuePhase.L3_N, ), }; } if (powerSampledValueTemplate) { OCPP16ServiceUtils.checkMeasurandPowerDivider( chargingStation, - powerSampledValueTemplate.measurand + powerSampledValueTemplate.measurand, ); const errMsg = `MeterValues measurand ${ powerSampledValueTemplate.measurand ?? @@ -262,11 +260,11 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { chargingStation.getConnectorMaximumAvailablePower(connectorId); const connectorMaximumPower = Math.round(connectorMaximumAvailablePower); const connectorMaximumPowerPerPhase = Math.round( - connectorMaximumAvailablePower / chargingStation.getNumberOfPhases() + connectorMaximumAvailablePower / chargingStation.getNumberOfPhases(), ); const connectorMinimumPower = Math.round(powerSampledValueTemplate.minimumValue) ?? 0; const connectorMinimumPowerPerPhase = Math.round( - connectorMinimumPower / chargingStation.getNumberOfPhases() + connectorMinimumPower / chargingStation.getNumberOfPhases(), ); switch (chargingStation.getCurrentOutType()) { case CurrentType.AC: @@ -277,10 +275,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( powerSampledValueTemplate.value, connectorMaximumPower / unitDivider, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ) / chargingStation.getNumberOfPhases(), powerSampledValueTemplate.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); const phase1FluctuatedValue = powerPerPhaseSampledValueTemplates?.L1?.value && @@ -288,10 +286,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( powerPerPhaseSampledValueTemplates.L1.value, connectorMaximumPowerPerPhase / unitDivider, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), powerPerPhaseSampledValueTemplates.L1.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); const phase2FluctuatedValue = powerPerPhaseSampledValueTemplates?.L2?.value && @@ -299,10 +297,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( powerPerPhaseSampledValueTemplates.L2.value, connectorMaximumPowerPerPhase / unitDivider, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), powerPerPhaseSampledValueTemplates.L2.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); const phase3FluctuatedValue = powerPerPhaseSampledValueTemplates?.L3?.value && @@ -310,31 +308,31 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( powerPerPhaseSampledValueTemplates.L3.value, connectorMaximumPowerPerPhase / unitDivider, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), powerPerPhaseSampledValueTemplates.L3.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); powerMeasurandValues.L1 = phase1FluctuatedValue ?? defaultFluctuatedPowerPerPhase ?? getRandomFloatRounded( connectorMaximumPowerPerPhase / unitDivider, - connectorMinimumPowerPerPhase / unitDivider + connectorMinimumPowerPerPhase / unitDivider, ); powerMeasurandValues.L2 = phase2FluctuatedValue ?? defaultFluctuatedPowerPerPhase ?? getRandomFloatRounded( connectorMaximumPowerPerPhase / unitDivider, - connectorMinimumPowerPerPhase / unitDivider + connectorMinimumPowerPerPhase / unitDivider, ); powerMeasurandValues.L3 = phase3FluctuatedValue ?? defaultFluctuatedPowerPerPhase ?? getRandomFloatRounded( connectorMaximumPowerPerPhase / unitDivider, - connectorMinimumPowerPerPhase / unitDivider + connectorMinimumPowerPerPhase / unitDivider, ); } else { powerMeasurandValues.L1 = powerSampledValueTemplate.value @@ -342,21 +340,21 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( powerSampledValueTemplate.value, connectorMaximumPower / unitDivider, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), powerSampledValueTemplate.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ) : getRandomFloatRounded( connectorMaximumPower / unitDivider, - connectorMinimumPower / unitDivider + connectorMinimumPower / unitDivider, ); powerMeasurandValues.L2 = 0; powerMeasurandValues.L3 = 0; } powerMeasurandValues.allPhases = roundTo( powerMeasurandValues.L1 + powerMeasurandValues.L2 + powerMeasurandValues.L3, - 2 + 2, ); break; case CurrentType.DC: @@ -365,14 +363,14 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( powerSampledValueTemplate.value, connectorMaximumPower / unitDivider, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), powerSampledValueTemplate.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ) : getRandomFloatRounded( connectorMaximumPower / unitDivider, - connectorMinimumPower / unitDivider + connectorMinimumPower / unitDivider, ); break; default: @@ -382,8 +380,8 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { meterValue.sampledValue.push( OCPP16ServiceUtils.buildSampledValue( powerSampledValueTemplate, - powerMeasurandValues.allPhases - ) + powerMeasurandValues.allPhases, + ), ); const sampledValuesIndex = meterValue.sampledValue.length - 1; const connectorMaximumPowerRounded = roundTo(connectorMaximumPower / unitDivider, 2); @@ -399,11 +397,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { `${chargingStation.logPrefix()} MeterValues measurand ${ meterValue.sampledValue[sampledValuesIndex].measurand ?? OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER - }: connector id ${connectorId}, transaction id ${ - connector?.transactionId - }, value: ${connectorMinimumPowerRounded}/${ + }: connector id ${connectorId}, transaction id ${connector?.transactionId}, value: ${connectorMinimumPowerRounded}/${ meterValue.sampledValue[sampledValuesIndex].value - }/${connectorMaximumPowerRounded}` + }/${connectorMaximumPowerRounded}`, ); } for ( @@ -418,17 +414,17 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { powerSampledValueTemplate, powerMeasurandValues[`L${phase}`] as number, undefined, - phaseValue as OCPP16MeterValuePhase - ) + phaseValue as OCPP16MeterValuePhase, + ), ); const sampledValuesPerPhaseIndex = meterValue.sampledValue.length - 1; const connectorMaximumPowerPerPhaseRounded = roundTo( connectorMaximumPowerPerPhase / unitDivider, - 2 + 2, ); const connectorMinimumPowerPerPhaseRounded = roundTo( connectorMinimumPowerPerPhase / unitDivider, - 2 + 2, ); if ( convertToFloat(meterValue.sampledValue[sampledValuesPerPhaseIndex].value) > @@ -443,11 +439,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER }: phase ${ meterValue.sampledValue[sampledValuesPerPhaseIndex].phase - }, connector id ${connectorId}, transaction id ${ - connector?.transactionId - }, value: ${connectorMinimumPowerPerPhaseRounded}/${ + }, connector id ${connectorId}, transaction id ${connector?.transactionId}, value: ${connectorMinimumPowerPerPhaseRounded}/${ meterValue.sampledValue[sampledValuesPerPhaseIndex].value - }/${connectorMaximumPowerPerPhaseRounded}` + }/${connectorMaximumPowerPerPhaseRounded}`, ); } } @@ -456,7 +450,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { const currentSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, - OCPP16MeterValueMeasurand.CURRENT_IMPORT + OCPP16MeterValueMeasurand.CURRENT_IMPORT, ); let currentPerPhaseSampledValueTemplates: MeasurandPerPhaseSampledValueTemplates = {}; if (chargingStation.getNumberOfPhases() === 3) { @@ -465,26 +459,26 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { chargingStation, connectorId, OCPP16MeterValueMeasurand.CURRENT_IMPORT, - OCPP16MeterValuePhase.L1 + OCPP16MeterValuePhase.L1, ), L2: OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, OCPP16MeterValueMeasurand.CURRENT_IMPORT, - OCPP16MeterValuePhase.L2 + OCPP16MeterValuePhase.L2, ), L3: OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, connectorId, OCPP16MeterValueMeasurand.CURRENT_IMPORT, - OCPP16MeterValuePhase.L3 + OCPP16MeterValuePhase.L3, ), }; } if (currentSampledValueTemplate) { OCPP16ServiceUtils.checkMeasurandPowerDivider( chargingStation, - currentSampledValueTemplate.measurand + currentSampledValueTemplate.measurand, ); const errMsg = `MeterValues measurand ${ currentSampledValueTemplate.measurand ?? @@ -505,7 +499,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { connectorMaximumAmperage = ACElectricUtils.amperagePerPhaseFromPower( chargingStation.getNumberOfPhases(), connectorMaximumAvailablePower, - chargingStation.getVoltageOut() + chargingStation.getVoltageOut(), ); if (chargingStation.getNumberOfPhases() === 3) { const defaultFluctuatedAmperagePerPhase = @@ -514,10 +508,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( currentSampledValueTemplate.value, connectorMaximumAmperage, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), currentSampledValueTemplate.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); const phase1FluctuatedValue = currentPerPhaseSampledValueTemplates?.L1?.value && @@ -525,10 +519,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( currentPerPhaseSampledValueTemplates.L1.value, connectorMaximumAmperage, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), currentPerPhaseSampledValueTemplates.L1.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); const phase2FluctuatedValue = currentPerPhaseSampledValueTemplates?.L2?.value && @@ -536,10 +530,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( currentPerPhaseSampledValueTemplates.L2.value, connectorMaximumAmperage, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), currentPerPhaseSampledValueTemplates.L2.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); const phase3FluctuatedValue = currentPerPhaseSampledValueTemplates?.L3?.value && @@ -547,10 +541,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( currentPerPhaseSampledValueTemplates.L3.value, connectorMaximumAmperage, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), currentPerPhaseSampledValueTemplates.L3.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ); currentMeasurandValues.L1 = phase1FluctuatedValue ?? @@ -570,10 +564,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( currentSampledValueTemplate.value, connectorMaximumAmperage, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), currentSampledValueTemplate.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ) : getRandomFloatRounded(connectorMaximumAmperage, connectorMinimumAmperage); currentMeasurandValues.L2 = 0; @@ -582,23 +576,23 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { currentMeasurandValues.allPhases = roundTo( (currentMeasurandValues.L1 + currentMeasurandValues.L2 + currentMeasurandValues.L3) / chargingStation.getNumberOfPhases(), - 2 + 2, ); break; case CurrentType.DC: connectorMaximumAmperage = DCElectricUtils.amperage( connectorMaximumAvailablePower, - chargingStation.getVoltageOut() + chargingStation.getVoltageOut(), ); currentMeasurandValues.allPhases = currentSampledValueTemplate.value ? getRandomFloatFluctuatedRounded( OCPP16ServiceUtils.getLimitFromSampledValueTemplateCustomValue( currentSampledValueTemplate.value, connectorMaximumAmperage, - { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() } + { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues() }, ), currentSampledValueTemplate.fluctuationPercent ?? - Constants.DEFAULT_FLUCTUATION_PERCENT + Constants.DEFAULT_FLUCTUATION_PERCENT, ) : getRandomFloatRounded(connectorMaximumAmperage, connectorMinimumAmperage); break; @@ -609,8 +603,8 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { meterValue.sampledValue.push( OCPP16ServiceUtils.buildSampledValue( currentSampledValueTemplate, - currentMeasurandValues.allPhases - ) + currentMeasurandValues.allPhases, + ), ); const sampledValuesIndex = meterValue.sampledValue.length - 1; if ( @@ -624,11 +618,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { `${chargingStation.logPrefix()} MeterValues measurand ${ meterValue.sampledValue[sampledValuesIndex].measurand ?? OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER - }: connector id ${connectorId}, transaction id ${ - connector?.transactionId - }, value: ${connectorMinimumAmperage}/${ + }: connector id ${connectorId}, transaction id ${connector?.transactionId}, value: ${connectorMinimumAmperage}/${ meterValue.sampledValue[sampledValuesIndex].value - }/${connectorMaximumAmperage}` + }/${connectorMaximumAmperage}`, ); } for ( @@ -643,8 +635,8 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { currentSampledValueTemplate, currentMeasurandValues[phaseValue] as number, undefined, - phaseValue as OCPP16MeterValuePhase - ) + phaseValue as OCPP16MeterValuePhase, + ), ); const sampledValuesPerPhaseIndex = meterValue.sampledValue.length - 1; if ( @@ -660,11 +652,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER }: phase ${ meterValue.sampledValue[sampledValuesPerPhaseIndex].phase - }, connector id ${connectorId}, transaction id ${ - connector?.transactionId - }, value: ${connectorMinimumAmperage}/${ + }, connector id ${connectorId}, transaction id ${connector?.transactionId}, value: ${connectorMinimumAmperage}/${ meterValue.sampledValue[sampledValuesPerPhaseIndex].value - }/${connectorMaximumAmperage}` + }/${connectorMaximumAmperage}`, ); } } @@ -672,12 +662,12 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { // Energy.Active.Import.Register measurand (default) const energySampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, - connectorId + connectorId, ); if (energySampledValueTemplate) { OCPP16ServiceUtils.checkMeasurandPowerDivider( chargingStation, - energySampledValueTemplate.measurand + energySampledValueTemplate.measurand, ); const unitDivider = energySampledValueTemplate?.unit === MeterValueUnit.KILO_WATT_HOUR ? 1000 : 1; @@ -685,7 +675,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { chargingStation.getConnectorMaximumAvailablePower(connectorId); const connectorMaximumEnergyRounded = roundTo( (connectorMaximumAvailablePower * interval) / (3600 * 1000), - 2 + 2, ); const energyValueRounded = energySampledValueTemplate.value ? // Cumulate the fluctuated value around the static one @@ -696,9 +686,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { { limitationEnabled: chargingStation.getCustomValueLimitationMeterValues(), unitMultiplier: unitDivider, - } + }, ), - energySampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT + energySampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT, ) : getRandomFloatRounded(connectorMaximumEnergyRounded); // Persist previous value on connector @@ -721,9 +711,9 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { roundTo( chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId) / unitDivider, - 2 - ) - ) + 2, + ), + ), ); const sampledValuesIndex = meterValue.sampledValue.length - 1; if (energyValueRounded > connectorMaximumEnergyRounded || debug) { @@ -731,12 +721,10 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { `${chargingStation.logPrefix()} MeterValues measurand ${ meterValue.sampledValue[sampledValuesIndex].measurand ?? OCPP16MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER - }: connector id ${connectorId}, transaction id ${ - connector?.transactionId - }, value: ${energyValueRounded}/${connectorMaximumEnergyRounded}, duration: ${roundTo( + }: connector id ${connectorId}, transaction id ${connector?.transactionId}, value: ${energyValueRounded}/${connectorMaximumEnergyRounded}, duration: ${roundTo( interval / (3600 * 1000), - 4 - )}h` + 4, + )}h`, ); } } @@ -746,7 +734,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { public static buildTransactionBeginMeterValue( chargingStation: ChargingStation, connectorId: number, - meterStart: number + meterStart: number, ): OCPP16MeterValue { const meterValue: OCPP16MeterValue = { timestamp: new Date(), @@ -755,15 +743,15 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { // Energy.Active.Import.Register measurand (default) const sampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, - connectorId + connectorId, ); const unitDivider = sampledValueTemplate?.unit === MeterValueUnit.KILO_WATT_HOUR ? 1000 : 1; meterValue.sampledValue.push( OCPP16ServiceUtils.buildSampledValue( sampledValueTemplate, roundTo((meterStart ?? 0) / unitDivider, 4), - MeterValueContext.TRANSACTION_BEGIN - ) + MeterValueContext.TRANSACTION_BEGIN, + ), ); return meterValue; } @@ -771,7 +759,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { public static buildTransactionEndMeterValue( chargingStation: ChargingStation, connectorId: number, - meterStop: number + meterStop: number, ): OCPP16MeterValue { const meterValue: OCPP16MeterValue = { timestamp: new Date(), @@ -780,22 +768,22 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { // Energy.Active.Import.Register measurand (default) const sampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate( chargingStation, - connectorId + connectorId, ); const unitDivider = sampledValueTemplate?.unit === MeterValueUnit.KILO_WATT_HOUR ? 1000 : 1; meterValue.sampledValue.push( OCPP16ServiceUtils.buildSampledValue( sampledValueTemplate, roundTo((meterStop ?? 0) / unitDivider, 4), - MeterValueContext.TRANSACTION_END - ) + MeterValueContext.TRANSACTION_END, + ), ); return meterValue; } public static buildTransactionDataMeterValues( transactionBeginMeterValue: OCPP16MeterValue, - transactionEndMeterValue: OCPP16MeterValue + transactionEndMeterValue: OCPP16MeterValue, ): OCPP16MeterValue[] { const meterValues: OCPP16MeterValue[] = []; meterValues.push(transactionBeginMeterValue); @@ -806,11 +794,11 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { public static setChargingProfile( chargingStation: ChargingStation, connectorId: number, - cp: OCPP16ChargingProfile + cp: OCPP16ChargingProfile, ): void { if (isNullOrUndefined(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles)) { logger.error( - `${chargingStation.logPrefix()} Trying to set a charging profile on connector id ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization` + `${chargingStation.logPrefix()} Trying to set a charging profile on connector id ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization`, ); chargingStation.getConnectorStatus(connectorId).chargingProfiles = []; } @@ -818,7 +806,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { Array.isArray(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles) === false ) { logger.error( - `${chargingStation.logPrefix()} Trying to set a charging profile on connector id ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization` + `${chargingStation.logPrefix()} Trying to set a charging profile on connector id ${connectorId} with an improper attribute type for the charging profiles array, applying proper type initialization`, ); chargingStation.getConnectorStatus(connectorId).chargingProfiles = []; } @@ -843,20 +831,20 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { public static parseJsonSchemaFile( relativePath: string, moduleName?: string, - methodName?: string + methodName?: string, ): JSONSchemaType { return super.parseJsonSchemaFile( relativePath, OCPPVersion.VERSION_16, moduleName, - methodName + methodName, ); } public static async isIdTagAuthorized( chargingStation: ChargingStation, connectorId: number, - idTag: string + idTag: string, ): Promise { let authorized = false; const connectorStatus = chargingStation.getConnectorStatus(connectorId); @@ -870,7 +858,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { } else { logger.warn( `${chargingStation.logPrefix()} The charging station configuration expects authorize at - remote start transaction but local authorization or authorize isn't enabled` + remote start transaction but local authorization or authorize isn't enabled`, ); } return authorized; @@ -880,7 +868,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { sampledValueTemplate: SampledValueTemplate, value: number, context?: MeterValueContext, - phase?: OCPP16MeterValuePhase + phase?: OCPP16MeterValuePhase, ): OCPP16SampledValue { const sampledValueValue = value ?? sampledValueTemplate?.value ?? null; const sampledValueContext = context ?? sampledValueTemplate?.context ?? null; @@ -904,7 +892,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { private static checkMeasurandPowerDivider( chargingStation: ChargingStation, - measurandType: OCPP16MeterValueMeasurand + measurandType: OCPP16MeterValueMeasurand, ): void { if (isUndefined(chargingStation.powerDivider)) { const errMsg = `MeterValues measurand ${ @@ -922,7 +910,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { } private static getMeasurandDefaultLocation( - measurandType: OCPP16MeterValueMeasurand + measurandType: OCPP16MeterValueMeasurand, ): MeterValueLocation | undefined { switch (measurandType) { case OCPP16MeterValueMeasurand.STATE_OF_CHARGE: @@ -931,7 +919,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { } private static getMeasurandDefaultUnit( - measurandType: OCPP16MeterValueMeasurand + measurandType: OCPP16MeterValueMeasurand, ): MeterValueUnit | undefined { switch (measurandType) { case OCPP16MeterValueMeasurand.CURRENT_EXPORT: @@ -959,14 +947,14 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { isNotEmptyString( chargingStation.idTagsCache .getIdTags(getIdTagsFile(chargingStation.stationInfo)) - ?.find((tag) => tag === idTag) + ?.find((tag) => tag === idTag), ) ); } private static async isIdTagRemoteAuthorized( chargingStation: ChargingStation, - idTag: string + idTag: string, ): Promise { const authorizeResponse: OCPP16AuthorizeResponse = await chargingStation.ocppRequestService.requestHandler< diff --git a/src/charging-station/ocpp/2.0/OCPP20Constants.ts b/src/charging-station/ocpp/2.0/OCPP20Constants.ts index 8c64d8e7..c64fe13d 100644 --- a/src/charging-station/ocpp/2.0/OCPP20Constants.ts +++ b/src/charging-station/ocpp/2.0/OCPP20Constants.ts @@ -86,6 +86,6 @@ export class OCPP20Constants extends OCPPConstants { to: OCPP20ConnectorStatusEnumType.Unavailable, }, // { from: OCPP20ConnectorStatusEnumType.Faulted, to: OCPP20ConnectorStatusEnumType.Faulted }, - ] + ], ); } diff --git a/src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts b/src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts index 3fdb5ced..6cfb4ec1 100644 --- a/src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts +++ b/src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts @@ -37,14 +37,14 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/ClearCacheRequest.json', moduleName, - 'constructor' + 'constructor', ), ], ]); this.validatePayload = this.validatePayload.bind(this) as ( chargingStation: ChargingStation, commandName: OCPP20IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ) => boolean; } @@ -52,7 +52,7 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { chargingStation: ChargingStation, messageId: string, commandName: OCPP20IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ): Promise { let response: JsonType; if ( @@ -66,10 +66,10 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { `${commandName} cannot be issued to handle request PDU ${JSON.stringify( commandPayload, null, - 2 + 2, )} while the charging station is in pending state on the central server`, commandName, - commandPayload + commandPayload, ); } if ( @@ -86,13 +86,13 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { // Call the method to build the response response = await this.incomingRequestHandlers.get(commandName)( chargingStation, - commandPayload + commandPayload, ); } catch (error) { // Log logger.error( `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`, - error + error, ); throw error; } @@ -103,10 +103,10 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { `${commandName} is not implemented to handle request PDU ${JSON.stringify( commandPayload, null, - 2 + 2, )}`, commandName, - commandPayload + commandPayload, ); } } else { @@ -115,10 +115,10 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { `${commandName} cannot be issued to handle request PDU ${JSON.stringify( commandPayload, null, - 2 + 2, )} while the charging station is not registered on the central server.`, commandName, - commandPayload + commandPayload, ); } // Send the built response @@ -126,25 +126,25 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService { chargingStation, messageId, response, - commandName + commandName, ); } private validatePayload( chargingStation: ChargingStation, commandName: OCPP20IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ): boolean { if (this.jsonSchemas.has(commandName) === true) { return this.validateIncomingRequestPayload( chargingStation, commandName, this.jsonSchemas.get(commandName), - commandPayload + commandPayload, ); } logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation` + `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`, ); return false; } diff --git a/src/charging-station/ocpp/2.0/OCPP20RequestService.ts b/src/charging-station/ocpp/2.0/OCPP20RequestService.ts index 15a3b502..e7584236 100644 --- a/src/charging-station/ocpp/2.0/OCPP20RequestService.ts +++ b/src/charging-station/ocpp/2.0/OCPP20RequestService.ts @@ -37,7 +37,7 @@ export class OCPP20RequestService extends OCPPRequestService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/BootNotificationRequest.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -45,7 +45,7 @@ export class OCPP20RequestService extends OCPPRequestService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/HeartbeatRequest.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -53,14 +53,14 @@ export class OCPP20RequestService extends OCPPRequestService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/StatusNotificationRequest.json', moduleName, - 'constructor' + 'constructor', ), ], ]); this.buildRequestPayload = this.buildRequestPayload.bind(this) as ( chargingStation: ChargingStation, commandName: OCPP20RequestCommand, - commandParams?: JsonType + commandParams?: JsonType, ) => Request; } @@ -68,7 +68,7 @@ export class OCPP20RequestService extends OCPPRequestService { chargingStation: ChargingStation, commandName: OCPP20RequestCommand, commandParams?: JsonType, - params?: RequestParams + params?: RequestParams, ): Promise { // FIXME?: add sanity checks on charging station availability, connector availability, connector status, etc. if (OCPP20ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) { @@ -77,7 +77,7 @@ export class OCPP20RequestService extends OCPPRequestService { generateUUID(), this.buildRequestPayload(chargingStation, commandName, commandParams), commandName, - params + params, )) as ResponseType; } // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError(). @@ -85,14 +85,14 @@ export class OCPP20RequestService extends OCPPRequestService { ErrorType.NOT_SUPPORTED, `Unsupported OCPP command '${commandName}'`, commandName, - commandParams + commandParams, ); } private buildRequestPayload( chargingStation: ChargingStation, commandName: OCPP20RequestCommand, - commandParams?: JsonType + commandParams?: JsonType, ): Request { commandParams = commandParams as JsonObject; switch (commandName) { @@ -112,7 +112,7 @@ export class OCPP20RequestService extends OCPPRequestService { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Unsupported OCPP command '${commandName}'`, commandName, - commandParams + commandParams, ); } } diff --git a/src/charging-station/ocpp/2.0/OCPP20ResponseService.ts b/src/charging-station/ocpp/2.0/OCPP20ResponseService.ts index 50566300..aefd93dc 100644 --- a/src/charging-station/ocpp/2.0/OCPP20ResponseService.ts +++ b/src/charging-station/ocpp/2.0/OCPP20ResponseService.ts @@ -50,7 +50,7 @@ export class OCPP20ResponseService extends OCPPResponseService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/BootNotificationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -58,7 +58,7 @@ export class OCPP20ResponseService extends OCPPResponseService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/HeartbeatResponse.json', moduleName, - 'constructor' + 'constructor', ), ], [ @@ -66,7 +66,7 @@ export class OCPP20ResponseService extends OCPPResponseService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/StatusNotificationResponse.json', moduleName, - 'constructor' + 'constructor', ), ], ]); @@ -76,14 +76,14 @@ export class OCPP20ResponseService extends OCPPResponseService { OCPP20ServiceUtils.parseJsonSchemaFile( 'assets/json-schemas/ocpp/2.0/ClearCacheResponse.json', moduleName, - 'constructor' + 'constructor', ), ], ]); this.validatePayload = this.validatePayload.bind(this) as ( chargingStation: ChargingStation, commandName: OCPP20RequestCommand, - payload: JsonType + payload: JsonType, ) => boolean; } @@ -91,7 +91,7 @@ export class OCPP20ResponseService extends OCPPResponseService { chargingStation: ChargingStation, commandName: OCPP20RequestCommand, payload: JsonType, - requestPayload: JsonType + requestPayload: JsonType, ): Promise { if ( chargingStation.isRegistered() === true || @@ -107,7 +107,7 @@ export class OCPP20ResponseService extends OCPPResponseService { } catch (error) { logger.error( `${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`, - error + error, ); throw error; } @@ -118,10 +118,10 @@ export class OCPP20ResponseService extends OCPPResponseService { `${commandName} is not implemented to handle response PDU ${JSON.stringify( payload, null, - 2 + 2, )}`, commandName, - payload + payload, ); } } else { @@ -130,10 +130,10 @@ export class OCPP20ResponseService extends OCPPResponseService { `${commandName} cannot be issued to handle response PDU ${JSON.stringify( payload, null, - 2 + 2, )} while the charging station is not registered on the central server.`, commandName, - payload + payload, ); } } @@ -141,25 +141,25 @@ export class OCPP20ResponseService extends OCPPResponseService { private validatePayload( chargingStation: ChargingStation, commandName: OCPP20RequestCommand, - payload: JsonType + payload: JsonType, ): boolean { if (this.jsonSchemas.has(commandName) === true) { return this.validateResponsePayload( chargingStation, commandName, this.jsonSchemas.get(commandName), - payload + payload, ); } logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation` + `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command '${commandName}' PDU validation`, ); return false; } private handleResponseBootNotification( chargingStation: ChargingStation, - payload: OCPP20BootNotificationResponse + payload: OCPP20BootNotificationResponse, ): void { if (payload.status === RegistrationStatusEnumType.ACCEPTED) { ChargingStationConfigurationUtils.addConfigurationKey( @@ -167,7 +167,7 @@ export class OCPP20ResponseService extends OCPPResponseService { OCPP20OptionalVariableName.HeartbeatInterval, payload.interval.toString(), {}, - { overwrite: true, save: true } + { overwrite: true, save: true }, ); OCPP20ServiceUtils.startHeartbeatInterval(chargingStation, payload.interval); } @@ -181,7 +181,7 @@ export class OCPP20ResponseService extends OCPPResponseService { } else { logger.error( `${chargingStation.logPrefix()} Charging station boot notification response received: %j with undefined registration status`, - payload + payload, ); } } diff --git a/src/charging-station/ocpp/2.0/OCPP20ServiceUtils.ts b/src/charging-station/ocpp/2.0/OCPP20ServiceUtils.ts index 8d6ccdf5..c924b240 100644 --- a/src/charging-station/ocpp/2.0/OCPP20ServiceUtils.ts +++ b/src/charging-station/ocpp/2.0/OCPP20ServiceUtils.ts @@ -9,13 +9,13 @@ export class OCPP20ServiceUtils extends OCPPServiceUtils { public static parseJsonSchemaFile( relativePath: string, moduleName?: string, - methodName?: string + methodName?: string, ): JSONSchemaType { return super.parseJsonSchemaFile( relativePath, OCPPVersion.VERSION_20, moduleName, - methodName + methodName, ); } } diff --git a/src/charging-station/ocpp/OCPPIncomingRequestService.ts b/src/charging-station/ocpp/OCPPIncomingRequestService.ts index 0fc67ed2..d364f7aa 100644 --- a/src/charging-station/ocpp/OCPPIncomingRequestService.ts +++ b/src/charging-station/ocpp/OCPPIncomingRequestService.ts @@ -37,15 +37,15 @@ export abstract class OCPPIncomingRequestService extends AsyncResource { chargingStation: ChargingStation, messageId: string, commandName: IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ) => Promise; this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this) as < - T extends JsonType + T extends JsonType, >( chargingStation: ChargingStation, commandName: IncomingRequestCommand, schema: JSONSchemaType, - payload: T + payload: T, ) => boolean; } @@ -60,12 +60,12 @@ export abstract class OCPPIncomingRequestService extends AsyncResource { chargingStation: ChargingStation, commandName: IncomingRequestCommand, error: Error, - params: HandleErrorParams = { throwError: true, consoleOut: false } + params: HandleErrorParams = { throwError: true, consoleOut: false }, ): T | undefined { setDefaultErrorParams(params); logger.error( `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`, - error + error, ); if (!params?.throwError && params?.errorResponse) { return params?.errorResponse; @@ -82,7 +82,7 @@ export abstract class OCPPIncomingRequestService extends AsyncResource { chargingStation: ChargingStation, commandName: IncomingRequestCommand, schema: JSONSchemaType, - payload: T + payload: T, ): boolean { if (chargingStation.getOcppStrictCompliance() === false) { return true; @@ -93,13 +93,13 @@ export abstract class OCPPIncomingRequestService extends AsyncResource { } logger.error( `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`, - validate.errors + validate.errors, ); throw new OCPPError( OCPPServiceUtils.ajvErrorsToErrorType(validate.errors), 'Incoming request PDU is invalid', commandName, - JSON.stringify(validate.errors, null, 2) + JSON.stringify(validate.errors, null, 2), ); } @@ -114,6 +114,6 @@ export abstract class OCPPIncomingRequestService extends AsyncResource { chargingStation: ChargingStation, messageId: string, commandName: IncomingRequestCommand, - commandPayload: JsonType + commandPayload: JsonType, ): Promise; } diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index 4ea134b6..6d0809c5 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -56,31 +56,31 @@ export abstract class OCPPRequestService { this.ocppResponseService = ocppResponseService; this.requestHandler = this.requestHandler.bind(this) as < ReqType extends JsonType, - ResType extends JsonType + ResType extends JsonType, >( chargingStation: ChargingStation, commandName: RequestCommand, commandParams?: JsonType, - params?: RequestParams + params?: RequestParams, ) => Promise; this.sendMessage = this.sendMessage.bind(this) as ( chargingStation: ChargingStation, messageId: string, messagePayload: JsonType, commandName: RequestCommand, - params?: RequestParams + params?: RequestParams, ) => Promise; this.sendResponse = this.sendResponse.bind(this) as ( chargingStation: ChargingStation, messageId: string, messagePayload: JsonType, - commandName: IncomingRequestCommand + commandName: IncomingRequestCommand, ) => Promise; this.sendError = this.sendError.bind(this) as ( chargingStation: ChargingStation, messageId: string, ocppError: OCPPError, - commandName: RequestCommand | IncomingRequestCommand + commandName: RequestCommand | IncomingRequestCommand, ) => Promise; this.internalSendMessage = this.internalSendMessage.bind(this) as ( chargingStation: ChargingStation, @@ -88,7 +88,7 @@ export abstract class OCPPRequestService { messagePayload: JsonType | OCPPError, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand, - params?: RequestParams + params?: RequestParams, ) => Promise; this.buildMessageToSend = this.buildMessageToSend.bind(this) as ( chargingStation: ChargingStation, @@ -97,25 +97,25 @@ export abstract class OCPPRequestService { messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand, responseCallback: ResponseCallback, - errorCallback: ErrorCallback + errorCallback: ErrorCallback, ) => string; this.validateRequestPayload = this.validateRequestPayload.bind(this) as ( chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, - payload: T + payload: T, ) => boolean; this.validateIncomingRequestResponsePayload = this.validateIncomingRequestResponsePayload.bind( - this + this, ) as ( chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, - payload: T + payload: T, ) => boolean; } public static getInstance( this: new (ocppResponseService: OCPPResponseService) => T, - ocppResponseService: OCPPResponseService + ocppResponseService: OCPPResponseService, ): T { if (OCPPRequestService.instance === null) { OCPPRequestService.instance = new this(ocppResponseService); @@ -127,7 +127,7 @@ export abstract class OCPPRequestService { chargingStation: ChargingStation, messageId: string, messagePayload: JsonType, - commandName: IncomingRequestCommand + commandName: IncomingRequestCommand, ): Promise { try { // Send response message @@ -136,7 +136,7 @@ export abstract class OCPPRequestService { messageId, messagePayload, MessageType.CALL_RESULT_MESSAGE, - commandName + commandName, ); } catch (error) { handleSendMessageError(chargingStation, commandName, error as Error, { @@ -149,7 +149,7 @@ export abstract class OCPPRequestService { chargingStation: ChargingStation, messageId: string, ocppError: OCPPError, - commandName: RequestCommand | IncomingRequestCommand + commandName: RequestCommand | IncomingRequestCommand, ): Promise { try { // Send error message @@ -158,7 +158,7 @@ export abstract class OCPPRequestService { messageId, ocppError, MessageType.CALL_ERROR_MESSAGE, - commandName + commandName, ); } catch (error) { handleSendMessageError(chargingStation, commandName, error as Error); @@ -170,7 +170,7 @@ export abstract class OCPPRequestService { messageId: string, messagePayload: JsonType, commandName: RequestCommand, - params: RequestParams = defaultRequestParams + params: RequestParams = defaultRequestParams, ): Promise { params = { ...defaultRequestParams, @@ -183,7 +183,7 @@ export abstract class OCPPRequestService { messagePayload, MessageType.CALL_MESSAGE, commandName, - params + params, ); } catch (error) { handleSendMessageError(chargingStation, commandName, error as Error, { @@ -195,14 +195,14 @@ export abstract class OCPPRequestService { private validateRequestPayload( chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, - payload: T + payload: T, ): boolean { if (chargingStation.getOcppStrictCompliance() === false) { return true; } if (this.jsonSchemas.has(commandName as RequestCommand) === false) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation` + `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`, ); return true; } @@ -214,39 +214,39 @@ export abstract class OCPPRequestService { } logger.error( `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`, - validate.errors + validate.errors, ); // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError(). throw new OCPPError( OCPPServiceUtils.ajvErrorsToErrorType(validate.errors), 'Request PDU is invalid', commandName, - JSON.stringify(validate.errors, null, 2) + JSON.stringify(validate.errors, null, 2), ); } private validateIncomingRequestResponsePayload( chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, - payload: T + payload: T, ): boolean { if (chargingStation.getOcppStrictCompliance() === false) { return true; } if ( this.ocppResponseService.jsonIncomingRequestResponseSchemas.has( - commandName as IncomingRequestCommand + commandName as IncomingRequestCommand, ) === false ) { logger.warn( - `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation` + `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`, ); return true; } const validate = this.ajv.compile( this.ocppResponseService.jsonIncomingRequestResponseSchemas.get( - commandName as IncomingRequestCommand - ) + commandName as IncomingRequestCommand, + ), ); payload = cloneObject(payload); OCPPServiceUtils.convertDateToISOString(payload); @@ -255,14 +255,14 @@ export abstract class OCPPRequestService { } logger.error( `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`, - validate.errors + validate.errors, ); // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError(). throw new OCPPError( OCPPServiceUtils.ajvErrorsToErrorType(validate.errors), 'Response PDU is invalid', commandName, - JSON.stringify(validate.errors, null, 2) + JSON.stringify(validate.errors, null, 2), ); } @@ -272,7 +272,7 @@ export abstract class OCPPRequestService { messagePayload: JsonType | OCPPError, messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand, - params: RequestParams = defaultRequestParams + params: RequestParams = defaultRequestParams, ): Promise { params = { ...defaultRequestParams, @@ -302,7 +302,7 @@ export abstract class OCPPRequestService { if (chargingStation.getEnableStatistics() === true) { chargingStation.performanceStatistics?.addRequestStatistic( commandName, - MessageType.CALL_RESULT_MESSAGE + MessageType.CALL_RESULT_MESSAGE, ); } // Handle the request's response @@ -311,7 +311,7 @@ export abstract class OCPPRequestService { chargingStation, commandName as RequestCommand, payload, - requestPayload + requestPayload, ) .then(() => { resolve(payload); @@ -334,15 +334,15 @@ export abstract class OCPPRequestService { if (requestStatistic === true && chargingStation.getEnableStatistics() === true) { chargingStation.performanceStatistics?.addRequestStatistic( commandName, - MessageType.CALL_ERROR_MESSAGE + MessageType.CALL_ERROR_MESSAGE, ); } logger.error( `${chargingStation.logPrefix()} Error occurred at ${OCPPServiceUtils.getMessageTypeString( - messageType + messageType, )} command ${commandName} with PDU %j:`, messagePayload, - error + error, ); chargingStation.requests.delete(messageId); reject(error); @@ -358,7 +358,7 @@ export abstract class OCPPRequestService { messageType, commandName, responseCallback, - errorCallback + errorCallback, ); let sendError = false; // Check if wsConnection opened @@ -369,15 +369,15 @@ export abstract class OCPPRequestService { chargingStation.wsConnection?.send(messageToSend); logger.debug( `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString( - messageType - )} payload: ${messageToSend}` + messageType, + )} payload: ${messageToSend}`, ); } catch (error) { logger.error( `${chargingStation.logPrefix()} >> Command '${commandName}' failed to send ${OCPPServiceUtils.getMessageTypeString( - messageType + messageType, )} payload: ${messageToSend}:`, - error + error, ); sendError = true; } @@ -393,15 +393,15 @@ export abstract class OCPPRequestService { ErrorType.GENERIC_ERROR, `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`, commandName, - (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FREEZED_OBJECT - ) + (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FREEZED_OBJECT, + ), ); } else if (wsClosedOrErrored) { const ocppError = new OCPPError( ErrorType.GENERIC_ERROR, `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`, commandName, - (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FREEZED_OBJECT + (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FREEZED_OBJECT, ); // Reject response if (messageType !== MessageType.CALL_MESSAGE) { @@ -420,17 +420,17 @@ export abstract class OCPPRequestService { ErrorType.GENERIC_ERROR, `Timeout for message id '${messageId}'`, commandName, - (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FREEZED_OBJECT + (messagePayload as JsonObject)?.details ?? Constants.EMPTY_FREEZED_OBJECT, ), () => { messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId); - } + }, ); } throw new OCPPError( ErrorType.SECURITY_ERROR, `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`, - commandName + commandName, ); } @@ -441,7 +441,7 @@ export abstract class OCPPRequestService { messageType: MessageType, commandName: RequestCommand | IncomingRequestCommand, responseCallback: ResponseCallback, - errorCallback: ErrorCallback + errorCallback: ErrorCallback, ): string { let messageToSend: string; // Type of message @@ -469,7 +469,7 @@ export abstract class OCPPRequestService { this.validateIncomingRequestResponsePayload( chargingStation, commandName, - messagePayload as JsonObject + messagePayload as JsonObject, ); messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response); break; @@ -493,6 +493,6 @@ export abstract class OCPPRequestService { chargingStation: ChargingStation, commandName: RequestCommand, commandParams?: JsonType, - params?: RequestParams + params?: RequestParams, ): Promise; } diff --git a/src/charging-station/ocpp/OCPPResponseService.ts b/src/charging-station/ocpp/OCPPResponseService.ts index 1bc4a8a8..b15b7cd6 100644 --- a/src/charging-station/ocpp/OCPPResponseService.ts +++ b/src/charging-station/ocpp/OCPPResponseService.ts @@ -35,13 +35,13 @@ export abstract class OCPPResponseService { chargingStation: ChargingStation, commandName: RequestCommand, payload: JsonType, - requestPayload: JsonType + requestPayload: JsonType, ) => Promise; this.validateResponsePayload = this.validateResponsePayload.bind(this) as ( chargingStation: ChargingStation, commandName: RequestCommand, schema: JSONSchemaType, - payload: T + payload: T, ) => boolean; } @@ -56,7 +56,7 @@ export abstract class OCPPResponseService { chargingStation: ChargingStation, commandName: RequestCommand, schema: JSONSchemaType, - payload: T + payload: T, ): boolean { if (chargingStation.getOcppStrictCompliance() === false) { return true; @@ -67,13 +67,13 @@ export abstract class OCPPResponseService { } logger.error( `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Command '${commandName}' response PDU is invalid: %j`, - validate.errors + validate.errors, ); throw new OCPPError( OCPPServiceUtils.ajvErrorsToErrorType(validate.errors), 'Response PDU is invalid', commandName, - JSON.stringify(validate.errors, null, 2) + JSON.stringify(validate.errors, null, 2), ); } @@ -85,6 +85,6 @@ export abstract class OCPPResponseService { chargingStation: ChargingStation, commandName: RequestCommand, payload: JsonType, - requestPayload: JsonType + requestPayload: JsonType, ): Promise; } diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index 8e206490..f18db3e0 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -74,7 +74,7 @@ export class OCPPServiceUtils { public static isRequestCommandSupported( chargingStation: ChargingStation, - command: RequestCommand + command: RequestCommand, ): boolean { const isRequestCommand = Object.values(RequestCommand).includes(command); if ( @@ -94,7 +94,7 @@ export class OCPPServiceUtils { public static isIncomingRequestCommandSupported( chargingStation: ChargingStation, - command: IncomingRequestCommand + command: IncomingRequestCommand, ): boolean { const isIncomingRequestCommand = Object.values(IncomingRequestCommand).includes(command); @@ -115,7 +115,7 @@ export class OCPPServiceUtils { public static isMessageTriggerSupported( chargingStation: ChargingStation, - messageTrigger: MessageTrigger + messageTrigger: MessageTrigger, ): boolean { const isMessageTrigger = Object.values(MessageTrigger).includes(messageTrigger); if (isMessageTrigger === true && !chargingStation.stationInfo?.messageTriggerSupport) { @@ -124,7 +124,7 @@ export class OCPPServiceUtils { return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger] ?? false; } logger.error( - `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'` + `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`, ); return false; } @@ -132,11 +132,11 @@ export class OCPPServiceUtils { public static isConnectorIdValid( chargingStation: ChargingStation, ocppCommand: IncomingRequestCommand, - connectorId: number + connectorId: number, ): boolean { if (connectorId < 0) { logger.error( - `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}` + `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`, ); return false; } @@ -157,7 +157,7 @@ export class OCPPServiceUtils { chargingStation: ChargingStation, connectorId: number, status: ConnectorStatusEnum, - evseId?: number + evseId?: number, ): StatusNotificationRequest { switch (chargingStation.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16) { case OCPPVersion.VERSION_16: @@ -192,7 +192,7 @@ export class OCPPServiceUtils { connectorId: number, status: ConnectorStatusEnum, evseId?: number, - options: { send: boolean } = { send: true } + options: { send: boolean } = { send: true }, ) { options = { send: true, ...options }; if (options.send) { @@ -207,8 +207,8 @@ export class OCPPServiceUtils { chargingStation, connectorId, status, - evseId - ) + evseId, + ), ); } chargingStation.getConnectorStatus(connectorId).status = status; @@ -217,7 +217,7 @@ export class OCPPServiceUtils { protected static checkConnectorStatusTransition( chargingStation: ChargingStation, connectorId: number, - status: ConnectorStatusEnum + status: ConnectorStatusEnum, ): boolean { const fromStatus = chargingStation.getConnectorStatus(connectorId).status; let transitionAllowed = false; @@ -226,11 +226,11 @@ export class OCPPServiceUtils { if ( (connectorId === 0 && OCPP16Constants.ChargePointStatusChargingStationTransitions.findIndex( - (transition) => transition.from === fromStatus && transition.to === status + (transition) => transition.from === fromStatus && transition.to === status, ) !== -1) || (connectorId > 0 && OCPP16Constants.ChargePointStatusConnectorTransitions.findIndex( - (transition) => transition.from === fromStatus && transition.to === status + (transition) => transition.from === fromStatus && transition.to === status, ) !== -1) ) { transitionAllowed = true; @@ -241,11 +241,11 @@ export class OCPPServiceUtils { if ( (connectorId === 0 && OCPP20Constants.ChargingStationStatusTransitions.findIndex( - (transition) => transition.from === fromStatus && transition.to === status + (transition) => transition.from === fromStatus && transition.to === status, ) !== -1) || (connectorId > 0 && OCPP20Constants.ConnectorStatusTransitions.findIndex( - (transition) => transition.from === fromStatus && transition.to === status + (transition) => transition.from === fromStatus && transition.to === status, ) !== -1) ) { transitionAllowed = true; @@ -254,7 +254,7 @@ export class OCPPServiceUtils { default: throw new BaseError( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported` + `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`, ); } if (transitionAllowed === false) { @@ -263,7 +263,7 @@ export class OCPPServiceUtils { chargingStation.stationInfo.ocppVersion } connector id ${connectorId} status transition from '${ chargingStation.getConnectorStatus(connectorId).status - }' to '${status}' is not allowed` + }' to '${status}' is not allowed`, ); } return transitionAllowed; @@ -273,7 +273,7 @@ export class OCPPServiceUtils { relativePath: string, ocppVersion: OCPPVersion, moduleName?: string, - methodName?: string + methodName?: string, ): JSONSchemaType { const filePath = join(dirname(fileURLToPath(import.meta.url)), relativePath); try { @@ -284,7 +284,7 @@ export class OCPPServiceUtils { FileType.JsonSchema, error as NodeJS.ErrnoException, OCPPServiceUtils.logPrefix(ocppVersion, moduleName, methodName), - { throwError: false } + { throwError: false }, ); } } @@ -293,12 +293,12 @@ export class OCPPServiceUtils { chargingStation: ChargingStation, connectorId: number, measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, - phase?: MeterValuePhase + phase?: MeterValuePhase, ): SampledValueTemplate | undefined { const onPhaseStr = phase ? `on phase ${phase} ` : ''; if (OCPPConstants.OCPP_MEASURANDS_SUPPORTED.includes(measurand) === false) { logger.warn( - `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}` + `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, ); return; } @@ -306,13 +306,13 @@ export class OCPPServiceUtils { measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, - StandardParametersKey.MeterValuesSampledData + StandardParametersKey.MeterValuesSampledData, )?.value?.includes(measurand) === false ) { logger.debug( `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${ StandardParametersKey.MeterValuesSampledData - }' OCPP parameter` + }' OCPP parameter`, ); return; } @@ -326,11 +326,11 @@ export class OCPPServiceUtils { if ( OCPPConstants.OCPP_MEASURANDS_SUPPORTED.includes( sampledValueTemplates[index]?.measurand ?? - MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER + MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, ) === false ) { logger.warn( - `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}` + `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, ); } else if ( phase && @@ -338,7 +338,7 @@ export class OCPPServiceUtils { sampledValueTemplates[index]?.measurand === measurand && ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, - StandardParametersKey.MeterValuesSampledData + StandardParametersKey.MeterValuesSampledData, )?.value?.includes(measurand) === true ) { return sampledValueTemplates[index]; @@ -348,7 +348,7 @@ export class OCPPServiceUtils { sampledValueTemplates[index]?.measurand === measurand && ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, - StandardParametersKey.MeterValuesSampledData + StandardParametersKey.MeterValuesSampledData, )?.value?.includes(measurand) === true ) { return sampledValueTemplates[index]; @@ -366,7 +366,7 @@ export class OCPPServiceUtils { throw new BaseError(errorMsg); } logger.debug( - `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}` + `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, ); } @@ -376,7 +376,7 @@ export class OCPPServiceUtils { options: { limitationEnabled?: boolean; unitMultiplier?: number } = { limitationEnabled: true, unitMultiplier: 1, - } + }, ): number { options = { ...{ @@ -395,7 +395,7 @@ export class OCPPServiceUtils { private static logPrefix = ( ocppVersion: OCPPVersion, moduleName?: string, - methodName?: string + methodName?: string, ): string => { const logMsg = isNotEmptyString(moduleName) && isNotEmptyString(methodName) diff --git a/src/charging-station/ui-server/AbstractUIServer.ts b/src/charging-station/ui-server/AbstractUIServer.ts index e6894416..8bd45e68 100644 --- a/src/charging-station/ui-server/AbstractUIServer.ts +++ b/src/charging-station/ui-server/AbstractUIServer.ts @@ -33,7 +33,7 @@ export abstract class AbstractUIServer { public buildProtocolRequest( id: string, procedureName: ProcedureName, - requestPayload: RequestPayload + requestPayload: RequestPayload, ): ProtocolRequest { return [id, procedureName, requestPayload]; } @@ -104,6 +104,6 @@ export abstract class AbstractUIServer { public abstract logPrefix( moduleName?: string, methodName?: string, - prefixSuffix?: string + prefixSuffix?: string, ): string; } diff --git a/src/charging-station/ui-server/UIHttpServer.ts b/src/charging-station/ui-server/UIHttpServer.ts index 97eaa119..32b82e9c 100644 --- a/src/charging-station/ui-server/UIHttpServer.ts +++ b/src/charging-station/ui-server/UIHttpServer.ts @@ -60,13 +60,13 @@ export class UIHttpServer extends AbstractUIServer { .end(JSON.stringify(payload)); } else { logger.error( - `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}` + `${this.logPrefix(moduleName, 'sendResponse')} Response for unknown request id: ${uuid}`, ); } } catch (error) { logger.error( `${this.logPrefix(moduleName, 'sendResponse')} Error at sending response id '${uuid}':`, - error + error, ); } finally { this.responseHandlers.delete(uuid); @@ -99,7 +99,7 @@ export class UIHttpServer extends AbstractUIServer { const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [ Protocol, ProtocolVersion, - ProcedureName + ProcedureName, ]; const uuid = generateUUID(); this.responseHandlers.set(uuid, res); @@ -112,7 +112,7 @@ export class UIHttpServer extends AbstractUIServer { req.on('error', (error) => { logger.error( `${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`, - error + error, ); }); if (req.method === HttpMethods.POST) { @@ -129,8 +129,8 @@ export class UIHttpServer extends AbstractUIServer { this.buildProtocolRequest( uuid, procedureName, - body ?? Constants.EMPTY_FREEZED_OBJECT - ) + body ?? Constants.EMPTY_FREEZED_OBJECT, + ), ) .then((protocolResponse: ProtocolResponse) => { if (!isNullOrUndefined(protocolResponse)) { @@ -145,7 +145,7 @@ export class UIHttpServer extends AbstractUIServer { } catch (error) { logger.error( `${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`, - error + error, ); this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE })); } diff --git a/src/charging-station/ui-server/UIServerFactory.ts b/src/charging-station/ui-server/UIServerFactory.ts index a5fb5a5d..1bdd9dad 100644 --- a/src/charging-station/ui-server/UIServerFactory.ts +++ b/src/charging-station/ui-server/UIServerFactory.ts @@ -13,13 +13,13 @@ export class UIServerFactory { } public static getUIServerImplementation( - uiServerConfiguration?: UIServerConfiguration + uiServerConfiguration?: UIServerConfiguration, ): AbstractUIServer | null { if (UIServerUtils.isLoopback(uiServerConfiguration.options?.host) === false) { console.warn( chalk.yellow( - 'Loopback address not detected in UI server configuration. This is not recommended.' - ) + 'Loopback address not detected in UI server configuration. This is not recommended.', + ), ); } switch (uiServerConfiguration?.type ?? Configuration.getUIServer().type) { diff --git a/src/charging-station/ui-server/UIServerUtils.ts b/src/charging-station/ui-server/UIServerUtils.ts index cada1399..2b0bf3de 100644 --- a/src/charging-station/ui-server/UIServerUtils.ts +++ b/src/charging-station/ui-server/UIServerUtils.ts @@ -11,7 +11,7 @@ export class UIServerUtils { public static handleProtocols = ( protocols: Set, // eslint-disable-next-line @typescript-eslint/no-unused-vars - request: IncomingMessage + request: IncomingMessage, ): string | false => { let protocol: Protocol; let version: ProtocolVersion; @@ -25,8 +25,8 @@ export class UIServerUtils { } logger.error( `${logPrefix( - ' UI WebSocket Server |' - )} Unsupported protocol: ${protocol} or protocol version: ${version}` + ' UI WebSocket Server |', + )} Unsupported protocol: ${protocol} or protocol version: ${version}`, ); return false; }; @@ -43,7 +43,7 @@ export class UIServerUtils { const protocolIndex = protocolStr.indexOf(Protocol.UI); const protocol = protocolStr.substring( protocolIndex, - protocolIndex + Protocol.UI.length + protocolIndex + Protocol.UI.length, ) as Protocol; const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion; return [protocol, version]; @@ -53,7 +53,7 @@ export class UIServerUtils { const isLoopbackRegExp = new RegExp( // eslint-disable-next-line no-useless-escape /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/, - 'i' + 'i', ); return isLoopbackRegExp.test(address); } diff --git a/src/charging-station/ui-server/UIWebSocketServer.ts b/src/charging-station/ui-server/UIWebSocketServer.ts index 2cd0267c..8306be0e 100644 --- a/src/charging-station/ui-server/UIWebSocketServer.ts +++ b/src/charging-station/ui-server/UIWebSocketServer.ts @@ -42,8 +42,8 @@ export class UIWebSocketServer extends AbstractUIServer { logger.error( `${this.logPrefix( moduleName, - 'start.server.onconnection' - )} Unsupported UI protocol version: '${ws.protocol}'` + 'start.server.onconnection', + )} Unsupported UI protocol version: '${ws.protocol}'`, ); ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR); } @@ -74,10 +74,10 @@ export class UIWebSocketServer extends AbstractUIServer { logger.debug( `${this.logPrefix( moduleName, - 'start.ws.onclose' + 'start.ws.onclose', )} WebSocket closed: '${getWebSocketCloseEventStatusString( - code - )}' - '${reason.toString()}'` + code, + )}' - '${reason.toString()}'`, ); }); }); @@ -103,9 +103,9 @@ export class UIWebSocketServer extends AbstractUIServer { logger.error( `${this.logPrefix( moduleName, - 'start.httpServer.on.upgrade' + 'start.httpServer.on.upgrade', )} Error at handling connection upgrade:`, - error + error, ); } }); @@ -128,27 +128,25 @@ export class UIWebSocketServer extends AbstractUIServer { logger.error( `${this.logPrefix( moduleName, - 'sendResponse' - )} Error at sending response id '${responseId}', WebSocket is not open: ${ - ws?.readyState - }` + 'sendResponse', + )} Error at sending response id '${responseId}', WebSocket is not open: ${ws?.readyState}`, ); } } else { logger.error( `${this.logPrefix( moduleName, - 'sendResponse' - )} Response for unknown request id: ${responseId}` + 'sendResponse', + )} Response for unknown request id: ${responseId}`, ); } } catch (error) { logger.error( `${this.logPrefix( moduleName, - 'sendResponse' + 'sendResponse', )} Error at sending response id '${responseId}':`, - error + error, ); } finally { this.responseHandlers.delete(responseId); @@ -188,9 +186,9 @@ export class UIWebSocketServer extends AbstractUIServer { logger.error( `${this.logPrefix( moduleName, - 'validateRawDataRequest' + 'validateRawDataRequest', )} UI protocol request is not an array:`, - request + request, ); return false; } @@ -198,7 +196,7 @@ export class UIWebSocketServer extends AbstractUIServer { if (request.length !== 3) { logger.error( `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`, - request + request, ); return false; } @@ -207,9 +205,9 @@ export class UIWebSocketServer extends AbstractUIServer { logger.error( `${this.logPrefix( moduleName, - 'validateRawDataRequest' + 'validateRawDataRequest', )} UI protocol request UUID field is invalid:`, - request + request, ); return false; } diff --git a/src/charging-station/ui-server/ui-services/AbstractUIService.ts b/src/charging-station/ui-server/ui-services/AbstractUIService.ts index ab2c1167..7da2b62f 100644 --- a/src/charging-station/ui-server/ui-services/AbstractUIService.ts +++ b/src/charging-station/ui-server/ui-services/AbstractUIService.ts @@ -79,8 +79,8 @@ export abstract class AbstractUIService { `${command} is not implemented to handle message payload ${JSON.stringify( requestPayload, null, - 2 - )}` + 2, + )}`, ); } @@ -136,21 +136,21 @@ export abstract class AbstractUIService { protected handleProtocolRequest( uuid: string, procedureName: ProcedureName, - payload: RequestPayload + payload: RequestPayload, ): void { this.sendBroadcastChannelRequest( uuid, AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping[ procedureName ] as BroadcastChannelProcedureName, - payload + payload, ); } private sendBroadcastChannelRequest( uuid: string, procedureName: BroadcastChannelProcedureName, - payload: BroadcastChannelRequestPayload + payload: BroadcastChannelRequestPayload, ): void { if (isNotEmptyArray(payload.hashIds)) { payload.hashIds = payload.hashIds @@ -162,8 +162,8 @@ export abstract class AbstractUIService { logger.warn( `${this.logPrefix( moduleName, - 'sendBroadcastChannelRequest' - )} Charging station with hashId '${hashId}' not found` + 'sendBroadcastChannelRequest', + )} Charging station with hashId '${hashId}' not found`, ); }); } diff --git a/src/charging-station/ui-server/ui-services/UIService001.ts b/src/charging-station/ui-server/ui-services/UIService001.ts index e6ee2d2c..b8ac1c91 100644 --- a/src/charging-station/ui-server/ui-services/UIService001.ts +++ b/src/charging-station/ui-server/ui-services/UIService001.ts @@ -8,7 +8,7 @@ export class UIService001 extends AbstractUIService { for (const procedureName in AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping) { this.requestHandlers.set( procedureName as ProcedureName, - this.handleProtocolRequest.bind(this) as ProtocolRequestHandler + this.handleProtocolRequest.bind(this) as ProtocolRequestHandler, ); } } diff --git a/src/charging-station/ui-server/ui-services/UIServiceFactory.ts b/src/charging-station/ui-server/ui-services/UIServiceFactory.ts index 47a1893d..41d60ddd 100644 --- a/src/charging-station/ui-server/ui-services/UIServiceFactory.ts +++ b/src/charging-station/ui-server/ui-services/UIServiceFactory.ts @@ -10,7 +10,7 @@ export class UIServiceFactory { public static getUIServiceImplementation( version: ProtocolVersion, - uiServer: AbstractUIServer + uiServer: AbstractUIServer, ): AbstractUIService { switch (version) { case ProtocolVersion['0.0.1']: diff --git a/src/exception/OCPPError.ts b/src/exception/OCPPError.ts index 35df1f50..0c69eb23 100644 --- a/src/exception/OCPPError.ts +++ b/src/exception/OCPPError.ts @@ -18,7 +18,7 @@ export class OCPPError extends BaseError { code: ErrorType, message: string, command?: RequestCommand | IncomingRequestCommand, - details?: JsonType + details?: JsonType, ) { super(message); diff --git a/src/performance/PerformanceStatistics.ts b/src/performance/PerformanceStatistics.ts index 317acf54..9672b381 100644 --- a/src/performance/PerformanceStatistics.ts +++ b/src/performance/PerformanceStatistics.ts @@ -55,7 +55,7 @@ export class PerformanceStatistics { public static getInstance( objId: string, objName: string, - uri: URL + uri: URL, ): PerformanceStatistics | undefined { if (!PerformanceStatistics.instances.has(objId)) { PerformanceStatistics.instances.set(objId, new PerformanceStatistics(objId, objName, uri)); @@ -77,7 +77,7 @@ export class PerformanceStatistics { public addRequestStatistic( command: RequestCommand | IncomingRequestCommand, - messageType: MessageType + messageType: MessageType, ): void { switch (messageType) { case MessageType.CALL_MESSAGE: @@ -132,7 +132,7 @@ export class PerformanceStatistics { logger.info( `${this.logPrefix()} storage enabled: type ${ Configuration.getPerformanceStorage().type - }, uri: ${Configuration.getPerformanceStorage().uri}` + }, uri: ${Configuration.getPerformanceStorage().uri}`, ); } } @@ -177,15 +177,15 @@ export class PerformanceStatistics { this.logStatistics(); }, logStatisticsInterval * 1000); logger.info( - `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}` + `${this.logPrefix()} logged every ${formatDurationSeconds(logStatisticsInterval)}`, ); } else if (this.displayInterval) { logger.info( - `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}` + `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`, ); } else if (Configuration.getLog().enabled) { logger.info( - `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics` + `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics`, ); } } @@ -210,11 +210,11 @@ export class PerformanceStatistics { this.statistics.statisticsData.get(entryName).currentTimeMeasurement = entry.duration; this.statistics.statisticsData.get(entryName).minTimeMeasurement = Math.min( entry.duration, - this.statistics.statisticsData.get(entryName)?.minTimeMeasurement ?? Infinity + this.statistics.statisticsData.get(entryName)?.minTimeMeasurement ?? Infinity, ); this.statistics.statisticsData.get(entryName).maxTimeMeasurement = Math.max( entry.duration, - this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement ?? -Infinity + this.statistics.statisticsData.get(entryName)?.maxTimeMeasurement ?? -Infinity, ); this.statistics.statisticsData.get(entryName).totalTimeMeasurement = (this.statistics.statisticsData.get(entryName)?.totalTimeMeasurement ?? 0) + entry.duration; @@ -231,17 +231,17 @@ export class PerformanceStatistics { value: entry.duration, })); this.statistics.statisticsData.get(entryName).medTimeMeasurement = median( - extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).measurementTimeSeries) + extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).measurementTimeSeries), ); this.statistics.statisticsData.get(entryName).ninetyFiveThPercentileTimeMeasurement = nthPercentile( extractTimeSeriesValues( - this.statistics.statisticsData.get(entryName).measurementTimeSeries + this.statistics.statisticsData.get(entryName).measurementTimeSeries, ), - 95 + 95, ); this.statistics.statisticsData.get(entryName).stdDevTimeMeasurement = stdDeviation( - extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).measurementTimeSeries) + extractTimeSeriesValues(this.statistics.statisticsData.get(entryName).measurementTimeSeries), ); if (Configuration.getPerformanceStorage().enabled) { parentPort?.postMessage(buildPerformanceStatisticsMessage(this.statistics)); diff --git a/src/performance/storage/JsonFileStorage.ts b/src/performance/storage/JsonFileStorage.ts index c4a9f748..8bbbd42c 100644 --- a/src/performance/storage/JsonFileStorage.ts +++ b/src/performance/storage/JsonFileStorage.ts @@ -39,7 +39,7 @@ export class JsonFileStorage extends Storage { this.dbName, FileType.PerformanceRecords, error as NodeJS.ErrnoException, - this.logPrefix + this.logPrefix, ); }) .finally(() => { @@ -60,7 +60,7 @@ export class JsonFileStorage extends Storage { this.dbName, FileType.PerformanceRecords, error as NodeJS.ErrnoException, - this.logPrefix + this.logPrefix, ); } } @@ -76,7 +76,7 @@ export class JsonFileStorage extends Storage { this.dbName, FileType.PerformanceRecords, error as NodeJS.ErrnoException, - this.logPrefix + this.logPrefix, ); } } @@ -84,7 +84,7 @@ export class JsonFileStorage extends Storage { private checkPerformanceRecordsFile(): void { if (!this?.fd) { throw new BaseError( - `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found` + `${this.logPrefix} Performance records '${this.dbName}' file descriptor not found`, ); } } diff --git a/src/performance/storage/MongoDBStorage.ts b/src/performance/storage/MongoDBStorage.ts index 7dd505d3..3e1abd2b 100644 --- a/src/performance/storage/MongoDBStorage.ts +++ b/src/performance/storage/MongoDBStorage.ts @@ -58,15 +58,15 @@ export class MongoDBStorage extends Storage { if (!this?.client) { throw new BaseError( `${this.logPrefix} ${this.getDBNameFromStorageType( - StorageType.MONGO_DB - )} client initialization failed while trying to issue a request` + StorageType.MONGO_DB, + )} client initialization failed while trying to issue a request`, ); } if (!this.connected) { throw new BaseError( `${this.logPrefix} ${this.getDBNameFromStorageType( - StorageType.MONGO_DB - )} connection not opened while trying to issue a request` + StorageType.MONGO_DB, + )} connection not opened while trying to issue a request`, ); } } diff --git a/src/performance/storage/Storage.ts b/src/performance/storage/Storage.ts index f0fda133..4c9ece35 100644 --- a/src/performance/storage/Storage.ts +++ b/src/performance/storage/Storage.ts @@ -25,7 +25,7 @@ export abstract class Storage { type: StorageType, error: Error, table?: string, - params: HandleErrorParams = { throwError: false, consoleOut: false } + params: HandleErrorParams = { throwError: false, consoleOut: false }, ): void { setDefaultErrorParams(params, { throwError: false, consoleOut: false }); const inTableOrCollectionStr = @@ -34,7 +34,7 @@ export abstract class Storage { `${this.logPrefix} ${this.getDBNameFromStorageType(type)} error '${ error.message }'${inTableOrCollectionStr}:`, - error + error, ); if (params?.throwError) { throw error; @@ -57,6 +57,6 @@ export abstract class Storage { public abstract open(): void | Promise; public abstract close(): void | Promise; public abstract storePerformanceStatistics( - performanceStatistics: Statistics + performanceStatistics: Statistics, ): void | Promise; } diff --git a/src/scripts/deleteChargingStations.cjs b/src/scripts/deleteChargingStations.cjs index 4f65bdd3..6890d4bb 100755 --- a/src/scripts/deleteChargingStations.cjs +++ b/src/scripts/deleteChargingStations.cjs @@ -25,7 +25,7 @@ if (config && config.mongoConnectionString) { console.info( response.deletedCount, `Charging Stations with id = %${config.idPattern}% deleted. TenantID =`, - tenantID + tenantID, ); } client.close(); diff --git a/src/scripts/setCSPublicFlag.cjs b/src/scripts/setCSPublicFlag.cjs index e591d3ba..7192341e 100755 --- a/src/scripts/setCSPublicFlag.cjs +++ b/src/scripts/setCSPublicFlag.cjs @@ -26,7 +26,7 @@ if (config && config.mongoConnectionString) { console.info( response.modifiedCount, `Charging Stations with id = %${config.idPattern}% updated. TenantID =`, - tenantID + tenantID, ); } client.close(); diff --git a/src/types/UIProtocol.ts b/src/types/UIProtocol.ts index 52b91b97..f4811943 100644 --- a/src/types/UIProtocol.ts +++ b/src/types/UIProtocol.ts @@ -24,7 +24,7 @@ export type ProtocolResponse = [string, ResponsePayload]; export type ProtocolRequestHandler = ( uuid?: string, procedureName?: ProcedureName, - payload?: RequestPayload + payload?: RequestPayload, ) => undefined | Promise | ResponsePayload | Promise; export enum ProcedureName { diff --git a/src/types/WorkerBroadcastChannel.ts b/src/types/WorkerBroadcastChannel.ts index d2afcb90..21671fbb 100644 --- a/src/types/WorkerBroadcastChannel.ts +++ b/src/types/WorkerBroadcastChannel.ts @@ -3,7 +3,7 @@ import type { RequestPayload, ResponsePayload } from './UIProtocol'; export type BroadcastChannelRequest = [ string, BroadcastChannelProcedureName, - BroadcastChannelRequestPayload + BroadcastChannelRequestPayload, ]; export type BroadcastChannelResponse = [string, BroadcastChannelResponsePayload]; diff --git a/src/types/ocpp/Requests.ts b/src/types/ocpp/Requests.ts index 9ca43da7..38cb22fc 100644 --- a/src/types/ocpp/Requests.ts +++ b/src/types/ocpp/Requests.ts @@ -57,7 +57,7 @@ export type CachedRequest = [ ResponseCallback, ErrorCallback, RequestCommand | IncomingRequestCommand, - JsonType + JsonType, ]; export const MessageTrigger = { @@ -83,7 +83,7 @@ export type FirmwareStatusNotificationRequest = OCPP16FirmwareStatusNotification export type IncomingRequestHandler = ( chargingStation: ChargingStation, - commandPayload: JsonType + commandPayload: JsonType, ) => JsonType | Promise; export const AvailabilityType = { diff --git a/src/types/ocpp/Responses.ts b/src/types/ocpp/Responses.ts index 94dcd07c..d36a5478 100644 --- a/src/types/ocpp/Responses.ts +++ b/src/types/ocpp/Responses.ts @@ -32,7 +32,7 @@ export type ErrorResponse = [MessageType.CALL_ERROR_MESSAGE, string, ErrorType, export type ResponseHandler = ( chargingStation: ChargingStation, payload: JsonType, - requestPayload?: JsonType + requestPayload?: JsonType, ) => void | Promise; export type BootNotificationResponse = diff --git a/src/utils/ChargingStationConfigurationUtils.ts b/src/utils/ChargingStationConfigurationUtils.ts index d264afec..08dbdbde 100644 --- a/src/utils/ChargingStationConfigurationUtils.ts +++ b/src/utils/ChargingStationConfigurationUtils.ts @@ -8,7 +8,7 @@ import type { } from '../types'; export const buildChargingStationAutomaticTransactionGeneratorConfiguration = ( - chargingStation: ChargingStation + chargingStation: ChargingStation, ): ChargingStationAutomaticTransactionGeneratorConfiguration => { return { automaticTransactionGenerator: chargingStation.getAutomaticTransactionGeneratorConfiguration(), @@ -23,7 +23,7 @@ export const buildChargingStationAutomaticTransactionGeneratorConfiguration = ( export const buildConnectorsStatus = (chargingStation: ChargingStation): ConnectorStatus[] => { return [...chargingStation.connectors.values()].map( // eslint-disable-next-line @typescript-eslint/no-unused-vars - ({ transactionSetInterval, ...connectorStatusRest }) => connectorStatusRest + ({ transactionSetInterval, ...connectorStatusRest }) => connectorStatusRest, ); }; @@ -34,12 +34,12 @@ export const enum OutputFormat { export const buildEvsesStatus = ( chargingStation: ChargingStation, - outputFormat: OutputFormat = OutputFormat.configuration + outputFormat: OutputFormat = OutputFormat.configuration, ): (EvseStatusWorkerType | EvseStatusConfiguration)[] => { return [...chargingStation.evses.values()].map((evseStatus) => { const connectorsStatus = [...evseStatus.connectors.values()].map( // eslint-disable-next-line @typescript-eslint/no-unused-vars - ({ transactionSetInterval, ...connectorStatusRest }) => connectorStatusRest + ({ transactionSetInterval, ...connectorStatusRest }) => connectorStatusRest, ); let status: EvseStatusConfiguration; switch (outputFormat) { diff --git a/src/utils/CircularArray.ts b/src/utils/CircularArray.ts index fb73ced9..f87ddd45 100644 --- a/src/utils/CircularArray.ts +++ b/src/utils/CircularArray.ts @@ -39,7 +39,7 @@ export class CircularArray extends Array { if (concatenatedCircularArray.length > concatenatedCircularArray.size) { concatenatedCircularArray.splice( 0, - concatenatedCircularArray.length - concatenatedCircularArray.size + concatenatedCircularArray.length - concatenatedCircularArray.size, ); } return concatenatedCircularArray; diff --git a/src/utils/Configuration.ts b/src/utils/Configuration.ts index e5f8a7c0..c22fc334 100644 --- a/src/utils/Configuration.ts +++ b/src/utils/Configuration.ts @@ -26,7 +26,7 @@ export class Configuration { private static configurationFile = join( dirname(fileURLToPath(import.meta.url)), 'assets', - 'config.json' + 'config.json', ); private static configurationFileWatcher: FSWatcher | undefined; @@ -45,8 +45,8 @@ export class Configuration { if (hasOwnProp(Configuration.getConfig(), 'uiWebSocketServer')) { console.error( `${chalk.green(Configuration.logPrefix())} ${chalk.red( - "Deprecated configuration section 'uiWebSocketServer' usage. Use 'uiServer' instead" - )}` + "Deprecated configuration section 'uiWebSocketServer' usage. Use 'uiServer' instead", + )}`, ); } let uiServerConfiguration: UIServerConfiguration = { @@ -60,7 +60,7 @@ export class Configuration { if (hasOwnProp(Configuration.getConfig(), 'uiServer')) { uiServerConfiguration = merge( uiServerConfiguration, - Configuration.getConfig()?.uiServer + Configuration.getConfig()?.uiServer, ); } if (isCFEnvironment() === true) { @@ -84,7 +84,7 @@ export class Configuration { ...(Configuration.getConfig()?.performanceStorage?.type === StorageType.JSON_FILE && Configuration.getConfig()?.performanceStorage?.uri && { uri: Configuration.buildPerformanceUriFilePath( - new URL(Configuration.getConfig()?.performanceStorage?.uri).pathname + new URL(Configuration.getConfig()?.performanceStorage?.uri).pathname, ), }), }; @@ -96,17 +96,17 @@ export class Configuration { Configuration.warnDeprecatedConfigurationKey( 'autoReconnectTimeout', undefined, - "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead" + "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead", ); Configuration.warnDeprecatedConfigurationKey( 'connectionTimeout', undefined, - "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead" + "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead", ); Configuration.warnDeprecatedConfigurationKey( 'autoReconnectMaxRetries', undefined, - 'Use it in charging station template instead' + 'Use it in charging station template instead', ); // Read conf if (hasOwnProp(Configuration.getConfig(), 'autoReconnectMaxRetries')) { @@ -118,7 +118,7 @@ export class Configuration { Configuration.warnDeprecatedConfigurationKey( 'stationTemplateURLs', undefined, - "Use 'stationTemplateUrls' instead" + "Use 'stationTemplateUrls' instead", ); !isUndefined(Configuration.getConfig()['stationTemplateURLs']) && (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()[ @@ -129,11 +129,11 @@ export class Configuration { if (!isUndefined(stationTemplateUrl['numberOfStation'])) { console.error( `${chalk.green(Configuration.logPrefix())} ${chalk.red( - `Deprecated configuration key 'numberOfStation' usage for template file '${stationTemplateUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead` - )}` + `Deprecated configuration key 'numberOfStation' usage for template file '${stationTemplateUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead`, + )}`, ); } - } + }, ); // Read conf return Configuration.getConfig()?.stationTemplateUrls; @@ -143,52 +143,52 @@ export class Configuration { Configuration.warnDeprecatedConfigurationKey( 'logEnabled', undefined, - "Use 'log' section to define the logging enablement instead" + "Use 'log' section to define the logging enablement instead", ); Configuration.warnDeprecatedConfigurationKey( 'logFile', undefined, - "Use 'log' section to define the log file instead" + "Use 'log' section to define the log file instead", ); Configuration.warnDeprecatedConfigurationKey( 'logErrorFile', undefined, - "Use 'log' section to define the log error file instead" + "Use 'log' section to define the log error file instead", ); Configuration.warnDeprecatedConfigurationKey( 'logConsole', undefined, - "Use 'log' section to define the console logging enablement instead" + "Use 'log' section to define the console logging enablement instead", ); Configuration.warnDeprecatedConfigurationKey( 'logStatisticsInterval', undefined, - "Use 'log' section to define the log statistics interval instead" + "Use 'log' section to define the log statistics interval instead", ); Configuration.warnDeprecatedConfigurationKey( 'logLevel', undefined, - "Use 'log' section to define the log level instead" + "Use 'log' section to define the log level instead", ); Configuration.warnDeprecatedConfigurationKey( 'logFormat', undefined, - "Use 'log' section to define the log format instead" + "Use 'log' section to define the log format instead", ); Configuration.warnDeprecatedConfigurationKey( 'logRotate', undefined, - "Use 'log' section to define the log rotation enablement instead" + "Use 'log' section to define the log rotation enablement instead", ); Configuration.warnDeprecatedConfigurationKey( 'logMaxFiles', undefined, - "Use 'log' section to define the log maximum files instead" + "Use 'log' section to define the log maximum files instead", ); Configuration.warnDeprecatedConfigurationKey( 'logMaxSize', undefined, - "Use 'log' section to define the log maximum size instead" + "Use 'log' section to define the log maximum size instead", ); const defaultLogConfiguration: LogConfiguration = { enabled: true, @@ -243,47 +243,47 @@ export class Configuration { Configuration.warnDeprecatedConfigurationKey( 'useWorkerPool', undefined, - "Use 'worker' section to define the type of worker process model instead" + "Use 'worker' section to define the type of worker process model instead", ); Configuration.warnDeprecatedConfigurationKey( 'workerProcess', undefined, - "Use 'worker' section to define the type of worker process model instead" + "Use 'worker' section to define the type of worker process model instead", ); Configuration.warnDeprecatedConfigurationKey( 'workerStartDelay', undefined, - "Use 'worker' section to define the worker start delay instead" + "Use 'worker' section to define the worker start delay instead", ); Configuration.warnDeprecatedConfigurationKey( 'chargingStationsPerWorker', undefined, - "Use 'worker' section to define the number of element(s) per worker instead" + "Use 'worker' section to define the number of element(s) per worker instead", ); Configuration.warnDeprecatedConfigurationKey( 'elementStartDelay', undefined, - "Use 'worker' section to define the worker's element start delay instead" + "Use 'worker' section to define the worker's element start delay instead", ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolMinSize', undefined, - "Use 'worker' section to define the worker pool minimum size instead" + "Use 'worker' section to define the worker pool minimum size instead", ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolSize;', undefined, - "Use 'worker' section to define the worker pool maximum size instead" + "Use 'worker' section to define the worker pool maximum size instead", ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolMaxSize;', undefined, - "Use 'worker' section to define the worker pool maximum size instead" + "Use 'worker' section to define the worker pool maximum size instead", ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolStrategy;', undefined, - "Use 'worker' section to define the worker pool strategy instead" + "Use 'worker' section to define the worker pool strategy instead", ); const defaultWorkerConfiguration: WorkerConfiguration = { processType: WorkerProcessType.workerSet, @@ -328,7 +328,7 @@ export class Configuration { public static workerPoolInUse(): boolean { return [WorkerProcessType.dynamicPool, WorkerProcessType.staticPool].includes( - Configuration.getWorker().processType + Configuration.getWorker().processType, ); } @@ -340,7 +340,7 @@ export class Configuration { Configuration.warnDeprecatedConfigurationKey( 'supervisionURLs', undefined, - "Use 'supervisionUrls' instead" + "Use 'supervisionUrls' instead", ); !isUndefined(Configuration.getConfig()['supervisionURLs']) && (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as @@ -354,12 +354,12 @@ export class Configuration { Configuration.warnDeprecatedConfigurationKey( 'distributeStationToTenantEqually', undefined, - "Use 'supervisionUrlDistribution' instead" + "Use 'supervisionUrlDistribution' instead", ); Configuration.warnDeprecatedConfigurationKey( 'distributeStationsToTenantsEqually', undefined, - "Use 'supervisionUrlDistribution' instead" + "Use 'supervisionUrlDistribution' instead", ); return hasOwnProp(Configuration.getConfig(), 'supervisionUrlDistribution') ? Configuration.getConfig()?.supervisionUrlDistribution @@ -373,7 +373,7 @@ export class Configuration { private static warnDeprecatedConfigurationKey( key: string, sectionName?: string, - logMsgToAppend = '' + logMsgToAppend = '', ) { if ( sectionName && @@ -384,16 +384,16 @@ export class Configuration { `${chalk.green(Configuration.logPrefix())} ${chalk.red( `Deprecated configuration key '${key}' usage in section '${sectionName}'${ logMsgToAppend.trim().length > 0 ? `. ${logMsgToAppend}` : '' - }` - )}` + }`, + )}`, ); } else if (!isUndefined(Configuration.getConfig()[key])) { console.error( `${chalk.green(Configuration.logPrefix())} ${chalk.red( `Deprecated configuration key '${key}' usage${ logMsgToAppend.trim().length > 0 ? `. ${logMsgToAppend}` : '' - }` - )}` + }`, + )}`, ); } } @@ -403,14 +403,14 @@ export class Configuration { if (!Configuration.configuration) { try { Configuration.configuration = JSON.parse( - readFileSync(Configuration.configurationFile, 'utf8') + readFileSync(Configuration.configurationFile, 'utf8'), ) as ConfigurationData; } catch (error) { Configuration.handleFileException( Configuration.configurationFile, FileType.Configuration, error as NodeJS.ErrnoException, - Configuration.logPrefix() + Configuration.logPrefix(), ); } if (!Configuration.configurationFileWatcher) { @@ -438,7 +438,7 @@ export class Configuration { Configuration.configurationFile, FileType.Configuration, error as NodeJS.ErrnoException, - Configuration.logPrefix() + Configuration.logPrefix(), ); } } @@ -447,7 +447,7 @@ export class Configuration { file: string, fileType: FileType, error: NodeJS.ErrnoException, - logPrefix: string + logPrefix: string, ): void { const prefix = isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''; let logMsg: string; @@ -475,11 +475,11 @@ export class Configuration { switch (storageType) { case StorageType.JSON_FILE: return Configuration.buildPerformanceUriFilePath( - `${Constants.DEFAULT_PERFORMANCE_DIRECTORY}/${Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME}` + `${Constants.DEFAULT_PERFORMANCE_DIRECTORY}/${Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME}`, ); case StorageType.SQLITE: return Configuration.buildPerformanceUriFilePath( - `${Constants.DEFAULT_PERFORMANCE_DIRECTORY}/${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db` + `${Constants.DEFAULT_PERFORMANCE_DIRECTORY}/${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`, ); default: throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`); diff --git a/src/utils/ErrorUtils.ts b/src/utils/ErrorUtils.ts index 0e3dbc50..fea221e4 100644 --- a/src/utils/ErrorUtils.ts +++ b/src/utils/ErrorUtils.ts @@ -34,7 +34,7 @@ export const handleFileException = ( fileType: FileType, error: NodeJS.ErrnoException, logPrefix: string, - params: HandleErrorParams = defaultErrorParams + params: HandleErrorParams = defaultErrorParams, ): void => { setDefaultErrorParams(params); const prefix = isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''; @@ -77,7 +77,7 @@ export const handleSendMessageError = ( chargingStation: ChargingStation, commandName: RequestCommand | IncomingRequestCommand, error: Error, - params: HandleErrorParams = { throwError: false, consoleOut: false } + params: HandleErrorParams = { throwError: false, consoleOut: false }, ): void => { setDefaultErrorParams(params, { throwError: false, consoleOut: false }); logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error); @@ -88,7 +88,7 @@ export const handleSendMessageError = ( export const setDefaultErrorParams = ( params: HandleErrorParams, - defaultParams: HandleErrorParams = defaultErrorParams + defaultParams: HandleErrorParams = defaultErrorParams, ): HandleErrorParams => { params = { ...defaultParams, ...params }; return params; diff --git a/src/utils/FileUtils.ts b/src/utils/FileUtils.ts index d1d5d629..ecb945bf 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -21,7 +21,7 @@ export const watchJsonFile = ( }); } } - } + }, ): FSWatcher | undefined => { if (isNotEmptyString(file)) { try { diff --git a/src/utils/Logger.ts b/src/utils/Logger.ts index 3f94e63e..c4db93c0 100644 --- a/src/utils/Logger.ts +++ b/src/utils/Logger.ts @@ -15,7 +15,7 @@ if (Configuration.getLog().rotate === true) { filename: insertAt( Configuration.getLog().errorFile, '-%DATE%', - Configuration.getLog().errorFile?.indexOf('.log') + Configuration.getLog().errorFile?.indexOf('.log'), ), level: 'error', ...(logMaxFiles && { maxFiles: logMaxFiles }), @@ -25,7 +25,7 @@ if (Configuration.getLog().rotate === true) { filename: insertAt( Configuration.getLog().file, '-%DATE%', - Configuration.getLog().file?.indexOf('.log') + Configuration.getLog().file?.indexOf('.log'), ), ...(logMaxFiles && { maxFiles: logMaxFiles }), ...(logMaxSize && { maxSize: logMaxSize }), @@ -54,8 +54,8 @@ if (Configuration.getLog().console) { new TransportType.Console({ format: format.combine( format.splat(), - (format[Configuration.getLog().format] as FormatWrap)() + (format[Configuration.getLog().format] as FormatWrap)(), ), - }) + }), ); } diff --git a/src/utils/MessageChannelUtils.ts b/src/utils/MessageChannelUtils.ts index 2bb43a96..39c8b819 100644 --- a/src/utils/MessageChannelUtils.ts +++ b/src/utils/MessageChannelUtils.ts @@ -13,7 +13,7 @@ import { } from '../types'; export const buildStartedMessage = ( - chargingStation: ChargingStation + chargingStation: ChargingStation, ): ChargingStationWorkerMessage => { return { id: ChargingStationWorkerMessageEvents.started, @@ -22,7 +22,7 @@ export const buildStartedMessage = ( }; export const buildStoppedMessage = ( - chargingStation: ChargingStation + chargingStation: ChargingStation, ): ChargingStationWorkerMessage => { return { id: ChargingStationWorkerMessageEvents.stopped, @@ -31,7 +31,7 @@ export const buildStoppedMessage = ( }; export const buildUpdatedMessage = ( - chargingStation: ChargingStation + chargingStation: ChargingStation, ): ChargingStationWorkerMessage => { return { id: ChargingStationWorkerMessageEvents.updated, @@ -40,7 +40,7 @@ export const buildUpdatedMessage = ( }; export const buildPerformanceStatisticsMessage = ( - statistics: Statistics + statistics: Statistics, ): ChargingStationWorkerMessage => { return { id: ChargingStationWorkerMessageEvents.performanceStatistics, diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index b253bfa2..3ef99c5f 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -16,7 +16,7 @@ export const generateUUID = (): string => { export const validateUUID = (uuid: string): boolean => { return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test( - uuid + uuid, ); }; @@ -50,7 +50,7 @@ export const formatDurationSeconds = (duration: number): string => { }; export const convertToDate = ( - value: Date | string | number | null | undefined + value: Date | string | number | null | undefined, ): Date | null | undefined => { if (isNullOrUndefined(value)) { return value as null | undefined; @@ -155,11 +155,11 @@ export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2 export const getRandomFloatFluctuatedRounded = ( staticValue: number, fluctuationPercent: number, - scale = 2 + scale = 2, ): number => { if (fluctuationPercent < 0 || fluctuationPercent > 100) { throw new RangeError( - `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` + `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`, ); } if (fluctuationPercent === 0) { @@ -169,7 +169,7 @@ export const getRandomFloatFluctuatedRounded = ( return getRandomFloatRounded( staticValue * (1 + fluctuationRatio), staticValue * (1 - fluctuationRatio), - scale + scale, ); }; @@ -265,7 +265,7 @@ export const promiseWithTimeout = async ( timeoutError: Error, timeoutCallback: () => void = () => { /* This is intentional */ - } + }, ): Promise => { // Create a timeout promise that rejects in timeout milliseconds const timeoutPromise = new Promise((_, reject) => { @@ -293,7 +293,7 @@ export const secureRandom = (): number => { export const JSONStringifyWithMapSupport = ( obj: Record | Record[] | Map, - space?: number + space?: number, ): string => { return JSON.stringify( obj, @@ -306,7 +306,7 @@ export const JSONStringifyWithMapSupport = ( } return value; }, - space + space, ); }; diff --git a/src/worker/WorkerAbstract.ts b/src/worker/WorkerAbstract.ts index 59610667..2f9093f2 100644 --- a/src/worker/WorkerAbstract.ts +++ b/src/worker/WorkerAbstract.ts @@ -31,7 +31,7 @@ export abstract class WorkerAbstract { poolMaxSize: WorkerConstants.DEFAULT_POOL_MAX_SIZE, elementsPerWorker: WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER, poolOptions: {}, - } + }, ) { if (workerScript === null || workerScript === undefined) { throw new Error('Worker script is not defined'); diff --git a/src/worker/WorkerDynamicPool.ts b/src/worker/WorkerDynamicPool.ts index 45bc6a7a..eebc8fbb 100644 --- a/src/worker/WorkerDynamicPool.ts +++ b/src/worker/WorkerDynamicPool.ts @@ -19,7 +19,7 @@ export class WorkerDynamicPool extends WorkerAbstract { this.workerOptions.poolMinSize, this.workerOptions.poolMaxSize, this.workerScript, - this.workerOptions.poolOptions + this.workerOptions.poolOptions, ); } diff --git a/src/worker/WorkerFactory.ts b/src/worker/WorkerFactory.ts index 35fe82eb..f64d2781 100644 --- a/src/worker/WorkerFactory.ts +++ b/src/worker/WorkerFactory.ts @@ -17,7 +17,7 @@ export class WorkerFactory { public static getWorkerImplementation( workerScript: string, workerProcessType: WorkerProcessType, - workerOptions?: WorkerOptions + workerOptions?: WorkerOptions, ): WorkerAbstract | null { if (!isMainThread) { throw new Error('Cannot get a worker implementation outside the main thread'); diff --git a/src/worker/WorkerSet.ts b/src/worker/WorkerSet.ts index d761a12a..dd7cf2d7 100644 --- a/src/worker/WorkerSet.ts +++ b/src/worker/WorkerSet.ts @@ -48,7 +48,7 @@ export class WorkerSet extends WorkerAbstract { size: this.size, elementsExecuting: [...this.workerSet].reduce( (accumulator, workerSetElement) => accumulator + workerSetElement.numberOfWorkerElements, - 0 + 0, ), elementsPerWorker: this.maxElementsPerWorker, }; @@ -110,11 +110,11 @@ export class WorkerSet extends WorkerAbstract { }); worker.on( 'message', - this.workerOptions?.poolOptions?.messageHandler ?? WorkerConstants.EMPTY_FUNCTION + this.workerOptions?.poolOptions?.messageHandler ?? WorkerConstants.EMPTY_FUNCTION, ); worker.on( 'error', - this.workerOptions?.poolOptions?.errorHandler ?? WorkerConstants.EMPTY_FUNCTION + this.workerOptions?.poolOptions?.errorHandler ?? WorkerConstants.EMPTY_FUNCTION, ); worker.on('error', (error) => { if (this.emitter !== undefined) { @@ -126,14 +126,14 @@ export class WorkerSet extends WorkerAbstract { }); worker.on( 'online', - this.workerOptions?.poolOptions?.onlineHandler ?? WorkerConstants.EMPTY_FUNCTION + this.workerOptions?.poolOptions?.onlineHandler ?? WorkerConstants.EMPTY_FUNCTION, ); worker.on( 'exit', - this.workerOptions?.poolOptions?.exitHandler ?? WorkerConstants.EMPTY_FUNCTION + this.workerOptions?.poolOptions?.exitHandler ?? WorkerConstants.EMPTY_FUNCTION, ); worker.once('exit', () => - this.removeWorkerSetElement(this.getWorkerSetElementByWorker(worker)) + this.removeWorkerSetElement(this.getWorkerSetElementByWorker(worker)), ); const workerSetElement: WorkerSetElement = { worker, numberOfWorkerElements: 0 }; this.workerSet.add(workerSetElement); diff --git a/src/worker/WorkerStaticPool.ts b/src/worker/WorkerStaticPool.ts index 39298123..7000ac9a 100644 --- a/src/worker/WorkerStaticPool.ts +++ b/src/worker/WorkerStaticPool.ts @@ -18,7 +18,7 @@ export class WorkerStaticPool extends WorkerAbstract { this.pool = new FixedThreadPool( this.workerOptions.poolMaxSize, this.workerScript, - this.workerOptions.poolOptions + this.workerOptions.poolOptions, ); } diff --git a/test/utils/CircularArray.test.ts b/test/utils/CircularArray.test.ts index 720ca68d..d77cec58 100644 --- a/test/utils/CircularArray.test.ts +++ b/test/utils/CircularArray.test.ts @@ -29,15 +29,15 @@ describe('CircularArray test suite', () => { it('Verify that circular array size is valid at instance creation', () => { expect(() => new CircularArray(0.25)).toThrowError( - new TypeError('Invalid circular array size: 0.25 is not a safe integer') + new TypeError('Invalid circular array size: 0.25 is not a safe integer'), ); expect(() => new CircularArray(-1)).toThrowError( - new RangeError('Invalid circular array size: -1 < 0') + new RangeError('Invalid circular array size: -1 < 0'), ); expect(() => new CircularArray(Number.MAX_SAFE_INTEGER + 1)).toThrowError( new TypeError( - `Invalid circular array size: ${Number.MAX_SAFE_INTEGER + 1} is not a safe integer` - ) + `Invalid circular array size: ${Number.MAX_SAFE_INTEGER + 1} is not a safe integer`, + ), ); }); @@ -113,15 +113,15 @@ describe('CircularArray test suite', () => { it('Verify that circular array resize works as intended', () => { expect(() => new CircularArray().resize(0.25)).toThrowError( - new TypeError('Invalid circular array size: 0.25 is not a safe integer') + new TypeError('Invalid circular array size: 0.25 is not a safe integer'), ); expect(() => new CircularArray().resize(-1)).toThrowError( - new RangeError('Invalid circular array size: -1 < 0') + new RangeError('Invalid circular array size: -1 < 0'), ); expect(() => new CircularArray().resize(Number.MAX_SAFE_INTEGER + 1)).toThrowError( new TypeError( - `Invalid circular array size: ${Number.MAX_SAFE_INTEGER + 1} is not a safe integer` - ) + `Invalid circular array size: ${Number.MAX_SAFE_INTEGER + 1} is not a safe integer`, + ), ); let circularArray = new CircularArray(5, 1, 2, 3, 4, 5); circularArray.resize(0); diff --git a/test/utils/Utils.test.ts b/test/utils/Utils.test.ts index 892f25a5..e3b8cc3e 100644 --- a/test/utils/Utils.test.ts +++ b/test/utils/Utils.test.ts @@ -137,15 +137,15 @@ describe('Utils test suite', () => { expect(randomInteger).toBeGreaterThanOrEqual(-Constants.MAX_RANDOM_INTEGER); expect(randomInteger).toBeLessThanOrEqual(0); expect(() => getRandomInteger(0, 1)).toThrowError( - 'The value of "max" is out of range. It must be greater than the value of "min" (1). Received 1' + 'The value of "max" is out of range. It must be greater than the value of "min" (1). Received 1', ); expect(() => getRandomInteger(-1)).toThrowError( - 'The value of "max" is out of range. It must be greater than the value of "min" (0). Received 0' + 'The value of "max" is out of range. It must be greater than the value of "min" (0). Received 0', ); expect(() => getRandomInteger(Constants.MAX_RANDOM_INTEGER + 1)).toThrowError( `The value of "max" is out of range. It must be <= ${ Constants.MAX_RANDOM_INTEGER + 1 - }. Received 281_474_976_710_656` + }. Received 281_474_976_710_656`, ); randomInteger = getRandomInteger(2, 1); expect(randomInteger).toBeGreaterThanOrEqual(1); @@ -180,7 +180,7 @@ describe('Utils test suite', () => { expect(randomFloat).not.toEqual(getRandomFloat()); expect(() => getRandomFloat(0, 1)).toThrowError(new RangeError('Invalid interval')); expect(() => getRandomFloat(Number.MAX_VALUE, -Number.MAX_VALUE)).toThrowError( - new RangeError('Invalid interval') + new RangeError('Invalid interval'), ); randomFloat = getRandomFloat(0, -Number.MAX_VALUE); expect(randomFloat).toBeGreaterThanOrEqual(-Number.MAX_VALUE);