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 { Storage
} from
'../performance/storage/Storage';
7 import { StorageFactory
} from
'../performance/storage/StorageFactory';
8 import { UIServiceUtils
} from
'./UIWebSocketServices/UIServiceUtils';
9 import UIWebSocketServer from
'./UIWebSocketServer';
10 import Utils from
'../utils/Utils';
11 import WorkerAbstract from
'../worker/WorkerAbstract';
12 import WorkerFactory from
'../worker/WorkerFactory';
13 import chalk from
'chalk';
14 import { isMainThread
} from
'worker_threads';
15 import path from
'path';
16 import { version
} from
'../../package.json';
18 export default class Bootstrap
{
19 private static instance
: Bootstrap
| null = null;
20 private workerImplementation
: WorkerAbstract
| null = null;
21 private readonly uiWebSocketServer
: UIWebSocketServer
;
22 private readonly storage
: Storage
;
23 private numberOfChargingStations
: number;
24 private readonly version
: string = version
;
25 private started
: boolean;
26 private readonly workerScript
: string;
28 private constructor() {
30 this.workerScript
= path
.join(path
.resolve(__dirname
, '../'), 'charging-station', 'ChargingStationWorker.js');
31 this.initWorkerImplementation();
32 this.uiWebSocketServer
= new UIWebSocketServer({ port
: 80, handleProtocols
: UIServiceUtils
.handleProtocols
});
33 this.storage
= StorageFactory
.getStorage(Configuration
.getPerformanceStorage().type, Configuration
.getPerformanceStorage().URI
, this.logPrefix());
34 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
37 public static getInstance(): Bootstrap
{
38 if (!Bootstrap
.instance
) {
39 Bootstrap
.instance
= new Bootstrap();
41 return Bootstrap
.instance
;
44 public async start(): Promise
<void> {
45 if (isMainThread
&& !this.started
) {
47 this.numberOfChargingStations
= 0;
48 await this.storage
.open();
49 await this.workerImplementation
.start();
50 this.uiWebSocketServer
.start();
51 // Start ChargingStation object in worker thread
52 if (Configuration
.getStationTemplateURLs()) {
53 for (const stationURL
of Configuration
.getStationTemplateURLs()) {
55 const nbStations
= stationURL
.numberOfStations
?? 0;
56 for (let index
= 1; index
<= nbStations
; index
++) {
57 const workerData
: ChargingStationWorkerData
= {
59 templateFile
: path
.join(path
.resolve(__dirname
, '../'), 'assets', 'station-templates', path
.basename(stationURL
.file
))
61 await this.workerImplementation
.addElement(workerData
);
62 this.numberOfChargingStations
++;
65 console
.error(chalk
.red('Charging station start with template file ' + stationURL
.file
+ ' error '), error
);
69 console
.warn(chalk
.yellow('No stationTemplateURLs defined in configuration, exiting'));
71 if (this.numberOfChargingStations
=== 0) {
72 console
.warn(chalk
.yellow('No charging station template enabled in configuration, exiting'));
74 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)` : ''}`));
78 console.error(chalk.red('Bootstrap start error '), error);
81 console.error(chalk.red('Cannot start an already started charging stations simulator'));
85 public async stop(): Promise<void> {
86 if (isMainThread && this.started) {
87 await this.workerImplementation.stop();
88 this.uiWebSocketServer.stop();
89 await this.storage.close();
91 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
96 public async restart(): Promise<void> {
98 this.initWorkerImplementation();
102 private initWorkerImplementation(): void {
103 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
105 startDelay: Configuration.getWorkerStartDelay(),
106 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
107 poolMinSize: Configuration.getWorkerPoolMinSize(),
108 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
110 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
112 messageHandler: async (msg: ChargingStationWorkerMessage) => {
113 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
114 this.uiWebSocketServer.uiService.chargingStations.add(msg.data.id);
115 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
116 this.uiWebSocketServer.uiService.chargingStations.delete(msg.data.id);
117 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
118 await this.storage.storePerformanceStatistics(msg.data);
124 private logPrefix(): string {
125 return Utils.logPrefix(' Bootstrap |');