| 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
| 2 | |
| 3 | import { parentPort, workerData } from 'node:worker_threads'; |
| 4 | |
| 5 | import { ThreadWorker } from 'poolifier'; |
| 6 | |
| 7 | import { ChargingStation } from './ChargingStation'; |
| 8 | import type { ChargingStationWorkerData } from '../types'; |
| 9 | import { Configuration } from '../utils'; |
| 10 | import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker'; |
| 11 | |
| 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 | |
| 33 | // Conditionally export ThreadWorker instance for pool usage |
| 34 | export let threadWorker: ThreadWorker; |
| 35 | if (Configuration.workerPoolInUse()) { |
| 36 | threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { |
| 37 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, |
| 38 | async: false, |
| 39 | }); |
| 40 | } else { |
| 41 | // Add message listener to start charging station from main thread |
| 42 | addMessageListener(); |
| 43 | if (workerData !== undefined) { |
| 44 | startChargingStation(workerData as ChargingStationWorkerData); |
| 45 | } |
| 46 | } |