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);
type: 'sqlite',
clientUrl: `file://${join(
dirname(fileURLToPath(import.meta.url)),
- `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`
+ `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`,
)}`,
};
"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",
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
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
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:
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
}
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);
...args: any[]
) => Promise<void>,
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`);
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) {
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;
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;
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;
) {
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;
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);
this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
.maxDelayBetweenTwoTransactions,
this.chargingStation.getAutomaticTransactionGeneratorConfiguration()
- .minDelayBetweenTwoTransactions
+ .minDelayBetweenTwoTransactions,
) * 1000;
logger.info(`${this.logPrefix(connectorId)} waiting for ${formatDurationMilliSeconds(wait)}`);
await sleep(wait);
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);
}
.get(connectorId)
?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus
.get(connectorId)
- ?.skippedTransactions?.toString()} transaction(s)`
+ ?.skippedTransactions?.toString()} transaction(s)`,
);
}
this.connectorsStatus.get(connectorId).lastRunDate = new Date();
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),
);
}
this.chargingStation.getAutomaticTransactionGeneratorConfiguration().stopAfterHours *
3600 *
1000 -
- previousRunDuration
+ previousRunDuration,
);
this.connectorsStatus.get(connectorId).start = true;
}
private getConnectorStatus(connectorId: number): Status {
const connectorStatus = cloneObject(
- this.chargingStation.getAutomaticTransactionGeneratorStatuses()
+ this.chargingStation.getAutomaticTransactionGeneratorStatuses(),
)[connectorId];
delete connectorStatus?.startDate;
delete connectorStatus?.lastRunDate;
}
private async startTransaction(
- connectorId: number
+ connectorId: number,
): Promise<StartTransactionResponse | undefined> {
const measureId = 'StartTransaction with ATG';
const beginId = PerformanceStatistics.beginMeasure(measureId);
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;
private async stopTransaction(
connectorId: number,
- reason: StopTransactionReason = StopTransactionReason.LOCAL
+ reason: StopTransactionReason = StopTransactionReason.LOCAL,
): Promise<StopTransactionResponse> {
const measureId = 'StopTransaction with ATG';
const beginId = PerformanceStatistics.beginMeasure(measureId);
logger.warn(
`${this.logPrefix(connectorId)} stopping a not started transaction${
!isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : ''
- }`
+ }`,
);
}
PerformanceStatistics.endMeasure(measureId, beginId);
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) {
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()));
(this.storage = StorageFactory.getStorage(
Configuration.getPerformanceStorage().type,
Configuration.getPerformanceStorage().uri,
- this.logPrefix()
+ this.logPrefix(),
));
Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
}
} 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,
);
}
}
!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;
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<string>((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);
workerChoiceStrategy: Configuration.getWorker().poolStrategy,
messageHandler: this.messageHandler.bind(this) as (message: unknown) => void,
},
- }
+ },
));
}
private messageHandler(
- msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
+ msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>,
): void {
// logger.debug(
// `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
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) {
`${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
msg.id
}' event:`,
- error
+ error,
);
}
}
data.stationInfo.chargingStationId
} (hashId: ${data.stationInfo.hashId}) started (${
this.numberOfStartedChargingStations
- } started from ${this.numberOfChargingStations})`
+ } started from ${this.numberOfChargingStations})`,
);
};
data.stationInfo.chargingStationId
} (hashId: ${data.stationInfo.hashId}) stopped (${
this.numberOfStartedChargingStations
- } started from ${this.numberOfChargingStations})`
+ } started from ${this.numberOfChargingStations})`,
);
};
}
} 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);
}
private async startChargingStation(
index: number,
- stationTemplateUrl: StationTemplateUrl
+ stationTemplateUrl: StationTemplateUrl,
): Promise<void> {
await this.workerImplementation?.addElement({
index,
dirname(fileURLToPath(import.meta.url)),
'assets',
'station-templates',
- stationTemplateUrl.file
+ stationTemplateUrl.file,
),
});
}
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}`,
);
}
? this?.stationInfo?.chargingStationId
: getChargingStationId(this.index, this.getTemplateFromFile())) ??
'Error at building log prefix'
- } |`
+ } |`,
);
};
const defaultVoltageOut = getDefaultVoltageOut(
this.getCurrentOutType(stationInfo),
this.logPrefix(),
- this.templateFile
+ this.templateFile,
);
return (stationInfo ?? this.stationInfo).voltageOut ?? defaultVoltageOut;
}
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;
isNaN(connectorAmperageLimitationPowerLimit)
? Infinity
: connectorAmperageLimitationPowerLimit,
- isNaN(connectorChargingProfilesPowerLimit) ? Infinity : connectorChargingProfilesPowerLimit
+ isNaN(connectorChargingProfilesPowerLimit) ? Infinity : connectorChargingProfilesPowerLimit,
);
}
public getEnergyActiveImportRegisterByTransactionId(
transactionId: number,
- rounded = false
+ rounded = false,
): number {
return this.getEnergyActiveImportRegister(
this.getConnectorStatus(this.getConnectorIdByTransactionId(transactionId)),
- rounded
+ rounded,
);
}
public getAuthorizeRemoteTxRequests(): boolean {
const authorizeRemoteTxRequests = ChargingStationConfigurationUtils.getConfigurationKey(
this,
- StandardParametersKey.AuthorizeRemoteTxRequests
+ StandardParametersKey.AuthorizeRemoteTxRequests,
);
return authorizeRemoteTxRequests ? convertToBoolean(authorizeRemoteTxRequests.value) : false;
}
public getLocalAuthListEnabled(): boolean {
const localAuthListEnabled = ChargingStationConfigurationUtils.getConfigurationKey(
this,
- StandardParametersKey.LocalAuthListEnabled
+ StandardParametersKey.LocalAuthListEnabled,
);
return localAuthListEnabled ? convertToBoolean(localAuthListEnabled.value) : false;
}
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;
logger.warn(
`${this.logPrefix()} Heartbeat interval configuration key not set, using default value: ${
Constants.DEFAULT_HEARTBEAT_INTERVAL
- }`
+ }`,
);
return Constants.DEFAULT_HEARTBEAT_INTERVAL;
}
ChargingStationConfigurationUtils.setConfigurationKeyValue(
this,
this.getSupervisionUrlOcppKey(),
- url
+ url,
);
} else {
this.stationInfo.supervisionUrls = url;
.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`,
);
}
}
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 (
) {
logger.error(
`${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId}
- with no transaction id`
+ with no transaction id`,
);
return;
}
this,
connectorId,
this.getConnectorStatus(connectorId).transactionId,
- interval
+ interval,
);
this.ocppRequestService
.requestHandler<MeterValuesRequest, MeterValuesResponse>(
connectorId,
transactionId: this.getConnectorStatus(connectorId)?.transactionId,
meterValue: [meterValue],
- }
+ },
)
.catch((error) => {
logger.error(
`${this.logPrefix()} Error while sending '${RequestCommand.METER_VALUES}':`,
- error
+ error,
);
});
}, interval);
logger.error(
`${this.logPrefix()} Charging station ${
StandardParametersKey.MeterValueSampleInterval
- } configuration set to ${interval}, not sending MeterValues`
+ } configuration set to ${interval}, not sending MeterValues`,
);
}
}
logger.debug(
`${this.logPrefix()} ${FileType.ChargingStationTemplate} ${
this.templateFile
- } file have changed, reload`
+ } file have changed, reload`,
);
this.sharedLRUCache.deleteChargingStationTemplate(this.templateFileHash);
// Initialize
} catch (error) {
logger.error(
`${this.logPrefix()} ${FileType.ChargingStationTemplate} file monitoring error:`,
- error
+ error,
);
}
}
- }
+ },
);
this.started = true;
parentPort?.postMessage(buildStartedMessage(this));
public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean | undefined {
return ChargingStationConfigurationUtils.getConfigurationKey(
this,
- StandardParametersKey.SupportedFeatureProfiles
+ StandardParametersKey.SupportedFeatureProfiles,
)?.value?.includes(featureProfile);
}
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;
}
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);
public async stopTransactionOnConnector(
connectorId: number,
- reason = StopTransactionReason.NONE
+ reason = StopTransactionReason.NONE,
): Promise<StopTransactionResponse> {
const transactionId = this.getConnectorStatus(connectorId)?.transactionId;
if (
const transactionEndMeterValue = OCPP16ServiceUtils.buildTransactionEndMeterValue(
this,
connectorId,
- this.getEnergyActiveImportRegisterByTransactionId(transactionId)
+ this.getEnergyActiveImportRegisterByTransactionId(transactionId),
);
await this.ocppRequestService.requestHandler<MeterValuesRequest, MeterValuesResponse>(
this,
connectorId,
transactionId,
meterValue: [transactionEndMeterValue],
- }
+ },
);
}
return this.ocppRequestService.requestHandler<StopTransactionRequest, StopTransactionResponse>(
transactionId,
meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId, true),
reason,
- }
+ },
);
}
return convertToBoolean(
ChargingStationConfigurationUtils.getConfigurationKey(
this,
- StandardParametersKey.ReserveConnectorZeroSupported
- ).value
+ StandardParametersKey.ReserveConnectorZeroSupported,
+ ).value,
);
}
reservation.connectorId,
ConnectorStatusEnum.Reserved,
null,
- { send: reservation.connectorId !== 0 }
+ { send: reservation.connectorId !== 0 },
);
}
public async removeReservation(
reservation: Reservation,
- reason?: ReservationTerminationReason
+ reason?: ReservationTerminationReason,
): Promise<void> {
const connector = this.getConnectorStatus(reservation.connectorId);
switch (reason) {
reservation.connectorId,
ConnectorStatusEnum.Available,
null,
- { send: reservation.connectorId !== 0 }
+ { send: reservation.connectorId !== 0 },
);
delete connector.reservation;
break;
public getReservationBy(
filterKey: ReservationFilterKey,
- value: number | string
+ value: number | string,
): Reservation | undefined {
if (this.hasEvses) {
for (const evseStatus of this.evses.values()) {
public doesReservationExists(reservation: Partial<Reservation>): [boolean, Reservation] {
const foundReservation = this.getReservationBy(
ReservationFilterKey.RESERVATION_ID,
- reservation?.id
+ reservation?.id,
);
return isUndefined(foundReservation) ? [false, null] : [true, foundReservation];
}
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<void> => {
if (connectorStatus?.reservation?.expiryDate < now) {
await this.removeReservation(
connectorStatus.reservation,
- ReservationTerminationReason.EXPIRED
+ ReservationTerminationReason.EXPIRED,
);
}
}
if (connectorStatus?.reservation?.expiryDate < now) {
await this.removeReservation(
connectorStatus.reservation,
- ReservationTerminationReason.EXPIRED
+ ReservationTerminationReason.EXPIRED,
);
}
}
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;
isRequest && PerformanceStatistics.endMeasure(commandName, beginId);
logger.debug(
`${this.logPrefix()} >> Buffered ${OCPPServiceUtils.getMessageTypeString(
- messageType
- )} payload sent: ${message}`
+ messageType,
+ )} payload sent: ${message}`,
);
this.messageBuffer.delete(message);
}
this.templateFile,
FileType.ChargingStationTemplate,
error as NodeJS.ErrnoException,
- this.logPrefix()
+ this.logPrefix(),
);
}
return template;
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<FirmwareUpgrade>(
},
reset: true,
},
- stationTemplate?.firmwareUpgrade ?? {}
+ stationTemplate?.firmwareUpgrade ?? {},
);
stationInfo.resetTime = !isNullOrUndefined(stationTemplate?.resetTime)
? stationTemplate.resetTime * 1000
propagateSerialNumber(
this.getTemplateFromFile(),
stationInfoFromFile,
- stationInfoFromTemplate
+ stationInfoFromTemplate,
);
return stationInfoFromTemplate;
}
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 (
this.performanceStatistics = PerformanceStatistics.getInstance(
this.stationInfo.hashId,
this.stationInfo.chargingStationId,
- this.configuredSupervisionUrl
+ this.configuredSupervisionUrl,
);
}
this.bootNotificationRequest = createBootNotificationRequest(this.stationInfo);
this.ocppIncomingRequestService =
OCPP16IncomingRequestService.getInstance<OCPP16IncomingRequestService>();
this.ocppRequestService = OCPP16RequestService.getInstance<OCPP16RequestService>(
- OCPP16ResponseService.getInstance<OCPP16ResponseService>()
+ OCPP16ResponseService.getInstance<OCPP16ResponseService>(),
);
break;
case OCPPVersion.VERSION_20:
this.ocppIncomingRequestService =
OCPP20IncomingRequestService.getInstance<OCPP20IncomingRequestService>();
this.ocppRequestService = OCPP20RequestService.getInstance<OCPP20RequestService>(
- OCPP20ResponseService.getInstance<OCPP20ResponseService>()
+ OCPP20ResponseService.getInstance<OCPP20ResponseService>(),
);
break;
default:
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 (
this,
this.getSupervisionUrlOcppKey(),
this.configuredSupervisionUrl.href,
- { reboot: true }
+ { reboot: true },
);
} else if (
!this.getSupervisionUrlOcppConfiguration() &&
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(
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(
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[] = [];
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();
evseStatusConfiguration.connectorsStatus.map((connectorStatus, connectorId) => [
connectorId,
connectorStatus,
- ])
+ ]),
),
});
}
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) {
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 =
templateConnectorId,
connectorStatus,
this.logPrefix(),
- this.templateFile
+ this.templateFile,
);
this.connectors.set(connectorId, cloneObject<ConnectorStatus>(connectorStatus));
}
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`,
);
}
}
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`,
);
}
}
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) {
connectors: buildConnectorsMap(
stationTemplate?.Evses[evse]?.Connectors,
this.logPrefix(),
- this.templateFile
+ this.templateFile,
),
availability: AvailabilityType.Operative,
});
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`,
);
}
}
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`,
);
}
}
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);
this.configurationFile,
FileType.ChargingStationConfiguration,
error as NodeJS.ErrnoException,
- this.logPrefix()
+ this.logPrefix(),
);
}
}
}
configurationData = merge<ChargingStationConfiguration>(
configurationData,
- buildChargingStationAutomaticTransactionGeneratorConfiguration(this)
+ buildChargingStationAutomaticTransactionGeneratorConfiguration(this),
);
if (
!this.getAutomaticTransactionGeneratorPersistentConfiguration() ||
stationInfo: configurationData.stationInfo,
configurationKey: configurationData.configurationKey,
automaticTransactionGenerator: configurationData.automaticTransactionGenerator,
- } as ChargingStationConfiguration)
+ } as ChargingStationConfiguration),
)
.digest('hex');
if (this.configurationFileHash !== configurationHash) {
this.configurationFile,
FileType.ChargingStationConfiguration,
error as NodeJS.ErrnoException,
- this.logPrefix()
+ this.logPrefix(),
);
})
.finally(() => {
logger.debug(
`${this.logPrefix()} Not saving unchanged charging station configuration file ${
this.configurationFile
- }`
+ }`,
);
}
} catch (error) {
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`,
);
}
}
private async onOpen(): Promise<void> {
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
await sleep(
this?.bootNotificationResponse?.interval
? this.bootNotificationResponse.interval * 1000
- : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL
+ : Constants.DEFAULT_BOOT_NOTIFICATION_INTERVAL,
);
}
} while (
}
} 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;
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`,
);
}
}
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;
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;
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,
);
}
}
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,
);
}
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);
}
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));
}
`${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(
? ` matching cached request '${JSON.stringify(this.requests.get(messageId))}'`
: ''
} processing error:`,
- error
+ error,
);
}
}
if (
ChargingStationConfigurationUtils.getConfigurationKey(
this,
- StandardParametersKey.ConnectionTimeOut
+ StandardParametersKey.ConnectionTimeOut,
)
) {
return (
parseInt(
ChargingStationConfigurationUtils.getConfigurationKey(
this,
- StandardParametersKey.ConnectionTimeOut
- ).value
+ StandardParametersKey.ConnectionTimeOut,
+ ).value,
) ?? Constants.DEFAULT_CONNECTION_TIMEOUT
);
}
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));
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)
);
}
this,
connectorId,
connectorBootStatus,
- evseId
+ evseId,
);
}
}
const connectorBootStatus = getBootConnectorStatus(
this,
connectorId,
- this.getConnectorStatus(connectorId)
+ this.getConnectorStatus(connectorId),
);
await OCPPServiceUtils.sendAndSetConnectorStatus(this, connectorId, connectorBootStatus);
}
}
private async stopMessageSequence(
- reason: StopTransactionReason = StopTransactionReason.NONE
+ reason: StopTransactionReason = StopTransactionReason.NONE,
): Promise<void> {
// Stop WebSocket ping
this.stopWebSocketPing();
this,
connectorId,
ConnectorStatusEnum.Unavailable,
- evseId
- )
+ evseId,
+ ),
);
delete connectorStatus?.status;
}
OCPPServiceUtils.buildStatusNotificationRequest(
this,
connectorId,
- ConnectorStatusEnum.Unavailable
- )
+ ConnectorStatusEnum.Unavailable,
+ ),
);
delete this.getConnectorStatus(connectorId)?.status;
}
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) {
}, 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`,
);
}
}
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;
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()})`,
);
}
}
public static getConfigurationKey(
chargingStation: ChargingStation,
key: ConfigurationKeyType,
- caseInsensitive = false
+ caseInsensitive = false,
): ConfigurationKey | undefined {
return chargingStation.ocppConfiguration?.configurationKey?.find((configElement) => {
if (caseInsensitive) {
visible: true,
reboot: false,
},
- params: AddConfigurationKeyParams = { overwrite: false, save: false }
+ params: AddConfigurationKeyParams = { overwrite: false, save: false },
): void {
options = {
...{
} else {
logger.error(
`${chargingStation.logPrefix()} Trying to add an already existing configuration key: %j`,
- keyFound
+ keyFound,
);
}
}
chargingStation: ChargingStation,
key: ConfigurationKeyType,
value: string,
- caseInsensitive = false
+ caseInsensitive = false,
): void {
const keyFound = ChargingStationConfigurationUtils.getConfigurationKey(
chargingStation,
key,
- caseInsensitive
+ caseInsensitive,
);
if (keyFound) {
chargingStation.ocppConfiguration.configurationKey[
} else {
logger.error(
`${chargingStation.logPrefix()} Trying to set a value on a non existing configuration key: %j`,
- { key, value }
+ { key, value },
);
}
}
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;
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;
return stationTemplate?.fixedName
? stationTemplate.baseName
: `${stationTemplate.baseName}-${instanceIndex.toString()}${idStr.substring(
- idStr.length - 4
+ idStr.length - 4,
)}${idSuffix}`;
};
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`);
export const getPhaseRotationValue = (
connectorId: number,
- numberOfPhases: number
+ numberOfPhases: number,
): string | undefined => {
// AC/DC
if (connectorId === 0 && numberOfPhases === 0) {
export const getBootConnectorStatus = (
chargingStation: ChargingStation,
connectorId: number,
- connectorStatus: ConnectorStatus
+ connectorStatus: ConnectorStatus,
): ConnectorStatusEnum => {
let connectorBootStatus: ConnectorStatusEnum;
if (
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}`;
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`,
);
}
};
export const checkConnectorsConfiguration = (
stationTemplate: ChargingStationTemplate,
logPrefix: string,
- templateFile: string
+ templateFile: string,
): {
configuredMaxConnectors: number;
templateMaxConnectors: number;
!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;
}
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;
}
export const buildConnectorsMap = (
connectors: Record<string, ConnectorStatus>,
logPrefix: string,
- templateFile: string
+ templateFile: string,
): Map<number, ConnectorStatus> => {
const connectorsMap = new Map<number, ConnectorStatus>();
if (getMaxNumberOfConnectors(connectors) > 0) {
}
} 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;
export const initializeConnectorsMapStatus = (
connectors: Map<number, ConnectorStatus>,
- 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) {
export const createBootNotificationRequest = (
stationInfo: ChargingStationInfo,
- bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp
+ bootReason: BootReasonEnumType = BootReasonEnumType.PowerUp,
): BootNotificationRequest => {
const ocppVersion = stationInfo.ocppVersion ?? OCPPVersion.VERSION_16;
switch (ocppVersion) {
export const warnTemplateKeysDeprecation = (
stationTemplate: ChargingStationTemplate,
logPrefix: string,
- templateFile: string
+ templateFile: string,
) => {
const templateKeys: { key: string; deprecatedKey: string }[] = [
{ key: 'supervisionUrls', deprecatedKey: 'supervisionUrl' },
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<ChargingStationTemplate>(stationTemplate);
delete stationTemplate.power;
} = {
randomSerialNumberUpperCase: true,
randomSerialNumber: true,
- }
+ },
): void => {
params = { ...{ randomSerialNumberUpperCase: true, randomSerialNumber: true }, ...params };
const serialNumberSuffix = params?.randomSerialNumber
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
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<ChargingProfile[]>(
- 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<ChargingProfile[]>(
- 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)) {
: ACElectricUtils.powerTotal(
chargingStation.getNumberOfPhases(),
chargingStation.getVoltageOut(),
- limit
+ limit,
);
break;
case CurrentType.DC:
`${chargingStation.logPrefix()} Charging profile id ${
matchingChargingProfile.chargingProfileId
} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
- result
+ result,
);
limit = connectorMaximumPower;
}
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;
export const waitChargingStationEvents = async (
emitter: EventEmitter,
event: ChargingStationWorkerMessageEvents,
- eventsToWait: number
+ eventsToWait: number,
): Promise<number> => {
return new Promise((resolve) => {
let events = 0;
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`,
);
}
};
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`,
);
}
};
key: string,
logPrefix: string,
templateFile: string,
- logMsgToAppend = ''
+ logMsgToAppend = '',
): void => {
if (!isUndefined(template[key])) {
const logMsg = `Deprecated template key '${key}' usage in file '${templateFile}'${
const convertDeprecatedTemplateKey = (
template: ChargingStationTemplate,
deprecatedKey: string,
- key: string
+ key: string,
): void => {
if (!isUndefined(template[deprecatedKey])) {
template[key] = template[deprecatedKey] as unknown;
*/
const getLimitFromChargingProfiles = (
chargingProfiles: ChargingProfile[],
- logPrefix: string
+ logPrefix: string,
): {
limit: number;
matchingChargingProfile: ChargingProfile;
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
) {
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)) {
this.runInAsyncScope(
startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void,
this,
- message.data
+ message.data,
);
}
});
public getIdTag(
distribution: IdTagDistribution,
chargingStation: ChargingStation,
- connectorId: number
+ connectorId: number,
): string {
const hashId = chargingStation.stationInfo.hashId;
const idTagsFile = getIdTagsFile(chargingStation.stationInfo);
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)];
}
const idTag = idTags[idTagIndex];
this.idTagsCachesAddressableIndexes.set(
addressableKey,
- idTagIndex === idTags.length - 1 ? 0 : idTagIndex + 1
+ idTagIndex === idTags.length - 1 ? 0 : idTagIndex + 1,
);
return idTag;
}
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)];
}
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);
this.logPrefix(file),
{
throwError: false,
- }
+ },
);
}
}
- }
+ },
),
});
}
file,
FileType.Authorization,
error as NodeJS.ErrnoException,
- this.logPrefix(file)
+ this.logPrefix(file),
);
}
}
private constructor() {
this.lruCache = new LRUCache<string, CacheValueType>(
Bootstrap.getInstance().numberOfChargingStationTemplates +
- Bootstrap.getInstance().numberOfChargingStations
+ Bootstrap.getInstance().numberOfChargingStations,
);
}
}
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;
}
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;
}
}
private isChargingStationConfigurationCacheable(
- chargingStationConfiguration: ChargingStationConfiguration
+ chargingStationConfiguration: ChargingStationConfiguration,
): boolean {
return (
isNullOrUndefined(chargingStationConfiguration?.configurationKey) === false &&
| FirmwareStatusNotificationResponse;
type CommandHandler = (
- requestPayload?: BroadcastChannelRequestPayload
+ requestPayload?: BroadcastChannelRequestPayload,
) => Promise<CommandResponse | void> | void;
export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChannel {
{
meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId(
requestPayload.transactionId,
- true
+ true,
),
...requestPayload,
},
- requestParams
+ requestParams,
),
],
[
{
skipBufferingOnError: true,
throwError: true,
- }
+ },
);
return this.chargingStation.bootNotificationResponse;
},
this.chargingStation,
RequestCommand.STATUS_NOTIFICATION,
requestPayload,
- requestParams
+ requestParams,
),
],
[
const configuredMeterValueSampleInterval =
ChargingStationConfigurationUtils.getConfigurationKey(
chargingStation,
- StandardParametersKey.MeterValueSampleInterval
+ StandardParametersKey.MeterValueSampleInterval,
);
return this.chargingStation.ocppRequestService.requestHandler<
MeterValuesRequest,
?.transactionId,
configuredMeterValueSampleInterval
? convertToInt(configuredMeterValueSampleInterval.value) * 1000
- : Constants.DEFAULT_METER_VALUES_INTERVAL
+ : Constants.DEFAULT_METER_VALUES_INTERVAL,
),
],
...requestPayload,
},
- requestParams
+ requestParams,
);
},
],
this.chargingStation,
RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
requestPayload,
- requestParams
+ requestParams,
),
],
[
this.chargingStation,
RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
requestPayload,
- requestParams
+ requestParams,
),
],
]);
}
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;
}
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,
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<CommandResponse | void> {
if (this.commandHandlers.has(command) === true) {
this.cleanRequestPayload(command, requestPayload);
private cleanRequestPayload(
command: BroadcastChannelProcedureName,
- requestPayload: BroadcastChannelRequestPayload
+ requestPayload: BroadcastChannelRequestPayload,
): void {
delete requestPayload.hashId;
delete requestPayload.hashIds;
private commandResponseToResponsePayload(
command: BroadcastChannelProcedureName,
requestPayload: BroadcastChannelRequestPayload,
- commandResponse: CommandResponse
+ commandResponse: CommandResponse,
): BroadcastChannelResponsePayload {
const responseStatus = this.commandResponseToResponseStatus(command, commandResponse);
if (responseStatus === ResponseStatus.SUCCESS) {
private commandResponseToResponseStatus(
command: BroadcastChannelProcedureName,
- commandResponse: CommandResponse
+ commandResponse: CommandResponse,
): ResponseStatus {
switch (command) {
case BroadcastChannelProcedureName.START_TRANSACTION:
private messageErrorHandler(messageEvent: MessageEvent): void {
logger.error(
`${this.uiService.logPrefix(moduleName, 'messageErrorHandler')} Error at handling message:`,
- messageEvent
+ messageEvent,
);
}
}
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;
}
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;
}
OCPP16ServiceUtils.parseJsonSchemaFile<ResetRequest>(
'assets/json-schemas/ocpp/1.6/Reset.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ClearCacheRequest>(
'assets/json-schemas/ocpp/1.6/ClearCache.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<UnlockConnectorRequest>(
'assets/json-schemas/ocpp/1.6/UnlockConnector.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GetConfigurationRequest>(
'assets/json-schemas/ocpp/1.6/GetConfiguration.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<ChangeConfigurationRequest>(
'assets/json-schemas/ocpp/1.6/ChangeConfiguration.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GetDiagnosticsRequest>(
'assets/json-schemas/ocpp/1.6/GetDiagnostics.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16GetCompositeScheduleRequest>(
'assets/json-schemas/ocpp/1.6/GetCompositeSchedule.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<SetChargingProfileRequest>(
'assets/json-schemas/ocpp/1.6/SetChargingProfile.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<ClearChargingProfileRequest>(
'assets/json-schemas/ocpp/1.6/ClearChargingProfile.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<ChangeAvailabilityRequest>(
'assets/json-schemas/ocpp/1.6/ChangeAvailability.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<RemoteStartTransactionRequest>(
'assets/json-schemas/ocpp/1.6/RemoteStartTransaction.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<RemoteStopTransactionRequest>(
'assets/json-schemas/ocpp/1.6/RemoteStopTransaction.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16TriggerMessageRequest>(
'assets/json-schemas/ocpp/1.6/TriggerMessage.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferRequest>(
'assets/json-schemas/ocpp/1.6/DataTransfer.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16UpdateFirmwareRequest>(
'assets/json-schemas/ocpp/1.6/UpdateFirmware.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ReserveNowRequest>(
'assets/json-schemas/ocpp/1.6/ReserveNow.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16CancelReservationRequest>(
'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;
}
chargingStation: ChargingStation,
messageId: string,
commandName: OCPP16IncomingRequestCommand,
- commandPayload: JsonType
+ commandPayload: JsonType,
): Promise<void> {
let response: JsonType;
if (
`${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 (
// 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;
}
`${commandName} is not implemented to handle request PDU ${JSON.stringify(
commandPayload,
null,
- 2
+ 2,
)}`,
commandName,
- commandPayload
+ commandPayload,
);
}
} else {
`${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
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;
}
// Simulate charging station restart
private handleRequestReset(
chargingStation: ChargingStation,
- commandPayload: ResetRequest
+ commandPayload: ResetRequest,
): GenericResponse {
this.runInAsyncScope(
chargingStation.reset.bind(chargingStation) as (
...args: any[]
) => Promise<void>,
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<UnlockConnectorResponse> {
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;
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[] = [];
const keyFound = ChargingStationConfigurationUtils.getConfigurationKey(
chargingStation,
key,
- true
+ true,
);
if (keyFound) {
if (isUndefined(keyFound.visible) === true) {
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;
chargingStation,
commandPayload.key,
commandPayload.value,
- true
+ true,
);
valueChanged = true;
}
ChargingStationConfigurationUtils.setConfigurationKeyValue(
chargingStation,
OCPP16StandardParametersKey.HeartbeatInterval,
- commandPayload.value
+ commandPayload.value,
);
triggerHeartbeatRestart = true;
}
ChargingStationConfigurationUtils.setConfigurationKeyValue(
chargingStation,
OCPP16StandardParametersKey.HeartBeatInterval,
- commandPayload.value
+ commandPayload.value,
);
triggerHeartbeatRestart = true;
}
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;
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;
}
) {
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;
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;
}
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;
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;
}
connectorStatus?.chargingProfiles?.splice(index, 1);
logger.debug(
`${chargingStation.logPrefix()} Matching charging profile(s) cleared: %j`,
- chargingProfile
+ chargingProfile,
);
clearedCP = true;
}
- }
+ },
);
}
};
private async handleRequestChangeAvailability(
chargingStation: ChargingStation,
- commandPayload: ChangeAvailabilityRequest
+ commandPayload: ChangeAvailabilityRequest,
): Promise<ChangeAvailabilityResponse> {
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;
}
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
id,
- chargePointStatus
+ chargePointStatus,
);
}
};
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
connectorId,
- chargePointStatus
+ chargePointStatus,
);
return OCPP16Constants.OCPP_AVAILABILITY_RESPONSE_ACCEPTED;
}
private async handleRequestRemoteStartTransaction(
chargingStation: ChargingStation,
- commandPayload: RemoteStartTransactionRequest
+ commandPayload: RemoteStartTransactionRequest,
): Promise<GenericResponse> {
const { connectorId: transactionConnectorId, idTag, chargingProfile } = commandPayload;
const reserved =
return this.notifyRemoteStartTransactionRejected(
chargingStation,
transactionConnectorId,
- idTag
+ idTag,
);
}
if (
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
this.setRemoteStartTransactionChargingProfile(
chargingStation,
transactionConnectorId,
- chargingProfile
+ chargingProfile,
) === true
) {
connectorStatus.transactionRemoteStarted = true;
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 (
return this.notifyRemoteStartTransactionRejected(
chargingStation,
transactionConnectorId,
- idTag
+ idTag,
);
}
return this.notifyRemoteStartTransactionRejected(
chargingStation,
transactionConnectorId,
- idTag
+ idTag,
);
}
// No authorization check required, start transaction
this.setRemoteStartTransactionChargingProfile(
chargingStation,
transactionConnectorId,
- chargingProfile
+ chargingProfile,
) === true
) {
connectorStatus.transactionRemoteStarted = true;
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<GenericResponse> {
if (
chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.Available
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;
}
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) {
private async handleRequestRemoteStopTransaction(
chargingStation: ChargingStation,
- commandPayload: RemoteStopTransactionRequest
+ commandPayload: RemoteStopTransactionRequest,
): Promise<GenericResponse> {
const transactionId = commandPayload.transactionId;
const remoteStopTransaction = async (connectorId: number): Promise<GenericResponse> => {
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;
}
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;
}
) {
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;
}
...args: any[]
) => Promise<void>,
this,
- chargingStation
+ chargingStation,
).catch(Constants.EMPTY_FUNCTION);
} else {
- setTimeout(() => {
- this.runInAsyncScope(
- this.updateFirmwareSimulation.bind(this) as (
- this: OCPP16IncomingRequestService,
- ...args: any[]
- ) => Promise<void>,
- this,
- chargingStation
- ).catch(Constants.EMPTY_FUNCTION);
- }, retrieveDate?.getTime() - now);
+ setTimeout(
+ () => {
+ this.runInAsyncScope(
+ this.updateFirmwareSimulation.bind(this) as (
+ this: OCPP16IncomingRequestService,
+ ...args: any[]
+ ) => Promise<void>,
+ this,
+ chargingStation,
+ ).catch(Constants.EMPTY_FUNCTION);
+ },
+ retrieveDate?.getTime() - now,
+ );
}
return OCPP16Constants.OCPP_RESPONSE_EMPTY;
}
private async updateFirmwareSimulation(
chargingStation: ChargingStation,
maxDelay = 30,
- minDelay = 15
+ minDelay = 15,
): Promise<void> {
if (checkChargingStation(chargingStation, chargingStation.logPrefix()) === false) {
return;
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
connectorId,
- OCPP16ChargePointStatus.Unavailable
+ OCPP16ChargePointStatus.Unavailable,
);
}
}
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
connectorId,
- OCPP16ChargePointStatus.Unavailable
+ OCPP16ChargePointStatus.Unavailable,
);
}
}
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;
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
connectorId,
- OCPP16ChargePointStatus.Unavailable
+ OCPP16ChargePointStatus.Unavailable,
);
}
}
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
connectorId,
- OCPP16ChargePointStatus.Unavailable
+ OCPP16ChargePointStatus.Unavailable,
);
}
}
private async handleRequestGetDiagnostics(
chargingStation: ChargingStation,
- commandPayload: GetDiagnosticsRequest
+ commandPayload: GetDiagnosticsRequest,
): Promise<GetDiagnosticsResponse> {
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;
}
logger.info(
`${chargingStation.logPrefix()} ${
info.bytes / 1024
- } bytes transferred from diagnostics archive ${info.name}`
+ } bytes transferred from diagnostics archive ${info.name}`,
);
chargingStation.ocppRequestService
.requestHandler<
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<
`Diagnostics transfer failed with error code ${accessResponse.code.toString()}${
uploadResponse?.code && `|${uploadResponse?.code.toString()}`
}`,
- OCPP16IncomingRequestCommand.GET_DIAGNOSTICS
+ OCPP16IncomingRequestCommand.GET_DIAGNOSTICS,
);
}
throw new OCPPError(
`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<
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,
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;
!OCPP16ServiceUtils.isConnectorIdValid(
chargingStation,
OCPP16IncomingRequestCommand.TRIGGER_MESSAGE,
- commandPayload.connectorId
+ commandPayload.connectorId,
)
) {
return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_REJECTED;
chargingStation,
OCPP16RequestCommand.BOOT_NOTIFICATION,
chargingStation.bootNotificationRequest,
- { skipBufferingOnError: true, triggerMessage: true }
+ { skipBufferingOnError: true, triggerMessage: true },
)
.then((response) => {
chargingStation.bootNotificationResponse = response;
null,
{
triggerMessage: true,
- }
+ },
)
.catch(Constants.EMPTY_FUNCTION);
}, OCPP16Constants.OCPP_TRIGGER_MESSAGE_DELAY);
},
{
triggerMessage: true,
- }
+ },
)
.catch(Constants.EMPTY_FUNCTION);
} else {
},
{
triggerMessage: true,
- }
+ },
)
.catch(Constants.EMPTY_FUNCTION);
}
},
{
triggerMessage: true,
- }
+ },
)
.catch(Constants.EMPTY_FUNCTION);
}
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)) {
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<OCPP16ReserveNowResponse> {
if (
!OCPP16ServiceUtils.checkFeatureProfile(
chargingStation,
OCPP16SupportedFeatureProfiles.Reservation,
- OCPP16IncomingRequestCommand.RESERVE_NOW
+ OCPP16IncomingRequestCommand.RESERVE_NOW,
)
) {
return OCPP16Constants.OCPP_RESERVATION_RESPONSE_REJECTED;
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<GenericResponse> {
if (
!OCPP16ServiceUtils.checkFeatureProfile(
chargingStation,
OCPP16SupportedFeatureProfiles.Reservation,
- OCPP16IncomingRequestCommand.CANCEL_RESERVATION
+ OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
)
) {
return OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED;
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) {
chargingStation,
OCPP16IncomingRequestCommand.CANCEL_RESERVATION,
error as Error,
- { errorResponse: OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED }
+ { errorResponse: OCPP16Constants.OCPP_CANCEL_RESERVATION_RESPONSE_REJECTED },
);
}
}
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16AuthorizeRequest>(
'assets/json-schemas/ocpp/1.6/Authorize.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16BootNotificationRequest>(
'assets/json-schemas/ocpp/1.6/BootNotification.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationRequest>(
'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotification.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16HeartbeatRequest>(
'assets/json-schemas/ocpp/1.6/Heartbeat.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16MeterValuesRequest>(
'assets/json-schemas/ocpp/1.6/MeterValues.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StatusNotificationRequest>(
'assets/json-schemas/ocpp/1.6/StatusNotification.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StartTransactionRequest>(
'assets/json-schemas/ocpp/1.6/StartTransaction.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StopTransactionRequest>(
'assets/json-schemas/ocpp/1.6/StopTransaction.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferRequest>(
'assets/json-schemas/ocpp/1.6/DataTransfer.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationRequest>(
'assets/json-schemas/ocpp/1.6/FirmwareStatusNotification.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
]);
this.buildRequestPayload = this.buildRequestPayload.bind(this) as <Request extends JsonType>(
chargingStation: ChargingStation,
commandName: OCPP16RequestCommand,
- commandParams?: JsonType
+ commandParams?: JsonType,
) => Request;
}
chargingStation: ChargingStation,
commandName: OCPP16RequestCommand,
commandParams?: JsonType,
- params?: RequestParams
+ params?: RequestParams,
): Promise<ResponseType> {
// FIXME?: add sanity checks on charging station availability, connector availability, connector status, etc.
if (OCPP16ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) {
generateUUID(),
this.buildRequestPayload<RequestType>(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().
ErrorType.NOT_SUPPORTED,
`Unsupported OCPP command '${commandName}'`,
commandName,
- commandParams
+ commandParams,
);
}
private buildRequestPayload<Request extends JsonType>(
chargingStation: ChargingStation,
commandName: OCPP16RequestCommand,
- commandParams?: JsonType
+ commandParams?: JsonType,
): Request {
let connectorId: number;
let energyActiveImportRegister: number;
idTag: Constants.DEFAULT_IDTAG,
meterStart: chargingStation.getEnergyActiveImportRegisterByConnectorId(
commandParams?.connectorId as number,
- true
+ true,
),
timestamp: new Date(),
...commandParams,
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),
OCPP16ServiceUtils.buildTransactionEndMeterValue(
chargingStation,
connectorId,
- energyActiveImportRegister
- )
+ energyActiveImportRegister,
+ ),
),
}),
...commandParams,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Unsupported OCPP command '${commandName}'`,
commandName,
- commandParams
+ commandParams,
);
}
}
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16BootNotificationResponse>(
'assets/json-schemas/ocpp/1.6/BootNotificationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16HeartbeatResponse>(
'assets/json-schemas/ocpp/1.6/HeartbeatResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16AuthorizeResponse>(
'assets/json-schemas/ocpp/1.6/AuthorizeResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StartTransactionResponse>(
'assets/json-schemas/ocpp/1.6/StartTransactionResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StopTransactionResponse>(
'assets/json-schemas/ocpp/1.6/StopTransactionResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16StatusNotificationResponse>(
'assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16MeterValuesResponse>(
'assets/json-schemas/ocpp/1.6/MeterValuesResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationResponse>(
'assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
'assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationResponse>(
'assets/json-schemas/ocpp/1.6/FirmwareStatusNotificationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
]);
OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
'assets/json-schemas/ocpp/1.6/ResetResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
'assets/json-schemas/ocpp/1.6/ClearCacheResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<ChangeAvailabilityResponse>(
'assets/json-schemas/ocpp/1.6/ChangeAvailabilityResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<UnlockConnectorResponse>(
'assets/json-schemas/ocpp/1.6/UnlockConnectorResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GetConfigurationResponse>(
'assets/json-schemas/ocpp/1.6/GetConfigurationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<ChangeConfigurationResponse>(
'assets/json-schemas/ocpp/1.6/ChangeConfigurationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16GetCompositeScheduleResponse>(
'assets/json-schemas/ocpp/1.6/GetCompositeScheduleResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<SetChargingProfileResponse>(
'assets/json-schemas/ocpp/1.6/SetChargingProfileResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<ClearChargingProfileResponse>(
'assets/json-schemas/ocpp/1.6/ClearChargingProfileResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
'assets/json-schemas/ocpp/1.6/RemoteStartTransactionResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
'assets/json-schemas/ocpp/1.6/RemoteStopTransactionResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GetDiagnosticsResponse>(
'assets/json-schemas/ocpp/1.6/GetDiagnosticsResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16TriggerMessageResponse>(
'assets/json-schemas/ocpp/1.6/TriggerMessageResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16DataTransferResponse>(
'assets/json-schemas/ocpp/1.6/DataTransferResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16UpdateFirmwareResponse>(
'assets/json-schemas/ocpp/1.6/UpdateFirmwareResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<OCPP16ReserveNowResponse>(
'assets/json-schemas/ocpp/1.6/ReserveNowResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP16ServiceUtils.parseJsonSchemaFile<GenericResponse>(
'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;
}
chargingStation: ChargingStation,
commandName: OCPP16RequestCommand,
payload: JsonType,
- requestPayload: JsonType
+ requestPayload: JsonType,
): Promise<void> {
if (
chargingStation.isRegistered() === true ||
} catch (error) {
logger.error(
`${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`,
- error
+ error,
);
throw error;
}
`${commandName} is not implemented to handle response PDU ${JSON.stringify(
payload,
null,
- 2
+ 2,
)}`,
commandName,
- payload
+ payload,
);
}
} else {
`${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,
);
}
}
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(
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);
}
} else {
logger.error(
`${chargingStation.logPrefix()} Charging station boot notification response received: %j with undefined registration status`,
- payload
+ payload,
);
}
}
private handleResponseAuthorize(
chargingStation: ChargingStation,
payload: OCPP16AuthorizeResponse,
- requestPayload: OCPP16AuthorizeRequest
+ requestPayload: OCPP16AuthorizeRequest,
): void {
let authorizeConnectorId: number;
if (chargingStation.hasEvses) {
logger.debug(
`${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' accepted${
authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''
- }`
+ }`,
);
} else {
if (authorizeConnectorIdDefined) {
logger.debug(
`${chargingStation.logPrefix()} idTag '${requestPayload.idTag}' rejected with status '${
payload.idTagInfo.status
- }'${authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''}`
+ }'${authorizeConnectorIdDefined ? ` on connector id ${authorizeConnectorId}` : ''}`,
);
}
}
private async handleResponseStartTransaction(
chargingStation: ChargingStation,
payload: OCPP16StartTransactionResponse,
- requestPayload: OCPP16StartTransactionRequest
+ requestPayload: OCPP16StartTransactionRequest,
): Promise<void> {
const transactionConnectorId = requestPayload.connectorId;
if (
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;
}
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;
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;
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;
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;
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;
}
) {
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;
}
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;
}
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);
}
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<
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;
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);
}
private async resetConnectorOnStartTransactionError(
chargingStation: ChargingStation,
- connectorId: number
+ connectorId: number,
): Promise<void> {
resetConnectorStatus(chargingStation.getConnectorStatus(connectorId));
chargingStation.stopMeterValues(connectorId);
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
connectorId,
- OCPP16ChargePointStatus.Available
+ OCPP16ChargePointStatus.Available,
);
}
}
private async handleResponseStopTransaction(
chargingStation: ChargingStation,
payload: OCPP16StopTransactionResponse,
- requestPayload: OCPP16StopTransactionRequest
+ requestPayload: OCPP16StopTransactionRequest,
): Promise<void> {
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;
}
OCPP16ServiceUtils.buildTransactionEndMeterValue(
chargingStation,
transactionConnectorId,
- requestPayload.meterStop
+ requestPayload.meterStop,
),
],
}));
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
transactionConnectorId,
- OCPP16ChargePointStatus.Unavailable
+ OCPP16ChargePointStatus.Unavailable,
);
} else {
await OCPP16ServiceUtils.sendAndSetConnectorStatus(
chargingStation,
transactionConnectorId,
- OCPP16ChargePointStatus.Available
+ OCPP16ChargePointStatus.Available,
);
}
if (chargingStation.stationInfo.powerSharedByConnectors) {
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;
}
connectorId: number,
transactionId: number,
interval: number,
- debug = false
+ debug = false,
): OCPP16MeterValue {
const meterValue: OCPP16MeterValue = {
timestamp: new Date(),
const socSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate(
chargingStation,
connectorId,
- OCPP16MeterValueMeasurand.STATE_OF_CHARGE
+ OCPP16MeterValueMeasurand.STATE_OF_CHARGE,
);
if (socSampledValueTemplate) {
const socMaximumValue = 100;
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 (
`${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}}`,
);
}
}
const voltageSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate(
chargingStation,
connectorId,
- OCPP16MeterValueMeasurand.VOLTAGE
+ OCPP16MeterValueMeasurand.VOLTAGE,
);
if (voltageSampledValueTemplate) {
const voltageSampledValueTemplateValue = voltageSampledValueTemplate.value
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 (
chargingStation,
connectorId,
OCPP16MeterValueMeasurand.VOLTAGE,
- phaseLineToNeutralValue as OCPP16MeterValuePhase
+ phaseLineToNeutralValue as OCPP16MeterValuePhase,
);
let voltagePhaseLineToNeutralMeasurandValue: number;
if (voltagePhaseLineToNeutralSampledValueTemplate) {
Constants.DEFAULT_FLUCTUATION_PERCENT;
voltagePhaseLineToNeutralMeasurandValue = getRandomFloatFluctuatedRounded(
voltagePhaseLineToNeutralSampledValueTemplateValue,
- fluctuationPhaseToNeutralPercent
+ fluctuationPhaseToNeutralPercent,
);
}
meterValue.sampledValue.push(
voltagePhaseLineToNeutralSampledValueTemplate ?? voltageSampledValueTemplate,
voltagePhaseLineToNeutralMeasurandValue ?? voltageMeasurandValue,
undefined,
- phaseLineToNeutralValue as OCPP16MeterValuePhase
- )
+ phaseLineToNeutralValue as OCPP16MeterValuePhase,
+ ),
);
if (chargingStation.getPhaseLineToLineVoltageMeterValues()) {
const phaseLineToLineValue = `L${phase}-L${
chargingStation,
connectorId,
OCPP16MeterValueMeasurand.VOLTAGE,
- phaseLineToLineValue as OCPP16MeterValuePhase
+ phaseLineToLineValue as OCPP16MeterValuePhase,
);
let voltagePhaseLineToLineMeasurandValue: number;
if (voltagePhaseLineToLineSampledValueTemplate) {
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,
+ ),
);
}
}
const powerSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate(
chargingStation,
connectorId,
- OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT
+ OCPP16MeterValueMeasurand.POWER_ACTIVE_IMPORT,
);
let powerPerPhaseSampledValueTemplates: MeasurandPerPhaseSampledValueTemplates = {};
if (chargingStation.getNumberOfPhases() === 3) {
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 ??
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:
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 &&
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 &&
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 &&
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
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:
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:
meterValue.sampledValue.push(
OCPP16ServiceUtils.buildSampledValue(
powerSampledValueTemplate,
- powerMeasurandValues.allPhases
- )
+ powerMeasurandValues.allPhases,
+ ),
);
const sampledValuesIndex = meterValue.sampledValue.length - 1;
const connectorMaximumPowerRounded = roundTo(connectorMaximumPower / unitDivider, 2);
`${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 (
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) >
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}`,
);
}
}
const currentSampledValueTemplate = OCPP16ServiceUtils.getSampledValueTemplate(
chargingStation,
connectorId,
- OCPP16MeterValueMeasurand.CURRENT_IMPORT
+ OCPP16MeterValueMeasurand.CURRENT_IMPORT,
);
let currentPerPhaseSampledValueTemplates: MeasurandPerPhaseSampledValueTemplates = {};
if (chargingStation.getNumberOfPhases() === 3) {
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 ??
connectorMaximumAmperage = ACElectricUtils.amperagePerPhaseFromPower(
chargingStation.getNumberOfPhases(),
connectorMaximumAvailablePower,
- chargingStation.getVoltageOut()
+ chargingStation.getVoltageOut(),
);
if (chargingStation.getNumberOfPhases() === 3) {
const defaultFluctuatedAmperagePerPhase =
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 &&
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 &&
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 &&
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 ??
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;
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;
meterValue.sampledValue.push(
OCPP16ServiceUtils.buildSampledValue(
currentSampledValueTemplate,
- currentMeasurandValues.allPhases
- )
+ currentMeasurandValues.allPhases,
+ ),
);
const sampledValuesIndex = meterValue.sampledValue.length - 1;
if (
`${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 (
currentSampledValueTemplate,
currentMeasurandValues[phaseValue] as number,
undefined,
- phaseValue as OCPP16MeterValuePhase
- )
+ phaseValue as OCPP16MeterValuePhase,
+ ),
);
const sampledValuesPerPhaseIndex = meterValue.sampledValue.length - 1;
if (
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}`,
);
}
}
// 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;
chargingStation.getConnectorMaximumAvailablePower(connectorId);
const connectorMaximumEnergyRounded = roundTo(
(connectorMaximumAvailablePower * interval) / (3600 * 1000),
- 2
+ 2,
);
const energyValueRounded = energySampledValueTemplate.value
? // Cumulate the fluctuated value around the static one
{
limitationEnabled: chargingStation.getCustomValueLimitationMeterValues(),
unitMultiplier: unitDivider,
- }
+ },
),
- energySampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT
+ energySampledValueTemplate.fluctuationPercent ?? Constants.DEFAULT_FLUCTUATION_PERCENT,
)
: getRandomFloatRounded(connectorMaximumEnergyRounded);
// Persist previous value on connector
roundTo(
chargingStation.getEnergyActiveImportRegisterByTransactionId(transactionId) /
unitDivider,
- 2
- )
- )
+ 2,
+ ),
+ ),
);
const sampledValuesIndex = meterValue.sampledValue.length - 1;
if (energyValueRounded > connectorMaximumEnergyRounded || debug) {
`${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`,
);
}
}
public static buildTransactionBeginMeterValue(
chargingStation: ChargingStation,
connectorId: number,
- meterStart: number
+ meterStart: number,
): OCPP16MeterValue {
const meterValue: OCPP16MeterValue = {
timestamp: new Date(),
// 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;
}
public static buildTransactionEndMeterValue(
chargingStation: ChargingStation,
connectorId: number,
- meterStop: number
+ meterStop: number,
): OCPP16MeterValue {
const meterValue: OCPP16MeterValue = {
timestamp: new Date(),
// 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);
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 = [];
}
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 = [];
}
public static parseJsonSchemaFile<T extends JsonType>(
relativePath: string,
moduleName?: string,
- methodName?: string
+ methodName?: string,
): JSONSchemaType<T> {
return super.parseJsonSchemaFile<T>(
relativePath,
OCPPVersion.VERSION_16,
moduleName,
- methodName
+ methodName,
);
}
public static async isIdTagAuthorized(
chargingStation: ChargingStation,
connectorId: number,
- idTag: string
+ idTag: string,
): Promise<boolean> {
let authorized = false;
const connectorStatus = chargingStation.getConnectorStatus(connectorId);
} 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;
sampledValueTemplate: SampledValueTemplate,
value: number,
context?: MeterValueContext,
- phase?: OCPP16MeterValuePhase
+ phase?: OCPP16MeterValuePhase,
): OCPP16SampledValue {
const sampledValueValue = value ?? sampledValueTemplate?.value ?? null;
const sampledValueContext = context ?? sampledValueTemplate?.context ?? null;
private static checkMeasurandPowerDivider(
chargingStation: ChargingStation,
- measurandType: OCPP16MeterValueMeasurand
+ measurandType: OCPP16MeterValueMeasurand,
): void {
if (isUndefined(chargingStation.powerDivider)) {
const errMsg = `MeterValues measurand ${
}
private static getMeasurandDefaultLocation(
- measurandType: OCPP16MeterValueMeasurand
+ measurandType: OCPP16MeterValueMeasurand,
): MeterValueLocation | undefined {
switch (measurandType) {
case OCPP16MeterValueMeasurand.STATE_OF_CHARGE:
}
private static getMeasurandDefaultUnit(
- measurandType: OCPP16MeterValueMeasurand
+ measurandType: OCPP16MeterValueMeasurand,
): MeterValueUnit | undefined {
switch (measurandType) {
case OCPP16MeterValueMeasurand.CURRENT_EXPORT:
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<boolean> {
const authorizeResponse: OCPP16AuthorizeResponse =
await chargingStation.ocppRequestService.requestHandler<
to: OCPP20ConnectorStatusEnumType.Unavailable,
},
// { from: OCPP20ConnectorStatusEnumType.Faulted, to: OCPP20ConnectorStatusEnumType.Faulted },
- ]
+ ],
);
}
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20ClearCacheRequest>(
'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;
}
chargingStation: ChargingStation,
messageId: string,
commandName: OCPP20IncomingRequestCommand,
- commandPayload: JsonType
+ commandPayload: JsonType,
): Promise<void> {
let response: JsonType;
if (
`${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 (
// 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;
}
`${commandName} is not implemented to handle request PDU ${JSON.stringify(
commandPayload,
null,
- 2
+ 2,
)}`,
commandName,
- commandPayload
+ commandPayload,
);
}
} else {
`${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
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;
}
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20BootNotificationRequest>(
'assets/json-schemas/ocpp/2.0/BootNotificationRequest.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20HeartbeatRequest>(
'assets/json-schemas/ocpp/2.0/HeartbeatRequest.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20StatusNotificationRequest>(
'assets/json-schemas/ocpp/2.0/StatusNotificationRequest.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
]);
this.buildRequestPayload = this.buildRequestPayload.bind(this) as <Request extends JsonType>(
chargingStation: ChargingStation,
commandName: OCPP20RequestCommand,
- commandParams?: JsonType
+ commandParams?: JsonType,
) => Request;
}
chargingStation: ChargingStation,
commandName: OCPP20RequestCommand,
commandParams?: JsonType,
- params?: RequestParams
+ params?: RequestParams,
): Promise<ResponseType> {
// FIXME?: add sanity checks on charging station availability, connector availability, connector status, etc.
if (OCPP20ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) {
generateUUID(),
this.buildRequestPayload<RequestType>(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().
ErrorType.NOT_SUPPORTED,
`Unsupported OCPP command '${commandName}'`,
commandName,
- commandParams
+ commandParams,
);
}
private buildRequestPayload<Request extends JsonType>(
chargingStation: ChargingStation,
commandName: OCPP20RequestCommand,
- commandParams?: JsonType
+ commandParams?: JsonType,
): Request {
commandParams = commandParams as JsonObject;
switch (commandName) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`Unsupported OCPP command '${commandName}'`,
commandName,
- commandParams
+ commandParams,
);
}
}
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20BootNotificationResponse>(
'assets/json-schemas/ocpp/2.0/BootNotificationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20HeartbeatResponse>(
'assets/json-schemas/ocpp/2.0/HeartbeatResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
[
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20StatusNotificationResponse>(
'assets/json-schemas/ocpp/2.0/StatusNotificationResponse.json',
moduleName,
- 'constructor'
+ 'constructor',
),
],
]);
OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20ClearCacheResponse>(
'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;
}
chargingStation: ChargingStation,
commandName: OCPP20RequestCommand,
payload: JsonType,
- requestPayload: JsonType
+ requestPayload: JsonType,
): Promise<void> {
if (
chargingStation.isRegistered() === true ||
} catch (error) {
logger.error(
`${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`,
- error
+ error,
);
throw error;
}
`${commandName} is not implemented to handle response PDU ${JSON.stringify(
payload,
null,
- 2
+ 2,
)}`,
commandName,
- payload
+ payload,
);
}
} else {
`${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,
);
}
}
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(
OCPP20OptionalVariableName.HeartbeatInterval,
payload.interval.toString(),
{},
- { overwrite: true, save: true }
+ { overwrite: true, save: true },
);
OCPP20ServiceUtils.startHeartbeatInterval(chargingStation, payload.interval);
}
} else {
logger.error(
`${chargingStation.logPrefix()} Charging station boot notification response received: %j with undefined registration status`,
- payload
+ payload,
);
}
}
public static parseJsonSchemaFile<T extends JsonType>(
relativePath: string,
moduleName?: string,
- methodName?: string
+ methodName?: string,
): JSONSchemaType<T> {
return super.parseJsonSchemaFile<T>(
relativePath,
OCPPVersion.VERSION_20,
moduleName,
- methodName
+ methodName,
);
}
}
chargingStation: ChargingStation,
messageId: string,
commandName: IncomingRequestCommand,
- commandPayload: JsonType
+ commandPayload: JsonType,
) => Promise<void>;
this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this) as <
- T extends JsonType
+ T extends JsonType,
>(
chargingStation: ChargingStation,
commandName: IncomingRequestCommand,
schema: JSONSchemaType<T>,
- payload: T
+ payload: T,
) => boolean;
}
chargingStation: ChargingStation,
commandName: IncomingRequestCommand,
error: Error,
- params: HandleErrorParams<T> = { throwError: true, consoleOut: false }
+ params: HandleErrorParams<T> = { 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;
chargingStation: ChargingStation,
commandName: IncomingRequestCommand,
schema: JSONSchemaType<T>,
- payload: T
+ payload: T,
): boolean {
if (chargingStation.getOcppStrictCompliance() === false) {
return true;
}
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),
);
}
chargingStation: ChargingStation,
messageId: string,
commandName: IncomingRequestCommand,
- commandPayload: JsonType
+ commandPayload: JsonType,
): Promise<void>;
}
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<ResType>;
this.sendMessage = this.sendMessage.bind(this) as (
chargingStation: ChargingStation,
messageId: string,
messagePayload: JsonType,
commandName: RequestCommand,
- params?: RequestParams
+ params?: RequestParams,
) => Promise<ResponseType>;
this.sendResponse = this.sendResponse.bind(this) as (
chargingStation: ChargingStation,
messageId: string,
messagePayload: JsonType,
- commandName: IncomingRequestCommand
+ commandName: IncomingRequestCommand,
) => Promise<ResponseType>;
this.sendError = this.sendError.bind(this) as (
chargingStation: ChargingStation,
messageId: string,
ocppError: OCPPError,
- commandName: RequestCommand | IncomingRequestCommand
+ commandName: RequestCommand | IncomingRequestCommand,
) => Promise<ResponseType>;
this.internalSendMessage = this.internalSendMessage.bind(this) as (
chargingStation: ChargingStation,
messagePayload: JsonType | OCPPError,
messageType: MessageType,
commandName: RequestCommand | IncomingRequestCommand,
- params?: RequestParams
+ params?: RequestParams,
) => Promise<ResponseType>;
this.buildMessageToSend = this.buildMessageToSend.bind(this) as (
chargingStation: ChargingStation,
messageType: MessageType,
commandName: RequestCommand | IncomingRequestCommand,
responseCallback: ResponseCallback,
- errorCallback: ErrorCallback
+ errorCallback: ErrorCallback,
) => string;
this.validateRequestPayload = this.validateRequestPayload.bind(this) as <T extends JsonObject>(
chargingStation: ChargingStation,
commandName: RequestCommand | IncomingRequestCommand,
- payload: T
+ payload: T,
) => boolean;
this.validateIncomingRequestResponsePayload = this.validateIncomingRequestResponsePayload.bind(
- this
+ this,
) as <T extends JsonObject>(
chargingStation: ChargingStation,
commandName: RequestCommand | IncomingRequestCommand,
- payload: T
+ payload: T,
) => boolean;
}
public static getInstance<T extends OCPPRequestService>(
this: new (ocppResponseService: OCPPResponseService) => T,
- ocppResponseService: OCPPResponseService
+ ocppResponseService: OCPPResponseService,
): T {
if (OCPPRequestService.instance === null) {
OCPPRequestService.instance = new this(ocppResponseService);
chargingStation: ChargingStation,
messageId: string,
messagePayload: JsonType,
- commandName: IncomingRequestCommand
+ commandName: IncomingRequestCommand,
): Promise<ResponseType> {
try {
// Send response message
messageId,
messagePayload,
MessageType.CALL_RESULT_MESSAGE,
- commandName
+ commandName,
);
} catch (error) {
handleSendMessageError(chargingStation, commandName, error as Error, {
chargingStation: ChargingStation,
messageId: string,
ocppError: OCPPError,
- commandName: RequestCommand | IncomingRequestCommand
+ commandName: RequestCommand | IncomingRequestCommand,
): Promise<ResponseType> {
try {
// Send error message
messageId,
ocppError,
MessageType.CALL_ERROR_MESSAGE,
- commandName
+ commandName,
);
} catch (error) {
handleSendMessageError(chargingStation, commandName, error as Error);
messageId: string,
messagePayload: JsonType,
commandName: RequestCommand,
- params: RequestParams = defaultRequestParams
+ params: RequestParams = defaultRequestParams,
): Promise<ResponseType> {
params = {
...defaultRequestParams,
messagePayload,
MessageType.CALL_MESSAGE,
commandName,
- params
+ params,
);
} catch (error) {
handleSendMessageError(chargingStation, commandName, error as Error, {
private validateRequestPayload<T extends JsonObject>(
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;
}
}
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<T extends JsonObject>(
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<T>(payload);
OCPPServiceUtils.convertDateToISOString<T>(payload);
}
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),
);
}
messagePayload: JsonType | OCPPError,
messageType: MessageType,
commandName: RequestCommand | IncomingRequestCommand,
- params: RequestParams = defaultRequestParams
+ params: RequestParams = defaultRequestParams,
): Promise<ResponseType> {
params = {
...defaultRequestParams,
if (chargingStation.getEnableStatistics() === true) {
chargingStation.performanceStatistics?.addRequestStatistic(
commandName,
- MessageType.CALL_RESULT_MESSAGE
+ MessageType.CALL_RESULT_MESSAGE,
);
}
// Handle the request's response
chargingStation,
commandName as RequestCommand,
payload,
- requestPayload
+ requestPayload,
)
.then(() => {
resolve(payload);
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);
messageType,
commandName,
responseCallback,
- errorCallback
+ errorCallback,
);
let sendError = false;
// Check if wsConnection opened
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;
}
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) {
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,
);
}
messageType: MessageType,
commandName: RequestCommand | IncomingRequestCommand,
responseCallback: ResponseCallback,
- errorCallback: ErrorCallback
+ errorCallback: ErrorCallback,
): string {
let messageToSend: string;
// Type of message
this.validateIncomingRequestResponsePayload(
chargingStation,
commandName,
- messagePayload as JsonObject
+ messagePayload as JsonObject,
);
messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
break;
chargingStation: ChargingStation,
commandName: RequestCommand,
commandParams?: JsonType,
- params?: RequestParams
+ params?: RequestParams,
): Promise<ResType>;
}
chargingStation: ChargingStation,
commandName: RequestCommand,
payload: JsonType,
- requestPayload: JsonType
+ requestPayload: JsonType,
) => Promise<void>;
this.validateResponsePayload = this.validateResponsePayload.bind(this) as <T extends JsonType>(
chargingStation: ChargingStation,
commandName: RequestCommand,
schema: JSONSchemaType<T>,
- payload: T
+ payload: T,
) => boolean;
}
chargingStation: ChargingStation,
commandName: RequestCommand,
schema: JSONSchemaType<T>,
- payload: T
+ payload: T,
): boolean {
if (chargingStation.getOcppStrictCompliance() === false) {
return true;
}
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),
);
}
chargingStation: ChargingStation,
commandName: RequestCommand,
payload: JsonType,
- requestPayload: JsonType
+ requestPayload: JsonType,
): Promise<void>;
}
public static isRequestCommandSupported(
chargingStation: ChargingStation,
- command: RequestCommand
+ command: RequestCommand,
): boolean {
const isRequestCommand = Object.values<RequestCommand>(RequestCommand).includes(command);
if (
public static isIncomingRequestCommandSupported(
chargingStation: ChargingStation,
- command: IncomingRequestCommand
+ command: IncomingRequestCommand,
): boolean {
const isIncomingRequestCommand =
Object.values<IncomingRequestCommand>(IncomingRequestCommand).includes(command);
public static isMessageTriggerSupported(
chargingStation: ChargingStation,
- messageTrigger: MessageTrigger
+ messageTrigger: MessageTrigger,
): boolean {
const isMessageTrigger = Object.values(MessageTrigger).includes(messageTrigger);
if (isMessageTrigger === true && !chargingStation.stationInfo?.messageTriggerSupport) {
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;
}
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;
}
chargingStation: ChargingStation,
connectorId: number,
status: ConnectorStatusEnum,
- evseId?: number
+ evseId?: number,
): StatusNotificationRequest {
switch (chargingStation.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16) {
case OCPPVersion.VERSION_16:
connectorId: number,
status: ConnectorStatusEnum,
evseId?: number,
- options: { send: boolean } = { send: true }
+ options: { send: boolean } = { send: true },
) {
options = { send: true, ...options };
if (options.send) {
chargingStation,
connectorId,
status,
- evseId
- )
+ evseId,
+ ),
);
}
chargingStation.getConnectorStatus(connectorId).status = status;
protected static checkConnectorStatusTransition(
chargingStation: ChargingStation,
connectorId: number,
- status: ConnectorStatusEnum
+ status: ConnectorStatusEnum,
): boolean {
const fromStatus = chargingStation.getConnectorStatus(connectorId).status;
let transitionAllowed = false;
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;
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;
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) {
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;
relativePath: string,
ocppVersion: OCPPVersion,
moduleName?: string,
- methodName?: string
+ methodName?: string,
): JSONSchemaType<T> {
const filePath = join(dirname(fileURLToPath(import.meta.url)), relativePath);
try {
FileType.JsonSchema,
error as NodeJS.ErrnoException,
OCPPServiceUtils.logPrefix(ocppVersion, moduleName, methodName),
- { throwError: false }
+ { throwError: false },
);
}
}
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;
}
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;
}
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 &&
sampledValueTemplates[index]?.measurand === measurand &&
ChargingStationConfigurationUtils.getConfigurationKey(
chargingStation,
- StandardParametersKey.MeterValuesSampledData
+ StandardParametersKey.MeterValuesSampledData,
)?.value?.includes(measurand) === true
) {
return sampledValueTemplates[index];
sampledValueTemplates[index]?.measurand === measurand &&
ChargingStationConfigurationUtils.getConfigurationKey(
chargingStation,
- StandardParametersKey.MeterValuesSampledData
+ StandardParametersKey.MeterValuesSampledData,
)?.value?.includes(measurand) === true
) {
return sampledValueTemplates[index];
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}`,
);
}
options: { limitationEnabled?: boolean; unitMultiplier?: number } = {
limitationEnabled: true,
unitMultiplier: 1,
- }
+ },
): number {
options = {
...{
private static logPrefix = (
ocppVersion: OCPPVersion,
moduleName?: string,
- methodName?: string
+ methodName?: string,
): string => {
const logMsg =
isNotEmptyString(moduleName) && isNotEmptyString(methodName)
public buildProtocolRequest(
id: string,
procedureName: ProcedureName,
- requestPayload: RequestPayload
+ requestPayload: RequestPayload,
): ProtocolRequest {
return [id, procedureName, requestPayload];
}
public abstract logPrefix(
moduleName?: string,
methodName?: string,
- prefixSuffix?: string
+ prefixSuffix?: string,
): string;
}
.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);
const [protocol, version, procedureName] = req.url?.split('/').slice(1) as [
Protocol,
ProtocolVersion,
- ProcedureName
+ ProcedureName,
];
const uuid = generateUUID();
this.responseHandlers.set(uuid, res);
req.on('error', (error) => {
logger.error(
`${this.logPrefix(moduleName, 'requestListener.req.onerror')} Error on HTTP request:`,
- error
+ error,
);
});
if (req.method === HttpMethods.POST) {
this.buildProtocolRequest(
uuid,
procedureName,
- body ?? Constants.EMPTY_FREEZED_OBJECT
- )
+ body ?? Constants.EMPTY_FREEZED_OBJECT,
+ ),
)
.then((protocolResponse: ProtocolResponse) => {
if (!isNullOrUndefined(protocolResponse)) {
} catch (error) {
logger.error(
`${this.logPrefix(moduleName, 'requestListener')} Handle HTTP request error:`,
- error
+ error,
);
this.sendResponse(this.buildProtocolResponse(uuid, { status: ResponseStatus.FAILURE }));
}
}
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) {
public static handleProtocols = (
protocols: Set<string>,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
- request: IncomingMessage
+ request: IncomingMessage,
): string | false => {
let protocol: Protocol;
let version: ProtocolVersion;
}
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;
};
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];
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);
}
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);
}
logger.debug(
`${this.logPrefix(
moduleName,
- 'start.ws.onclose'
+ 'start.ws.onclose',
)} WebSocket closed: '${getWebSocketCloseEventStatusString(
- code
- )}' - '${reason.toString()}'`
+ code,
+ )}' - '${reason.toString()}'`,
);
});
});
logger.error(
`${this.logPrefix(
moduleName,
- 'start.httpServer.on.upgrade'
+ 'start.httpServer.on.upgrade',
)} Error at handling connection upgrade:`,
- error
+ error,
);
}
});
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);
logger.error(
`${this.logPrefix(
moduleName,
- 'validateRawDataRequest'
+ 'validateRawDataRequest',
)} UI protocol request is not an array:`,
- request
+ request,
);
return false;
}
if (request.length !== 3) {
logger.error(
`${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
- request
+ request,
);
return false;
}
logger.error(
`${this.logPrefix(
moduleName,
- 'validateRawDataRequest'
+ 'validateRawDataRequest',
)} UI protocol request UUID field is invalid:`,
- request
+ request,
);
return false;
}
`${command} is not implemented to handle message payload ${JSON.stringify(
requestPayload,
null,
- 2
- )}`
+ 2,
+ )}`,
);
}
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
logger.warn(
`${this.logPrefix(
moduleName,
- 'sendBroadcastChannelRequest'
- )} Charging station with hashId '${hashId}' not found`
+ 'sendBroadcastChannelRequest',
+ )} Charging station with hashId '${hashId}' not found`,
);
});
}
for (const procedureName in AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping) {
this.requestHandlers.set(
procedureName as ProcedureName,
- this.handleProtocolRequest.bind(this) as ProtocolRequestHandler
+ this.handleProtocolRequest.bind(this) as ProtocolRequestHandler,
);
}
}
public static getUIServiceImplementation(
version: ProtocolVersion,
- uiServer: AbstractUIServer
+ uiServer: AbstractUIServer,
): AbstractUIService {
switch (version) {
case ProtocolVersion['0.0.1']:
code: ErrorType,
message: string,
command?: RequestCommand | IncomingRequestCommand,
- details?: JsonType
+ details?: JsonType,
) {
super(message);
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));
public addRequestStatistic(
command: RequestCommand | IncomingRequestCommand,
- messageType: MessageType
+ messageType: MessageType,
): void {
switch (messageType) {
case MessageType.CALL_MESSAGE:
logger.info(
`${this.logPrefix()} storage enabled: type ${
Configuration.getPerformanceStorage().type
- }, uri: ${Configuration.getPerformanceStorage().uri}`
+ }, uri: ${Configuration.getPerformanceStorage().uri}`,
);
}
}
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`,
);
}
}
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;
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));
this.dbName,
FileType.PerformanceRecords,
error as NodeJS.ErrnoException,
- this.logPrefix
+ this.logPrefix,
);
})
.finally(() => {
this.dbName,
FileType.PerformanceRecords,
error as NodeJS.ErrnoException,
- this.logPrefix
+ this.logPrefix,
);
}
}
this.dbName,
FileType.PerformanceRecords,
error as NodeJS.ErrnoException,
- this.logPrefix
+ this.logPrefix,
);
}
}
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`,
);
}
}
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`,
);
}
}
type: StorageType,
error: Error,
table?: string,
- params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false }
+ params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false },
): void {
setDefaultErrorParams(params, { throwError: false, consoleOut: false });
const inTableOrCollectionStr =
`${this.logPrefix} ${this.getDBNameFromStorageType(type)} error '${
error.message
}'${inTableOrCollectionStr}:`,
- error
+ error,
);
if (params?.throwError) {
throw error;
public abstract open(): void | Promise<void>;
public abstract close(): void | Promise<void>;
public abstract storePerformanceStatistics(
- performanceStatistics: Statistics
+ performanceStatistics: Statistics,
): void | Promise<void>;
}
console.info(
response.deletedCount,
`Charging Stations with id = %${config.idPattern}% deleted. TenantID =`,
- tenantID
+ tenantID,
);
}
client.close();
console.info(
response.modifiedCount,
`Charging Stations with id = %${config.idPattern}% updated. TenantID =`,
- tenantID
+ tenantID,
);
}
client.close();
export type ProtocolRequestHandler = (
uuid?: string,
procedureName?: ProcedureName,
- payload?: RequestPayload
+ payload?: RequestPayload,
) => undefined | Promise<undefined> | ResponsePayload | Promise<ResponsePayload>;
export enum ProcedureName {
export type BroadcastChannelRequest = [
string,
BroadcastChannelProcedureName,
- BroadcastChannelRequestPayload
+ BroadcastChannelRequestPayload,
];
export type BroadcastChannelResponse = [string, BroadcastChannelResponsePayload];
ResponseCallback,
ErrorCallback,
RequestCommand | IncomingRequestCommand,
- JsonType
+ JsonType,
];
export const MessageTrigger = {
export type IncomingRequestHandler = (
chargingStation: ChargingStation,
- commandPayload: JsonType
+ commandPayload: JsonType,
) => JsonType | Promise<JsonType>;
export const AvailabilityType = {
export type ResponseHandler = (
chargingStation: ChargingStation,
payload: JsonType,
- requestPayload?: JsonType
+ requestPayload?: JsonType,
) => void | Promise<void>;
export type BootNotificationResponse =
} from '../types';
export const buildChargingStationAutomaticTransactionGeneratorConfiguration = (
- chargingStation: ChargingStation
+ chargingStation: ChargingStation,
): ChargingStationAutomaticTransactionGeneratorConfiguration => {
return {
automaticTransactionGenerator: chargingStation.getAutomaticTransactionGeneratorConfiguration(),
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,
);
};
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) {
if (concatenatedCircularArray.length > concatenatedCircularArray.size) {
concatenatedCircularArray.splice(
0,
- concatenatedCircularArray.length - concatenatedCircularArray.size
+ concatenatedCircularArray.length - concatenatedCircularArray.size,
);
}
return concatenatedCircularArray;
private static configurationFile = join(
dirname(fileURLToPath(import.meta.url)),
'assets',
- 'config.json'
+ 'config.json',
);
private static configurationFileWatcher: FSWatcher | undefined;
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 = {
if (hasOwnProp(Configuration.getConfig(), 'uiServer')) {
uiServerConfiguration = merge<UIServerConfiguration>(
uiServerConfiguration,
- Configuration.getConfig()?.uiServer
+ Configuration.getConfig()?.uiServer,
);
}
if (isCFEnvironment() === true) {
...(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,
),
}),
};
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')) {
Configuration.warnDeprecatedConfigurationKey(
'stationTemplateURLs',
undefined,
- "Use 'stationTemplateUrls' instead"
+ "Use 'stationTemplateUrls' instead",
);
!isUndefined(Configuration.getConfig()['stationTemplateURLs']) &&
(Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()[
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;
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,
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,
public static workerPoolInUse(): boolean {
return [WorkerProcessType.dynamicPool, WorkerProcessType.staticPool].includes(
- Configuration.getWorker().processType
+ Configuration.getWorker().processType,
);
}
Configuration.warnDeprecatedConfigurationKey(
'supervisionURLs',
undefined,
- "Use 'supervisionUrls' instead"
+ "Use 'supervisionUrls' instead",
);
!isUndefined(Configuration.getConfig()['supervisionURLs']) &&
(Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as
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
private static warnDeprecatedConfigurationKey(
key: string,
sectionName?: string,
- logMsgToAppend = ''
+ logMsgToAppend = '',
) {
if (
sectionName &&
`${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}` : ''
- }`
- )}`
+ }`,
+ )}`,
);
}
}
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) {
Configuration.configurationFile,
FileType.Configuration,
error as NodeJS.ErrnoException,
- Configuration.logPrefix()
+ Configuration.logPrefix(),
);
}
}
file: string,
fileType: FileType,
error: NodeJS.ErrnoException,
- logPrefix: string
+ logPrefix: string,
): void {
const prefix = isNotEmptyString(logPrefix) ? `${logPrefix} ` : '';
let logMsg: string;
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}'`);
fileType: FileType,
error: NodeJS.ErrnoException,
logPrefix: string,
- params: HandleErrorParams<EmptyObject> = defaultErrorParams
+ params: HandleErrorParams<EmptyObject> = defaultErrorParams,
): void => {
setDefaultErrorParams(params);
const prefix = isNotEmptyString(logPrefix) ? `${logPrefix} ` : '';
chargingStation: ChargingStation,
commandName: RequestCommand | IncomingRequestCommand,
error: Error,
- params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false }
+ params: HandleErrorParams<EmptyObject> = { throwError: false, consoleOut: false },
): void => {
setDefaultErrorParams(params, { throwError: false, consoleOut: false });
logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
export const setDefaultErrorParams = <T extends JsonType>(
params: HandleErrorParams<T>,
- defaultParams: HandleErrorParams<T> = defaultErrorParams
+ defaultParams: HandleErrorParams<T> = defaultErrorParams,
): HandleErrorParams<T> => {
params = { ...defaultParams, ...params };
return params;
});
}
}
- }
+ },
): FSWatcher | undefined => {
if (isNotEmptyString(file)) {
try {
filename: insertAt(
Configuration.getLog().errorFile,
'-%DATE%',
- Configuration.getLog().errorFile?.indexOf('.log')
+ Configuration.getLog().errorFile?.indexOf('.log'),
),
level: 'error',
...(logMaxFiles && { maxFiles: logMaxFiles }),
filename: insertAt(
Configuration.getLog().file,
'-%DATE%',
- Configuration.getLog().file?.indexOf('.log')
+ Configuration.getLog().file?.indexOf('.log'),
),
...(logMaxFiles && { maxFiles: logMaxFiles }),
...(logMaxSize && { maxSize: logMaxSize }),
new TransportType.Console({
format: format.combine(
format.splat(),
- (format[Configuration.getLog().format] as FormatWrap)()
+ (format[Configuration.getLog().format] as FormatWrap)(),
),
- })
+ }),
);
}
} from '../types';
export const buildStartedMessage = (
- chargingStation: ChargingStation
+ chargingStation: ChargingStation,
): ChargingStationWorkerMessage<ChargingStationData> => {
return {
id: ChargingStationWorkerMessageEvents.started,
};
export const buildStoppedMessage = (
- chargingStation: ChargingStation
+ chargingStation: ChargingStation,
): ChargingStationWorkerMessage<ChargingStationData> => {
return {
id: ChargingStationWorkerMessageEvents.stopped,
};
export const buildUpdatedMessage = (
- chargingStation: ChargingStation
+ chargingStation: ChargingStation,
): ChargingStationWorkerMessage<ChargingStationData> => {
return {
id: ChargingStationWorkerMessageEvents.updated,
};
export const buildPerformanceStatisticsMessage = (
- statistics: Statistics
+ statistics: Statistics,
): ChargingStationWorkerMessage<Statistics> => {
return {
id: ChargingStationWorkerMessageEvents.performanceStatistics,
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,
);
};
};
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;
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) {
return getRandomFloatRounded(
staticValue * (1 + fluctuationRatio),
staticValue * (1 - fluctuationRatio),
- scale
+ scale,
);
};
timeoutError: Error,
timeoutCallback: () => void = () => {
/* This is intentional */
- }
+ },
): Promise<T> => {
// Create a timeout promise that rejects in timeout milliseconds
const timeoutPromise = new Promise<never>((_, reject) => {
export const JSONStringifyWithMapSupport = (
obj: Record<string, unknown> | Record<string, unknown>[] | Map<unknown, unknown>,
- space?: number
+ space?: number,
): string => {
return JSON.stringify(
obj,
}
return value;
},
- space
+ space,
);
};
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');
this.workerOptions.poolMinSize,
this.workerOptions.poolMaxSize,
this.workerScript,
- this.workerOptions.poolOptions
+ this.workerOptions.poolOptions,
);
}
public static getWorkerImplementation<T extends WorkerData>(
workerScript: string,
workerProcessType: WorkerProcessType,
- workerOptions?: WorkerOptions
+ workerOptions?: WorkerOptions,
): WorkerAbstract<T> | null {
if (!isMainThread) {
throw new Error('Cannot get a worker implementation outside the main thread');
size: this.size,
elementsExecuting: [...this.workerSet].reduce(
(accumulator, workerSetElement) => accumulator + workerSetElement.numberOfWorkerElements,
- 0
+ 0,
),
elementsPerWorker: this.maxElementsPerWorker,
};
});
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) {
});
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);
this.pool = new FixedThreadPool(
this.workerOptions.poolMaxSize,
this.workerScript,
- this.workerOptions.poolOptions
+ this.workerOptions.poolOptions,
);
}
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`,
+ ),
);
});
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);
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);
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);