9324fea9c3ee8d61e0aa2322bd320176b284355c
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 2.0 / OCPP20IncomingRequestService.ts
1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
2
3 import type { ValidateFunction } from 'ajv'
4
5 import type { ChargingStation } from '../../../charging-station/index.js'
6
7 import { OCPPError } from '../../../exception/index.js'
8 import {
9 ErrorType,
10 type IncomingRequestHandler,
11 type JsonType,
12 type OCPP20ClearCacheRequest,
13 OCPP20IncomingRequestCommand,
14 OCPPVersion,
15 } from '../../../types/index.js'
16 import { isAsyncFunction, logger } from '../../../utils/index.js'
17 import { OCPPIncomingRequestService } from '../OCPPIncomingRequestService.js'
18 import { OCPP20ServiceUtils } from './OCPP20ServiceUtils.js'
19
20 const moduleName = 'OCPP20IncomingRequestService'
21
22 export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
23 protected payloadValidateFunctions: Map<OCPP20IncomingRequestCommand, ValidateFunction<JsonType>>
24
25 private readonly incomingRequestHandlers: Map<
26 OCPP20IncomingRequestCommand,
27 IncomingRequestHandler
28 >
29
30 public constructor () {
31 // if (new.target.name === moduleName) {
32 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
33 // }
34 super(OCPPVersion.VERSION_201)
35 this.incomingRequestHandlers = new Map<OCPP20IncomingRequestCommand, IncomingRequestHandler>([
36 [OCPP20IncomingRequestCommand.CLEAR_CACHE, this.handleRequestClearCache.bind(this)],
37 ])
38 this.payloadValidateFunctions = new Map<
39 OCPP20IncomingRequestCommand,
40 ValidateFunction<JsonType>
41 >([
42 [
43 OCPP20IncomingRequestCommand.CLEAR_CACHE,
44 this.ajv.compile(
45 OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20ClearCacheRequest>(
46 'assets/json-schemas/ocpp/2.0/ClearCacheRequest.json',
47 moduleName,
48 'constructor'
49 )
50 ),
51 ],
52 ])
53 this.validatePayload = this.validatePayload.bind(this)
54 }
55
56 private validatePayload (
57 chargingStation: ChargingStation,
58 commandName: OCPP20IncomingRequestCommand,
59 commandPayload: JsonType
60 ): boolean {
61 if (this.payloadValidateFunctions.has(commandName)) {
62 return this.validateIncomingRequestPayload(chargingStation, commandName, commandPayload)
63 }
64 logger.warn(
65 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
66 )
67 return false
68 }
69
70 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
71 public async incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
72 chargingStation: ChargingStation,
73 messageId: string,
74 commandName: OCPP20IncomingRequestCommand,
75 commandPayload: ReqType
76 ): Promise<void> {
77 let response: ResType
78 if (
79 chargingStation.stationInfo?.ocppStrictCompliance === true &&
80 chargingStation.inPendingState() &&
81 (commandName === OCPP20IncomingRequestCommand.REQUEST_START_TRANSACTION ||
82 commandName === OCPP20IncomingRequestCommand.REQUEST_STOP_TRANSACTION)
83 ) {
84 throw new OCPPError(
85 ErrorType.SECURITY_ERROR,
86 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
87 commandPayload,
88 undefined,
89 2
90 )} while the charging station is in pending state on the central server`,
91 commandName,
92 commandPayload
93 )
94 }
95 if (
96 chargingStation.isRegistered() ||
97 (chargingStation.stationInfo?.ocppStrictCompliance === false &&
98 chargingStation.inUnknownState())
99 ) {
100 if (
101 this.incomingRequestHandlers.has(commandName) &&
102 OCPP20ServiceUtils.isIncomingRequestCommandSupported(chargingStation, commandName)
103 ) {
104 try {
105 this.validatePayload(chargingStation, commandName, commandPayload)
106 // Call the method to build the response
107 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
108 const incomingRequestHandler = this.incomingRequestHandlers.get(commandName)!
109 if (isAsyncFunction(incomingRequestHandler)) {
110 response = (await incomingRequestHandler(chargingStation, commandPayload)) as ResType
111 } else {
112 response = incomingRequestHandler(chargingStation, commandPayload) as ResType
113 }
114 } catch (error) {
115 // Log
116 logger.error(
117 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
118 error
119 )
120 throw error
121 }
122 } else {
123 // Throw exception
124 throw new OCPPError(
125 ErrorType.NOT_IMPLEMENTED,
126 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
127 commandPayload,
128 undefined,
129 2
130 )}`,
131 commandName,
132 commandPayload
133 )
134 }
135 } else {
136 throw new OCPPError(
137 ErrorType.SECURITY_ERROR,
138 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
139 commandPayload,
140 undefined,
141 2
142 )} while the charging station is not registered on the central server`,
143 commandName,
144 commandPayload
145 )
146 }
147 // Send the built response
148 await chargingStation.ocppRequestService.sendResponse(
149 chargingStation,
150 messageId,
151 response,
152 commandName
153 )
154 // Emit command name event to allow delayed handling
155 this.emit(commandName, chargingStation, commandPayload, response)
156 }
157 }