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