import { fileURLToPath } from 'node:url';
import type { DefinedError, ErrorObject, JSONSchemaType } from 'ajv';
+import { isDate } from 'date-fns';
import { OCPP16Constants } from './1.6/OCPP16Constants';
import { OCPP20Constants } from './2.0/OCPP20Constants';
import { OCPPConstants } from './OCPPConstants';
-import { type ChargingStation, ChargingStationConfigurationUtils } from '../../charging-station';
+import { type ChargingStation, getConfigurationKey, getIdTagsFile } from '../../charging-station';
import { BaseError } from '../../exception';
import {
+ AuthorizationStatus,
+ type AuthorizeRequest,
+ type AuthorizeResponse,
ChargePointErrorCode,
+ ChargingStationEvents,
+ type ConnectorStatus,
type ConnectorStatusEnum,
ErrorType,
FileType,
IncomingRequestCommand,
- type JsonObject,
type JsonType,
MessageTrigger,
MessageType,
isNotEmptyString,
logPrefix,
logger,
+ max,
+ min,
} from '../../utils';
export class OCPPServiceUtils {
// This is intentional
}
- public static ajvErrorsToErrorType(errors: ErrorObject[]): ErrorType {
- for (const error of errors as DefinedError[]) {
- switch (error.keyword) {
- case 'type':
- return ErrorType.TYPE_CONSTRAINT_VIOLATION;
- case 'dependencies':
- case 'required':
- return ErrorType.OCCURRENCE_CONSTRAINT_VIOLATION;
- case 'pattern':
- case 'format':
- return ErrorType.PROPERTY_CONSTRAINT_VIOLATION;
+ public static ajvErrorsToErrorType(errors: ErrorObject[] | null | undefined): ErrorType {
+ if (isNotEmptyArray(errors) === true) {
+ for (const error of errors as DefinedError[]) {
+ switch (error.keyword) {
+ case 'type':
+ return ErrorType.TYPE_CONSTRAINT_VIOLATION;
+ case 'dependencies':
+ case 'required':
+ return ErrorType.OCCURRENCE_CONSTRAINT_VIOLATION;
+ case 'pattern':
+ case 'format':
+ return ErrorType.PROPERTY_CONSTRAINT_VIOLATION;
+ }
}
}
return ErrorType.FORMAT_VIOLATION;
return true;
} else if (
isRequestCommand === true &&
- chargingStation.stationInfo?.commandsSupport?.outgoingCommands
+ chargingStation.stationInfo?.commandsSupport?.outgoingCommands?.[command]
) {
- return chargingStation.stationInfo?.commandsSupport?.outgoingCommands[command] ?? false;
+ return chargingStation.stationInfo?.commandsSupport?.outgoingCommands[command];
}
logger.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
return false;
return true;
} else if (
isIncomingRequestCommand === true &&
- chargingStation.stationInfo?.commandsSupport?.incomingCommands
+ chargingStation.stationInfo?.commandsSupport?.incomingCommands?.[command]
) {
- return chargingStation.stationInfo?.commandsSupport?.incomingCommands[command] ?? false;
+ return chargingStation.stationInfo?.commandsSupport?.incomingCommands[command];
}
logger.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
return false;
const isMessageTrigger = Object.values(MessageTrigger).includes(messageTrigger);
if (isMessageTrigger === true && !chargingStation.stationInfo?.messageTriggerSupport) {
return true;
- } else if (isMessageTrigger === true && chargingStation.stationInfo?.messageTriggerSupport) {
- return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger] ?? false;
+ } else if (
+ isMessageTrigger === true &&
+ chargingStation.stationInfo?.messageTriggerSupport?.[messageTrigger]
+ ) {
+ return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger];
}
logger.error(
`${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`,
}
public static convertDateToISOString<T extends JsonType>(obj: T): void {
- for (const key in obj as JsonObject) {
- if (obj![key] instanceof Date) {
- obj![key] = (obj![key] as Date).toISOString();
+ for (const key in obj) {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ if (isDate(obj![key])) {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ (obj![key] as string) = (obj![key] as Date).toISOString();
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
} else if (obj![key] !== null && typeof obj![key] === 'object') {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
OCPPServiceUtils.convertDateToISOString<T>(obj![key] as T);
}
}
status: ConnectorStatusEnum,
evseId?: number,
): StatusNotificationRequest {
- switch (chargingStation.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16) {
+ switch (chargingStation.stationInfo?.ocppVersion) {
case OCPPVersion.VERSION_16:
return {
connectorId,
);
}
chargingStation.getConnectorStatus(connectorId)!.status = status;
+ chargingStation.emit(ChargingStationEvents.connectorStatusChanged, {
+ connectorId,
+ ...chargingStation.getConnectorStatus(connectorId),
+ });
+ }
+
+ public static async isIdTagAuthorized(
+ chargingStation: ChargingStation,
+ connectorId: number,
+ idTag: string,
+ ): Promise<boolean> {
+ if (
+ !chargingStation.getLocalAuthListEnabled() &&
+ !chargingStation.stationInfo?.remoteAuthorization
+ ) {
+ logger.warn(
+ `${chargingStation.logPrefix()} The charging station expects to authorize RFID tags but nor local authorization nor remote authorization are enabled. Misbehavior may occur`,
+ );
+ }
+ if (
+ chargingStation.getLocalAuthListEnabled() === true &&
+ OCPPServiceUtils.isIdTagLocalAuthorized(chargingStation, idTag)
+ ) {
+ const connectorStatus: ConnectorStatus = chargingStation.getConnectorStatus(connectorId)!;
+ connectorStatus.localAuthorizeIdTag = idTag;
+ connectorStatus.idTagLocalAuthorized = true;
+ return true;
+ } else if (chargingStation.stationInfo?.remoteAuthorization) {
+ return await OCPPServiceUtils.isIdTagRemoteAuthorized(chargingStation, connectorId, idTag);
+ }
+ return false;
}
protected static checkConnectorStatusTransition(
): boolean {
const fromStatus = chargingStation.getConnectorStatus(connectorId)!.status;
let transitionAllowed = false;
- switch (chargingStation.stationInfo.ocppVersion) {
+ switch (chargingStation.stationInfo?.ocppVersion) {
case OCPPVersion.VERSION_16:
if (
(connectorId === 0 &&
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) {
logger.warn(
- `${chargingStation.logPrefix()} OCPP ${
- chargingStation.stationInfo.ocppVersion
- } connector id ${connectorId} status transition from '${
+ `${chargingStation.logPrefix()} OCPP ${chargingStation.stationInfo
+ ?.ocppVersion} connector id ${connectorId} status transition from '${
chargingStation.getConnectorStatus(connectorId)!.status
}' to '${status}' is not allowed`,
);
}
if (
measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
- ChargingStationConfigurationUtils.getConfigurationKey(
+ getConfigurationKey(
chargingStation,
StandardParametersKey.MeterValuesSampledData,
)?.value?.includes(measurand) === false
phase &&
sampledValueTemplates[index]?.phase === phase &&
sampledValueTemplates[index]?.measurand === measurand &&
- ChargingStationConfigurationUtils.getConfigurationKey(
+ getConfigurationKey(
chargingStation,
StandardParametersKey.MeterValuesSampledData,
)?.value?.includes(measurand) === true
return sampledValueTemplates[index];
} else if (
!phase &&
- !sampledValueTemplates[index].phase &&
+ !sampledValueTemplates[index]?.phase &&
sampledValueTemplates[index]?.measurand === measurand &&
- ChargingStationConfigurationUtils.getConfigurationKey(
+ getConfigurationKey(
chargingStation,
StandardParametersKey.MeterValuesSampledData,
)?.value?.includes(measurand) === true
return sampledValueTemplates[index];
} else if (
measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER &&
- (!sampledValueTemplates[index].measurand ||
- sampledValueTemplates[index].measurand === measurand)
+ (!sampledValueTemplates[index]?.measurand ||
+ sampledValueTemplates[index]?.measurand === measurand)
) {
return sampledValueTemplates[index];
}
}
protected static getLimitFromSampledValueTemplateCustomValue(
- value: string,
- limit: number,
- options: { limitationEnabled?: boolean; unitMultiplier?: number } = {
- limitationEnabled: true,
- unitMultiplier: 1,
- },
+ value: string | undefined,
+ maxLimit: number,
+ minLimit: number,
+ options?: { limitationEnabled?: boolean; fallbackValue?: number; unitMultiplier?: number },
): number {
options = {
...{
limitationEnabled: true,
unitMultiplier: 1,
+ fallbackValue: 0,
},
...options,
};
- const parsedInt = parseInt(value);
- const numberValue = isNaN(parsedInt) ? Infinity : parsedInt;
- return options?.limitationEnabled
- ? Math.min(numberValue * options.unitMultiplier!, limit)
- : numberValue * options.unitMultiplier!;
+ const parsedValue = parseInt(value ?? '');
+ if (options?.limitationEnabled) {
+ return max(
+ min((!isNaN(parsedValue) ? parsedValue : Infinity) * options.unitMultiplier!, maxLimit),
+ minLimit,
+ );
+ }
+ return (!isNaN(parsedValue) ? parsedValue : options.fallbackValue!) * options.unitMultiplier!;
+ }
+
+ private static isIdTagLocalAuthorized(chargingStation: ChargingStation, idTag: string): boolean {
+ return (
+ chargingStation.hasIdTags() === true &&
+ isNotEmptyString(
+ chargingStation.idTagsCache
+ .getIdTags(getIdTagsFile(chargingStation.stationInfo)!)
+ ?.find((tag) => tag === idTag),
+ )
+ );
+ }
+
+ private static async isIdTagRemoteAuthorized(
+ chargingStation: ChargingStation,
+ connectorId: number,
+ idTag: string,
+ ): Promise<boolean> {
+ chargingStation.getConnectorStatus(connectorId)!.authorizeIdTag = idTag;
+ return (
+ (
+ await chargingStation.ocppRequestService.requestHandler<
+ AuthorizeRequest,
+ AuthorizeResponse
+ >(chargingStation, RequestCommand.AUTHORIZE, {
+ idTag,
+ })
+ )?.idTagInfo?.status === AuthorizationStatus.ACCEPTED
+ );
}
private static logPrefix = (