项目用的小工具,简单写的,算是做个备份。 串口发送工具用的是sscom。模拟的是地磅仪表数据 格式如下:ZR,GS+002903kg 配置文件写在app.config里面
static void Main(string[] args)
{
ReciveData.SerialPort_DataReceived();
Console.Read();
}
public class ReciveData {
private static SerialPort serialPort = new SerialPort();
static bool IsUdpcRecvStart = false;
public static void SerialPort_DataReceived() {
try {
serialPort.BaudRate = Convert.ToInt32(Models.BaudRrate);
serialPort.Parity = System.IO.Ports.Parity.None;
serialPort.DataBits = Convert.ToInt32(Models.DataBit);
serialPort.StopBits = System.IO.Ports.StopBits.One;
serialPort.PortName = Models.COM;
serialPort.Open();
Thread thrRecv = new Thread(ReceiveMessage);
thrRecv.Start();
IsUdpcRecvStart = true;
Console.WriteLine("串口监听器已成功启动");
} catch (Exception ex) {
throw new Exception(ex.Message);
}
}
private static List<byte> buffer = new List<byte>(4096);
private static byte[] binary_data = new byte[14];
private static void ReceiveMessage() {
while (IsUdpcRecvStart) {
int Readlen = serialPort.BytesToRead;
byte[] byteData = new byte[Readlen];
serialPort.Read(byteData, 0, byteData.Length);
buffer.AddRange(byteData);
while (buffer.Count>=14) {
if (buffer[0] == 90&&buffer[13]==103) {
buffer.CopyTo(0, binary_data, 0, 14);
buffer.RemoveRange(0, 14);
Console.WriteLine(DateTime.Now.ToString()+" "+ Encoding.Default.GetString(binary_data));
} else {
buffer.RemoveAt(0);
}
}
}
}
}
|