1 import { readFileSync
} from
'node:fs';
2 import { dirname
, join
} from
'node:path';
3 import { fileURLToPath
} from
'node:url';
5 import type { DefinedError
, ErrorObject
, JSONSchemaType
} from
'ajv';
6 import { isDate
} from
'date-fns';
8 import { OCPP16Constants
} from
'./1.6/OCPP16Constants';
9 import { OCPP20Constants
} from
'./2.0/OCPP20Constants';
10 import { OCPPConstants
} from
'./OCPPConstants';
11 import { type ChargingStation
, getConfigurationKey
, getIdTagsFile
} from
'../../charging-station';
12 import { BaseError
} from
'../../exception';
15 type AuthorizeRequest
,
16 type AuthorizeResponse
,
19 type ConnectorStatusEnum
,
22 IncomingRequestCommand
,
28 type OCPP16StatusNotificationRequest
,
29 type OCPP20StatusNotificationRequest
,
32 type SampledValueTemplate
,
33 StandardParametersKey
,
34 type StatusNotificationRequest
,
35 type StatusNotificationResponse
,
46 export class OCPPServiceUtils
{
47 protected constructor() {
48 // This is intentional
51 public static ajvErrorsToErrorType(errors
: ErrorObject
[]): ErrorType
{
52 for (const error
of errors
as DefinedError
[]) {
53 switch (error
.keyword
) {
55 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
58 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
61 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
64 return ErrorType
.FORMAT_VIOLATION
;
67 public static getMessageTypeString(messageType
: MessageType
): string {
68 switch (messageType
) {
69 case MessageType
.CALL_MESSAGE
:
71 case MessageType
.CALL_RESULT_MESSAGE
:
73 case MessageType
.CALL_ERROR_MESSAGE
:
80 public static isRequestCommandSupported(
81 chargingStation
: ChargingStation
,
82 command
: RequestCommand
,
84 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
86 isRequestCommand
=== true &&
87 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
91 isRequestCommand
=== true &&
92 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
?.[command
]
94 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
];
96 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
100 public static isIncomingRequestCommandSupported(
101 chargingStation
: ChargingStation
,
102 command
: IncomingRequestCommand
,
104 const isIncomingRequestCommand
=
105 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
107 isIncomingRequestCommand
=== true &&
108 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
112 isIncomingRequestCommand
=== true &&
113 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
?.[command
]
115 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
];
117 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
121 public static isMessageTriggerSupported(
122 chargingStation
: ChargingStation
,
123 messageTrigger
: MessageTrigger
,
125 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
126 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
129 isMessageTrigger
=== true &&
130 chargingStation
.stationInfo
?.messageTriggerSupport
?.[messageTrigger
]
132 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
];
135 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`,
140 public static isConnectorIdValid(
141 chargingStation
: ChargingStation
,
142 ocppCommand
: IncomingRequestCommand
,
145 if (connectorId
< 0) {
147 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`,
154 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
155 for (const key
in obj
) {
156 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
157 if (isDate(obj
![key
])) {
158 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
159 (obj
![key
] as string) = (obj
![key
] as Date).toISOString();
160 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
161 } else if (obj
![key
] !== null && typeof obj
![key
] === 'object') {
162 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
163 OCPPServiceUtils
.convertDateToISOString
<T
>(obj
![key
] as T
);
168 public static buildStatusNotificationRequest(
169 chargingStation
: ChargingStation
,
171 status: ConnectorStatusEnum
,
173 ): StatusNotificationRequest
{
174 switch (chargingStation
.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
) {
175 case OCPPVersion
.VERSION_16
:
179 errorCode
: ChargePointErrorCode
.NO_ERROR
,
180 } as OCPP16StatusNotificationRequest
;
181 case OCPPVersion
.VERSION_20
:
182 case OCPPVersion
.VERSION_201
:
184 timestamp
: new Date(),
185 connectorStatus
: status,
188 } as OCPP20StatusNotificationRequest
;
190 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
194 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
195 if (!chargingStation
.heartbeatSetInterval
) {
196 chargingStation
.startHeartbeat();
197 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
198 chargingStation
.restartHeartbeat();
202 public static async sendAndSetConnectorStatus(
203 chargingStation
: ChargingStation
,
205 status: ConnectorStatusEnum
,
207 options
?: { send
: boolean },
209 options
= { send
: true, ...options
};
211 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
212 await chargingStation
.ocppRequestService
.requestHandler
<
213 StatusNotificationRequest
,
214 StatusNotificationResponse
217 RequestCommand
.STATUS_NOTIFICATION
,
218 OCPPServiceUtils
.buildStatusNotificationRequest(
226 chargingStation
.getConnectorStatus(connectorId
)!.status = status;
229 public static async isIdTagAuthorized(
230 chargingStation
: ChargingStation
,
233 ): Promise
<boolean> {
234 if (!chargingStation
.getLocalAuthListEnabled() && !chargingStation
.getRemoteAuthorization()) {
236 `${chargingStation.logPrefix()} The charging station expects to authorize RFID tags but nor local authorization nor remote authorization are enabled. Misbehavior may occur`,
240 chargingStation
.getLocalAuthListEnabled() === true &&
241 OCPPServiceUtils
.isIdTagLocalAuthorized(chargingStation
, idTag
)
243 const connectorStatus
: ConnectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
244 connectorStatus
.localAuthorizeIdTag
= idTag
;
245 connectorStatus
.idTagLocalAuthorized
= true;
247 } else if (chargingStation
.getRemoteAuthorization()) {
248 return await OCPPServiceUtils
.isIdTagRemoteAuthorized(chargingStation
, connectorId
, idTag
);
253 protected static checkConnectorStatusTransition(
254 chargingStation
: ChargingStation
,
256 status: ConnectorStatusEnum
,
258 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
)!.status;
259 let transitionAllowed
= false;
260 switch (chargingStation
.stationInfo
.ocppVersion
) {
261 case OCPPVersion
.VERSION_16
:
263 (connectorId
=== 0 &&
264 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
265 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
268 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
269 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
272 transitionAllowed
= true;
275 case OCPPVersion
.VERSION_20
:
276 case OCPPVersion
.VERSION_201
:
278 (connectorId
=== 0 &&
279 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
280 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
283 OCPP20Constants
.ConnectorStatusTransitions
.findIndex(
284 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
287 transitionAllowed
= true;
292 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
293 `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`,
296 if (transitionAllowed
=== false) {
298 `${chargingStation.logPrefix()} OCPP ${
299 chargingStation.stationInfo.ocppVersion
300 } connector id ${connectorId} status transition from '${
301 chargingStation.getConnectorStatus(connectorId)!.status
302 }' to '${status}' is not allowed`,
305 return transitionAllowed
;
308 protected static parseJsonSchemaFile
<T
extends JsonType
>(
309 relativePath
: string,
310 ocppVersion
: OCPPVersion
,
313 ): JSONSchemaType
<T
> {
314 const filePath
= join(dirname(fileURLToPath(import.meta
.url
)), relativePath
);
316 return JSON
.parse(readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
321 error
as NodeJS
.ErrnoException
,
322 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
323 { throwError
: false },
325 return {} as JSONSchemaType
<T
>;
329 protected static getSampledValueTemplate(
330 chargingStation
: ChargingStation
,
332 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
333 phase
?: MeterValuePhase
,
334 ): SampledValueTemplate
| undefined {
335 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
336 if (OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(measurand
) === false) {
338 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
343 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
346 StandardParametersKey
.MeterValuesSampledData
,
347 )?.value
?.includes(measurand
) === false
350 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
351 StandardParametersKey.MeterValuesSampledData
356 const sampledValueTemplates
: SampledValueTemplate
[] =
357 chargingStation
.getConnectorStatus(connectorId
)!.MeterValues
;
360 isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
364 OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(
365 sampledValueTemplates
[index
]?.measurand
??
366 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
370 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
374 sampledValueTemplates
[index
]?.phase
=== phase
&&
375 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
378 StandardParametersKey
.MeterValuesSampledData
,
379 )?.value
?.includes(measurand
) === true
381 return sampledValueTemplates
[index
];
384 !sampledValueTemplates
[index
]?.phase
&&
385 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
388 StandardParametersKey
.MeterValuesSampledData
,
389 )?.value
?.includes(measurand
) === true
391 return sampledValueTemplates
[index
];
393 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
394 (!sampledValueTemplates
[index
]?.measurand
||
395 sampledValueTemplates
[index
]?.measurand
=== measurand
)
397 return sampledValueTemplates
[index
];
400 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
401 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
402 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
403 throw new BaseError(errorMsg
);
406 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
410 protected static getLimitFromSampledValueTemplateCustomValue(
413 options
?: { limitationEnabled
?: boolean; unitMultiplier
?: number },
417 limitationEnabled
: true,
422 const parsedInt
= parseInt(value
);
423 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
424 return options
?.limitationEnabled
425 ? min(numberValue
* options
.unitMultiplier
!, limit
)
426 : numberValue
* options
.unitMultiplier
!;
429 private static isIdTagLocalAuthorized(chargingStation
: ChargingStation
, idTag
: string): boolean {
431 chargingStation
.hasIdTags() === true &&
433 chargingStation
.idTagsCache
434 .getIdTags(getIdTagsFile(chargingStation
.stationInfo
)!)
435 ?.find((tag
) => tag
=== idTag
),
440 private static async isIdTagRemoteAuthorized(
441 chargingStation
: ChargingStation
,
444 ): Promise
<boolean> {
445 chargingStation
.getConnectorStatus(connectorId
)!.authorizeIdTag
= idTag
;
448 await chargingStation
.ocppRequestService
.requestHandler
<
451 >(chargingStation
, RequestCommand
.AUTHORIZE
, {
454 )?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
458 private static logPrefix
= (
459 ocppVersion
: OCPPVersion
,
464 isNotEmptyString(moduleName
) && isNotEmptyString(methodName
)
465 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
466 : ` OCPP ${ocppVersion} |`;
467 return logPrefix(logMsg
);