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