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 | ||
4c3c0d59 | 7 | import { ChargingStation } from './ChargingStation'; |
268a74bb | 8 | import type { ChargingStationWorkerData } from '../types'; |
aa7d6d95 | 9 | import { Configuration, Utils } from '../utils'; |
268a74bb | 10 | import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker'; |
7dde0b73 | 11 | |
e8a92d57 JB |
12 | /** |
13 | * Create and start a charging station instance | |
14 | * | |
15 | * @param data - workerData | |
16 | */ | |
17 | const startChargingStation = (data: ChargingStationWorkerData): void => { | |
18 | const station = new ChargingStation(data.index, data.templateFile); | |
19 | station.start(); | |
20 | }; | |
21 | ||
22 | /** | |
23 | * Listen messages send by the main thread | |
24 | */ | |
25 | const addMessageListener = (): void => { | |
26 | parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => { | |
27 | if (message.id === WorkerMessageEvents.startWorkerElement) { | |
28 | startChargingStation(message.data); | |
29 | } | |
30 | }); | |
31 | }; | |
32 | ||
b8da29bc | 33 | // Conditionally export ThreadWorker instance for pool usage |
56a74dae | 34 | export let threadWorker: ThreadWorker; |
aa7d6d95 | 35 | if (Configuration.workerPoolInUse()) { |
e7aeea18 | 36 | threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { |
3fa0f0ed | 37 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, |
e7aeea18 JB |
38 | async: false, |
39 | }); | |
74bbc59b | 40 | } else { |
56a74dae JB |
41 | // Add message listener to start charging station from main thread |
42 | addMessageListener(); | |
48d17ce2 | 43 | if (Utils.isUndefined(workerData) === false) { |
6d6dc22e | 44 | startChargingStation(workerData as ChargingStationWorkerData); |
6013bc53 | 45 | } |
3d2ff9e4 | 46 | } |