1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
4 ChargingStationWorkerData
,
5 ChargingStationWorkerMessage
,
6 ChargingStationWorkerMessageEvents
,
7 } from
'../types/ChargingStationWorker';
9 import { AbstractUIServer
} from
'./ui-server/AbstractUIServer';
10 import { ApplicationProtocol
} from
'../types/UIProtocol';
11 import { ChargingStationUtils
} from
'./ChargingStationUtils';
12 import Configuration from
'../utils/Configuration';
13 import { StationTemplateUrl
} from
'../types/ConfigurationData';
14 import Statistics from
'../types/Statistics';
15 import { Storage
} from
'../performance/storage/Storage';
16 import { StorageFactory
} from
'../performance/storage/StorageFactory';
17 import UIServerFactory from
'./ui-server/UIServerFactory';
18 import { UIServiceUtils
} from
'./ui-server/ui-services/UIServiceUtils';
19 import Utils from
'../utils/Utils';
20 import WorkerAbstract from
'../worker/WorkerAbstract';
21 import WorkerFactory from
'../worker/WorkerFactory';
22 import chalk from
'chalk';
23 import { fileURLToPath
} from
'url';
24 import { isMainThread
} from
'worker_threads';
25 import path from
'path';
26 import { version
} from
'../../package.json';
28 export default class Bootstrap
{
29 private static instance
: Bootstrap
| null = null;
30 private workerImplementation
: WorkerAbstract
<ChargingStationWorkerData
> | null = null;
31 private readonly uiServer
!: AbstractUIServer
;
32 private readonly storage
!: Storage
;
33 private numberOfChargingStationTemplates
!: number;
34 private numberOfChargingStations
!: number;
35 private readonly version
: string = version
;
36 private started
: boolean;
37 private readonly workerScript
: string;
39 private constructor() {
41 this.workerScript
= path
.join(
42 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
44 'ChargingStationWorker' + path
.extname(fileURLToPath(import.meta
.url
))
47 Configuration
.getUIServer().enabled
&&
48 (this.uiServer
= UIServerFactory
.getUIServerImplementation(ApplicationProtocol
.WS
, {
49 ...Configuration
.getUIServer().options
,
50 handleProtocols
: UIServiceUtils
.handleProtocols
,
52 Configuration
.getPerformanceStorage().enabled
&&
53 (this.storage
= StorageFactory
.getStorage(
54 Configuration
.getPerformanceStorage().type,
55 Configuration
.getPerformanceStorage().uri
,
58 Configuration
.setConfigurationChangeCallback(async () => Bootstrap
.getInstance().restart());
61 public static getInstance(): Bootstrap
{
62 if (!Bootstrap
.instance
) {
63 Bootstrap
.instance
= new Bootstrap();
65 return Bootstrap
.instance
;
68 public async start(): Promise
<void> {
69 if (isMainThread
&& !this.started
) {
72 await this.storage
?.open();
73 await this.workerImplementation
.start();
74 this.uiServer
?.start();
75 const stationTemplateUrls
= Configuration
.getStationTemplateUrls();
76 this.numberOfChargingStationTemplates
= stationTemplateUrls
.length
;
77 // Start ChargingStation object in worker thread
78 if (!Utils
.isEmptyArray(stationTemplateUrls
)) {
79 for (const stationTemplateUrl
of stationTemplateUrls
) {
81 const nbStations
= stationTemplateUrl
.numberOfStations
?? 0;
82 for (let index
= 1; index
<= nbStations
; index
++) {
83 await this.startChargingStation(index
, stationTemplateUrl
);
88 'Error at starting charging station with template file ' +
89 stationTemplateUrl
.file
+
98 chalk
.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
101 if (this.numberOfChargingStations
=== 0) {
103 chalk
.yellow('No charging station template enabled in configuration, exiting')
108 `Charging stations simulator ${
110 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
111 ChargingStationUtils.workerDynamicPoolInUse()
112 ? `${Configuration.getWorkerPoolMinSize().toString()}
/`
114 }${this.workerImplementation.size}${
115 ChargingStationUtils.workerPoolInUse()
116 ? `/${Configuration.getWorkerPoolMaxSize().toString()}
`
118 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
119 this.workerImplementation.maxElementsPerWorker
120 ? ` (${this.workerImplementation.maxElementsPerWorker} charging
station(s
) per worker
)`
128 console
.error(chalk
.red('Bootstrap start error '), error
);
131 console
.error(chalk
.red('Cannot start an already started charging stations simulator'));
135 public async stop(): Promise
<void> {
136 if (isMainThread
&& this.started
) {
137 await this.workerImplementation
.stop();
138 this.workerImplementation
= null;
139 this.uiServer
?.stop();
140 await this.storage
?.close();
142 console
.error(chalk
.red('Trying to stop the charging stations simulator while not started'));
144 this.started
= false;
147 public async restart(): Promise
<void> {
153 private initializeWorkerImplementation(): void {
154 !this.workerImplementation
&&
155 (this.workerImplementation
= WorkerFactory
.getWorkerImplementation
<ChargingStationWorkerData
>(
157 Configuration
.getWorkerProcess(),
159 workerStartDelay
: Configuration
.getWorkerStartDelay(),
160 elementStartDelay
: Configuration
.getElementStartDelay(),
161 poolMaxSize
: Configuration
.getWorkerPoolMaxSize(),
162 poolMinSize
: Configuration
.getWorkerPoolMinSize(),
163 elementsPerWorker
: Configuration
.getChargingStationsPerWorker(),
165 workerChoiceStrategy
: Configuration
.getWorkerPoolStrategy(),
167 messageHandler
: async (msg
: ChargingStationWorkerMessage
) => {
168 if (msg
.id
=== ChargingStationWorkerMessageEvents
.STARTED
) {
169 this.uiServer
.chargingStations
.add(msg
.data
.id
as string);
170 } else if (msg
.id
=== ChargingStationWorkerMessageEvents
.STOPPED
) {
171 this.uiServer
.chargingStations
.delete(msg
.data
.id
as string);
172 } else if (msg
.id
=== ChargingStationWorkerMessageEvents
.PERFORMANCE_STATISTICS
) {
173 await this.storage
.storePerformanceStatistics(msg
.data
as unknown
as Statistics
);
180 private initialize() {
181 this.numberOfChargingStations
= 0;
182 this.numberOfChargingStationTemplates
= 0;
183 this.initializeWorkerImplementation();
186 private async startChargingStation(
188 stationTemplateUrl
: StationTemplateUrl
190 const workerData
: ChargingStationWorkerData
= {
192 templateFile
: path
.join(
193 path
.resolve(path
.dirname(fileURLToPath(import.meta
.url
)), '../'),
196 path
.basename(stationTemplateUrl
.file
)
199 await this.workerImplementation
.addElement(workerData
);
200 this.numberOfChargingStations
++;
203 private logPrefix(): string {
204 return Utils
.logPrefix(' Bootstrap |');