TcpClientCommunication.cs 2.85 KB
using DataAcquisition.Models;
using HHECS.BllModel;
using System.Net.Sockets;
using System.Text;

namespace DataAcquisition.Common.Communications
{
    public class TcpClientCommunication : ICommunication
    {
        public int CommunicationId { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public string IpAddress => _ipAddress;

        protected TcpClient tcpClient = new();

        protected string _ipAddress = null!;

        protected int _port;

        protected byte[] _data = new byte[1024 * 8];

        protected TcpClientCommunication() { }

        public TcpClientCommunication(int communicationId, string ip, int port) : this()
        {
            CommunicationId = communicationId;
            _ipAddress = ip;
            _port = port;
        }

        public BllResult ConnectClose()
        {
            try
            {
                tcpClient.Close();
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        public BllResult ConnectServer()
        {
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(_ipAddress, _port);
                Task.Run(async () =>
                {
                    while (tcpClient.Connected)
                    {
                        try
                        {

                            var stream = tcpClient.GetStream();
                            var buffer = new byte[_data.Length];
                            stream.Read(buffer);
                            var bufferString = Encoding.Default.GetString(buffer).TrimEnd('\0');
                            if (!string.IsNullOrWhiteSpace(bufferString))
                            {
                                _data = buffer;
                            }
                            await Task.Delay(100);
                        }
                        catch (Exception) { }
                    }
                });
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        public virtual BllResult Read(IEnumerable<EquipmentProperty> equipmentProperties)
        {
            throw new NotImplementedException();
        }

        public BllResult Read(EquipmentProperty equipmentProperty)
        {
            return Read([equipmentProperty]);
        }

        public virtual BllResult Write(IEnumerable<EquipmentProperty> equipmentProperties)
        {
            throw new NotImplementedException();
        }

        public BllResult Write(EquipmentProperty equipmentProperty)
        {
            return Write([equipmentProperty]);
        }
    }
}