Fix remaining linter errors properly
[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({
27 index: (workerData as Record<string, unknown>).index as number,
28 templateFile: (workerData as Record<string, unknown>).templateFile as string,
29 });
30 }
31 }
32
33 /**
34 * Listen messages send by the main thread
35 */
36 function addMessageListener(): void {
37 parentPort?.on('message', (message: ChargingStationWorkerMessage) => {
38 if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
39 startChargingStation(message.data);
40 }
41 });
42 }
43
44 /**
45 * Create and start a charging station instance
46 *
47 * @param data workerData
48 */
49 function startChargingStation(data: ChargingStationWorkerData): void {
50 const station = new ChargingStation(data.index, data.templateFile);
51 station.start();
52 }