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