123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
- using System.Threading;
- using System.Text.RegularExpressions;
- using System.Xml;
- using System.IO;
- using AGV_WPF_Global;
- namespace Services
- {
- public class UdpCommunication : CommunicationBase
- {
- private string localIP;
- byte[] buf_traffic = { 0x10, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x03 };
- private string str1061 = "";
- public string LocalIP
- {
- get
- {
- if (string.IsNullOrEmpty(localIP))
- {
- return Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
- }
- return localIP;
- }
- set
- {
- string str = @"^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$";
- if (Regex.IsMatch(value, str))
- {
- localIP = value;
- }
- else
- {
- throw new Exception("IP地址格式错误");
- }
- }
- }
- private int port;
- public int Port
- {
- get
- {
- if (port <= 0)
- return 10000;
- return port;
- }
- set { port = value; }
- }
- private int scanTime;
- public int ScanTime
- {
- get
- {
- if (scanTime <= 0)
- return 10;
- return scanTime;
- }
- set { scanTime = value; }
- }
- public override object GetTag()
- {
- return this;
- }
- private UdpClient udpServer;
- private Thread thread;
- public UdpCommunication(string ip, int port, int scanTime = 0)
- {
- LocalIP = ip;
- Port = port;
- ScanTime = scanTime;
- //InitIPConfig();
- IsOpen = false;
- str1061 = ByteToHexString(buf_traffic);
- }
- AutoResetEvent done = new AutoResetEvent(true);
- public static string ByteToHexString(byte[] buffer)
- {
- StringBuilder builder = new StringBuilder(buffer.Length * 3);
- foreach (byte data in buffer)
- {
- builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
- }
- return builder.ToString().ToUpper();
- }
- bool isChange = false;
- /// <summary>
- /// 网络接收线程
- /// </summary>
- private void ReceiveThread()
- {
- IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
- //开始循环监听
- while (true)
- {
- if (IsOpen && udpServer != null)
- {
- ReceivedEventArgs e = new ReceivedEventArgs();
- try
- {
- // e.buffer = udpServer.Receive(ref remotePoint);//接收数据
- var resultAny = udpServer.BeginReceive(null, null);
- e.buffer = udpServer.EndReceive(resultAny, ref remotePoint);
- e.type = "UDP";
- if (isChange)
- {
- Console.ForegroundColor = ConsoleColor.Yellow;
- isChange = false;
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Green;
- isChange = true;
- }
- if (remotePoint.Address.ToString() != LocalIP)//如果为本机IP,则不触发接收事件
- {
- //if(e.buffer.Count()>=10)
- //{
- if (e.buffer!=null&&ByteToHexString(e.buffer) != str1061&&e.buffer.Length>10)
- {
-
- base.OnReceivedEvent(remotePoint, e);
-
- }
- }
- }
- catch (System.Exception ex)
- {
-
- }
- }
- }
- }
- private List<string> IpBuffer = new List<string>();
- private static object portLock = new object();
- private static object portLock2 = new object();
- void WriteFile(string fileName, string context)
- {
- try
- {
- lock (portLock)
- {
- DateTime time = DateTime.Now;
- //MessageBox.Show("线程异常:"+e.ExceptionObject);
- FileStream stream = File.Open(@"Exception\" + fileName + ".txt", FileMode.Append, FileAccess.Write);
- StreamWriter writer = new StreamWriter(stream);
- {
- string msg = string.Format("[{0}]Test:\r\nMessage:{1}\r\n", time.ToString("yyyy-MM-dd HH:mm:ss"), context);
- writer.WriteLine(msg);
- writer.Close();
- stream.Close();
- }
- }
- }
- catch (Exception)
- {
- }
- }
- string Str1063 = "";
- /// <summary>
- /// 发送数据给AGV车辆
- /// </summary>
- /// <param name="buffer"></param>
- /// <param name="o"></param>
- public override void SendData(byte[] buffer, object o)
- {
- IPEndPoint ip = o as IPEndPoint;
- if (ip == null)
- {
- string ipStr = LocalIP.Substring(0, LocalIP.LastIndexOf('.') + 1);
- try
- {
- if (IsOpen && buffer != null && buffer.Length > 0)
- {
- //string msg = string.Format("[{0,-15}:{1} {2}]发送:{3}", LocalIP, Port, DateTime.Now.ToString("HH:mm:ss.fff"), ByteToHexString(buffer));
- //Console.WriteLine(msg);
- // lock (portLock2)
- {
- if (buffer[0] == 0x10 && (buffer[1] == 0x61 || buffer[1] == 0x63))
- {
- if (GlobalPara.Gloal1063Flag)
- {
- if (Str1063 != UdpCommunication.ByteToHexString(buffer))
- {
- Str1063 = UdpCommunication.ByteToHexString(buffer);
- WriteFile("1061发送记录-" + DateTime.Now.ToString("yyyy-MM-dd"), Str1063);
- }
- }
- }
- {
- // udpServer.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(ipStr + "255"), Port));
- }
- }
- foreach (var ipstr in IpBuffer)
- {
- if (IPCheck(ipstr))
- {
- udpServer.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(ipstr), Port));
- }
- }
- Thread.Sleep(20);
- }
- }
- catch (System.Exception ex)
- {
- }
- }
- else
- {
- try
- {
- if (IsOpen)
- {
- Console.WriteLine(string.Format("[{0,-15}:{1} {2}]发送:{3}", LocalIP, Port, DateTime.Now.ToString("HH:mm:ss"), ByteToHexString(buffer)));
- udpServer.Send(buffer, buffer.Length, new IPEndPoint(ip.Address, Port));
- }
- }
- catch (System.Exception ex)
- {
- }
- }
- }
- /// <summary>
- /// 关闭通讯服务器连接
- /// </summary>
- public override void Close()
- {
- if (udpServer != null)
- {
- udpServer.Close();
- udpServer = null;
- }
- if (thread != null && thread.ThreadState != ThreadState.Stopped)
- {
- if (done.WaitOne(500))
- {
- //thread.Resume();
- thread.Abort();
- }
- thread = null;
- }
- IsOpen = false;
- }
- /// <summary>
- /// 释放资源
- /// </summary>
- public override void Dispose()
- {
- if (udpServer != null)
- udpServer.Close();
- if (thread != null && thread.ThreadState != ThreadState.Stopped)
- {
- if (done.WaitOne(500))
- {
- thread.Abort();
- }
- thread.Abort();
- thread = null;
- }
- base.Dispose();
- }
- /// <summary>
- /// 打开通讯服务器连接端口
- /// </summary>
- public override void Open()
- {
- if (thread != null && udpServer != null)
- {
- if (thread.ThreadState == ThreadState.Suspended)
- {
- thread.Resume();
- }
- else if (thread.ThreadState == ThreadState.Unstarted)
- {
- thread.Start();
- }
- }
- else
- {
- IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName());
- for (int i = 0; i < address.Count(); i++)
- {
- if (address[i].AddressFamily.ToString().ToLower() == "internetwork" && address[i].ToString() == LocalIP)
- {
- udpServer = new UdpClient(new IPEndPoint(IPAddress.Parse(LocalIP), Port));
- udpServer.Client.ReceiveTimeout = 500;
- udpServer.Client.SendTimeout = 500;
- thread = new Thread(ReceiveThread);
- thread.IsBackground = true;
- thread.Start();
- break;
- }
- else if (i == address.Count() - 1)
- {
- //MessageBox.Show("IP地址不存在");
- //throw new Exception("UDP中IP地址不存在");
- Console.WriteLine("UDP中IP地址不存在");
- return;
- }
- }
- }
- IsOpen = true;
- InitIPConfig();
- }
- private void InitIPConfig()
- {
- XmlDocument xmlDoc = new XmlDocument();
- xmlDoc.Load("IPAddress.xml");
- XmlNode xn = xmlDoc.SelectSingleNode("AGVS");//根节点
- XmlNodeList nodeList = xn.ChildNodes;//根节点下面的子节点
- foreach (XmlNode xnf in nodeList)//遍历所有子节点
- {
- XmlElement xe = (XmlElement)xnf;
- string AgvId = xe.ChildNodes[0].InnerText;//agv编号
- XmlNodeList ipList = xe.ChildNodes[1].ChildNodes;
- foreach (XmlNode ip in ipList)
- {
- XmlElement ipxe = (XmlElement)ip;
- string ipStr = ip.InnerText;//IP地址
- if (IPCheck(ipStr))
- {
- if (!IpBuffer.Contains(ipStr))
- {
- IpBuffer.Add(ipStr);
- }
- }
- }
- }
- }
- public bool IPCheck(string ipAddress)
- {
- if (string.IsNullOrEmpty(ipAddress))
- return false;
- Regex validipregex = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
- return (ipAddress != "" && validipregex.IsMatch(ipAddress.Trim()));
- }
- }
- }
|