chore: apply dependencies update
[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 'worker_threads';
4
5import { ThreadWorker } from 'poolifier';
6
7import { ChargingStation, ChargingStationUtils } from './internal';
8import type { ChargingStationWorkerData } from '../types';
9import { Utils } from '../utils';
10import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
11
12// Conditionally export ThreadWorker instance for pool usage
13export let threadWorker: ThreadWorker;
14if (ChargingStationUtils.workerPoolInUse()) {
15 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
16 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
17 async: false,
18 });
19} else {
20 // Add message listener to start charging station from main thread
21 addMessageListener();
22 if (Utils.isUndefined(workerData) === false) {
23 startChargingStation(workerData as ChargingStationWorkerData);
24 }
25}
26
27/**
28 * Listen messages send by the main thread
29 */
30function addMessageListener(): void {
31 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
32 if (message.id === WorkerMessageEvents.START_WORKER_ELEMENT) {
33 startChargingStation(message.data);
34 }
35 });
36}
37
38/**
39 * Create and start a charging station instance
40 *
41 * @param data - workerData
42 */
43function startChargingStation(data: ChargingStationWorkerData): void {
44 const station = new ChargingStation(data.index, data.templateFile);
45 station.start();
46}