build(deps-dev): apply updates
[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
01f4001e 3import { parentPort, workerData } from 'node:worker_threads';
8114d10e
JB
4
5import { ThreadWorker } from 'poolifier';
6
4c3c0d59
JB
7import { ChargingStation } from './ChargingStation';
8import { ChargingStationUtils } from './ChargingStationUtils';
268a74bb 9import type { ChargingStationWorkerData } from '../types';
60a74391 10import { Utils } from '../utils';
268a74bb 11import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
7dde0b73 12
e8a92d57
JB
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
b8da29bc 34// Conditionally export ThreadWorker instance for pool usage
56a74dae 35export let threadWorker: ThreadWorker;
17ac262c 36if (ChargingStationUtils.workerPoolInUse()) {
e7aeea18 37 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
3fa0f0ed 38 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
e7aeea18
JB
39 async: false,
40 });
74bbc59b 41} else {
56a74dae
JB
42 // Add message listener to start charging station from main thread
43 addMessageListener();
48d17ce2 44 if (Utils.isUndefined(workerData) === false) {
6d6dc22e 45 startChargingStation(workerData as ChargingStationWorkerData);
6013bc53 46 }
3d2ff9e4 47}