C#实现串口监听(以中盛来电显示盒为例)

来源:互联网 发布:文泰刻绘2009软件安装 编辑:程序博客网 时间:2024/06/07 08:42

C#实现串口监听(以中盛来电显示盒为例)

 

 

中盛来电显示盒(DTMF/FSK双制式)设备可靠,接口简单规范,编程处理非常容易,所以这里以该设备为例介绍一下C#串口监听的编程。该设备深受广大程序员喜爱,订餐、订票订房、企业客服等行业多有使用。

中盛来电显示盒(DTMF/FSK双制式)的原理:当有电话打进时,来电显示盒自动上传号码数据到电脑,接口格式为:/r/nNUM=0108888888/r/n/r/nOK/r/n。所以串口监听事件中,需要将接收的字符追加到一全局字符串变量中,并判断该字符串变量是否包含/r/nOK/r/n,当/r/nOK/r/n来到时,说明串口已经接收完全部数据,此时处理接收到的字符串,从数据库查找该号码记录即可。

 

Visual Stdio 2005,对于串口操作Framework提供了一个很好的类接口-SerialPort,在这当中,串口数据的读取与写入有较大的不同。由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取。

1、用线程实时读串口

2、用事件触发方式实现。

   但由于线程实时读串口的效率不是十分高效,因此比较好的方法是事件触发的方式。在SerialPort类中有DataReceived事件,当串口的读缓存有数据到达时则触发DataReceived事件,其中SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1

   此外,SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现。

一、创建WIndow项目,设计界面:

上图界面中各组件名称:端口号:tbID,波特率:cmRate,监听:btENT,暂停:BtPause,数据:tbData

二、实现代码:

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;

 

namespace CidDemo

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private SerialPort Sp = new SerialPort();

        public delegate void HandleInterfaceUpdataDelegate(string text);

        private HandleInterfaceUpdataDelegate interfaceUpdataHandle;

        private string CidNum = "";//定义一个全局变量,存放接收到的字符串;

 

        private void Form1_Load(object sender, EventArgs e)

        {

            tbID.Focus();

            BtPause.Enabled = false;           

        }

 

        private void UpdateTextBox(string text)

        {           

            CidNum = CidNum + text.TrimEnd('/0');//接收到的字符串加到全局变量中。          

            if (CidNum.IndexOf("/r/nOK/r/n") != -1)

            {

tbData.AppendText("接收到的号码字符串是:" + CidNum);

                CidNum = "";//清字符串,等待下次接收。

            }

        }

 

        public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

        {

            byte[] readBuffer = new byte[Sp.ReadBufferSize];

            //readBuffer数组长度,转换成字符串长度也是,所以使用该字符串时需要将后面的/0全部trim掉。          

            Sp.Read(readBuffer, 0, readBuffer.Length);

            this.Invoke(interfaceUpdataHandle, new object[] { Encoding.UTF8.GetString(readBuffer) });

        }

 

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)

        {

            Sp.Close();

        }

 

        private void btENT_Click(object sender, EventArgs e)

        {

            if ((tbID.Text.Trim() != "") && (cmRate.Text != ""))

            {

                interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象

                Sp.PortName = tbID.Text.Trim();

                Sp.BaudRate = Convert.ToInt32(cmRate.Text.Trim());

                Sp.Parity = Parity.None;

                Sp.StopBits = StopBits.One;               

                Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);

                Sp.ReceivedBytesThreshold = 1;

                try

                {

                    Sp.Open();

                    tbID.ReadOnly = true;

                    BtPause.Enabled = true;

                    btENT.Enabled = false;

                }

                catch

                {

                    MessageBox.Show("端口" + tbID.Text.Trim() + "打开失败!");

                }

            }

            else

            {

                MessageBox.Show("请输入正确的端口号和波特率!");

                tbID.Focus();

            }

        }

 

        private void BtPause_Click(object sender, EventArgs e)

        {

            Sp.Close();

            tbID.ReadOnly = false;

            btENT.Enabled = true;

            BtPause.Enabled = false;

        }

       

    }

}

 

说明:本文大部分引自http://blog.csdn.net/zh2305/archive/2008/01/12/2039372.aspx,只修改了接收字符串的处理函数。

 

 

 

原创粉丝点击