ddffa657f2a131df81b11058b786807eea15e0fd
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPIncomingRequestService.ts
1 import { AsyncResource } from 'async_hooks';
2
3 import Ajv, { type JSONSchemaType } from 'ajv';
4 import ajvFormats from 'ajv-formats';
5
6 import OCPPConstants from './OCPPConstants';
7 import { OCPPServiceUtils } from './OCPPServiceUtils';
8 import OCPPError from '../../exception/OCPPError';
9 import type { HandleErrorParams } from '../../types/Error';
10 import type { JsonObject, JsonType } from '../../types/JsonType';
11 import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
12 import type { IncomingRequestCommand } from '../../types/ocpp/Requests';
13 import type { ClearCacheResponse } from '../../types/ocpp/Responses';
14 import logger from '../../utils/Logger';
15 import type ChargingStation from '../ChargingStation';
16 import { ChargingStationUtils } from '../ChargingStationUtils';
17
18 const moduleName = 'OCPPIncomingRequestService';
19
20 export default abstract class OCPPIncomingRequestService {
21 private static instance: OCPPIncomingRequestService | null = null;
22 protected asyncResource: AsyncResource;
23 private readonly version: OCPPVersion;
24 private readonly ajv: Ajv;
25 protected abstract jsonSchemas: Map<IncomingRequestCommand, JSONSchemaType<JsonObject>>;
26
27 protected constructor(version: OCPPVersion) {
28 this.version = version;
29 this.ajv = new Ajv({
30 keywords: ['javaType'],
31 multipleOfPrecision: 2,
32 });
33 ajvFormats(this.ajv);
34 this.asyncResource = new AsyncResource(moduleName);
35 this.incomingRequestHandler.bind(this);
36 this.validateIncomingRequestPayload.bind(this);
37 }
38
39 public static getInstance<T extends OCPPIncomingRequestService>(this: new () => T): T {
40 if (OCPPIncomingRequestService.instance === null) {
41 OCPPIncomingRequestService.instance = new this();
42 }
43 return OCPPIncomingRequestService.instance as T;
44 }
45
46 protected handleIncomingRequestError<T>(
47 chargingStation: ChargingStation,
48 commandName: IncomingRequestCommand,
49 error: Error,
50 params: HandleErrorParams<T> = { throwError: true }
51 ): T | undefined {
52 logger.error(
53 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
54 error
55 );
56 if (!params?.throwError && params?.errorResponse) {
57 return params?.errorResponse;
58 }
59 if (params?.throwError && !params?.errorResponse) {
60 throw error;
61 }
62 if (params?.throwError && params?.errorResponse) {
63 return params?.errorResponse;
64 }
65 }
66
67 protected validateIncomingRequestPayload<T extends JsonType>(
68 chargingStation: ChargingStation,
69 commandName: IncomingRequestCommand,
70 schema: JSONSchemaType<T>,
71 payload: T
72 ): boolean {
73 if (chargingStation.getPayloadSchemaValidation() === false) {
74 return true;
75 }
76 const validate = this.ajv.compile(schema);
77 if (validate(payload)) {
78 return true;
79 }
80 logger.error(
81 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
82 validate.errors
83 );
84 throw new OCPPError(
85 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
86 'Incoming request PDU is invalid',
87 commandName,
88 JSON.stringify(validate.errors, null, 2)
89 );
90 }
91
92 protected handleRequestClearCache(chargingStation: ChargingStation): ClearCacheResponse {
93 chargingStation.authorizedTagsCache.deleteAuthorizedTags(
94 ChargingStationUtils.getAuthorizationFile(chargingStation.stationInfo)
95 );
96 return OCPPConstants.OCPP_RESPONSE_ACCEPTED;
97 }
98
99 public abstract incomingRequestHandler(
100 chargingStation: ChargingStation,
101 messageId: string,
102 commandName: IncomingRequestCommand,
103 commandPayload: JsonType
104 ): Promise<void>;
105 }