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
174 ): JSONSchemaType
<T
> {
176 return JSON
.parse(fs
.readFileSync(filePath
, 'utf8')) as JSONSchemaType
<T
>;
178 FileUtils
.handleFileException(
181 error
as NodeJS
.ErrnoException
,
182 OCPPServiceUtils
.logPrefix(ocppVersion
),
183 { throwError
: false }
188 protected static getSampledValueTemplate(
189 chargingStation
: ChargingStation
,
191 measurand
: MeterValueMeasurand
= MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
,
192 phase
?: MeterValuePhase
193 ): SampledValueTemplate
| undefined {
194 const onPhaseStr
= phase
? `on phase ${phase} ` : '';
195 if (Constants
.SUPPORTED_MEASURANDS
.includes(measurand
) === false) {
197 `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
202 measurand
!== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
203 ChargingStationConfigurationUtils
.getConfigurationKey(
205 StandardParametersKey
.MeterValuesSampledData
206 )?.value
?.includes(measurand
) === false
209 `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId} not found in '${
210 StandardParametersKey.MeterValuesSampledData
215 const sampledValueTemplates
: SampledValueTemplate
[] =
216 chargingStation
.getConnectorStatus(connectorId
)?.MeterValues
;
219 Utils
.isEmptyArray(sampledValueTemplates
) === false && index
< sampledValueTemplates
.length
;
223 Constants
.SUPPORTED_MEASURANDS
.includes(
224 sampledValueTemplates
[index
]?.measurand
??
225 MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
229 `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
233 sampledValueTemplates
[index
]?.phase
=== phase
&&
234 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
235 ChargingStationConfigurationUtils
.getConfigurationKey(
237 StandardParametersKey
.MeterValuesSampledData
238 )?.value
?.includes(measurand
) === true
240 return sampledValueTemplates
[index
];
243 !sampledValueTemplates
[index
].phase
&&
244 sampledValueTemplates
[index
]?.measurand
=== measurand
&&
245 ChargingStationConfigurationUtils
.getConfigurationKey(
247 StandardParametersKey
.MeterValuesSampledData
248 )?.value
?.includes(measurand
) === true
250 return sampledValueTemplates
[index
];
252 measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
&&
253 (!sampledValueTemplates
[index
].measurand
||
254 sampledValueTemplates
[index
].measurand
=== measurand
)
256 return sampledValueTemplates
[index
];
259 if (measurand
=== MeterValueMeasurand
.ENERGY_ACTIVE_IMPORT_REGISTER
) {
260 const errorMsg
= `Missing MeterValues for default measurand '${measurand}' in template on connectorId ${connectorId}`;
261 logger
.error(`${chargingStation.logPrefix()} ${errorMsg}`);
262 throw new BaseError(errorMsg
);
265 `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connectorId ${connectorId}`
269 protected static getLimitFromSampledValueTemplateCustomValue(
272 options
: { limitationEnabled
?: boolean; unitMultiplier
?: number } = {
273 limitationEnabled
: true,
277 options
.limitationEnabled
= options
?.limitationEnabled
?? true;
278 options
.unitMultiplier
= options
?.unitMultiplier
?? 1;
279 const parsedInt
= parseInt(value
);
280 const numberValue
= isNaN(parsedInt
) ? Infinity : parsedInt
;
281 return options
?.limitationEnabled
282 ? Math.min(numberValue
* options
.unitMultiplier
, limit
)
283 : numberValue
* options
.unitMultiplier
;
286 private static logPrefix(ocppVersion
: OCPPVersion
): string {
287 return Utils
.logPrefix(` OCPP ${ocppVersion} |`);