Fix workerSet linear ramp up at startup
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { ChargingStationWorkerData, ChargingStationWorkerMessage, ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
4 import { parentPort, workerData } from 'worker_threads';
5
6 import ChargingStation from './ChargingStation';
7 import Constants from '../utils/Constants';
8 import { ThreadWorker } from 'poolifier';
9 import Utils from '../utils/Utils';
10
11 // Conditionally export ThreadWorker instance for pool usage
12 export let threadWorker: ThreadWorker;
13 if (Utils.workerPoolInUse()) {
14 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { maxInactiveTime: Constants.WORKER_POOL_MAX_INACTIVE_TIME, async: false });
15 } else {
16 // Add message listener to start charging station from main thread
17 addMessageListener();
18 if (!Utils.isUndefined(workerData)) {
19 startChargingStation({ index: workerData.index as number, templateFile: workerData.templateFile as string });
20 }
21 }
22
23 /**
24 * Listen messages send by the main thread
25 */
26 function addMessageListener(): void {
27 parentPort?.on('message', async (message: ChargingStationWorkerMessage) => {
28 if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
29 startChargingStation(message.data);
30 message.workerOptions?.elementStartDelay > 0 && await Utils.sleep(this.workerOptions.elementStartDelay);
31 }
32 });
33 }
34
35 /**
36 * Create and start a charging station instance
37 *
38 * @param data workerData
39 */
40 function startChargingStation(data: ChargingStationWorkerData): void {
41 const station = new ChargingStation(data.index, data.templateFile);
42 station.start();
43 }