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