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