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