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
150 ): StatusNotificationRequest
{
151 switch (chargingStation
.stationInfo
.ocppVersion
?? OCPPVersion
.VERSION_16
) {
152 case OCPPVersion
.VERSION_16
:
156 errorCode
: ChargePointErrorCode
.NO_ERROR
,
157 } as OCPP16StatusNotificationRequest
;
158 case OCPPVersion
.VERSION_20
:
159 case OCPPVersion
.VERSION_201
:
161 timestamp
: new Date(),
162 connectorStatus
: status,
165 } as OCPP20StatusNotificationRequest
;
167 throw new BaseError('Cannot build status notification payload: OCPP version not supported');
171 public static startHeartbeatInterval(chargingStation
: ChargingStation
, interval
: number): void {
172 if (!chargingStation
.heartbeatSetInterval
) {
173 chargingStation
.startHeartbeat();
174 } else if (chargingStation
.getHeartbeatInterval() !== interval
) {
175 chargingStation
.restartHeartbeat();
179 public static async sendAndSetConnectorStatus(
180 chargingStation
: ChargingStation
,
182 status: ConnectorStatusEnum
184 OCPPServiceUtils
.checkConnectorStatusTransition(chargingStation
, connectorId
, status);
185 await chargingStation
.ocppRequestService
.requestHandler
<
186 StatusNotificationRequest
,
187 StatusNotificationResponse
190 RequestCommand
.STATUS_NOTIFICATION
,
191 OCPPServiceUtils
.buildStatusNotificationRequest(chargingStation
, connectorId
, status)
193 chargingStation
.getConnectorStatus(connectorId
).status = status;
196 protected static checkConnectorStatusTransition(
197 chargingStation
: ChargingStation
,
199 status: ConnectorStatusEnum
201 const fromStatus
= chargingStation
.getConnectorStatus(connectorId
).status;
202 let transitionAllowed
= false;
203 switch (chargingStation
.stationInfo
.ocppVersion
) {
204 case OCPPVersion
.VERSION_16
:
207 OCPP16Constants
.ChargePointStatusChargingStationTransitions
.findIndex(
208 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
211 transitionAllowed
= true;
213 OCPP16Constants
.ChargePointStatusConnectorTransitions
.findIndex(
214 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
217 transitionAllowed
= true;
220 case OCPPVersion
.VERSION_20
:
221 case OCPPVersion
.VERSION_201
:
224 OCPP20Constants
.ChargingStationStatusTransitions
.findIndex(
225 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
228 transitionAllowed
= true;
230 OCPP20Constants
.ConnectorStatusTransitions
.findIndex(
231 (transition
) => transition
.from
=== fromStatus
&& transition
.to
=== status
234 transitionAllowed
= true;
239 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
240 `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`
243 if (transitionAllowed
=== false) {
245 `${chargingStation.logPrefix()} OCPP ${
246 chargingStation.stationInfo.ocppVersion
247 } connector id ${connectorId} status transition from '${
248 chargingStation.getConnectorStatus(connectorId).status
249 }' to '${status}' is not allowed`
252 return transitionAllowed
;
255 protected static parseJsonSchemaFile
<T
extends JsonType
>(
257 ocppVersion
: OCPPVersion
,
260 ): JSONSchemaType
<T
> {
262 return JSON
.parse(fs
.readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
264 FileUtils
.handleFileException(
267 error
as NodeJS
.ErrnoException
,
268 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
269 { throwError
: false }
274 protected static getSampledValueTemplate(
275 chargingStation
: ChargingStation
,
277 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
278 phase
?: MeterValuePhase
279 ): SampledValueTemplate
| undefined {
280 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
281 if (Constants
.SUPPORTED_MEASURANDS
.includes(measurand
) === false) {
283 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
288 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
289 ChargingStationConfigurationUtils
.getConfigurationKey(
291 StandardParametersKey
.MeterValuesSampledData
292 )?.value
?.includes(measurand
) === false
295 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${
296 StandardParametersKey.MeterValuesSampledData
301 const sampledValueTemplates
: SampledValueTemplate
[] =
302 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
305 Utils
.isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
309 Constants
.SUPPORTED_MEASURANDS
.includes(
310 sampledValueTemplates
[index
]?.measurand
??
311 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
315 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
319 sampledValueTemplates
[index
]?.phase
=== phase
&&
320 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
321 ChargingStationConfigurationUtils
.getConfigurationKey(
323 StandardParametersKey
.MeterValuesSampledData
324 )?.value
?.includes(measurand
) === true
326 return sampledValueTemplates
[index
];
329 !sampledValueTemplates
[index
].phase
&&
330 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
331 ChargingStationConfigurationUtils
.getConfigurationKey(
333 StandardParametersKey
.MeterValuesSampledData
334 )?.value
?.includes(measurand
) === true
336 return sampledValueTemplates
[index
];
338 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
339 (!sampledValueTemplates
[index
].measurand
||
340 sampledValueTemplates
[index
].measurand
=== measurand
)
342 return sampledValueTemplates
[index
];
345 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
346 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`;
347 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
348 throw new BaseError(errorMsg
);
351 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`
355 protected static getLimitFromSampledValueTemplateCustomValue(
358 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
359 limitationEnabled
: true,
363 options
.limitationEnabled
= options
?.limitationEnabled
?? true;
364 options
.unitMultiplier
= options
?.unitMultiplier
?? 1;
365 const parsedInt
= parseInt(value
);
366 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
367 return options
?.limitationEnabled
368 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
369 : numberValue
* options
.unitMultiplier
;
372 private static logPrefix
= (
373 ocppVersion
: OCPPVersion
,
378 Utils
.isNotEmptyString(moduleName
) && Utils
.isNotEmptyString(methodName
)
379 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
380 : ` OCPP ${ocppVersion} |`;
381 return Utils
.logPrefix(logMsg
);