//Does not get called... private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { print("DataRecieved Handler called"); /* SerialPort spL = (SerialPort)sender; byte[] buf = new byte[spL.BytesToRead]; //Console.WriteLine("DATA RECEIVED!"); print("DATA RECEIVED!"); spL.Read(buf, 0, buf.Length); foreach (Byte b in buf) { //Console.Write(b.ToString()); print("Input recieved:" + b.ToString() + "\n"); } //Console.WriteLine(); */ try { //string indata = sp.ReadExisting(); string indata = sp.ReadLine(); print("Input recieved:" + indata + "\n"); } catch (Exception ex) { print(ex.Message.ToString()); } }
private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Debug.Log(indata); Debug.Log("test"); //freqvalue = System.Convert.ToSingle(indata); }
private static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Show all the incoming data in the port's buffer string line = port.ReadLine(); string[] fields = line.Split(','); if (fields.Length == 9) { AHRS.Update(deg2rad(float.Parse(fields[0])), deg2rad(float.Parse(fields[1])), deg2rad(float.Parse(fields[2])), deg2rad(float.Parse(fields[3])), deg2rad(float.Parse(fields[4])), deg2rad(float.Parse(fields[5]))); } form_3DcuboidA.RotationMatrix = ConvertToRotationMatrix(AHRS.Quaternion); }
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { int n = comm.BytesToRead; //先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 byte[] buf = new byte[n]; // byte[] arrSendMsg = new byte[n + 1]; string str_tmp; received_count += n; //增加接收计数 comm.Read(buf, 0, n); //读取缓冲数据 Buffer.BlockCopy(buf, 0, arrSendMsg, 1, n); builder.Clear(); //清除字符串构造器的内容 //因为要访问ui资源,所以需要使用invoke方式同步ui。 this.Invoke((EventHandler)(delegate { //判断是否是显示为16禁止 //依次的拼接出16进制字符串 foreach (byte b in buf) { builder.Append(b.ToString("X2") + " "); } //追加的形式添加到文本框末端,并滚动到最后。 //this.txGet.AppendText(builder.ToString()); str_tmp = builder.ToString(); label4.BackColor = System.Drawing.Color.Gray; label5.BackColor = System.Drawing.Color.Gray; label6.BackColor = System.Drawing.Color.Gray; label7.BackColor = System.Drawing.Color.Gray; label8.BackColor = System.Drawing.Color.Gray; label9.BackColor = System.Drawing.Color.Gray; label10.BackColor = System.Drawing.Color.Gray; label11.BackColor = System.Drawing.Color.Gray; if (str_tmp == "FE ") { label4.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "FD ") { label5.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "FB ") { label6.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "F7 ") { label7.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "EF ") { label8.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "DF ") { label9.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "BF ") { label10.BackColor = System.Drawing.Color.Red; } else if (str_tmp == "7F ") { label11.BackColor = System.Drawing.Color.Red; } //修改接收计数 // labelGetCount.Text = "Get:" + received_count.ToString(); })); //string strMsg = "服务器" + "\r\n" + " -->" + builder.ToString() + "\r\n"; //string strMsg =builder.ToString(); //byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg); // 将要发送的字符串转换成Utf-8字节数组; arrSendMsg[0] = 0; // 表示发送的是消息数据 string strKey = ""; strKey = str_clnt; if (send_data == 1) { if (string.IsNullOrEmpty(strKey)) // 判断是不是选择了发送的对象; { MessageBox.Show("请选择你要发送的好友!!!"); } else { dict[strKey].Send(arrSendMsg);// 解决了 sokConnection是局部变量,不能再本函数中引用的问题; } } }
private void ComDataRec(object sender, SerialDataReceivedEventArgs e) // заносим сообщение в глобальную переменную Comreply { SerialPort sp = (SerialPort)sender; ComReply += sp.ReadExisting(); }
private void _serial_DataReceived(object sender, SerialDataReceivedEventArgs e) { _response += _serial.ReadExisting(); }
/// <summary> /// 接收到串口数据的时候触发 /// </summary> /// <param name="sender">串口对象</param> /// <param name="e">消息</param> private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { int rCount = 0; byte[] buffer = new byte[1024]; byte[] receive = null; while (true) { System.Threading.Thread.Sleep(20); // 此处做个微小的延时,等待数据接收完成 int count = serialPort.Read(buffer, rCount, serialPort.BytesToRead); rCount += count; if (count == 0) { break; } receive = new byte[rCount]; Array.Copy(buffer, 0, receive, 0, count); } if (receive == null) { return; } if (receive.Length < 3) { LogNet?.WriteError(ToString( ), $"Uknown Data:" + SoftBasic.ByteToHexString(receive, ' ')); return; } if (Serial.SoftCRC16.CheckCRC16(receive)) { byte[] modbusCore = SoftBasic.BytesArrayRemoveLast(receive, 2); if (!CheckModbusMessageLegal(modbusCore)) { // 指令长度验证错误,关闭网络连接 LogNet?.WriteError(ToString( ), $"Receive Nosense Modbus-rtu : " + SoftBasic.ByteToHexString(receive, ' ')); return; } // 验证站号是否一致 if (station >= 0 && station != modbusCore[0]) { LogNet?.WriteError(ToString( ), $"Station not match Modbus-rtu : " + SoftBasic.ByteToHexString(receive, ' ')); return; } // LogNet?.WriteError( ToString( ), $"Success:" + BasicFramework.SoftBasic.ByteToHexString( receive, ' ' ) ); // 需要回发消息 byte[] copy = ModbusInfo.PackCommandToRtu(ReadFromModbusCore(modbusCore)); serialPort.Write(copy, 0, copy.Length); if (IsStarted) { RaiseDataReceived(receive); } } else { LogNet?.WriteWarn("CRC Check Failed : " + SoftBasic.ByteToHexString(receive, ' ')); } }
void sport_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort thisPort = (sender as SerialPort); byte[] buf = new byte[thisPort.BytesToRead]; thisPort.Read(buf, 0, buf.Length); string strData = string.Empty; foreach (Byte b in buf) { BitacoraModel.addItem ("Leer puerto",string.Format ("Puerto {0}", thisPort.PortName),string.Format ("Dato recibido [ {0} ] ",b)); strData += ((char) b).ToString(); } BitacoraModel.addItem ("Cadena recibida",string.Format ("Puerto {0}", thisPort.PortName),string.Format ("Cadena [ {0} ] ",strData)); /* * CODIGO DE ENVÍO AUTOMATICO DE PULSACIONES A OTRO PUERTO DE MANERA AUTOMÁTICA */ this.senDataToPort ("COM1", //NOMBRE DEL PUERTO "p"); //DATO A ENVIAR }
/// <summary> /// Com Port Data Received event /// </summary> /// <param name="sender">object sender</param> /// <param name="e">event Args</param> private void ComPortDataReceived(object sender, SerialDataReceivedEventArgs e) { lock ("Flag") { StringBuilder result = new StringBuilder(); while (this.comPort.BytesToRead > 0) { System.Threading.Thread.Sleep(100); try { byte[] bufferData = new byte[this.comPort.BytesToRead]; this.comPort.Read(bufferData, 0, bufferData.Length); result.Append(System.Text.Encoding.UTF8.GetString(bufferData)); } catch (TimeoutException timeoutEx) { // 以下這邊請自行撰寫你想要的例外處理 this.UpdateTXMessage("[Debug] Timeout"); this.UpdateTXMessage("[Debug]" + timeoutEx.ToString()); } catch (Exception ex) { this.UpdateTXMessage("[Debug]" + ex.ToString()); Debug.WriteLine(ex.ToString()); } } string context = result.ToString(); this.UpdateRXMessage(this.PortName + " [RX] " + context); if (context.Contains("meter_")) { int intStart = 0, intEnd = 0; string strNewResponse = string.Empty; intStart = context.IndexOf("meter"); strNewResponse = context.Substring(intStart, context.Length - intStart); intEnd = strNewResponse.IndexOf("\r"); strNewResponse = strNewResponse.Substring(0, intEnd); string[] strTmp = strNewResponse.Split('_'); string ackString = "dbu_" + strTmp[1] + Environment.NewLine; this.SendData(ackString); } else { byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(context); } } }
private void Puerto_DataReceived(object sender, SerialDataReceivedEventArgs e) { string line = puerto.ReadLine(); this.BeginInvoke(new LineaRecibidaEvent(onLineaRecibida), line); }
private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e) { richTextBox1.Text += "Serial:ID2: " + serialPort2.ReadLine(); }
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string data = serialPort.ReadLine(); OnScanCoded?.Invoke(data); }
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e) { RxString = Serial.ReadExisting(); /*chama outra thread para escrever o dado em alguma posição do Formulário*/ this.Invoke(new EventHandler(trataDadoRecebido)); }
void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Show all the incoming data in the port's buffer MessageBox.Show(port.ReadExisting()); }
public override void portDataReceived(object sender, SerialDataReceivedEventArgs e) { throw new NotImplementedException(); }
}//用于测试串口功能的字节转换函数,在具体业务中不使用 private static void M8128DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { TorqeIsUpdate = false; M8128RevData = new byte[29]; SerialPort sp = (SerialPort)sender; if (sp.BytesToRead <= 0) { return; } _ = M8128RevData; lock (M8128Lock) { bool FirstIsOk = false; bool HeadIsOK = false; int RevNum = 0; for (; RevNum < 29;) { byte RevData; if (!sp.IsOpen) { return; } RevData = Convert.ToByte(sp.ReadByte()); if (HeadIsOK) { M8128RevData[RevNum] = RevData; RevNum++; } if (!FirstIsOk && RevData == 0xAA) { FirstIsOk = true; } if (FirstIsOk && RevData == 0x55 && !HeadIsOK) { HeadIsOK = true; } } } _ = M8128RevData; if (M8128RevData == null) { Console.WriteLine(ByteArrayToHexString(M8128RevData)); return; } FTSensor.forceX = BitConverter.ToSingle(M8128RevData, 4); FTSensor.torqueX = BitConverter.ToSingle(M8128RevData, 16); //实际力矩 FTSensor.forceY = BitConverter.ToSingle(M8128RevData, 8); //实际力 FTSensor.torqueY = BitConverter.ToSingle(M8128RevData, 20); //实际力矩 FTSensor.forceZ = BitConverter.ToSingle(M8128RevData, 12); //实际力 FTSensor.torqueZ = BitConverter.ToSingle(M8128RevData, 24); //实际力矩 TorqeIsUpdate = true; Console.WriteLine("Fx=" + FTSensor.forceX + "Tx=" + FTSensor.torqueX + "Fy=" + FTSensor.forceY + "Ty=" + FTSensor.torqueY + "Fz=" + FTSensor.forceZ + "Tz=" + FTSensor.torqueZ ); }//采集卡串口接收线程
void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (timeSet == false) { startTime = DateTime.Now; timeSet = true; } if (portActive == false) { if (port != null) { port.DiscardInBuffer(); } return; } while (port.BytesToRead > 0) { int length = port.BytesToRead; if (length > 50) { length = 50; } byte[] bytes = new byte[length]; length = port.Read(bytes, 0, length); foreach (var b in bytes) { var v = b; switch (v) { case SOF_EVENT: frameTimeStamp = new DateTime(DateTime.Now.Ticks - startTime.Ticks); frameType = FrameType.Event; break; case SOF_MESSAGE: frameTimeStamp = new DateTime(DateTime.Now.Ticks - startTime.Ticks); frameType = FrameType.Message; break; case SOF_STATE: frameTimeStamp = DateTime.Now; frameType = FrameType.State; break; case ESC: escReceived = true; break; case EOF: try { switch (frameType) { case FrameType.Event: eventFrameQueue.Enqueue(new EventFrame(frameTimeStamp, frameData.ToArray())); Interlocked.Increment(ref framesReceived); break; case FrameType.Message: msgFrameQueue.Enqueue(new MessageFrame(frameTimeStamp, frameData.ToArray())); Interlocked.Increment(ref framesReceived); break; case FrameType.State: break; } } catch { Console.WriteLine("!"); } frameData.Clear(); break; default: if (escReceived) { escReceived = false; v |= 0x80; } frameData.Add(v); break; } } Interlocked.Add(ref bytesReceived, length); } }
/// <summary> /// Callback for data received /// </summary> void OnDataReceived(object sender, SerialDataReceivedEventArgs args) { //count++; while (COM.BytesToRead > 0) { //read byte from port byte ByteRead = (byte)COM.ReadByte(); //add onto list message.Add(ByteRead); //remove first byte if message exceed size limit if (message.Count > PackageMaxSizeLimit) { message.RemoveAt(0); } //find package end int loc = -1; if (PackageMode == PackageModes.UseFPGA) { // if first byte is start of header if (message[0] == (byte)0x01) { // find eof loc = message.IndexOf(0x04); // if eof detected if (loc > 0) { //fetch package if (message.Count == 9) { byte[] package = new byte[loc + 1]; try { int messageLength = loc + 1; for (int i = 0; i < messageLength; i++) { package[i] = message[i]; } //take off read package message.RemoveRange(0, messageLength); //do action of package received if (PackageReceived != null) { PackageReceived(package); } count++; } catch (IndexOutOfRangeException) { } } else if (loc != -1) { message.Clear(); } } } else { message.Clear(); } } // else if not using FPGA else { if (PackageMode == PackageModes.UseEscapeToken) { //if eof detected loc = message.IndexOfSeq <byte>(EscapeToken); } else if (PackageMode == PackageModes.UseFunction) { //if eof detected loc = FindPackageEnd(message.ToArray()); } //notify package if found if (loc > -1) { //fetch package byte[] package = new byte[loc]; try { for (int i = 0; i < loc; i++) { package[i] = message[i]; } //take off read package message.RemoveRange(0, loc + EscapeToken.Length); //do action of package received if (PackageReceived != null) { PackageReceived(package); } count++; } catch (IndexOutOfRangeException) { } } } } }
private void Port_ReceivedEvent(object sender, SerialDataReceivedEventArgs e) { while (Port.BytesToRead > 0) { if (processCOM ()) { switch (id) { case HSPid: HPacket = (HandShakePacket)ByteArrayToStructure (buffer, HPacket); Invoke ("HandShake", 0); if ((HPacket.M1 == 3) && (HPacket.M2 == 1) && (HPacket.M3 == 4)) { DisplayFound = true; } else { DisplayFound = false; } break; case Cid: VesselControls (); //Invoke("VesselControls", 0); break; default: Invoke ("Unimplemented", 0); break; } } } }
void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { this.RefreshInfoTextBox(); }
void ReceiveDataHandler(object sender, SerialDataReceivedEventArgs e) { SerialPort port = (SerialPort) sender; string indata = port.ReadExisting(); Debug.Log("Data Received : " + indata); }
// 串口接收数据 private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { int encoderPulse = 0x00000000, otrEncoderPulse = 0x00000000; ushort bytChk = 0x00, bytTailByte = 0x00;; int dataSize = 0, errorNum = 0; int n = serialPort1.BytesToRead; byte[] dataBuff = new byte[n]; byte[] cmdata = new byte[3]; //接收数据命令段缓存 serialPort1.Read(dataBuff, 0, dataBuff.Length); //获取串口数据 buffer.AddRange(dataBuff); //将读取的数据放入buffer中 serialPort1.DiscardInBuffer(); //清空串口数据 printLog(sendData); //打印串口数据 dataSize = buffer.Count; while (buffer.Count >= 4) //当buffer中的数据的个数大于等于4个时,即每一帧的数据长度所在位(第4位)出现时 { if (buffer[0] == 0x55 && buffer[1] == 0xAA) { int len = buffer[3]; //长度位 if (len > 0 && len <= 250) { if (dataSize >= (len + 6)) //如果接收到的数据没有达到一帧数据的指定长度, 则执行下次循环 { int num = 0; //数据帧为:55 AA 01 0D 50 0B 00 01 86 A0 00 01 86 AA 05 02 01 XOR F0 bytChk = Get_CheckXor(dataBuff, dataBuff.Length); //计算校验位 bytTailByte = buffer[dataSize - 1]; //结束位 if (bytChk == buffer[dataSize - 2] && bytTailByte == 0xF0) //检查校验位和尾帧数据是否正确 { int dataLen = buffer[5]; buffer.RemoveRange(0, 6); //删去帧头,地址和帧长度,命令字 while (dataLen > 0) //读取命令段 { //encoderPulse = buffer[0]; //encoderPulse <<= 8; //encoderPulse += buffer[1]; //encoderPulse <<= 8; //encoderPulse += buffer[2]; //encoderPulse <<= 8; //encoderPulse += buffer[3]; for (int i = 0; i < 4; i++) { encoderPulse += buffer[i]; // 00 01 86 A0 00 01 86 AA if (i == 3) { break; } encoderPulse <<= 8; } encoderPulse = (int)(encoderPulse & 0xFFFFFFFF); // 第一个编码器脉冲数 for (int j = 4; j < 8; j++) { otrEncoderPulse += buffer[j]; // 00 01 86 A0 00 01 86 AA if (j == 7) { break; } otrEncoderPulse <<= 8; } otrEncoderPulse = (int)(otrEncoderPulse & 0xFFFFFFFF); // 第二个编码器脉冲数 buffer.RemoveRange(0, 8); // 删除存储过的命令段 for (int k = 0; k < 3; k++) { cmdata[k] = buffer[k]; // cmdata[0]:电机转动速度;cmdata[1]:电机转动时间;cmdata[2]:所有数据回传结束标志 } dataLen = 0; dataSize = 0; buffer.Clear(); int firEncoder = Convert.ToInt32(encoderPulse); int secEncoder = Convert.ToInt32(otrEncoderPulse); int dValue = Math.Abs(firEncoder - secEncoder); tbspeed.Text = cmdata[0].ToString(); // time = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日HH:mm:ss"); time = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日HH时mm分ss秒"); fileName = System.Environment.CurrentDirectory + "\\" + time + ".txt"; //"+ time + " if (cmdata[2] > 0) //回传数据结束cmdata[1]= 01 { string outputStr = time + " 电机在转速为:" + cmdata[0] + "转每分钟下,工作时间了:" + cmdata[1] + "分钟,第一个编码器输出脉冲数为:" + Convert.ToString(firEncoder) + "个,第二个编码器输出脉冲数为:" + Convert.ToString(secEncoder) + "个,两编码器输出脉冲数差为:" + Convert.ToString(dValue) + ";\r\n"; rtbDspMsg.Text += outputStr; StringBuilder fileData = new StringBuilder(); fileData.Append(outputStr); saveFileToTxt(fileData.ToString(), fileName); fileData.Clear(); } else { //所有数据没回传完毕处理 string outputStr = time + "当前电机转速为:" + cmdata[0] + "转每分钟,第一个编码器输出脉冲数为:" + Convert.ToString(firEncoder) + "个,第二个编码器输出脉冲数为:" + Convert.ToString(secEncoder) + "个,两编码器输出脉冲数差为:" + Convert.ToString(dValue) + ";\r\n"; rtbDspMsg.Text += outputStr; } } } else { rtbDspMsg.Text += "校验位验证失败!\n"; buffer.Clear(); errorNum++; //错误数据个数 } } else { break; } } else { buffer.RemoveRange(0, 2); } } else { buffer.RemoveRange(0, 1); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "出错提示"); } }
public void process_DoWorkHandler(object sender, SerialDataReceivedEventArgs e) { // checksum test if package is transfered successfull // Function is still not robust enough Thread.Sleep(20); //sleep for 100ms to be sure all data from PFC is received SerialPort serialPort = (SerialPort)sender; pfc_response[0] = (byte)serialPort.ReadByte(); //First byte returns first byte of request, e.g. 0xF0 for advanced data pfc_response[1] = (byte)serialPort.ReadByte(); //Second byte indicates remaining size from data package, w/o first byte!! pfc_SizeOfPackage = pfc_response[1] -1; // Second byte is already red, so remainingbytes minus 1 for (int i = 0; pfc_SizeOfPackage <= i; i++) //loop trough array to get all data from serialInBuffer { pfc_response[i + 2] = (byte)serialPort.ReadByte(); } //calculate Checksum from pfc_package: 0xFF minus each byte = last byte in array, if not -> discard pfc_checkSum = 0xFF; for (int i = 0; pfc_SizeOfPackage <= i; i++) { pfc_checkSum = pfc_checkSum - pfc_response[i]; } if (pfc_checkSum == pfc_response[pfc_SizeOfPackage + 1]) //check the checksum { parse_serialData(pfc_response); //call parser } }
private void post_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(50); //延时 /* * if (!radioButton1.Checked) * { * string str = serialPort1.ReadExisting();//字符串方式读 * textBox_receive.AppendText(str); * * } * else * { * * byte data; * data = (byte)serialPort1.ReadByte(); * string str = Convert.ToString(data, 16).ToUpper();// * textBox_receive.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " "); * * Byte[] receivedData = new Byte[serialPort1.BytesToRead]; //创建接收字节数组 * serialPort1.Read(receivedData, 0, receivedData.Length); //读取数据 * textBox_receive.AppendText(receivedData.ToString()); * }*/ try //尝试协议接收数据 { Byte[] receivedData = new Byte[serialPort1.BytesToRead]; //创建接收字节数组 serialPort1.Read(receivedData, 0, receivedData.Length); //读取数据 //循环遍历接收到的数组 for (int i = 0; i < receivedData.Length - 4; i++) { if (receivedData[i] == Header_data) { //数据协议 帧头 if ((receivedData[i + 1] + receivedData[i + 2] + receivedData[i + 3]) == receivedData[i + 4]) { //和校验 if (receivedData[i + 1] >= Flag_VoltageData[0] && receivedData[i + 1] <= Flag_VoltageData[1]) { //电压数据显示 Voltage_Battery[receivedData[i + 1] - Flag_VoltageData[0]].Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "mv"; //.ToString("X2"); i = i + 4; // textBox_receive.AppendText(i.ToString());//测试用语句 } else if (receivedData[i + 1] >= Flag_SOCData[0] && receivedData[i + 1] <= Flag_SOCData[1]) {//SOC数据显示 Soc_Battery[receivedData[i + 1] - Flag_SOCData[0]].Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "ma"; i = i + 4; // textBox_receive.AppendText(i.ToString());//测试用语句 } else if (receivedData[i + 1] >= Flag_SOHData[0] && receivedData[i + 1] <= Flag_SOHData[1]) {//SOH数据显示 Soh_Battery[receivedData[i + 1] - Flag_SOHData[0]].Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "mv"; i = i + 4; // textBox_receive.AppendText(i.ToString());//测试用语句 } else if (receivedData[i + 1] >= Flag_TemperatureData[0] && receivedData[i + 1] <= Flag_TemperatureData[1]) {//Temperature数据显示 Temperature_Battery[receivedData[i + 1] - Flag_TemperatureData[0]].Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "mv"; i = i + 4; // textBox_receive.AppendText(i.ToString());//测试用语句 } //总电池显示显示 else if (receivedData[i + 1] == Flag_Sum[0]) {//充电状态 if (receivedData[i + 2] == 0x01) { Statu_Battery.Text = "静置状态"; i = i + 4; } else if (receivedData[i + 2] == 0x02) { Statu_Battery.Text = "放电状态"; i = i + 4; } else if (receivedData[i + 2] == 0x04) { Statu_Battery.Text = "充电状态"; i = i + 4; } } else if (receivedData[i + 1] == Flag_Sum[1]) {//总电压显示 Voltage_Sum.Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "mv"; i = i + 4; } else if (receivedData[i + 1] == Flag_Sum[2]) {//总电流显示 Current_Sum.Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "mv"; i = i + 4; } else if (receivedData[i + 1] == Flag_Sum[3]) {//总SOC显示 SOC_Sum.Text = (receivedData[i + 2] * 16 + receivedData[i + 3]).ToString() + "mv"; i = i + 4; } } } else { // textBox1.AppendText(receivedData[i].ToString("X2") + " "); // strRcv += receivedData[i].ToString("X2") + " "; } } Length_Data = Length_Data + receivedData.Length;//记录数据量 Counter.Text = Length_Data.ToString(); // int count = strRcv.Length / 48; // 记录数据的个数 // for (int j = 0; j < count; j++) { /// 获取每条记录 // string buf1 = strRcv.Substring(j * 48, 48); /// 添加字符串数据到数据库 // DataList.Add(buf1); } } catch (System.Exception ex) { MessageBox.Show(ex.Message, "出错提示"); // textBox1.Text = ""; } }
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { SetText(serialPort1.ReadLine()); }
public void DataReceived(object sender, SerialDataReceivedEventArgs e) { if (!Port.IsOpen) { return; } _TempString += Port.ReadExisting(); if (_TempString.Contains("\r\n")) { #if DEBUG Console.WriteLine(_TempString); #endif string commandResponse = _TempString.Substring(0, _TempString.IndexOf("\r\n") + 2); _TempString = _TempString.Replace(commandResponse, ""); //========== ismeterconnected request (returns software version) ========== if (commandResponse.StartsWith("?")) { if (commandResponse.Split(new char [] { '.' }).Length == 3) { _MeterResponded = true; } } if (commandResponse.StartsWith("S ")) { _MeterResponded = true; } //========== serial number response ========== if (commandResponse.StartsWith("@")) { _MeterResponded = true; SerialNumber = commandResponse.Split(new char[] { ' ' })[1].Replace('\"', ' ').Trim(); #if DEBUG Console.WriteLine("SerialNumber: " + SerialNumber); #endif }//if //========== patient record response ========== else if (commandResponse.StartsWith("P")) { if (!_HeaderRead) { //first row of P records is the header _HeaderRead = true; _RecordCount = 0; string[] header = commandResponse.Split(new char[] { ',' }); SampleCount = int.Parse(header[0].Split(new char[] { ' ' })[1]); SerialNumber = header[1].Replace("\"", ""); SampleFormat = header[2].Substring(header[2].IndexOf('\"') + 1, header[2].LastIndexOf('\"') - (header[2].IndexOf('\"') + 1)).ToLower().Trim() == "mg/dl" ? SampleFormat.MGDL : SampleFormat.MMOL; #if DEBUG Console.WriteLine("SampleCount: " + SampleCount); Console.WriteLine("SampleFormat: " + SampleFormat.ToString()); Console.WriteLine("SerialNumber: " + SerialNumber); #endif OnHeaderRead(new HeaderReadEventArgs(SampleCount, this)); }//if else { //all other P records are glucose records Console.WriteLine("Record: " + commandResponse); string[] parsedMsg = commandResponse.Replace("\"", "").Replace(" ", "").Split(new char[] { ',' }); string[] parsedDate = parsedMsg[1].Split(new char[] { '/' }); string[] parsedTime = parsedMsg[2].Split(new char[] { ':' }); try { DateTime dtTimeStamp = new DateTime(int.Parse(parsedDate[2].ToString()), int.Parse(parsedDate[0].ToString()), int.Parse(parsedDate[1].ToString()), int.Parse(parsedTime[0].ToString()), int.Parse(parsedTime[1].ToString()), int.Parse(parsedTime[2].ToString())); if (dtTimeStamp.Year < 100) { //two digit year encountered (all dates are assumed to be in 2000+) dtTimeStamp = dtTimeStamp.AddYears(2000); }//if OnRecordRead(new RecordReadEventArgs(Records.AddRecordRow(dtTimeStamp, Int32.Parse(parsedMsg[3].ToString()), "mg/dl")));//always returns data in mg/dl }//try catch { } finally { ++_RecordCount; } if (_RecordCount == SampleCount) { //all records read so close the port and dispose OnReadFinished(new ReadFinishedEventArgs(this)); Dispose(); } //if } } //elseif } //if }
void m_Port_DataReceived(object sender, SerialDataReceivedEventArgs e) { lock (this) { byte[] buff = new byte[m_Port.BytesToRead]; int length = m_Port.Read(buff, 0, buff.Length); System.Diagnostics.Debug.Print("DataReceived {0} bytes , State {1}", length, m_State); System.Diagnostics.Debug.Print("Hex : " + GetHexString(buff)); if (length == 0) { return; } switch (m_State) { case CommuState.Idle: if (length == 1) { System.Diagnostics.Debug.Print("RecvControlChar := " + (HandshakeCodes)buff[0]); if ((HandshakeCodes)buff[0] == HandshakeCodes.ENQ) { m_State = CommuState.Receiving; SendHandshakeCode(HandshakeCodes.EOT); //3. NO MESSAGE AFTER EOT Start_T1_Timer(); } } break; case CommuState.Receiving: Stop_T2_Timer(); OnDataArrival(buff, length); break; case CommuState.Send_Request: System.Diagnostics.Debug.Print("RecvControlChar := " + (HandshakeCodes)buff[0]); if ((HandshakeCodes)buff[0] == HandshakeCodes.EOT) { Stop_T2_Timer(); m_State = CommuState.Sending; StartSend(); } break; case CommuState.Sending: System.Diagnostics.Debug.Print("RecvControlChar := " + (HandshakeCodes)buff[0]); if ((HandshakeCodes)buff[0] == HandshakeCodes.ACK) { Stop_T2_Timer(); m_State = CommuState.Idle; } else if ((HandshakeCodes)buff[0] == HandshakeCodes.NAK) { Stop_T2_Timer(); m_State = CommuState.Idle; //message failed } break; } } if (m_State == CommuState.Idle && m_QueueSendingBlock.Count > 0) { RequestToSend(); } }
private void DataReceivedCallback(object sender, SerialDataReceivedEventArgs e) { _dataDisplayer.Show("Received: " + serialPort.ReadLine()); }
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { data = serialPort1.ReadLine(); this.Invoke(new EventHandler(displayData_event)); }
void read(object sender, SerialDataReceivedEventArgs ev) { int n = comm.BytesToRead; if (0 != n) { byte[] buf = new byte[n]; try { comm.Read(buf, 0, n); } catch (Exception e) { Report(e.ToString()); } if (null != mReader) { mReader(this, buf, n); } } }
private void RS232_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; while (boolRead) { try { string tempStr = ""; //побайтовое чтение того, что порт посылает if (!sp.IsOpen) { return; } byte newByte = (byte)sp.BaseStream.ReadByte(); tempBytesList.Add(newByte); byte[] tempBytes = tempBytesList.ToArray(); tempStr = Encoding.ASCII.GetString(tempBytes); tempBytesList.Clear(); // Encoding.ASCII.GetChars() sBuffer.Add(newByte); if (sBuffer.Count > 0) { //преобразование их в массив if (tempStr == "\n") { byte[] recivedByte = sBuffer.ToArray(); string recivedStr = Encoding.ASCII.GetString(recivedByte); processLineFromComPort(recivedStr); this.sBuffer.Clear(); } // FullMessageRecived(recivedStr); } } //если кончилось время ожидания.. catch (Exception exp) { Console.WriteLine(exp.Message); } } // this.spPort.Close(); //this.Invoke(new EventHandler(displayText)); // string s = RS232.ReadLine(); //s = convertAsciiTextToHex(s); //вызов функция конвертации // if (s.Length >= 31 * 2 + 30 ) // { //try //{ // mRxCounter += (ulong)sp.Read(inputBuffer, 0, inputBuffer.Length); // Array.Clear(inputBuffer, 0, inputBuffer.Length); //} //catch (System.TimeoutException) //{ // MessageBox.Show("Time out Failure"); //} //catch (System.ArgumentException) //{ // MessageBox.Show("Argument Exception"); //} //catch (System.Exception) //{ // MessageBox.Show("Exception"); //} //byte[] buffer = new byte[blockLimit]; //Action kickoffRead = null; //kickoffRead = delegate //{ // sp.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult ar) // { // try // { // int actualLength = port.BaseStream.EndRead(ar); // byte[] received = new byte[actualLength]; // Buffer.BlockCopy(buffer, 0, received, 0, actualLength); // raiseAppSerialDataEvent(received); // } // catch (IOException exc) // { // handleAppSerialError(exc); // } // kickoffRead(); // }, null); //}; //kickoffRead(); //sp.Write(GET_TIME, 0, GET_TIME.Length); //Thread.Sleep(500);//Даем больше времени на ожидание данных //string readex = newPort.ReadExisting();//Убираем эту строку и заменяем на // int byteRecieved = sp.BytesToRead; //byte[] messByte = new byte[sp.BytesToRead]; //sp.Read(messByte, 0, sp.BytesToRead); //Console.WriteLine(BitConverter.ToString(messByte)); //foreach (Byte b in messByte) //{ // // Console.Write(b.ToString() + @" "); //} //bytesHashtable.Add(DateTime.UtcNow.Ticks, messByte); // processData(messByte); // } }
public static void Serial_Received(object sender, SerialDataReceivedEventArgs e) { // Show all the incoming data in the port's buffer string serial_catcher; serial_catcher = Serial_Pi.ReadExisting(); if (serial_catcher.StartsWith("\x00" + "\x00" )) { Console.WriteLine("Header Found (0x00 0x00 0x11 0x00)!"); } Console.WriteLine("RX: "+serial_catcher); }
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { var receivedData = GetDataFromSerialPort(serialPort1); EnrichTextbox(receivedData); }
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { //SerialPort portSerie = (SerialPort)sender; //string donneeArduino = portSerie.ReadLine(); }
void sport_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort thisPort = (sender as SerialPort); byte[] buf = new byte[thisPort.BytesToRead]; thisPort.Read(buf, 0, buf.Length); string strData = string.Empty; foreach (Byte b in buf) { BitacoraModel.addItem ("Leer puerto",string.Format ("Puerto {0}", thisPort.PortName),string.Format ("Dato recibido [ {0} ] ",b)); strData += ((char) b).ToString(); } BitacoraModel.addItem ("Cadena recibida",string.Format ("Puerto {0}", thisPort.PortName),string.Format ("Cadena [ {0} ] ",strData)); }
private void Port1_DataReceived(object sender, SerialDataReceivedEventArgs e) { }
// When serial port receives data private void SerialPortOBD_DataReceived(object sender, SerialDataReceivedEventArgs e) { datareceivedOBD = true; //changes data received to true }
void SerialOnReceivedHandler(object sender, SerialDataReceivedEventArgs e) { evtSerialOnRx.Set(); }
void HandleGcodeWriterPortDataReceived(object sender, SerialDataReceivedEventArgs e) { }
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { buffer_rx += SerialPort.ReadExisting(); if (iniciar == 's' && buffer_rx == "k") { iniciar = 'n'; timer_ControlDeTiempos.Enabled = false; this.Invoke(new EventHandler(Inicializar)); buffer_rx = ""; } else if (iniciar == 'n' && buffer_rx == "k") { buffer_rx = ""; } else if (iniciar == 'n') { decimales = 'n'; num_dec = 0; incompleto = 'n'; while (buffer_rx.Length > 0 && incompleto == 'n') { orden1.sector = sectores.Total; orden1.tiempo = ""; orden1.record = 'n'; if (buffer_rx[0] == 'T') { orden1.record = 's'; } else if (buffer_rx[0] == 'P') { orden1.sector = sectores.Primero; orden1.record = 's'; } else if (buffer_rx[0] == 'p') { orden1.sector = sectores.Primero; } else if (buffer_rx[0] == 'S') { orden1.sector = sectores.Segundo; orden1.record = 's'; } else if (buffer_rx[0] == 's') { orden1.sector = sectores.Segundo; } for (aux = 1; aux < buffer_rx.Length; aux++) { if (buffer_rx[aux] != 'f') { orden1.tiempo += buffer_rx[aux]; if (buffer_rx[aux] == '.') { decimales = 's'; } else if (decimales == 's') { num_dec++; } } else if (buffer_rx[aux] == 'f') { string buffer_aux = ""; aux++; for (; aux < buffer_rx.Length; aux++) { buffer_aux += buffer_rx[aux]; } buffer_rx = buffer_aux; break; } } if (aux == buffer_rx.Length) { if (buffer_rx[aux - 1] != 'f') { incompleto = 's'; } } if (incompleto == 'n') { if (decimales == 'n') { orden1.tiempo += ".00"; } else { for (; num_dec < 2; num_dec++) { orden1.tiempo += '0'; } } if (orden1.sector == sectores.Primero) { this.Invoke(new EventHandler(Agregar_tiempo)); if (rb_Sectores1.Checked == true) { t = Math.Round(System.Convert.ToDouble(orden1.tiempo), 2) / 100; if (orden1.tiempo[3] == '0') { t = t / 10; if (orden1.tiempo[2] == '0') { t = t / 10; } } v = Math.Round(d / t, 2); v_string = v.ToString("0.00"); this.Invoke(new EventHandler(Agregar_velocidad)); if (orden1.record == 's') { this.Invoke(new EventHandler(Agregar_Vmax)); } } if (orden1.record == 's') { this.Invoke(new EventHandler(Agregar_mejor_tiempo)); Console.Beep(); } Console.Beep(); } else if (orden1.sector == sectores.Segundo) { this.Invoke(new EventHandler(Agregar_tiempo)); if (rb_Sectores2.Checked == true) { t = Math.Round(System.Convert.ToDouble(orden1.tiempo), 2) / 100; if (orden1.tiempo[3] == '0') { t = t / 10; if (orden1.tiempo[2] == '0') { t = t / 10; } } v = Math.Round(d / t, 2); v_string = v.ToString("0.00"); this.Invoke(new EventHandler(Agregar_velocidad)); if (orden1.record == 's') { this.Invoke(new EventHandler(Agregar_Vmax)); } } if (orden1.record == 's') { this.Invoke(new EventHandler(Agregar_mejor_tiempo)); Console.Beep(); } Console.Beep(); } else { this.Invoke(new EventHandler(Agregar_tiempo)); if (rb_Sectores0.Checked == true) { t = Math.Round(System.Convert.ToDouble(orden1.tiempo), 2) / 100; v = Math.Round(d / t, 2); v_string = v.ToString("0.00"); this.Invoke(new EventHandler(Agregar_velocidad)); if (orden1.record == 's') { this.Invoke(new EventHandler(Agregar_Vmax)); } } if (orden1.record == 's') { this.Invoke(new EventHandler(Agregar_mejor_tiempo)); if (bt_Sectores.Text == "Activar tiempo por sectores") { Console.Beep(); } } if (bt_Sectores.Text == "Activar tiempo por sectores") { Console.Beep(); } } } } } }
//データ受信 void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { //受信データを読み取り string rData = serialPort.ReadLine(); string[] rDataArray = rData.Split(separator); if (rDataArray.Length == 7) { //Q:の返値の時 Stat = (string[])rDataArray.Clone(); setStat(); } logSet(rData); }
/// <summary> /// Method that process received data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void comSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { throw new NotImplementedException(); }
/** * Method name: serialPort_DataReceived * Method description: method that activates when * the data is received through * the serial port * Input params: object sender - the object * that raised the event * SerialDataReceivedEventArgs e * - contains info about the * event * Output params: n/a */ private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { this.Invoke(new EventHandler(treatNewData)); }
private void DataReceivedHandlerUmidade(object sender, SerialDataReceivedEventArgs e) { string indata = ConexaoSerial.Instancia.GetConexao().ReadLine().ToString(); SetUmidade(indata); }
public static void Serial_Received(object sender, SerialDataReceivedEventArgs e) { int buffer_length=Serial_Pi.BytesToRead; byte[] serial_catcher; serial_catcher=new byte[buffer_length]; Serial_Pi.Read(serial_catcher, 0, Serial_Pi.BytesToRead); Console.WriteLine("RX: "); foreach (ushort value in serial_catcher) { Console.Write("{0}(0x{1:X})\t",(char)value,value); } Console.WriteLine(); //Init/ID if (compare_arr(serial_catcher, new byte[] { 0x00, 0x00, 0x00, 0x00, 0xC1, 0x00, 0x00, 0x00, 0xC1 })) { Console.WriteLine("Sending ID"); Serial_Write_Bytes(new byte[] { 0x00, 0x00, 0x11, 0x00, 0xC1, 0xF3, 0x00, 0x00, 0xC5 }); } //Firmware if (compare_arr(serial_catcher, new byte[] { 0x11, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x00, 0x00, 0xC5 })) { Console.WriteLine("Sending FW"); Serial_Write_Bytes(new byte[] { 0x00, 0x00, 0x11, 0x00, 0xB4, 0xF3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE3, 0x00, 0x09, 0x09, 0x34, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDA }); } //Data if (compare_arr(serial_catcher, new byte[] { 0x11, 0x00, 0x00, 0x00, 0xB6, 0x00, 0x00, 0x00, 0xC7 })) { Random random_voltage = new Random(); byte voltage = Convert.ToByte(random_voltage.Next(210, 240)); Random random_power = new Random(); byte power = Convert.ToByte(random_power.Next(0, 100)); byte running_1 = (byte)(running_minutes & 0xff); byte running_2 = (byte)((running_minutes >> 8) & 0xff); byte running_3 = (byte)((running_minutes >> 16) & 0xff); byte running_4 = (byte)(running_minutes >> 24); Console.WriteLine("Sending Data"); byte[] Data_Bytes=new byte[] { 0x00, 0x00, 0x11, 0x00, 0xB6, 0xF3, 0x00, 0x00, 0x04, 0x03, 0x35, 0x00, 0x8A, 0x13, 0xE8, 0x00, 0x00, 0x00, 0x24, 0x00, 0x90, 0x0B, 0x00, 0x1F, running_1, running_2, running_3, running_4, 0x00, 0x00}; Serial_Write_Bytes_and_Checksum(Data_Bytes); } //Max Power if (compare_arr(serial_catcher, new byte[] { 0x11, 0x00, 0x00, 0x00, 0xB9, 0x00, 0x00, 0x00, 0xCA })) { Console.WriteLine("Sending Max PWR"); Serial_Write_Bytes(new byte[] { 0x00, 0x00, 0x11, 0x00, 0xB9, 0xF3, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x21, 0x00, 0x22, 0x00, 0x00, 0x00, 0xE5, 0x02, 0x7E, 0x48, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E }); } //Reset Max Power if (compare_arr(serial_catcher, new byte[] { 0x11, 0x00, 0x00, 0x00, 0x97, 0x01, 0x00, 0x00, 0xA9 })) { Console.WriteLine("Reset Max PWR"); Serial_Write_Bytes(new byte[] { 0x00, 0x00, 0x11, 0x00, 0x97, 0x01, 0x00, 0x00, 0xA9 }); } int old_debug = debug; debug = 1; if (debug > 1) { Console.WriteLine("RX: " + serial_catcher); } debug = old_debug; }
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { string indata = ConexaoSerial.Instancia.GetConexao().ReadExisting(); SetTexts(indata); }
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Show all the incoming data in the port's buffer Debug.Log("received:" + serialPort.ReadExisting()); }
void ThePort_DataReceived(object sender, SerialDataReceivedEventArgs e) { //ReadTo_ByString(); }