UI services: fix broadcast channel reponse handler with one hashId only
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16ResponseService.ts
1 // Partial Copyright Jerome Benoit. 2021. 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 OCPPError from '../../../exception/OCPPError';
10 import type { JsonObject, JsonType } from '../../../types/JsonType';
11 import { OCPP16ChargePointErrorCode } from '../../../types/ocpp/1.6/ChargePointErrorCode';
12 import { OCPP16ChargePointStatus } from '../../../types/ocpp/1.6/ChargePointStatus';
13 import { OCPP16StandardParametersKey } from '../../../types/ocpp/1.6/Configuration';
14 import type {
15 OCPP16MeterValuesRequest,
16 OCPP16MeterValuesResponse,
17 } from '../../../types/ocpp/1.6/MeterValues';
18 import {
19 OCPP16BootNotificationRequest,
20 OCPP16RequestCommand,
21 OCPP16StatusNotificationRequest,
22 } from '../../../types/ocpp/1.6/Requests';
23 import {
24 DiagnosticsStatusNotificationResponse,
25 OCPP16BootNotificationResponse,
26 OCPP16HeartbeatResponse,
27 OCPP16RegistrationStatus,
28 OCPP16StatusNotificationResponse,
29 } from '../../../types/ocpp/1.6/Responses';
30 import {
31 OCPP16AuthorizationStatus,
32 OCPP16AuthorizeRequest,
33 OCPP16AuthorizeResponse,
34 OCPP16StartTransactionRequest,
35 OCPP16StartTransactionResponse,
36 OCPP16StopTransactionRequest,
37 OCPP16StopTransactionResponse,
38 } from '../../../types/ocpp/1.6/Transaction';
39 import { ErrorType } from '../../../types/ocpp/ErrorType';
40 import type { ResponseHandler } from '../../../types/ocpp/Responses';
41 import logger from '../../../utils/Logger';
42 import Utils from '../../../utils/Utils';
43 import type ChargingStation from '../../ChargingStation';
44 import { ChargingStationConfigurationUtils } from '../../ChargingStationConfigurationUtils';
45 import { ChargingStationUtils } from '../../ChargingStationUtils';
46 import OCPPResponseService from '../OCPPResponseService';
47 import { OCPP16ServiceUtils } from './OCPP16ServiceUtils';
48
49 const moduleName = 'OCPP16ResponseService';
50
51 export default class OCPP16ResponseService extends OCPPResponseService {
52 private responseHandlers: Map<OCPP16RequestCommand, ResponseHandler>;
53 private jsonSchemas: Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>;
54
55 public constructor() {
56 if (new.target?.name === moduleName) {
57 throw new TypeError(`Cannot construct ${new.target?.name} instances directly`);
58 }
59 super();
60 this.responseHandlers = new Map<OCPP16RequestCommand, ResponseHandler>([
61 [OCPP16RequestCommand.BOOT_NOTIFICATION, this.handleResponseBootNotification.bind(this)],
62 [OCPP16RequestCommand.HEARTBEAT, this.emptyResponseHandler.bind(this)],
63 [OCPP16RequestCommand.AUTHORIZE, this.handleResponseAuthorize.bind(this)],
64 [OCPP16RequestCommand.START_TRANSACTION, this.handleResponseStartTransaction.bind(this)],
65 [OCPP16RequestCommand.STOP_TRANSACTION, this.handleResponseStopTransaction.bind(this)],
66 [OCPP16RequestCommand.STATUS_NOTIFICATION, this.emptyResponseHandler.bind(this)],
67 [OCPP16RequestCommand.METER_VALUES, this.emptyResponseHandler.bind(this)],
68 [OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION, this.emptyResponseHandler.bind(this)],
69 ]);
70 this.jsonSchemas = new Map<OCPP16RequestCommand, JSONSchemaType<JsonObject>>([
71 [
72 OCPP16RequestCommand.BOOT_NOTIFICATION,
73 JSON.parse(
74 fs.readFileSync(
75 path.resolve(
76 path.dirname(fileURLToPath(import.meta.url)),
77 '../../../assets/json-schemas/ocpp/1.6/BootNotificationResponse.json'
78 ),
79 'utf8'
80 )
81 ) as JSONSchemaType<OCPP16BootNotificationResponse>,
82 ],
83 [
84 OCPP16RequestCommand.HEARTBEAT,
85 JSON.parse(
86 fs.readFileSync(
87 path.resolve(
88 path.dirname(fileURLToPath(import.meta.url)),
89 '../../../assets/json-schemas/ocpp/1.6/HeartbeatResponse.json'
90 ),
91 'utf8'
92 )
93 ) as JSONSchemaType<OCPP16HeartbeatResponse>,
94 ],
95 [
96 OCPP16RequestCommand.AUTHORIZE,
97 JSON.parse(
98 fs.readFileSync(
99 path.resolve(
100 path.dirname(fileURLToPath(import.meta.url)),
101 '../../../assets/json-schemas/ocpp/1.6/AuthorizeResponse.json'
102 ),
103 'utf8'
104 )
105 ) as JSONSchemaType<OCPP16AuthorizeResponse>,
106 ],
107 [
108 OCPP16RequestCommand.START_TRANSACTION,
109 JSON.parse(
110 fs.readFileSync(
111 path.resolve(
112 path.dirname(fileURLToPath(import.meta.url)),
113 '../../../assets/json-schemas/ocpp/1.6/StartTransactionResponse.json'
114 ),
115 'utf8'
116 )
117 ) as JSONSchemaType<OCPP16StartTransactionResponse>,
118 ],
119 [
120 OCPP16RequestCommand.STOP_TRANSACTION,
121 JSON.parse(
122 fs.readFileSync(
123 path.resolve(
124 path.dirname(fileURLToPath(import.meta.url)),
125 '../../../assets/json-schemas/ocpp/1.6/StopTransactionResponse.json'
126 ),
127 'utf8'
128 )
129 ) as JSONSchemaType<OCPP16StopTransactionResponse>,
130 ],
131 [
132 OCPP16RequestCommand.STATUS_NOTIFICATION,
133 JSON.parse(
134 fs.readFileSync(
135 path.resolve(
136 path.dirname(fileURLToPath(import.meta.url)),
137 '../../../assets/json-schemas/ocpp/1.6/StatusNotificationResponse.json'
138 ),
139 'utf8'
140 )
141 ) as JSONSchemaType<OCPP16StatusNotificationResponse>,
142 ],
143 [
144 OCPP16RequestCommand.METER_VALUES,
145 JSON.parse(
146 fs.readFileSync(
147 path.resolve(
148 path.dirname(fileURLToPath(import.meta.url)),
149 '../../../assets/json-schemas/ocpp/1.6/MeterValuesResponse.json'
150 ),
151 'utf8'
152 )
153 ) as JSONSchemaType<OCPP16MeterValuesResponse>,
154 ],
155 [
156 OCPP16RequestCommand.DIAGNOSTICS_STATUS_NOTIFICATION,
157 JSON.parse(
158 fs.readFileSync(
159 path.resolve(
160 path.dirname(fileURLToPath(import.meta.url)),
161 '../../../assets/json-schemas/ocpp/1.6/DiagnosticsStatusNotificationResponse.json'
162 ),
163 'utf8'
164 )
165 ) as JSONSchemaType<DiagnosticsStatusNotificationResponse>,
166 ],
167 ]);
168 this.validatePayload.bind(this);
169 }
170
171 public async responseHandler(
172 chargingStation: ChargingStation,
173 commandName: OCPP16RequestCommand,
174 payload: JsonType,
175 requestPayload: JsonType
176 ): Promise<void> {
177 if (chargingStation.isRegistered() || commandName === OCPP16RequestCommand.BOOT_NOTIFICATION) {
178 if (
179 this.responseHandlers.has(commandName) &&
180 ChargingStationUtils.isRequestCommandSupported(commandName, chargingStation)
181 ) {
182 try {
183 this.validatePayload(chargingStation, commandName, payload);
184 await this.responseHandlers.get(commandName)(chargingStation, payload, requestPayload);
185 } catch (error) {
186 logger.error(
187 `${chargingStation.logPrefix()} ${moduleName}.responseHandler: Handle response error:`,
188 error
189 );
190 throw error;
191 }
192 } else {
193 // Throw exception
194 throw new OCPPError(
195 ErrorType.NOT_IMPLEMENTED,
196 `${commandName} is not implemented to handle response PDU ${JSON.stringify(
197 payload,
198 null,
199 2
200 )}`,
201 commandName,
202 payload
203 );
204 }
205 } else {
206 throw new OCPPError(
207 ErrorType.SECURITY_ERROR,
208 `${commandName} cannot be issued to handle response PDU ${JSON.stringify(
209 payload,
210 null,
211 2
212 )} while the charging station is not registered on the central server. `,
213 commandName,
214 payload
215 );
216 }
217 }
218
219 private validatePayload(
220 chargingStation: ChargingStation,
221 commandName: OCPP16RequestCommand,
222 payload: JsonType
223 ): boolean {
224 if (this.jsonSchemas.has(commandName)) {
225 return this.validateResponsePayload(
226 chargingStation,
227 commandName,
228 this.jsonSchemas.get(commandName),
229 payload
230 );
231 }
232 logger.warn(
233 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema found for command ${commandName} PDU validation`
234 );
235 return false;
236 }
237
238 private handleResponseBootNotification(
239 chargingStation: ChargingStation,
240 payload: OCPP16BootNotificationResponse
241 ): void {
242 if (payload.status === OCPP16RegistrationStatus.ACCEPTED) {
243 ChargingStationConfigurationUtils.addConfigurationKey(
244 chargingStation,
245 OCPP16StandardParametersKey.HeartbeatInterval,
246 payload.interval.toString(),
247 {},
248 { overwrite: true, save: true }
249 );
250 ChargingStationConfigurationUtils.addConfigurationKey(
251 chargingStation,
252 OCPP16StandardParametersKey.HeartBeatInterval,
253 payload.interval.toString(),
254 { visible: false },
255 { overwrite: true, save: true }
256 );
257 chargingStation.heartbeatSetInterval
258 ? chargingStation.restartHeartbeat()
259 : chargingStation.startHeartbeat();
260 }
261 if (Object.values(OCPP16RegistrationStatus).includes(payload.status)) {
262 const logMsg = `${chargingStation.logPrefix()} Charging station in '${
263 payload.status
264 }' state on the central server`;
265 payload.status === OCPP16RegistrationStatus.REJECTED
266 ? logger.warn(logMsg)
267 : logger.info(logMsg);
268 } else {
269 logger.error(
270 chargingStation.logPrefix() +
271 ' Charging station boot notification response received: %j with undefined registration status',
272 payload
273 );
274 }
275 }
276
277 private handleResponseAuthorize(
278 chargingStation: ChargingStation,
279 payload: OCPP16AuthorizeResponse,
280 requestPayload: OCPP16AuthorizeRequest
281 ): void {
282 let authorizeConnectorId: number;
283 for (const connectorId of chargingStation.connectors.keys()) {
284 if (
285 connectorId > 0 &&
286 chargingStation.getConnectorStatus(connectorId)?.authorizeIdTag === requestPayload.idTag
287 ) {
288 authorizeConnectorId = connectorId;
289 break;
290 }
291 }
292 if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) {
293 chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = true;
294 logger.debug(
295 `${chargingStation.logPrefix()} IdTag '${
296 requestPayload.idTag
297 }' authorized on connector ${authorizeConnectorId}`
298 );
299 } else {
300 chargingStation.getConnectorStatus(authorizeConnectorId).idTagAuthorized = false;
301 delete chargingStation.getConnectorStatus(authorizeConnectorId).authorizeIdTag;
302 logger.debug(
303 `${chargingStation.logPrefix()} IdTag '${requestPayload.idTag}' refused with status '${
304 payload.idTagInfo.status
305 }' on connector ${authorizeConnectorId}`
306 );
307 }
308 }
309
310 private async handleResponseStartTransaction(
311 chargingStation: ChargingStation,
312 payload: OCPP16StartTransactionResponse,
313 requestPayload: OCPP16StartTransactionRequest
314 ): Promise<void> {
315 const connectorId = requestPayload.connectorId;
316
317 let transactionConnectorId: number;
318 for (const id of chargingStation.connectors.keys()) {
319 if (id > 0 && id === connectorId) {
320 transactionConnectorId = id;
321 break;
322 }
323 }
324 if (!transactionConnectorId) {
325 logger.error(
326 chargingStation.logPrefix() +
327 ' Trying to start a transaction on a non existing connector Id ' +
328 connectorId.toString()
329 );
330 return;
331 }
332 if (
333 chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true &&
334 chargingStation.getAuthorizeRemoteTxRequests() &&
335 chargingStation.getLocalAuthListEnabled() &&
336 chargingStation.hasAuthorizedTags() &&
337 chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false
338 ) {
339 logger.error(
340 chargingStation.logPrefix() +
341 ' Trying to start a transaction with a not local authorized idTag ' +
342 chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag +
343 ' on connector Id ' +
344 connectorId.toString()
345 );
346 await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
347 return;
348 }
349 if (
350 chargingStation.getConnectorStatus(connectorId).transactionRemoteStarted === true &&
351 chargingStation.getAuthorizeRemoteTxRequests() &&
352 chargingStation.getMustAuthorizeAtRemoteStart() &&
353 chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized === false &&
354 chargingStation.getConnectorStatus(connectorId).idTagAuthorized === false
355 ) {
356 logger.error(
357 chargingStation.logPrefix() +
358 ' Trying to start a transaction with a not authorized idTag ' +
359 chargingStation.getConnectorStatus(connectorId).authorizeIdTag +
360 ' on connector Id ' +
361 connectorId.toString()
362 );
363 await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
364 return;
365 }
366 if (
367 chargingStation.getConnectorStatus(connectorId).idTagAuthorized &&
368 chargingStation.getConnectorStatus(connectorId).authorizeIdTag !== requestPayload.idTag
369 ) {
370 logger.error(
371 chargingStation.logPrefix() +
372 ' Trying to start a transaction with an idTag ' +
373 requestPayload.idTag +
374 ' different from the authorize request one ' +
375 chargingStation.getConnectorStatus(connectorId).authorizeIdTag +
376 ' on connector Id ' +
377 connectorId.toString()
378 );
379 await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
380 return;
381 }
382 if (
383 chargingStation.getConnectorStatus(connectorId).idTagLocalAuthorized &&
384 chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag !== requestPayload.idTag
385 ) {
386 logger.error(
387 chargingStation.logPrefix() +
388 ' Trying to start a transaction with an idTag ' +
389 requestPayload.idTag +
390 ' different from the local authorized one ' +
391 chargingStation.getConnectorStatus(connectorId).localAuthorizeIdTag +
392 ' on connector Id ' +
393 connectorId.toString()
394 );
395 await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
396 return;
397 }
398 if (chargingStation.getConnectorStatus(connectorId)?.transactionStarted === true) {
399 logger.debug(
400 chargingStation.logPrefix() +
401 ' Trying to start a transaction on an already used connector ' +
402 connectorId.toString() +
403 ': %j',
404 chargingStation.getConnectorStatus(connectorId)
405 );
406 return;
407 }
408 if (
409 chargingStation.getConnectorStatus(connectorId)?.status !==
410 OCPP16ChargePointStatus.AVAILABLE &&
411 chargingStation.getConnectorStatus(connectorId)?.status !== OCPP16ChargePointStatus.PREPARING
412 ) {
413 logger.error(
414 `${chargingStation.logPrefix()} Trying to start a transaction on connector ${connectorId.toString()} with status ${
415 chargingStation.getConnectorStatus(connectorId)?.status
416 }`
417 );
418 return;
419 }
420 // if (!Number.isInteger(payload.transactionId)) {
421 // logger.warn(
422 // `${chargingStation.logPrefix()} Trying to start a transaction on connector ${connectorId.toString()} with a non integer transaction Id ${
423 // payload.transactionId
424 // }, converting to integer`
425 // );
426 // payload.transactionId = Utils.convertToInt(payload.transactionId);
427 // }
428
429 if (payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
430 chargingStation.getConnectorStatus(connectorId).transactionStarted = true;
431 chargingStation.getConnectorStatus(connectorId).transactionId = payload.transactionId;
432 chargingStation.getConnectorStatus(connectorId).transactionIdTag = requestPayload.idTag;
433 chargingStation.getConnectorStatus(
434 connectorId
435 ).transactionEnergyActiveImportRegisterValue = 0;
436 chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue =
437 OCPP16ServiceUtils.buildTransactionBeginMeterValue(
438 chargingStation,
439 connectorId,
440 requestPayload.meterStart
441 );
442 chargingStation.getBeginEndMeterValues() &&
443 (await chargingStation.ocppRequestService.requestHandler<
444 OCPP16MeterValuesRequest,
445 OCPP16MeterValuesResponse
446 >(chargingStation, OCPP16RequestCommand.METER_VALUES, {
447 connectorId,
448 transactionId: payload.transactionId,
449 meterValue: [chargingStation.getConnectorStatus(connectorId).transactionBeginMeterValue],
450 }));
451 await chargingStation.ocppRequestService.requestHandler<
452 OCPP16StatusNotificationRequest,
453 OCPP16StatusNotificationResponse
454 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
455 connectorId,
456 status: OCPP16ChargePointStatus.CHARGING,
457 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
458 });
459 chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.CHARGING;
460 logger.info(
461 chargingStation.logPrefix() +
462 ' Transaction ' +
463 payload.transactionId.toString() +
464 ' STARTED on ' +
465 chargingStation.stationInfo.chargingStationId +
466 '#' +
467 connectorId.toString() +
468 " for idTag '" +
469 requestPayload.idTag +
470 "'"
471 );
472 if (chargingStation.stationInfo.powerSharedByConnectors) {
473 chargingStation.powerDivider++;
474 }
475 const configuredMeterValueSampleInterval =
476 ChargingStationConfigurationUtils.getConfigurationKey(
477 chargingStation,
478 OCPP16StandardParametersKey.MeterValueSampleInterval
479 );
480 chargingStation.startMeterValues(
481 connectorId,
482 configuredMeterValueSampleInterval
483 ? Utils.convertToInt(configuredMeterValueSampleInterval.value) * 1000
484 : 60000
485 );
486 } else {
487 logger.warn(
488 chargingStation.logPrefix() +
489 ' Starting transaction id ' +
490 payload.transactionId.toString() +
491 " REJECTED with status '" +
492 payload?.idTagInfo?.status +
493 "', idTag '" +
494 requestPayload.idTag +
495 "'"
496 );
497 await this.resetConnectorOnStartTransactionError(chargingStation, connectorId);
498 }
499 }
500
501 private async resetConnectorOnStartTransactionError(
502 chargingStation: ChargingStation,
503 connectorId: number
504 ): Promise<void> {
505 chargingStation.resetConnectorStatus(connectorId);
506 if (
507 chargingStation.getConnectorStatus(connectorId).status !== OCPP16ChargePointStatus.AVAILABLE
508 ) {
509 await chargingStation.ocppRequestService.requestHandler<
510 OCPP16StatusNotificationRequest,
511 OCPP16StatusNotificationResponse
512 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
513 connectorId,
514 status: OCPP16ChargePointStatus.AVAILABLE,
515 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
516 });
517 chargingStation.getConnectorStatus(connectorId).status = OCPP16ChargePointStatus.AVAILABLE;
518 }
519 }
520
521 private async handleResponseStopTransaction(
522 chargingStation: ChargingStation,
523 payload: OCPP16StopTransactionResponse,
524 requestPayload: OCPP16StopTransactionRequest
525 ): Promise<void> {
526 const transactionConnectorId = chargingStation.getConnectorIdByTransactionId(
527 requestPayload.transactionId
528 );
529 if (!transactionConnectorId) {
530 logger.error(
531 chargingStation.logPrefix() +
532 ' Trying to stop a non existing transaction ' +
533 requestPayload.transactionId.toString()
534 );
535 return;
536 }
537 if (payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED) {
538 chargingStation.getBeginEndMeterValues() &&
539 !chargingStation.getOcppStrictCompliance() &&
540 chargingStation.getOutOfOrderEndMeterValues() &&
541 (await chargingStation.ocppRequestService.requestHandler<
542 OCPP16MeterValuesRequest,
543 OCPP16MeterValuesResponse
544 >(chargingStation, OCPP16RequestCommand.METER_VALUES, {
545 connectorId: transactionConnectorId,
546 transactionId: requestPayload.transactionId,
547 meterValue: [
548 OCPP16ServiceUtils.buildTransactionEndMeterValue(
549 chargingStation,
550 transactionConnectorId,
551 requestPayload.meterStop
552 ),
553 ],
554 }));
555 if (
556 !chargingStation.isChargingStationAvailable() ||
557 !chargingStation.isConnectorAvailable(transactionConnectorId)
558 ) {
559 await chargingStation.ocppRequestService.requestHandler<
560 OCPP16StatusNotificationRequest,
561 OCPP16StatusNotificationResponse
562 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
563 connectorId: transactionConnectorId,
564 status: OCPP16ChargePointStatus.UNAVAILABLE,
565 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
566 });
567 chargingStation.getConnectorStatus(transactionConnectorId).status =
568 OCPP16ChargePointStatus.UNAVAILABLE;
569 } else {
570 await chargingStation.ocppRequestService.requestHandler<
571 OCPP16BootNotificationRequest,
572 OCPP16BootNotificationResponse
573 >(chargingStation, OCPP16RequestCommand.STATUS_NOTIFICATION, {
574 connectorId: transactionConnectorId,
575 status: OCPP16ChargePointStatus.AVAILABLE,
576 errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
577 });
578 chargingStation.getConnectorStatus(transactionConnectorId).status =
579 OCPP16ChargePointStatus.AVAILABLE;
580 }
581 if (chargingStation.stationInfo.powerSharedByConnectors) {
582 chargingStation.powerDivider--;
583 }
584 chargingStation.resetConnectorStatus(transactionConnectorId);
585 logger.info(
586 chargingStation.logPrefix() +
587 ' Transaction ' +
588 requestPayload.transactionId.toString() +
589 ' STOPPED on ' +
590 chargingStation.stationInfo.chargingStationId +
591 '#' +
592 transactionConnectorId.toString()
593 );
594 } else {
595 logger.warn(
596 chargingStation.logPrefix() +
597 ' Stopping transaction id ' +
598 requestPayload.transactionId.toString() +
599 " REJECTED with status '" +
600 payload.idTagInfo?.status +
601 "'"
602 );
603 }
604 }
605 }