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