using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;

namespace SerialPortTest
{
    public struct tagData
    {
        public byte addr;
        public byte volt;
        public uint tagID;
        public DateTime time;
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public byte Addr
        {
            get
            {
                try
                {
                    return byte.Parse(textBoxReadID.Text);
                }
                catch
                {
                    return 0;
                }
            }
        }
        byte[] mysendBuf = new byte[50];
        byte[] myrevBuf = new byte[6000];
        SerialPort myport = new SerialPort();
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBoxSerial.SelectedIndex = 0;
            comboBoxBaudrate.SelectedIndex = 4;
        }
        #region 串口类
        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            OpenPort();
        }


        #region 打开串口
        public void OpenPort()
        {
            if (myport.IsOpen)
            {

                myport.Close();//打开时点击,则关闭串口 
            }
            else
            {

                myport.PortName = comboBoxSerial.Text;//关闭时点击,则设置好端口,波特率后打开 
                myport.BaudRate = int.Parse(comboBoxBaudrate.Text);
                try
                {
                    myport.Open();
                }
                catch (Exception ex)
                {
                    //捕获到异常信息,创建一个新的comm对象,之前的不能用了。   
                    myport = new SerialPort();
                    //现实异常信息给客户。   
                    MessageBox.Show(ex.Message);
                }
            }
            //设置按钮的状态   
            btnOpenPort.Text = myport.IsOpen ? "关闭" : "打开";
        }


        private void comboBoxBaudrate_SelectionChangeCommitted(object sender, EventArgs e)
        {
            myport.Close();
            btnOpenPort.Text = "打开";
        }
        #endregion
        private void btninfo_Click_1(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {

                readid();
                readDB();
                textBoxBaudrate.Text = comboBoxBaudrate.Text;

            }
        }
        #region 参数读取方法
        private void readDB()
        {
            byte addr = Addr;
            mysendBuf[0] = addr;
            mysendBuf[1] = 0x04;
            mysendBuf[2] = 0x4c;
            mysendBuf[3] = 0x03;
            try
            {
                myport.DiscardInBuffer();
                myport.DiscardOutBuffer();
                myport.Write(mysendBuf, 0, 4);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            for (int i = 0; i < 10; i++)
            {
                if (myport.BytesToRead >= 6)
                {
                    myport.Read(myrevBuf, 0, 6);

                    if (myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[2] == addr && myrevBuf[4] == 0xEE && myrevBuf[5] == 0xEE)
                    {
                        textBoxReaderDB.Text = myrevBuf[3].ToString();
                    }
                    break;
                }
                System.Threading.Thread.Sleep(50);

            }
        }

        private void readid()
        {
            mysendBuf[0] = 0xFF;
            mysendBuf[1] = 0xFF;
            mysendBuf[2] = 0x08;
            mysendBuf[3] = 0xEE;
            mysendBuf[4] = 0xEE;
            try
            {
                myport.DiscardInBuffer();
                myport.DiscardOutBuffer();
                myport.Write(mysendBuf, 0, 5);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            for (int i = 0; i < 10; i++)
            {
                if (myport.BytesToRead >= 5)
                {
                    myport.Read(myrevBuf, 0, 5);

                    if (myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[3] == 0xEE && myrevBuf[4] == 0xEE)
                        textBoxReadID.Text = myrevBuf[2].ToString();

                    break;
                }
                System.Threading.Thread.Sleep(50);
            }
        }

        #endregion
        private void btnSetReadID_Click(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {
                byte addr = Addr;
                byte newaddr = 1;
                try
                {
                    newaddr = byte.Parse(textBoxSetReadID.Text.Trim());
                    if (newaddr <= 0 || newaddr > 127)
                    {
                        MessageBox.Show("读卡器地址超出字节范围( 0 < 读卡器地址 < 128 )", "警告提示");
                        textBoxSetReadID.Text = "";
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("您要设置的读卡器地址格式错误!", "提示");
                }
                mysendBuf[0] = addr;
                mysendBuf[1] = 0x05;
                mysendBuf[2] = 0xc8;
                mysendBuf[3] = newaddr;
                mysendBuf[4] = 0x03;
                try
                {
                    myport.DiscardInBuffer();
                    myport.DiscardOutBuffer();
                    myport.Write(mysendBuf, 0, 5);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                for (int i = 0; i < 10; i++)
                {
                    if (myport.BytesToRead >= 5)
                    {
                        myport.Read(myrevBuf, 0, 5);
                        if (myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[3] == 0xEE && myrevBuf[4] == 0xEE)
                        {
                            myrevBuf[0] = myrevBuf[3];
                            textBoxReadID.Text = myrevBuf[0].ToString();
                        }
                        break;
                    }
                    System.Threading.Thread.Sleep(50);
                }
                readid();
                textBoxRaw.Text = "";
                textBoxRaw.Text += string.Format("地址  设为:{0}\r\n", myrevBuf[2]);
                textBoxSetReadID.Text = "";
                dataSetTest.DataTable.Clear();
            }
        }

        private void btnSetReadDB_Click(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {
                byte addr = Addr;
                byte stdb = 0;
                try
                {
                    stdb = byte.Parse(textBoxSetReadDB.Text.Trim());
                    if (stdb < 0 || stdb > 31)
                    {
                        MessageBox.Show("衰减值超出限定范围( 0 = 衰减值 < 32 )", "警告提示");
                        textBoxSetReadDB.Text = "";
                        return;
                    }
                }
                catch
                {
                    MessageBox.Show("您要设置的衰减值格式错误!", "提示");
                }

                mysendBuf[0] = addr;
                mysendBuf[1] = 0x05;
                mysendBuf[2] = 0xcc;
                mysendBuf[3] = stdb;
                mysendBuf[4] = 0x03;
                try
                {
                    myport.DiscardInBuffer();
                    myport.DiscardOutBuffer();
                    myport.Write(mysendBuf, 0, 5);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                for (int i = 0; i < 10; i++)
                {
                    if (myport.BytesToRead >= 6)
                    {
                        myport.Read(myrevBuf, 0, 6);
                        if (myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[4] == 0xEE && myrevBuf[5] == 0xEE)
                        {
                            textBoxSetReadDB.Text = myrevBuf[3].ToString();
                        }
                        break;
                    }
                    System.Threading.Thread.Sleep(50);
                }
                readDB();
                textBoxRaw.Text = string.Format("衰减值  设为:{0}\r\n", myrevBuf[3]);
                textBoxSetReadDB.Text = "";
                dataSetTest.DataTable.Clear();
            }
        }

        private void btnSetBaudrate_Click(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {
                if (comboBoxBuzzer.Text == "" || comboBoxBuzzer.Text == "开")
                {
                    MessageBox.Show("先关闭蜂鸣器", "操作提示");
                }
                else
                {
                    MessageBox.Show("你确定要更改 波特率 吗?", "警告提示");
                    byte addr = Addr;
                    byte baud = (byte)(comboBoxSetBaudrate.SelectedIndex);
                    mysendBuf[0] = addr;
                    mysendBuf[1] = 0x05;
                    mysendBuf[2] = 0xc9;
                    mysendBuf[3] = baud;
                    mysendBuf[4] = 0x03;
                    myport.DiscardInBuffer();
                    myport.DiscardOutBuffer();
                    myport.Write(mysendBuf, 0, 5);
                    for (int i = 0; i < 10; i++)
                    {
                        if (myport.BytesToRead >= 6)
                        {
                            myport.Read(mysendBuf, 0, 6);
                            if (myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[3] == baud && myrevBuf[4] == 0xEE && myrevBuf[5] == 0xEE) { }
                        }
                    }
                    textBoxBaudrate.Text = comboBoxBaudrate.Text = comboBoxSetBaudrate.Text;
                    OpenPort();
                    OpenPort();
                    textBoxRaw.Text = "\r波特率 设为:" + comboBoxBaudrate.Text;
                    dataSetTest.DataTable.Clear();

                }
            }
        }

        private void btnBuzzerNF_Click(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {
                Buzzer();

            }
            textBoxRaw.Text = "\r蜂鸣器 状态:" + comboBoxBuzzer.Text;
        }

        private void Buzzer()
        {
            byte addr = Addr;
            mysendBuf[0] = addr;
            mysendBuf[1] = 0x05;
            mysendBuf[2] = 0xcd;
            mysendBuf[3] = (byte)(comboBoxBuzzer.SelectedIndex);
            mysendBuf[4] = 0x03;

            myport.DiscardInBuffer();
            myport.DiscardOutBuffer();
            myport.Write(mysendBuf, 0, 5);

            for (int i = 0; i < 10; i++)
            {
                if (myport.BytesToRead >= 6)
                {
                    myport.Read(mysendBuf, 0, 6);
                    if (myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[4] == 0xEE && myrevBuf[5] == 0xEE) { }
                }
            }
        }
        #endregion
        private void btnRead_Click(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {
                dataSetTest.DataTable.Clear();
                textBoxRaw.Text = "";
                byte addr = Addr;
                mysendBuf[0] = addr;
                mysendBuf[1] = 4;
                mysendBuf[2] = 1;
                mysendBuf[3] = 3;
                myport.DiscardInBuffer();
                myport.DiscardOutBuffer();
                myport.Write(mysendBuf, 0, 4);
                readOld(addr);
            }
        }
        #region 读取
        private void readOld(byte addr)
        {
            int revLength = 0;
            for (int i = 0; i < 100; i++)
            {
                int btr = myport.BytesToRead;
                if (btr > 0)
                {
                    int num = myport.Read(myrevBuf, revLength, btr);
 /*=====================================================================*/
                    string strData = "";//
                    for (int j = revLength; j < revLength + num; j++)//
                    {
                        strData += string.Format("{0:X2}   ", myrevBuf[j]);//
                    }
                    revLength += num;//
                    textBoxRaw.Text += strData;//
/*=====================================================================*/         
                    if (revLength >= 6 && myrevBuf[0] == 0xFF && myrevBuf[1] == 0xFF && myrevBuf[revLength - 2] == 0xEE && myrevBuf[revLength - 1] == 0xEE)
                    {
                        #region 2字节
                        if (rbtn2.Checked)
                        {
                            if ((revLength - 6) % 2 == 0)
                            {
                                for (int j = 4; j < revLength - 2; j += 2)
                                {
                                    string adr = addr.ToString();
                                    string volt = (myrevBuf[j] & 0x80) == 0 ? "正常" : "欠压";
                                    string tagID = Convert.ToString(((myrevBuf[j] & 0x7F) << 8) | myrevBuf[j + 1]);
                                    string b2 = (revLength - 6) % 2 == 0 ? "2" : "非2字节";
                                    DateTime nowTime = DateTime.Now;
                                    dataSetTest.DataTable.AddDataTableRow(adr, tagID, b2.ToString(), volt, nowTime.ToString());
                                }
                            }
                            else
                            {
                                MessageBox.Show("2字节读取数据出现错误", "信息提示");
                            }
                        }
                        #endregion
                        #region 5字节
                        else if (rbtn5.Checked)
                        {
                            if ((revLength - 6) % 5 == 0)
                            {
                                for (int j = 4; j < revLength - 5; j += 5)
                                {
                                    string adr = addr.ToString();
                                    string volt = (myrevBuf[j] & 0x80) == 0 ? "正常" : "欠压";
                                    UInt32 tagID = myrevBuf[j + 1];
                                    tagID <<= 8;
                                    tagID |= myrevBuf[j + 2];
                                    tagID <<= 8;
                                    tagID |= myrevBuf[j + 3];
                                    tagID <<= 8;
                                    tagID |= myrevBuf[j + 4];
                                    string strtagID = Convert.ToString(tagID);
                                    string b5 = (revLength - 6) % 5 == 0 ? "5" : "非5字节";
                                    DateTime nowTime = DateTime.Now;
                                    dataSetTest.DataTable.AddDataTableRow(adr, strtagID, b5.ToString(), volt, nowTime.ToString());
                                }
                            }

                            else
                            {
                                MessageBox.Show("5字节读取数据出现错误", "信息提示");
                            }
                        }
                        #endregion
                        #region 内容
                        else
                        {
                            MessageBox.Show("请先选择读取数据的字节格式!", "信息提示");
                        }
                        label13.Text = dataSetTest.DataTable.Count.ToString();
                        break;
                        #endregion
                    }
                }
                System.Threading.Thread.Sleep(50);
            }
        }
        #endregion
        private void 导出数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        #region 导出数据
        private void ExportToExcel()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl Files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "保存为Excel文件";
            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"

            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string columnTitle = "";
            try
            {
                //写入列标题
                for (int i = 0; i < dataGridViewX1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        columnTitle += "\t";
                    }
                    columnTitle += dataGridViewX1.Columns[i].HeaderText;
                }
                sw.WriteLine(columnTitle);

                //写入列内容
                for (int j = 0; j < dataGridViewX1.Rows.Count; j++)
                {
                    string columnValue = "";
                    for (int k = 0; k < dataGridViewX1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            columnValue += "\t";
                        }
                        if (dataGridViewX1.Rows[j].Cells[k].Value == null)
                            columnValue += "";
                        else
                            columnValue += dataGridViewX1.Rows[j].Cells[k].Value.ToString().Trim();
                    }
                    sw.WriteLine(columnValue);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }
        #endregion

        private void btnClear_Click(object sender, EventArgs e)
        {
            if (!myport.IsOpen)
            {
                MessageBox.Show("请先打开串口!");
            }
            else
            {
                byte addr = Addr;
                if (addr == 0)
                {
                    MessageBox.Show("您输入的读卡器地址格式错误", "提示信息");
                    return;
                }
                mysendBuf[0] = addr;
                mysendBuf[1] = 0x04;
                mysendBuf[2] = 0x02;
                mysendBuf[3] = 0x03;
                myport.DiscardInBuffer();
                myport.DiscardOutBuffer();
                myport.Write(mysendBuf, 0, 4);
                dataSetTest.DataTable.Clear();
                textBoxRaw.Text = "";
            }
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataSetTest.DataTable.Clear();
        }

        private void 清空ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            textBoxRaw.Text = "";
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值