using HMI.UI.Entity;
|
using System.IO.Ports;
|
using System.Windows.Controls;
|
|
namespace Plugin.StandardTest
|
{
|
public class ScannerManager
|
{
|
public static Dictionary<string, SerialPort> map = new Dictionary<string, SerialPort>();
|
public static Dictionary<SerialPort, Queue<TextBox>> controlMap = new Dictionary<SerialPort, Queue<TextBox>>();
|
|
public static Dictionary<SerialPort, TextBox> focusMap = new Dictionary<SerialPort, TextBox>();
|
public static Dictionary<TextBox, SerialPort> reverseMap = new Dictionary<TextBox, SerialPort>();
|
|
|
public static void RegisterCom(ScannerConfig setting, TextBox tb)
|
{
|
if (!map.ContainsKey(setting.PortName))
|
{
|
// 配置串口
|
var serialPort = new SerialPort
|
{
|
PortName = setting.PortName,
|
BaudRate = setting.BaudRate,
|
Parity = Parity.None,
|
DataBits = setting.DataBits,
|
StopBits = setting.StopBits,
|
Handshake = Handshake.None,
|
DtrEnable = setting.DtrEnable,
|
RtsEnable = setting.RtsEnable
|
//ReadTimeout = 500,
|
//WriteTimeout = 500,
|
//ReciveBufferSize=4096
|
};
|
|
try
|
{
|
// 打开串口
|
serialPort.Open();
|
map[setting.PortName] = serialPort;
|
controlMap[serialPort] = new Queue<TextBox>();
|
reverseMap[tb] = serialPort;
|
tb.GotFocus += Tb_GotFocus;
|
controlMap[serialPort].Enqueue(tb);
|
|
// 注册接收数据事件
|
serialPort.DataReceived += SerialPort_DataReceived; ;
|
}
|
catch (Exception ex)
|
{
|
|
}
|
}
|
else {
|
|
}
|
}
|
|
private static string ReadDataFrom(SerialPort sp)
|
{
|
string barcode = "";
|
while (sp.BytesToRead > 0)
|
{
|
byte[] buffer = new byte[sp.BytesToRead];
|
sp.Read(buffer, 0, buffer.Length);
|
barcode += System.Text.Encoding.UTF8.GetString(buffer);
|
System.Threading.Thread.Sleep(50);
|
}
|
return barcode;
|
}
|
|
private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
{
|
var sp = sender as SerialPort;
|
string barcode = ReadDataFrom(sp);
|
TextBox tb;
|
if (focusMap.ContainsKey(sp))
|
{
|
tb = focusMap[sp];
|
}
|
else
|
{
|
tb = controlMap[sp].Dequeue();
|
}
|
//string barcode =
|
tb.Dispatcher.Invoke(() =>
|
{
|
tb.Text = barcode;
|
});
|
}
|
|
private static void Tb_GotFocus(object sender, System.Windows.RoutedEventArgs e)
|
{
|
var tb = sender as TextBox;
|
SerialPort sp = reverseMap[tb];
|
focusMap[sp] = tb;
|
}
|
}
|
}
|