Commit | Line | Data |
---|---|---|
c8eeb62b JB |
1 | // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. |
2 | ||
e7aeea18 JB |
3 | import { |
4 | ChargingStationWorkerData, | |
5 | ChargingStationWorkerMessage, | |
6 | ChargingStationWorkerMessageEvents, | |
7 | } from '../types/ChargingStationWorker'; | |
74bbc59b | 8 | import { parentPort, workerData } from 'worker_threads'; |
3f40bc9c | 9 | |
6af9012e | 10 | import ChargingStation from './ChargingStation'; |
a4624c96 | 11 | import { ThreadWorker } from 'poolifier'; |
6013bc53 | 12 | import Utils from '../utils/Utils'; |
3fa0f0ed | 13 | import WorkerConstants from '../worker/WorkerConstants'; |
7dde0b73 | 14 | |
b8da29bc | 15 | // Conditionally export ThreadWorker instance for pool usage |
56a74dae | 16 | export let threadWorker: ThreadWorker; |
b8da29bc | 17 | if (Utils.workerPoolInUse()) { |
e7aeea18 | 18 | threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, { |
3fa0f0ed | 19 | maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, |
e7aeea18 JB |
20 | async: false, |
21 | }); | |
74bbc59b | 22 | } else { |
56a74dae JB |
23 | // Add message listener to start charging station from main thread |
24 | addMessageListener(); | |
6013bc53 | 25 | if (!Utils.isUndefined(workerData)) { |
e7aeea18 | 26 | startChargingStation({ |
3fa0f0ed | 27 | // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access |
e7aeea18 | 28 | index: workerData.index as number, |
3fa0f0ed | 29 | // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access |
e7aeea18 JB |
30 | templateFile: workerData.templateFile as string, |
31 | }); | |
6013bc53 | 32 | } |
3d2ff9e4 J |
33 | } |
34 | ||
3340259a | 35 | /** |
6f09a43f | 36 | * Listen messages send by the main thread |
3340259a | 37 | */ |
56a74dae | 38 | function addMessageListener(): void { |
d070d967 | 39 | parentPort?.on('message', (message: ChargingStationWorkerMessage) => { |
98dc07fa | 40 | if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) { |
81797102 | 41 | startChargingStation(message.data); |
3d2ff9e4 J |
42 | } |
43 | }); | |
44 | } | |
45 | ||
3340259a | 46 | /** |
6f09a43f JB |
47 | * Create and start a charging station instance |
48 | * | |
81797102 | 49 | * @param data workerData |
3340259a | 50 | */ |
07f35004 | 51 | function startChargingStation(data: ChargingStationWorkerData): void { |
8bbe7426 | 52 | const station = new ChargingStation(data.index, data.templateFile); |
3d2ff9e4 | 53 | station.start(); |
7dde0b73 | 54 | } |