1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
3 import { parentPort
, workerData
} from
'worker_threads';
5 import { ThreadWorker
} from
'poolifier';
8 ChargingStationWorkerData
,
9 ChargingStationWorkerMessage
,
10 ChargingStationWorkerMessageEvents
,
11 } from
'../types/ChargingStationWorker';
12 import Utils from
'../utils/Utils';
13 import WorkerConstants from
'../worker/WorkerConstants';
14 import ChargingStation from
'./ChargingStation';
15 import { ChargingStationUtils
} from
'./ChargingStationUtils';
17 // Conditionally export ThreadWorker instance for pool usage
18 export let threadWorker
: ThreadWorker
;
19 if (ChargingStationUtils
.workerPoolInUse()) {
20 threadWorker
= new ThreadWorker
<ChargingStationWorkerData
>(startChargingStation
, {
21 maxInactiveTime
: WorkerConstants
.POOL_MAX_INACTIVE_TIME
,
25 // Add message listener to start charging station from main thread
27 if (Utils
.isUndefined(workerData
) === false) {
28 startChargingStation(workerData
as ChargingStationWorkerData
);
33 * Listen messages send by the main thread
35 function addMessageListener(): void {
36 parentPort
?.on('message', (message
: ChargingStationWorkerMessage
<ChargingStationWorkerData
>) => {
37 if (message
.id
=== ChargingStationWorkerMessageEvents
.START_WORKER_ELEMENT
) {
38 startChargingStation(message
.data
);
44 * Create and start a charging station instance
46 * @param data workerData
48 function startChargingStation(data
: ChargingStationWorkerData
): void {
49 const station
= new ChargingStation(data
.index
, data
.templateFile
);