build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
CommitLineData
66a7748d 1import { BaseError, type OCPPError } from '../../../exception/index.js'
675fa8e3 2import {
268a74bb
JB
3 BroadcastChannelProcedureName,
4 type BroadcastChannelRequestPayload,
66a7748d 5 type JsonType,
32de5a57 6 ProcedureName,
976d11ec
JB
7 type ProtocolRequest,
8 type ProtocolRequestHandler,
f130b8e6 9 type ProtocolResponse,
976d11ec
JB
10 type ProtocolVersion,
11 type RequestPayload,
12 type ResponsePayload,
66a7748d
JB
13 ResponseStatus
14} from '../../../types/index.js'
4b9332af 15import { isAsyncFunction, isNotEmptyArray, logger } from '../../../utils/index.js'
66a7748d
JB
16import { Bootstrap } from '../../Bootstrap.js'
17import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js'
18import type { AbstractUIServer } from '../AbstractUIServer.js'
4198ad5c 19
66a7748d 20const moduleName = 'AbstractUIService'
32de5a57 21
268a74bb 22export abstract class AbstractUIService {
a37fc6dc 23 protected static readonly ProcedureNameToBroadCastChannelProcedureNameMapping = new Map<
66a7748d
JB
24 ProcedureName,
25 BroadcastChannelProcedureName
a37fc6dc
JB
26 >([
27 [ProcedureName.START_CHARGING_STATION, BroadcastChannelProcedureName.START_CHARGING_STATION],
28 [ProcedureName.STOP_CHARGING_STATION, BroadcastChannelProcedureName.STOP_CHARGING_STATION],
29 [ProcedureName.CLOSE_CONNECTION, BroadcastChannelProcedureName.CLOSE_CONNECTION],
30 [ProcedureName.OPEN_CONNECTION, BroadcastChannelProcedureName.OPEN_CONNECTION],
31 [
32 ProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR,
66a7748d 33 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR
a37fc6dc
JB
34 ],
35 [
36 ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
66a7748d 37 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR
a37fc6dc
JB
38 ],
39 [ProcedureName.SET_SUPERVISION_URL, BroadcastChannelProcedureName.SET_SUPERVISION_URL],
40 [ProcedureName.START_TRANSACTION, BroadcastChannelProcedureName.START_TRANSACTION],
41 [ProcedureName.STOP_TRANSACTION, BroadcastChannelProcedureName.STOP_TRANSACTION],
42 [ProcedureName.AUTHORIZE, BroadcastChannelProcedureName.AUTHORIZE],
43 [ProcedureName.BOOT_NOTIFICATION, BroadcastChannelProcedureName.BOOT_NOTIFICATION],
44 [ProcedureName.STATUS_NOTIFICATION, BroadcastChannelProcedureName.STATUS_NOTIFICATION],
45 [ProcedureName.HEARTBEAT, BroadcastChannelProcedureName.HEARTBEAT],
46 [ProcedureName.METER_VALUES, BroadcastChannelProcedureName.METER_VALUES],
47 [ProcedureName.DATA_TRANSFER, BroadcastChannelProcedureName.DATA_TRANSFER],
48 [
49 ProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION,
66a7748d 50 BroadcastChannelProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION
a37fc6dc
JB
51 ],
52 [
53 ProcedureName.FIRMWARE_STATUS_NOTIFICATION,
66a7748d
JB
54 BroadcastChannelProcedureName.FIRMWARE_STATUS_NOTIFICATION
55 ]
56 ])
57
58 protected readonly requestHandlers: Map<ProcedureName, ProtocolRequestHandler>
59 private readonly version: ProtocolVersion
60 private readonly uiServer: AbstractUIServer
61 private readonly uiServiceWorkerBroadcastChannel: UIServiceWorkerBroadcastChannel
62 private readonly broadcastChannelRequests: Map<string, number>
63
64 constructor (uiServer: AbstractUIServer, version: ProtocolVersion) {
65 this.uiServer = uiServer
66 this.version = version
02a6943a 67 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
42e341c4 68 [ProcedureName.LIST_TEMPLATES, this.handleListTemplates.bind(this)],
32de5a57
LM
69 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
70 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
66a7748d
JB
71 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)]
72 ])
73 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this)
74 this.broadcastChannelRequests = new Map<string, number>()
4198ad5c
JB
75 }
76
66a7748d
JB
77 public async requestHandler (request: ProtocolRequest): Promise<ProtocolResponse | undefined> {
78 let messageId: string | undefined
79 let command: ProcedureName | undefined
80 let requestPayload: RequestPayload | undefined
81 let responsePayload: ResponsePayload | undefined
32de5a57 82 try {
66a7748d 83 [messageId, command, requestPayload] = request
32de5a57 84
66a7748d 85 if (!this.requestHandlers.has(command)) {
32de5a57
LM
86 throw new BaseError(
87 `${command} is not implemented to handle message payload ${JSON.stringify(
88 requestPayload,
4ed03b6e 89 undefined,
66a7748d
JB
90 2
91 )}`
92 )
4198ad5c 93 }
89b7a234 94
6c8f5d90 95 // Call the request handler to build the response payload
66a7748d 96 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4b9332af
JB
97 const requestHandler = this.requestHandlers.get(command)!
98 if (isAsyncFunction(requestHandler)) {
99 responsePayload = await requestHandler(messageId, command, requestPayload)
100 } else {
101 responsePayload = (
102 requestHandler as (
103 uuid?: string,
104 procedureName?: ProcedureName,
105 payload?: RequestPayload
106 ) => undefined | ResponsePayload
107 )(messageId, command, requestPayload)
108 }
32de5a57
LM
109 } catch (error) {
110 // Log
66a7748d 111 logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error)
6c8f5d90 112 responsePayload = {
551e477c 113 hashIds: requestPayload?.hashIds,
6c8f5d90
JB
114 status: ResponseStatus.FAILURE,
115 command,
116 requestPayload,
117 responsePayload,
7375968c
JB
118 errorMessage: (error as OCPPError).message,
119 errorStack: (error as OCPPError).stack,
66a7748d
JB
120 errorDetails: (error as OCPPError).details
121 }
f130b8e6 122 }
aa63c9b7 123 if (responsePayload != null) {
66a7748d 124 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
aa63c9b7 125 return this.uiServer.buildProtocolResponse(messageId!, responsePayload)
4198ad5c 126 }
6c8f5d90
JB
127 }
128
66a7748d 129 // public sendRequest (
0b22144c
JB
130 // messageId: string,
131 // procedureName: ProcedureName,
66a7748d 132 // requestPayload: RequestPayload
0b22144c
JB
133 // ): void {
134 // this.uiServer.sendRequest(
66a7748d
JB
135 // this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
136 // )
0b22144c 137 // }
32de5a57 138
66a7748d 139 public sendResponse (messageId: string, responsePayload: ResponsePayload): void {
1ca4a038 140 if (this.uiServer.hasResponseHandler(messageId)) {
66a7748d 141 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload))
1ca4a038 142 }
4198ad5c
JB
143 }
144
8b7072dc 145 public logPrefix = (modName: string, methodName: string): string => {
66a7748d
JB
146 return this.uiServer.logPrefix(modName, methodName, this.version)
147 }
0d2cec76 148
66a7748d
JB
149 public deleteBroadcastChannelRequest (uuid: string): void {
150 this.broadcastChannelRequests.delete(uuid)
0d2cec76
JB
151 }
152
66a7748d
JB
153 public getBroadcastChannelExpectedResponses (uuid: string): number {
154 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
155 return this.broadcastChannelRequests.get(uuid)!
0d2cec76
JB
156 }
157
66a7748d 158 protected handleProtocolRequest (
2a3cf7fc
JB
159 uuid: string,
160 procedureName: ProcedureName,
66a7748d 161 payload: RequestPayload
2a3cf7fc
JB
162 ): void {
163 this.sendBroadcastChannelRequest(
164 uuid,
66a7748d 165 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
a37fc6dc 166 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping.get(procedureName)!,
66a7748d
JB
167 payload
168 )
2a3cf7fc
JB
169 }
170
66a7748d 171 private sendBroadcastChannelRequest (
0d2cec76
JB
172 uuid: string,
173 procedureName: BroadcastChannelProcedureName,
66a7748d 174 payload: BroadcastChannelRequestPayload
0d2cec76 175 ): void {
9bf0ef23 176 if (isNotEmptyArray(payload.hashIds)) {
0d2cec76 177 payload.hashIds = payload.hashIds
5dc7c990 178 .map(hashId => {
5199f9fd 179 if (this.uiServer.chargingStations.has(hashId)) {
66a7748d 180 return hashId
0d2cec76 181 }
3a6ef20a
JB
182 logger.warn(
183 `${this.logPrefix(
184 moduleName,
66a7748d
JB
185 'sendBroadcastChannelRequest'
186 )} Charging station with hashId '${hashId}' not found`
187 )
188 return undefined
f12cf7ef 189 })
a974c8e4 190 .filter(hashId => hashId != null) as string[]
3a6ef20a 191 } else {
66a7748d 192 delete payload.hashIds
0d2cec76 193 }
3a6ef20a
JB
194 const expectedNumberOfResponses = Array.isArray(payload.hashIds)
195 ? payload.hashIds.length
66a7748d 196 : this.uiServer.chargingStations.size
3a6ef20a
JB
197 if (expectedNumberOfResponses === 0) {
198 throw new BaseError(
66a7748d
JB
199 'hashIds array in the request payload does not contain any valid charging station hashId'
200 )
3a6ef20a 201 }
66a7748d
JB
202 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload])
203 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses)
6c8f5d90
JB
204 }
205
42e341c4
JB
206 private handleListTemplates (): ResponsePayload {
207 return {
208 status: ResponseStatus.SUCCESS,
209 templates: [...this.uiServer.chargingStationTemplates.values()] as JsonType[]
210 } satisfies ResponsePayload
211 }
212
66a7748d 213 private handleListChargingStations (): ResponsePayload {
32de5a57
LM
214 return {
215 status: ResponseStatus.SUCCESS,
66a7748d
JB
216 chargingStations: [...this.uiServer.chargingStations.values()] as JsonType[]
217 } satisfies ResponsePayload
32de5a57
LM
218 }
219
66a7748d 220 private async handleStartSimulator (): Promise<ResponsePayload> {
4ec634b7 221 try {
66a7748d
JB
222 await Bootstrap.getInstance().start()
223 return { status: ResponseStatus.SUCCESS }
9c0ecbdf 224 } catch {
66a7748d 225 return { status: ResponseStatus.FAILURE }
4ec634b7 226 }
32de5a57
LM
227 }
228
66a7748d 229 private async handleStopSimulator (): Promise<ResponsePayload> {
4ec634b7 230 try {
66a7748d
JB
231 await Bootstrap.getInstance().stop()
232 return { status: ResponseStatus.SUCCESS }
9c0ecbdf 233 } catch {
66a7748d 234 return { status: ResponseStatus.FAILURE }
4ec634b7 235 }
4198ad5c
JB
236 }
237}