1. 程式人生 > >WINCE5.0利用C#語言編寫的串列埠採集、顯示和儲存

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