UI Protocol: add boot notification command support
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
1 import BaseError from '../../../exception/BaseError';
2 import type OCPPError from '../../../exception/OCPPError';
3 import { Bootstrap } from '../../../internal';
4 import {
5 ProcedureName,
6 type ProtocolRequest,
7 type ProtocolRequestHandler,
8 type ProtocolVersion,
9 type RequestPayload,
10 type ResponsePayload,
11 ResponseStatus,
12 } from '../../../types/UIProtocol';
13 import {
14 BroadcastChannelProcedureName,
15 type BroadcastChannelRequestPayload,
16 } from '../../../types/WorkerBroadcastChannel';
17 import logger from '../../../utils/Logger';
18 import Utils from '../../../utils/Utils';
19 import UIServiceWorkerBroadcastChannel from '../../UIServiceWorkerBroadcastChannel';
20 import type { AbstractUIServer } from '../AbstractUIServer';
21
22 const moduleName = 'AbstractUIService';
23
24 export default abstract class AbstractUIService {
25 private static readonly ProcedureNameToBroadCastChannelProcedureNameMap: Omit<
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,
40 [ProcedureName.BOOT_NOTIFICATION]: BroadcastChannelProcedureName.BOOT_NOTIFICATION,
41 [ProcedureName.STATUS_NOTIFICATION]: BroadcastChannelProcedureName.STATUS_NOTIFICATION,
42 [ProcedureName.HEARTBEAT]: BroadcastChannelProcedureName.HEARTBEAT,
43 [ProcedureName.METER_VALUES]: BroadcastChannelProcedureName.METER_VALUES,
44 };
45
46 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
47 private readonly version: ProtocolVersion;
48 private readonly uiServer: AbstractUIServer;
49 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
50 private readonly broadcastChannelRequests: Map<string, number>;
51
52 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
53 this.uiServer = uiServer;
54 this.version = version;
55 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
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)],
59 ]);
60 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
61 this.broadcastChannelRequests = new Map<string, number>();
62 }
63
64 public async requestHandler(request: ProtocolRequest): Promise<void> {
65 let messageId: string;
66 let command: ProcedureName;
67 let requestPayload: RequestPayload | undefined;
68 let responsePayload: ResponsePayload;
69 try {
70 [messageId, command, requestPayload] = request;
71
72 if (this.requestHandlers.has(command) === false) {
73 throw new BaseError(
74 `${command} is not implemented to handle message payload ${JSON.stringify(
75 requestPayload,
76 null,
77 2
78 )}`
79 );
80 }
81
82 // Call the request handler to build the response payload
83 responsePayload = await this.requestHandlers.get(command)(messageId, command, requestPayload);
84 } catch (error) {
85 // Log
86 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
87 responsePayload = {
88 hashIds: requestPayload.hashIds,
89 status: ResponseStatus.FAILURE,
90 command,
91 requestPayload,
92 responsePayload,
93 errorMessage: (error as Error).message,
94 errorStack: (error as Error).stack,
95 errorDetails: (error as OCPPError).details,
96 };
97 } finally {
98 // Send response for payload not forwarded to broadcast channel
99 if (responsePayload !== undefined) {
100 this.sendResponse(messageId, responsePayload);
101 }
102 }
103 }
104
105 public sendRequest(
106 messageId: string,
107 procedureName: ProcedureName,
108 requestPayload: RequestPayload
109 ): void {
110 this.uiServer.sendRequest(
111 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
112 );
113 }
114
115 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
116 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
117 }
118
119 public logPrefix(modName: string, methodName: string): string {
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
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(
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;
168 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
169 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
170 }
171
172 private handleListChargingStations(): ResponsePayload {
173 return {
174 status: ResponseStatus.SUCCESS,
175 chargingStations: [...this.uiServer.chargingStations.values()],
176 } as ResponsePayload;
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 };
187 }
188 }