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', (message
: ChargingStationWorkerMessage
) => {
28 if (message
.id
=== ChargingStationWorkerMessageEvents
.START_WORKER_ELEMENT
) {
29 startChargingStation(message
.data
);
35 * Create and start a charging station instance
37 * @param data workerData
39 function startChargingStation(data
: ChargingStationWorkerData
): void {
40 const station
= new ChargingStation(data
.index
, data
.templateFile
);