В этот класс; using System;
using System.Net;
using System.Threading.Tasks;
using DataType.ExternalSystems.Psy;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using TheRepresentationOfTheDateInPsycholophysiology.Models;
using TheRepresentationOfTheDateInPsycholophysiology.ViewModel;

namespace TheRepresentationOfTheDateInPsycholophysiology.Services
{
    public class PsyDataSenderReceiver
    {
        private static PsyDataSenderReceiver _instance;
        private static readonly object _lock = new object();

        private readonly UdpSendReceiveService<PilotMetrics, PilotMetrics> _udpSendReceiveService;
        private readonly DataTransferService _dataTransferService;

        private bool _isRunning;

        // Данные
        public PilotMetrics ReceivedOutputs;
        public PilotMetrics SendOutputs { get; private set; }

        public event Action<PilotMetrics> DataUpdated;

        AutONvertViewModel _autonvertDataCommands;

        public int FlagSwitch { get; set; }

        public PsyDataSenderReceiver(IPAddress ipAddress, int sendPort, int receivePort, DataTransferService dataTransferService)
        {
            _udpSendReceiveService = new UdpSendReceiveService<PilotMetrics, PilotMetrics>(ipAddress, sendPort, receivePort);
            
            //_autonvertDataCommands = serviceProvider.GetRequiredService<AutONvertViewModel>();
            _dataTransferService = dataTransferService;

            // Подписка на событие получения данных из сервиса
            _dataTransferService.DataReceived += OnDataReceived;

            SendOutputs = new PilotMetrics();
            ReceivedOutputs = InitPilotMetrics();
        }

        

        // Метод для получения экземпляра Singleton
        public static PsyDataSenderReceiver GetInstance(IPAddress ipAddress, int sendPort, int receivePort, DataTransferService dataTransferService)
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new PsyDataSenderReceiver(ipAddress, sendPort, receivePort, dataTransferService);
                    }
                }
            }
            return _instance;
        }

        // Старт работы
        public void Start()
        {
            _isRunning = true;
            _udpSendReceiveService.StartSending(); // Отправка данных через UDP
            Task.Run(() => SendLoop());
        }

        // Остановка работы
        public void Stop()
        {
            _isRunning = false;
            _udpSendReceiveService.StopSending();
        }

        // Цикл отправки данных через UDP
        private async Task SendLoop()
        {
            while (_isRunning)
            {
                try
                {
                    // Подготовка данных для отправки
                    SendOutputs = ReceivedOutputs;
                    _udpSendReceiveService.DataToSend = SendOutputs;

                    var tempOutputs = ReceivedOutputs;
                    // Модификация данных в зависимости от флага
                    if (FlagSwitch == 2)
                    {
                        MakeGoodOutputs(ref tempOutputs);
                        DataUpdated?.Invoke(ReceivedOutputs);
                    }
                    else if (FlagSwitch == 3)
                    {
                        MakeBadOutputs(ref tempOutputs);
                        DataUpdated?.Invoke(ReceivedOutputs);
                    }

                    ReceivedOutputs = tempOutputs;

                    await Task.Delay(100); // Задержка для предотвращения перегрузки
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Ошибка в цикле отправки: {ex.Message}");
                }
            }
        }

        // Обработка данных, полученных через DataTransferService
        private void OnDataReceived(string sourceName, string data)
        {
            try
            {
                // Предполагаем, что данные в формате JSON
                var receivedData = JsonConvert.DeserializeObject<PilotMetrics>(data);
                ReceivedOutputs = receivedData;

                // Уведомляем подписчиков о получении новых данных
                SendLoop();
                DataUpdated?.Invoke(ReceivedOutputs);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Ошибка при десериализации данных из {sourceName}: {ex.Message}");
            }
        }


        // Формирование "хороших" данных
        private void MakeGoodOutputs(ref PilotMetrics outputs)
        {
            outputs.HR = 75;
            outputs.EEGLastPoint = 0.35f;
            outputs.PhysiologicalState = 0;
            outputs.PsychophysiologicalState = 0;
        }

        // Формирование "плохих" данных
        private void MakeBadOutputs(ref PilotMetrics outputs)
        {
            outputs.HR = 0;
            outputs.EEGLastPoint = 0f;
            outputs.PhysiologicalState = 1;
            outputs.PsychophysiologicalState = 1;
        }

        public PilotMetrics InitPilotMetrics()
        {
            var outputs = new PilotMetrics
            {
                Source = string.Empty,
                Timestamp = 0,
                Version = 1,
                IsECGValid = false,
                HR = 0,
                RR = 0,
                BR = 0,
                SI = 0f,
                CardiovascularCenterState = 0,
                IsEEGValid = false,
                EEGFrequencyInterval = 0,
                EEGLastPoint = 0f,
                SpectrumPower = new float[0],
                AlertnessLevel = 0,
                AudioEngagement = 0f,
                CognitivePerformanceIndex = 0f,
                IsGDAValid = false,
                IsEyesClosed = false,
                PhysiologicalState = 0,
                PsychophysiologicalState = 0,
                IsNotInCabin = false
            };

            return outputs;
        }
    }
}








Положи функционал этого класса; [using Newtonsoft.Json;
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TheRepresentationOfTheDateInPsycholophysiology.Services
{
    public class UdpSendReceiveService<TSend, TReceive> : IDisposable
    {
        public event Action<TReceive> OnReceived;

        private readonly UdpClient udpClient;
        private CancellationTokenSource cancellationTokenSource;

        private readonly JsonConverterService<TSend> jsonConverterSend;
        private readonly JsonConverterService<TReceive> jsonConverterReceive;

        private readonly IPAddress ipAddress;
        private readonly int sendPort;
        private readonly int receivePort;
        private bool isRunning = false;

        public TSend DataToSend { get; set; }

        public UdpSendReceiveService(IPAddress ipAddress, int sendPort, int receivePort)
        {
            this.ipAddress = ipAddress;
            this.sendPort = sendPort;
            this.receivePort = receivePort;

            this.udpClient = new UdpClient(receivePort);
            this.cancellationTokenSource = new CancellationTokenSource();

            this.jsonConverterSend = new JsonConverterService<TSend>();
            this.jsonConverterReceive = new JsonConverterService<TReceive>();
        }

        public void Dispose() => Disconnect();

        private void Disconnect()
        {
            cancellationTokenSource?.Cancel();
            udpClient?.Close();
        }

        public void StartSending()
        {
            isRunning = true;
            Task.Run(() => SendLoop());
        }

        private async Task SendLoop()
        {
            using (var udpSender = new UdpClient())
            {
                IPEndPoint endPoint = new IPEndPoint(ipAddress, sendPort);

                while (isRunning)
                {
                    string message = jsonConverterSend.Serialize(DataToSend);
                    byte[] data = Encoding.UTF8.GetBytes(message);

                    await udpSender.SendAsync(data, data.Length, endPoint);
                    await Task.Delay(30);
                }
            }
        }

        public void StopSending()
        {
            isRunning = false;
        }
    }

    public class JsonConverterService<T>
    {
        public string Serialize(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        public T Deserialize(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}
]