RFID設備管理C#客戶端學習筆記之4:更新數據庫

事實上,前面的客戶端是不夠完善的,咱們要自動獲取IP,還要從數據庫中選擇工做人員。sql

除此以外手動控制服務器關閉也是有必要的……像下圖所示的效果:數據庫

圖1  收到讀寫器的消息以後當即插入到數據庫c#

圖2 開啓、打開服務器服務器

一、獲取當前主機IP地址

/// <summary>
        /// 獲取本機地址列表
        /// </summary>
        public List<string> GetLocalAddresses()
        {
            // 獲取主機名
            string strHostName = Dns.GetHostName();

            // 根據主機名進行查找
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
            List<string> iplist = new List<string>();
            
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {//過濾IPv6地址
                if (ipaddress.ToString().Length < "111.222.333.444".Length)
                {
                    iplist.Add(ipaddress.ToString());
                }                
            }
            return iplist;
        }

啓動時調用socket

//爲cb_ips添加本地ip
            List<string> IPs = GetLocalAddresses();
            if (IPs.Count() > 0)
            {                
                this.cb_IPs.Items.Clear();
                foreach (var i in IPs)
                {
                    cb_IPs.Items.Add(i);
                }
                cb_IPs.SelectedIndex = 0;                
            }


二、查詢「人員表」,添加到ComboBox中

2.1 rfid_DBHelper.cs(調用了MySqlHelper.cs,源碼

/// <summary>
    /// 本身定製一些增刪改查功能
    /// </summary>
    public abstract class rfid_DBhelper
    {        
        static string connectionString =
"Database='rfid2';Data Source='localhost';User Id='uid';Password='psd';charset='utf8';pooling=true";
        /// <summary>
        /// 獲取下拉列表的dataset
        /// </summary>
        /// <returns>dataset</returns>
        public static DataSet getComboBox()
        {
            //Debug.WriteLine("【dbhelper】");
            string sql = "select * from tb_people";
            DataSet ds = MySqlHelper.GetDataSet(connectionString, CommandType.Text, sql, null);
            return ds;
        }
        /// <summary>
        /// 插入數據到iohistory中
        /// </summary>
        /// <param name="epc"></param>
        /// <param name="hander"></param>
        /// <param name="dt"></param>
        /// <returns>受影響的行數</returns>
        public static int insert_iohistory(string epc, int hander, DateTime dt)
        {
            string sql =
string.Format("insert into tb_iohistory(tagID,hander,occorTime) values('{0}','{1}','{2}')", epc, hander, dt);
            Debug.WriteLine(sql);

            return MySqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sql, null);
        }
    }


2.2 HandleFeedback.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections;

namespace Ex02_wifiServer
{
    public class HandleFeedback
    {
        public string type { get; set; }//指令類型
        List<string> devices = new List<string>();
        
        public void processDevIO(out bool isOK, string code, string h = "1001")
        {
            //識別失敗回:(E4 04 82)頭,(00 )usercode (05)Status ,( 91)Checksum 
            //識別成功回:(E0 10 82)頭,(00 )usercode (01)天線號 ,(12 34 00 00 00 00 00 00 00 00 00 10)ID,(37)Checksum 

            string[] strs = code.Split(' ');
            int hander = Convert.ToInt32(h);
            DateTime datetime = DateTime.Now;

            if (strs[4] == "05")
            {
                Debug.WriteLine("【handle feedback】識別失敗。");
                isOK = false;
                return;
            }
            else
            {
                StringBuilder epc = new StringBuilder();
                //一、只選擇EPC區,12個字節
                epc.Append(strs[5]);
                for (int i = 6; i < 17; i++)
                {
                    epc.Append(' ' + strs[i]);
                }
                Debug.WriteLine("【handle feedback】{0},{1},{2}", epc, hander, datetime);//test ok
                if (rfid_DBhelper.insert_iohistory(epc.ToString(), hander, datetime) != 0)
                {
                    //插入成功
                    isOK = true;
                    //插入過程除了點問題,暫時刪除外鍵
                    //ALTER TABLE `tb_iohistory` DROP FOREIGN KEY `fk_io_tag`;
                }
                else
                {
                    isOK = false;
                }
                return;
            }
            
        }
       
    }
}


2.3 調用

//動態綁定cb_people下拉列表
            cb_people.DataSource = rfid_DBhelper.getComboBox().Tables[0];
            cb_people.ValueMember = "personID";
            cb_people.DisplayMember = "Name";

三、手動開啓和關閉服務器端程序

開啓服務器按鈕調用StartServer(),關閉服務器按鈕調用StopServer()
ui

/// <summary>
        /// 啓動服務器
        /// </summary>
        private void ServerStart()
        {
            data = "等待用戶鏈接……\n";
            richTextBox1.AppendText(data);
            richTextBox1.Focus();            
            toolStripStatusLabel1.Text = DateTime.Now + ":服務器已經打開";
            btn_start.Enabled = false;
            btn_stop.Enabled = true;            
            //定義線程開始
            server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipadd = IPAddress.Parse(server_ip);
            IPEndPoint ipe = new IPEndPoint(ipadd, server_port);
            try
            {
                server_socket.Bind(ipe);
                server_socket.Listen(100);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return;
            }
            server_thread = new Thread(Run);            
            //後臺線程將會隨着主線程的退出而退出
            server_thread.IsBackground = true;
            server_thread.Start(server_socket);            
        }
        /// <summary>
        /// 關閉服務器
        /// </summary>
        private void ServerStop()
        {
            try
            {
                toolStripStatusLabel1.Text = DateTime.Now+":服務器已經關閉";
                richTextBox1.AppendText("服務器已經關閉\n");
                btn_start.Enabled = true;
                btn_stop.Enabled = false;
                
                //注意先關閉socket,再中止線程
                foreach (var i in dicSocket)
                {
                    i.Value.Close();
                }
                foreach (var i in dicThread)
                {
                    i.Value.Abort();
                }
                server_socket.Close();
                server_thread.Abort();
            }
            catch (Exception ex)
            {                
                toolStripStatusLabel1.Text = "關閉出現異常:" + ex;
                throw;
            }
        }


四、RFID讀寫器讀到的結果插入到數據庫

在RecMsg(object o)中添加this

//交給HandleFeedback去處理
                    bool isInsertOK = false;
                    HandleFeedback hander = new HandleFeedback();
                    hander.processDevIO(out isInsertOK, str, worker);
                    if (isInsertOK)
                    {
                        toolStripStatusLabel1.Text = "添加事件成功";
                    }
                    else
                    {
                        toolStripStatusLabel1.Text = "添加事件失敗";
                    }

其中str是接收到的字符串。spa

相關文章
相關標籤/搜索