RFID设备管理C#客户端学习笔记之4:更新数据库

事实上,前面的客户端是不够完善的,我们要自动获取IP,还要从数据库中选择工作人员。

除此之外手动控制服务器关闭也是有必要的……像下图所示的效果:

RFID设备管理C#客户端学习笔记之4:更新数据库

图1  收到读写器的消息之后立即插入到数据库

RFID设备管理C#客户端学习笔记之4:更新数据库

图2 开启、打开服务器

1、获取当前主机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;
        }

启动时调用

//为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;                
            }


2、查询“人员表”,添加到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();
                //1、只选择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";

3、手动开启和关闭服务器端程序

开启服务器按钮调用StartServer(),关闭服务器按钮调用StopServer()

/// <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;
            }
        }


4、RFID读写器读到的结果插入到数据库

在RecMsg(object o)中添加

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

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


你可能感兴趣的:(RFID设备管理C#客户端学习笔记之4:更新数据库)