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';
7 import { OCPP16Constants
} from
'./1.6/OCPP16Constants';
8 import { OCPP20Constants
} from
'./2.0/OCPP20Constants';
9 import { OCPPConstants
} from
'./OCPPConstants';
10 import { type ChargingStation
, ChargingStationConfigurationUtils
} from
'../../charging-station';
11 import { BaseError
} from
'../../exception';
14 type ConnectorStatusEnum
,
17 IncomingRequestCommand
,
24 type OCPP16StatusNotificationRequest
,
25 type OCPP20StatusNotificationRequest
,
28 type SampledValueTemplate
,
29 StandardParametersKey
,
30 type StatusNotificationRequest
,
31 type StatusNotificationResponse
,
41 export class OCPPServiceUtils
{
42 protected constructor() {
43 // This is intentional
46 public static ajvErrorsToErrorType(errors
: ErrorObject
[]): ErrorType
{
47 for (const error
of errors
as DefinedError
[]) {
48 switch (error
.keyword
) {
50 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
53 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
56 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
59 return ErrorType
.FORMAT_VIOLATION
;
62 public static getMessageTypeString(messageType
: MessageType
): string {
63 switch (messageType
) {
64 case MessageType
.CALL_MESSAGE
:
66 case MessageType
.CALL_RESULT_MESSAGE
:
68 case MessageType
.CALL_ERROR_MESSAGE
:
75 public static isRequestCommandSupported(
76 chargingStation
: ChargingStation
,
77 command
: RequestCommand
,
79 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
81 isRequestCommand
=== true &&
82 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
86 isRequestCommand
=== true &&
87 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
89 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
] ?? false;
91 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
95 public static isIncomingRequestCommandSupported(
96 chargingStation
: ChargingStation
,
97 command
: IncomingRequestCommand
,
99 const isIncomingRequestCommand
=
100 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
102 isIncomingRequestCommand
=== true &&
103 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
107 isIncomingRequestCommand
=== true &&
108 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
110 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
] ?? false;
112 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
116 public static isMessageTriggerSupported(
117 chargingStation
: ChargingStation
,
118 messageTrigger
: MessageTrigger
,
120 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
121 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
123 } else if (isMessageTrigger
=== true && chargingStation
.stationInfo
?.messageTriggerSupport
) {
124 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
] ?? false;
127 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`,
132 public static isConnectorIdValid(
133 chargingStation
: ChargingStation
,
134 ocppCommand
: IncomingRequestCommand
,
137 if (connectorId
< 0) {
139 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`,
146 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
147 for (const key
in obj
) {
148 if (obj
[key
] instanceof Date) {
149 (obj
as JsonObject
)[key
] = (obj
[key
] as Date).toISOString();
150 } else if (obj
[key
] !== null && typeof obj
[key
] === 'object') {
151 OCPPServiceUtils
.convertDateToISOString
<T
>(obj
[key
] as T
);
156 public static buildStatusNotificationRequest(
157 chargingStation
: ChargingStation
,
159 status: ConnectorStatusEnum
,
161 ): StatusNotificationRequest
{
162 switch (chargingStation
.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
) {
163 case OCPPVersion
.VERSION_16
:
167 errorCode
: ChargePointErrorCode
.NO_ERROR
,
168 } as OCPP16StatusNotificationRequest
;
169 case OCPPVersion
.VERSION_20
:
170 case OCPPVersion
.VERSION_201
:
172 timestamp
: new Date(),
173 connectorStatus
: status,
176 } as OCPP20StatusNotificationRequest
;
178 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
182 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
183 if (!chargingStation
.heartbeatSetInterval
) {
184 chargingStation
.startHeartbeat();
185 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
186 chargingStation
.restartHeartbeat();
190 public static async sendAndSetConnectorStatus(
191 chargingStation
: ChargingStation
,
193 status: ConnectorStatusEnum
,
195 options
: { send
: boolean } = { send
: true },
197 options
= { send
: true, ...options
};
199 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
200 await chargingStation
.ocppRequestService
.requestHandler
<
201 StatusNotificationRequest
,
202 StatusNotificationResponse
205 RequestCommand
.STATUS_NOTIFICATION
,
206 OCPPServiceUtils
.buildStatusNotificationRequest(
214 chargingStation
.getConnectorStatus(connectorId
).status = status;
217 protected static checkConnectorStatusTransition(
218 chargingStation
: ChargingStation
,
220 status: ConnectorStatusEnum
,
222 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
).status;
223 let transitionAllowed
= false;
224 switch (chargingStation
.stationInfo
.ocppVersion
) {
225 case OCPPVersion
.VERSION_16
:
227 (connectorId
=== 0 &&
228 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
229 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
232 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
233 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
236 transitionAllowed
= true;
239 case OCPPVersion
.VERSION_20
:
240 case OCPPVersion
.VERSION_201
:
242 (connectorId
=== 0 &&
243 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
244 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
247 OCPP20Constants
.ConnectorStatusTransitions
.findIndex(
248 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status,
251 transitionAllowed
= true;
256 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
257 `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`,
260 if (transitionAllowed
=== false) {
262 `${chargingStation.logPrefix()} OCPP ${
263 chargingStation.stationInfo.ocppVersion
264 } connector id ${connectorId} status transition from '${
265 chargingStation.getConnectorStatus(connectorId).status
266 }' to '${status}' is not allowed`,
269 return transitionAllowed
;
272 protected static parseJsonSchemaFile
<T
extends JsonType
>(
273 relativePath
: string,
274 ocppVersion
: OCPPVersion
,
277 ): JSONSchemaType
<T
> {
278 const filePath
= join(dirname(fileURLToPath(import.meta
.url
)), relativePath
);
280 return JSON
.parse(readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
285 error
as NodeJS
.ErrnoException
,
286 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
287 { throwError
: false },
292 protected static getSampledValueTemplate(
293 chargingStation
: ChargingStation
,
295 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
296 phase
?: MeterValuePhase
,
297 ): SampledValueTemplate
| undefined {
298 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
299 if (OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(measurand
) === false) {
301 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
306 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
307 ChargingStationConfigurationUtils
.getConfigurationKey(
309 StandardParametersKey
.MeterValuesSampledData
,
310 )?.value
?.includes(measurand
) === false
313 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
314 StandardParametersKey.MeterValuesSampledData
319 const sampledValueTemplates
: SampledValueTemplate
[] =
320 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
323 isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
327 OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(
328 sampledValueTemplates
[index
]?.measurand
??
329 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
333 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
337 sampledValueTemplates
[index
]?.phase
=== phase
&&
338 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
339 ChargingStationConfigurationUtils
.getConfigurationKey(
341 StandardParametersKey
.MeterValuesSampledData
,
342 )?.value
?.includes(measurand
) === true
344 return sampledValueTemplates
[index
];
347 !sampledValueTemplates
[index
].phase
&&
348 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
349 ChargingStationConfigurationUtils
.getConfigurationKey(
351 StandardParametersKey
.MeterValuesSampledData
,
352 )?.value
?.includes(measurand
) === true
354 return sampledValueTemplates
[index
];
356 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
357 (!sampledValueTemplates
[index
].measurand
||
358 sampledValueTemplates
[index
].measurand
=== measurand
)
360 return sampledValueTemplates
[index
];
363 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
364 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
365 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
366 throw new BaseError(errorMsg
);
369 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`,
373 protected static getLimitFromSampledValueTemplateCustomValue(
376 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
377 limitationEnabled
: true,
383 limitationEnabled
: true,
388 const parsedInt
= parseInt(value
);
389 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
390 return options
?.limitationEnabled
391 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
392 : numberValue
* options
.unitMultiplier
;
395 private static logPrefix
= (
396 ocppVersion
: OCPPVersion
,
401 isNotEmptyString(moduleName
) && isNotEmptyString(methodName
)
402 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
403 : ` OCPP ${ocppVersion} |`;
404 return logPrefix(logMsg
);