Fix a type casting
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
... / ...
CommitLineData
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3import {
4 ChargingStationWorkerData,
5 ChargingStationWorkerMessage,
6 ChargingStationWorkerMessageEvents,
7} from '../types/ChargingStationWorker';
8import { parentPort, workerData } from 'worker_threads';
9
10import ChargingStation from './ChargingStation';
11import { ThreadWorker } from 'poolifier';
12import Utils from '../utils/Utils';
13import WorkerConstants from '../worker/WorkerConstants';
14
15// Conditionally export ThreadWorker instance for pool usage
16export let threadWorker: ThreadWorker;
17if (Utils.workerPoolInUse()) {
18 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
19 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
20 async: false,
21 });
22} else {
23 // Add message listener to start charging station from main thread
24 addMessageListener();
25 if (!Utils.isUndefined(workerData)) {
26 startChargingStation({
27 index: (workerData as ChargingStationWorkerData).index,
28 templateFile: (workerData as ChargingStationWorkerData).templateFile,
29 });
30 }
31}
32
33/**
34 * Listen messages send by the main thread
35 */
36function addMessageListener(): void {
37 parentPort?.on('message', (message: ChargingStationWorkerMessage) => {
38 if (message.id === ChargingStationWorkerMessageEvents.START_WORKER_ELEMENT) {
39 startChargingStation(message.data);
40 }
41 });
42}
43
44/**
45 * Create and start a charging station instance
46 *
47 * @param data workerData
48 */
49function startChargingStation(data: ChargingStationWorkerData): void {
50 const station = new ChargingStation(data.index, data.templateFile);
51 station.start();
52}