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