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;
///
/// 网络接收线程
///
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 IpBuffer = new List();
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 = "";
///
/// 发送数据给AGV车辆
///
///
///
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)
{
}
}
}
///
/// 关闭通讯服务器连接
///
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;
}
///
/// 释放资源
///
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();
}
///
/// 打开通讯服务器连接端口
///
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()));
}
}
}