protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { readCancelTokenSource?.Cancel(); port?.DiscardInBuffer(); port?.DiscardOutBuffer(); port?.Close(); port?.Dispose(); } disposedValue = true; } }
public string ExecCommand(SerialPort port, string command, int responseTimeout, string errorMessage) { try { port.DiscardOutBuffer(); port.DiscardInBuffer(); port.Write(command + "\r"); return "Success"; } catch (Exception ex) { throw ex; } }
internal void ClearBuffers() { _port?.DiscardInBuffer(); _port?.DiscardOutBuffer(); }
/// <summary> /// Flushes the com port buffers /// </summary> private void Flush() { debugMsg("Just entered Flush()."); comPort.DiscardInBuffer(); comPort.DiscardOutBuffer(); }
public void SerialPort_DataReceived(object s, SerialDataReceivedEventArgs e) { //function is called whenever data is available try { Thread.Sleep(serialBaseDataTable.baseReceiveDelay); recBuf = new byte[_uart.BytesToRead]; _uart.Read(recBuf, 0, recBuf.Length); f.AppendLog("Received Data:" + SendRecivePrint(recBuf)); if (ReceivedData(recBuf)) { if (f.InvokeRequired) { f.Invoke(new MethodInvoker(delegate { f.updateResponseCount(); f.setDataRreadingLabel(true); })); } else { f.updateResponseCount(); f.setDataRreadingLabel(true); } //call datalogging function if (logFile_SerialDataTable.dataLogOnFlag && !logFile_SerialDataTable.dataLogTimer.Enabled) { logFile_SerialDataTable.AddToDataLogFile(); } } else { if (f.InvokeRequired) { f.Invoke(new MethodInvoker(delegate { f.setDataRreadingLabel(false); })); } } //below is working so if backgroundworker method fails for sendReceive then uncomment it //Thread.Sleep(serialBaseDataTable.baseRequestDelay - receiveDelay); //if (!stopTransferFlag) // sendSingleData(); //else //{ // //_uart.DiscardOutBuffer(); // //_uart.DiscardInBuffer(); //} _uart.DiscardOutBuffer(); _uart.DiscardInBuffer(); } catch (Exception es) { f.AppendLog(es.Message); f.AppendLog("Error Receiving Message"); } }
private void clearBuffers() { port.DiscardInBuffer(); port.DiscardOutBuffer(); }
public void Domeasure() { terminated = false; bTimeOut = false; bComGetted = false; dataChkCnt = 0; Log = ""; if (this.cmpdata.IndexOf("/") > 0) { string[] tmp = this.cmpdata.Split('/'); cmpMin = tmp[0]; cmpMax = tmp[1]; if (float.Parse(cmpMax) < float.Parse(cmpMin)) { cmpMax = tmp[0]; cmpMin = tmp[1]; } } else { cmpMax = cmpMin = this.cmpdata; } if (!port.IsOpen) { port.Open(); } port.DiscardInBuffer(); port.DiscardOutBuffer(); foreach (string cmd in this.commandset) { int splitidx = cmd.IndexOf(":"); string data; if (cmd.Length - 1 == splitidx) { data = "0"; } else { data = (cmd.Substring(splitidx + 1, cmd.Length - 1 - (cmd.Substring(0, splitidx).Length))); } if (cmd.Substring(0, splitidx) == "SCPI") { chkmltmt(data); port.Write(String.Format("{0}{1}", data, "\n")); } else if (cmd.Substring(0, splitidx) == "Delay") { Thread.Sleep(Int32.Parse(data)); } else if (cmd.Substring(0, splitidx) == "Recv") { int Interval; if (data != "" && Int32.TryParse(data, out Interval)) { locRecvTimer.Interval = Int32.Parse(data); } locRecvTimer.Start(); } } }
public static void MoveToPosition_L(String handCommand) { //handPortL.WriteLine(handCommand); handPortL.Write(handCommand); handPortL.DiscardOutBuffer(); }
/// <summary> /// 发送数据及接收数据 /// </summary> /// <param name="wData">写入字符串</param> /// <param name="rLen">读取字符长度;0表示不返回数据</param> /// <param name="rData">返回字符串</param> /// <param name="er"></param> /// <param name="timeOut">超时时间</param> /// <returns></returns> public bool send(string wData, int rLen, out string rData, out string er, int timeOut = 500) { er = string.Empty; rData = string.Empty; try { _comLock.AcquireWriterLock(-1); if (_rs232 == null) { er = CLanguage.Lan("串口未打开"); return(false); } byte[] wByte = null; int wByteLen = 0; if (_comDataType == EDataType.HEX格式) { wByteLen = wData.Length / 2; wByte = new byte[wByteLen]; for (int i = 0; i < wByteLen; i++) { wByte[i] = System.Convert.ToByte(wData.Substring(i * 2, 2), 16); } } else { wByteLen = System.Text.Encoding.UTF8.GetByteCount(wData); wByte = new byte[wByteLen]; wByte = System.Text.Encoding.UTF8.GetBytes(wData); } _rs232.DiscardInBuffer(); _rs232.DiscardOutBuffer(); _rs232.Write(wByte, 0, wByteLen); if (rLen == 0) { return(true); } Stopwatch watcher = new Stopwatch(); watcher.Start(); while (true) { System.Threading.Thread.Sleep(5); if (_rs232.BytesToRead >= rLen) { break; } if (watcher.ElapsedMilliseconds > timeOut) { break; } } watcher.Stop(); if (_rs232.BytesToRead == 0) { er = CLanguage.Lan("接收数据超时"); return(false); } int rByteLen = _rs232.BytesToRead; byte[] rByte = new byte[rByteLen]; _rs232.Read(rByte, 0, rByteLen); if (_comDataType == EDataType.HEX格式) { for (int i = 0; i < rByteLen; i++) { rData += rByte[i].ToString("X2"); } } else { rData = System.Text.Encoding.UTF8.GetString(rByte); } if (rByteLen != rLen) { er = CLanguage.Lan("接收数据长度错误") + ":" + rData; return(false); } return(true); } catch (Exception e) { er = e.ToString(); return(false); } finally { _comLock.ReleaseWriterLock(); } }
/// <summary> /// 读取数据 /// </summary> /// <param name="area">读取区域 Q I M 等</param> /// <param name="addrS">数据开始地址 格式:0.0</param> /// <param name="length">读取数据长度 默认:1</param> private byte Read(string area, string addrS, int length = 1) { lock (_lock) { byte[] PIDfx = new byte[33]; PIDfx[0] = 0x68; //开始符 PIDfx[1] = 0x1B; //长度 PIDfx[2] = 0x1B; //长度 PIDfx[3] = 0x68; //开始符 PIDfx[4] = 0x02; //站好 PIDfx[5] = 0x00; //源地址 PIDfx[6] = 0x6C; //功能码 6C:读取 7C:写入 PIDfx[7] = 0x32; //协议识别 PIDfx[8] = 0x01; //远程控制 PIDfx[9] = 0x00; //冗余识别 PIDfx[10] = 0x00; //冗余识别 PIDfx[11] = 0x00; //协议数据 PIDfx[12] = 0x00; //单元参考 PIDfx[13] = 0x00; //参数长度 PIDfx[14] = 0x0E; //参数长度 PIDfx[15] = 0x00; //数据长度 PIDfx[16] = 0x00; //数据长度 PIDfx[17] = 0x04; //读写 04:读 05:写 PIDfx[18] = 0x01; //变量地址数 PIDfx[19] = 0x12; PIDfx[20] = 0x0A; PIDfx[21] = 0x10; PIDfx[22] = 0x01; //读取长度 01:1bit 02:1byte 04:1word 06:double word PIDfx[23] = 0x00; //读取长度 PIDfx[24] = 0x01; //数据个数 PIDfx[25] = 0x00; //数据个数 PIDfx[26] = 0x00; //存储器类型 01:V存储器 00:其他 switch (area) { case "Q": PIDfx[27] = 0x82; break; case "I": PIDfx[27] = 0x81; break; case "M": PIDfx[27] = 0x83; break; } //PIDfx[27] = 0x83;//存储器类型 04:S 05:SM 06:AI 07:AQ 1E:C 81:I 82:Q 83:M 84:V 1F:T string[] addr = addrS.Split('.'); byte temp2 = (byte)(double.Parse(addr[0]) * 8 + double.Parse(addr[1])); PIDfx[28] = 0x00; //偏移量 PIDfx[29] = 0x00; //偏移量 PIDfx[30] = temp2; //偏移量 int temp = 0; for (int i = 4; i <= 30; i++) { temp += PIDfx[i]; } temp = temp % 256; PIDfx[31] = (byte)temp; //效验码 PIDfx[32] = 0x16; //结束符 byte[] PIDfx2 = new byte[] { 0x10, 0x02, 0x00, 0x5C, 0x5E, 0x16 }; //执行命令 if (!_port.IsOpen) { _port.Open(); } _port.ReadTimeout = 1000; _port.DiscardInBuffer(); _port.DiscardOutBuffer(); _port.Write(PIDfx, 0, 33); //System.Threading.Thread.Sleep(200); int startTick = Environment.TickCount; while (_port.BytesToRead < 1 && Environment.TickCount - startTick < 500) { System.Threading.Thread.Sleep(20); } _port.Write(PIDfx2, 0, 6); startTick = Environment.TickCount; while (_port.BytesToRead < 29 && Environment.TickCount - startTick < 500) { System.Threading.Thread.Sleep(20); } byte[] results = new byte[29]; _port.Read(results, 0, 29); System.Threading.Thread.Sleep(20); _port.Close(); return(results[26]); } }
private void spDataReceived(object sender, SerialDataReceivedEventArgs e) { try { Dispatcher.Invoke((Action) delegate { txtRepairBarcode.Text = string.Empty; }); string data = string.Empty; while (true) { if (!sp.IsOpen) { if (sp != null) { sp.DiscardInBuffer(); sp.DiscardOutBuffer(); } serialPortStatusUpdate(); break; } if (sp != null) { data += sp.ReadExisting(); } if (data.EndsWith("\r") || data.EndsWith("\n")) { break; } else { if (data.Length > 0) { if (txtRepairBarcode.Dispatcher.Thread == System.Threading.Thread.CurrentThread) { txtRepairBarcode.Text += data; } else { Dispatcher.Invoke((Action) delegate { txtRepairBarcode.Text += data; }); data = string.Empty; } } } } if (data.Length > 0) { if (txtRepairBarcode.Dispatcher.Thread == System.Threading.Thread.CurrentThread) { txtRepairBarcode.Text += data; beginSerialNumberSearch(); } else { Dispatcher.Invoke((Action) delegate { txtRepairBarcode.Text += data; txtRepairBarcode.Text = txtRepairBarcode.Text.TrimEnd(); beginSerialNumberSearch(); }); data = string.Empty; } } using (csSerialNumberMapper mapper = csSerialNumberMapper.Instance) { Task.Factory.StartNew(new Action(() => { Dispatcher.Invoke(async delegate // perform actions on dispatched thread { if (!mapper.GetData(txtSN.Text)) { throw new InvalidOperationException("Couldn't find data for this barcode!"); } else { (string filename, bool found)result = await mapper.FindFileAsync(".xls"); //TODO: Make User Control for BOM Matcher (2 cmbx: Ref Des. -> Part Number) if (!mapper.NoFilesFound) { csCrossClassInteraction.MapperSuccessMessage(result.filename, mapper.PartNumber); } } }); })); }
//发送按钮 private void btnSend_Click(object sender, EventArgs e) { if (!sp1.IsOpen) //如果没打开 { MessageBox.Show("请先打开串口!", "Error"); return; } if (canOpen.Enabled) { MessageBox.Show("请先打开CANTool装置!", "Error"); return; } string strMessage = ""; string strSignal = ""; if (message.SelectedItem == null) { MessageBox.Show("请选择Message!", "Error"); return; } else { strMessage = (string)message.SelectedItem.ToString(); } if (signal.SelectedItem == null) { MessageBox.Show("请选择Signal!", "Error"); return; } else { strSignal = (string)signal.SelectedItem.ToString(); } double strSend = -1; if (txtSend.Text == "") { MessageBox.Show("请填写信息!", "Error"); return; } else if (double.TryParse(txtSend.Text, out strSend) == false) { MessageBox.Show("输入内容有误,请重新输入", "Error"); return; } //检查sendcycle非法输入 string str3 = ""; int strcheck = -1; if (sendcycle.Text == "Range:0 - 65535") { str3 = Encode.EncodeCANSignal(strMessage, strSignal, strSend); } else if (int.TryParse(sendcycle.Text, out strcheck) == false) { MessageBox.Show("输入内容有误,请重新输入", "Error"); return; } else { int a = int.Parse(sendcycle.Text); if (a < 0 || a > 65535) { MessageBox.Show("输入数据超出范围,请重新输入", "Error"); return; } else { str3 = Encode.EncodeCANSignal(strMessage, strSignal, strSend, Convert.ToUInt32(sendcycle.Text).ToString("x4").ToUpper()); } } //丢弃来自串行驱动程序的接受缓冲区的数据 sp1.DiscardInBuffer(); //丢弃来自串行驱动程序的传输缓冲区的数据 sp1.DiscardOutBuffer(); //使用缓冲区的数据将指定数量的字节写入串行端口 //MessageBox.Show(str3, "发送的数据为"); //sp1.Write(str3); if (str3!=null&&!str3.Equals("")) { sp1.Write(str3); } }
private void ListenSerial() { const int packetSize = 1 + 2 + 8 + 8 + 1 + 1; byte[] packetData = new byte[packetSize]; UInt16 pressure = 0; AccordeonRightKeys rightKeysState = AccordeonRightKeys.None; UInt64 leftVoicesState = 0; while (true) { // Если порт закрыт, то ждем когда откроется while (!mPort.IsOpen) { Thread.Sleep(100); DebugText = "Offline"; } // Блокировка нужна, чтобы не возникало казусов при открытии и закрытии порта lock (mPort) { try { var readed = 0; packetData[0] = 0; while (packetData[0] != 0x5B) { readed = mPort.Read(packetData, 0, 1); } while (readed < packetSize) { readed += mPort.Read(packetData, readed, packetSize - readed); } } catch (TimeoutException) { mPort.DiscardInBuffer(); mPort.DiscardOutBuffer(); DebugText = "timeout"; continue; } catch { DebugText = "IO Error"; continue; } var startByte = packetData[0]; var endByte = packetData[packetData.Length - 1]; // Проверка контрольных сумм if (startByte != 0x5B || endByte != 0x5E) { EAccordeon.MidiHelper.ResetDevice(); mPort.DiscardInBuffer(); mPort.DiscardOutBuffer(); DebugText = "Checksum error"; continue; } int offset = 1; pressure = BitConverter.ToUInt16(packetData, offset); offset += sizeof(UInt16); rightKeysState = (AccordeonRightKeys)BitConverter.ToUInt64(packetData, offset); offset += sizeof(ulong); leftVoicesState = BitConverter.ToUInt64(packetData, offset); offset += sizeof(ulong); var pressedKey = System.Text.Encoding.ASCII.GetChars(packetData, offset, 1)[0]; var pressedKeyCode = (int)pressedKey; byte bPressure = EAccordeon.TransformPressure(pressure); EAccordeon.HandleKeys(bPressure, rightKeysState, leftVoicesState); DebugText = $"pressure={pressure}; rightKeysState={rightKeysState}; leftVoicesState={leftVoicesState}; pressedKey={pressedKey} ({pressedKeyCode})"; } } }
//读取盘点激光数据 public static int ReadLaserData(PLC_Tcp_AP.LaserType type) { int result = -1; while (spIsBusy) { Thread.Sleep(100); } spIsBusy = true; SerialPort spLaser = spLaserLeft; if (type == PLC_Tcp_AP.LaserType.Right) { spLaser = spLaserRight; } if (spLaser != null) { string send = "24" + "00" + "01" + "00" + "2000" + "0000" + "00000000" + "0A" + "00" + "0000" + "0000" + "0000" + "00000000" + "00000000"; send += GetFCS(send) + "2E3B"; string response = ""; try { spLaser.DiscardInBuffer(); spLaser.DiscardOutBuffer(); byte[] buffer_send = PLC_Tcp_AP.GetBytes(send); spLaser.Write(buffer_send, 0, buffer_send.Length); DateTime begin = DateTime.Now; int m = 0, n = 0; Thread.Sleep(200); do { Thread.Sleep(50); m = spLaser.BytesToRead; Thread.Sleep(50); n = spLaser.BytesToRead; }while ((m == 0 || m < n) && DateTime.Now < begin.AddSeconds(2)); byte[] buffer_response = new byte[m]; spLaser.Read(buffer_response, 0, m); spIsBusy = false; response = PLC_Tcp_AP.GetString(buffer_response); if (response.Length >= 79) { string s = response.Substring(72, 8); string value = s.Substring(6, 2) + s.Substring(4, 2) + s.Substring(2, 2) + s.Substring(0, 2); result = Convert.ToInt32(value, 16); } } catch (Exception ex) { spIsBusy = false; csLOG.WriteLog(ex.Message); if (ThrowMsg == null) { csMsg.ShowWarning(ex.Message, false); } else { ThrowMsg(ex.Message); } } } else if (ThrowMsg != null) { ThrowMsg("激光串口不存在"); } return(result); }
private void Timer_Tick(object sender, EventArgs e) { ++countTime; if (triger) { double trackNumber = trackBar1.Value + 1; serialPort.WriteLine(trackNumber.ToString()); } else { double trackNumber = global + 1; serialPort.WriteLine(trackNumber.ToString()); } x += time; try { dataCurves[0] = serialPort.ReadLine().Trim(); if (dataCurves[0].Contains("\r")) { throw new Exception(); } string pattern = @"(?<numbers>\d+[\,*\.*]\d*)|(?<numbers>\d+)"; // Шаблон регулярных выражений для поиска в тексте всех числовых данных Regex regex = new Regex(pattern); foreach (Match item in regex.Matches(dataCurves[0])) { dataCurves[++count] = item.Groups["numbers"].Value; dataCurvesBuffer[count - 1] = dataCurves[count]; } count = 0; } catch { foreach (string item in dataCurvesBuffer) { dataCurves[++count] = item; } count = 0; }; try { y1 = Convert.ToDouble(dataCurves[1].Replace('.', ',')); y2 = Convert.ToDouble(dataCurves[2].Replace('.', ',')); y3 = Convert.ToDouble(dataCurves[3].Replace('.', ',')); y4 = Convert.ToDouble(dataCurves[4].Replace('.', ',')); } catch { y1 = Convert.ToDouble(dataCurves[1]); y2 = Convert.ToDouble(dataCurves[2]); y3 = Convert.ToDouble(dataCurves[3]); y4 = Convert.ToDouble(dataCurves[4]); } //////// Алгоритм для инверсии кривых от датчика освещенности /////////////// yIStrih[0] = y1; yIStrih[2] = y3; yIStrih[1] = y2; yIStrih[3] = y4; y1 = Math.Abs(yNull[0] + (yI[0] - yIStrih[0])); y3 = Math.Abs(yNull[2] + (yI[2] - yIStrih[2])); y2 = Math.Abs(yNull[1] + (yI[1] - yIStrih[1])); y4 = Math.Abs(yNull[3] + (yI[3] - yIStrih[3])); yNull[0] = y1; yNull[2] = y3; yNull[1] = y2; yNull[3] = y4; yI[0] = yIStrih[0]; yI[2] = yIStrih[2]; yI[1] = yIStrih[1]; yI[3] = yIStrih[3]; ///////////////////////////////////////////////////////////////////////////// if (trigerLess) { y1 = (yLessBufer[0] > y1) ? yLessBufer[0] : y1; //y2 = (yLessBufer[1] > y2) ? yLessBufer[1] : y2; y3 = (yLessBufer[2] > y3) ? yLessBufer[2] : y3; //y4 = (yLessBufer[3] > y4) ? yLessBufer[3] : y4; yLessBufer[0] = y1; yLessBufer[2] = y3; //yLessBufer[1] = y2; //yLessBufer[3] = y4; } else { yLessBufer[0] = y1; yLessBufer[2] = y3; //yLessBufer[1] = y2; //yLessBufer[3] = y4; } _data.Add(x, y1); _data.Add(x, y2); _data.Add(x, y3); _data.Add(x, y4); double xmin = x - _capacity * 0.1; double xmax = x; lists[0].Add(x, y1); lists[1].Add(x, y2); lists[2].Add(x, y3); lists[3].Add(x, y4); listData[0].Add(y1.ToString()); listData[1].Add(y2.ToString()); listData[2].Add(y3.ToString()); listData[3].Add(y4.ToString()); listData[4].Add(Math.Round(x, 3).ToString()); if (i++ == 0) { myCurves[0] = myPane.AddCurve("servo (curve 1)", lists[0], Color.FromArgb(6, 245, 7), SymbolType.None); myCurves[2] = myPane.AddCurve("servo - filter (curve 2)", lists[2], Color.Yellow, SymbolType.None); myCurves[1] = myPane.AddCurve("light (curve 3)", lists[1], Color.BlueViolet, SymbolType.None); myCurves[3] = myPane.AddCurve("light - filter (curve 4)", lists[3], Color.Red, SymbolType.None); } if (curveOne) { myCurves[0].Line.IsVisible = true; } else { myCurves[0].Line.IsVisible = false; } myCurves[2].Line.IsVisible = true; if (curveThree) { myCurves[1].Line.IsVisible = true; } else { myCurves[1].Line.IsVisible = false; } if (curveFour) { myCurves[3].Line.IsVisible = true; } else { myCurves[3].Line.IsVisible = false; } myPane.YAxis.Scale.MinAuto = true; myPane.YAxis.Scale.MaxAuto = true; myPane.XAxis.Scale.MinAuto = false; myPane.XAxis.Scale.MaxAuto = true; myPane.XAxis.Scale.Min = xmin; myPane.XAxis.Scale.Max = xmax; myPane.IsBoundedRanges = true; myCurves[0].AddPoint(x, y1); myCurves[0].Line.Width = 2; myCurves[1].AddPoint(x, y2); myCurves[1].Line.Width = 2; myCurves[2].AddPoint(x, y3); myCurves[2].Line.Width = 2; myCurves[3].AddPoint(x, y4); myCurves[3].Line.Width = 2; zedGraph.AxisChange(); zedGraph.Refresh(); serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); this.label7.Text = "all time = " + Math.Round(x, 2) + " s"; this.label8.Text = "count = " + countTime; this.label14.Text = $"f = {Math.Round((countTime / Math.Round(x, 2)))} Hz"; timeContinue = DateTime.Now.Ticks; timeSpan = new TimeSpan(timeContinue - timeStart); timeStart = timeContinue; time = timeSpan.Milliseconds / 1000d; }
/// <summary> /// Open the serial port connection /// </summary> /// <param name="portname">ttyUSB0 / ttyUSB1 / ttyUSB2 / etc.</param> /// <param name="baudrate">115200</param> /// <param name="parity">None / Odd / Even / Mark / Space</param> /// <param name="databits">5 / 6 / 7 / 8</param> /// <param name="stopbits">None / One / Two / OnePointFive</param> /// <param name="handshake">None / XOnXOff / RequestToSend / RequestToSendXOnXOff</param> public void Open( string portname = "/dev/ttyUSB0", int baudrate = 115200, Parity parity = Parity.None, int databits = 8, StopBits stopbits = StopBits.One, Handshake handshake = Handshake.None) { Close(); try { _serial.PortName = $"{portname}"; _serial.BaudRate = baudrate; _serial.Parity = parity; _serial.DataBits = databits; _serial.StopBits = stopbits; _serial.Handshake = handshake; _serial.ReadTimeout = 300; _serial.WriteTimeout = 300; _serial.Open(); _serial.DiscardInBuffer(); _serial.DiscardOutBuffer(); StartReading(); } catch (IOException exception) { OnStatusChanged?.Invoke(this, $"{portname} does not exist.{Environment.NewLine}{exception.StackTrace}"); } catch (UnauthorizedAccessException exception) { OnStatusChanged?.Invoke(this, $"{portname} already in use.{Environment.NewLine}{exception.StackTrace}"); } catch (Exception ex) { OnStatusChanged?.Invoke(this, "Error: " + ex.Message); } if (_serial.IsOpen) { var sb = StopBits.None.ToString().Substring(0, 1); switch (_serial.StopBits) { case StopBits.One: sb = "1"; break; case StopBits.OnePointFive: sb = "1.5"; break; case StopBits.Two: sb = "2"; break; } var p = _serial.Parity.ToString().Substring(0, 1); var hs = _serial.Handshake == Handshake.None ? "No Handshake" : _serial.Handshake.ToString(); OnStatusChanged?.Invoke(this, $"Connected to {_serial.PortName}: {_serial.BaudRate} bps, " + "{_serial.DataBits}{p}{sb}, {hs}."); OnSerialPortOpened?.Invoke(this, true); } else { OnStatusChanged?.Invoke(this, $"{portname} already in use."); OnSerialPortOpened?.Invoke(this, false); } }
public void PurgeQueue() { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); Reply = ""; }
// Use this for initialization public static void Start() { Debug.Log("Start can run"); try { handPortL = new SerialPort("\\\\.\\COM255", 115200); handPortR = new SerialPort("\\\\.\\COM256", 115200); Debug.Log("Hand ports open "); } catch (System.Exception e) { Debug.Log("Hand ports could not open " + e); } if (!handPortL.IsOpen) { try { handPortL.Open(); handPortL.BaudRate = 115200; handPortL.WriteLine("H2"); handPortL.DiscardOutBuffer(); } catch (System.Exception e) { Debug.Log("Could not open comport for hands" + e); } } if (!handPortR.IsOpen) { try { handPortR.Open(); handPortR.BaudRate = 115200; handPortR.WriteLine("H1"); handPortR.DiscardOutBuffer(); } catch (System.Exception e) { Debug.Log("Could not open comport for hands" + e); } } try { Debug.Log("Try Start Ran "); handPortL.WriteLine("500,500,500,500"); handPortR.WriteLine("500,500,500,500"); handPortL.DiscardOutBuffer(); handPortR.DiscardOutBuffer(); } catch (System.Exception e) { Debug.Log("Stuff sucks on start " + e); } }
public void closePort() { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); serialPort.Close(); }
/// <summary> /// 丢弃来自串行驱动程序的接收和发送缓冲区的数据 /// </summary> public void DiscardBuffer() { comPort.DiscardInBuffer(); comPort.DiscardOutBuffer(); }
public bool connect(String parameter, processDataRx process_rx_data) { process_data = process_rx_data; try { serial_port = new SerialPort(parameter); // // We know now that the baud rate must be 460800 because we will only be communicating with the // the unit via USB. The actual COM port will vary with the machine so we shouldn't // restrict ourselves. // // Setup the serial port serial_port.BaudRate = 460800; serial_port.Parity = Parity.None; serial_port.DataBits = 8; serial_port.StopBits = StopBits.One; serial_port.Handshake = Handshake.None; serial_port.ReadBufferSize = 0x10000; // Try to open it serial_port.Open(); // Clear out the buffers serial_port.DiscardInBuffer(); serial_port.DiscardOutBuffer(); serial_port.ReceivedBytesThreshold = 1; // Write 'x' to the unit serial_port.Write("x\r\n"); int loops = 10; while (loops > 0) { if (serial_port.BytesToRead > 12) { String sdata = serial_port.ReadLine(); break; } System.Threading.Thread.Sleep(10); loops--; } serial_port.DiscardInBuffer(); serial_port.DiscardOutBuffer(); if (loops == 0) { //02 00 20 E0 03 byte[] cmd = new byte[] { 0x02, 0x00, 0x20, 0xE0, 0x03 }; serial_port.Write(cmd, 0, cmd.Length); loops = 10; while (loops > 0) { if (serial_port.BytesToRead > 12) { String sdata = serial_port.ReadExisting(); break; } System.Threading.Thread.Sleep(10); loops--; } serial_port.DiscardInBuffer(); serial_port.DiscardOutBuffer(); if (loops == 0) { serial_port.Close(); serial_port = null; return(false); } } } catch (Exception) { serial_port.Close(); serial_port = null; return(false); } serial_port.DataReceived += new SerialDataReceivedEventHandler(receive_data); return(true); }
/// <summary> /// 读取条码 /// </summary> /// <param name="serialNo"></param> /// <param name="er"></param> /// <param name="timeOut"></param> /// <returns></returns> public bool Read(out string serialNo, out string er, int rLen = 0, int timeOut = 500) { serialNo = string.Empty; er = string.Empty; byte[] wByte = new byte[] { 0x16, 0x54, 0x0D }; byte[] rByte = new byte[] { 0x16, 0x55, 0x0D }; string rSOI = System.Text.ASCIIEncoding.ASCII.GetString(rByte); string wCmd = System.Text.ASCIIEncoding.ASCII.GetString(wByte); try { if (_rs232 == null) { er = "串口未打开"; return(false); } _enableThreshold = false; Stopwatch watcher = new Stopwatch(); string rData = string.Empty; _rs232.DiscardInBuffer(); _rs232.DiscardOutBuffer(); _rs232.Write(wCmd); watcher.Start(); while (true) { System.Threading.Thread.Sleep(10); if (_rs232.BytesToRead > 0) { System.Threading.Thread.Sleep(10); rData += _rs232.ReadExisting(); } if (rLen > 0) { if (rData.Length >= rLen) { System.Threading.Thread.Sleep(10); if (_rs232.BytesToRead == 0) { break; } } } else { if (rData.Length > 0) { System.Threading.Thread.Sleep(10); if (_rs232.BytesToRead == 0) { break; } } } if (watcher.ElapsedMilliseconds > timeOut) { break; } } watcher.Stop(); if (rData == string.Empty || rData.ToUpper() == "NOREAD") { er = "扫描条码超时"; return(false); } serialNo = rData; return(true); } catch (Exception ex) { er = ex.ToString(); return(false); } finally { if (_rs232 != null) { _rs232.Write(rSOI); } } }
public HeatmasterGroup(ISettings settings) { // No implementation for Heatmaster on Unix systems int p = (int)Environment.OSVersion.Platform; if ((p == 4) || (p == 128)) { return; } string[] portNames = GetRegistryPortNames(); for (int i = 0; i < portNames.Length; i++) { bool isValid = false; try { using (SerialPort serialPort = new SerialPort(portNames[i], 38400, Parity.None, 8, StopBits.One)) { serialPort.NewLine = ((char)0x0D).ToString(); report.Append("Port Name: "); report.AppendLine(portNames[i]); try { serialPort.Open(); } catch (UnauthorizedAccessException) { report.AppendLine("Exception: Access Denied"); } if (serialPort.IsOpen) { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); serialPort.Write(new byte[] { 0xAA }, 0, 1); int j = 0; while (serialPort.BytesToRead == 0 && j < 10) { Thread.Sleep(20); j++; } if (serialPort.BytesToRead > 0) { bool flag = false; while (serialPort.BytesToRead > 0 && !flag) { flag |= (serialPort.ReadByte() == 0xAA); } if (flag) { serialPort.WriteLine("[0:0]RH"); try { int k = 0; int revision = 0; while (k < 5) { string line = ReadLine(serialPort, 100); if (line.StartsWith("-[0:0]RH:", StringComparison.Ordinal)) { revision = int.Parse(line.Substring(9), CultureInfo.InvariantCulture); break; } k++; } isValid = (revision == 770); if (!isValid) { report.Append("Status: Wrong Hardware Revision " + revision.ToString(CultureInfo.InvariantCulture)); } } catch (TimeoutException) { report.AppendLine("Status: Timeout Reading Revision"); } } else { report.AppendLine("Status: Wrong Startflag"); } } else { report.AppendLine("Status: No Response"); } serialPort.DiscardInBuffer(); } else { report.AppendLine("Status: Port not Open"); } } } catch (Exception e) { report.AppendLine(e.ToString()); } if (isValid) { report.AppendLine("Status: OK"); hardware.Add(new Heatmaster(portNames[i], settings)); } report.AppendLine(); } }
public void run2(int ahour, int amin) { SerialPort _serialPort; _serialPort = new SerialPort(); _serialPort.PortName = "COM4"; _serialPort.BaudRate = 9600; _serialPort.Open(); _serialPort.DiscardInBuffer(); _serialPort.DiscardOutBuffer(); int nowhour = DateTime.Now.Hour; int nowminute = DateTime.Now.Minute; int nowsecond = DateTime.Now.Second; int aday = 0; int count = 0; int temp = 0; string fileName = DateTime.Now.ToString(); fileName = fileName.Replace(':', '-'); string X, Y, Z, volts; double dx, dy, dz, dvolts; byte[] time = new byte[5]; time[0] = (byte)nowhour; time[1] = (byte)nowminute; time[2] = (byte)nowsecond; time[3] = (byte)ahour; time[4] = (byte)amin; if (nowhour >= ahour && nowminute > amin) { aday = DateTime.Now.Day + 1; } else { aday = DateTime.Now.Day; } System.DateTime date1 = new System.DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, nowhour, nowminute, nowsecond); System.DateTime date2 = new System.DateTime(DateTime.Now.Year, DateTime.Now.Month, aday, ahour, amin, 0); System.TimeSpan diff1 = date2.Subtract(date1); double diff2 = 0; diff2 = diff1.TotalSeconds; Console.WriteLine(diff2); int[] count_data = new int[(int)diff2]; int[] maxValue = new int[(int)diff2]; double[] volts_data = new double[(int)diff2]; maxValue[0] = 99; Console.WriteLine("시간 : " + nowhour + " 분 : " + nowminute + " 초 : " + nowsecond); for (int i = 0; i < 5; i++) { _serialPort.Write(time, i, 1); Console.WriteLine("보낸 값 : " + time[i]); } Console.WriteLine("아두이노에서 반환된 시간 :" + _serialPort.ReadLine()); Console.WriteLine("아두이노에서 반환된 부운 :" + _serialPort.ReadLine()); Console.WriteLine("아두이노에서 반환된 초오 :" + _serialPort.ReadLine()); string start = _serialPort.ReadLine(); Console.WriteLine(start); string start2 = _serialPort.ReadLine(); Console.WriteLine(start2); for (int i = 0; i < (int)diff2; i++) { X = _serialPort.ReadLine(); Console.WriteLine("X = " + X); Y = _serialPort.ReadLine(); Console.WriteLine("Y = " + Y); Z = _serialPort.ReadLine(); Console.WriteLine("Z = " + Z); volts = _serialPort.ReadLine(); Console.WriteLine("volts = " + volts); dx = double.Parse(X); dy = double.Parse(Y); dz = double.Parse(Z); dvolts = double.Parse(volts); volts_data[i] = dvolts; if (i == 0) { maxValue[i] = 99; temp++; } else if (dx >= 1 || dx <= -1 || dy >= 1 && dy <= -1) { count++; if (maxValue[i - 1] <= 94) { maxValue[i] = maxValue[i - 1] + 5; } else if (maxValue[i] == 95) { maxValue[i - 1] = maxValue[i - 1] + 4; } else if (maxValue[i - 1] == 96) { maxValue[i] = maxValue[i - 1] + 3; } else if (maxValue[i - 1] == 97) { maxValue[i] = maxValue[i - 1] + 2; } else if (maxValue[i - 1] == 98) { maxValue[i] = maxValue[i - 1] + 1; } else { maxValue[i] = 99; } temp = 0; } else { if (temp >= 5) {//temp = 13; maxValue[i-1] = 21 if (maxValue[i - 1] >= 1) { if (maxValue[i - 1] > (temp - 4)) { maxValue[i] = maxValue[i - 1] - (temp - 4); } else { maxValue[i] = 0; } } else if (maxValue[i - 1] == 0) { maxValue[i] = 0; } temp++; } else { maxValue[i] = maxValue[i - 1]; temp++; } } count_data[i] = count; Console.WriteLine("뒤척임 횟수 = " + count); Console.WriteLine("카운트 = " + i); Console.WriteLine(""); Thread.Sleep(1000); } string path = "D:\\time\\" + fileName + ".txt"; StreamWriter sw = File.CreateText(path); sw.WriteLine(date2.ToString()); for (int i = 0; i < (int)diff2; i++) { sw.WriteLine(maxValue[i] + " " + volts_data[i]); } sw.Close(); }
public void DiscardOutBuffer() { serialPort.DiscardOutBuffer(); }
public override void DiscardOutBuffer() { port?.DiscardOutBuffer(); }
//write DO public bool SendFc5(byte address, ushort start, short values) { //Ensure port is open: if (sp.IsOpen) { //Clear in/out buffers: sp.DiscardOutBuffer(); sp.DiscardInBuffer(); byte[] message = new byte[8]; //Function 16 response is fixed at 8 bytes byte[] response = new byte[8]; //Build outgoing message: byte[] CRC = new byte[2]; message[0] = address; message[1] = (byte)5; message[2] = (byte)(start >> 8); message[3] = (byte)start; if (values == 1) { message[4] = (byte)(0xff); message[5] = (byte)0x00; } else { message[4] = (byte)0; message[5] = (byte)0; } GetCRC(message, ref CRC); message[message.Length - 2] = CRC[0]; message[message.Length - 1] = CRC[1]; //Send Modbus message to Serial Port: try { sp.Write(message, 0, message.Length); GetResponse(ref response); } catch (Exception err) { modbusStatus = "Error in write event: " + err.Message; return(false); } //Evaluate message: if (CheckResponse(response)) { modbusStatus = "Write successful"; return(true); } else { modbusStatus = "CRC error"; return(false); } } else { modbusStatus = "Serial port not open"; return(false); } }
private void Reset() { _serialPort?.DiscardOutBuffer(); _serialPort?.DiscardInBuffer(); IsRecv = false; }
static void send(int buggy, String message) { archive.Add(buggy + ": " + message); port.DiscardOutBuffer(); port.WriteLine(buggy + ": " + message); }
/// <summary> /// 1. создаем ком порт, /// 2. настраиваем его /// 3. пытаемся открыть /// 4. даем некоторые at /// 5. слушаем порт /// </summary> private void Idle() { try { SerialPort serialPort = null; do { try { isBroken = true; if (serialPort != null) { if (serialPort.IsOpen) { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); serialPort.Close(); } serialPort = null; } var sleepTimeout = 20 * 1000; while ((sleepTimeout -= 100) > 0 && loop) { Thread.Sleep(100); } serialPort = new SerialPort(); serialPort.PortName = GetPort(); serialPort.BaudRate = GetBaudRate(); serialPort.Handshake = GetHandshake(); serialPort.StopBits = GetStopBits(); serialPort.DataBits = 8; serialPort.Parity = GetParity(); serialPort.NewLine = "\r\n"; serialPort.RtsEnable = true; //IsRtsEnable(); serialPort.DtrEnable = true; //IsDtrEnable(); serialPort.WriteTimeout = 10000; serialPort.ReadTimeout = 10000; serialPort.Open(); serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); //Thread.Sleep(30 * 1000); // ожидание после перезагрузки модема //SendAt(serialPort, "at+cfun=1,1"); Thread.Sleep(30 * 1000); // ожидание после перезагрузки модема turnDtr = (enable) => serialPort.DtrEnable = enable; write = (bytes) => { try { if (serialPort != null) { serialPort.Write(bytes, 0, bytes.Length); SuperLog(bytes, true); } else { log.Debug(string.Format("сериал порт у {0} занулен", this)); } } catch (Exception ex) { log.Error(string.Format("при записи в {0}", this), ex); } }; clearBuffer = () => { if (serialPort != null) { serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); } else { log.Debug(string.Format("сериал порт у {0} занулен", this)); } }; foreach (var ini in GetInit()) { SendAt(serialPort, ini); //log.Debug(string.Format("{0}->{1}='{2}'", this, ini, SendAt(serialPort, ini))); } //log.Debug(string.Format("{0}->AT&D2='{1}'", this, SendAt(serialPort, "AT&D2"))); //log.Debug(string.Format("{0}->ATE0='{1}'", this, SendAt(serialPort, "ATE0"))); var creg = SendAt(serialPort, "AT+CREG?"); if (!creg.Contains("CREG: 0,1")) { log.Warn(string.Format("модем {0} не зарегестрирован в сети ({1})", this, creg)); continue; } log.Debug(string.Format("{0}->AT+CREG?='{1}'", this, creg)); isBroken = false; break; } catch (Exception ex) { if (!(ex is TimeoutException) && !(ex is TimeoutException)) { log.Error(string.Format("{0}: ", this), ex); } } } while (loop); Notify(); var allBuffer = new List <byte>(); while (loop) { try { var bytesCount = serialPort.BytesToRead; if (bytesCount > 0) { do { var buffer = new byte[bytesCount]; serialPort.Read(buffer, 0, bytesCount); SuperLog(buffer, false); allBuffer.AddRange(buffer); Thread.Sleep(IDLE_TIMEOUT); bytesCount = serialPort.BytesToRead; } while (bytesCount > 0); if (callback != null) { callback(allBuffer.ToArray()); } allBuffer.Clear(); } Thread.Sleep(100); } catch (Exception ex) { log.Error(string.Format("цикл приема данных {0}: {1}", this, ex)); } } serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); serialPort.Close(); serialPort = null; log.Debug(string.Format("[{0}] модем остановил процесс получения данных", this)); } catch (Exception ex) { log.Error(string.Format("[{0}] поток работы с ком портом остановлен", this), ex); } }
private void button1_Click(object sender, EventArgs e) { serialport.Write(sentc[0]); serialport.DiscardOutBuffer(); pictureBox1.Image = NewReplicant.Resource1.red; }