1 import { AsyncResource
} from
'async_hooks';
3 import type { JSONSchemaType
} from
'ajv';
4 import Ajv from
'ajv-draft-04';
5 import ajvFormats from
'ajv-formats';
7 import OCPPError from
'../../exception/OCPPError';
8 import type { HandleErrorParams
} from
'../../types/Error';
9 import type { JsonType
} from
'../../types/JsonType';
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 ajv
: Ajv
;
22 protected constructor() {
23 this.asyncResource
= new AsyncResource(moduleName
);
26 this.incomingRequestHandler
.bind(this);
27 this.validateIncomingRequestPayload
.bind(this);
30 public static getInstance
<T
extends OCPPIncomingRequestService
>(this: new () => T
): T
{
31 if (OCPPIncomingRequestService
.instance
=== null) {
32 OCPPIncomingRequestService
.instance
= new this();
34 return OCPPIncomingRequestService
.instance
as T
;
37 protected handleIncomingRequestError
<T
>(
38 chargingStation
: ChargingStation
,
39 commandName
: IncomingRequestCommand
,
41 params
: HandleErrorParams
<T
> = { throwError
: true }
44 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
47 if (!params
?.throwError
&& params
?.errorResponse
) {
48 return params
?.errorResponse
;
50 if (params
?.throwError
&& !params
?.errorResponse
) {
53 if (params
?.throwError
&& params
?.errorResponse
) {
54 return params
?.errorResponse
;
58 protected validateIncomingRequestPayload
<T
extends JsonType
>(
59 chargingStation
: ChargingStation
,
60 commandName
: IncomingRequestCommand
,
61 schema
: JSONSchemaType
<T
>,
64 if (chargingStation
.getPayloadSchemaValidation() === false) {
67 const validate
= this.ajv
.compile(schema
);
68 if (validate(payload
)) {
72 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Incoming request PDU is invalid: %j`,
76 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
77 'Incoming request PDU is invalid',
79 JSON
.stringify(validate
.errors
, null, 2)
83 public abstract incomingRequestHandler(
84 chargingStation
: ChargingStation
,
86 commandName
: IncomingRequestCommand
,
87 commandPayload
: JsonType