WINCE5.0利用C#语言编写的串口采集、显示和存储

          首先简单说一下该程序实现的功能:定时采集现场的数据,在界面上实时显示设备数据,同时将采集到的设备数据存储到sqlite中,以方便第三方数据调用。该程序使用在wince5.0中,使用的是VS2008 C#语言。

        内容涉及到wince同步的应用、串口的收发、数据的存储、CRC校验知识、Modbus协议的应用等。


         程序主要分成几部分:

  1. 数据采集
  2. 数据分析、显示
  3. 数据存储 
  • 数据采集说明
      其中数据采集主要实现定时发送Mobus RTU协议的报文,由于现场设备较少,发送一个包就足够将所有设备数据采集到.
  • 数据分析、显示说明
      将接收到的数据按照指定的协议拆分,分析并在界面上实时显示出来。其中在接收中添加了报文的判断,一般先判断接收到的报文长度是否符合正常的长度,如果符合再判断帧头是否符合协议,数据长度是否足够,校验是否正常,如果都正常的话,就按一定算法解析报文。
  • 数据存储说明
     按照采集的频率存储界面上的数据。

说明:sqlite的使用,须在前面引用:
using System.Data.SQLite;
using System.Data.Common;
using System.Data.SqlTypes;


  #region  窗体事件

        private void frmMain_Load(object sender, EventArgs e)
        {
            for (int i = 1000; i <= 60000; i = i + 1000)//时间间隔设置
            {
                this.cboxInterval.Items.Add(i);
            }
            this.cboxInterval.SelectedIndex = 0;

            for (int i = 1; i < 4; i++)
            {
                this.cboxPortName.Items.Add("COM" + i.ToString());
            }
            this.cboxPortName.SelectedIndex = 2;

            /*
            string[] baudRates = new string[] { "115200", "57600", "38400", "19200", "14400", "9600" };
            foreach (string baudRate in baudRates)
            {
                this.cboxBaudRate.Items.Add(baudRate);
            }
            this.cboxBaudRate.SelectedIndex = 5;

            cboxCheck.Items.Add("None");
            cboxCheck.Items.Add("Odd");
            cboxCheck.Items.Add("Even");
            cboxCheck.SelectedIndex = 0;

            cboxDataBit.Items.Add("8");
            cboxDataBit.Items.Add("7");
            cboxDataBit.Items.Add("6");
            cboxDataBit.SelectedIndex = 0;

            cboxStopBit.Items.Add("1");
            cboxStopBit.Items.Add("2");
            cboxStopBit.SelectedIndex = 0;
            */

            this.timer1.Enabled = true;
            this.labDate.Text = string.Format("日期: {0}", DateTime.Now.ToString("yyyy年MM月dd日 dddd"));
            this.cboxSend.Text = "01 03 00 00 00 04 44 09";

            //参数初始化
            this.temper1.Text = "0";
            this.temper2.Text = "0";
            this.pressure.Text = "0";
            this.voltage.Text = "0";


            this.ChangeEnable(false);
            this.ShowFormCenter();

            //sqlite数据库加载
           string aurl = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\";
           string strConn = aurl + "db.db3";
            //strConn = "db.db3";
           connection.ConnectionString = "Data Source=" + strConn+";Pooling = true; FailIfMissing = true";
            connection.Open();//连接数据库
        }


//打开串口
        private void btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnOpen.Text == "打开串口")
                {
                    sp.PortName = cboxPortName.SelectedItem.ToString();
                   // sp.BaudRate = Convert.ToInt32(cboxBaudRate.SelectedItem.ToString());
                    sp.BaudRate = baudRates;//默认9600
                   // sp.DataBits = 8;
                   // sp.StopBits = 1;
                    sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);//订阅委托

                    //委托实例化
                    UpdateTextHandle = new UpdateTextDelegate(UpdateTextBox);  //实例化委托对象 

                    sp.Open();
                    System.Threading.Thread.Sleep(10);
                    sp.DiscardInBuffer();//清除串行驱动程序的接收缓冲区的数据;
                    sp.DiscardOutBuffer();//清除串行驱动程序发送缓冲区的数据;
                    btnOpen.Text = "关闭串口";
                    this.ChangeEnable(true);
                   // MessageBox.Show("打开串口成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    sp.Close();
                    btnOpen.Text = "打开串口";
                    this.ChangeEnable(false);
                }
            }
            catch { MessageBox.Show("打开串口失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); }
        }


/// <summary>
/// 定时发送报文
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
               
                    //将16进制数据转换为字节数组
                    byte[] data = this.HexStringToByteArray(cboxSend.Text);
                    sp.Write(data, 0, data.Length);
                    sendCount += data.Length;
                labSend.Text = String.Format("发送: {0} B", sendCount);

                if (isreceive == true)
                {
                    //向sqlite中存储数据
                    command.Connection = connection;
                    SQLiteTransaction ta = connection.BeginTransaction();
                    string time2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//获取当前时间
                    command.CommandText = "insert into datatable(time,temper1,temper2,pressure,voltage,battery) VALUES ( '" + time2 + "','" + temper1.Text + "','" + temper2.Text + "','" + pressure.Text + "','" + voltage.Text + "','" + voltage.Text + "' )";
                    command.ExecuteNonQuery();
                    ta.Commit();
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }<pre name="code" class="csharp">

 
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(100);//具备休眠作用,使数据得到缓存,缓存0.1秒
            int readlen = sp.BytesToRead; //读取数据的长度
            receiveCount += readlen; 
            if (readlen >= 5)//至少要包含设备号、功能码(2字节)+长度(1字节)+校验(2字节)
            {
                byte[] readBuffer = new byte[readlen];
                sp.Read(readBuffer, 0, readlen);
                string readbuf = null;
                if (readBuffer[0] == 0x01 && readBuffer[1] == 0x03)//第一个字节是不是01,第二个字节是不是03
                {
                    int len = readBuffer[2];//数据长度 
                    if (readlen >= len + 5)//数据长度够了的话才判断
                    {
                        byte[] data1 = new byte[len + 3];
                        for (int i = 0; i < len + 3; i++)//取得除了crc检验码所有数据
                        {
                            data1[i] = readBuffer[i];
                        }
                        byte[] checksum = GetCRC16(data1, true);
                        if ((checksum[0] == readBuffer[len + 3]) && (checksum[1] == readBuffer[len + 4])) //判断crc校验是否成功  
                        {
                            //十六进制格式化数据
                            for (int i = 0; i < readlen; i++)
                            {
                                string s = String.Format("{0:X}", Convert.ToInt32(readBuffer[i]));
                                if (s.Length > 1)
                                {
                                    readbuf += s + " ";
                                }
                                else
                                {
                                    readbuf += "0" + s + " ";
                                }
                            }
                            this.Invoke(UpdateTextHandle, readbuf);
                        }
                    }
                }
            }
            else
            {
                sp.DiscardInBuffer();//清除串行驱动程序的接收缓冲区的数据;
            }
        }

        #endregion
      
delegate void UpdateTextDelegate(string text);//定义委托
        UpdateTextDelegate UpdateTextHandle = null;
        void UpdateTextBox(string txt)
        {
            try
  


            {
                if (!isStop)
                {
                    txtReceive.Text += txt + "\r\n";
                    labReceive.Text = String.Format("接收: {0} B", receiveCount);
                    if (txt.Length > 0)//判断接收到的报文是否大于0
                    {
                       /*
                        * 解析算法
                        */
                    }

                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
            }
        }

#region  CRC校验函数

        /// <summary>  
        /// 计算CRC16循环校验码  
        /// </summary>  
        /// <param name="Cmd">命令数组</param>  
        /// <param name="IsHighBefore">高位是否在前</param>  
        /// <returns>高低位校验码</returns>  
        public static byte[] GetCRC16(byte[] Cmd, bool IsHighBefore)
        {
            int index;
            int crc_Low = 0xFF;
            int crc_High = 0xFF;
            for (int i = 0; i < Cmd.Length; i++)
            {
                index = crc_High ^ (char)Cmd[i];
                crc_High = crc_Low ^ CRCHigh[index];
                crc_Low = (byte)CRCLow[index];
            }
            if (IsHighBefore == true)
            {
                return new byte[2] { (byte)crc_High, (byte)crc_Low };
            }
            else
            {
                return new byte[2] { (byte)crc_Low, (byte)crc_High };
            }
        }
        #endregion


        #region CRC对应表
        //高位表  
        readonly static byte[] CRCHigh = new byte[]{  
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,   
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,   
            0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,   
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,   
            0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,   
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,   
            0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,   
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,   
            0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,   
            0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,   
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,   
            0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,   
            0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,   
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,   
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,   
            0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,   
            0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,   
            0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,   
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,   
            0x80, 0x41, 0x00, 0xC1, 0x81, 0x40};
        //低位表  
        readonly static byte[] CRCLow = new byte[]{  
            0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,   
            0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,   
            0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,   
            0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,   
            0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,   
            0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,   
            0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,   
            0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,   
            0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,   
            0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,   
            0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,   
            0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,   
            0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,   
            0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,   
            0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,   
            0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,   
            0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,   
            0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,   
            0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,   
            0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,   
            0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,   
            0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,   
            0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,   
            0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,   
            0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,   
            0x43, 0x83, 0x41, 0x81, 0x80, 0x40};
        #endregion   

 /// <summary>
        /// 重要应用:!!!!!写程序故障登录日志记录
        /// </summary>
        /// <param name="strLogMsg"></param>
        public static void WriteLog(string strLogMsg)
        {
            System.IO.FileStream HFile;//先声明一个文件流的句柄,用来存储文件地址 

            string strFileName = System.DateTime.Today.ToString("yyyyMMdd");
            HFile = OpenCreateFile(strFileName);//打开或者创建文件

            strLogMsg = System.DateTime.Now.ToString() + " #Msg: " + strLogMsg + "\r\n";
            WriteFile(HFile, strLogMsg);//写文件           
            CloseFile(HFile);//关闭文件
        }

        /// <summary>
        /// 打开或者创建一个txt文档,这个文档存在于“移动设备”的根目录下面
        /// “我的设备”中的所有文件夹,只有“FlashDisk”和“FlashDisk2”文件夹中的内容掉电后不会丢失,
        /// 所以用户需要保存的文件可以保存在该文件夹中。
        /// </summary>        
        /// <param name="strTextFileName">txt文件的名称</param>
        /// <return>创建的文件的句柄</return>
        private static System.IO.FileStream OpenCreateFile(string strTextFileName)
        {
            System.IO.FileStream HFile;

            string strLogpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\"+"Log";
            if (!Directory.Exists(strLogpath))
                Directory.CreateDirectory(strLogpath);

            string strFilePath = strLogpath+"\\" + strTextFileName + ".txt";//在程序目录下面

            try
            {
                HFile = System.IO.File.Open(strFilePath, System.IO.FileMode.OpenOrCreate);

            }
            catch (Exception)
            {
                //MessageBox.Show("文件创建或打开失败");
                HFile = null;
            }

            return HFile;
        }

        /// <summary>
        /// 往文件中写入内容
        /// </summary>
        /// <param name="HFile">文件句柄</param>
        /// <param name="strWriteText">需要写入的内容</param>
        private static void WriteFile(System.IO.FileStream HFile, string strWriteText)
        {
            if (HFile == null)
            {
                // MessageBox.Show("文件未打开");
                return;
            }
            //strWriteText = "Hello File";
            Byte[] buffer;
            buffer = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage).GetBytes(strWriteText);

            HFile.Position = HFile.Length;
            HFile.Write(buffer, 0, buffer.Length);
        }

        private static void CloseFile(System.IO.FileStream HFile)
        {
            if (HFile != null)
            {
                HFile.Close();
                HFile = null;
            }
        }




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值