1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { AsyncResource
} from
'node:async_hooks';
4 import { parentPort
} from
'node:worker_threads';
6 import { ThreadWorker
} from
'poolifier';
8 import { ChargingStation
} from
'./ChargingStation';
9 import type { ChargingStationWorkerData
} from
'../types';
10 import { Configuration
} from
'../utils';
11 import { WorkerConstants
, type WorkerMessage
, WorkerMessageEvents
} from
'../worker';
14 * Create and start a charging station instance
16 * @param data - workerData
18 const startChargingStation
= (data
: ChargingStationWorkerData
): void => {
19 new ChargingStation(data
.index
, data
.templateFile
).start();
22 class ChargingStationWorker
extends AsyncResource
{
24 super('ChargingStationWorker');
25 // Add message listener to create and start charging station from the main thread
26 parentPort
?.on('message', (message
: WorkerMessage
<ChargingStationWorkerData
>) => {
27 if (message
.id
=== WorkerMessageEvents
.startWorkerElement
) {
29 startChargingStation
.bind(this) as (data
: ChargingStationWorkerData
) => void,
38 export let chargingStationWorker
: ChargingStationWorker
;
39 // Conditionally export ThreadWorker instance for pool usage
40 export let threadWorker
: ThreadWorker
;
41 if (Configuration
.workerPoolInUse()) {
42 threadWorker
= new ThreadWorker
<ChargingStationWorkerData
>(startChargingStation
, {
43 maxInactiveTime
: WorkerConstants
.POOL_MAX_INACTIVE_TIME
,
46 chargingStationWorker
= new ChargingStationWorker();