9979c70aa8101f41facf955a637b5d3fc2bd5b52
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16RequestService.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import fs from 'fs';
4 import path from 'path';
5 import { fileURLToPath } from 'url';
6
7 import type { JSONSchemaType } from 'ajv';
8
9 import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
10 import OCPPError from '../../../exception/OCPPError';
11 import type { JsonObject, JsonType } from '../../../types/JsonType';
12 import type { OCPP16MeterValuesRequest } from '../../../types/ocpp/1.6/MeterValues';
13 import {
14 type OCPP16BootNotificationRequest,
15 type OCPP16DataTransferRequest,
16 type OCPP16DiagnosticsStatusNotificationRequest,
17 type OCPP16FirmwareStatusNotificationRequest,
18 type OCPP16HeartbeatRequest,
19 OCPP16RequestCommand,
20 type OCPP16StatusNotificationRequest,
21 } from '../../../types/ocpp/1.6/Requests';
22 import type {
23 OCPP16AuthorizeRequest,
24 OCPP16StartTransactionRequest,
25 OCPP16StopTransactionRequest,
26 } from '../../../types/ocpp/1.6/Transaction';
27 import { ErrorType } from '../../../types/ocpp/ErrorType';
28 import { OCPPVersion } from '../../../types/ocpp/OCPPVersion';
29 import type { RequestParams } from '../../../types/ocpp/Requests';
30 import Constants from '../../../utils/Constants';
31 import Utils from '../../../utils/Utils';
32 import type ChargingStation from '../../ChargingStation';
33 import OCPPConstants from '../OCPPConstants';
34 import OCPPRequestService from '../OCPPRequestService';
35 import type OCPPResponseService from '../OCPPResponseService';
36
37 const moduleName = 'OCPP16RequestService';
38
39 export default class OCPP16RequestService extends OCPPRequestService {
40 protected jsonSchemas: Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>;
41
42 public constructor(ocppResponseService: OCPPResponseService) {
43 if (new.target?.name === moduleName) {
44 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
45 }
46 super(OCPPVersion.VERSION_16, ocppResponseService);
47 this.jsonSchemas = new Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>([
48 [
49 OCPP16RequestCommand.AUTHORIZE,
50 this.parseJsonSchemaFile<OCPP16AuthorizeRequest>(
51 '../../../assets/json-schemas/ocpp/1.6/Authorize.json'
52 ),
53 ],
54 [
55 OCPP16RequestCommand.BOOT_NOTIFICATION,
56 this.parseJsonSchemaFile<OCPP16BootNotificationRequest>(
57 '../../../assets/json-schemas/ocpp/1.6/BootNotification.json'
58 ),
59 ],
60 [
61 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
62 this.parseJsonSchemaFile<OCPP16DiagnosticsStatusNotificationRequest>(
63 '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotification.json'
64 ),
65 ],
66 [
67 OCPP16RequestCommand.HEARTBEAT,
68 this.parseJsonSchemaFile<OCPP16HeartbeatRequest>(
69 '../../../assets/json-schemas/ocpp/1.6/Heartbeat.json'
70 ),
71 ],
72 [
73 OCPP16RequestCommand.METER_VALUES,
74 this.parseJsonSchemaFile<OCPP16MeterValuesRequest>(
75 '../../../assets/json-schemas/ocpp/1.6/MeterValues.json'
76 ),
77 ],
78 [
79 OCPP16RequestCommand.STATUS_NOTIFICATION,
80 this.parseJsonSchemaFile<OCPP16StatusNotificationRequest>(
81 '../../../assets/json-schemas/ocpp/1.6/StatusNotification.json'
82 ),
83 ],
84 [
85 OCPP16RequestCommand.START_TRANSACTION,
86 this.parseJsonSchemaFile<OCPP16StartTransactionRequest>(
87 '../../../assets/json-schemas/ocpp/1.6/StartTransaction.json'
88 ),
89 ],
90 [
91 OCPP16RequestCommand.STOP_TRANSACTION,
92 this.parseJsonSchemaFile<OCPP16StopTransactionRequest>(
93 '../../../assets/json-schemas/ocpp/1.6/StopTransaction.json'
94 ),
95 ],
96 [
97 OCPP16RequestCommand.DATA_TRANSFER,
98 this.parseJsonSchemaFile<OCPP16DataTransferRequest>(
99 '../../../assets/json-schemas/ocpp/1.6/DataTransfer.json'
100 ),
101 ],
102 [
103 OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION,
104 this.parseJsonSchemaFile<OCPP16FirmwareStatusNotificationRequest>(
105 '../../../assets/json-schemas/ocpp/1.6/FirmwareStatusNotification.json'
106 ),
107 ],
108 ]);
109 this.buildRequestPayload.bind(this);
110 }
111
112 public async requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
113 chargingStation: ChargingStation,
114 commandName: OCPP16RequestCommand,
115 commandParams?: JsonType,
116 params?: RequestParams
117 ): Promise<ResponseType> {
118 if (OCPP16ServiceUtils.isRequestCommandSupported(chargingStation, commandName) === true) {
119 const requestPayload = this.buildRequestPayload<RequestType>(
120 chargingStation,
121 commandName,
122 commandParams
123 );
124 return (await this.sendMessage(
125 chargingStation,
126 Utils.generateUUID(),
127 requestPayload,
128 commandName,
129 params
130 )) as unknown as ResponseType;
131 }
132 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
133 throw new OCPPError(
134 ErrorType.NOT_SUPPORTED,
135 `Unsupported OCPP command '${commandName}'`,
136 commandName,
137 commandParams
138 );
139 }
140
141 private buildRequestPayload<Request extends JsonType>(
142 chargingStation: ChargingStation,
143 commandName: OCPP16RequestCommand,
144 commandParams?: JsonType
145 ): Request {
146 let connectorId: number;
147 let energyActiveImportRegister: number;
148 commandParams = commandParams as JsonObject;
149 switch (commandName) {
150 case OCPP16RequestCommand.BOOT_NOTIFICATION:
151 case OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION:
152 case OCPP16RequestCommand.FIRMWARE_STATUS_NOTIFICATION:
153 case OCPP16RequestCommand.METER_VALUES:
154 case OCPP16RequestCommand.STATUS_NOTIFICATION:
155 case OCPP16RequestCommand.DATA_TRANSFER:
156 return commandParams as unknown as Request;
157 case OCPP16RequestCommand.AUTHORIZE:
158 return {
159 idTag: Constants.DEFAULT_IDTAG,
160 ...commandParams,
161 } as unknown as Request;
162 case OCPP16RequestCommand.HEARTBEAT:
163 return OCPPConstants.OCPP_REQUEST_EMPTY as unknown as Request;
164 case OCPP16RequestCommand.START_TRANSACTION:
165 return {
166 idTag: Constants.DEFAULT_IDTAG,
167 meterStart: chargingStation.getEnergyActiveImportRegisterByConnectorId(
168 commandParams?.connectorId as number
169 ),
170 timestamp: new Date(),
171 ...commandParams,
172 } as unknown as Request;
173 case OCPP16RequestCommand.STOP_TRANSACTION:
174 chargingStation.getTransactionDataMeterValues() &&
175 (connectorId = chargingStation.getConnectorIdByTransactionId(
176 commandParams?.transactionId as number
177 ));
178 energyActiveImportRegister = chargingStation.getEnergyActiveImportRegisterByTransactionId(
179 commandParams?.transactionId as number,
180 true
181 );
182 return {
183 idTag: chargingStation.getTransactionIdTag(commandParams?.transactionId as number),
184 meterStop: energyActiveImportRegister,
185 timestamp: new Date(),
186 ...(chargingStation.getTransactionDataMeterValues() && {
187 transactionData: OCPP16ServiceUtils.buildTransactionDataMeterValues(
188 chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue,
189 OCPP16ServiceUtils.buildTransactionEndMeterValue(
190 chargingStation,
191 connectorId,
192 energyActiveImportRegister
193 )
194 ),
195 }),
196 ...commandParams,
197 } as unknown as Request;
198 default:
199 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
200 throw new OCPPError(
201 ErrorType.NOT_SUPPORTED,
202 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
203 `Unsupported OCPP command '${commandName}'`,
204 commandName,
205 commandParams
206 );
207 }
208 }
209
210 private parseJsonSchemaFile<T extends JsonType>(relativePath: string): JSONSchemaType<T> {
211 return JSON.parse(
212 fs.readFileSync(
213 path.resolve(path.dirname(fileURLToPath(import.meta.url)), relativePath),
214 'utf8'
215 )
216 ) as JSONSchemaType<T>;
217 }
218 }