refactor: consolidate charging stations tracking
[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>([
32de5a57
LM
68 [ProcedureName.LIST_CHARGING_STATIONS, this.handleListChargingStations.bind(this)],
69 [ProcedureName.START_SIMULATOR, this.handleStartSimulator.bind(this)],
66a7748d
JB
70 [ProcedureName.STOP_SIMULATOR, this.handleStopSimulator.bind(this)]
71 ])
72 this.uiServiceWorkerBroadcastChannel = new UIServiceWorkerBroadcastChannel(this)
73 this.broadcastChannelRequests = new Map<string, number>()
4198ad5c
JB
74 }
75
66a7748d
JB
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
32de5a57 81 try {
66a7748d 82 [messageId, command, requestPayload] = request
32de5a57 83
66a7748d 84 if (!this.requestHandlers.has(command)) {
32de5a57
LM
85 throw new BaseError(
86 `${command} is not implemented to handle message payload ${JSON.stringify(
87 requestPayload,
4ed03b6e 88 undefined,
66a7748d
JB
89 2
90 )}`
91 )
4198ad5c 92 }
89b7a234 93
6c8f5d90 94 // Call the request handler to build the response payload
66a7748d 95 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
4b9332af
JB
96 const requestHandler = this.requestHandlers.get(command)!
97 if (isAsyncFunction(requestHandler)) {
98 responsePayload = await requestHandler(messageId, command, requestPayload)
99 } else {
100 responsePayload = (
101 requestHandler as (
102 uuid?: string,
103 procedureName?: ProcedureName,
104 payload?: RequestPayload
105 ) => undefined | ResponsePayload
106 )(messageId, command, requestPayload)
107 }
32de5a57
LM
108 } catch (error) {
109 // Log
66a7748d 110 logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error)
6c8f5d90 111 responsePayload = {
551e477c 112 hashIds: requestPayload?.hashIds,
6c8f5d90
JB
113 status: ResponseStatus.FAILURE,
114 command,
115 requestPayload,
116 responsePayload,
7375968c
JB
117 errorMessage: (error as OCPPError).message,
118 errorStack: (error as OCPPError).stack,
66a7748d
JB
119 errorDetails: (error as OCPPError).details
120 }
f130b8e6 121 }
aa63c9b7 122 if (responsePayload != null) {
66a7748d 123 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
aa63c9b7 124 return this.uiServer.buildProtocolResponse(messageId!, responsePayload)
4198ad5c 125 }
6c8f5d90
JB
126 }
127
66a7748d 128 // public sendRequest (
0b22144c
JB
129 // messageId: string,
130 // procedureName: ProcedureName,
66a7748d 131 // requestPayload: RequestPayload
0b22144c
JB
132 // ): void {
133 // this.uiServer.sendRequest(
66a7748d
JB
134 // this.uiServer.buildProtocolRequest(messageId, procedureName, requestPayload)
135 // )
0b22144c 136 // }
32de5a57 137
66a7748d 138 public sendResponse (messageId: string, responsePayload: ResponsePayload): void {
1ca4a038 139 if (this.uiServer.hasResponseHandler(messageId)) {
66a7748d 140 this.uiServer.sendResponse(this.uiServer.buildProtocolResponse(messageId, responsePayload))
1ca4a038 141 }
4198ad5c
JB
142 }
143
8b7072dc 144 public logPrefix = (modName: string, methodName: string): string => {
66a7748d
JB
145 return this.uiServer.logPrefix(modName, methodName, this.version)
146 }
0d2cec76 147
66a7748d
JB
148 public deleteBroadcastChannelRequest (uuid: string): void {
149 this.broadcastChannelRequests.delete(uuid)
0d2cec76
JB
150 }
151
66a7748d
JB
152 public getBroadcastChannelExpectedResponses (uuid: string): number {
153 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
154 return this.broadcastChannelRequests.get(uuid)!
0d2cec76
JB
155 }
156
66a7748d 157 protected handleProtocolRequest (
2a3cf7fc
JB
158 uuid: string,
159 procedureName: ProcedureName,
66a7748d 160 payload: RequestPayload
2a3cf7fc
JB
161 ): void {
162 this.sendBroadcastChannelRequest(
163 uuid,
66a7748d 164 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
a37fc6dc 165 AbstractUIService.ProcedureNameToBroadCastChannelProcedureNameMapping.get(procedureName)!,
66a7748d
JB
166 payload
167 )
2a3cf7fc
JB
168 }
169
66a7748d 170 private sendBroadcastChannelRequest (
0d2cec76
JB
171 uuid: string,
172 procedureName: BroadcastChannelProcedureName,
66a7748d 173 payload: BroadcastChannelRequestPayload
0d2cec76 174 ): void {
9bf0ef23 175 if (isNotEmptyArray(payload.hashIds)) {
0d2cec76 176 payload.hashIds = payload.hashIds
5dc7c990 177 .map(hashId => {
5199f9fd 178 if (this.uiServer.chargingStations.has(hashId)) {
66a7748d 179 return hashId
0d2cec76 180 }
3a6ef20a
JB
181 logger.warn(
182 `${this.logPrefix(
183 moduleName,
66a7748d
JB
184 'sendBroadcastChannelRequest'
185 )} Charging station with hashId '${hashId}' not found`
186 )
187 return undefined
f12cf7ef 188 })
a974c8e4 189 .filter(hashId => hashId != null) as string[]
3a6ef20a 190 } else {
66a7748d 191 delete payload.hashIds
0d2cec76 192 }
3a6ef20a
JB
193 const expectedNumberOfResponses = Array.isArray(payload.hashIds)
194 ? payload.hashIds.length
66a7748d 195 : this.uiServer.chargingStations.size
3a6ef20a
JB
196 if (expectedNumberOfResponses === 0) {
197 throw new BaseError(
66a7748d
JB
198 'hashIds array in the request payload does not contain any valid charging station hashId'
199 )
3a6ef20a 200 }
66a7748d
JB
201 this.uiServiceWorkerBroadcastChannel.sendRequest([uuid, procedureName, payload])
202 this.broadcastChannelRequests.set(uuid, expectedNumberOfResponses)
6c8f5d90
JB
203 }
204
66a7748d 205 private handleListChargingStations (): ResponsePayload {
32de5a57
LM
206 return {
207 status: ResponseStatus.SUCCESS,
66a7748d
JB
208 chargingStations: [...this.uiServer.chargingStations.values()] as JsonType[]
209 } satisfies ResponsePayload
32de5a57
LM
210 }
211
66a7748d 212 private async handleStartSimulator (): Promise<ResponsePayload> {
4ec634b7 213 try {
66a7748d
JB
214 await Bootstrap.getInstance().start()
215 return { status: ResponseStatus.SUCCESS }
9c0ecbdf 216 } catch {
66a7748d 217 return { status: ResponseStatus.FAILURE }
4ec634b7 218 }
32de5a57
LM
219 }
220
66a7748d 221 private async handleStopSimulator (): Promise<ResponsePayload> {
4ec634b7 222 try {
66a7748d
JB
223 await Bootstrap.getInstance().stop()
224 return { status: ResponseStatus.SUCCESS }
9c0ecbdf 225 } catch {
66a7748d 226 return { status: ResponseStatus.FAILURE }
4ec634b7 227 }
4198ad5c
JB
228 }
229}