UI Protocol: add Authorize command support
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
CommitLineData
8114d10e 1import BaseError from '../../../exception/BaseError';
9d73266c 2import type OCPPError from '../../../exception/OCPPError';
5a010bf0 3import { Bootstrap } from '../../../internal';
675fa8e3 4import {
32de5a57 5 ProcedureName,
675fa8e3
JB
6 ProtocolRequest,
7 ProtocolRequestHandler,
33cea517 8 ProtocolVersion,
89b7a234 9 RequestPayload,
32de5a57
LM
10 ResponsePayload,
11 ResponseStatus,
675fa8e3 12} from '../../../types/UIProtocol';
0d2cec76
JB
13import type {
14 BroadcastChannelProcedureName,
15 BroadcastChannelRequestPayload,
16} from '../../../types/WorkerBroadcastChannel';
675fa8e3 17import logger from '../../../utils/Logger';
0d2cec76 18import Utils from '../../../utils/Utils';
6c8f5d90 19import UIServiceWorkerBroadcastChannel from '../../UIServiceWorkerBroadcastChannel';
db2336d9 20import type { AbstractUIServer } from '../AbstractUIServer';
4198ad5c 21
32de5a57
LM
22const moduleName = 'AbstractUIService';
23
4198ad5c 24export default abstract class AbstractUIService {
02a6943a 25 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
53870cff
JB
26 private readonly version: ProtocolVersion;
27 private readonly uiServer: AbstractUIServer;
28 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
0d2cec76 29 private readonly broadcastChannelRequests: Map<string, number>;
4198ad5c 30
33cea517
JB
31 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
32 this.version = version;
675fa8e3 33 this.uiServer = uiServer;
02a6943a 34 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
32de5a57
LM
35 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
36 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
37 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)],
4198ad5c 38 ]);
6812b4e1 39 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
0d2cec76 40 this.broadcastChannelRequests = new Map<string, number>();
4198ad5c
JB
41 }
42
5e3cb728 43 public async requestHandler(request: ProtocolRequest): Promise<void> {
98a5256a 44 let messageId: string;
32de5a57 45 let command: ProcedureName;
6c8f5d90 46 let requestPayload: RequestPayload | undefined;
32de5a57
LM
47 let responsePayload: ResponsePayload;
48 try {
5e3cb728 49 [messageId, command, requestPayload] = request;
32de5a57 50
02a6943a 51 if (this.requestHandlers.has(command) === false) {
32de5a57
LM
52 throw new BaseError(
53 `${command} is not implemented to handle message payload ${JSON.stringify(
54 requestPayload,
55 null,
56 2
57 )}`
58 );
4198ad5c 59 }
89b7a234 60
6c8f5d90 61 // Call the request handler to build the response payload
02a6943a 62 responsePayload = await this.requestHandlers.get(command)(messageId, requestPayload);
32de5a57
LM
63 } catch (error) {
64 // Log
1f7fa4de 65 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
6c8f5d90 66 responsePayload = {
9d73266c 67 hashIds: requestPayload.hashIds,
6c8f5d90
JB
68 status: ResponseStatus.FAILURE,
69 command,
70 requestPayload,
71 responsePayload,
72 errorMessage: (error as Error).message,
73 errorStack: (error as Error).stack,
9d73266c 74 errorDetails: (error as OCPPError).details,
6c8f5d90
JB
75 };
76 }
0d2cec76 77 // Send response for payload not forwarded to broadcast channel
6c8f5d90 78 if (responsePayload !== undefined) {
1f7fa4de 79 this.sendResponse(messageId ?? 'error', responsePayload);
4198ad5c 80 }
6c8f5d90
JB
81 }
82
83 public sendRequest(
84 messageId: string,
85 procedureName: ProcedureName,
86 requestPayload: RequestPayload
87 ): void {
852a4c5f
JB
88 this.uiServer.sendRequest(
89 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
90 );
6c8f5d90 91 }
32de5a57 92
6c8f5d90 93 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
852a4c5f 94 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
4198ad5c
JB
95 }
96
6c8f5d90 97 public logPrefix(modName: string, methodName: string): string {
0d2cec76
JB
98 return this.uiServer.logPrefix(modName, methodName, this.version);
99 }
100
101 public deleteBroadcastChannelRequest(uuid: string): void {
102 this.broadcastChannelRequests.delete(uuid);
103 }
104
105 public getBroadcastChannelExpectedResponses(uuid: string): number {
106 return this.broadcastChannelRequests.get(uuid) ?? 0;
107 }
108
109 protected sendBroadcastChannelRequest(
110 uuid: string,
111 procedureName: BroadcastChannelProcedureName,
112 payload: BroadcastChannelRequestPayload
113 ): void {
114 if (!Utils.isEmptyArray(payload.hashIds)) {
115 payload.hashIds = payload.hashIds
116 .map((hashId) => {
117 if (this.uiServer.chargingStations.has(hashId) === true) {
118 return hashId;
119 }
120 logger.warn(
121 `${this.logPrefix(
122 moduleName,
123 'sendBroadcastChannelRequest'
124 )} Charging station with hashId '${hashId}' not found`
125 );
126 })
127 .filter((hashId) => hashId !== undefined);
128 }
129 const expectedNumberOfResponses = !Utils.isEmptyArray(payload.hashIds)
130 ? payload.hashIds.length
131 : this.uiServer.chargingStations.size;
0d2cec76 132 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
853ed24a 133 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
6c8f5d90
JB
134 }
135
89b7a234 136 private handleListChargingStations(): ResponsePayload {
32de5a57
LM
137 return {
138 status: ResponseStatus.SUCCESS,
5e3cb728
JB
139 chargingStations: [...this.uiServer.chargingStations.values()],
140 } as ResponsePayload;
32de5a57
LM
141 }
142
143 private async handleStartSimulator(): Promise<ResponsePayload> {
144 await Bootstrap.getInstance().start();
145 return { status: ResponseStatus.SUCCESS };
146 }
147
148 private async handleStopSimulator(): Promise<ResponsePayload> {
149 await Bootstrap.getInstance().stop();
150 return { status: ResponseStatus.SUCCESS };
4198ad5c
JB
151 }
152}