refactor: revert internal exports
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
... / ...
CommitLineData
1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3import { parentPort, workerData } from 'node:worker_threads';
4
5import { ThreadWorker } from 'poolifier';
6
7import { ChargingStation } from './ChargingStation';
8import { ChargingStationUtils } from './ChargingStationUtils';
9import type { ChargingStationWorkerData } from '../types';
10import { Utils } from '../utils';
11import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
12
13/**
14 * Create and start a charging station instance
15 *
16 * @param data - workerData
17 */
18const 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 */
26const 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
35export let threadWorker: ThreadWorker;
36if (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}