1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 import { parentPort
, workerData
} from
'node:worker_threads';
5 import { ThreadWorker
} from
'poolifier';
7 import { ChargingStation
} from
'./ChargingStation';
8 import { ChargingStationUtils
} from
'./ChargingStationUtils';
9 import type { ChargingStationWorkerData
} from
'../types';
10 import { Utils
} 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 const station
= new ChargingStation(data
.index
, data
.templateFile
);
24 * Listen messages send by the main thread
26 const addMessageListener
= (): void => {
27 parentPort
?.on('message', (message
: WorkerMessage
<ChargingStationWorkerData
>) => {
28 if (message
.id
=== WorkerMessageEvents
.startWorkerElement
) {
29 startChargingStation(message
.data
);
34 // Conditionally export ThreadWorker instance for pool usage
35 export let threadWorker
: ThreadWorker
;
36 if (ChargingStationUtils
.workerPoolInUse()) {
37 threadWorker
= new ThreadWorker
<ChargingStationWorkerData
>(startChargingStation
, {
38 maxInactiveTime
: WorkerConstants
.POOL_MAX_INACTIVE_TIME
,
42 // Add message listener to start charging station from main thread
44 if (Utils
.isUndefined(workerData
) === false) {
45 startChargingStation(workerData
as ChargingStationWorkerData
);