using Community; using MahApps.Metro.Controls; using Model; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using DAL; using System.IO; namespace ViewModel { /// /// 通讯服务器管理逻辑类 /// public class CommunicationServerVM : NotificationObject { /// /// 系统软件ID /// int SoftID { get; set; } /// /// 自动获取端口号 /// public DelegateCommand GetPortCommand { get; set; } /// /// 添加 /// public DelegateCommand AddTCPIPCommand { get; set; } /// /// 删除 /// public DelegateCommand DeleteTCPIPCommand { get; set; } /// /// 保存TCPIP参数 /// public DelegateCommand SaveParCommand { get; set; } /// /// 发送信息方法 /// public DelegateCommand SendInfoCommand { get; set; } /// /// 连接监听套接字 /// public Socket SocketListen { get; set; } private ShowInfo showmsg; /// /// 监听连接状态 /// public ShowInfo Showmsg { get { return showmsg; } set { showmsg = value; this.RaisePropertyChanged("Showmsg"); } } #region 监听开关 private bool monitorsWitch; /// /// 监听开关 /// public bool MonitorsWitch { get { return monitorsWitch; } set { monitorsWitch = value; if (value) { // StartListen(); StartListen(); } else { EndListen(); } this.RaisePropertyChanged("MonitorsWitch"); } } #endregion #region TCPIP通讯连接参数 private TCPIPClass serverConn; /// /// TCPIP通讯连接参数 /// public TCPIPClass ServerConn { get { return serverConn; } set { serverConn = value; this.RaisePropertyChanged("ServerConn"); } } #endregion #region 已连接通讯对象集合 private ObservableCollection commList; /// /// 已连接对象集合 /// public ObservableCollection CommList { get { return commList; } set { commList = value; //this.RaisePropertyChanged("ConnectionClassList"); } } #endregion #region 当前选中的通讯对象 private CommunicationManagementClass selectComm; /// /// 当前选中的通讯对象 Text="{Binding SelectComm.ActionName}" IsEditable="True" /// public CommunicationManagementClass SelectComm { get { return selectComm; } set { selectComm = value; this.RaisePropertyChanged("SelectComm"); } } #endregion /// /// 生产喷码信息 /// public DelegateCommand GeneratePenmaDateCommand { get; set; } /// /// OCV仪器初始化归零 /// public DelegateCommand OCVInitializeZeroCommand { get; set; } /// /// OCV仪器状态查询 /// public DelegateCommand OCVStatusQueryCommand { get; set; } #region 构造函数 /// /// 构造函数 /// /// /// public CommunicationServerVM(string ip, int port) { //IP= GetIP(); //获取IP地址 因为无法获取指定网卡的IP 此处不用 ServerConn = new TCPIPClass(); ServerConn.IP = ip; ServerConn.Port = port; //端口号随便来 Showmsg = new ShowInfo(); CommList = new ObservableCollection(); } MainWindowDAL dal = new MainWindowDAL(); /// /// 程序主线程队列 用于异步属性界面 /// Dispatcher MyDispatcher { get; set; } /// /// 构造函数重载 /// /// 系统软件ID /// 窗体对象,用于动态添加项 public CommunicationServerVM(int softID, Dispatcher dp) { MyDispatcher = dp; PLCConn = new CommunicationManagementClass(); FrontStation = new CommunicationManagementClass(); SoftID = softID; ServerConn = dal.GetTCPIPServer(SoftID);//new TCPIPClass(); CommList = dal.GetCommClientList1(SoftID); if (CommList.Count > 0) { CommList.Insert(0, new CommunicationManagementClass() { ActionName = " ", ID = -1 }); SelectComm = CommList[1]; } Showmsg = new ShowInfo(); GetPortCommand = new DelegateCommand(); GetPortCommand.ExecuteAction = new Action(GetPort); SaveParCommand = new DelegateCommand(); SaveParCommand.ExecuteAction = new Action(SavePar); SendInfoCommand = new DelegateCommand(); SendInfoCommand.ExecuteAction = new Action(SendInfo); AddTCPIPCommand = new DelegateCommand(); AddTCPIPCommand.ExecuteAction = new Action(AddTCPIP); DeleteTCPIPCommand = new DelegateCommand(); DeleteTCPIPCommand.ExecuteAction = new Action(DeleteTCPIP); GeneratePenmaDateCommand = new DelegateCommand(); GeneratePenmaDateCommand.ExecuteAction = new Action(GeneratePenmaDate); OCVInitializeZeroCommand = new DelegateCommand(); OCVInitializeZeroCommand.ExecuteAction = new Action(OCVInitializeZero); OCVStatusQueryCommand = new DelegateCommand(); OCVStatusQueryCommand.ExecuteAction = new Action(OCVStatusQuery); } /// /// 删除TCPIP /// /// private void DeleteTCPIP(object obj) { if (SelectComm == null || SelectComm.ID < 0) { return; } if (SelectComm.ID > 0) { if (dal.DelectTcpIP(SelectComm.ID) <= 0) { MyMessageBox.Show("删除失败"); } else { CommList.Remove(SelectComm); } } else { CommList.Remove(SelectComm); } } private void AddTCPIP(object obj) { CommunicationManagementClass cmc = new CommunicationManagementClass() { SoftID = this.SoftID, ActionName = "新来的", InServer = false, IP = "127.0.0.1" }; CommList.Add(cmc); SelectComm = cmc; } #endregion #region 1、获取本地IP string GetIP() /// /// 获取本地IP /// /// private string GetIP() //获取本地IP { string ip = string.Empty; foreach (IPAddress ipadd in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (ipadd.AddressFamily.ToString() == "InterNetwork") { ip = ipadd.ToString(); break; } } return ip; } #endregion #region 2、获取可使用端口 int GetPort() /// /// 获取可使用端口 /// /// private void GetPort(object obj) { int max_port = 65535; //系统tcp/udp端口数最大是65535 int begin_port = 5000;//从这个端口开始检测 int port = 0; for (int i = begin_port; i < max_port; i++) { if (PortIsAvailable(i)) { port = i; break; } } ServerConn.Port = port; } /// /// 检查指定端是否已占用 /// /// /// private static bool PortIsAvailable(int port) { bool isAvailable = true; IList portUsed = PortIsUsed(); foreach (int p in portUsed) { if (p == port) { isAvailable = false; break; } } return isAvailable; } /// /// 获取操作系统已用的端口号 /// /// public static IList PortIsUsed() { //获取本地计算机的网络连接和通信统计数据的信息 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); //返回本地计算机上的所有Tcp监听程序 IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners(); //返回本地计算机上的所有UDP监听程序 IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners(); //返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); IList allPorts = new ArrayList(); foreach (IPEndPoint ep in ipsTCP) allPorts.Add(ep.Port); foreach (IPEndPoint ep in ipsUDP) allPorts.Add(ep.Port); foreach (TcpConnectionInformation conn in tcpConnInfoArray) allPorts.Add(conn.LocalEndPoint.Port); return allPorts; } #endregion #region 3、循环接受客户端连接的方法 #region 临时通讯对象 /// /// 临时通讯对象 /// public CommunicationManagementClass TempConn { get; set; } #endregion #region 各通讯连接对象 #region PLC连接 private CommunicationManagementClass pLCConn; /// /// PLC连接 /// public CommunicationManagementClass PLCConn { get { return pLCConn; } set { pLCConn = value; this.RaisePropertyChanged("PLCConn"); } } #endregion #region 测试站PC连接1 private CommunicationManagementClass frontStation; /// /// 上一站连接 /// public CommunicationManagementClass FrontStation { get { return frontStation; } set { frontStation = value; this.RaisePropertyChanged("FrontStation"); } } #endregion #endregion #region 1、开启监听 /// /// 开启监听 /// private void StartListen() { try { SocketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); SocketListen.Bind(new IPEndPoint(IPAddress.Parse(ServerConn.IP), ServerConn.Port)); SocketListen.Listen(10);//同时连接的最大连接数 SocketListen.BeginAccept(new AsyncCallback(ClientAccepted), SocketListen);//获取连接 Showmsg.StatuInfo = "通讯服务正常"; Showmsg.StatusBackground = ColorStr.Green; Showmsg.StatusForeground = ColorStr.White; } catch (Exception ex) { Showmsg.StatuInfo = ex.Message; Showmsg.StatusBackground = ColorStr.Red; Showmsg.StatusForeground = ColorStr.White; if (SocketListen != null) { SocketListen.Close(); SocketListen.Dispose(); } } } #endregion #region 2、异步连接回调 获取请求Socket /// /// 接收到的字节 /// byte[] buffer = new byte[1024 * 1024 * 1]; /// /// 异步连接回调 获取请求Socket /// /// 请求的Socket private void ClientAccepted(IAsyncResult ar) { try { //获取连接Socket 创建新的连接 Socket myServer = ar.AsyncState as Socket; Socket client = myServer.EndAccept(ar); IPAddress ip = ((System.Net.IPEndPoint)client.RemoteEndPoint).Address; int ports = ((System.Net.IPEndPoint)client.RemoteEndPoint).Port; string ClientName = ""; ClientName = ip.ToString(); if (!string.IsNullOrEmpty(ClientName)) { //CommunicationManagementClass cmc = CommList.Where(w => w.IP == ip.ToString()).FirstOrDefault(); //if(cmc!=null) //{ // ClientName = cmc.ActionName; //} if (!RestartConn(ClientName, client, ClientName, ports)) { TempConn = new CommunicationManagementClass(client, ClientName, ClientName); //异步新增项 这是微软的BUG 只能这么麻烦了 MyDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn); //这样写也可以 MyMessageBox.MetroWin.Dispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn); SelectComm = TempConn; } } else { //异步识别验证连接者身份验证 client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client); } //异步识别验证连接者身份验证 // client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client); myServer.BeginAccept(new AsyncCallback(ClientAccepted), myServer);//等待下一个连接 } catch (Exception ex) { Showmsg.StatuInfo = ex.Message; Showmsg.StatusBackground = ColorStr.Red; Showmsg.StatusForeground = ColorStr.White; } } #endregion #region 3、数据接收 进行身份识别 /// /// 数据接收 进行身份识别 /// /// 请求的Socket private void ReadCallback(IAsyncResult ar) { Socket c_socket = ar.AsyncState as Socket; #region 这里是特殊情况 用IP地址来识别身份 IPAddress ip = ((System.Net.IPEndPoint)c_socket.RemoteEndPoint).Address; string ClientName = ""; switch (ip.ToString()) { case "192.168.20.1": //ClientName = "C1"; break; case "192.168.3.10": //ClientName = "PL"; break; default: try { int length = c_socket.EndReceive(ar); ClientName = Encoding.UTF8.GetString(buffer, 0, length); } catch (Exception) { } break; } if (!RestartConn(ClientName, c_socket)) { switch (ClientName) { case "PL": TempConn = new CommunicationManagementClass(c_socket, ClientName, "PLC连接"); //异步新增项 这是微软的BUG 只能这么麻烦了 MyDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn); SelectComm = TempConn; PLCConn = TempConn; break; case "SL": TempConn = new CommunicationManagementClass(c_socket, ClientName, "上一站"); //异步新增项 这是微软的BUG 只能这么麻烦了 MyDispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), TempConn); FrontStation = TempConn; SelectComm = TempConn; break; } } #endregion } void AddItem(object info) { CommList.Add((CommunicationManagementClass)info); } #endregion #region 4、查看是否已连接,如果已连接 就重启接收信息 /// /// 查看是否已连接,如果已连接 就重启接收信息 /// /// 用户对象 /// public bool RestartConn(string userName, Socket currSocket, string nameStr = "", int ports = 0) { bool CheckConnAre = false; if (CommList == null || CommList.Count <= 0) { return CheckConnAre; } foreach (CommunicationManagementClass cl in CommList) { // if (cl.ShortCode == userName||cl.IP== userName) if (cl.ShortCode == userName || (cl.PortDis && cl.IP == userName && cl.Port == ports) || (cl.IP == userName && !cl.PortDis)) { CheckConnAre = true; //重新开启此连接 cl.ConnSocket = currSocket; //替换新的通信套接字 cl.OpenReceivesMassage(); cl.Names = string.IsNullOrEmpty(cl.ActionName) ? nameStr : cl.ActionName;//cl.TempName; cl.Showmsg.StatuInfo = "连接正常"; cl.Showmsg.StatusBackground = ColorStr.Green; cl.Showmsg.StatusForeground = ColorStr.White; SelectComm = cl; break; } } return CheckConnAre; } #endregion #endregion #region 4、关闭连接 /// /// 关闭连接 /// public void EndListen() { try { SocketListen.Close(); SocketListen.Dispose(); Showmsg.StatuInfo = "未启动"; Showmsg.StatusBackground = ColorStr.Red; Showmsg.StatusForeground = ColorStr.White; } catch (Exception) { } } #endregion #region 5、更新TCPIP参数 /// /// 5、更新TCPIP参数 /// /// private void SavePar(object obj) { if (dal.TCPUpdata(this.ServerConn) <= 0) { MyMessageBox.Show("服务器参数保存失败"); } if (SelectComm != null && SelectComm.ID >= 0) { if (dal.SaveTCPIPPar(SelectComm) > 0) { MyMessageBox.Show("保存成功"); } else { MyMessageBox.Show("保存失败"); } } } #endregion /// /// 发送信息 /// public void SendInfo(object obj) { if (SelectComm != null) { SelectComm.SendInfo(SelectComm.SendStr); } } #region IP地址格式验证 /// /// IP地址格式验证1 /// /// /// public bool IPCheck(string IPstr) { bool blnTest = false; bool Result = true; Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$"); blnTest = regex.IsMatch(IPstr); if (blnTest == true) { string[] strTemp = IPstr.Split(new char[] { '.' }); // textBox1.Text.Split(new char[] { '.' }); for (int i = 0; i < strTemp.Length; i++) { if (Convert.ToInt32(strTemp[i]) > 255) { //大于255则提示,不符合IP格式 MessageBox.Show("不符合IP格式"); Result = false; } } } else { //输入非数字则提示,不符合IP格式 MessageBox.Show("不符合IP格式"); Result = false; } return Result; } /// /// IP地址格式验证2 /// /// /// private bool isIP(String IpStr) { bool IsIpResult = false; try { IPAddress ipAd = IPAddress.Parse(IpStr); IsIpResult = true; } catch { IsIpResult = false; } return IsIpResult; } #endregion /// /// 查询OCV仪器状态 /// /// private void OCVStatusQuery(object obj) { if (SelectComm == null && ZeroBl) { return; } if (ZeroTime.AddSeconds(10) < DateTime.Now) { SelectComm.SendStr = ":ADJ?\r\n"; SendInfo(0); } else { MyMessageBox.Show("归零操作之后请间隔10秒以上再进行状态查询"); } } /// /// 归零时间 归零操作之后要间隔10秒才能查询状态 /// DateTime ZeroTime { get; set; } /// /// 是否进行了归零操作 /// bool ZeroBl { get; set; } /// /// OCV仪器初始化归零 /// /// private void OCVInitializeZero(object obj) { if (SelectComm != null) { SelectComm.SendStr = ":ADJ:CLEA\r\n"; SendInfo(0); ZeroTime = DateTime.Now; ZeroBl = true; } } #region 喷码信息 private string rowStr1; /// /// 喷码信息的第一行 /// public string RowStr1 { get { return rowStr1; } set { rowStr1 = value; RaisePropertyChanged("RowStr1"); } } private string rowStr2; /// /// 喷码信息的第二行 /// public string RowStr2 { get { return rowStr2; } set { rowStr2 = value; RaisePropertyChanged("RowStr2"); } } private string rowStr3; /// /// 喷码信息的第3行 /// public string RowStr3 { get { return rowStr3; } set { rowStr3 = value; RaisePropertyChanged("RowStr3"); } } private string rowStr4; /// /// 喷码信息的第4行 /// public string RowStr4 { get { return rowStr4; } set { rowStr4 = value; RaisePropertyChanged("RowStr4"); } } private string rowStr5; /// /// 喷码信息的第5行 /// public string RowStr5 { get { return rowStr5; } set { rowStr5 = value; RaisePropertyChanged("RowStr5"); } } private string rowStr6; /// /// 喷码信息的第6行 /// public string RowStr6 { get { return rowStr6; } set { rowStr6 = value; RaisePropertyChanged("RowStr6"); } } private string rowStr7; /// /// 喷码信息的第7行 /// public string RowStr7 { get { return rowStr7; } set { rowStr7 = value; RaisePropertyChanged("RowStr7"); } } #endregion /// /// 生产喷码信息 /// /// private void GeneratePenmaDate(object obj) { if (SelectComm != null) { List list = new List(); //if (!string.IsNullOrEmpty(RowStr1)) //{ // list.Add(RowStr1); //} //if (!string.IsNullOrEmpty(RowStr2)) //{ // list.Add(RowStr2); //} //if (!string.IsNullOrEmpty(RowStr3)) //{ // list.Add(RowStr3); //} //if (!string.IsNullOrEmpty(RowStr4)) //{ // list.Add(RowStr4); //} //if (!string.IsNullOrEmpty(RowStr5)) //{ // list.Add(RowStr5); //} //if (!string.IsNullOrEmpty(RowStr6)) //{ // list.Add(RowStr6); //} //if (!string.IsNullOrEmpty(RowStr7)) //{ // list.Add(RowStr7); //} if (!string.IsNullOrEmpty(RowStr1) && !string.IsNullOrEmpty(RowStr2) && !string.IsNullOrEmpty(RowStr3) && !string.IsNullOrEmpty(RowStr4) && !string.IsNullOrEmpty(RowStr5) && !string.IsNullOrEmpty(RowStr6) && !string.IsNullOrEmpty(RowStr7)) { string s1 = RowStr1 + " " + RowStr2 + " " + RowStr3 + " " + RowStr4; string s2 = RowStr5 + " " + RowStr6 + " " + RowStr7; if (!string.IsNullOrEmpty(s1)) { list.Add(s1); } if (!string.IsNullOrEmpty(s2)) { list.Add(s2); } } if (list.Count > 0) { SelectComm.SendStr = GetMarkingSendStr(list); } } else { MyMessageBox.Show("请选中对应的喷码机后重试"); } } #region 获取发送给喷码机的字符串 /// /// 获取发送给喷码机的字符串 /// /// /// public string GetMarkingSendStr(List strList) { //发送内容 string contentAll = ""; //序号 int xuhao = 1; foreach (var item in strList) { //每行喷码长度固定位50 不足50 用空格补满 string str = item.PadRight(50, ' '); //转字节数组 byte[] byt = Encoding.ASCII.GetBytes(str); //字节数量 4字节 string contenrStr = byt.Length.ToString("X4"); //需要发送的所有内容 格式:序号(2字节)+内容长度(4字节)+内容(2字节) contentAll = contentAll + xuhao.ToString("X2") + contenrStr + BitConverter.ToString(byt, 0).Replace("-", string.Empty).ToUpper(); xuhao++; } //内容的总长度(4字节) string Allcount = (contentAll.Length / 2).ToString("X4"); contentAll = "E8" + Allcount + contentAll; //最终的发送内容 识别码+内容总长度+内容+校验码 string Sendstr = contentAll + GetCheckCode(contentAll); return Sendstr;//Regex.Replace(allstr, @"(\w{2})", "$1 ").Trim(' '); } /// /// 获得校验码 (异或校验) /// public static string GetCheckCode(string str) { str = str.Replace(" ", ""); str = System.Text.RegularExpressions.Regex.Replace(str, @"(\w{2})", "$1 ").Trim(' '); List listste = str.Split(' ').ToList(); byte a = 0; foreach (string st in listste) { a ^= (byte)Convert.ToInt32(st, 16); } string rstr = Convert.ToString(a, 16).ToUpper(); return rstr; } #endregion } }