/// <summary> /// 发送命令 /// </summary> /// <param name="SendData">发送数据</param> /// <param name="ReceiveData">接收数据</param> /// <param name="Overtime">超时时间</param> /// <returns></returns> public int SendCommand(byte[] SendData, ref byte[] ReceiveData, int Overtime) { if (_seriaPort.IsOpen) { try { _seriaPort.WriteTimeout = 3000; ReceiveEventFlag = true; //关闭接收事件 _seriaPort.DiscardInBuffer(); //清空接收缓冲区 _seriaPort.Write(SendData, 0, SendData.Length); if (SCEEC.Data.Logger.log != null) { SCEEC.Data.Logger.log.Info("Send:" + XmlConfig.GetBytestring(SendData)); } int num = 0, ret = 0; System.Threading.Thread.Sleep(10); ReceiveEventFlag = false;//打开事件 while (num++ < Overtime) { if (_seriaPort.BytesToRead >= ReceiveData.Length) { break; } System.Threading.Thread.Sleep(10); } if (_seriaPort.BytesToRead >= ReceiveData.Length) { ret = _seriaPort.Read(ReceiveData, 0, ReceiveData.Length); } else { _seriaPort.Write(new byte[] { 0x01, 0x00, 0x01 }, 0, 3); ret = _seriaPort.Read(ReceiveData, 0, _seriaPort.BytesToRead); } if (SCEEC.Data.Logger.log != null) { SCEEC.Data.Logger.log.Info("Rec:" + XmlConfig.GetBytestring(ReceiveData)); } return(ret); } catch { // throw ex; _seriaPort.Open(); } } return(-1); }
/// <summary> /// 读取长数据>4092 /// </summary> /// <param name="SendData">发送指令</param> /// <param name="RecData">接受数组</param> /// <param name="RecDataLength">需要接受数据的长度</param> /// <param name="Timeout">超时时间</param> /// <returns></returns> public byte[] ReadPortsData(byte[] SendData, byte[] RecData, int RecDataLength, int Timeout) { byte[] q = new byte[4] { 0x5e, 0x14, 0x07, 0xc0 }; float b = BitConverter.ToSingle(q, 0); if (_seriaPort.IsOpen) { ReceiveEventFlag = true; //关闭接收事件 _seriaPort.DiscardInBuffer(); //清空接收缓冲区 Thread.Sleep(10); _seriaPort.DiscardInBuffer(); //清空接收缓冲区 if (SendData.Length != 0) { _seriaPort.Write(SendData, 0, SendData.Length); } if (SCEEC.Data.Logger.log != null) { SCEEC.Data.Logger.log.Info("Send:" + XmlConfig.GetBytestring(SendData)); } if (RecDataLength == 0) { return(null); } if (RecDataLength != -1) { for (int t = 0; t < Timeout; t++) { if (_seriaPort.BytesToRead >= RecDataLength) { break; } Thread.Sleep(100); } } else { for (int t = 0; t < Timeout; t++) { if (_seriaPort.BytesToRead > 0) { break; } Thread.Sleep(10); } } int count = _seriaPort.BytesToRead; int offset = 0; int SingalReadDataLength = 0; if (count >= RecDataLength && count != 0) { while (offset < count) { SingalReadDataLength = _seriaPort.Read(RecData, offset, count - offset); if (SingalReadDataLength > 0) { offset += SingalReadDataLength; if (RecData.Length == RecDataLength) { if (SCEEC.Data.Logger.log != null) { SCEEC.Data.Logger.log.Info("Wave:" + XmlConfig.GetBytestring(RecData)); } return(RecData); } Thread.Sleep(100); } } } } else { return(new byte[1] { 0x01 }); //串口出错 } return(new byte[1] { 0x02 }); //shezhi }