日期:2014-05-18 浏览次数:20883 次
private Queue<string> RobotBy = new Queue<string>(); // received data . robot private bool SendDataToRobot(string DataStr) { bool rut = false; string sendDataFormat; try { if (!serialPort_Robot.IsOpen) { string portName = System.IO.Ports.SerialPort.GetPortNames().Where(pName => (pName == serialPort_Robot.PortName)).First(); if (string.IsNullOrEmpty(portName)) { WriteLog(string.Format("port '{0}' is denied", serialPort_Robot.PortName)); throw new Exception(string.Format("port '{0}' is denied", serialPort_Robot.PortName)); } serialPort_Robot.Open(); } } catch (Exception err) { WriteLog(string.Format("Open Robot Port Exception Message:{0}", err.Message)); throw new Exception(err.Message); } if (serialPort_Robot.IsOpen && !!string.IsNullOrEmpty(DataStr)) { try{ serialPort_Robot.DiscardOutBuffer(); byte[] buf = Encoding.ASCII.GetBytes(DataStr.ToString()); serialPort_Robot.Write(buf, 0, buf.Length); }catch(Exception e) { throw new Exception("Write Data to Robot Error,message:"+ e.Message); } } } public MainForm() { serialPort_Robot.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.SerialPort_RobotDataReceived); } private void SerialPort_RobotDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { RobotBy.Enqueue(serialPort_Robot.ReadTo("\x001a")); serialPort_Robot.Close(); } catch (IOException se) { WriteLog(string.Format( "Robot receivedata {0} : The write operation could not be performed because the specified part of the file is locked.", se.GetType().Name) ); } }