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