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