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