Commit | Line | Data |
---|---|---|
c8eeb62b JB |
1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
8114d10e JB |
3 | import { parentPort, workerData } from 'worker_threads'; |
4 | ||
5 | import { ThreadWorker } from 'poolifier'; | |
6 | ||
c72f6634 JB |
7 | import type { ChargingStationWorkerData } from '../types/ChargingStationWorker'; |
8 | import { WorkerMessage, WorkerMessageEvents } from '../types/Worker'; | |
6013bc53 | 9 | import Utils from '../utils/Utils'; |
3fa0f0ed | 10 | import WorkerConstants from '../worker/WorkerConstants'; |
8114d10e JB |
11 | import ChargingStation from './ChargingStation'; |
12 | import { ChargingStationUtils } from './ChargingStationUtils'; | |
7dde0b73 | 13 | |
b8da29bc | 14 | // Conditionally export ThreadWorker instance for pool usage |
56a74dae | 15 | export let threadWorker: ThreadWorker; |
17ac262c | 16 | if (ChargingStationUtils.workerPoolInUse()) { |
e7aeea18 | 17 | threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { |
3fa0f0ed | 18 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, |
e7aeea18 JB |
19 | async: false, |
20 | }); | |
74bbc59b | 21 | } else { |
56a74dae JB |
22 | // Add message listener to start charging station from main thread |
23 | addMessageListener(); | |
48d17ce2 | 24 | if (Utils.isUndefined(workerData) === false) { |
6d6dc22e | 25 | startChargingStation(workerData as ChargingStationWorkerData); |
6013bc53 | 26 | } |
3d2ff9e4 J |
27 | } |
28 | ||
3340259a | 29 | /** |
6f09a43f | 30 | * Listen messages send by the main thread |
3340259a | 31 | */ |
56a74dae | 32 | function addMessageListener(): void { |
c72f6634 JB |
33 | parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => { |
34 | if (message.id === WorkerMessageEvents.START_WORKER_ELEMENT) { | |
81797102 | 35 | startChargingStation(message.data); |
3d2ff9e4 J |
36 | } |
37 | }); | |
38 | } | |
39 | ||
3340259a | 40 | /** |
6f09a43f JB |
41 | * Create and start a charging station instance |
42 | * | |
81797102 | 43 | * @param data workerData |
3340259a | 44 | */ |
07f35004 | 45 | function startChargingStation(data: ChargingStationWorkerData): void { |
8bbe7426 | 46 | const station = new ChargingStation(data.index, data.templateFile); |
3d2ff9e4 | 47 | station.start(); |
7dde0b73 | 48 | } |