Apply dependencies update
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
e7aeea18
JB
3import {
4 ChargingStationWorkerData,
5 ChargingStationWorkerMessage,
6 ChargingStationWorkerMessageEvents,
7} from '../types/ChargingStationWorker';
74bbc59b 8import { parentPort, workerData } from 'worker_threads';
3f40bc9c 9
6af9012e 10import ChargingStation from './ChargingStation';
17ac262c 11import { ChargingStationUtils } from './ChargingStationUtils';
a4624c96 12import { ThreadWorker } from 'poolifier';
6013bc53 13import Utils from '../utils/Utils';
3fa0f0ed 14import WorkerConstants from '../worker/WorkerConstants';
7dde0b73 15
b8da29bc 16// Conditionally export ThreadWorker instance for pool usage
56a74dae 17export let threadWorker: ThreadWorker;
17ac262c 18if (ChargingStationUtils.workerPoolInUse()) {
e7aeea18 19 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
3fa0f0ed 20 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
e7aeea18
JB
21 async: false,
22 });
74bbc59b 23} else {
56a74dae
JB
24 // Add message listener to start charging station from main thread
25 addMessageListener();
6013bc53 26 if (!Utils.isUndefined(workerData)) {
6d6dc22e 27 startChargingStation(workerData as ChargingStationWorkerData);
6013bc53 28 }
3d2ff9e4
J
29}
30
3340259a 31/**
6f09a43f 32 * Listen messages send by the main thread
3340259a 33 */
56a74dae 34function addMessageListener(): void {
d070d967 35 parentPort?.on('message', (message: ChargingStationWorkerMessage) => {
98dc07fa 36 if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
81797102 37 startChargingStation(message.data);
3d2ff9e4
J
38 }
39 });
40}
41
3340259a 42/**
6f09a43f
JB
43 * Create and start a charging station instance
44 *
81797102 45 * @param data workerData
3340259a 46 */
07f35004 47function startChargingStation(data: ChargingStationWorkerData): void {
8bbe7426 48 const station = new ChargingStation(data.index, data.templateFile);
3d2ff9e4 49 station.start();
7dde0b73 50}