1 import fs from
'node:fs';
2 import path 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
,
33 import { Utils
, handleFileException
, logger
} from
'../../utils';
35 export class OCPPServiceUtils
{
36 protected constructor() {
37 // This is intentional
40 public static ajvErrorsToErrorType(errors
: ErrorObject
[]): ErrorType
{
41 for (const error
of errors
as DefinedError
[]) {
42 switch (error
.keyword
) {
44 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
47 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
50 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
53 return ErrorType
.FORMAT_VIOLATION
;
56 public static getMessageTypeString(messageType
: MessageType
): string {
57 switch (messageType
) {
58 case MessageType
.CALL_MESSAGE
:
60 case MessageType
.CALL_RESULT_MESSAGE
:
62 case MessageType
.CALL_ERROR_MESSAGE
:
69 public static isRequestCommandSupported(
70 chargingStation
: ChargingStation
,
71 command
: RequestCommand
73 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
75 isRequestCommand
=== true &&
76 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
80 isRequestCommand
=== true &&
81 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
83 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
] ?? false;
85 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
89 public static isIncomingRequestCommandSupported(
90 chargingStation
: ChargingStation
,
91 command
: IncomingRequestCommand
93 const isIncomingRequestCommand
=
94 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
96 isIncomingRequestCommand
=== true &&
97 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
101 isIncomingRequestCommand
=== true &&
102 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
104 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
] ?? false;
106 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
110 public static isMessageTriggerSupported(
111 chargingStation
: ChargingStation
,
112 messageTrigger
: MessageTrigger
114 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
115 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
117 } else if (isMessageTrigger
=== true && chargingStation
.stationInfo
?.messageTriggerSupport
) {
118 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
] ?? false;
121 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`
126 public static isConnectorIdValid(
127 chargingStation
: ChargingStation
,
128 ocppCommand
: IncomingRequestCommand
,
131 if (connectorId
< 0) {
133 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`
140 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
141 for (const key
in obj
) {
142 if (obj
[key
] instanceof Date) {
143 (obj
as JsonObject
)[key
] = (obj
[key
] as Date).toISOString();
144 } else if (obj
[key
] !== null && typeof obj
[key
] === 'object') {
145 OCPPServiceUtils
.convertDateToISOString
<T
>(obj
[key
] as T
);
150 public static buildStatusNotificationRequest(
151 chargingStation
: ChargingStation
,
153 status: ConnectorStatusEnum
,
155 ): StatusNotificationRequest
{
156 switch (chargingStation
.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
) {
157 case OCPPVersion
.VERSION_16
:
161 errorCode
: ChargePointErrorCode
.NO_ERROR
,
162 } as OCPP16StatusNotificationRequest
;
163 case OCPPVersion
.VERSION_20
:
164 case OCPPVersion
.VERSION_201
:
166 timestamp
: new Date(),
167 connectorStatus
: status,
170 } as OCPP20StatusNotificationRequest
;
172 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
176 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
177 if (!chargingStation
.heartbeatSetInterval
) {
178 chargingStation
.startHeartbeat();
179 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
180 chargingStation
.restartHeartbeat();
184 public static async sendAndSetConnectorStatus(
185 chargingStation
: ChargingStation
,
187 status: ConnectorStatusEnum
,
190 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
191 await chargingStation
.ocppRequestService
.requestHandler
<
192 StatusNotificationRequest
,
193 StatusNotificationResponse
196 RequestCommand
.STATUS_NOTIFICATION
,
197 OCPPServiceUtils
.buildStatusNotificationRequest(chargingStation
, connectorId
, status, evseId
)
199 chargingStation
.getConnectorStatus(connectorId
).status = status;
202 protected static checkConnectorStatusTransition(
203 chargingStation
: ChargingStation
,
205 status: ConnectorStatusEnum
207 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
).status;
208 let transitionAllowed
= false;
209 switch (chargingStation
.stationInfo
.ocppVersion
) {
210 case OCPPVersion
.VERSION_16
:
212 (connectorId
=== 0 &&
213 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
214 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
217 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
218 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
221 transitionAllowed
= true;
224 case OCPPVersion
.VERSION_20
:
225 case OCPPVersion
.VERSION_201
:
227 (connectorId
=== 0 &&
228 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
229 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
232 OCPP20Constants
.ConnectorStatusTransitions
.findIndex(
233 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
236 transitionAllowed
= true;
241 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
242 `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`
245 if (transitionAllowed
=== false) {
247 `${chargingStation.logPrefix()} OCPP ${
248 chargingStation.stationInfo.ocppVersion
249 } connector id ${connectorId} status transition from '${
250 chargingStation.getConnectorStatus(connectorId).status
251 }' to '${status}' is not allowed`
254 return transitionAllowed
;
257 protected static parseJsonSchemaFile
<T
extends JsonType
>(
258 relativePath
: string,
259 ocppVersion
: OCPPVersion
,
262 ): JSONSchemaType
<T
> {
263 const filePath
= path
.join(path
.dirname(fileURLToPath(import.meta
.url
)), relativePath
);
265 return JSON
.parse(fs
.readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
270 error
as NodeJS
.ErrnoException
,
271 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
272 { throwError
: false }
277 protected static getSampledValueTemplate(
278 chargingStation
: ChargingStation
,
280 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
281 phase
?: MeterValuePhase
282 ): SampledValueTemplate
| undefined {
283 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
284 if (OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(measurand
) === false) {
286 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
291 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
292 ChargingStationConfigurationUtils
.getConfigurationKey(
294 StandardParametersKey
.MeterValuesSampledData
295 )?.value
?.includes(measurand
) === false
298 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
299 StandardParametersKey.MeterValuesSampledData
304 const sampledValueTemplates
: SampledValueTemplate
[] =
305 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
308 Utils
.isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
312 OCPPConstants
.OCPP_MEASURANDS_SUPPORTED
.includes(
313 sampledValueTemplates
[index
]?.measurand
??
314 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
318 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
322 sampledValueTemplates
[index
]?.phase
=== phase
&&
323 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
324 ChargingStationConfigurationUtils
.getConfigurationKey(
326 StandardParametersKey
.MeterValuesSampledData
327 )?.value
?.includes(measurand
) === true
329 return sampledValueTemplates
[index
];
332 !sampledValueTemplates
[index
].phase
&&
333 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
334 ChargingStationConfigurationUtils
.getConfigurationKey(
336 StandardParametersKey
.MeterValuesSampledData
337 )?.value
?.includes(measurand
) === true
339 return sampledValueTemplates
[index
];
341 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
342 (!sampledValueTemplates
[index
].measurand
||
343 sampledValueTemplates
[index
].measurand
=== measurand
)
345 return sampledValueTemplates
[index
];
348 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
349 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
350 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
351 throw new BaseError(errorMsg
);
354 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
358 protected static getLimitFromSampledValueTemplateCustomValue(
361 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
362 limitationEnabled
: true,
368 limitationEnabled
: true,
373 const parsedInt
= parseInt(value
);
374 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
375 return options
?.limitationEnabled
376 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
377 : numberValue
* options
.unitMultiplier
;
380 private static logPrefix
= (
381 ocppVersion
: OCPPVersion
,
386 Utils
.isNotEmptyString(moduleName
) && Utils
.isNotEmptyString(methodName
)
387 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
388 : ` OCPP ${ocppVersion} |`;
389 return Utils
.logPrefix(logMsg
);