1 import fs from
'node:fs';
3 import type { DefinedError
, ErrorObject
, JSONSchemaType
} from
'ajv';
5 import { OCPP16Constants
, OCPP20Constants
} from
'./internal';
6 import { type ChargingStation
, ChargingStationConfigurationUtils
} from
'../../charging-station';
7 import { BaseError
} from
'../../exception';
10 type ConnectorStatusEnum
,
13 IncomingRequestCommand
,
20 type OCPP16StatusNotificationRequest
,
21 type OCPP20StatusNotificationRequest
,
24 type SampledValueTemplate
,
25 StandardParametersKey
,
26 type StatusNotificationRequest
,
27 type StatusNotificationResponse
,
29 import { Constants
, FileUtils
, Utils
, logger
} from
'../../utils';
31 export class OCPPServiceUtils
{
32 protected constructor() {
33 // This is intentional
36 public static ajvErrorsToErrorType(errors
: ErrorObject
[]): ErrorType
{
37 for (const error
of errors
as DefinedError
[]) {
38 switch (error
.keyword
) {
40 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
43 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
46 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
49 return ErrorType
.FORMAT_VIOLATION
;
52 public static getMessageTypeString(messageType
: MessageType
): string {
53 switch (messageType
) {
54 case MessageType
.CALL_MESSAGE
:
56 case MessageType
.CALL_RESULT_MESSAGE
:
58 case MessageType
.CALL_ERROR_MESSAGE
:
65 public static isRequestCommandSupported(
66 chargingStation
: ChargingStation
,
67 command
: RequestCommand
69 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
71 isRequestCommand
=== true &&
72 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
76 isRequestCommand
=== true &&
77 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
79 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
] ?? false;
81 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
85 public static isIncomingRequestCommandSupported(
86 chargingStation
: ChargingStation
,
87 command
: IncomingRequestCommand
89 const isIncomingRequestCommand
=
90 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
92 isIncomingRequestCommand
=== true &&
93 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
97 isIncomingRequestCommand
=== true &&
98 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
100 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
] ?? false;
102 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
106 public static isMessageTriggerSupported(
107 chargingStation
: ChargingStation
,
108 messageTrigger
: MessageTrigger
110 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
111 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
113 } else if (isMessageTrigger
=== true && chargingStation
.stationInfo
?.messageTriggerSupport
) {
114 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
] ?? false;
117 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`
122 public static isConnectorIdValid(
123 chargingStation
: ChargingStation
,
124 ocppCommand
: IncomingRequestCommand
,
127 if (connectorId
< 0) {
129 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`
136 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
137 for (const key
in obj
) {
138 if (obj
[key
] instanceof Date) {
139 (obj
as JsonObject
)[key
] = (obj
[key
] as Date).toISOString();
140 } else if (obj
[key
] !== null && typeof obj
[key
] === 'object') {
141 OCPPServiceUtils
.convertDateToISOString
<T
>(obj
[key
] as T
);
146 public static buildStatusNotificationRequest(
147 chargingStation
: ChargingStation
,
149 status: ConnectorStatusEnum
,
151 ): StatusNotificationRequest
{
152 switch (chargingStation
.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
) {
153 case OCPPVersion
.VERSION_16
:
157 errorCode
: ChargePointErrorCode
.NO_ERROR
,
158 } as OCPP16StatusNotificationRequest
;
159 case OCPPVersion
.VERSION_20
:
160 case OCPPVersion
.VERSION_201
:
162 timestamp
: new Date(),
163 connectorStatus
: status,
166 } as OCPP20StatusNotificationRequest
;
168 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
172 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
173 if (!chargingStation
.heartbeatSetInterval
) {
174 chargingStation
.startHeartbeat();
175 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
176 chargingStation
.restartHeartbeat();
180 public static async sendAndSetConnectorStatus(
181 chargingStation
: ChargingStation
,
183 status: ConnectorStatusEnum
,
186 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
187 await chargingStation
.ocppRequestService
.requestHandler
<
188 StatusNotificationRequest
,
189 StatusNotificationResponse
192 RequestCommand
.STATUS_NOTIFICATION
,
193 OCPPServiceUtils
.buildStatusNotificationRequest(chargingStation
, connectorId
, status, evseId
)
195 chargingStation
.getConnectorStatus(connectorId
).status = status;
198 protected static checkConnectorStatusTransition(
199 chargingStation
: ChargingStation
,
201 status: ConnectorStatusEnum
203 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
).status;
204 let transitionAllowed
= false;
205 switch (chargingStation
.stationInfo
.ocppVersion
) {
206 case OCPPVersion
.VERSION_16
:
209 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
210 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
213 transitionAllowed
= true;
215 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
216 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
219 transitionAllowed
= true;
222 case OCPPVersion
.VERSION_20
:
223 case OCPPVersion
.VERSION_201
:
226 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
227 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
230 transitionAllowed
= true;
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
>(
259 ocppVersion
: OCPPVersion
,
262 ): JSONSchemaType
<T
> {
264 return JSON
.parse(fs
.readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
266 FileUtils
.handleFileException(
269 error
as NodeJS
.ErrnoException
,
270 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
271 { throwError
: false }
276 protected static getSampledValueTemplate(
277 chargingStation
: ChargingStation
,
279 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
280 phase
?: MeterValuePhase
281 ): SampledValueTemplate
| undefined {
282 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
283 if (Constants
.SUPPORTED_MEASURANDS
.includes(measurand
) === false) {
285 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
290 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
291 ChargingStationConfigurationUtils
.getConfigurationKey(
293 StandardParametersKey
.MeterValuesSampledData
294 )?.value
?.includes(measurand
) === false
297 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
298 StandardParametersKey.MeterValuesSampledData
303 const sampledValueTemplates
: SampledValueTemplate
[] =
304 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
307 Utils
.isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
311 Constants
.SUPPORTED_MEASURANDS
.includes(
312 sampledValueTemplates
[index
]?.measurand
??
313 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
317 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
321 sampledValueTemplates
[index
]?.phase
=== phase
&&
322 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
323 ChargingStationConfigurationUtils
.getConfigurationKey(
325 StandardParametersKey
.MeterValuesSampledData
326 )?.value
?.includes(measurand
) === true
328 return sampledValueTemplates
[index
];
331 !sampledValueTemplates
[index
].phase
&&
332 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
333 ChargingStationConfigurationUtils
.getConfigurationKey(
335 StandardParametersKey
.MeterValuesSampledData
336 )?.value
?.includes(measurand
) === true
338 return sampledValueTemplates
[index
];
340 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
341 (!sampledValueTemplates
[index
].measurand
||
342 sampledValueTemplates
[index
].measurand
=== measurand
)
344 return sampledValueTemplates
[index
];
347 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
348 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
349 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
350 throw new BaseError(errorMsg
);
353 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
357 protected static getLimitFromSampledValueTemplateCustomValue(
360 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
361 limitationEnabled
: true,
365 options
.limitationEnabled
= options
?.limitationEnabled
?? true;
366 options
.unitMultiplier
= options
?.unitMultiplier
?? 1;
367 const parsedInt
= parseInt(value
);
368 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
369 return options
?.limitationEnabled
370 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
371 : numberValue
* options
.unitMultiplier
;
374 private static logPrefix
= (
375 ocppVersion
: OCPPVersion
,
380 Utils
.isNotEmptyString(moduleName
) && Utils
.isNotEmptyString(methodName
)
381 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
382 : ` OCPP ${ocppVersion} |`;
383 return Utils
.logPrefix(logMsg
);