UI protocol: add meter values command
[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 ProtocolRequest,
7 ProtocolRequestHandler,
8 ProtocolVersion,
9 RequestPayload,
10 ResponsePayload,
11 ResponseStatus,
12 } from '../../../types/UIProtocol';
13 import type {
14 BroadcastChannelProcedureName,
15 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 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>;
26 private readonly version: ProtocolVersion;
27 private readonly uiServer: AbstractUIServer;
28 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel;
29 private readonly broadcastChannelRequests: Map<string, number>;
30
31 constructor(uiServer: AbstractUIServer, version: ProtocolVersion) {
32 this.version = version;
33 this.uiServer = uiServer;
34 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
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)],
38 ]);
39 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this);
40 this.broadcastChannelRequests = new Map<string, number>();
41 }
42
43 public async requestHandler(request: ProtocolRequest): Promise<void> {
44 let messageId: string;
45 let command: ProcedureName;
46 let requestPayload: RequestPayload | undefined;
47 let responsePayload: ResponsePayload;
48 try {
49 [messageId, command, requestPayload] = request;
50
51 if (this.requestHandlers.has(command) === false) {
52 throw new BaseError(
53 `${command} is not implemented to handle message payload ${JSON.stringify(
54 requestPayload,
55 null,
56 2
57 )}`
58 );
59 }
60
61 // Call the request handler to build the response payload
62 responsePayload = await this.requestHandlers.get(command)(messageId, command, requestPayload);
63 } catch (error) {
64 // Log
65 logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
66 responsePayload = {
67 hashIds: requestPayload.hashIds,
68 status: ResponseStatus.FAILURE,
69 command,
70 requestPayload,
71 responsePayload,
72 errorMessage: (error as Error).message,
73 errorStack: (error as Error).stack,
74 errorDetails: (error as OCPPError).details,
75 };
76 } finally {
77 // Send response for payload not forwarded to broadcast channel
78 if (responsePayload !== undefined) {
79 this.sendResponse(messageId, responsePayload);
80 }
81 }
82 }
83
84 public sendRequest(
85 messageId: string,
86 procedureName: ProcedureName,
87 requestPayload: RequestPayload
88 ): void {
89 this.uiServer.sendRequest(
90 this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
91 );
92 }
93
94 public sendResponse(messageId: string, responsePayload: ResponsePayload): void {
95 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload));
96 }
97
98 public logPrefix(modName: string, methodName: string): string {
99 return this.uiServer.logPrefix(modName, methodName, this.version);
100 }
101
102 public deleteBroadcastChannelRequest(uuid: string): void {
103 this.broadcastChannelRequests.delete(uuid);
104 }
105
106 public getBroadcastChannelExpectedResponses(uuid: string): number {
107 return this.broadcastChannelRequests.get(uuid) ?? 0;
108 }
109
110 protected sendBroadcastChannelRequest(
111 uuid: string,
112 procedureName: BroadcastChannelProcedureName,
113 payload: BroadcastChannelRequestPayload
114 ): void {
115 if (!Utils.isEmptyArray(payload.hashIds)) {
116 payload.hashIds = payload.hashIds
117 .map((hashId) => {
118 if (this.uiServer.chargingStations.has(hashId) === true) {
119 return hashId;
120 }
121 logger.warn(
122 `${this.logPrefix(
123 moduleName,
124 'sendBroadcastChannelRequest'
125 )} Charging station with hashId '${hashId}' not found`
126 );
127 })
128 .filter((hashId) => hashId !== undefined);
129 }
130 const expectedNumberOfResponses = !Utils.isEmptyArray(payload.hashIds)
131 ? payload.hashIds.length
132 : this.uiServer.chargingStations.size;
133 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload]);
134 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses);
135 }
136
137 private handleListChargingStations(): ResponsePayload {
138 return {
139 status: ResponseStatus.SUCCESS,
140 chargingStations: [...this.uiServer.chargingStations.values()],
141 } as ResponsePayload;
142 }
143
144 private async handleStartSimulator(): Promise<ResponsePayload> {
145 await Bootstrap.getInstance().start();
146 return { status: ResponseStatus.SUCCESS };
147 }
148
149 private async handleStopSimulator(): Promise<ResponsePayload> {
150 await Bootstrap.getInstance().stop();
151 return { status: ResponseStatus.SUCCESS };
152 }
153 }