Commit | Line | Data |
---|---|---|
d972af76 JB |
1 | import { readFileSync } from 'node:fs'; |
2 | import { dirname, join } from 'node:path'; | |
51022aa0 | 3 | import { fileURLToPath } from 'node:url'; |
7164966d JB |
4 | |
5 | import type { DefinedError, ErrorObject, JSONSchemaType } from 'ajv'; | |
3dcf7b67 | 6 | import { isDate } from 'date-fns'; |
06ad945f | 7 | |
4c3c0d59 JB |
8 | import { OCPP16Constants } from './1.6/OCPP16Constants'; |
9 | import { OCPP20Constants } from './2.0/OCPP20Constants'; | |
c3da35d4 | 10 | import { OCPPConstants } from './OCPPConstants'; |
ae725be3 | 11 | import { type ChargingStation, getConfigurationKey, getIdTagsFile } from '../../charging-station'; |
268a74bb | 12 | import { BaseError } from '../../exception'; |
6e939d9e | 13 | import { |
ae725be3 JB |
14 | AuthorizationStatus, |
15 | type AuthorizeRequest, | |
16 | type AuthorizeResponse, | |
268a74bb | 17 | ChargePointErrorCode, |
ae725be3 | 18 | type ConnectorStatus, |
268a74bb JB |
19 | type ConnectorStatusEnum, |
20 | ErrorType, | |
21 | FileType, | |
6e939d9e | 22 | IncomingRequestCommand, |
268a74bb | 23 | type JsonType, |
6e939d9e | 24 | MessageTrigger, |
268a74bb JB |
25 | MessageType, |
26 | MeterValueMeasurand, | |
27 | type MeterValuePhase, | |
28 | type OCPP16StatusNotificationRequest, | |
29 | type OCPP20StatusNotificationRequest, | |
30 | OCPPVersion, | |
6e939d9e | 31 | RequestCommand, |
268a74bb JB |
32 | type SampledValueTemplate, |
33 | StandardParametersKey, | |
6e939d9e | 34 | type StatusNotificationRequest, |
48b75072 | 35 | type StatusNotificationResponse, |
268a74bb | 36 | } from '../../types'; |
9bf0ef23 JB |
37 | import { |
38 | handleFileException, | |
39 | isNotEmptyArray, | |
40 | isNotEmptyString, | |
41 | logPrefix, | |
42 | logger, | |
43 | } from '../../utils'; | |
06ad945f | 44 | |
90befdb8 | 45 | export class OCPPServiceUtils { |
d5bd1c00 JB |
46 | protected constructor() { |
47 | // This is intentional | |
48 | } | |
49 | ||
01a4dcbb | 50 | public static ajvErrorsToErrorType(errors: ErrorObject[]): ErrorType { |
06ad945f JB |
51 | for (const error of errors as DefinedError[]) { |
52 | switch (error.keyword) { | |
53 | case 'type': | |
54 | return ErrorType.TYPE_CONSTRAINT_VIOLATION; | |
55 | case 'dependencies': | |
56 | case 'required': | |
57 | return ErrorType.OCCURRENCE_CONSTRAINT_VIOLATION; | |
58 | case 'pattern': | |
59 | case 'format': | |
60 | return ErrorType.PROPERTY_CONSTRAINT_VIOLATION; | |
61 | } | |
62 | } | |
63 | return ErrorType.FORMAT_VIOLATION; | |
64 | } | |
65 | ||
2cc5d5ec JB |
66 | public static getMessageTypeString(messageType: MessageType): string { |
67 | switch (messageType) { | |
68 | case MessageType.CALL_MESSAGE: | |
69 | return 'request'; | |
70 | case MessageType.CALL_RESULT_MESSAGE: | |
71 | return 'response'; | |
72 | case MessageType.CALL_ERROR_MESSAGE: | |
73 | return 'error'; | |
336f2829 JB |
74 | default: |
75 | return 'unknown'; | |
2cc5d5ec JB |
76 | } |
77 | } | |
78 | ||
ed3d2808 | 79 | public static isRequestCommandSupported( |
fd3c56d1 | 80 | chargingStation: ChargingStation, |
5edd8ba0 | 81 | command: RequestCommand, |
ed3d2808 | 82 | ): boolean { |
edd13439 | 83 | const isRequestCommand = Object.values<RequestCommand>(RequestCommand).includes(command); |
ed3d2808 JB |
84 | if ( |
85 | isRequestCommand === true && | |
86 | !chargingStation.stationInfo?.commandsSupport?.outgoingCommands | |
87 | ) { | |
88 | return true; | |
89 | } else if ( | |
90 | isRequestCommand === true && | |
91 | chargingStation.stationInfo?.commandsSupport?.outgoingCommands | |
92 | ) { | |
93 | return chargingStation.stationInfo?.commandsSupport?.outgoingCommands[command] ?? false; | |
94 | } | |
95 | logger.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`); | |
96 | return false; | |
97 | } | |
98 | ||
99 | public static isIncomingRequestCommandSupported( | |
fd3c56d1 | 100 | chargingStation: ChargingStation, |
5edd8ba0 | 101 | command: IncomingRequestCommand, |
ed3d2808 | 102 | ): boolean { |
edd13439 JB |
103 | const isIncomingRequestCommand = |
104 | Object.values<IncomingRequestCommand>(IncomingRequestCommand).includes(command); | |
ed3d2808 JB |
105 | if ( |
106 | isIncomingRequestCommand === true && | |
107 | !chargingStation.stationInfo?.commandsSupport?.incomingCommands | |
108 | ) { | |
109 | return true; | |
110 | } else if ( | |
111 | isIncomingRequestCommand === true && | |
112 | chargingStation.stationInfo?.commandsSupport?.incomingCommands | |
113 | ) { | |
114 | return chargingStation.stationInfo?.commandsSupport?.incomingCommands[command] ?? false; | |
115 | } | |
116 | logger.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`); | |
117 | return false; | |
118 | } | |
119 | ||
c60ed4b8 JB |
120 | public static isMessageTriggerSupported( |
121 | chargingStation: ChargingStation, | |
5edd8ba0 | 122 | messageTrigger: MessageTrigger, |
c60ed4b8 JB |
123 | ): boolean { |
124 | const isMessageTrigger = Object.values(MessageTrigger).includes(messageTrigger); | |
125 | if (isMessageTrigger === true && !chargingStation.stationInfo?.messageTriggerSupport) { | |
126 | return true; | |
127 | } else if (isMessageTrigger === true && chargingStation.stationInfo?.messageTriggerSupport) { | |
128 | return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger] ?? false; | |
129 | } | |
130 | logger.error( | |
5edd8ba0 | 131 | `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`, |
c60ed4b8 JB |
132 | ); |
133 | return false; | |
134 | } | |
135 | ||
136 | public static isConnectorIdValid( | |
137 | chargingStation: ChargingStation, | |
138 | ocppCommand: IncomingRequestCommand, | |
5edd8ba0 | 139 | connectorId: number, |
c60ed4b8 JB |
140 | ): boolean { |
141 | if (connectorId < 0) { | |
142 | logger.error( | |
5edd8ba0 | 143 | `${chargingStation.logPrefix()} ${ocppCommand} incoming request received with invalid connector id ${connectorId}`, |
c60ed4b8 JB |
144 | ); |
145 | return false; | |
146 | } | |
147 | return true; | |
148 | } | |
149 | ||
1799761a | 150 | public static convertDateToISOString<T extends JsonType>(obj: T): void { |
a37fc6dc JB |
151 | for (const key in obj) { |
152 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion | |
3dcf7b67 | 153 | if (isDate(obj![key])) { |
a37fc6dc JB |
154 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion |
155 | (obj![key] as string) = (obj![key] as Date).toISOString(); | |
156 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion | |
e1d9a0f4 | 157 | } else if (obj![key] !== null && typeof obj![key] === 'object') { |
a37fc6dc | 158 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion |
e1d9a0f4 | 159 | OCPPServiceUtils.convertDateToISOString<T>(obj![key] as T); |
1799761a JB |
160 | } |
161 | } | |
162 | } | |
163 | ||
6e939d9e JB |
164 | public static buildStatusNotificationRequest( |
165 | chargingStation: ChargingStation, | |
166 | connectorId: number, | |
12f26d4a | 167 | status: ConnectorStatusEnum, |
5edd8ba0 | 168 | evseId?: number, |
6e939d9e | 169 | ): StatusNotificationRequest { |
cda96260 | 170 | switch (chargingStation.stationInfo.ocppVersion ?? OCPPVersion.VERSION_16) { |
6e939d9e JB |
171 | case OCPPVersion.VERSION_16: |
172 | return { | |
173 | connectorId, | |
174 | status, | |
175 | errorCode: ChargePointErrorCode.NO_ERROR, | |
176 | } as OCPP16StatusNotificationRequest; | |
177 | case OCPPVersion.VERSION_20: | |
178 | case OCPPVersion.VERSION_201: | |
179 | return { | |
180 | timestamp: new Date(), | |
181 | connectorStatus: status, | |
182 | connectorId, | |
12f26d4a | 183 | evseId, |
6e939d9e | 184 | } as OCPP20StatusNotificationRequest; |
cda96260 JB |
185 | default: |
186 | throw new BaseError('Cannot build status notification payload: OCPP version not supported'); | |
6e939d9e JB |
187 | } |
188 | } | |
189 | ||
8f953431 JB |
190 | public static startHeartbeatInterval(chargingStation: ChargingStation, interval: number): void { |
191 | if (!chargingStation.heartbeatSetInterval) { | |
192 | chargingStation.startHeartbeat(); | |
193 | } else if (chargingStation.getHeartbeatInterval() !== interval) { | |
194 | chargingStation.restartHeartbeat(); | |
195 | } | |
196 | } | |
197 | ||
48b75072 JB |
198 | public static async sendAndSetConnectorStatus( |
199 | chargingStation: ChargingStation, | |
200 | connectorId: number, | |
12f26d4a | 201 | status: ConnectorStatusEnum, |
ec94a3cf | 202 | evseId?: number, |
e1d9a0f4 | 203 | options?: { send: boolean }, |
48b75072 | 204 | ) { |
ec94a3cf JB |
205 | options = { send: true, ...options }; |
206 | if (options.send) { | |
207 | OCPPServiceUtils.checkConnectorStatusTransition(chargingStation, connectorId, status); | |
208 | await chargingStation.ocppRequestService.requestHandler< | |
209 | StatusNotificationRequest, | |
210 | StatusNotificationResponse | |
211 | >( | |
212 | chargingStation, | |
213 | RequestCommand.STATUS_NOTIFICATION, | |
214 | OCPPServiceUtils.buildStatusNotificationRequest( | |
215 | chargingStation, | |
216 | connectorId, | |
217 | status, | |
5edd8ba0 JB |
218 | evseId, |
219 | ), | |
ec94a3cf JB |
220 | ); |
221 | } | |
e1d9a0f4 | 222 | chargingStation.getConnectorStatus(connectorId)!.status = status; |
48b75072 JB |
223 | } |
224 | ||
ae725be3 JB |
225 | public static async isIdTagAuthorized( |
226 | chargingStation: ChargingStation, | |
227 | connectorId: number, | |
228 | idTag: string, | |
229 | ): Promise<boolean> { | |
230 | let authorized = false; | |
231 | if (OCPPServiceUtils.isIdTagLocalAuthorized(chargingStation, idTag)) { | |
232 | const connectorStatus: ConnectorStatus = chargingStation.getConnectorStatus(connectorId)!; | |
233 | connectorStatus.localAuthorizeIdTag = idTag; | |
234 | connectorStatus.idTagLocalAuthorized = true; | |
235 | authorized = true; | |
236 | } else { | |
237 | authorized = await OCPPServiceUtils.isIdTagRemoteAuthorized( | |
238 | chargingStation, | |
239 | connectorId, | |
240 | idTag, | |
241 | ); | |
242 | } | |
243 | return authorized; | |
244 | } | |
245 | ||
48b75072 JB |
246 | protected static checkConnectorStatusTransition( |
247 | chargingStation: ChargingStation, | |
248 | connectorId: number, | |
5edd8ba0 | 249 | status: ConnectorStatusEnum, |
48b75072 | 250 | ): boolean { |
e1d9a0f4 | 251 | const fromStatus = chargingStation.getConnectorStatus(connectorId)!.status; |
48b75072 JB |
252 | let transitionAllowed = false; |
253 | switch (chargingStation.stationInfo.ocppVersion) { | |
254 | case OCPPVersion.VERSION_16: | |
255 | if ( | |
ff9d1031 JB |
256 | (connectorId === 0 && |
257 | OCPP16Constants.ChargePointStatusChargingStationTransitions.findIndex( | |
5edd8ba0 | 258 | (transition) => transition.from === fromStatus && transition.to === status, |
ff9d1031 JB |
259 | ) !== -1) || |
260 | (connectorId > 0 && | |
261 | OCPP16Constants.ChargePointStatusConnectorTransitions.findIndex( | |
5edd8ba0 | 262 | (transition) => transition.from === fromStatus && transition.to === status, |
ff9d1031 | 263 | ) !== -1) |
48b75072 JB |
264 | ) { |
265 | transitionAllowed = true; | |
266 | } | |
267 | break; | |
268 | case OCPPVersion.VERSION_20: | |
269 | case OCPPVersion.VERSION_201: | |
270 | if ( | |
ff9d1031 JB |
271 | (connectorId === 0 && |
272 | OCPP20Constants.ChargingStationStatusTransitions.findIndex( | |
5edd8ba0 | 273 | (transition) => transition.from === fromStatus && transition.to === status, |
ff9d1031 JB |
274 | ) !== -1) || |
275 | (connectorId > 0 && | |
276 | OCPP20Constants.ConnectorStatusTransitions.findIndex( | |
5edd8ba0 | 277 | (transition) => transition.from === fromStatus && transition.to === status, |
ff9d1031 | 278 | ) !== -1) |
48b75072 JB |
279 | ) { |
280 | transitionAllowed = true; | |
281 | } | |
282 | break; | |
283 | default: | |
284 | throw new BaseError( | |
285 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
5edd8ba0 | 286 | `Cannot check connector status transition: OCPP version ${chargingStation.stationInfo.ocppVersion} not supported`, |
48b75072 JB |
287 | ); |
288 | } | |
289 | if (transitionAllowed === false) { | |
290 | logger.warn( | |
291 | `${chargingStation.logPrefix()} OCPP ${ | |
292 | chargingStation.stationInfo.ocppVersion | |
54ebb82c | 293 | } connector id ${connectorId} status transition from '${ |
e1d9a0f4 | 294 | chargingStation.getConnectorStatus(connectorId)!.status |
5edd8ba0 | 295 | }' to '${status}' is not allowed`, |
48b75072 JB |
296 | ); |
297 | } | |
298 | return transitionAllowed; | |
299 | } | |
300 | ||
7164966d | 301 | protected static parseJsonSchemaFile<T extends JsonType>( |
51022aa0 | 302 | relativePath: string, |
1b271a54 JB |
303 | ocppVersion: OCPPVersion, |
304 | moduleName?: string, | |
5edd8ba0 | 305 | methodName?: string, |
7164966d | 306 | ): JSONSchemaType<T> { |
d972af76 | 307 | const filePath = join(dirname(fileURLToPath(import.meta.url)), relativePath); |
7164966d | 308 | try { |
d972af76 | 309 | return JSON.parse(readFileSync(filePath, 'utf8')) as JSONSchemaType<T>; |
7164966d | 310 | } catch (error) { |
fa5995d6 | 311 | handleFileException( |
7164966d JB |
312 | filePath, |
313 | FileType.JsonSchema, | |
314 | error as NodeJS.ErrnoException, | |
1b271a54 | 315 | OCPPServiceUtils.logPrefix(ocppVersion, moduleName, methodName), |
5edd8ba0 | 316 | { throwError: false }, |
7164966d | 317 | ); |
e1d9a0f4 | 318 | return {} as JSONSchemaType<T>; |
7164966d | 319 | } |
130783a7 JB |
320 | } |
321 | ||
884a6fdf JB |
322 | protected static getSampledValueTemplate( |
323 | chargingStation: ChargingStation, | |
324 | connectorId: number, | |
325 | measurand: MeterValueMeasurand = MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, | |
5edd8ba0 | 326 | phase?: MeterValuePhase, |
884a6fdf JB |
327 | ): SampledValueTemplate | undefined { |
328 | const onPhaseStr = phase ? `on phase ${phase} ` : ''; | |
c3da35d4 | 329 | if (OCPPConstants.OCPP_MEASURANDS_SUPPORTED.includes(measurand) === false) { |
884a6fdf | 330 | logger.warn( |
5edd8ba0 | 331 | `${chargingStation.logPrefix()} Trying to get unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, |
884a6fdf JB |
332 | ); |
333 | return; | |
334 | } | |
335 | if ( | |
336 | measurand !== MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && | |
f2d5e3d9 | 337 | getConfigurationKey( |
884a6fdf | 338 | chargingStation, |
5edd8ba0 | 339 | StandardParametersKey.MeterValuesSampledData, |
72092cfc | 340 | )?.value?.includes(measurand) === false |
884a6fdf JB |
341 | ) { |
342 | logger.debug( | |
54ebb82c | 343 | `${chargingStation.logPrefix()} Trying to get MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId} not found in '${ |
884a6fdf | 344 | StandardParametersKey.MeterValuesSampledData |
5edd8ba0 | 345 | }' OCPP parameter`, |
884a6fdf JB |
346 | ); |
347 | return; | |
348 | } | |
349 | const sampledValueTemplates: SampledValueTemplate[] = | |
e1d9a0f4 | 350 | chargingStation.getConnectorStatus(connectorId)!.MeterValues; |
884a6fdf JB |
351 | for ( |
352 | let index = 0; | |
9bf0ef23 | 353 | isNotEmptyArray(sampledValueTemplates) === true && index < sampledValueTemplates.length; |
884a6fdf JB |
354 | index++ |
355 | ) { | |
356 | if ( | |
c3da35d4 | 357 | OCPPConstants.OCPP_MEASURANDS_SUPPORTED.includes( |
884a6fdf | 358 | sampledValueTemplates[index]?.measurand ?? |
5edd8ba0 | 359 | MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER, |
884a6fdf JB |
360 | ) === false |
361 | ) { | |
362 | logger.warn( | |
5edd8ba0 | 363 | `${chargingStation.logPrefix()} Unsupported MeterValues measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, |
884a6fdf JB |
364 | ); |
365 | } else if ( | |
366 | phase && | |
367 | sampledValueTemplates[index]?.phase === phase && | |
368 | sampledValueTemplates[index]?.measurand === measurand && | |
f2d5e3d9 | 369 | getConfigurationKey( |
884a6fdf | 370 | chargingStation, |
5edd8ba0 | 371 | StandardParametersKey.MeterValuesSampledData, |
72092cfc | 372 | )?.value?.includes(measurand) === true |
884a6fdf JB |
373 | ) { |
374 | return sampledValueTemplates[index]; | |
375 | } else if ( | |
376 | !phase && | |
377 | !sampledValueTemplates[index].phase && | |
378 | sampledValueTemplates[index]?.measurand === measurand && | |
f2d5e3d9 | 379 | getConfigurationKey( |
884a6fdf | 380 | chargingStation, |
5edd8ba0 | 381 | StandardParametersKey.MeterValuesSampledData, |
72092cfc | 382 | )?.value?.includes(measurand) === true |
884a6fdf JB |
383 | ) { |
384 | return sampledValueTemplates[index]; | |
385 | } else if ( | |
386 | measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && | |
387 | (!sampledValueTemplates[index].measurand || | |
388 | sampledValueTemplates[index].measurand === measurand) | |
389 | ) { | |
390 | return sampledValueTemplates[index]; | |
391 | } | |
392 | } | |
393 | if (measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER) { | |
54ebb82c | 394 | const errorMsg = `Missing MeterValues for default measurand '${measurand}' in template on connector id ${connectorId}`; |
884a6fdf JB |
395 | logger.error(`${chargingStation.logPrefix()} ${errorMsg}`); |
396 | throw new BaseError(errorMsg); | |
397 | } | |
398 | logger.debug( | |
5edd8ba0 | 399 | `${chargingStation.logPrefix()} No MeterValues for measurand '${measurand}' ${onPhaseStr}in template on connector id ${connectorId}`, |
884a6fdf JB |
400 | ); |
401 | } | |
402 | ||
90befdb8 JB |
403 | protected static getLimitFromSampledValueTemplateCustomValue( |
404 | value: string, | |
405 | limit: number, | |
406 | options: { limitationEnabled?: boolean; unitMultiplier?: number } = { | |
407 | limitationEnabled: true, | |
408 | unitMultiplier: 1, | |
5edd8ba0 | 409 | }, |
90befdb8 | 410 | ): number { |
20f0b76c JB |
411 | options = { |
412 | ...{ | |
413 | limitationEnabled: true, | |
414 | unitMultiplier: 1, | |
415 | }, | |
416 | ...options, | |
417 | }; | |
231d1ecd JB |
418 | const parsedInt = parseInt(value); |
419 | const numberValue = isNaN(parsedInt) ? Infinity : parsedInt; | |
90befdb8 | 420 | return options?.limitationEnabled |
e1d9a0f4 JB |
421 | ? Math.min(numberValue * options.unitMultiplier!, limit) |
422 | : numberValue * options.unitMultiplier!; | |
90befdb8 | 423 | } |
7164966d | 424 | |
ae725be3 JB |
425 | private static isIdTagLocalAuthorized(chargingStation: ChargingStation, idTag: string): boolean { |
426 | return ( | |
427 | chargingStation.getLocalAuthListEnabled() === true && | |
428 | chargingStation.hasIdTags() === true && | |
429 | isNotEmptyString( | |
430 | chargingStation.idTagsCache | |
431 | .getIdTags(getIdTagsFile(chargingStation.stationInfo)!) | |
432 | ?.find((tag) => tag === idTag), | |
433 | ) | |
434 | ); | |
435 | } | |
436 | ||
437 | private static async isIdTagRemoteAuthorized( | |
438 | chargingStation: ChargingStation, | |
439 | connectorId: number, | |
440 | idTag: string, | |
441 | ): Promise<boolean> { | |
442 | chargingStation.getConnectorStatus(connectorId)!.authorizeIdTag = idTag; | |
443 | return ( | |
444 | ( | |
445 | await chargingStation.ocppRequestService.requestHandler< | |
446 | AuthorizeRequest, | |
447 | AuthorizeResponse | |
448 | >(chargingStation, RequestCommand.AUTHORIZE, { | |
449 | idTag, | |
450 | }) | |
451 | )?.idTagInfo?.status === AuthorizationStatus.ACCEPTED | |
452 | ); | |
453 | } | |
454 | ||
1b271a54 JB |
455 | private static logPrefix = ( |
456 | ocppVersion: OCPPVersion, | |
457 | moduleName?: string, | |
5edd8ba0 | 458 | methodName?: string, |
1b271a54 JB |
459 | ): string => { |
460 | const logMsg = | |
9bf0ef23 | 461 | isNotEmptyString(moduleName) && isNotEmptyString(methodName) |
1b271a54 JB |
462 | ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:` |
463 | : ` OCPP ${ocppVersion} |`; | |
9bf0ef23 | 464 | return logPrefix(logMsg); |
8b7072dc | 465 | }; |
90befdb8 | 466 | } |