码迷,mamicode.com
首页 > 编程语言 > 详细

多线程

时间:2014-11-26 07:59:45      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:des   datagridview   style   blog   io   ar   color   os   sp   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WG3000_COMM.Core;
using System.Collections;
using WComm_UDP;
using System.IO;
using System.Xml;
using Frontier.VideoMonitor.Library.Configuration;
using Frontier.VideoMonitor.Library.Utils;
using Frontier.VideoMonitor.Packet.Base;
using Frontier.VideoMonitor.Packet.Model;
using Frontier.VideoMonitor.Packet.Receive.Xml;
using Frontier.VideoMonitor.Packet.Send.Xml;
using QIF.NewAFFZ.Client.Contact;
using QIF.NewAFFZ.Client.Contact.Common;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Threading; 

namespace DoorServer
{
    public partial class frmWatching : Form
    {
        
        /// <param name="packet">xml通信包</param>        
        private delegate void InvokeXmlProcess(XmlPacket packet);

        /// <summary>声明xml通信委托</summary>
        private OnResponseDelegate onResponse;

        /// <summary>声明线程处理委托</summary>
        private InvokeXmlProcess invoke;

        private DB2 database;

        private const string dsn = "DSN=OutBound";
        private const string conn = "Driver={IBM DB2 ODBC DRIVER};Database=AFFZDB;hostname=172.26.1.10;port=50000;protocol=TCPIP; uid=db2admin; pwd=qif";

        UDPTalkChannel.Client client;

        class HeartIP
        {
          public  string IP;
          public int nHeart;
        };

        private List<HeartIP> listIP = new List<HeartIP>();
       
        public struct controllerOld
        {
          public  long sn;
          public  string ip;
          public int port;

        };

        private List<controllerOld> ctrlOld = new List<controllerOld>();
 
        public frmWatching()
        {
            InitializeComponent();
        }

        static int receivedPktCount = 0;
        Queue QueRecText = new Queue(); 
        private void evtNewInfoCallBack(string text)
        {
           System.Diagnostics.Debug.WriteLine("Got text through callback! {0}", text);
            receivedPktCount++;
            lock (QueRecText.SyncRoot)
            {
                QueRecText.Enqueue(text);  //加入到文件中
            }
        }

        //选定要监控的控制表
        Dictionary<int, wgMjController> selectedControllers = new Dictionary<int, wgMjController>();

        WComm_Operate wudp;

        wgWatchingService watching; //实时监控服务
        wgMjController wgMjControllerWatching = null; //2011-11-15_23:50:42 要监控的控制器
        private void btnStart_Click(object sender, EventArgs e)
        {
            this.dgvControllers.RefreshEdit(); 
            if (this.dgvControllers.Rows.Count <= 0)
            {
                return;
            }
            this.btnStart.Enabled = false;
            if (watching == null)
            {
                watching = new wgWatchingService();  //加载监视服务
                watching.EventHandler += new OnEventHandler(evtNewInfoCallBack); //事件处理
            }

            if (wudp == null)
            {
                wudp = new WComm_Operate();
                wudp.minUDPWaitTimeout = 3000;
            }  

            this.timerUpdateDoorInfo.Enabled = false;  //停止刷新
            Cursor.Current = Cursors.WaitCursor; //2010-11-11 14:42:33 

            foreach (DataGridViewRow dgvr in this.dgvControllers.Rows )
            {
                if (dgvr.Cells["Ctrl_ID"].Value != null)
                {
                    int sn;
                    if (int.TryParse(dgvr.Cells["Ctrl_ID"].Value.ToString(), out  sn))
                    {

                        if (int.Parse(dgvr.Cells["Ctrl_ID"].Value.ToString()) > 100000)
                        {
                            wgMjControllerWatching = new wgMjController(); //Create New 
                            wgMjControllerWatching.ControllerSN = sn;
                            if (dgvr.Cells["IP"].Value != null)
                            {
                                wgMjControllerWatching.IP = dgvr.Cells["IP"].Value.ToString();
                            }
                            int port;
                            if (dgvr.Cells["Port"].Value != null)
                            {
                                if (int.TryParse(dgvr.Cells["Port"].Value.ToString(), out port))
                                {
                                    wgMjControllerWatching.PORT = port;
                                }
                            }
                            selectedControllers.Add(wgMjControllerWatching.ControllerSN, wgMjControllerWatching);
                        }
                        else
                        {
                            controllerOld ctrl = new controllerOld();
                            ctrl.sn = sn;
                            ctrl.ip = dgvr.Cells["IP"].Value.ToString();
                            ctrl.port = int.Parse(dgvr.Cells["Port"].Value.ToString());

                            ctrlOld.Add(ctrl);
                        }                  
                    }
                }
            }
            if (selectedControllers.Count > 0)
            {
               System.Diagnostics.Debug.WriteLine ("selectedControllers.Count=" + selectedControllers.Count.ToString());
                watching.WatchingController = selectedControllers;

                this.timerUpdateDoorInfo.Interval = 300; 
                this.timerUpdateDoorInfo.Enabled = true;
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("selectedControllers.Count=" + selectedControllers.Count.ToString());
                watching.WatchingController = null;
                this.timerUpdateDoorInfo.Enabled = false;
 
            }
            Cursor.Current = Cursors.Default; //2010-11-11 14:42:33 

            this.textBox1 .AppendText("\r\n监控已经开始!\r\n");
        }

        //用于定时更新门的信息  实时监控时
        private void timerUpdateDoorInfo_Tick(object sender, EventArgs e)
        {
            this.timerUpdateDoorInfo.Enabled = false;

            if (watching != null)
            {
                updateControllerStatus();
                if (QueRecText.Count > 0)
                {
                    this.Invoke(new txtInfoHaveNewInfo(txtInfoHaveNewInfoEntry)); //2010-8-1 09:09:12
                }
                Application.DoEvents();//2010-8-1 09:09:06 显示
                this.timerUpdateDoorInfo.Enabled = true; //2010-11-11 12:00:43 下次执行
            }

            if (wudp !=null  && ctrlOld.Count >0)
            {
                txtInfoUpdateEntryOld();
            }
        }

        /// <summary>
        /// 获取控制器信息并更新显示列表
        /// </summary>
        void updateControllerStatus()  
        {
            if (watching != null  &&  wudp != null)
            {
                foreach (DataGridViewRow dgvr in this.dgvControllers.Rows)
                {
                    if (dgvr.Cells["Ctrl_ID"].Value != null)
                    {
                        int sn;
                        if (int.TryParse(dgvr.Cells["Ctrl_ID"].Value.ToString(), out  sn))
                        {
                            if (sn > 100000)
                            {
                                wgMjControllerRunInformation conRunInfo = null;
                                int commStatus;
                                commStatus = watching.CheckControllerCommStatus(sn, ref conRunInfo);
                                if (commStatus == -1)
                                {
                                    ////实时监控 超过3秒后 仍未通信上, 则提示未连接
                                    dgvr.Cells["Status"].Value = "failed";
                                    dgvr.Cells["Time"].Value = "";
                                }
                                else if (commStatus == 1)
                                {
                                    dgvr.Cells["Status"].Value = "OK";
                                    dgvr.Cells["Time"].Value = conRunInfo.dtNow.ToString("yyyy-MM-dd HH:mm:ss");
                                }
                            }
                            else
                            {                               
                                string strTemp = String.Concat("8110", wudp.NumToStrHex(0, 2));            //表示第watchIndex个记录, 如果是0则取最新一条记录
                                string strCmd = wudp.CreateBstrCommand(sn, strTemp);                  //生成指令帧 
                                wudp.minUDPWaitTimeout = 3000;
                                string strFrame = wudp.udp_comm(strCmd, dgvr.Cells["IP"].Value.ToString(), int.Parse(dgvr.Cells["Port"].Value.ToString()));                        //发送指令, 并获取返回信息
                                wudp.minUDPWaitTimeout = 3000;
                                this.textBox1.AppendText("老门禁控制器读取刷卡状态:" + wudp.ErrCode.ToString() + "!\r\n");
                                if ((0 != wudp.ErrCode) || (strFrame.Length == 0))
                                {
                                    dgvr.Cells["Status"].Value = "false";
                                }
                                else
                                {
                                    RunInfo runInfo = null;
                                    string strIndex = WComm_Tools.numToHexString(0, 4);
                                    string command = wudp.CreateBstrCommand(sn, PKType.DC_GET_RUN_INFO + strIndex);
                                    string result = wudp.udp_comm(command, dgvr.Cells["IP"].Value.ToString(), int.Parse(dgvr.Cells["Port"].Value.ToString()));
                                    runInfo = new RunInfo();
                                    runInfo.CtrlSN = (uint)wudp.GetSNFromRunInfo(result);
                                    runInfo.CurrDateTime = wudp.GetClockTimeFromRunInfo(result);
                                    
                                    dgvr.Cells["Status"].Value = "OK";
                                    dgvr.Cells["Time"].Value = runInfo.CurrDateTime.ToString();                 
                                }
                            }
                      
                        }
                    }
                }
                this.dgvControllers.Refresh();
            }
        }

        private delegate void txtInfoHaveNewInfo();

        private delegate void txtInfoHaveNewInfold();

        private void txtInfoHaveNewInfoldEntry()
        {
        }

        static int dealingTxt = 0;
        static int infoRowsCount = 0;
        private void txtInfoHaveNewInfoEntry()
        {
            if (dealingTxt > 0)
            {
                return;
            }
            if (watching.WatchingController == null) //2010-8-1 08:27:15 没有选中监控的就退出
            {
                return;
            }
            System.Threading.Interlocked.Exchange(ref dealingTxt, 1);
            int dealt = 0;
            object obj;
            long startTicks = DateTime.Now.Ticks; // Date.Now.Ticks  ‘us
            long updateSpan = 2000 * 1000 * 10;
            long endTicks = startTicks + updateSpan; // ‘100毫微秒的倍数  ‘一个Ticks=10亿分之一秒,一毫秒=10000Ticks
            while (QueRecText.Count > 0)
            {
                lock (QueRecText.SyncRoot)
                {
                    obj = QueRecText.Dequeue();//取出
                }
                txtInfoUpdateEntry(obj);

              //  txtInfoUpdateEntryOld();
                infoRowsCount++;
                dealt++;
                if (DateTime.Now.Ticks > endTicks)
                {
                    endTicks = DateTime.Now.Ticks + updateSpan;
                    if (watching.WatchingController == null)
                    {
                        break;
                    }
                }
            }
            Application.DoEvents();//显示
            System.Threading.Interlocked.Exchange(ref dealingTxt, 0);
        }

        static private string lastTime = "0";
        static private string initTime = "0";

        private bool bCard = false;

        private void txtInfoUpdateEntryOld()
        {
          //   WComm_Operate  wudp = new WComm_Operate();
            if (wudp == null)
            {
                wudp = new WComm_Operate();
            }

            string strRunDetail;
            String strSwipeDate;   //日期时间
            string  strInfo;
            string strT;
            long watchIndex = 0;
            long  cardId =0;        //卡号    
            long  status = 0;        //状态    

            foreach (controllerOld ctrl in ctrlOld)
            {
                string strTemp = String.Concat("8110", wudp.NumToStrHex(watchIndex, 2));            //表示第watchIndex个记录, 如果是0则取最新一条记录
                string strCmd = wudp.CreateBstrCommand(ctrl.sn, strTemp);                  //生成指令帧 
                string strFrame = wudp.udp_comm(strCmd, ctrl.ip, ctrl.port);                        //发送指令, 并获取返回信息
                if ((0 != wudp.ErrCode) || (strFrame.Length == 0))
                {
                    strInfo = "\r\n实时监控失败";
                }
                else
                {
                    strSwipeDate = wudp.GetSwipeDateFromRunInfo(strFrame, ref cardId, ref status);
                    if (strSwipeDate.Length != 0)
                    {
                        //记录的详细解析
                        strRunDetail = "";
                        strInfo = String.Concat("\r\n", "卡号: ", cardId.ToString());
                        strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);
                        strT = wudp.NumToStrHex(status, 1);
                        strInfo = String.Concat("\t", "状态: ", (status.ToString()));
                        strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);
                        strInfo = String.Concat("(", strT, ")");
                        strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);
                        strInfo = String.Concat("\t", "时间:  ", strSwipeDate);

                        strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);

                        if (!bCard)
                        {
                            initTime = strSwipeDate;
                            bCard = true;
                        }

                        if (!lastTime.Equals(strSwipeDate.ToString()) && !strSwipeDate.Equals(initTime.ToString()))
                        {
                             this.textBox1.AppendText(strRunDetail.ToString());
                             lastTime = strSwipeDate;

                             testMessage tstMsg = new testMessage()
                             {
                                 ID = (uint)cardId,
                                 time =  strSwipeDate.ToString(),
                                 ReaderNo =  (uint)cardId,
                                 ControllerSN = (uint)ctrl.sn,
                                 status = cardId.ToString()
                             };

                             string door_user_id;
                             string name;
                             string card_id;
                             string read_time;
                             string ctrl_sn;
                             string ctrl_name;
                             string door_id;
                             string door_name;
                             string reader_id;
                             string read_status;
                             string rcd_id;

                             door_user_id = "";
                             name = "";
                             ctrl_name = "";
                             door_name = "";
                             rcd_id = CommonUtils.GetNewGUID();

                             card_id = cardId != null ? cardId.ToString() : "";
                             //read_time = mjrec.ReadDate.ToShortDateString() + mjrec.ReadDate.ToShortTimeString() ;
                             read_time = strSwipeDate.ToString();// ("yyyy-MM-dd HH:mm:ss");
                             ctrl_sn = ctrl.sn.ToString();
                             door_id = cardId.ToString();
                             reader_id = cardId.ToString();
                             read_status = cardId.ToString();

                             int reader = this.ExecuteNonQuery(conn, "INSERT INTO U_DOOR_CARD_READ_RCD (door_user_id,name,card_id,read_time,ctrl_sn,ctrl_name,door_id,door_name,reader_id,read_status,rcd_id) VALUES (‘" + door_user_id + "‘,‘ " + name + "‘, ‘" + card_id + "‘, ‘" + read_time + "‘, ‘" + ctrl_sn + "‘,‘" + ctrl_name + "‘,‘" + door_id + "‘,‘" + door_name + "‘, ‘" + reader_id + "‘, ‘" + read_status + "‘, ‘" + rcd_id + "‘)");
                             if (reader >= 0)
                             {
                                 this.textBox1.AppendText("\t数据库存储刷卡记录成功!\r\n");
                             }

                             foreach (HeartIP ip in listIP)
                             {
                                 this.client.BindIP(ip.IP.ToString());
                                 this.client.Send(tstMsg.ToByte());
                                 this.textBox1.AppendText("\r\n向客户端:" + ip.IP.ToString() + " 发送读卡记录!\r\n");
                             }
                        }
                    }
                }
            }

        }


        private void txtInfoUpdateEntry(object info)
        {
            wgMjControllerSwipeRecord mjrec = new wgMjControllerSwipeRecord(info as string);
            if (mjrec.ControllerSN > 0)
            {
                //如果不处于监控的控制器 则不作数据处理
                try
                {
                    if (!watching.WatchingController.ContainsKey((int)mjrec.ControllerSN))
                    {
                        return; //不属于监控的控制器发出的信息 则返回
                    }
                }
                catch (Exception)
                {
                    return;
                }
           //     this.textBox1.AppendText(mjrec.ToDisplaySimpleInfo(true));

                string strRunDetail;
                string strT;
                string strInfo;

                //记录的详细解析
                strRunDetail = "";
                strInfo = String.Concat("\r\n", "卡号: ", mjrec.CardID.ToString());
                strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);
                //strT = wudp.NumToStrHex(status, 1);
                strInfo = String.Concat("\t", "状态: ", (mjrec.IsEnterIn.ToString()));
                strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);
               // strInfo = String.Concat("(", strT, ")");
              //  strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);
                strInfo = String.Concat("\t", "时间:  ", mjrec.ReadDate.ToString("yyyy-MM-dd HH:mm:ss"));

                strRunDetail = strRunDetail.Insert(strRunDetail.Length, strInfo);

                this.textBox1.AppendText(strRunDetail.ToString());

                testMessage tstMsg = new testMessage()
                {
                    ID = mjrec.CardID,
                    time = mjrec.ReadDate.ToShortDateString() + "  " + mjrec.ReadDate.ToShortTimeString(),
                    ReaderNo = mjrec.ReaderNo,
                    ControllerSN = mjrec.ControllerSN,
                    status = mjrec.SwipeStatus.ToString()
                };
  
                string door_user_id;
                string name;
                string card_id;
                string read_time;
                string ctrl_sn;
                string ctrl_name;
                string door_id;
                string door_name;
                string reader_id;
                string read_status;
                string rcd_id;

                door_user_id = "";
                name = "";
                ctrl_name = "";
                door_name = "";
                rcd_id = CommonUtils.GetNewGUID();

                card_id = mjrec.CardID != null ? mjrec.CardID.ToString() : "";
             
                //read_time = mjrec.ReadDate.ToShortDateString() + mjrec.ReadDate.ToShortTimeString() ;
                read_time = mjrec.ReadDate.ToString("yyyy-MM-dd HH:mm:ss");

                ctrl_sn = mjrec.ControllerSN.ToString();
                door_id = mjrec.DoorNo.ToString();
                reader_id = mjrec.ReaderNo.ToString();
                read_status = mjrec.SwipeStatus.ToString();

                int reader = this.ExecuteNonQuery(conn, "INSERT INTO U_DOOR_CARD_READ_RCD (door_user_id,name,card_id,read_time,ctrl_sn,ctrl_name,door_id,door_name,reader_id,read_status,rcd_id) VALUES (‘" + door_user_id + "‘,‘ " + name + "‘, ‘" + card_id + "‘, ‘" + read_time + "‘, ‘" + ctrl_sn + "‘,‘" + ctrl_name + "‘,‘" + door_id + "‘,‘" + door_name+ "‘, ‘" + reader_id + "‘, ‘" + read_status + "‘, ‘"+rcd_id+"‘)");
                if (reader >= 0)
                {
                    this.textBox1.AppendText("\t数据库存储刷卡记录成功!\r\n");
                }

                foreach (HeartIP ip in listIP)
                {
                    this.client.BindIP(ip.IP.ToString());
                    this.client.Send(tstMsg.ToByte());
                    this.textBox1.AppendText("\r\n向客户端:" + ip.IP.ToString() + " 发送读卡记录!\r\n");
                }
           }
     }

        private void btnStop_Click(object sender, EventArgs e)
        {

            //将所有的停止放在一个按钮上
            if (watching != null)
            {
                //停止实时监控
                watching.WatchingController = null;
                this.timerUpdateDoorInfo.Enabled = false;
            }
            System.Threading.Interlocked.Exchange(ref dealingTxt, 0);
            this.btnStart.Enabled = true;
            Cursor.Current = Cursors.Default; 

            selectedControllers.Clear();
            ctrlOld.Clear();

            this.textBox1.AppendText("\r\n监控已经停止!\r\n");

         }


        public OdbcDataReader ExecuteReader(string connectionStr, string strSQL)
        {
            OdbcConnection connection = new OdbcConnection(connectionStr);

            OdbcCommand cmd = new OdbcCommand(strSQL, connection);
            try
            {
                connection.Open();
             
               OdbcDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
             //   int myReader = cmd.ExecuteNonQuery();
                return myReader;
            }
            catch (SqlException E)
            {
       //         WriteLogFile.WriteMessage("DBOper.log", "error DBHelper.ExecuteReader " + E.Message.ToString());
             
            }
            return null;
        }

        public int ExecuteNonQuery(string connectionStr, string strSQL)
        {
            OdbcConnection connection = new OdbcConnection(connectionStr);

            OdbcCommand cmd = new OdbcCommand(strSQL, connection);
            try
            {
                connection.Open(); 
                int myReader = cmd.ExecuteNonQuery();
                return myReader;
            }
            catch (SqlException E)
            {
                //         WriteLogFile.WriteMessage("DBOper.log", "error DBHelper.ExecuteReader " + E.Message.ToString());

            }
            return  -1;
        }

        public wgMjController controller;  //

        DataTable dtController = null; //控制器表 
        private void frmWatching_Load(object sender, EventArgs e)
        {
           /* database = new DB2();

            database.ConnectionString = "Database=AFFZDB;UserID=db2admin; Password=qifdz;";

            database.CommandText = "INSERT INTO t_node (rvu_id,sm_id,node_id,node_name,node_desc,node_type_id,min_value,max_value,precision,saved,unit,alarm_enable) VALUES (‘" + 123456789 + "‘, " + 123456789 + ", " + 1 + ", ‘上‘, ‘‘," + 4 + "," + 0.000000 + "," + 0.000000 + ", " + 0.000000 + ", " + 1 + ", ‘‘, " + 1 + ")";

            database.Execute();
            */
          //  FrmLogin login = new FrmLogin();

      //      if (login.ShowDialog(this) != DialogResult.OK)
            {
     //           return;
            }
       //     else
            {
                this.dgvControllers.ForeColor = Color.Black;

                dtController = new DataTable("Controllers");

                DataColumn col = new DataColumn("Ctrl_ID", typeof(System.UInt32));
                dtController.Columns.Add(col);
                col = new DataColumn("IP", typeof(string));
                dtController.Columns.Add(col);
                col = new DataColumn("Port", typeof(UInt32));
                dtController.Columns.Add(col);
                col = new DataColumn("Status", typeof(string));
                dtController.Columns.Add(col);
                col = new DataColumn("Time", typeof(string));
                dtController.Columns.Add(col);

                this.dgvControllers.DataSource = dtController;

                OdbcDataReader reader = ExecuteReader(conn, "select ctrl_sn,ip,port from u_door_ctrl");
                while (reader.Read())
                {
                    if (!reader.IsDBNull(0))
                    {
                        if (int.Parse(reader[0].ToString()) > 100000)
                        {
                            if (!reader[1].ToString().Equals("") && !reader[2].ToString().Equals(""))
                            {
                                wgMjControllerWatching = new wgMjController(); //Create New 
                                wgMjControllerWatching.ControllerSN = int.Parse(reader[0].ToString());
                                wgMjControllerWatching.IP = reader[1].ToString();
                                wgMjControllerWatching.PORT = int.Parse(reader[2].ToString());
                                selectedControllers.Add(wgMjControllerWatching.ControllerSN, wgMjControllerWatching);
                            }
                           
                        }
                        else 
                        {
                            if (!reader[1].ToString().Equals("") && !reader[2].ToString().Equals(""))
                            {
                                controllerOld ctrl = new controllerOld();
                                ctrl.sn = int.Parse(reader[0].ToString());
                                ctrl.ip = reader[1].ToString();
                                ctrl.port = int.Parse(reader[2].ToString());
                                ctrlOld.Add(ctrl);
                            }
                        }

                        //加入控制器
                        DataTable dt = this.dgvControllers.DataSource as DataTable;
                        if (dt != null)
                        {

                            if (!reader[1].ToString().Equals("") && !reader[2].ToString().Equals(""))
                            {
                                DataRow dr = dt.NewRow();
                                dr["Ctrl_ID"] = int.Parse(reader[0].ToString());
                                dr["IP"] = reader[1].ToString();
                                dr["Port"] = int.Parse(reader[2].ToString());
                                dt.Rows.Add(dr);
                                dt.AcceptChanges();
                            }
                        }     
                    }
                }
                reader.Close();

                this.textBox1.AppendText("成功从数据库读取门禁控制器参数!\r\n");

                client = new UDPTalkChannel.Client(Convert.ToInt32("5001"), Convert.ToInt32("5000"), Convert.ToInt32("1024"));
                client.onSent += new UDPTalkChannel.Client.SentEventHandler(client_onSent);
                client.onError += new UDPTalkChannel.Client.ErrorEventHandler(client_onError);
                client.onReceived += new UDPTalkChannel.Client.ReceivedEventHandler(client_onReceived);

                if (watching == null)
                {
                    watching = new wgWatchingService();  //加载监视服务
                    watching.EventHandler += new OnEventHandler(evtNewInfoCallBack); //事件处理
                }

                if (wudp == null)
                {
                    wudp = new WComm_Operate();  //加载监视服务
                    wudp.minUDPWaitTimeout = 3000;
                }

                if (selectedControllers.Count > 0)
                {
                    System.Diagnostics.Debug.WriteLine("selectedControllers.Count=" + selectedControllers.Count.ToString());
                    watching.WatchingController = selectedControllers;

                    this.timerUpdateDoorInfo.Interval = 300;
                    this.timerUpdateDoorInfo.Enabled = true;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("selectedControllers.Count=" + selectedControllers.Count.ToString());
                    watching.WatchingController = null;
                    this.timerUpdateDoorInfo.Enabled = false;

                }
                Cursor.Current = Cursors.Default; 

                this.btnStart.Enabled = false;

                this.textBox1.AppendText("\r\n监控已经开始!\r\n");
            }
        }


        /// <summary>
        /// 线程委托处理
        /// </summary>
        /// <param name="packet">xml数据包</param>
        private void OnInvoke(XmlPacket packet)
        {
            try
            {
                // 短连接失败的场合
                if (PKType.CONNECT_SERVER_FAILED.Equals(packet.pkType))
                {
                    FrmWait.CloseWaitForm();
                    ConnectFailed connectFailed = (ConnectFailed)packet;
                    // 消息提示
                    MsgBox.ShowInfo(this, VMMessages.GetValue("I_9999"));
             
                }
                else if (PKType.GET_U_COMPANYINFO_ACK.Equals(packet.pkType))//获取单位报文返回
                {
                   
                    Get_U_CompanyInfoAck getCompanyInfoAck = (Get_U_CompanyInfoAck)packet;
                    // 返回结果正确的场合
                    if (getCompanyInfoAck.Result == 1)
                    {
                       
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), getCompanyInfoAck.Desc);
                    }
                }
                else if (PKType.GET_U_COMPDEPTCLASSINFO_ACK.Equals(packet.pkType))//获取班组报文返回
                {
                 
                    Get_U_ComDeptClassInfoAck getComDeptClassInfoAck = (Get_U_ComDeptClassInfoAck)packet;
                    // 返回结果正确的场合
                    if (getComDeptClassInfoAck.Result == 1)
                    {
                      

                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), getComDeptClassInfoAck.Desc);
                    }
                }
                else if (PKType.GET_U_COMPDEPTINFO_ACK.Equals(packet.pkType))//获取单位部门报文返回
                {
                
                    Get_U_ComDeptInfoAck getComDeptInfoAck = (Get_U_ComDeptInfoAck)packet;
                    // 返回结果正确的场合
                    if (getComDeptInfoAck.Result == 1)
                    {
                       
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), getComDeptInfoAck.Desc);
                    }
                }
                else if (PKType.GET_U_DOORCTRLINFO_ACK.Equals(packet.pkType))//获取控制器信息报文返回
                {
   
                    Get_U_DoorCtrlInfoAck getDoorCtrlInfoAck = (Get_U_DoorCtrlInfoAck)packet;
                    // 返回结果正确的场合
                    if (getDoorCtrlInfoAck.Result == 1)
                    {
                       
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), getDoorCtrlInfoAck.Desc);
                    }
                }
                else if (PKType.GET_U_DOORBELONG_INFO_ACK.Equals(packet.pkType))//获取控制器归属信息报文返回
                {
                 
                    Get_U_DoorBelongInfoAck get_U_DoorBelongInfoAck = (Get_U_DoorBelongInfoAck)packet;
                    // 返回结果正确的场合
                    if (get_U_DoorBelongInfoAck.Result == 1)
                    {
                        
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), get_U_DoorBelongInfoAck.Desc);
                    }
                }
                else if (PKType.GET_U_DOOR_PERIOD_INFO_ACK.Equals(packet.pkType))//获取门禁时段信息报文返回
                {
                    Get_U_DoorPeriodInfoAck get_U_DoorPeriodInfoAck = (Get_U_DoorPeriodInfoAck)packet;
                    // 返回结果正确的场合
                    if (get_U_DoorPeriodInfoAck.Result == 1)
                    {
              
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), get_U_DoorPeriodInfoAck.Desc);
                    }
                }
       
                else if (PKType.GET_U_OPT_USER_INFO_ACK.Equals(packet.pkType))//获取操作人员门禁权限配置信息报文返回
                {
                 
                    Get_U_OptUserConfigInfoAck get_U_OptUserConfigInfoAck = (Get_U_OptUserConfigInfoAck)packet;
                    // 返回结果正确的场合
                    if (get_U_OptUserConfigInfoAck.Result == 1)
                    {
                       
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), get_U_OptUserConfigInfoAck.Desc);
                    }
                }
                else if (PKType.GET_U_USERINFO_ACK.Equals(packet.pkType))//获取人员信息报文返回
                {
                    Get_U_UserInfoAck get_U_UserInfoAck = (Get_U_UserInfoAck)packet;
                    // 返回结果正确的场合
                    if (get_U_UserInfoAck.Result == 1)
                    {
                     
                    }
                    else
                    {
                        FrmWait.CloseWaitForm();
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), get_U_UserInfoAck.Desc);
                    }
                }
                else if (PKType.GET_ALLUSERINFO_ACK.Equals(packet.pkType))
                {
          
                }
                else if (PKType.UPDATE_READ_CARD_RECORD_INFO_ACK.Equals(packet.pkType))
                {
                    FrmWait.CloseWaitForm();
                    UpdateReadCardRecordInfoACK upateRcdAck = (UpdateReadCardRecordInfoACK)packet;
                    if (upateRcdAck.Result == 1)
                    {
                        MsgBox.ShowInfo(this, "提取记录成功");
                    
                    }
                    else
                    {
                        // 消息告知错误描述
                        MsgBox.ShowError(this, VMMessages.GetValue("E_0007"), upateRcdAck.Desc);
                    }
                }
                else if (PKType.UPDATE_U_LOGINREQUEST_ACK.Equals(packet.pkType))
                {
                    //FrmWait.CloseWaitForm();
                    XmlReceivePacket loginRequestAck = (XmlReceivePacket)packet;
                    if (loginRequestAck.Result == 1)
                    {
                     
                    }
                    else
                    {
                    
                    }
                }
                else if (PKType.UPDATE_U_DOORCTRLINFO_ACK.Equals(packet.pkType))
                {
                    FrmWait.CloseWaitForm();
                    UpdateDoorCtrlInfoAck updateDoorCtrlAck = (UpdateDoorCtrlInfoAck)packet;
                    if (updateDoorCtrlAck.Result == 1)
                    {
                        MsgBox.ShowInfo(this, "布撤防操作成功");
                    }
                    else
                    {
                        MsgBox.ShowError(this, updateDoorCtrlAck.Desc);
                     
                    }
                }     
             
            }
            catch (Exception ex)
            {
                FrmWait.CloseWaitForm();
                UICommon.ExceptionHandler(this, ex);
            }
        }

        void client_onReceived(object sender, UDPTalkChannel.Client.ReceivedEventArgs e)
        {
            testMessage tstMsg = new testMessage();
            tstMsg = (testMessage)tstMsg.ToMessage(e.MessageByte);

            string strTem = string.Format("Received: {0},  ID: {1}, IP: {2}", tstMsg.textMessage, tstMsg.ID, e.senderClient.ToString());

            string[] splits = new string[] { };

            splits = e.senderClient.ToString().Split(:);
            String ip = splits[0]; 

            String add = "add";
            String del = "del";


            if (add.Equals(tstMsg.textMessage))
            {

                foreach (HeartIP tempIP in listIP)
                {
                    if (tempIP.IP.Equals(ip))
                    {
                        listIP.Remove(tempIP);
                        break;
                    }
                }
                {
                    HeartIP tempIP =  new HeartIP();
                    tempIP.nHeart = 0;
                    tempIP.IP = ip;
                    listIP.Add(tempIP);
                }
            }
            else if (del.Equals(tstMsg.textMessage))
            {
                foreach (HeartIP tempIP in listIP)
                {
                     if(tempIP.IP.Equals(ip))
                     {
                         listIP.Remove(tempIP);
                         break;
                     }
                }
            }

        //    MessageBox.Show(strTem);
        }

        void client_onError(object sender, UDPTalkChannel.Client.ErrorEventArgs e)
        {
     //       MessageBox.Show(e.Ex.Message, "Error");
        }

        void client_onSent(object sender, UDPTalkChannel.Client.SentEventArgs e)
        {
       //     MessageBox.Show("Message Sent");
        }

        //clear controllers
        private void btnClear_Click(object sender, EventArgs e)
        {
             //清空控制器
            DataTable dt = this.dgvControllers.DataSource as DataTable ;
            if (dt != null)
            {
                dt.Rows.Clear();
            }
        }

        //add a controller
        private void btnAddController_Click(object sender, EventArgs e)
        {
            using (dfrmControllerSetup dfrm = new dfrmControllerSetup())
            {
                if (dfrm.ShowDialog(this) == DialogResult.OK)
                {
                    //加入控制器
                    DataTable dt = this.dgvControllers.DataSource as DataTable;
                    if (dt != null)
                    {
                        using (DataView dv = new DataView(dt))
                        {
                            dv.RowFilter = string.Format("Ctrl_ID = {0:d}", (uint)dfrm.txtSN.Value);
                            if (dv.Count == 0)
                            {
                                DataRow dr = dt.NewRow();
                                dr["Ctrl_ID"] = (uint)(dfrm.txtSN.Value);
                                dr["IP"] =   dfrm.txtControllerIP.Text;
                                dr["Port"] = dfrm.nudPort.Value;
                                dt.Rows.Add(dr);
                                dt.AcceptChanges();
                            }
                        }
                    }
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
           //将所有的停止放在一个按钮上
            if (watching != null)
            {
                //停止实时监控
                watching.WatchingController = null;
                this.timerUpdateDoorInfo.Enabled = false;
            }
            if (watching != null)
            {
                watching.StopWatch(); //2010-6-24 09:11:04 停止监控
            }
            this.Close();
        }

        //窗体已关闭事件
        private void frmWatching_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (watching != null)
            {
                watching.StopWatch(); //2010-6-24 09:11:04 停止监控
            }
        }
        //搜索控制器
    //    dfrmNetControllerConfig dfrmNetControllerConfig1 = null;
        private void btnSearchControllers_Click(object sender, EventArgs e)
        {
       //    dfrmNetControllerConfig1 = new dfrmNetControllerConfig();
         //   dfrmNetControllerConfig1.Show(this);

            using (dfrmNetControllerConfig dfrm = new dfrmNetControllerConfig())
            {
                if (dfrm.ShowDialog(this) == DialogResult.OK)
                {
                    //加入控制器
                    DataTable dt = this.dgvControllers.DataSource as DataTable;

                    DataTable src = dfrm.dgvFoundControllers.DataSource as DataTable;

                    if (dt != null)
                    {
                             DataGridViewRow rowIndex;    
                        for (int index = 0; index < dfrm.dgvFoundControllers.Rows.Count; index++)
                        {
                            rowIndex = dfrm.dgvFoundControllers.Rows[index];
                          //  rowIndex = src.Rows[index];

                            using (DataView dv = new DataView(dt))
                            {
                                dv.RowFilter = string.Format("Ctrl_ID = {0:d}", uint.Parse(rowIndex.Cells["f_ControllerSN"].Value.ToString()));
                                if (dv.Count == 0)
                                {
                                    DataRow dr = dt.NewRow();
                                    dr["Ctrl_ID"] = rowIndex.Cells["f_ControllerSN"].Value;
                                    dr["IP"] = rowIndex.Cells["f_IP"].Value;
                                    dr["Port"] = rowIndex.Cells["f_PORT"].Value;
                                    dt.Rows.Add(dr);
                                    dt.AcceptChanges();
                                }
                            }

                        }
                 
                    }
                }
            }
        
        
        }

        private void frmWatching_Shown(object sender, EventArgs e)
        {

        }

        private void timerHeart_Tick(object sender, EventArgs e)
        {

            for (int n = 0; n< listIP.Count; n++)
            {
                if (listIP[n].nHeart > 6)
                {
                    listIP.RemoveAt(n);
                }
                else
                {
                    listIP[n].nHeart++;
                }
            
            }

        }

        private void dgvControllers_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

    }
}

 

多线程

标签:des   datagridview   style   blog   io   ar   color   os   sp   

原文地址:http://www.cnblogs.com/wlzhang/p/4122367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!