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