KukaTcpCommunication.cs
2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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);
}
}
}
}