1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ChargingStationWorkerData
, ChargingStationWorkerMessage
, ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
5 import Configuration from
'../utils/Configuration';
6 import { StationTemplateUrl
} from
'../types/ConfigurationData';
7 import Statistics from
'../types/Statistics';
8 import { Storage
} from
'../performance/storage/Storage';
9 import { StorageFactory
} from
'../performance/storage/StorageFactory';
10 import { UIServiceUtils
} from
'./ui-websocket-services/UIServiceUtils';
11 import UIWebSocketServer from
'./UIWebSocketServer';
12 import Utils from
'../utils/Utils';
13 import WorkerAbstract from
'../worker/WorkerAbstract';
14 import WorkerFactory from
'../worker/WorkerFactory';
15 import chalk from
'chalk';
16 import { isMainThread
} from
'worker_threads';
17 import path from
'path';
18 import { version
} from
'../../package.json';
20 export default class Bootstrap
{
21 private static instance
: Bootstrap
| null = null;
22 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
23 private readonly uiWebSocketServer
!: UIWebSocketServer
;
24 private readonly storage
!: Storage
;
25 private numberOfChargingStations
: number;
26 private readonly version
: string = version
;
27 private started
: boolean;
28 private readonly workerScript
: string;
30 private constructor() {
32 this.workerScript
= path
.join(path
.resolve(__dirname
, '../'), 'charging-station', 'ChargingStationWorker.js');
33 this.initWorkerImplementation();
34 Configuration
.getUIWebSocketServer().enabled
&& (this.uiWebSocketServer
= new UIWebSocketServer({
35 ...Configuration
.getUIWebSocketServer().options
, handleProtocols
: UIServiceUtils
.handleProtocols
37 Configuration
.getPerformanceStorage().enabled
&& (this.storage
= StorageFactory
.getStorage(
38 Configuration
.getPerformanceStorage().type,
39 Configuration
.getPerformanceStorage().uri
,
42 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
45 public static getInstance(): Bootstrap
{
46 if (!Bootstrap
.instance
) {
47 Bootstrap
.instance
= new Bootstrap();
49 return Bootstrap
.instance
;
52 public async start(): Promise
<void> {
53 if (isMainThread
&& !this.started
) {
55 this.numberOfChargingStations
= 0;
56 await this.storage
?.open();
57 await this.workerImplementation
.start();
58 this.uiWebSocketServer
?.start();
59 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
60 // Start ChargingStation object in worker thread
61 if (stationTemplateUrls
) {
62 for (const stationTemplateUrl
of stationTemplateUrls
) {
64 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
65 for (let index
= 1; index
<= nbStations
; index
++) {
66 await this.startChargingStation(index
, stationTemplateUrl
);
69 console
.error(chalk
.red('Charging station start with template file ' + stationTemplateUrl
.file
+ ' error '), error
);
73 console
.warn(chalk
.yellow('No stationTemplateUrls defined in configuration, exiting'));
75 if (this.numberOfChargingStations
=== 0) {
76 console
.warn(chalk
.yellow('No charging station template enabled in configuration, exiting'));
78 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)` : ''}`));
82 console.error(chalk.red('Bootstrap start error '), error);
85 console.error(chalk.red('Cannot start an already started charging stations simulator'));
89 public async stop(): Promise<void> {
90 if (isMainThread && this.started) {
91 await this.workerImplementation.stop();
92 this.uiWebSocketServer?.stop();
93 await this.storage?.close();
95 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
100 public async restart(): Promise<void> {
102 this.initWorkerImplementation();
106 private initWorkerImplementation(): void {
107 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
109 workerStartDelay: Configuration.getWorkerStartDelay(),
110 elementStartDelay: Configuration.getElementStartDelay(),
111 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
112 poolMinSize: Configuration.getWorkerPoolMinSize(),
113 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
115 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
117 messageHandler: async (msg: ChargingStationWorkerMessage) => {
118 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
119 this.uiWebSocketServer.chargingStations.add(msg.data.id as string);
120 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
121 this.uiWebSocketServer.chargingStations.delete(msg.data.id as string);
122 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
123 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
129 private async startChargingStation(index: number, stationTemplateUrl: StationTemplateUrl): Promise<void> {
130 const workerData: ChargingStationWorkerData = {
132 templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationTemplateUrl.file))
134 await this.workerImplementation.addElement(workerData);
135 this.numberOfChargingStations++;
138 private logPrefix(): string {
139 return Utils.logPrefix(' Bootstrap |');