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
,
45 export class OCPPServiceUtils
{
46 protected constructor() {
47 // This is intentional
50 public static ajvErrorsToErrorType(errors
: ErrorObject
[]): ErrorType
{
51 for (const error
of errors
as DefinedError
[]) {
52 switch (error
.keyword
) {
54 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
57 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
60 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
63 return ErrorType
.FORMAT_VIOLATION
;
66 public static getMessageTypeString(messageType
: MessageType
): string {
67 switch (messageType
) {
68 case MessageType
.CALL_MESSAGE
:
70 case MessageType
.CALL_RESULT_MESSAGE
:
72 case MessageType
.CALL_ERROR_MESSAGE
:
79 public static isRequestCommandSupported(
80 chargingStation
: ChargingStation
,
81 command
: RequestCommand
,
83 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
85 isRequestCommand
=== true &&
86 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
90 isRequestCommand
=== true &&
91 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
93 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
] ?? false;
95 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
99 public static isIncomingRequestCommandSupported(
100 chargingStation
: ChargingStation
,
101 command
: IncomingRequestCommand
,
103 const isIncomingRequestCommand
=
104 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
106 isIncomingRequestCommand
=== true &&
107 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
111 isIncomingRequestCommand
=== true &&
112 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
114 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
] ?? false;
116 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
120 public static isMessageTriggerSupported(
121 chargingStation
: ChargingStation
,
122 messageTrigger
: MessageTrigger
,
124 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
125 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
127 } else if (isMessageTrigger
=== true && chargingStation
.stationInfo
?.messageTriggerSupport
) {
128 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
] ?? false;
131 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`,
136 public static isConnectorIdValid(
137 chargingStation
: ChargingStation
,
138 ocppCommand
: IncomingRequestCommand
,
141 if (connectorId
< 0) {
143 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`,
150 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
151 for (const key
in obj
) {
152 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
153 if (isDate(obj
![key
])) {
154 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
155 (obj
![key
] as string) = (obj
![key
] as Date).toISOString();
156 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
157 } else if (obj
![key
] !== null && typeof obj
![key
] === 'object') {
158 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
159 OCPPServiceUtils
.convertDateToISOString
<T
>(obj
![key
] as T
);
164 public static buildStatusNotificationRequest(
165 chargingStation
: ChargingStation
,
167 status: ConnectorStatusEnum
,
169 ): StatusNotificationRequest
{
170 switch (chargingStation
.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
) {
171 case OCPPVersion
.VERSION_16
:
175 errorCode
: ChargePointErrorCode
.NO_ERROR
,
176 } as OCPP16StatusNotificationRequest
;
177 case OCPPVersion
.VERSION_20
:
178 case OCPPVersion
.VERSION_201
:
180 timestamp
: new Date(),
181 connectorStatus
: status,
184 } as OCPP20StatusNotificationRequest
;
186 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
190 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
191 if (!chargingStation
.heartbeatSetInterval
) {
192 chargingStation
.startHeartbeat();
193 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
194 chargingStation
.restartHeartbeat();
198 public static async sendAndSetConnectorStatus(
199 chargingStation
: ChargingStation
,
201 status: ConnectorStatusEnum
,
203 options
?: { send
: boolean },
205 options
= { send
: true, ...options
};
207 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
208 await chargingStation
.ocppRequestService
.requestHandler
<
209 StatusNotificationRequest
,
210 StatusNotificationResponse
213 RequestCommand
.STATUS_NOTIFICATION
,
214 OCPPServiceUtils
.buildStatusNotificationRequest(
222 chargingStation
.getConnectorStatus(connectorId
)!.status = status;
225 public static async isIdTagAuthorized(
226 chargingStation
: ChargingStation
,
229 ): Promise
<boolean> {
230 if (!chargingStation
.getLocalAuthListEnabled() && !chargingStation
.getRemoteAuthorization()) {
232 `${chargingStation.logPrefix()} The charging station expects to authorize RFID tags but nor local authorization nor remote authorization are enabled. Misbehavior may occur`,
235 let authorized
= false;
237 chargingStation
.getLocalAuthListEnabled() === true &&
238 OCPPServiceUtils
.isIdTagLocalAuthorized(chargingStation
, idTag
)
240 const connectorStatus
: ConnectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
241 connectorStatus
.localAuthorizeIdTag
= idTag
;
242 connectorStatus
.idTagLocalAuthorized
= true;
244 } else if (chargingStation
.getRemoteAuthorization()) {
245 authorized
= await OCPPServiceUtils
.isIdTagRemoteAuthorized(
254 protected static checkConnectorStatusTransition(
255 chargingStation
: ChargingStation
,
257 status: ConnectorStatusEnum
,
259 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
)!.status;
260 let transitionAllowed
= false;
261 switch (chargingStation
.stationInfo
.ocppVersion
) {
262 case OCPPVersion
.VERSION_16
:
264 (connectorId
=== 0 &&
265 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
266 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
269 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
270 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
273 transitionAllowed
= true;
276 case OCPPVersion
.VERSION_20
:
277 case OCPPVersion
.VERSION_201
:
279 (connectorId
=== 0 &&
280 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
281 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
284 OCPP20Constants
.ConnectorStatusTransitions
.findIndex(
285 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
288 transitionAllowed
= true;
293 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
294 `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`,
297 if (transitionAllowed
=== false) {
299 `${chargingStation.logPrefix()} OCPP ${
300 chargingStation.stationInfo.ocppVersion
301 } connector id ${connectorId} status transition from '${
302 chargingStation.getConnectorStatus(connectorId)!.status
303 }' to '${status}' is not allowed`,
306 return transitionAllowed
;
309 protected static parseJsonSchemaFile
<T
extends JsonType
>(
310 relativePath
: string,
311 ocppVersion
: OCPPVersion
,
314 ): JSONSchemaType
<T
> {
315 const filePath
= join(dirname(fileURLToPath(import.meta
.url
)), relativePath
);
317 return JSON
.parse(readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
322 error
as NodeJS
.ErrnoException
,
323 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
324 { throwError
: false },
326 return {} as JSONSchemaType
<T
>;
330 protected static getSampledValueTemplate(
331 chargingStation
: ChargingStation
,
333 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
334 phase
?: MeterValuePhase
,
335 ): SampledValueTemplate
| undefined {
336 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
337 if (OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(measurand
) === false) {
339 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
344 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
347 StandardParametersKey
.MeterValuesSampledData
,
348 )?.value
?.includes(measurand
) === false
351 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
352 StandardParametersKey.MeterValuesSampledData
357 const sampledValueTemplates
: SampledValueTemplate
[] =
358 chargingStation
.getConnectorStatus(connectorId
)!.MeterValues
;
361 isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
365 OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(
366 sampledValueTemplates
[index
]?.measurand
??
367 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
371 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
375 sampledValueTemplates
[index
]?.phase
=== phase
&&
376 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
379 StandardParametersKey
.MeterValuesSampledData
,
380 )?.value
?.includes(measurand
) === true
382 return sampledValueTemplates
[index
];
385 !sampledValueTemplates
[index
].phase
&&
386 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
389 StandardParametersKey
.MeterValuesSampledData
,
390 )?.value
?.includes(measurand
) === true
392 return sampledValueTemplates
[index
];
394 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
395 (!sampledValueTemplates
[index
].measurand
||
396 sampledValueTemplates
[index
].measurand
=== measurand
)
398 return sampledValueTemplates
[index
];
401 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
402 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
403 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
404 throw new BaseError(errorMsg
);
407 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
411 protected static getLimitFromSampledValueTemplateCustomValue(
414 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
415 limitationEnabled
: true,
421 limitationEnabled
: true,
426 const parsedInt
= parseInt(value
);
427 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
428 return options
?.limitationEnabled
429 ? Math.min(numberValue
* options
.unitMultiplier
!, limit
)
430 : numberValue
* options
.unitMultiplier
!;
433 private static isIdTagLocalAuthorized(chargingStation
: ChargingStation
, idTag
: string): boolean {
435 chargingStation
.hasIdTags() === true &&
437 chargingStation
.idTagsCache
438 .getIdTags(getIdTagsFile(chargingStation
.stationInfo
)!)
439 ?.find((tag
) => tag
=== idTag
),
444 private static async isIdTagRemoteAuthorized(
445 chargingStation
: ChargingStation
,
448 ): Promise
<boolean> {
449 chargingStation
.getConnectorStatus(connectorId
)!.authorizeIdTag
= idTag
;
452 await chargingStation
.ocppRequestService
.requestHandler
<
455 >(chargingStation
, RequestCommand
.AUTHORIZE
, {
458 )?.idTagInfo
?.status === AuthorizationStatus
.ACCEPTED
462 private static logPrefix
= (
463 ocppVersion
: OCPPVersion
,
468 isNotEmptyString(moduleName
) && isNotEmptyString(methodName
)
469 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
470 : ` OCPP ${ocppVersion} |`;
471 return logPrefix(logMsg
);