|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
using SlnMesnac.Config;
|
|
|
using System;
|
|
|
using System.Collections.Generic;
|
|
|
using System.IO.Ports;
|
|
|
using System.Linq;
|
|
|
using System.Text;
|
|
|
using System.Threading;
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
namespace SlnMesnac.Common
|
|
|
{
|
|
|
public sealed class ControlOffLineScanHelper
|
|
|
{
|
|
|
|
|
|
#region 单例实现
|
|
|
private static readonly ControlOffLineScanHelper lazy = new ControlOffLineScanHelper();
|
|
|
public static ControlOffLineScanHelper Instance
|
|
|
{
|
|
|
get
|
|
|
{
|
|
|
return lazy;
|
|
|
}
|
|
|
}
|
|
|
#endregion
|
|
|
|
|
|
#region 变量定义
|
|
|
private static SerialPort serialPort = new SerialPort();
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
/// <summary>
|
|
|
/// 扫码委托
|
|
|
/// </summary>
|
|
|
/// <param name="materialCodeStr"></param>
|
|
|
/// <param name="ip"></param>
|
|
|
public delegate void RefreshMaterialCodeStr(string code);
|
|
|
public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent;
|
|
|
|
|
|
public Action<string> RecAutoDataAction;
|
|
|
|
|
|
|
|
|
//初始化串口并启动接收数据
|
|
|
public void InstanceSerialPort(string ComPort)
|
|
|
{
|
|
|
try
|
|
|
{
|
|
|
//端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
|
|
|
serialPort.PortName = ComPort;// portName;
|
|
|
//波特率 霍尼威尔扫码枪115200,普通9600
|
|
|
serialPort.BaudRate = 115200;
|
|
|
//奇偶校验
|
|
|
serialPort.Parity = Parity.None;
|
|
|
//停止位
|
|
|
serialPort.StopBits = StopBits.One;
|
|
|
//数据位
|
|
|
serialPort.DataBits = 0x8;
|
|
|
//忽略null字节
|
|
|
serialPort.DiscardNull = true;
|
|
|
|
|
|
//接收事件
|
|
|
serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
|
|
|
|
|
|
//开启串口
|
|
|
serialPort.Open();
|
|
|
|
|
|
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
Console.WriteLine(ex.Message.ToString());
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
/// 接收数据
|
|
|
/// </summary>
|
|
|
/// <param name="sender"></param>
|
|
|
/// <param name="e"></param>
|
|
|
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
|
|
|
{
|
|
|
//string result = "";
|
|
|
//result = serialPort.ReadExisting().Trim();
|
|
|
//RecAutoDataAction?.Invoke(result);
|
|
|
//Console.WriteLine(result);
|
|
|
string g_s_Data = "";
|
|
|
try
|
|
|
{
|
|
|
#region
|
|
|
Thread.Sleep(100);
|
|
|
do
|
|
|
{
|
|
|
g_s_Data = serialPort.ReadExisting().Trim();
|
|
|
}
|
|
|
while (serialPort.BytesToRead > 0);
|
|
|
|
|
|
if (g_s_Data.Length > 0)
|
|
|
{
|
|
|
//区分箱体码
|
|
|
RecAutoDataAction?.Invoke(g_s_Data);
|
|
|
|
|
|
//逻辑操作,g_s_Data为条码数据
|
|
|
}
|
|
|
GC.Collect();
|
|
|
#endregion
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|