1 import fs from
'node:fs';
3 import type { DefinedError
, ErrorObject
, JSONSchemaType
} from
'ajv';
5 import BaseError from
'../../exception/BaseError';
6 import { FileType
} from
'../../types/FileType';
7 import type { JsonObject
, JsonType
} from
'../../types/JsonType';
8 import type { SampledValueTemplate
} from
'../../types/MeasurandPerPhaseSampledValueTemplates';
9 import type { OCPP16StatusNotificationRequest
} from
'../../types/ocpp/1.6/Requests';
10 import type { OCPP20StatusNotificationRequest
} from
'../../types/ocpp/2.0/Requests';
11 import { ChargePointErrorCode
} from
'../../types/ocpp/ChargePointErrorCode';
12 import { StandardParametersKey
} from
'../../types/ocpp/Configuration';
13 import type { ConnectorStatusEnum
} from
'../../types/ocpp/ConnectorStatusEnum';
14 import { ErrorType
} from
'../../types/ocpp/ErrorType';
15 import { MessageType
} from
'../../types/ocpp/MessageType';
16 import { MeterValueMeasurand
, type MeterValuePhase
} from
'../../types/ocpp/MeterValues';
17 import { OCPPVersion
} from
'../../types/ocpp/OCPPVersion';
19 IncomingRequestCommand
,
22 type StatusNotificationRequest
,
23 } from
'../../types/ocpp/Requests';
24 import Constants from
'../../utils/Constants';
25 import FileUtils from
'../../utils/FileUtils';
26 import logger from
'../../utils/Logger';
27 import Utils from
'../../utils/Utils';
28 import type ChargingStation from
'../ChargingStation';
29 import { ChargingStationConfigurationUtils
} from
'../ChargingStationConfigurationUtils';
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 this.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 protected static parseJsonSchemaFile
<T
extends JsonType
>(
173 ocppVersion
: OCPPVersion
,
176 ): JSONSchemaType
<T
> {
178 return JSON
.parse(fs
.readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
180 FileUtils
.handleFileException(
183 error
as NodeJS
.ErrnoException
,
184 OCPPServiceUtils
.logPrefix(ocppVersion
, moduleName
, methodName
),
185 { throwError
: false }
190 protected static getSampledValueTemplate(
191 chargingStation
: ChargingStation
,
193 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
194 phase
?: MeterValuePhase
195 ): SampledValueTemplate
| undefined {
196 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
197 if (Constants
.SUPPORTED_MEASURANDS
.includes(measurand
) === false) {
199 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
204 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
205 ChargingStationConfigurationUtils
.getConfigurationKey(
207 StandardParametersKey
.MeterValuesSampledData
208 )?.value
?.includes(measurand
) === false
211 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
212 StandardParametersKey.MeterValuesSampledData
217 const sampledValueTemplates
: SampledValueTemplate
[] =
218 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
221 Utils
.isNotEmptyArray(sampledValueTemplates
) === true && index
< sampledValueTemplates
.length
;
225 Constants
.SUPPORTED_MEASURANDS
.includes(
226 sampledValueTemplates
[index
]?.measurand
??
227 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
231 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
235 sampledValueTemplates
[index
]?.phase
=== phase
&&
236 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
237 ChargingStationConfigurationUtils
.getConfigurationKey(
239 StandardParametersKey
.MeterValuesSampledData
240 )?.value
?.includes(measurand
) === true
242 return sampledValueTemplates
[index
];
245 !sampledValueTemplates
[index
].phase
&&
246 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
247 ChargingStationConfigurationUtils
.getConfigurationKey(
249 StandardParametersKey
.MeterValuesSampledData
250 )?.value
?.includes(measurand
) === true
252 return sampledValueTemplates
[index
];
254 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
255 (!sampledValueTemplates
[index
].measurand
||
256 sampledValueTemplates
[index
].measurand
=== measurand
)
258 return sampledValueTemplates
[index
];
261 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
262 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
263 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
264 throw new BaseError(errorMsg
);
267 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
271 protected static getLimitFromSampledValueTemplateCustomValue(
274 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
275 limitationEnabled
: true,
279 options
.limitationEnabled
= options
?.limitationEnabled
?? true;
280 options
.unitMultiplier
= options
?.unitMultiplier
?? 1;
281 const parsedInt
= parseInt(value
);
282 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
283 return options
?.limitationEnabled
284 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
285 : numberValue
* options
.unitMultiplier
;
288 private static logPrefix
= (
289 ocppVersion
: OCPPVersion
,
294 Utils
.isNotEmptyString(moduleName
) && Utils
.isNotEmptyString(methodName
)
295 ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
296 : ` OCPP ${ocppVersion} |`;
297 return Utils
.logPrefix(logMsg
);