Release 1.0.36
[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
3340259a 21/**
6f09a43f 22 * Listen messages send by the main thread
3340259a 23 */
56a74dae 24function addMessageListener(): void {
6e0964c8 25 parentPort?.on('message', (message) => {
3e1416d8
JB
26 if (message.id === WorkerEvents.START_WORKER_ELEMENT) {
27 startChargingStation(message.workerData);
3d2ff9e4
J
28 }
29 });
30}
31
3340259a 32/**
6f09a43f
JB
33 * Create and start a charging station instance
34 *
35 * @param {StationWorkerData} data workerData
3340259a 36 */
abbd09af 37function startChargingStation(data: StationWorkerData): void {
8bbe7426 38 const station = new ChargingStation(data.index, data.templateFile);
3d2ff9e4 39 station.start();
7dde0b73 40}