1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { ChargingStationWorkerData
, ChargingStationWorkerMessage
, ChargingStationWorkerMessageEvents
} from
'../types/ChargingStationWorker';
4 import { parentPort
, workerData
} from
'worker_threads';
6 import ChargingStation from
'./ChargingStation';
7 import Constants from
'../utils/Constants';
8 import { ThreadWorker
} from
'poolifier';
9 import Utils from
'../utils/Utils';
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 });
16 // Add message listener to start charging station from main thread
18 if (!Utils
.isUndefined(workerData
)) {
19 startChargingStation({ index
: workerData
.index
as number, templateFile
: workerData
.templateFile
as string });
24 * Listen messages send by the main thread
26 function addMessageListener(): void {
27 parentPort
?.on('message', async (message
: ChargingStationWorkerMessage
) => {
28 if (message
.id
=== ChargingStationWorkerMessageEvents
.START_WORKER_ELEMENT
) {
29 startChargingStation(message
.data
);
30 message
.workerOptions
?.elementStartDelay
> 0 && await Utils
.sleep(this.workerOptions
.elementStartDelay
);
36 * Create and start a charging station instance
38 * @param data workerData
40 function startChargingStation(data
: ChargingStationWorkerData
): void {
41 const station
= new ChargingStation(data
.index
, data
.templateFile
);