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 Configuration
.getUIWebSocketServer().enabled
&& (this.uiWebSocketServer
= new UIWebSocketServer({
33 ...Configuration
.getUIWebSocketServer().options
, handleProtocols
: UIServiceUtils
.handleProtocols
35 Configuration
.getPerformanceStorage().enabled
&& (this.storage
= StorageFactory
.getStorage(
36 Configuration
.getPerformanceStorage().type,
37 Configuration
.getPerformanceStorage().URI
,
40 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
43 public static getInstance(): Bootstrap
{
44 if (!Bootstrap
.instance
) {
45 Bootstrap
.instance
= new Bootstrap();
47 return Bootstrap
.instance
;
50 public async start(): Promise
<void> {
51 if (isMainThread
&& !this.started
) {
53 this.numberOfChargingStations
= 0;
54 await this.storage
?.open();
55 await this.workerImplementation
.start();
56 this.uiWebSocketServer
?.start();
57 // Start ChargingStation object in worker thread
58 if (Configuration
.getStationTemplateURLs()) {
59 for (const stationURL
of Configuration
.getStationTemplateURLs()) {
61 const nbStations
= stationURL
.numberOfStations
?? 0;
62 for (let index
= 1; index
<= nbStations
; index
++) {
63 const workerData
: ChargingStationWorkerData
= {
65 templateFile
: path
.join(path
.resolve(__dirname
, '../'), 'assets', 'station-templates', path
.basename(stationURL
.file
))
67 await this.workerImplementation
.addElement(workerData
);
68 this.numberOfChargingStations
++;
71 console
.error(chalk
.red('Charging station start with template file ' + stationURL
.file
+ ' error '), error
);
75 console
.warn(chalk
.yellow('No stationTemplateURLs defined in configuration, exiting'));
77 if (this.numberOfChargingStations
=== 0) {
78 console
.warn(chalk
.yellow('No charging station template enabled in configuration, exiting'));
80 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)` : ''}`));
84 console.error(chalk.red('Bootstrap start error '), error);
87 console.error(chalk.red('Cannot start an already started charging stations simulator'));
91 public async stop(): Promise<void> {
92 if (isMainThread && this.started) {
93 await this.workerImplementation.stop();
94 this.uiWebSocketServer?.stop();
95 await this.storage?.close();
97 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
102 public async restart(): Promise<void> {
104 this.initWorkerImplementation();
108 private initWorkerImplementation(): void {
109 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
111 startDelay: Configuration.getWorkerStartDelay(),
112 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
113 poolMinSize: Configuration.getWorkerPoolMinSize(),
114 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
116 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
118 messageHandler: async (msg: ChargingStationWorkerMessage) => {
119 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
120 this.uiWebSocketServer.uiService.chargingStations.add(msg.data.id);
121 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
122 this.uiWebSocketServer.uiService.chargingStations.delete(msg.data.id);
123 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
124 await this.storage.storePerformanceStatistics(msg.data);
130 private logPrefix(): string {
131 return Utils.logPrefix(' Bootstrap |');