private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { RxString = serialPort.ReadExisting(); if (!serialIntercept) { if (oldEntry != RxString) { this.Invoke(new EventHandler(serialRecived)); oldEntry = RxString; } } else { switch (FromIntecepted) { case "Add": AddCard.TagAdd(RxString); break; case "Remove": RemoveCard.TagAdd(RxString); break; default: serialIntercept = false; break; } } }
static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { string str; str = ""; if (e.EventType == SerialData.Chars) { int amount; byte[] buffer; buffer = new byte[BUFFER_SIZE]; amount = ((SerialPort)sender).Read(buffer, 0, BUFFER_SIZE); if (amount > 0) { for (int index = 0; index < amount; index++) { str += buffer[index].ToString(); str += ""; } if (buffer[0] == 1) { led.Write(true); } else { led.Write(false); } Debug.Print("Data: " + str); } } }
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (e.EventType == SerialData.Chars) { receiveNow.Set(); } }
private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (!comPort.IsOpen) return; try { lock (thisLock) { var data = comPort.ReadExisting(); //Console.Write(data); if (sw != null) { sw.Write(data); sw.Flush(); } addText(data); } } catch (Exception) { if (!threadrun) return; TXT_terminal.AppendText("Error reading com port\r\n"); } }
void port1_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] readBuffer = new byte[9]; int count = port1.Read(readBuffer, 0, 9); // throw new NotImplementedException() }
public static void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { while(Port.IsOpen && Port.BytesToRead > 0) { int i = Port.ReadByte(); if (i != '\r') { if (i != '\n') { Line[Index++] = (char)i; } } else { string line = new string(Line, 0, Index); foreach (GRBL.LineReceivedHandler d in OnLineReceived.GetInvocationList()) { d.Invoke(line); } Index = 0; } } }
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.Write("Data Received:"); Console.WriteLine(indata); }
private void robotPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] sp_buffer = new byte[robotPort.BytesToRead]; robotPort.Read(sp_buffer, 0, robotPort.BytesToRead); PrintMessage(sp_buffer); }
static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e) { // throw new NotImplementedException(); byte[] bytes = new byte[serial.BytesToRead]; serial.Read(bytes, 0, bytes.Length); // // "a" received, move the servo and start // recording // if (bytes[0] == 97) { red.Write(false); green.Write(false); Thread.Sleep(waitTime); red.Write(true); flex.Duration = relPos; collectData(); green.Write(true); red.Write(false); flex.Duration = armPos; } // // "b" received, write the data to the port // else if (bytes[0] == 98) { for (int i = 0; i < nSamples; i++) { byte[] send = System.Text.Encoding.UTF8.GetBytes(readTime[i].ToString() + " " + reading[i].ToString() + "\n"); serial.Write(send, 0, send.Length); red.Write(true); green.Write(true); } } }
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { //在这里添加接收串口数据并处理的代码 byte data = portHelper.recvData(); matcher.match(data); }
private void OnReceive(Object sender, SerialDataReceivedEventArgs e) { List<byte> buffer = new List<byte>(); while (PortHasData()) buffer.Add((byte)Read()); socket.Send(buffer.ToArray()); }
private void ReceivedComData(object sender, SerialDataReceivedEventArgs e) { try { while (true) { int nCount = 1; byte[] preamble = new byte[nCount]; iSerialPort.Read(preamble, 0, nCount); if (preamble[0] == '!') { nCount = 6; byte[] header = new byte[nCount]; int nBytes = iSerialPort.Read(header, 0, nCount); if (nBytes != nCount) { iSerialPort.Read(header, nBytes, nCount-nBytes); } if (callback != null) { callback(header); } } } } catch (System.Exception ex) { string msg = ex.Message; } }
public void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { data = _serialPort.ReadExisting(); globald = data; data = ""; this.BeginInvoke(new SetTextDeleg(si_DataReceived)); }
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); //output.Text += "Data Received:\r\n"; output.Text += indata; // +"\r\n"; output.SelectionStart = output.Text.Length; output.SelectionLength = 0; output.ScrollToCaret(); //if (IsLoadingLua) //{ // output.SelectionStart = StartingLinePosition; // output.SelectionLength = output.TextLength - StartingLinePosition; // //output.Copy(); // //LuaCodeTextbox.Clear(); // //LuaCodeTextbox.Paste(); // Clipboard.Clear(); // Clipboard.SetText(output.SelectedText); // LuaCodeTextbox.Clear(); // LuaCodeTextbox.Text = Clipboard.GetText(); // IsLoadingLua = false; //} lastSerialActivity = DateTime.Now; }
private void Arduino_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { rx_data = new byte[arduino.BytesToRead]; // read the data read_count = arduino.Read(rx_data, 0, rx_data.Length); lastMessage += Encoding.ASCII.GetString(rx_data, 0, read_count); if (lastMessage.IndexOf("*") > -1) { message = lastMessage; lastMessage = ""; this.Invoke(new EventHandler(WriteData)); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e) { // returns the ID read from tag, provides easteregg. var serp = (SerialPort) sender; // var dbm = new DatabaseManager(); var DiagnosticID = "4510720867"; var BlueOysterID = "4519992145"; rfid = serp.ReadExisting().Trim(); Engine.QueueOfRfids.Enqueue(rfid); //Console.WriteLine(rfid); if (rfid == DiagnosticID) { // Play blue oyster soundtrack. //Console.WriteLine("Dun duu du du duuu duu duuu"); //Diagnostic = true; //if (Diagnostic) // { //// PrintDiagnosticData(DiagnosticID); // } //} if (rfid == BlueOysterID) { // AudioPlayer ap = new AudioPlayer("Blue Oyster Bar.wav"); // ap.Play(); } } }
private static void DataReceived(object sender, SerialDataReceivedEventArgs e) { var port = (SerialPort) sender; while (port.BytesToRead > 0) { int b = port.ReadByte(); if (b == -1) continue; Command command = ToCommand(b); if (command == Command.Unknown) { Debug.Print(b.ToString("X2")); continue; } var led = (OutputPort) Led[command]; bool newValue = !led.Read(); led.Write(newValue); string response = (char) b + "=" + (newValue ? "on" : "off") + "\r\n"; byte[] buffer = Encoding.UTF8.GetBytes(response); port.Write(buffer, 0, buffer.Length); } }
void comport_DataReceived(object sender, SerialDataReceivedEventArgs e) { // This method will be called when there is data waiting in the port's buffer // Determain which mode (string or binary) the user is in // Read all the data waiting in the buffer try { string data = ""; data = comport.ReadLine();//.ReadExisting(); string s = ""; // Display the text to the user in the terminal if (bUseHexDecode) s = Utility.HexEncoding.ToMixedString(data); else s = data; txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += "<" + s + "\r\n"; })); //added < to mark incoming data } catch (Exception ex) { txtReceive.Invoke(new EventHandler(delegate { txtReceive.Text += ex.Message + "\r\n"; })); //MessageBox.Show(ex.Message); } //label2.Invoke(new EventHandler(delegate{label2.Text = data;})); //Log(LogMsgType.Incoming, data); }
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e) { SerialPort reader = (SerialPort)sender; int buff=0; List<byte> list = new List<byte>(); byte[] buffer_rd = new byte[reader.BytesToRead]; do { try { buff = reader.ReadByte(); } catch (System.IO.IOException E) { //TODO: Handle } list.Add((byte)buff); } while (reader.BytesToRead > 0); //await reader.BaseStream.ReadAsync(buffer_rd, 0, buffer_rd.Length, System.Threading.CancellationToken.None); //Debug.WriteLine("{0} Bytes recieved", list.Count); list.AddRange(buffer_rd); foreach (byte to_push in list) { parser.push_byte(to_push); } buff=0; }
private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e){ if (!_serialPort.IsOpen) return; LastReadLines = _serialPort.ReadExisting(); AnswerReceived = true; FireOnAnswerReceived(); }
void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort port = (SerialPort)sender; int layer = 0; if (port.PortName == ports["1st"].PortName) layer = 0; if (port.PortName == ports["2nd"].PortName) layer = 1; if (port.PortName == ports["3rd"].PortName) layer = 2; string code = port.ReadLine(); var result = from box in packs[layer] where !box.HasBarcode select box; if (result.Count() > 0) { result.First().Barcode = code; } else { if (layer > 0) MessageBox.Show(string.Format("尚不存在需要赋码的{0}级包装,不准提前赋码!", layer + 1)); else packs.Add(layer, new DrugBox(code, layer)); } this.BeginInvoke(new MethodInvoker( delegate { ShowPacks(); })); }
private void SerialPortDataRecived(object sender, SerialDataReceivedEventArgs e) { while (serialPort.BytesToRead > 0) { // shift for (int j = 0; j < (buffForRead.Length-1); j++) { buffForRead[j] = buffForRead[j + 1]; } buffForRead[buffForRead.Length - 1] = (Byte)serialPort.ReadByte(); //select if (buffForRead[0] != 0xe6) continue; if (buffForRead[1] != 0x19) continue; if (buffForRead[2] != 0xff) continue; if (buffForRead[3] != 0x08) continue; if (buffForRead[8] != 0x00) continue; if (buffForRead[9] != 0x00) continue; if (buffForRead[10] != 0x00) continue; if (buffForRead[7] != crc.Crc8(buffForRead, 7)) continue; // swich do if (buffForRead[4] == 0x03) Recived_NewTube(); // новая труба if (buffForRead[4] == 0x02) Recived_SegmentTube(); // сегмент трубы if (buffForRead[4] == 0x01) Recived_Sample(); // образец ? if (buffForRead[4] != 0x01) Recived_NoSample(); // образец ? } }
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // read the available bytes int numBytes = serialPort1.BytesToRead; byte[] buffer = new byte[numBytes]; serialPort1.Read(buffer, 0, numBytes); // convert the bytes to string string bufferStr = ""; for (int i = 0; i < buffer.Length; i++) { bufferStr += buffer[i].ToString(); if (i < buffer.Length - 1) { bufferStr += " "; } } // increment the number of received packets receivedPacketCount++; // display the string and packet count textBox4.Invoke(new MethodInvoker(() => textBox4.Text = bufferStr)); textBox5.Invoke(new MethodInvoker(() => textBox5.Text = receivedPacketCount.ToString())); }
private void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e) { String a = sp1.ReadExisting(); txtRec.Text = txtRec.Text + a; txtRec.SelectionStart = txtRec.TextLength; txtRec.ScrollToCaret(); }
private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); }
/// <summary> /// Событие происходящее при получении данных /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { // TODO: Мы получаем одну команду или набор? try { Command = ProtocolForEx.Unpack(((SerialPort)sender).BaseStream); // TODO: А куда деваем команды 1, 2 и другие, если они есть? //Если мы получаем более одной команды, то это уже противоречит //Логике работы нашего умного дома (одна команда - один ответ) if ((Command != null) && (Command.Count != 0)) { answer = (DevCommand)Command[0]; IsFindCommand = true; } } catch { } /*SerialPort sp = (SerialPort)sender; int counter = sp.ReadByte(); byte[] BytArray = new byte[counter]; BytArray[0] = (byte)counter; for (int i = 1; i < counter; i++) { BytArray[i] = (byte)sp.ReadByte(); } // Program.MyParser.ParssComand(BytArray); string Pank = sp.ReadExisting(); answer = BytArray;*/ }
void arduino_DataReceived(object sender, SerialDataReceivedEventArgs e) { this.Invoke(new MethodInvoker(delegate { ReadCode(sender, e); })); }
async void Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { int bytesToRead; int startByte; // Thread.Sleep(1); // wait for messages to finish sending while(Port.BytesToRead > 0) { //await Port.BaseStream.ReadAsync(RxBuffer, 0, 1); Port.Read(RxBuffer, 0, 1); // Look for start byte if( RxBuffer[0] == 200) { bytesToRead = Port.BytesToRead > (RxBuffer.Length - 1) ? (RxBuffer.Length - 1) : Port.BytesToRead; //await Port.BaseStream.ReadAsync(RxBuffer, 1, bytesToRead); Port.Read(RxBuffer, 1, bytesToRead); //Port.DiscardInBuffer(); break; } } //bytesToRead = Port.BytesToRead > RxBuffer.Length ? RxBuffer.Length : Port.BytesToRead; //Port.Read(RxBuffer, 0, bytesToRead); //Port.DiscardInBuffer(); // throw away anything left over // Debug.WriteLine("Data received: " + new SoapHexBinary(RxBuffer).ToString()); if (RxBuffer[0] == 200 && DataReceived != null) DataReceived(RxBuffer); }
void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort spL = (SerialPort)sender; byte[] buf = new byte[spL.BytesToRead]; spL.Read(buf, 0, buf.Length); var result = Encoding.ASCII.GetString(buf); Regex _lineSplitter = new Regex("\\+CUSD: \\d,\"(.*)\",15", RegexOptions.Singleline); if (!_lineSplitter.IsMatch(result)) { return; } var f = _lineSplitter.Match(result); var hexString = f.Groups[1].ToString().Trim(); result = Encoding.ASCII.GetString(PduBitPacker.UnpackBytes(PduBitPacker.ConvertHexToBytes(hexString))); Log.Write(result); foreach (var amountRegExItem in Settings.Default.AmountRegExList) { _lineSplitter = new Regex(amountRegExItem, RegexOptions.Singleline); if (!_lineSplitter.IsMatch(result)) { continue; } f = _lineSplitter.Match(result); result = f.Groups[1].ToString().Trim(); var amount = float.Parse(result.Replace('.',',')); if (null != OnReceiveAmount) { OnReceiveAmount.Invoke(amount); } spL.Close(); } }
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string data = serialPort.ReadExisting(); DataReceived(data); //센서 데이터 수신부 }
//Arduino serial port receive in its own thread private void sp_DataReceivedRateRelay(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (spRelay.IsOpen) { try { System.Threading.Thread.Sleep(25); string sentence = spRelay.ReadLine(); this.BeginInvoke(new LineReceivedEventHandlerRelay(SerialLineReceivedRateRelay), sentence); if (spRelay.BytesToRead > 32) spRelay.DiscardInBuffer(); } //this is bad programming, it just ignores errors until its hooked up again. catch (Exception ex) { WriteErrorLog("Relay Data Recvd " + ex.ToString()); } } }
// Ingress and digest serial data coming from the USB device. // This one is a simple device, so only ping packets // are arriving. private void SP_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { while (SP.IsOpen && SP.BytesToRead >= 8) { try { byte inByte = Convert.ToByte(SP.ReadLine()); byte inByteExtra = Convert.ToByte(SP.ReadLine()); byte major = Convert.ToByte(SP.ReadLine()); byte minor = Convert.ToByte(SP.ReadLine()); byte command = Convert.ToByte(SP.ReadLine()); byte value = Convert.ToByte(SP.ReadLine()); SP.ReadLine(); SP.ReadLine(); if (inByte == 255 && inByteExtra == 255) { switch (command) { case 0xB0: // ping beacon // In order to not try to communicate with other unrelated // devices on the serial bus device identifier is checked here. if (value == 0xD2) { if (!deviceConnected) { firmwareVersionMajor = major; firmwareVersionMinor = minor; startMatrix(); } deviceConnected = true; lastPingTime = DateTime.Now; initiationTimer.Stop(); } break; } } } catch (Exception ex) { Console.WriteLine(ex); } } }
private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { SerialPort spl = (SerialPort)sender; Console.Write("Data " + count + ": " + spl.ReadLine() + "\n"); count++; textBox1.Invoke(new Action(() => textBox1.Text += "Data" + count + ": " + spl.ReadLine() + "\n")); //updateData(); tempReadings.Add(int.Parse(spl.ReadLine())); } catch (Exception ex) { } //listBox1.Text += "Data " + count + "" + spl.ReadLine() + "\n"; }
//serial port receive in its own thread private void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (sp.IsOpen) { try { //give it a sec to spit it out System.Threading.Thread.Sleep(50); //read whatever is in port string sentence = sp.ReadExisting(); this.BeginInvoke(new LineReceivedEventHandler(SerialLineReceived), sentence); } catch (Exception ex) { WriteErrorLog("GPS Data Recv" + ex.ToString()); } } }
void comport_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (this.bClosing == true) { return; } try { string temp = comport.ReadExisting(); this.protocal_parse(temp); } catch (System.Exception ex) { Debug.WriteLine( string.Format("frmHFRead.comport_DataReceived -> exception = {0}" , ex.Message)); } }
private void portDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { data = xbeePort.ReadLine(); do { if (writeOn) { file.Write(data); } dataRecievedArray = data.Split(':'); // Split up each piece of data into an array if (dataRecievedArray[START_BYTE_POS] == "255" && ((avionicsCheckbox.Checked && dataRecievedArray[1] == "T") || (noseCheckbox.Checked && dataRecievedArray[1] == "N"))) { addToListBox(); if (dataRecievedArray[COMMAND_ID_POS] == "PP" && dataRecievedArray[8] == "254\r") // Checks if we recieved BMP sensor info format BMP:ONLINE:PRESSURE:TEMPERATURE:ALTITUDE9 { // Console.WriteLine(dataRecievedArray[7]); setRocketStatus(); setTextBMP(); } else if (dataRecievedArray[COMMAND_ID_POS] == "GG" && dataRecievedArray[13] == "254\r") { setTextGPS(); } else if (dataRecievedArray[COMMAND_ID_POS] == "AA" && dataRecievedArray[8] == "254\r") { setTextAccel(); } else if (dataRecievedArray[COMMAND_ID_POS] == "CC" && dataRecievedArray[9] == "254\r") { //Console.WriteLine(dataRecievedArray[7]); setTextCustomData(); } } data = xbeePort.ReadLine(); } while (data != ""); } catch (Exception el) { // MessageBox.Show(el.InnerException.ToString()); } }
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string temp = serialPort1.ReadExisting().ToString(); try { if (temp[0].Equals('K')) { temp_cekkursi = temp; SetStatusKursi(temp.ToString()); } else { str += temp; SetText(str.ToString()); } } catch { } }
private void BootSerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { TimeCounter = 0; isGetBootinfo = true; string rev = BootSerialPort.ReadExisting(); if (rev.Contains("...") && !isSendAck) { //Thread.Sleep(1000); Delay(200); //ms BootSerialPort.Write("abc"); isSendAck = true; //BootTimer.Enabled = true; } ProbeIfoRichTextBox.AppendText(rev); ProbeIfoRichTextBox.SelectionStart = ProbeIfoRichTextBox.Text.Length; ProbeIfoRichTextBox.ScrollToCaret(); }
// Data_JD[] DJDQJ = new Data_JD[100]; private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (serialPort1.BytesToRead > 12) { if (serialPort1.ReadByte() == 10) { serialPort1.Read(buffer, 2, 11); if (buffer[12] == 0xFF) { DJDbufer.dateTime = DateTime.Now; DJDbufer.JDIP = buffer[4] + buffer[5] * 256; DJDbufer.Temperture.MyValue = buffer[6] - 50; DJDbufer.Humidity.MyValue = buffer[7]; DJDbufer.PM.MyValue = buffer[8] * 250 + buffer[9]; writeJDList(DJDbufer); } } } }
private void com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { /* precte prichozi data ... zatim nijak neosetreno pri prijeni neceleho packetu !!! */ //ret = com.ReadLine(); //int kolikZbyva = com.BytesToRead; //byte oneByte = 0; while (com.BytesToRead > 0) { int comReaded = com.ReadByte(); if (comReaded == -1) { MessageBox.Show("Chyba, cteni za koncem datoveho proudu"); return; } if (prijimamPacket == false && (byte)comReaded == UART_PCK_HEAD) { prijimamPacket = true; prijataData.Clear(); } else if (prijimamPacket == true) { prijataData.Add((byte)comReaded); if (prijataData.Count >= prijataData[0] + 2) { Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), prijataData.Skip(1).ToArray()); prijimamPacket = false; } } } /* vyvolani metody, ktera tato data zpracuje */ // Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(DisplayText), ret); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { int count = serialPort1.BytesToRead; byte[] data = new byte[count]; serialPort1.Read(data, 0, data.Length); foreach (var indata in data) { ReciveBytes++; if (indata == 0 && ReciveBytes > 4) { ReciveAllBytes += ReciveBytes; UpdateIMG(); ReciveBytes = 0; LineData = new List <byte>(); } if (ReciveBytes == 1) { lineNum = indata; } if (ReciveBytes == 2) { lineNum = lineNum * 256 + indata; } if (ReciveBytes > 2) { var colb = indata % 8; byte valb = (byte)(indata - colb); for (int i = 0; i < colb; i++) { LineData.Add(valb); } } } } catch (Exception) { } }
public void DataRecieved(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { SerialPort spl = (SerialPort)sender; string recievedData = spl.ReadLine(); SetText("Data" + " : " + recievedData + "\r\n"); BTnum = " "; if (BTnum != null) { if (i == 0) { curColor = color1.BackColor; panel2.BackColor = curColor; i = i + 1; } else if (i == 1) { curColor = color2.BackColor; panel2.BackColor = curColor; i = i + 1; } else if (i == 2) { curColor = color3.BackColor; panel2.BackColor = curColor; i = i + 1; } else if (i == 3) { curColor = color4.BackColor; panel2.BackColor = curColor; i = 0; } BTnum = null; } } catch (Exception ex) { MessageBox.Show("데이타 리시브 실패\n\r" + ex.Message); } }
/// <summary> /// 更新:采用一个缓冲区,当有数据到达时,把字节读取出来暂存到缓冲区中,缓冲区到达定值 /// 时,在显示区显示数据即可。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { SerialPort sp = sender as SerialPort; if (sp != null) { // 临时缓冲区将保存串口缓冲区的所有数据 int bytesToRead = sp.BytesToRead; byte[] tempBuffer = new byte[bytesToRead]; // 将缓冲区所有字节读取出来 sp.Read(tempBuffer, 0, bytesToRead); // 检查是否需要清空全局缓冲区先 if (shouldClear) { receiveBuffer.Clear(); shouldClear = false; } // 暂存缓冲区字节到全局缓冲区中等待处理 receiveBuffer.AddRange(tempBuffer); if (receiveBuffer.Count >= THRESH_VALUE) { // 异步进行数据处理 var task = Task.Run(() => { ReceivedDataHandler(receiveBuffer); }); } // 启动定时器,防止因为一直没有到达缓冲区字节阈值,而导致接收到的数据一直留存在缓冲区中无法处理。 StartCheckTimer(); this.Dispatcher.Invoke(new Action(() => { if (autoSendEnableCheckBox.IsChecked == false) { Information(""); } dataRecvStatusBarItem.Visibility = Visibility.Visible; })); } }
public void STM32DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) //接收数据的原始函数 { int i; byte RXbyte = 0; //读取数据 try { i = Form1.form1.myCOM.BytesToRead; } catch { return; } while (0 != i) { try { RXbyte = (byte)Form1.form1.myCOM.ReadByte(); if (RXbyte == ACK) { tmp_ack = RXbyte; } if (GetCMD_Flag) { Rxcount++; if (Rxcount == 10) { if (RXbyte == 0x43) { Extended_Erase = false; } else if (RXbyte == 0x44) { Extended_Erase = true; } GetCMD_Flag = false; } } i--; } catch { return; } } }
///// <summary> ///// 非同期文字列受信 ///// </summary> //public void ASync_Protocol_Recv ( ) { // //! 受信データを読み込む. // string data = m_serialPort.ReadExisting ( ); // // 受信文字をFormに投げる // cnt_mainform.Invoke ( eveCommGenePurPosApi, new Object [] { data } ); // //! 受信したデータをテキストボックスに書き込む. // // Invoke ( new CommTestTool.Form1.Delegate_RcvDataToTextBox ( TxtBx_Recv ), new Object [] { data } ); //} /// <summary> /// 非同期受信 イベント処理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void serialPort_ASyncDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { //! シリアルポートをオープンしていない場合、処理を行わない. if (m_serialPort.IsOpen == false) { return; } string strrecvdat = null; List <string> list_recv_buf = new List <string> ( ); // 受信バッファが空になるまで受信 while (true) { //byte brecvbuf = null; if (m_serialPort.BytesToRead == 0) { break; } strrecvdat = m_serialPort.ReadExisting(); list_recv_buf.Add(strrecvdat); System.Threading.Thread.Sleep(consTM_5MS); } string [] str1array = list_recv_buf.ToArray( ); // 受信文字をFormに投げる cnt_mainform.Invoke(eveCommGenePurPosApi, new Object [] { "← " + SprSgm.CUtility.ChgUnicodeToAscii_ForRecvDat(SprSgm.CUtility.ChgStringAryToString(str1array)) + "\r\n" }); bAsyncRecvContinueFlg = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { SerialPort sp = (SerialPort)sender; while (0 != sp.BytesToRead) { serialPort.RX_Data.Enqueue((char)sp.ReadByte()); } if (send.IsCompleted) { send = Task.Run(new Action(() => { try { Thread.Sleep(50); //ожидаем завершения передачи foreach (char c in serialPort.RX_Data) { if ((c != '\n') && RX_countSumbol <= 20) { RX_Message += c.ToString(); RX_countSumbol++; } else { ConsoleWrite(RX_Message, Colors.Blue); RX_Message = ""; RX_countSumbol = 0; } } serialPort.RX_Data = new Queue <char>(); } catch (Exception te) { ConsoleWrite(te.ToString(), Colors.Red); } })); } } catch (Exception ex) { ConsoleWrite(ex.ToString(), Colors.Red); } }
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (checkBox_portMon.Checked == true) { int i = 0; byte[] rx = new byte[524288]; while (serialPort1.BytesToRead > 0) { rx[i] = (byte)serialPort1.ReadByte(); i++; } while (buf_busy) { ; } buf_busy = true; buffer += System.Text.Encoding.GetEncoding(inputCodePage).GetString(rx, 0, i); buf_busy = false; } }
static private void BoardSerialDataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (dealWithBoardSerialStream) { return; } try { if (communicationStateList[0] == CommunicationState.STATE0) { serialList[0].DiscardInBuffer(); serialList[0].DiscardOutBuffer(); return; } string readStream = serialList[0].ReadExisting(); BoardSerialEvent(readStream); } catch (Exception) { }; }
private void OnDataReceive_serialPort(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { // binary mode int bytesAvailable = m_serialPort.BytesToRead; byte[] data = new byte[bytesAvailable]; m_serialPort.Read(data, 0, data.Length); ExtractSerialVSCPMessage(bytesAvailable, data); } catch (IOException ex) { Debug.WriteLine("IOException: " + ex.Message); } catch (Exception ex) { Debug.WriteLine(ex.Message); //MessageBox.Show(ex.Message); } }
private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { // Collecting the characters received to our 'buffer' (string). //recieved_data = serial.ReadExisting(); if (serial.BytesToRead > 0) { recieved_data = serial.ReadExisting(); //Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), recieved_data); //SerialCmdSend(rnd.Next(206, 211).ToString() + "#"); //string hexValue = f.ToString("X"); String s = f.ToString(); SerialCmdSend(ch.ToString()); //Debug.WriteLine(c.ToString()); } Random rnd = new Random(); Debug.WriteLine(recieved_data); }
private void Com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string msg = sp.ReadExisting(); foreach (char c in msg) { if (c == '\n') { DecodeCommand(Cmd); Cmd = ""; } else { Cmd += c; } } }
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { string text = string.Empty; byte[] result = new byte[serialPort1.BytesToRead]; serialPort1.Read(result, 0, serialPort1.BytesToRead); foreach (byte b in result) { text = text + Convert.ToString(b, 16); } textBox1.Text += text + " "; } catch (Exception err) { MessageBox.Show(err.Message); } }
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { int btr, c; SerialPort sp = (SerialPort)sender; //Debug.Print("Data Received!"); lock (inputBuffer) { // Debug.Print("locked and loaded!"); btr = sp.BytesToRead; for (c = 0; c < btr; c++) { inputBuffer[bufferWritePointer] = (byte)sp.ReadByte(); //Debug.Print(inputBuffer[bufferWritePointer].ToString("X2")); bufferWritePointer = (bufferWritePointer + 1) % 2048; } //Debug.Print("DataReceived: bytes in buff: " + bytesInBuffer().ToString()); } }
private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) //private void port_DataReceived(object sender, EventArgs e) { Byte[] DataBuff = new byte[1024]; if (mySerail.IsOpen == false) //如果断开了 直接退出 { return; } try { int SerCount = mySerail.BytesToRead; //读取串口缓存中数据大小 mySerail.Read(DataBuff, 0, SerCount); Debug.WriteLine("接收数据长度{0}:\r\n" + Stm32UsartIsp.ToHexString(DataBuff), DataBuff.Length); OnShowDataReceived(DataBuff.ToString()); } catch { MessageBox.Show("接收错误"); } }
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (!_serialPort.IsOpen) { return; } byte received_byte = 0; byte index = 0; byte[] rxBuf = new byte[255]; while (received_byte != Packet.END_COM) { received_byte = (byte)_serialPort.ReadByte(); rxBuf[index] = received_byte; index++; } handleData(rxBuf); }
public void TurnPage(object sender, System.IO.Ports.SerialDataReceivedEventArgs a) { int b = Arduino1.ReadByte(); if (b == 1) { this.Invoke((MethodInvoker) delegate() { Scroll2Forward(); }); } if (b == 0) { this.Invoke((MethodInvoker) delegate() { Scroll2Backward(); }); } b = 2; }
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { byte[] buffer = new byte[this.BytesToRead]; int read = 0; int index = 0; int count = buffer.Length; do { index += read; count -= read; read = Read(buffer, index, count); } while (read != 0); if (serialDataReceivedComplete != null) { serialDataReceivedComplete(this, new SerialDataReceivedCompleteEventArgs { Data = buffer, EventType = e.EventType }); } }
/// <summary> /// 串口接收处理 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { byte[] buf = new byte[serialPort1.BytesToRead]; serialPort1.Read(buf, 0, buf.Length); if (!isReceiving) { isReceiving = true; recvBuf = ""; //启动定时器计时 timer_serial.Enabled = true; Console.Out.WriteLine("串口有新数据到达,开始接收"); } foreach (Byte b in buf) { //Console.Out.WriteLine(b); recvBuf += Convert.ToChar(b);// == '\n' ? '@' : Convert.ToChar(b);//如果是回车的话用@代替,便于调试 } }
/// <summary> /// Debug prints received information of the Arduino /// </summary> /// <param name="sender">Object that raised the event</param> /// <param name="e">Event arguments</param> private void Recieved(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string s = this.serialPort.ReadLine(); StringBuilder sb = new StringBuilder("Arduino has the following values:"); foreach (char c in s) { if (c == ',') { sb.Append(","); } else { sb.Append((byte)c); } } System.Diagnostics.Debug.Print(sb.ToString()); serialPort.DiscardOutBuffer(); }
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { byte[] readBuffer = null; int n = serialPort1.BytesToRead; byte[] buf = new byte[n]; serialPort1.Read(buf, 0, n); //1.缓存数据 buffer.AddRange(buf); //2.完整性判断 while (buffer.Count >= 7) { //至少包含标头(1字节),长度(1字节),校验位(2字节)等等 //2.1 查找数据标记头 if (buffer[0] == 0x7B) //传输数据有帧头,用于判断 { if (buffer.Count < 10) { //数据未接收完整跳出循环 break; } readBuffer = new byte[10]; //得到完整的数据,复制到readBuffer中 buffer.CopyTo(0, readBuffer, 0, 10); //从缓冲区中清除 buffer.RemoveRange(0, 10); //触发外部处理接收消息事件 string str = System.Text.Encoding.ASCII.GetString(readBuffer); dayinshuju(str); } else //开始标记或版本号不正确时清除 { buffer.RemoveAt(0); } } }