Bound most called methods in the OCPP stack
[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';
10import { Storage } from '../performance/storage/Storage';
11import { StorageFactory } from '../performance/storage/StorageFactory';
e7aeea18
JB
12import {
13 ChargingStationWorkerData,
14 ChargingStationWorkerMessage,
15 ChargingStationWorkerMessageEvents,
16} from '../types/ChargingStationWorker';
717c1e56 17import { StationTemplateUrl } from '../types/ConfigurationData';
c3ee95af 18import Statistics from '../types/Statistics';
8114d10e
JB
19import { ApplicationProtocol } from '../types/UIProtocol';
20import Configuration from '../utils/Configuration';
ded13d97 21import Utils from '../utils/Utils';
fd1fdf1b 22import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 23import WorkerFactory from '../worker/WorkerFactory';
8114d10e
JB
24import { ChargingStationUtils } from './ChargingStationUtils';
25import { AbstractUIServer } from './ui-server/AbstractUIServer';
26import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
27import UIServerFactory from './ui-server/UIServerFactory';
ded13d97
JB
28
29export default class Bootstrap {
535aaa27 30 private static instance: Bootstrap | null = null;
c3ee95af 31 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
fe94fce0 32 private readonly uiServer!: AbstractUIServer;
6a49ad23 33 private readonly storage!: Storage;
7c72977b
JB
34 private numberOfChargingStationTemplates!: number;
35 private numberOfChargingStations!: number;
9e23580d 36 private readonly version: string = version;
eb87fe87 37 private started: boolean;
9e23580d 38 private readonly workerScript: string;
ded13d97
JB
39
40 private constructor() {
eb87fe87 41 this.started = false;
e7aeea18 42 this.workerScript = path.join(
0d8140bd 43 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 44 'charging-station',
44a95b7f 45 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
e7aeea18 46 );
7c72977b 47 this.initialize();
675fa8e3 48 Configuration.getUIServer().enabled &&
fe94fce0 49 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
675fa8e3 50 ...Configuration.getUIServer().options,
e7aeea18
JB
51 handleProtocols: UIServiceUtils.handleProtocols,
52 }));
53 Configuration.getPerformanceStorage().enabled &&
54 (this.storage = StorageFactory.getStorage(
55 Configuration.getPerformanceStorage().type,
56 Configuration.getPerformanceStorage().uri,
57 this.logPrefix()
58 ));
7874b0b1 59 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
60 }
61
62 public static getInstance(): Bootstrap {
1ca780f9 63 if (Bootstrap.instance === null) {
ded13d97
JB
64 Bootstrap.instance = new Bootstrap();
65 }
66 return Bootstrap.instance;
67 }
68
69 public async start(): Promise<void> {
eb87fe87 70 if (isMainThread && !this.started) {
ded13d97 71 try {
7c72977b 72 this.initialize();
6a49ad23 73 await this.storage?.open();
a4bc2942 74 await this.workerImplementation.start();
675fa8e3 75 this.uiServer?.start();
1f5df42a 76 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 77 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 78 // Start ChargingStation object in worker thread
45bd0627 79 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 80 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 81 try {
1f5df42a 82 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 83 for (let index = 1; index <= nbStations; index++) {
717c1e56 84 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
85 }
86 } catch (error) {
e7aeea18
JB
87 console.error(
88 chalk.red(
3d25cc86
JB
89 'Error at starting charging station with template file ' +
90 stationTemplateUrl.file +
91 ': '
e7aeea18
JB
92 ),
93 error
94 );
ded13d97
JB
95 }
96 }
97 } else {
45bd0627
JB
98 console.warn(
99 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
100 );
ded13d97 101 }
a4bc2942 102 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
103 console.warn(
104 chalk.yellow('No charging station template enabled in configuration, exiting')
105 );
ded13d97 106 } else {
e7aeea18
JB
107 console.log(
108 chalk.green(
109 `Charging stations simulator ${
110 this.version
7c72977b 111 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 112 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 113 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
114 : ''
115 }${this.workerImplementation.size}${
17ac262c 116 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 117 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 118 : ''
cf2a5d9b 119 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
120 this.workerImplementation.maxElementsPerWorker
121 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
122 : ''
123 }`
124 )
125 );
ded13d97 126 }
eb87fe87 127 this.started = true;
ded13d97 128 } catch (error) {
8eac9a09 129 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 130 }
b322b8b4
JB
131 } else {
132 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
133 }
134 }
135
136 public async stop(): Promise<void> {
eb87fe87 137 if (isMainThread && this.started) {
a4bc2942 138 await this.workerImplementation.stop();
b19021e2 139 this.workerImplementation = null;
675fa8e3 140 this.uiServer?.stop();
6a49ad23 141 await this.storage?.close();
b322b8b4
JB
142 } else {
143 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 144 }
eb87fe87 145 this.started = false;
ded13d97
JB
146 }
147
148 public async restart(): Promise<void> {
149 await this.stop();
7c72977b 150 this.initialize();
ded13d97
JB
151 await this.start();
152 }
153
ec7f4dce
JB
154 private initializeWorkerImplementation(): void {
155 !this.workerImplementation &&
156 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
157 this.workerScript,
cf2a5d9b 158 Configuration.getWorker().processType,
ec7f4dce 159 {
cf2a5d9b
JB
160 workerStartDelay: Configuration.getWorker().startDelay,
161 elementStartDelay: Configuration.getWorker().elementStartDelay,
162 poolMaxSize: Configuration.getWorker().poolMaxSize,
163 poolMinSize: Configuration.getWorker().poolMinSize,
164 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
ec7f4dce 165 poolOptions: {
cf2a5d9b 166 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce
JB
167 },
168 messageHandler: async (msg: ChargingStationWorkerMessage) => {
169 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
170 this.uiServer.chargingStations.add(msg.data.id as string);
171 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
172 this.uiServer.chargingStations.delete(msg.data.id as string);
173 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
174 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
175 }
176 },
177 }
178 ));
ded13d97 179 }
81797102 180
7c72977b
JB
181 private initialize() {
182 this.numberOfChargingStations = 0;
183 this.numberOfChargingStationTemplates = 0;
ec7f4dce 184 this.initializeWorkerImplementation();
7c72977b
JB
185 }
186
e7aeea18
JB
187 private async startChargingStation(
188 index: number,
189 stationTemplateUrl: StationTemplateUrl
190 ): Promise<void> {
717c1e56
JB
191 const workerData: ChargingStationWorkerData = {
192 index,
e7aeea18 193 templateFile: path.join(
0d8140bd 194 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
195 'assets',
196 'station-templates',
ee5f26a2 197 stationTemplateUrl.file
e7aeea18 198 ),
717c1e56
JB
199 };
200 await this.workerImplementation.addElement(workerData);
201 this.numberOfChargingStations++;
202 }
203
81797102 204 private logPrefix(): string {
689dca78 205 return Utils.logPrefix(' Bootstrap |');
81797102 206 }
ded13d97 207}