You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
116 lines
3.2 KiB
C#
116 lines
3.2 KiB
C#
using log4net;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO.Ports;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Aucma.Core.CodeBinding.Business
|
|
{
|
|
/// <summary>
|
|
/// 扫码枪补扫
|
|
/// </summary>
|
|
public class GunBusiness
|
|
{
|
|
#region 单例实现
|
|
private static readonly GunBusiness lazy = new GunBusiness();
|
|
public static GunBusiness Instance
|
|
{
|
|
get
|
|
{
|
|
return lazy;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
|
|
private static readonly log4net.ILog logHelper = LogManager.GetLogger(typeof(GunBusiness));
|
|
|
|
|
|
//初始化串口并启动接收数据
|
|
public static void InstanceSerialPort3()
|
|
{
|
|
try
|
|
{
|
|
string port = System.IO.Ports.SerialPort.GetPortNames().FirstOrDefault();
|
|
//实例化串行端口
|
|
SerialPort serialPort = new SerialPort();
|
|
//端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
|
|
serialPort.PortName = port;// portName;
|
|
//波特率
|
|
serialPort.BaudRate = 9600;
|
|
//奇偶校验
|
|
serialPort.Parity = Parity.None;
|
|
//停止位
|
|
serialPort.StopBits = StopBits.One;
|
|
//数据位
|
|
serialPort.DataBits = 8;
|
|
//忽略null字节
|
|
serialPort.DiscardNull = true;
|
|
//接收事件
|
|
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
|
|
//开启串口
|
|
serialPort.Open();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logHelper.Error(ex.Message.ToString());
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 接收数据
|
|
/// </summary>
|
|
/// <param name="sender"></param>
|
|
/// <param name="e"></param>
|
|
static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
|
|
{
|
|
try
|
|
{
|
|
|
|
SerialPort serialPort = (SerialPort)sender;
|
|
|
|
string code = serialPort.ReadExisting();
|
|
|
|
if (string.IsNullOrEmpty(code))
|
|
{
|
|
return;
|
|
}
|
|
//业务处理
|
|
Console.WriteLine("获取数据:" + code.Trim());
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.Write(ex.ToString());
|
|
}
|
|
}
|
|
private static void ReceiveData(object serialPortobj)
|
|
{
|
|
try
|
|
{
|
|
SerialPort serialPort = (SerialPort)serialPortobj;
|
|
|
|
string code = serialPort.ReadExisting();
|
|
|
|
if (string.IsNullOrEmpty(code))
|
|
{
|
|
return;
|
|
}
|
|
//业务处理
|
|
Console.WriteLine("获取数据:" + code.Trim());
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logHelper.Error(ex.Message);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|
|
}
|