在第一版 使用C# 實現串口撥號器的SIM卡通信 的代碼中,存在一些實際的問題,經過反復測試和實際使用,對原代碼進行了一些改進。
首先,博客園的ㄟ荖樹炪厊ㄖ同學提出將撥號指令ATD發出后,不必使用 Thread.Sleep(20 * 1000) 方法等待20秒后進行掛機,而改用AutoResetEvent來處理,不必讓線程死等,也能提高你程序的性能。但修改后效果並不理想,還是使用Thread.Sleep(20 * 1000) 方法快捷實用。
其次,由於撥號器以及服務器等硬件設備的差異,導致反饋信息的速度不一致,以前采用Thread.Sleep() 方法綁定固定秒數然后查看返回信息的方式存在一定的問題,改用如下代碼就行:
int i = 0; while (read.Trim() == "" && i <15) { Thread.Sleep(100); i++; } if (read.Contains("ATH") && read.Contains("OK")) { ...... }
其余的不詳細介紹,看代碼即可。
MySerialPort 類
對每一個連接到COM 串行端口的撥號器實例化 MySerialPort 對象,代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Threading; namespace Con_SerialPortExample { public class MySerialPort { private SerialPort com; public MySerialPort(string _portName) { this.com = new SerialPort(); //this.autoResetEvent_HasModem = new AutoResetEvent(true); //this.autoResetEvent_Dialing = new AutoResetEvent(false); //接收數據事件 this.com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived); //串口名 com.PortName = _portName; this.PortName = _portName; // BaudRate 串行波特率 com.BaudRate = 9600; //默認值 // 是否啟用請求發送 (RTS) 信號。 com.RtsEnable = true; //由計算機發送 Request To Send 信號到聯接的調制解調器,以請示允許發送數據。 // 是否使Data Terminal Ready (DTR)線有效。 xugang 2012.8.20 添加 //com.DtrEnable = true; //Data Terminal Ready 是計算機發送到調制解調器的信號,指示計算機在等待接受傳輸。 try { com.Open(); } catch //(Exception) { Close(); } } public MySerialPort(string _portName, int _baudRate) : this(_portName) { if (_baudRate != 0) { // BaudRate 串行波特率 com.BaudRate = _baudRate; } } private string portName; //串口名稱 public string PortName { get { return portName; } set { portName = value; } } // BaudRate 串行波特率 public int BaudRate { get { return com.BaudRate; } set { com.BaudRate = value; } } private bool isWorking; //設置是否正在使用 public bool IsWorking { get { return isWorking; } set { isWorking = value; } } //private enum AutoResetEvent_Type //{ // None, HasModem, Dialing //} //private AutoResetEvent autoResetEvent_HasModem; //private AutoResetEvent autoResetEvent_Dialing; //private AutoResetEvent_Type autoResetEvent_Type = AutoResetEvent_Type.None; //private bool enableUse; private DateTime lastUseTime = DateTime.MinValue; //當前撥號器能否使用 (解決連續使用撥號問題) public bool EnableUse { get { TimeSpan span = DateTime.Now - lastUseTime; return span.TotalSeconds >= 60; } //set { enableUse = value; } } // 檢測當前端口是否安裝有撥號器 public bool HasModem() { //this.autoResetEvent_Type = AutoResetEvent_Type.HasModem; //read = ""; //清空返回緩沖區 WriteSerial("AT\r\n"); //Thread.Sleep(500); //this.autoResetEvent_HasModem.WaitOne(5 * 1000); //this.autoResetEvent_Type = AutoResetEvent_Type.None; int i = 0; while (read.Trim() == "" && i < 40) { Thread.Sleep(100); i++; } Console.WriteLine(read.TrimEnd('\r', '\n')); //Console.Write(read); //if (read.Contains("AT") && read.Contains("OK")) if (read.Contains("OK")) { Console.WriteLine(this.com.PortName + "端口能使用!"); return true; } else { Console.WriteLine(this.com.PortName + "端口無法使用!"); return false; } } //進行撥號,喚醒上位機 public void Dialing(string _SIM) { IsWorking = true; //正在撥號 try { //this.autoResetEvent_Type = AutoResetEvent_Type.Dialing; read = ""; //清空返回緩沖區 StringBuilder sb = new StringBuilder(36); sb.Append(this.com.PortName); sb.Append("端口開始對SIM卡:"); sb.Append(_SIM); sb.Append(" 進行撥號..."); Console.WriteLine(sb.ToString()); WriteSerial(string.Format("ATD{0};\r\n", _SIM)); System.Threading.Thread.Sleep(20 * 1000); //this.autoResetEvent_Dialing.WaitOne(20 * 1000); //this.autoResetEvent_Type = AutoResetEvent_Type.None; read = ""; //清空返回緩沖區 WriteSerial("ATH\r\n"); //this.autoResetEvent.WaitOne(1000); int i = 0; while (read.Trim() == "" && i <15) { Thread.Sleep(100); i++; } Console.WriteLine(read); if (read.Contains("ATH") && read.Contains("OK")) { Console.WriteLine(this.com.PortName + "端口撥號已完成!"); } else { read = ""; //清空返回緩沖區 //System.Threading.Thread.Sleep(1000); WriteSerial("ATH\r\n"); //this.autoResetEvent.WaitOne(1000); i = 0; while (read.Trim() == "" && i < 20) { Thread.Sleep(100); i++; } Console.WriteLine(read); if (read.Contains("ATH") && read.Contains("OK")) { Console.WriteLine(this.com.PortName + "端口撥號已完成!"); } else { //IsWorking = false; //撥號完成 string strExc = this.com.PortName + "撥號異常!"; Console.WriteLine(strExc); throw new Exception(strExc); } } } catch (Exception ex) { throw ex; } finally { IsWorking = false; //撥號完成 } } /// <summary> /// 向串口端發送命令! /// </summary> /// <param name="s">命令字符串</param> private void WriteSerial(string s) { //this.autoResetEvent_HasModem.WaitOne(20*1000); //mLogger.Info(s); byte[] buff = Encoding.ASCII.GetBytes(s); try { this.com.Write(buff, 0, buff.Length); } catch (Exception ex) { //WriteExecLog.Writing(ex); Console.WriteLine(ex.Message); } } //int n = 0; string read = ""; //接收數據事件方法 void com_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (sender is SerialPort) { try { Thread.Sleep(500); read = ""; //清空返回緩沖區 SerialPort mySerial = sender as SerialPort; if (mySerial.IsOpen == false) { mySerial.Open(); } //方法一 //read += mySerial.ReadLine().Trim(); //Console.WriteLine(mySerial.PortName + " 第" + n.ToString() + "接收數據:" + read); //方法二 byte[] readBuffer = new byte[1024]; int count = mySerial.Read(readBuffer, 0, 1023); if (count > 0) { read = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count); //Console.WriteLine(read); } //AT 返回 //if (autoResetEvent_Type == AutoResetEvent_Type.HasModem // && read.Contains("OK")) //{ // this.autoResetEvent_HasModem.Set(); //} //ATD 返回 //if (autoResetEvent_Type == AutoResetEvent_Type.Dialing // && (read.Contains("ERROR") || read.Contains("BUSY") || read.Contains("OK") || read.Contains("NO CARRIER")) // ) //{ // this.autoResetEvent_Dialing.Set(); //} } catch (TimeoutException) { return; //xg備忘:可以將異常寫入日志! } catch (Exception) { return; //xg備忘:可以將異常寫入日志! } //finally //{ // this.autoResetEvent_HasModem.Set(); //} } } //private string ReadSerial() //{ // while (_keepReading) // { // if (com.IsOpen) // { // //byte[] readBuffer = new byte[com.ReadBufferSize + 1]; // byte[] readBuffer = new byte[10]; // try // { // //int count = com.Read(readBuffer, 0, com.ReadBufferSize); // int count = com.Read(readBuffer, 0, 9); // String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count); // if (count != 0) // { // return SerialIn; // } // } // catch (TimeoutException) // { // return ""; // } // } // else // { // TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50); // Thread.Sleep(waitTime); // } // } // return ""; //} //關閉 public void Close() { if (com != null) { com.Close(); com.Dispose(); } } } }
SerialPortList 類
定義一個 SerialPortList 類,實現對所有連接上的撥號器 MySerialPort 對象進行管理和調度使用。代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO.Ports; using System.Threading; namespace Con_SerialPortExample { public class SerialPortList { //已經安裝了撥號器的串口對象 private List<MySerialPort> al = null; //可使用的撥號器個數 public int WorkableCount { get { if (al == null) return 0; else return al.Count; } } private Dictionary<string, int> portBaudRate = null; //波特率配置列表 public Dictionary<string, int> PortBaudRate { get { return portBaudRate; } set { portBaudRate = value; } } private bool hasPort = false; //當前有無可使用的串口撥號器 public bool HasPort { get { return hasPort; } //set { hasPort = value; } } private int reCheckMinutes = 30; //默認30分鍾 //串口撥號器的重新檢測間隔分鍾 public int ReCheckMinutes { get { return reCheckMinutes; } set { reCheckMinutes = value; } } #region 構造方法重載 public SerialPortList() { } public SerialPortList(Dictionary<string, int> _portBaudRate) { this.portBaudRate = _portBaudRate; } public SerialPortList(int _reCheckMinutes) { this.reCheckMinutes = _reCheckMinutes; } public SerialPortList(Dictionary<string, int> _portBaudRate, int _reCheckMinutes) { this.portBaudRate = _portBaudRate; this.reCheckMinutes = _reCheckMinutes; } #endregion 構造方法重載 /// <summary> /// 獲得串口上已經安裝了撥號器的對象 /// </summary> public void GetSerialPortList() { al = new List<MySerialPort>(); //步驟一: 獲得所有的串口名稱(列表) string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { MySerialPort mySerialPort = null; Console.WriteLine("正在檢測:" + port); //測試使用 //是否設置波特率? if (portBaudRate != null && portBaudRate.ContainsKey(port) && portBaudRate[port] != 0) { mySerialPort = new MySerialPort(port, portBaudRate[port]); } else mySerialPort = new MySerialPort(port); bool ok = mySerialPort.HasModem(); if (ok) { al.Add(mySerialPort); } else { mySerialPort.Close(); mySerialPort = null; } } // 判斷當前計算機有無可使用串口端 hasPort = al.Count <= 0 ? false : true; } /// <summary> /// 重新獲得串口上已經安裝了撥號器的對象 /// </summary> public void ReGetSerialPortList() { if (al == null) GetSerialPortList(); else { //步驟一: 重新獲得所有的串口名稱(列表) string[] portsName_2 = SerialPort.GetPortNames(); //如果當前串口數目 > 正在使用的COM if (portsName_2.Length > al.Count) { Console.WriteLine("正在重新檢測可以使用的撥號器!"); //測試使用 foreach (string pName_2 in portsName_2) { //當前串口名是否存在撥號列表中 bool hasAt = al.Exists(delegate(MySerialPort port_1) { return pName_2 == port_1.PortName; }); //如果當前串口名不存在撥號列表中,則重新檢測! if (!hasAt) { Console.WriteLine("正在重新檢測:" + pName_2); //測試使用 MySerialPort mySerialPort = null; //是否設置波特率? if (portBaudRate != null && portBaudRate.ContainsKey(pName_2) && portBaudRate[pName_2] != 0) { mySerialPort = new MySerialPort(pName_2, portBaudRate[pName_2]); } else mySerialPort = new MySerialPort(pName_2); bool ok = mySerialPort.HasModem(); if (ok) { al.Add(mySerialPort); } else { mySerialPort.Close(); mySerialPort = null; } } } } } // 判斷當前計算機有無可使用串口端 hasPort = al.Count <= 0 ? false : true; } /// <summary> /// 重新獲得串口上已經安裝了撥號器的對象 (波特率使用默認值) /// </summary> public void ReGetSerialPortList(int _reCheckMinutes) { //串口撥號器的重新檢測間隔分鍾 reCheckMinutes = _reCheckMinutes; ReGetSerialPortList();//波特率全部使用默認值 } /// <summary> /// 釋放所有串口資源組件 /// </summary> public void ClearAllSerialPort() { if (al != null) { for (int i = 0; i < al.Count; i++) { al[i].Close(); al[i] = null; } al = null; } if (portBaudRate != null) { portBaudRate = null; } } private int index_Number = -1; //串口的調度號 private int IndexNumber() { lock (this) { if (index_Number + 1 >= al.Count) { if (al.Count == 0) index_Number = -1; else index_Number = 0; } else { index_Number++; } return index_Number; } } /// <summary> /// 對已經安裝了撥號器的串口調度使用 /// </summary> private void UseingSerialPort(string _SIM) { if (al == null) return; // 等待線程進入 Monitor.Enter(al); MySerialPort getPort = null; try { //獲得當前調用的串口對象的索引號 int num = IndexNumber(); if (num >= 0) //判斷是否存在撥號器 { getPort = al[num]; if (getPort != null && !getPort.IsWorking) { getPort.Dialing(_SIM); //對 SIM 進行撥號,喚醒上位機 } } else { //沒有可使用的撥號器,則重新檢測。 this.ReGetSerialPortList(); } } catch { //再一次檢查該 COM 能否使用! (范工提議) if (getPort != null) { string re_PortName = getPort.PortName; al.Remove(getPort); //從可用列表去除 getPort.Close(); MySerialPort mySerialPort = new MySerialPort(re_PortName); bool ok = mySerialPort.HasModem(); if (ok) { al.Add(mySerialPort); //重新添加到列表 } else { mySerialPort.Close(); mySerialPort = null; } } } finally { // 通知其它對象 Monitor.Pulse(al); // 釋放對象鎖 Monitor.Exit(al); } } //重新檢測端口時間 private DateTime dtCheck = DateTime.Now; /// <summary> /// 調用撥號器 /// </summary> /// <param name="_SIM"></param> public void InvokingSerialPort(string _SIM) { if (hasPort == false) { // 獲得串口上已經安裝了撥號器的對象 this.GetSerialPortList(); } if (hasPort == true) { this.UseingSerialPort(_SIM); //Thread.Sleep(5000); } //定期檢測串口列表 //if (dtCheck.AddMinutes(reCheckMinutes) <= DateTime.Now) if (dtCheck.AddMinutes(5) <= DateTime.Now) { // 重新獲得串口上已經安裝了撥號器的對象 this.ReGetSerialPortList(); dtCheck = DateTime.Now; } } } }
測試代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; // //using System.IO.Ports; using System.Threading; //using System.Collections; namespace Con_SerialPortExample { class Program { static void Main(string[] args) { // 獲得串口上已經安裝了撥號器的對象 (自定義波特率) Dictionary<string, int> _portBaudRate = new Dictionary<string, int>(); _portBaudRate["COM1"] = 9600; _portBaudRate["COM2"] = 9600; _portBaudRate["COM7"] = 9600; SerialPortList list = new SerialPortList(_portBaudRate,5); try { // 獲得串口上已經安裝了撥號器的對象 list.GetSerialPortList(); if (list.HasPort == false) { Console.WriteLine("當前計算機無可使用的串口撥號器!"); } while (list.HasPort) { // 調用撥號器 list.InvokingSerialPort("13500000000"); Thread.Sleep(5000); } Console.WriteLine("程序運行結束!"); } finally { // 釋放所有串口資源組件 list.ClearAllSerialPort(); } Console.ReadLine(); } } }