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