Storage: use worker threads message passing to store performance records from
[e-mobility-charging-stations-simulator.git] / src / charging-station / StationWorker.ts
CommitLineData
c8eeb62b
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
81797102 3import { StationWorkerData, WorkerEvents, WorkerMessage } from '../types/Worker';
74bbc59b 4import { parentPort, workerData } from 'worker_threads';
3f40bc9c 5
6af9012e 6import ChargingStation from './ChargingStation';
a4624c96
JB
7import Constants from '../utils/Constants';
8import { ThreadWorker } from 'poolifier';
6013bc53 9import Utils from '../utils/Utils';
7dde0b73 10
b8da29bc 11// Conditionally export ThreadWorker instance for pool usage
56a74dae 12export let threadWorker: ThreadWorker;
b8da29bc 13if (Utils.workerPoolInUse()) {
b0317ac7 14 threadWorker = new ThreadWorker<StationWorkerData>(startChargingStation, { maxInactiveTime: Constants.WORKER_POOL_MAX_INACTIVE_TIME, async: false });
74bbc59b 15} else {
56a74dae
JB
16 // Add message listener to start charging station from main thread
17 addMessageListener();
6013bc53
JB
18 if (!Utils.isUndefined(workerData)) {
19 startChargingStation({ index: workerData.index as number, templateFile: workerData.templateFile as string });
20 }
3d2ff9e4
J
21}
22
3340259a 23/**
6f09a43f 24 * Listen messages send by the main thread
3340259a 25 */
56a74dae 26function addMessageListener(): void {
81797102 27 parentPort?.on('message', (message: WorkerMessage) => {
3e1416d8 28 if (message.id === WorkerEvents.START_WORKER_ELEMENT) {
81797102 29 startChargingStation(message.data);
3d2ff9e4
J
30 }
31 });
32}
33
3340259a 34/**
6f09a43f
JB
35 * Create and start a charging station instance
36 *
81797102 37 * @param data workerData
3340259a 38 */
abbd09af 39function startChargingStation(data: StationWorkerData): void {
8bbe7426 40 const station = new ChargingStation(data.index, data.templateFile);
3d2ff9e4 41 station.start();
7dde0b73 42}