UI Protocol: add boot notification 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,
976d11ec
JB
6 type ProtocolRequest,
7 type ProtocolRequestHandler,
8 type ProtocolVersion,
9 type RequestPayload,
10 type ResponsePayload,
32de5a57 11 ResponseStatus,
675fa8e3 12} from '../../../types/UIProtocol';
976d11ec 13import {
0d2cec76 14 BroadcastChannelProcedureName,
976d11ec 15 type BroadcastChannelRequestPayload,
0d2cec76 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 {
5083d31a 25 private static readonly ProcedureNameToBroadCastChannelProcedureNameMap: Omit<
976d11ec
JB
26 Record<ProcedureName, BroadcastChannelProcedureName>,
27 'startSimulator' | 'stopSimulator' | 'listChargingStations'
28 > = {
29 [ProcedureName.START_CHARGING_STATION]: BroadcastChannelProcedureName.START_CHARGING_STATION,
30 [ProcedureName.STOP_CHARGING_STATION]: BroadcastChannelProcedureName.STOP_CHARGING_STATION,
31 [ProcedureName.CLOSE_CONNECTION]: BroadcastChannelProcedureName.CLOSE_CONNECTION,
32 [ProcedureName.OPEN_CONNECTION]: BroadcastChannelProcedureName.OPEN_CONNECTION,
33 [ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR]:
34 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
35 [ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR]:
36 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
37 [ProcedureName.START_TRANSACTION]: BroadcastChannelProcedureName.START_TRANSACTION,
38 [ProcedureName.STOP_TRANSACTION]: BroadcastChannelProcedureName.STOP_TRANSACTION,
39 [ProcedureName.AUTHORIZE]: BroadcastChannelProcedureName.AUTHORIZE,
8bfbc743 40 [ProcedureName.BOOT_NOTIFICATION]: BroadcastChannelProcedureName.BOOT_NOTIFICATION,
976d11ec
JB
41 [ProcedureName.STATUS_NOTIFICATION]: BroadcastChannelProcedureName.STATUS_NOTIFICATION,
42 [ProcedureName.HEARTBEAT]: BroadcastChannelProcedureName.HEARTBEAT,
43 [ProcedureName.METER_VALUES]: BroadcastChannelProcedureName.METER_VALUES,
44 };
45
02a6943a 46 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
53870cff
JB
47 private readonly version: ProtocolVersion;
48 private readonly uiServer: AbstractUIServer;
49 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
0d2cec76 50 private readonly broadcastChannelRequests: Map<string, number>;
4198ad5c 51
33cea517 52 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
675fa8e3 53 this.uiServer = uiServer;
976d11ec 54 this.version = version;
02a6943a 55 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
32de5a57
LM
56 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
57 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
58 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)],
4198ad5c 59 ]);
6812b4e1 60 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
0d2cec76 61 this.broadcastChannelRequests = new Map<string, number>();
4198ad5c
JB
62 }
63
5e3cb728 64 public async requestHandler(request: ProtocolRequest): Promise<void> {
98a5256a 65 let messageId: string;
32de5a57 66 let command: ProcedureName;
6c8f5d90 67 let requestPayload: RequestPayload | undefined;
32de5a57
LM
68 let responsePayload: ResponsePayload;
69 try {
5e3cb728 70 [messageId, command, requestPayload] = request;
32de5a57 71
02a6943a 72 if (this.requestHandlers.has(command) === false) {
32de5a57
LM
73 throw new BaseError(
74 `${command} is not implemented to handle message payload ${JSON.stringify(
75 requestPayload,
76 null,
77 2
78 )}`
79 );
4198ad5c 80 }
89b7a234 81
6c8f5d90 82 // Call the request handler to build the response payload
5e8e29f4 83 responsePayload = await this.requestHandlers.get(command)(messageId, command, requestPayload);
32de5a57
LM
84 } catch (error) {
85 // Log
1f7fa4de 86 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
6c8f5d90 87 responsePayload = {
9d73266c 88 hashIds: requestPayload.hashIds,
6c8f5d90
JB
89 status: ResponseStatus.FAILURE,
90 command,
91 requestPayload,
92 responsePayload,
93 errorMessage: (error as Error).message,
94 errorStack: (error as Error).stack,
9d73266c 95 errorDetails: (error as OCPPError).details,
6c8f5d90 96 };
623b39b5
JB
97 } finally {
98 // Send response for payload not forwarded to broadcast channel
99 if (responsePayload !== undefined) {
d3195f0a 100 this.sendResponse(messageId, responsePayload);
623b39b5 101 }
4198ad5c 102 }
6c8f5d90
JB
103 }
104
105 public sendRequest(
106 messageId: string,
107 procedureName: ProcedureName,
108 requestPayload: RequestPayload
109 ): void {
852a4c5f
JB
110 this.uiServer.sendRequest(
111 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
112 );
6c8f5d90 113 }
32de5a57 114
6c8f5d90 115 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
852a4c5f 116 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
4198ad5c
JB
117 }
118
6c8f5d90 119 public logPrefix(modName: string, methodName: string): string {
0d2cec76
JB
120 return this.uiServer.logPrefix(modName, methodName, this.version);
121 }
122
123 public deleteBroadcastChannelRequest(uuid: string): void {
124 this.broadcastChannelRequests.delete(uuid);
125 }
126
127 public getBroadcastChannelExpectedResponses(uuid: string): number {
128 return this.broadcastChannelRequests.get(uuid) ?? 0;
129 }
130
2a3cf7fc
JB
131 protected handleProtocolRequest(
132 uuid: string,
133 procedureName: ProcedureName,
134 payload: RequestPayload
135 ): void {
136 this.sendBroadcastChannelRequest(
137 uuid,
138 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMap[
139 procedureName
140 ] as BroadcastChannelProcedureName,
141 payload
142 );
143 }
144
145 private sendBroadcastChannelRequest(
0d2cec76
JB
146 uuid: string,
147 procedureName: BroadcastChannelProcedureName,
148 payload: BroadcastChannelRequestPayload
149 ): void {
150 if (!Utils.isEmptyArray(payload.hashIds)) {
151 payload.hashIds = payload.hashIds
152 .map((hashId) => {
153 if (this.uiServer.chargingStations.has(hashId) === true) {
154 return hashId;
155 }
156 logger.warn(
157 `${this.logPrefix(
158 moduleName,
159 'sendBroadcastChannelRequest'
160 )} Charging station with hashId '${hashId}' not found`
161 );
162 })
163 .filter((hashId) => hashId !== undefined);
164 }
165 const expectedNumberOfResponses = !Utils.isEmptyArray(payload.hashIds)
166 ? payload.hashIds.length
167 : this.uiServer.chargingStations.size;
0d2cec76 168 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
853ed24a 169 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
6c8f5d90
JB
170 }
171
89b7a234 172 private handleListChargingStations(): ResponsePayload {
32de5a57
LM
173 return {
174 status: ResponseStatus.SUCCESS,
5e3cb728
JB
175 chargingStations: [...this.uiServer.chargingStations.values()],
176 } as ResponsePayload;
32de5a57
LM
177 }
178
179 private async handleStartSimulator(): Promise<ResponsePayload> {
180 await Bootstrap.getInstance().start();
181 return { status: ResponseStatus.SUCCESS };
182 }
183
184 private async handleStopSimulator(): Promise<ResponsePayload> {
185 await Bootstrap.getInstance().stop();
186 return { status: ResponseStatus.SUCCESS };
4198ad5c
JB
187 }
188}