Commit | Line | Data |
---|---|---|
edd13439 | 1 | // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. |
c8eeb62b | 2 | |
6b57eb9a | 3 | import { parentPort } from 'node:worker_threads'; |
8114d10e JB |
4 | |
5 | import { ThreadWorker } from 'poolifier'; | |
6 | ||
a6ef1ece JB |
7 | import { ChargingStation } from './ChargingStation.js'; |
8 | import { BaseError } from '../exception/index.js'; | |
9 | import type { ChargingStationWorkerData } from '../types/index.js'; | |
10 | import { Configuration } from '../utils/index.js'; | |
11 | import { type WorkerMessage, WorkerMessageEvents } from '../worker/index.js'; | |
11353865 | 12 | |
e8a92d57 | 13 | /** |
361c98f5 | 14 | * Creates and starts a charging station instance |
e8a92d57 | 15 | * |
d769e04a | 16 | * @param data - data sent to worker |
e8a92d57 | 17 | */ |
a37fc6dc JB |
18 | const startChargingStation = (data?: ChargingStationWorkerData): void => { |
19 | new ChargingStation(data!.index, data!.templateFile).start(); | |
e8a92d57 JB |
20 | }; |
21 | ||
ca0da0da | 22 | class ChargingStationWorker<Data extends ChargingStationWorkerData> { |
6b57eb9a | 23 | constructor() { |
6b57eb9a | 24 | // Add message listener to create and start charging station from the main thread |
d769e04a | 25 | parentPort?.on('message', (message: WorkerMessage<Data>) => { |
f93dda6a JB |
26 | switch (message.event) { |
27 | case WorkerMessageEvents.startWorkerElement: | |
28 | try { | |
ca0da0da | 29 | startChargingStation(message.data); |
f93dda6a JB |
30 | parentPort?.postMessage({ |
31 | event: WorkerMessageEvents.startedWorkerElement, | |
32 | }); | |
33 | } catch (error) { | |
34 | parentPort?.postMessage({ | |
35 | event: WorkerMessageEvents.startWorkerElementError, | |
36 | data: { | |
7cd4006c | 37 | name: (error as Error).name, |
f93dda6a JB |
38 | message: (error as Error).message, |
39 | stack: (error as Error).stack, | |
40 | }, | |
41 | }); | |
42 | } | |
43 | break; | |
44 | default: | |
a6080904 | 45 | throw new BaseError( |
f93dda6a JB |
46 | `Unknown worker event: '${message.event}' received with data: '${JSON.stringify( |
47 | message.data, | |
4ed03b6e | 48 | undefined, |
f93dda6a JB |
49 | 2, |
50 | )}'`, | |
2bb7a73e | 51 | ); |
6b57eb9a JB |
52 | } |
53 | }); | |
54 | } | |
6b57eb9a JB |
55 | } |
56 | ||
d769e04a JB |
57 | export let chargingStationWorker: |
58 | | ChargingStationWorker<ChargingStationWorkerData> | |
59 | | ThreadWorker<ChargingStationWorkerData>; | |
aa7d6d95 | 60 | if (Configuration.workerPoolInUse()) { |
bcbb76a6 | 61 | chargingStationWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation); |
74bbc59b | 62 | } else { |
d769e04a | 63 | chargingStationWorker = new ChargingStationWorker<ChargingStationWorkerData>(); |
3d2ff9e4 | 64 | } |