KukaTcpCommunication.cs 2.17 KB
using HHECS.BllModel;
using System.Text;
using System.Xml;

namespace HHECS.DAQClient.Communications
{
    public class KukaTcpCommunication : TcpClientCommunication
    {
        public KukaTcpCommunication(int communicationId, string ip, int port) : base(communicationId, ip, port)
        {
        }

        public override BllResult Read(IEnumerable<DataItem> dataItems)
        {
            try
            {
                var stream = tcpClient.GetStream();
                stream.Write(Encoding.Default.GetBytes($"<Ext><Msg>{Guid.NewGuid().ToString("N")[..8]}</Msg></Ext>"));

                var buffer = new byte[8192];
                stream.Read(buffer);
                var bufferString = Encoding.Default.GetString(buffer).TrimEnd('\0');
                if (!string.IsNullOrWhiteSpace(bufferString))
                {
                    var xml = new XmlDocument();
                    xml.LoadXml(bufferString);
                    foreach (var property in dataItems)
                    {
                        property.Value = xml.DocumentElement?.SelectSingleNode(property.Code)?.InnerText ?? string.Empty;
                    }
                }
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        public override BllResult Write(IEnumerable<DataItem> dataItems)
        {
            try
            {
                var xml = new XmlDocument();
                var robot = xml.CreateElement("Robot");
                foreach (var property in dataItems)
                {
                    var element = xml.CreateElement(property.Code);
                    element.InnerText = property.Value ?? string.Empty;
                    robot.AppendChild(element);
                }
                xml.AppendChild(robot);
                var stream = tcpClient.GetStream();
                stream.Write(Encoding.Default.GetBytes(xml.InnerXml));
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }
    }
}