110,500
社区成员
发帖
与我相关
我的任务
分享
private List<byte> RevBuffer = new List<byte>();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
lock (RevBuffer)
{
var buffer = new byte[4000];
var len = 0;
while ((len = serialPort1.Read(buffer, 0, buffer.Length)) > 0)
RevBuffer.AddRange(buffer.Take(len));
ThreadPool.QueueUserWorkItem(h => //不等ProcessCommand执行完,立即重新读取串口新数据
{
while (ProcessCommand()) ; //处理收到的所有消息,直到再没有任务
});
}
}
private bool ProcessCommand()
{
lock (RevBuffer)
{
var len = 查找一个命令的长度(RevBuffer);
if (len == 0) //不包含任何完整的任务(比如说还没有接受到第一个消息的结束标志
return false;
var command = new byte[len];
Array.Copy( RevBuffer.ToArray() , command, len );
RevBuffer.RemoveRange(0, len ); //从接收缓冲区移除第一个消息内容
ThreadPool.QueueUserWorkItem(h => 执行一条命令(command));
return true; //通知调用程序,收到了一个任务
}
}
#region 事件定义
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (CurrentSortingStatus.ID == ESortingStatus.ScanStaffMode || CurrentSortingStatus.ID == ESortingStatus.ScanStaffID || CurrentSortingStatus.ID == ESortingStatus.ScanStaff2ID
|| CurrentSortingStatus.ID == ESortingStatus.ScanTaskID || CurrentSortingStatus.ID == ESortingStatus.ScanGoodsID || CurrentSortingStatus.ID == ESortingStatus.Start)
{
lock (lock_SerialPort_DataReceived)
{
int byteCount = serialPort.BytesToRead;
byte[] receiveBytes = new byte[byteCount];
serialPort.Read(receiveBytes, 0, byteCount);
serialPortScanGunText += Encoding.UTF8.GetString(receiveBytes);
if (!isFirstSerialPortScanGunScaning)
{
isFirstSerialPortScanGunScaning = true;
}
if (serialPortScanGunText.EndsWith(Environment.NewLine))
{
isFirstSerialPortScanGunScanDone = true;
CurrentScanText = serialPortScanGunText.Trim();
serialPortScanGunText = string.Empty;
}
}
}
else
{
serialPort.DiscardInBuffer();
}
}
catch
{
}
}
[code=csharp]
string currentScanText;
public string CurrentScanText
{
get
{ return currentScanText; }
set
{
// if (currentScanText != value) // 扫描相同号码也视为变动
{
currentScanText = value;
try
{
OnPropertyChanged(nameof(CurrentScanText));
}
finally
{
if (CurrentSortingStatus.ID != ESortingStatus.NoStart)
{
ProcessScan();
}
}
}
}
}
[/code]