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