bb2db88a4c749acafee441291b05dc8ef4fdf36e
[e-mobility-charging-stations-simulator.git] / src / charging-station / StationWorker.ts
1 import { StationWorkerData, WorkerEvents } from '../types/Worker';
2 import { parentPort, workerData } from 'worker_threads';
3
4 import ChargingStation from './ChargingStation';
5 import Constants from '../utils/Constants';
6 import { ThreadWorker } from 'poolifier';
7 import Utils from '../utils/Utils';
8
9 // Conditionally export ThreadWorker instance for pool usage
10 export let threadWorker: ThreadWorker;
11 if (Utils.workerPoolInUse()) {
12 threadWorker = new ThreadWorker<StationWorkerData>(startChargingStation, { maxInactiveTime: Constants.WORKER_POOL_MAX_INACTIVE_TIME, async: false });
13 } else {
14 // Add message listener to start charging station from main thread
15 addMessageListener();
16 if (!Utils.isUndefined(workerData)) {
17 startChargingStation({ index: workerData.index as number, templateFile: workerData.templateFile as string });
18 }
19 }
20
21 function addMessageListener(): void {
22 parentPort.on('message', (message) => {
23 if (message.id === WorkerEvents.START_WORKER_ELEMENT) {
24 startChargingStation(message.workerData);
25 }
26 });
27 }
28
29 function startChargingStation(data: StationWorkerData): void {
30 const station = new ChargingStation(data.index, data.templateFile);
31 station.start();
32 }