refactor: cleanup isNullOrUndefined usage
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
1 import { BaseError, type OCPPError } from '../../../exception/index.js'
2 import {
3 BroadcastChannelProcedureName,
4 type BroadcastChannelRequestPayload,
5 type JsonType,
6 ProcedureName,
7 type ProtocolRequest,
8 type ProtocolRequestHandler,
9 type ProtocolResponse,
10 type ProtocolVersion,
11 type RequestPayload,
12 type ResponsePayload,
13 ResponseStatus
14 } from '../../../types/index.js'
15 import { isNotEmptyArray, logger } from '../../../utils/index.js'
16 import { Bootstrap } from '../../Bootstrap.js'
17 import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js'
18 import type { AbstractUIServer } from '../AbstractUIServer.js'
19
20 const moduleName = 'AbstractUIService'
21
22 export abstract class AbstractUIService {
23 protected static readonly ProcedureNameToBroadCastChannelProcedureNameMapping = new Map<
24 ProcedureName,
25 BroadcastChannelProcedureName
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,
33 BroadcastChannelProcedureName.START_AUTOMATIC_TRANSACTION_GENERATOR
34 ],
35 [
36 ProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR,
37 BroadcastChannelProcedureName.STOP_AUTOMATIC_TRANSACTION_GENERATOR
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,
50 BroadcastChannelProcedureName.DIAGNOSTICS_STATUS_NOTIFICATION
51 ],
52 [
53 ProcedureName.FIRMWARE_STATUS_NOTIFICATION,
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
67 this.requestHandlers = new Map<ProcedureName, ProtocolRequestHandler>([
68 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
69 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
70 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)]
71 ])
72 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this)
73 this.broadcastChannelRequests = new Map<string, number>()
74 }
75
76 public async requestHandler (request: ProtocolRequest): Promise<ProtocolResponse | undefined> {
77 let messageId: string | undefined
78 let command: ProcedureName | undefined
79 let requestPayload: RequestPayload | undefined
80 let responsePayload: ResponsePayload | undefined
81 try {
82 [messageId, command, requestPayload] = request
83
84 if (!this.requestHandlers.has(command)) {
85 throw new BaseError(
86 `${command} is not implemented to handle message payload ${JSON.stringify(
87 requestPayload,
88 undefined,
89 2
90 )}`
91 )
92 }
93
94 // Call the request handler to build the response payload
95 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
96 responsePayload = await this.requestHandlers.get(command)!(messageId, command, requestPayload)
97 } catch (error) {
98 // Log
99 logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error)
100 responsePayload = {
101 hashIds: requestPayload?.hashIds,
102 status: ResponseStatus.FAILURE,
103 command,
104 requestPayload,
105 responsePayload,
106 errorMessage: (error as OCPPError).message,
107 errorStack: (error as OCPPError).stack,
108 errorDetails: (error as OCPPError).details
109 }
110 }
111 if (responsePayload != null) {
112 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
113 return this.uiServer.buildProtocolResponse(messageId!, responsePayload)
114 }
115 }
116
117 // public sendRequest (
118 // messageId: string,
119 // procedureName: ProcedureName,
120 // requestPayload: RequestPayload
121 // ): void {
122 // this.uiServer.sendRequest(
123 // this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
124 // )
125 // }
126
127 public sendResponse (messageId: string, responsePayload: ResponsePayload): void {
128 if (this.uiServer.hasResponseHandler(messageId)) {
129 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload))
130 }
131 }
132
133 public logPrefix = (modName: string, methodName: string): string => {
134 return this.uiServer.logPrefix(modName, methodName, this.version)
135 }
136
137 public deleteBroadcastChannelRequest (uuid: string): void {
138 this.broadcastChannelRequests.delete(uuid)
139 }
140
141 public getBroadcastChannelExpectedResponses (uuid: string): number {
142 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
143 return this.broadcastChannelRequests.get(uuid)!
144 }
145
146 protected handleProtocolRequest (
147 uuid: string,
148 procedureName: ProcedureName,
149 payload: RequestPayload
150 ): void {
151 this.sendBroadcastChannelRequest(
152 uuid,
153 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
154 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping.get(procedureName)!,
155 payload
156 )
157 }
158
159 private sendBroadcastChannelRequest (
160 uuid: string,
161 procedureName: BroadcastChannelProcedureName,
162 payload: BroadcastChannelRequestPayload
163 ): void {
164 if (isNotEmptyArray(payload.hashIds)) {
165 payload.hashIds = payload.hashIds
166 ?.map((hashId) => {
167 if (hashId != null && this.uiServer.chargingStations.has(hashId)) {
168 return hashId
169 }
170 logger.warn(
171 `${this.logPrefix(
172 moduleName,
173 'sendBroadcastChannelRequest'
174 )} Charging station with hashId '${hashId}' not found`
175 )
176 return undefined
177 })
178 ?.filter((hashId) => hashId != null) as string[]
179 } else {
180 delete payload.hashIds
181 }
182 const expectedNumberOfResponses = Array.isArray(payload.hashIds)
183 ? payload.hashIds.length
184 : this.uiServer.chargingStations.size
185 if (expectedNumberOfResponses === 0) {
186 throw new BaseError(
187 'hashIds array in the request payload does not contain any valid charging station hashId'
188 )
189 }
190 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload])
191 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses)
192 }
193
194 private handleListChargingStations (): ResponsePayload {
195 return {
196 status: ResponseStatus.SUCCESS,
197 chargingStations: [...this.uiServer.chargingStations.values()] as JsonType[]
198 } satisfies ResponsePayload
199 }
200
201 private async handleStartSimulator (): Promise<ResponsePayload> {
202 try {
203 await Bootstrap.getInstance().start()
204 return { status: ResponseStatus.SUCCESS }
205 } catch {
206 return { status: ResponseStatus.FAILURE }
207 }
208 }
209
210 private async handleStopSimulator (): Promise<ResponsePayload> {
211 try {
212 await Bootstrap.getInstance().stop()
213 return { status: ResponseStatus.SUCCESS }
214 } catch {
215 return { status: ResponseStatus.FAILURE }
216 }
217 }
218 }