Improve payload type checking in OCPP, UI and Broadcast Channel
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
8114d10e
JB
3import path from 'path';
4import { fileURLToPath } from 'url';
5import { isMainThread } from 'worker_threads';
6
7import chalk from 'chalk';
8
9import { version } from '../../package.json';
32de5a57 10import BaseError from '../exception/BaseError';
8114d10e
JB
11import { Storage } from '../performance/storage/Storage';
12import { StorageFactory } from '../performance/storage/StorageFactory';
e7aeea18 13import {
32de5a57 14 ChargingStationData,
e7aeea18
JB
15 ChargingStationWorkerData,
16 ChargingStationWorkerMessage,
53e5fd67 17 ChargingStationWorkerMessageData,
e7aeea18
JB
18 ChargingStationWorkerMessageEvents,
19} from '../types/ChargingStationWorker';
717c1e56 20import { StationTemplateUrl } from '../types/ConfigurationData';
c3ee95af 21import Statistics from '../types/Statistics';
8114d10e
JB
22import { ApplicationProtocol } from '../types/UIProtocol';
23import Configuration from '../utils/Configuration';
32de5a57 24import logger from '../utils/Logger';
ded13d97 25import Utils from '../utils/Utils';
fd1fdf1b 26import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 27import WorkerFactory from '../worker/WorkerFactory';
8114d10e
JB
28import { ChargingStationUtils } from './ChargingStationUtils';
29import { AbstractUIServer } from './ui-server/AbstractUIServer';
30import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
31import UIServerFactory from './ui-server/UIServerFactory';
ded13d97 32
32de5a57
LM
33const moduleName = 'Bootstrap';
34
ded13d97 35export default class Bootstrap {
535aaa27 36 private static instance: Bootstrap | null = null;
c3ee95af 37 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
fe94fce0 38 private readonly uiServer!: AbstractUIServer;
6a49ad23 39 private readonly storage!: Storage;
7c72977b
JB
40 private numberOfChargingStationTemplates!: number;
41 private numberOfChargingStations!: number;
89b7a234 42 private numberOfStartedChargingStations!: number;
9e23580d 43 private readonly version: string = version;
eb87fe87 44 private started: boolean;
9e23580d 45 private readonly workerScript: string;
ded13d97
JB
46
47 private constructor() {
eb87fe87 48 this.started = false;
e7aeea18 49 this.workerScript = path.join(
0d8140bd 50 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 51 'charging-station',
44a95b7f 52 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
e7aeea18 53 );
7c72977b 54 this.initialize();
675fa8e3 55 Configuration.getUIServer().enabled &&
fe94fce0 56 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
675fa8e3 57 ...Configuration.getUIServer().options,
e7aeea18
JB
58 handleProtocols: UIServiceUtils.handleProtocols,
59 }));
60 Configuration.getPerformanceStorage().enabled &&
61 (this.storage = StorageFactory.getStorage(
62 Configuration.getPerformanceStorage().type,
63 Configuration.getPerformanceStorage().uri,
64 this.logPrefix()
65 ));
7874b0b1 66 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
67 }
68
69 public static getInstance(): Bootstrap {
1ca780f9 70 if (Bootstrap.instance === null) {
ded13d97
JB
71 Bootstrap.instance = new Bootstrap();
72 }
73 return Bootstrap.instance;
74 }
75
76 public async start(): Promise<void> {
eb87fe87 77 if (isMainThread && !this.started) {
ded13d97 78 try {
7c72977b 79 this.initialize();
6a49ad23 80 await this.storage?.open();
a4bc2942 81 await this.workerImplementation.start();
675fa8e3 82 this.uiServer?.start();
1f5df42a 83 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 84 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 85 // Start ChargingStation object in worker thread
45bd0627 86 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 87 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 88 try {
1f5df42a 89 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 90 for (let index = 1; index <= nbStations; index++) {
717c1e56 91 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
92 }
93 } catch (error) {
e7aeea18
JB
94 console.error(
95 chalk.red(
3d25cc86
JB
96 'Error at starting charging station with template file ' +
97 stationTemplateUrl.file +
98 ': '
e7aeea18
JB
99 ),
100 error
101 );
ded13d97
JB
102 }
103 }
104 } else {
45bd0627
JB
105 console.warn(
106 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
107 );
ded13d97 108 }
a4bc2942 109 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
110 console.warn(
111 chalk.yellow('No charging station template enabled in configuration, exiting')
112 );
32de5a57 113 process.exit();
ded13d97 114 } else {
32de5a57 115 console.info(
e7aeea18
JB
116 chalk.green(
117 `Charging stations simulator ${
118 this.version
7c72977b 119 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 120 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 121 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
122 : ''
123 }${this.workerImplementation.size}${
17ac262c 124 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 125 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 126 : ''
cf2a5d9b 127 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
128 this.workerImplementation.maxElementsPerWorker
129 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
130 : ''
131 }`
132 )
133 );
ded13d97 134 }
eb87fe87 135 this.started = true;
ded13d97 136 } catch (error) {
8eac9a09 137 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 138 }
b322b8b4
JB
139 } else {
140 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
141 }
142 }
143
144 public async stop(): Promise<void> {
eb87fe87 145 if (isMainThread && this.started) {
a4bc2942 146 await this.workerImplementation.stop();
b19021e2 147 this.workerImplementation = null;
675fa8e3 148 this.uiServer?.stop();
6a49ad23 149 await this.storage?.close();
b322b8b4
JB
150 } else {
151 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 152 }
eb87fe87 153 this.started = false;
ded13d97
JB
154 }
155
156 public async restart(): Promise<void> {
157 await this.stop();
7c72977b 158 this.initialize();
ded13d97
JB
159 await this.start();
160 }
161
ec7f4dce
JB
162 private initializeWorkerImplementation(): void {
163 !this.workerImplementation &&
164 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
165 this.workerScript,
cf2a5d9b 166 Configuration.getWorker().processType,
ec7f4dce 167 {
cf2a5d9b
JB
168 workerStartDelay: Configuration.getWorker().startDelay,
169 elementStartDelay: Configuration.getWorker().elementStartDelay,
170 poolMaxSize: Configuration.getWorker().poolMaxSize,
171 poolMinSize: Configuration.getWorker().poolMinSize,
172 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
ec7f4dce 173 poolOptions: {
cf2a5d9b 174 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 175 },
32de5a57 176 messageHandler: this.messageHandler.bind(this) as (
53e5fd67 177 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57 178 ) => void,
ec7f4dce
JB
179 }
180 ));
ded13d97 181 }
81797102 182
32de5a57 183 private messageHandler(
53e5fd67 184 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
185 ): void {
186 // logger.debug(
187 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
188 // msg,
189 // null,
190 // 2
191 // )}`
192 // );
193 try {
194 switch (msg.id) {
195 case ChargingStationWorkerMessageEvents.STARTED:
196 this.workerEventStarted(msg.data as ChargingStationData);
197 break;
198 case ChargingStationWorkerMessageEvents.STOPPED:
199 this.workerEventStopped(msg.data as ChargingStationData);
200 break;
201 case ChargingStationWorkerMessageEvents.UPDATED:
202 this.workerEventUpdated(msg.data as ChargingStationData);
203 break;
204 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
205 this.workerEventPerformanceStatistics(msg.data as Statistics);
206 break;
207 default:
208 throw new BaseError(
209 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
210 );
211 }
212 } catch (error) {
213 logger.error(
214 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
215 msg.id
216 }' event:`,
217 error
218 );
219 }
220 }
221
222 private workerEventStarted(data: ChargingStationData) {
223 this.uiServer?.chargingStations.set(data.hashId, data);
89b7a234 224 ++this.numberOfStartedChargingStations;
32de5a57
LM
225 }
226
227 private workerEventStopped(data: ChargingStationData) {
89b7a234
JB
228 this.uiServer?.chargingStations.set(data.hashId, data);
229 --this.numberOfStartedChargingStations;
32de5a57
LM
230 }
231
232 private workerEventUpdated(data: ChargingStationData) {
233 this.uiServer?.chargingStations.set(data.hashId, data);
234 }
235
236 private workerEventPerformanceStatistics = (data: Statistics) => {
237 this.storage.storePerformanceStatistics(data) as void;
238 };
239
7c72977b 240 private initialize() {
7c72977b 241 this.numberOfChargingStationTemplates = 0;
89b7a234
JB
242 this.numberOfChargingStations = 0;
243 this.numberOfStartedChargingStations = 0;
ec7f4dce 244 this.initializeWorkerImplementation();
7c72977b
JB
245 }
246
e7aeea18
JB
247 private async startChargingStation(
248 index: number,
249 stationTemplateUrl: StationTemplateUrl
250 ): Promise<void> {
717c1e56
JB
251 const workerData: ChargingStationWorkerData = {
252 index,
e7aeea18 253 templateFile: path.join(
0d8140bd 254 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
255 'assets',
256 'station-templates',
ee5f26a2 257 stationTemplateUrl.file
e7aeea18 258 ),
717c1e56
JB
259 };
260 await this.workerImplementation.addElement(workerData);
89b7a234 261 ++this.numberOfChargingStations;
717c1e56
JB
262 }
263
81797102 264 private logPrefix(): string {
689dca78 265 return Utils.logPrefix(' Bootstrap |');
81797102 266 }
ded13d97 267}