Apply prettier formating
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
e7aeea18
JB
3import {
4 ChargingStationWorkerData,
5 ChargingStationWorkerMessage,
6 ChargingStationWorkerMessageEvents,
7} from '../types/ChargingStationWorker';
74bbc59b 8import { parentPort, workerData } from 'worker_threads';
3f40bc9c 9
6af9012e 10import ChargingStation from './ChargingStation';
a4624c96
JB
11import Constants from '../utils/Constants';
12import { ThreadWorker } from 'poolifier';
6013bc53 13import Utils from '../utils/Utils';
7dde0b73 14
b8da29bc 15// Conditionally export ThreadWorker instance for pool usage
56a74dae 16export let threadWorker: ThreadWorker;
b8da29bc 17if (Utils.workerPoolInUse()) {
e7aeea18
JB
18 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
19 maxInactiveTime: Constants.WORKER_POOL_MAX_INACTIVE_TIME,
20 async: false,
21 });
74bbc59b 22} else {
56a74dae
JB
23 // Add message listener to start charging station from main thread
24 addMessageListener();
6013bc53 25 if (!Utils.isUndefined(workerData)) {
e7aeea18
JB
26 startChargingStation({
27 index: workerData.index as number,
28 templateFile: workerData.templateFile as string,
29 });
6013bc53 30 }
3d2ff9e4
J
31}
32
3340259a 33/**
6f09a43f 34 * Listen messages send by the main thread
3340259a 35 */
56a74dae 36function addMessageListener(): void {
d070d967 37 parentPort?.on('message', (message: ChargingStationWorkerMessage) => {
98dc07fa 38 if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
81797102 39 startChargingStation(message.data);
3d2ff9e4
J
40 }
41 });
42}
43
3340259a 44/**
6f09a43f
JB
45 * Create and start a charging station instance
46 *
81797102 47 * @param data workerData
3340259a 48 */
07f35004 49function startChargingStation(data: ChargingStationWorkerData): void {
8bbe7426 50 const station = new ChargingStation(data.index, data.templateFile);
3d2ff9e4 51 station.start();
7dde0b73 52}