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 { 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
;
23 protected constructor(version
: OCPPVersion
) {
24 this.version
= version
;
26 multipleOfPrecision
: 2,
29 this.asyncResource
= new AsyncResource(moduleName
);
30 this.incomingRequestHandler
.bind(this);
31 this.validateIncomingRequestPayload
.bind(this);
34 public static getInstance
<T
extends OCPPIncomingRequestService
>(this: new () => T
): T
{
35 if (OCPPIncomingRequestService
.instance
=== null) {
36 OCPPIncomingRequestService
.instance
= new this();
38 return OCPPIncomingRequestService
.instance
as T
;
41 protected handleIncomingRequestError
<T
>(
42 chargingStation
: ChargingStation
,
43 commandName
: IncomingRequestCommand
,
45 params
: HandleErrorParams
<T
> = { throwError
: true }
48 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
51 if (!params
?.throwError
&& params
?.errorResponse
) {
52 return params
?.errorResponse
;
54 if (params
?.throwError
&& !params
?.errorResponse
) {
57 if (params
?.throwError
&& params
?.errorResponse
) {
58 return params
?.errorResponse
;
62 protected validateIncomingRequestPayload
<T
extends JsonType
>(
63 chargingStation
: ChargingStation
,
64 commandName
: IncomingRequestCommand
,
65 schema
: JSONSchemaType
<T
>,
68 if (chargingStation
.getPayloadSchemaValidation() === false) {
71 const validate
= this.ajv
.compile(schema
);
72 if (validate(payload
)) {
76 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
80 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
81 'Incoming request PDU is invalid',
83 JSON
.stringify(validate
.errors
, null, 2)
87 public abstract incomingRequestHandler(
88 chargingStation
: ChargingStation
,
90 commandName
: IncomingRequestCommand
,
91 commandPayload
: JsonType