1 import { AsyncResource
} from
'async_hooks';
3 import Ajv
, { type JSONSchemaType
} from
'ajv';
4 import ajvFormats from
'ajv-formats';
6 import OCPPError from
'../../exception/OCPPError';
7 import type { HandleErrorParams
} from
'../../types/Error';
8 import type { JsonObject
, JsonType
} from
'../../types/JsonType';
9 import type { OCPPVersion
} from
'../../types/ocpp/OCPPVersion';
10 import type { IncomingRequestCommand
} from
'../../types/ocpp/Requests';
11 import logger from
'../../utils/Logger';
12 import type ChargingStation from
'../ChargingStation';
13 import { OCPPServiceUtils
} from
'./OCPPServiceUtils';
15 const moduleName
= 'OCPPIncomingRequestService';
17 export default abstract class OCPPIncomingRequestService
{
18 private static instance
: OCPPIncomingRequestService
| null = null;
19 protected asyncResource
: AsyncResource
;
20 private readonly version
: OCPPVersion
;
21 private readonly ajv
: Ajv
;
22 protected abstract jsonSchemas
: Map
<IncomingRequestCommand
, JSONSchemaType
<JsonObject
>>;
24 protected constructor(version
: OCPPVersion
) {
25 this.version
= version
;
27 keywords
: ['javaType'],
28 multipleOfPrecision
: 2,
31 this.asyncResource
= new AsyncResource(moduleName
);
32 this.incomingRequestHandler
.bind(this);
33 this.validateIncomingRequestPayload
.bind(this);
36 public static getInstance
<T
extends OCPPIncomingRequestService
>(this: new () => T
): T
{
37 if (OCPPIncomingRequestService
.instance
=== null) {
38 OCPPIncomingRequestService
.instance
= new this();
40 return OCPPIncomingRequestService
.instance
as T
;
43 protected handleIncomingRequestError
<T
>(
44 chargingStation
: ChargingStation
,
45 commandName
: IncomingRequestCommand
,
47 params
: HandleErrorParams
<T
> = { throwError
: true }
50 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
53 if (!params
?.throwError
&& params
?.errorResponse
) {
54 return params
?.errorResponse
;
56 if (params
?.throwError
&& !params
?.errorResponse
) {
59 if (params
?.throwError
&& params
?.errorResponse
) {
60 return params
?.errorResponse
;
64 protected validateIncomingRequestPayload
<T
extends JsonType
>(
65 chargingStation
: ChargingStation
,
66 commandName
: IncomingRequestCommand
,
67 schema
: JSONSchemaType
<T
>,
70 if (chargingStation
.getPayloadSchemaValidation() === false) {
73 const validate
= this.ajv
.compile(schema
);
74 if (validate(payload
)) {
78 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
82 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
83 'Incoming request PDU is invalid',
85 JSON
.stringify(validate
.errors
, null, 2)
89 public abstract incomingRequestHandler(
90 chargingStation
: ChargingStation
,
92 commandName
: IncomingRequestCommand
,
93 commandPayload
: JsonType