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