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 keywords
: ['javaType'],
27 multipleOfPrecision
: 2,
30 this.asyncResource
= new AsyncResource(moduleName
);
31 this.incomingRequestHandler
.bind(this);
32 this.validateIncomingRequestPayload
.bind(this);
35 public static getInstance
<T
extends OCPPIncomingRequestService
>(this: new () => T
): T
{
36 if (OCPPIncomingRequestService
.instance
=== null) {
37 OCPPIncomingRequestService
.instance
= new this();
39 return OCPPIncomingRequestService
.instance
as T
;
42 protected handleIncomingRequestError
<T
>(
43 chargingStation
: ChargingStation
,
44 commandName
: IncomingRequestCommand
,
46 params
: HandleErrorParams
<T
> = { throwError
: true }
49 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
52 if (!params
?.throwError
&& params
?.errorResponse
) {
53 return params
?.errorResponse
;
55 if (params
?.throwError
&& !params
?.errorResponse
) {
58 if (params
?.throwError
&& params
?.errorResponse
) {
59 return params
?.errorResponse
;
63 protected validateIncomingRequestPayload
<T
extends JsonType
>(
64 chargingStation
: ChargingStation
,
65 commandName
: IncomingRequestCommand
,
66 schema
: JSONSchemaType
<T
>,
69 if (chargingStation
.getPayloadSchemaValidation() === false) {
72 const validate
= this.ajv
.compile(schema
);
73 if (validate(payload
)) {
77 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
81 OCPPServiceUtils
.ajvErrorsToErrorType(validate
.errors
),
82 'Incoming request PDU is invalid',
84 JSON
.stringify(validate
.errors
, null, 2)
88 public abstract incomingRequestHandler(
89 chargingStation
: ChargingStation
,
91 commandName
: IncomingRequestCommand
,
92 commandPayload
: JsonType