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 Statistics from
'../types/Statistics';
7 import { Storage
} from
'../performance/storage/Storage';
8 import { StorageFactory
} from
'../performance/storage/StorageFactory';
9 import { UIServiceUtils
} from
'./ui-websocket-services/UIServiceUtils';
10 import UIWebSocketServer from
'./UIWebSocketServer';
11 import Utils from
'../utils/Utils';
12 import WorkerAbstract from
'../worker/WorkerAbstract';
13 import WorkerFactory from
'../worker/WorkerFactory';
14 import chalk from
'chalk';
15 import { isMainThread
} from
'worker_threads';
16 import path from
'path';
17 import { version
} from
'../../package.json';
19 export default class Bootstrap
{
20 private static instance
: Bootstrap
| null = null;
21 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
22 private readonly uiWebSocketServer
!: UIWebSocketServer
;
23 private readonly storage
!: Storage
;
24 private numberOfChargingStations
: number;
25 private readonly version
: string = version
;
26 private started
: boolean;
27 private readonly workerScript
: string;
29 private constructor() {
31 this.workerScript
= path
.join(path
.resolve(__dirname
, '../'), 'charging-station', 'ChargingStationWorker.js');
32 this.initWorkerImplementation();
33 Configuration
.getUIWebSocketServer().enabled
&& (this.uiWebSocketServer
= new UIWebSocketServer({
34 ...Configuration
.getUIWebSocketServer().options
, handleProtocols
: UIServiceUtils
.handleProtocols
36 Configuration
.getPerformanceStorage().enabled
&& (this.storage
= StorageFactory
.getStorage(
37 Configuration
.getPerformanceStorage().type,
38 Configuration
.getPerformanceStorage().uri
,
41 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
44 public static getInstance(): Bootstrap
{
45 if (!Bootstrap
.instance
) {
46 Bootstrap
.instance
= new Bootstrap();
48 return Bootstrap
.instance
;
51 public async start(): Promise
<void> {
52 if (isMainThread
&& !this.started
) {
54 this.numberOfChargingStations
= 0;
55 await this.storage
?.open();
56 await this.workerImplementation
.start();
57 this.uiWebSocketServer
?.start();
58 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
59 // Start ChargingStation object in worker thread
60 if (stationTemplateUrls
) {
61 for (const stationTemplateUrl
of stationTemplateUrls
) {
63 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
64 for (let index
= 1; index
<= nbStations
; index
++) {
65 const workerData
: ChargingStationWorkerData
= {
67 templateFile
: path
.join(path
.resolve(__dirname
, '../'), 'assets', 'station-templates', path
.basename(stationTemplateUrl
.file
))
69 await this.workerImplementation
.addElement(workerData
);
70 this.numberOfChargingStations
++;
73 console
.error(chalk
.red('Charging station start with template file ' + stationTemplateUrl
.file
+ ' error '), error
);
77 console
.warn(chalk
.yellow('No stationTemplateUrls defined in configuration, exiting'));
79 if (this.numberOfChargingStations
=== 0) {
80 console
.warn(chalk
.yellow('No charging station template enabled in configuration, exiting'));
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)` : ''}`));
86 console.error(chalk.red('Bootstrap start error '), error);
89 console.error(chalk.red('Cannot start an already started charging stations simulator'));
93 public async stop(): Promise<void> {
94 if (isMainThread && this.started) {
95 await this.workerImplementation.stop();
96 this.uiWebSocketServer?.stop();
97 await this.storage?.close();
99 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
101 this.started = false;
104 public async restart(): Promise<void> {
106 this.initWorkerImplementation();
110 private initWorkerImplementation(): void {
111 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
113 workerStartDelay: Configuration.getWorkerStartDelay(),
114 elementStartDelay: Configuration.getElementStartDelay(),
115 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
116 poolMinSize: Configuration.getWorkerPoolMinSize(),
117 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
119 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
121 messageHandler: async (msg: ChargingStationWorkerMessage) => {
122 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
123 this.uiWebSocketServer.chargingStations.add(msg.data.id as string);
124 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
125 this.uiWebSocketServer.chargingStations.delete(msg.data.id as string);
126 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
127 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
133 private logPrefix(): string {
134 return Utils.logPrefix(' Bootstrap |');