feat: add connector status handling at boot with evses configuration
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
c8eeb62b 2
01f4001e 3import { parentPort, workerData } from 'node:worker_threads';
8114d10e
JB
4
5import { ThreadWorker } from 'poolifier';
6
2896e06d 7import { ChargingStation, ChargingStationUtils } from './internal';
268a74bb 8import type { ChargingStationWorkerData } from '../types';
60a74391 9import { Utils } from '../utils';
268a74bb 10import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
7dde0b73 11
e8a92d57
JB
12/**
13 * Create and start a charging station instance
14 *
15 * @param data - workerData
16 */
17const startChargingStation = (data: ChargingStationWorkerData): void => {
18 const station = new ChargingStation(data.index, data.templateFile);
19 station.start();
20};
21
22/**
23 * Listen messages send by the main thread
24 */
25const addMessageListener = (): void => {
26 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
27 if (message.id === WorkerMessageEvents.startWorkerElement) {
28 startChargingStation(message.data);
29 }
30 });
31};
32
b8da29bc 33// Conditionally export ThreadWorker instance for pool usage
56a74dae 34export let threadWorker: ThreadWorker;
17ac262c 35if (ChargingStationUtils.workerPoolInUse()) {
e7aeea18 36 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
3fa0f0ed 37 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
e7aeea18
JB
38 async: false,
39 });
74bbc59b 40} else {
56a74dae
JB
41 // Add message listener to start charging station from main thread
42 addMessageListener();
48d17ce2 43 if (Utils.isUndefined(workerData) === false) {
6d6dc22e 44 startChargingStation(workerData as ChargingStationWorkerData);
6013bc53 45 }
3d2ff9e4 46}