refactor: revert internal exports
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { parentPort, workerData } from 'node:worker_threads';
4
5 import { ThreadWorker } from 'poolifier';
6
7 import { ChargingStation } from './ChargingStation';
8 import { ChargingStationUtils } from './ChargingStationUtils';
9 import type { ChargingStationWorkerData } from '../types';
10 import { Utils } from '../utils';
11 import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
12
13 /**
14 * Create and start a charging station instance
15 *
16 * @param data - workerData
17 */
18 const startChargingStation = (data: ChargingStationWorkerData): void => {
19 const station = new ChargingStation(data.index, data.templateFile);
20 station.start();
21 };
22
23 /**
24 * Listen messages send by the main thread
25 */
26 const addMessageListener = (): void => {
27 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
28 if (message.id === WorkerMessageEvents.startWorkerElement) {
29 startChargingStation(message.data);
30 }
31 });
32 };
33
34 // Conditionally export ThreadWorker instance for pool usage
35 export let threadWorker: ThreadWorker;
36 if (ChargingStationUtils.workerPoolInUse()) {
37 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
38 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
39 async: false,
40 });
41 } else {
42 // Add message listener to start charging station from main thread
43 addMessageListener();
44 if (Utils.isUndefined(workerData) === false) {
45 startChargingStation(workerData as ChargingStationWorkerData);
46 }
47 }