Use camel case everywhere
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
98dc07fa 3import { ChargingStationWorkerData, ChargingStationWorkerMessage, ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
81797102 4
ded13d97 5import Configuration from '../utils/Configuration';
a6b3c6c3
JB
6import { Storage } from '../performance/storage/Storage';
7import { StorageFactory } from '../performance/storage/StorageFactory';
383cb2ae 8import { UIServiceUtils } from './ui-websocket-services/UIServiceUtils';
4198ad5c 9import UIWebSocketServer from './UIWebSocketServer';
ded13d97 10import Utils from '../utils/Utils';
fd1fdf1b 11import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 12import WorkerFactory from '../worker/WorkerFactory';
8eac9a09 13import chalk from 'chalk';
ded13d97 14import { isMainThread } from 'worker_threads';
bf1866b2 15import path from 'path';
84e52c2c 16import { version } from '../../package.json';
ded13d97
JB
17
18export default class Bootstrap {
535aaa27 19 private static instance: Bootstrap | null = null;
a4bc2942 20 private workerImplementation: WorkerAbstract | null = null;
6a49ad23
JB
21 private readonly uiWebSocketServer!: UIWebSocketServer;
22 private readonly storage!: Storage;
a4bc2942 23 private numberOfChargingStations: number;
9e23580d 24 private readonly version: string = version;
eb87fe87 25 private started: boolean;
9e23580d 26 private readonly workerScript: string;
ded13d97
JB
27
28 private constructor() {
eb87fe87 29 this.started = false;
07f35004 30 this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'ChargingStationWorker.js');
8df3f0a9 31 this.initWorkerImplementation();
6a49ad23
JB
32 Configuration.getUIWebSocketServer().enabled && (this.uiWebSocketServer = new UIWebSocketServer({
33 ...Configuration.getUIWebSocketServer().options, handleProtocols: UIServiceUtils.handleProtocols
34 }));
35 Configuration.getPerformanceStorage().enabled && (this.storage = StorageFactory.getStorage(
36 Configuration.getPerformanceStorage().type,
1f5df42a 37 Configuration.getPerformanceStorage().uri,
6a49ad23
JB
38 this.logPrefix()
39 ));
7874b0b1 40 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
41 }
42
43 public static getInstance(): Bootstrap {
44 if (!Bootstrap.instance) {
45 Bootstrap.instance = new Bootstrap();
46 }
47 return Bootstrap.instance;
48 }
49
50 public async start(): Promise<void> {
eb87fe87 51 if (isMainThread && !this.started) {
ded13d97 52 try {
a4bc2942 53 this.numberOfChargingStations = 0;
6a49ad23 54 await this.storage?.open();
a4bc2942 55 await this.workerImplementation.start();
6a49ad23 56 this.uiWebSocketServer?.start();
1f5df42a 57 const stationTemplateUrls = Configuration.getStationTemplateUrls();
ded13d97 58 // Start ChargingStation object in worker thread
1f5df42a
JB
59 if (stationTemplateUrls) {
60 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 61 try {
1f5df42a 62 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 63 for (let index = 1; index <= nbStations; index++) {
07f35004 64 const workerData: ChargingStationWorkerData = {
ded13d97 65 index,
1f5df42a 66 templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationTemplateUrl.file))
ded13d97 67 };
a4bc2942
JB
68 await this.workerImplementation.addElement(workerData);
69 this.numberOfChargingStations++;
ded13d97
JB
70 }
71 } catch (error) {
1f5df42a 72 console.error(chalk.red('Charging station start with template file ' + stationTemplateUrl.file + ' error '), error);
ded13d97
JB
73 }
74 }
75 } else {
1f5df42a 76 console.warn(chalk.yellow('No stationTemplateUrls defined in configuration, exiting'));
ded13d97 77 }
a4bc2942 78 if (this.numberOfChargingStations === 0) {
8eac9a09 79 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
ded13d97 80 } else {
a4bc2942 81 console.log(chalk.green(`Charging stations simulator ${this.version} started with ${this.numberOfChargingStations.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${this.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${this.workerImplementation.maxElementsPerWorker ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`));
ded13d97 82 }
eb87fe87 83 this.started = true;
ded13d97 84 } catch (error) {
8eac9a09 85 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 86 }
b322b8b4
JB
87 } else {
88 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
89 }
90 }
91
92 public async stop(): Promise<void> {
eb87fe87 93 if (isMainThread && this.started) {
a4bc2942 94 await this.workerImplementation.stop();
6a49ad23
JB
95 this.uiWebSocketServer?.stop();
96 await this.storage?.close();
b322b8b4
JB
97 } else {
98 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 99 }
eb87fe87 100 this.started = false;
ded13d97
JB
101 }
102
103 public async restart(): Promise<void> {
104 await this.stop();
535aaa27 105 this.initWorkerImplementation();
ded13d97
JB
106 await this.start();
107 }
108
2a370053 109 private initWorkerImplementation(): void {
a4bc2942 110 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
8df3f0a9
JB
111 {
112 startDelay: Configuration.getWorkerStartDelay(),
113 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
114 poolMinSize: Configuration.getWorkerPoolMinSize(),
115 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
116 poolOptions: {
117 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
ffd71f2c 118 },
98dc07fa 119 messageHandler: async (msg: ChargingStationWorkerMessage) => {
ee0f106b 120 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
de9136ae 121 this.uiWebSocketServer.chargingStations.add(msg.data.id);
ee0f106b 122 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
de9136ae 123 this.uiWebSocketServer.chargingStations.delete(msg.data.id);
ee0f106b 124 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
a4bc2942 125 await this.storage.storePerformanceStatistics(msg.data);
ffd71f2c 126 }
81797102 127 }
535aaa27 128 });
ded13d97 129 }
81797102
JB
130
131 private logPrefix(): string {
689dca78 132 return Utils.logPrefix(' Bootstrap |');
81797102 133 }
ded13d97 134}