1 import fs from
'node:fs';
3 import type { DefinedError
, ErrorObject
, JSONSchemaType
} from
'ajv';
5 import { type ChargingStation
, ChargingStationConfigurationUtils
} from
'../../charging-station';
6 import { BaseError
} from
'../../exception';
9 type ConnectorStatusEnum
,
12 IncomingRequestCommand
,
19 type OCPP16StatusNotificationRequest
,
20 type OCPP20StatusNotificationRequest
,
23 type SampledValueTemplate
,
24 StandardParametersKey
,
25 type StatusNotificationRequest
,
27 import { Constants
} from
'../../utils/Constants';
28 import { FileUtils
} from
'../../utils/FileUtils';
29 import { logger
} from
'../../utils/Logger';
30 import { Utils
} from
'../../utils/Utils';
32 export class OCPPServiceUtils
{
33 protected constructor() {
34 // This is intentional
37 public static ajvErrorsToErrorType(errors
: ErrorObject
[]): ErrorType
{
38 for (const error
of errors
as DefinedError
[]) {
39 switch (error
.keyword
) {
41 return ErrorType
.TYPE_CONSTRAINT_VIOLATION
;
44 return ErrorType
.OCCURRENCE_CONSTRAINT_VIOLATION
;
47 return ErrorType
.PROPERTY_CONSTRAINT_VIOLATION
;
50 return ErrorType
.FORMAT_VIOLATION
;
53 public static getMessageTypeString(messageType
: MessageType
): string {
54 switch (messageType
) {
55 case MessageType
.CALL_MESSAGE
:
57 case MessageType
.CALL_RESULT_MESSAGE
:
59 case MessageType
.CALL_ERROR_MESSAGE
:
66 public static isRequestCommandSupported(
67 chargingStation
: ChargingStation
,
68 command
: RequestCommand
70 const isRequestCommand
= Object.values
<RequestCommand
>(RequestCommand
).includes(command
);
72 isRequestCommand
=== true &&
73 !chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
77 isRequestCommand
=== true &&
78 chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
80 return chargingStation
.stationInfo
?.commandsSupport
?.outgoingCommands
[command
] ?? false;
82 logger
.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`);
86 public static isIncomingRequestCommandSupported(
87 chargingStation
: ChargingStation
,
88 command
: IncomingRequestCommand
90 const isIncomingRequestCommand
=
91 Object.values
<IncomingRequestCommand
>(IncomingRequestCommand
).includes(command
);
93 isIncomingRequestCommand
=== true &&
94 !chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
98 isIncomingRequestCommand
=== true &&
99 chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
101 return chargingStation
.stationInfo
?.commandsSupport
?.incomingCommands
[command
] ?? false;
103 logger
.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`);
107 public static isMessageTriggerSupported(
108 chargingStation
: ChargingStation
,
109 messageTrigger
: MessageTrigger
111 const isMessageTrigger
= Object.values(MessageTrigger
).includes(messageTrigger
);
112 if (isMessageTrigger
=== true && !chargingStation
.stationInfo
?.messageTriggerSupport
) {
114 } else if (isMessageTrigger
=== true && chargingStation
.stationInfo
?.messageTriggerSupport
) {
115 return chargingStation
.stationInfo
?.messageTriggerSupport
[messageTrigger
] ?? false;
118 `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`
123 public static isConnectorIdValid(
124 chargingStation
: ChargingStation
,
125 ocppCommand
: IncomingRequestCommand
,
128 if (connectorId
< 0) {
130 `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector Id ${connectorId}`
137 public static convertDateToISOString
<T
extends JsonType
>(obj
: T
): void {
138 for (const key
in obj
) {
139 if (obj
[key
] instanceof Date) {
140 (obj
as JsonObject
)[key
] = (obj
[key
] as Date).toISOString();
141 } else if (obj
[key
] !== null && typeof obj
[key
] === 'object') {
142 this.convertDateToISOString
<T
>(obj
[key
] as T
);
147 public static buildStatusNotificationRequest(
148 chargingStation
: ChargingStation
,
150 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 protected static parseJsonSchemaFile
<T
extends JsonType
>(
174 ocppVersion
: OCPPVersion
,
177 ): JSONSchemaType
<T
> {
179 return JSON
.parse(fs
.readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
181 FileUtils
.handleFileException(
184 error
as NodeJS
.ErrnoException
,
185 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
186 { throwError
: false }
191 protected static getSampledValueTemplate(
192 chargingStation
: ChargingStation
,
194 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
195 phase
?: MeterValuePhase
196 ): SampledValueTemplate
| undefined {
197 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
198 if (Constants
.SUPPORTED_MEASURANDS
.includes(measurand
) === false) {
200 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
205 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
206 ChargingStationConfigurationUtils
.getConfigurationKey(
208 StandardParametersKey
.MeterValuesSampledData
209 )?.value
?.includes(measurand
) === false
212 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
213 StandardParametersKey.MeterValuesSampledData
218 const sampledValueTemplates
: SampledValueTemplate
[] =
219 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
222 Utils
.isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
226 Constants
.SUPPORTED_MEASURANDS
.includes(
227 sampledValueTemplates
[index
]?.measurand
??
228 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
232 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
236 sampledValueTemplates
[index
]?.phase
=== phase
&&
237 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
238 ChargingStationConfigurationUtils
.getConfigurationKey(
240 StandardParametersKey
.MeterValuesSampledData
241 )?.value
?.includes(measurand
) === true
243 return sampledValueTemplates
[index
];
246 !sampledValueTemplates
[index
].phase
&&
247 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
248 ChargingStationConfigurationUtils
.getConfigurationKey(
250 StandardParametersKey
.MeterValuesSampledData
251 )?.value
?.includes(measurand
) === true
253 return sampledValueTemplates
[index
];
255 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
256 (!sampledValueTemplates
[index
].measurand
||
257 sampledValueTemplates
[index
].measurand
=== measurand
)
259 return sampledValueTemplates
[index
];
262 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
263 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
264 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
265 throw new BaseError(errorMsg
);
268 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
272 protected static getLimitFromSampledValueTemplateCustomValue(
275 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
276 limitationEnabled
: true,
280 options
.limitationEnabled
= options
?.limitationEnabled
?? true;
281 options
.unitMultiplier
= options
?.unitMultiplier
?? 1;
282 const parsedInt
= parseInt(value
);
283 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
284 return options
?.limitationEnabled
285 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
286 : numberValue
* options
.unitMultiplier
;
289 private static logPrefix
= (
290 ocppVersion
: OCPPVersion
,
295 Utils
.isNotEmptyString(moduleName
) && Utils
.isNotEmptyString(methodName
)
296 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
297 : ` OCPP ${ocppVersion} |`;
298 return Utils
.logPrefix(logMsg
);