public static bool Connect(string strCom, int nBaudrate) { SerialPortUtil serialPort; try { string[] coms = SerialPortUtil.GetComList(); if (!coms.Contains(strCom)) { string str = string.Format("未找到串口:{0}", strCom); PrintLog.LogText(string.Format(str)); #if TEST OutputDebugString(str); #endif return(false); } if (dictionarySerialPort.ContainsKey(strCom)) { serialPort = dictionarySerialPort[strCom]; } else { serialPort = new SerialPortUtil(strCom, nBaudrate.ToString(), "0", "8", "1"); dictionarySerialPort.Add(strCom, serialPort); } serialPort.OpenPort(); } catch { return(false); } if (serialPort.IsOpen) { return(true); } else { return(false); } }
public static string SendCMDStrToController(byte[] bytes, string strCom, int nBaudrate, int nCount = 0, int nOffset = 0) { SerialPortUtil serialPort; if (strCom == null) { return(null); } try { lock (ojbSend) { //1.初始化串口 if (false == InitSerialPort(strCom, out serialPort, nBaudrate)) { return(null); } serialPort.DiscardBuffer(); //2.发送数据 string strSendCMD = Encoding.ASCII.GetString(bytes, 0, bytes.Length); PrintLog.LogText(string.Format("{0} Send: {1}", strCom, strSendCMD)); readstring = string.Empty; //清空接收缓冲区 Thread SendCmdToControllerThread = new Thread(() => { try { if (!serialPort.IsOpen) { serialPort.OpenPort(); } #if TEST #else serialPort.DataReceived += new DataReceivedEventHandler(serialPort_DataReceived); #endif readstring = string.Empty; //写数据 if (nCount == 0 && nOffset == 0) { serialPort.WriteData(bytes); } else { serialPort.WriteData(bytes, nOffset, nCount); } } catch (Exception ex) { if (serialPort != null && serialPort.IsOpen) //关闭端口 { serialPort.ClosePort(); } dictionarySerialPort.Remove(strCom); serialPort = null; } finally { if (serialPort != null) { if (serialPort.IsOpen == true) { serialPort.ClosePort(); } } serialPort = null; } }); SendCmdToControllerThread.IsBackground = true; SendCmdToControllerThread.Start(); //根据命令与底层控制器之间的繁忙时间,适当增加延时,一般不用 ReceiveDataTimeOut(bytes); //回读数据超时,已经等到数据,返回 if (string.Empty == readstring) { return(null); } PrintLog.LogText(string.Format("{0} Receive :{1}", strCom, readstring)); } } catch (System.ArgumentNullException ex) { PrintLog.LogText(string.Format("{0} Receive Error: ArgumentNullException", strCom)); return(null); } catch (Exception e) { PrintLog.LogText(string.Format("{0} Receive Error: Exception", strCom)); return(null); } return(readstring); }