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
[] | null | undefined): ErrorType
{
52 if (isNotEmptyArray(errors
) === true) {
53 for (const error
of errors
as DefinedError
[]) {
54 switch (error
.keyword
) {
56 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
59 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
62 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
66 return ErrorType
.FORMAT_VIOLATION
;
69 public static getMessageTypeString(messageType
: MessageType
): string {
70 switch (messageType
) {
71 case MessageType
.CALL_MESSAGE
:
73 case MessageType
.CALL_RESULT_MESSAGE
:
75 case MessageType
.CALL_ERROR_MESSAGE
:
82 public static isRequestCommandSupported(
83 chargingStation
: ChargingStation
,
84 command
: RequestCommand
,
86 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
88 isRequestCommand
=== true &&
89 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
93 isRequestCommand
=== true &&
94 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
?.[command
]
96 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
];
98 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
102 public static isIncomingRequestCommandSupported(
103 chargingStation
: ChargingStation
,
104 command
: IncomingRequestCommand
,
106 const isIncomingRequestCommand
=
107 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
109 isIncomingRequestCommand
=== true &&
110 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
114 isIncomingRequestCommand
=== true &&
115 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
?.[command
]
117 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
];
119 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
123 public static isMessageTriggerSupported(
124 chargingStation
: ChargingStation
,
125 messageTrigger
: MessageTrigger
,
127 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
128 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
131 isMessageTrigger
=== true &&
132 chargingStation
.stationInfo
?.messageTriggerSupport
?.[messageTrigger
]
134 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
];
137 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`,
142 public static isConnectorIdValid(
143 chargingStation
: ChargingStation
,
144 ocppCommand
: IncomingRequestCommand
,
147 if (connectorId
< 0) {
149 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`,
156 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
157 for (const key
in obj
) {
158 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
159 if (isDate(obj
![key
])) {
160 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
161 (obj
![key
] as string) = (obj
![key
] as Date).toISOString();
162 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
163 } else if (obj
![key
] !== null && typeof obj
![key
] === 'object') {
164 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
165 OCPPServiceUtils
.convertDateToISOString
<T
>(obj
![key
] as T
);
170 public static buildStatusNotificationRequest(
171 chargingStation
: ChargingStation
,
173 status: ConnectorStatusEnum
,
175 ): StatusNotificationRequest
{
176 switch (chargingStation
.stationInfo
?.ocppVersion
) {
177 case OCPPVersion
.VERSION_16
:
181 errorCode
: ChargePointErrorCode
.NO_ERROR
,
182 } as OCPP16StatusNotificationRequest
;
183 case OCPPVersion
.VERSION_20
:
184 case OCPPVersion
.VERSION_201
:
186 timestamp
: new Date(),
187 connectorStatus
: status,
190 } as OCPP20StatusNotificationRequest
;
192 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
196 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
197 if (!chargingStation
.heartbeatSetInterval
) {
198 chargingStation
.startHeartbeat();
199 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
200 chargingStation
.restartHeartbeat();
204 public static async sendAndSetConnectorStatus(
205 chargingStation
: ChargingStation
,
207 status: ConnectorStatusEnum
,
209 options
?: { send
: boolean },
211 options
= { send
: true, ...options
};
213 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
214 await chargingStation
.ocppRequestService
.requestHandler
<
215 StatusNotificationRequest
,
216 StatusNotificationResponse
219 RequestCommand
.STATUS_NOTIFICATION
,
220 OCPPServiceUtils
.buildStatusNotificationRequest(
228 chargingStation
.getConnectorStatus(connectorId
)!.status = status;
231 public static async isIdTagAuthorized(
232 chargingStation
: ChargingStation
,
235 ): Promise
<boolean> {
237 !chargingStation
.getLocalAuthListEnabled() &&
238 !chargingStation
.stationInfo
?.remoteAuthorization
241 `${chargingStation.logPrefix()} The charging station expects to authorize RFID tags but nor local authorization nor remote authorization are enabled. Misbehavior may occur`,
245 chargingStation
.getLocalAuthListEnabled() === true &&
246 OCPPServiceUtils
.isIdTagLocalAuthorized(chargingStation
, idTag
)
248 const connectorStatus
: ConnectorStatus
= chargingStation
.getConnectorStatus(connectorId
)!;
249 connectorStatus
.localAuthorizeIdTag
= idTag
;
250 connectorStatus
.idTagLocalAuthorized
= true;
252 } else if (chargingStation
.stationInfo
?.remoteAuthorization
) {
253 return await OCPPServiceUtils
.isIdTagRemoteAuthorized(chargingStation
, connectorId
, idTag
);
258 protected static checkConnectorStatusTransition(
259 chargingStation
: ChargingStation
,
261 status: ConnectorStatusEnum
,
263 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
)!.status;
264 let transitionAllowed
= false;
265 switch (chargingStation
.stationInfo
?.ocppVersion
) {
266 case OCPPVersion
.VERSION_16
:
268 (connectorId
=== 0 &&
269 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
270 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
273 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
274 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
277 transitionAllowed
= true;
280 case OCPPVersion
.VERSION_20
:
281 case OCPPVersion
.VERSION_201
:
283 (connectorId
=== 0 &&
284 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
285 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
288 OCPP20Constants
.ConnectorStatusTransitions
.findIndex(
289 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
292 transitionAllowed
= true;
297 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
298 `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo?.ocppVersion} not supported`,
301 if (transitionAllowed
=== false) {
303 `${chargingStation.logPrefix()} OCPP ${chargingStation.stationInfo
304 ?.ocppVersion} connector id ${connectorId} status transition from '${
305 chargingStation.getConnectorStatus(connectorId)!.status
306 }' to '${status}' is not allowed`,
309 return transitionAllowed
;
312 protected static parseJsonSchemaFile
<T
extends JsonType
>(
313 relativePath
: string,
314 ocppVersion
: OCPPVersion
,
317 ): JSONSchemaType
<T
> {
318 const filePath
= join(dirname(fileURLToPath(import.meta
.url
)), relativePath
);
320 return JSON
.parse(readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
325 error
as NodeJS
.ErrnoException
,
326 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
327 { throwError
: false },
329 return {} as JSONSchemaType
<T
>;
333 protected static getSampledValueTemplate(
334 chargingStation
: ChargingStation
,
336 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
337 phase
?: MeterValuePhase
,
338 ): SampledValueTemplate
| undefined {
339 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
340 if (OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(measurand
) === false) {
342 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
347 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
350 StandardParametersKey
.MeterValuesSampledData
,
351 )?.value
?.includes(measurand
) === false
354 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
355 StandardParametersKey.MeterValuesSampledData
360 const sampledValueTemplates
: SampledValueTemplate
[] =
361 chargingStation
.getConnectorStatus(connectorId
)!.MeterValues
;
364 isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
368 OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(
369 sampledValueTemplates
[index
]?.measurand
??
370 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
374 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
378 sampledValueTemplates
[index
]?.phase
=== phase
&&
379 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
382 StandardParametersKey
.MeterValuesSampledData
,
383 )?.value
?.includes(measurand
) === true
385 return sampledValueTemplates
[index
];
388 !sampledValueTemplates
[index
]?.phase
&&
389 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
392 StandardParametersKey
.MeterValuesSampledData
,
393 )?.value
?.includes(measurand
) === true
395 return sampledValueTemplates
[index
];
397 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
398 (!sampledValueTemplates
[index
]?.measurand
||
399 sampledValueTemplates
[index
]?.measurand
=== measurand
)
401 return sampledValueTemplates
[index
];
404 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
405 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
406 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
407 throw new BaseError(errorMsg
);
410 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
414 protected static getLimitFromSampledValueTemplateCustomValue(
417 options
?: { limitationEnabled
?: boolean; unitMultiplier
?: number },
421 limitationEnabled
: true,
426 const parsedInt
= parseInt(value
);
427 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
428 return options
?.limitationEnabled
429 ? 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
);