string strAllChar = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
string buffer = ""; //存储读取到的条码数据
Queue<string> qBarcode = new Queue<string>();//存放所有读取的条码数据队列
/// <summary>
/// 读取串口条码数据
/// </summary>
private void ReadBarcode()
{
while (true)
{
if (!serialPort1.IsOpen) continue;
Thread.Sleep(1000);
try
{
buffer += serialPort1.ReadTo("\r\n");
Next:
if (!buffer.Contains("("))//“(开始说明是我的条码数据信息,‘)’结尾
{
buffer = "";
continue;
}
else
{
int iposleft = buffer.IndexOf("(") + 1;
if (!buffer.Contains(")"))
{//中包含"("说明本次没有读完,再读后面的一段,直到读取到”)“
buffer = buffer.Substring(iposleft - 1);
}
else
{
int iposright = buffer.IndexOf(")") - 1;
string tempnew = buffer.Substring(iposleft, iposright - iposleft + 1);
if (tempnew == "NoRead")//返回”(NoRead)“说明是没有读取到条码 报警 提示
{
qBarcode.Enqueue(tempnew);
Stop();
tsbStart.Enabled = true;
tsbStop.Enabled = false;
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
tBSN.Text = tempnew;
lbResult.Text = "条码位数不正确!请检查";
tBSN.Focus();
tBSN.SelectAll();
}
);
}
else if (tempnew.Length != 23)
{
//除 ”NoRead “之外的其它 !=23 位的条码报警提示
Stop();
tsbStart.Enabled = true;
tsbStop.Enabled = false;
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
tBSN.Text = tempnew;
lbResult.Text = "条码位数不正确!请检查";
tBSN.Focus();
tBSN.SelectAll();
}
);
}
else
{
bool isAllowChar = true;
for (int i = 0; i < tempnew.Length; i++)
{
if (strAllChar.Contains(tempnew[i].ToString()))
{
continue;
}
else
{
isAllowChar = false;
break;
}
}
if (!isAllowChar)
{
//数据中有非法字符,报警提示
qBarcode.Enqueue(tempnew);
Stop();
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
tBSN.Text = tempnew;
lbResult.Text = "条码中有无法识读的字符!请检查";
tBSN.Focus();
tBSN.SelectAll();
}
);
buffer = "";
continue;
}
else
{
//成功,将数据加入到队列中
if (!qBarcode.Contains(tempnew))
{
qBarcode.Enqueue(tempnew);
}
tsbStart.Enabled = false;
tsbStop.Enabled = true;
sendLow();
}
}
WriteToFile(strSaveTxt, tempnew + " " + qBarcode.Count.ToString());
if (iposright + 2 > buffer.Length)
{
buffer = "";
continue;
}
else
{
//如果有多个"(("那么 多次循环读取 实际上应该不会发生
buffer = buffer.Substring(iposright + 2);
goto Next;
}
}
}
}
catch { }
}
}
/// <summary>
/// 处理读取到的条码数据
/// </summary>
private void SendToDBFromQueue()
{
while (true)
{
Thread.Sleep(500);
if (qBarcode.Count == 0) continue;
string strBarcode = qBarcode.Peek();
if (strBarcode.Length != 23)
{
//WriteToFile("D:\\dealwith.txt", qBarcode.Peek());
if(qBarcode.Count>0) qBarcode.Dequeue();
}
else
{
//条码正确 开线
try
{
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
//WriteToFile("D:\\dealwith.txt", qBarcode.Peek());
//数据处理,存储到远程数据库服务器中
DealwithCommScan(strBarcode);
}
);
}
catch (Exception exc)
{
BaseClass.CSafeInvoke.SafeInvoke(this, delegate
{
lbResult.Text = exc.Message;
}
);
}
}
}
}