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 { /// /// 扫码枪补扫 /// 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 += serialPort_DataReceived; //开启串口 serialPort.Open(); } catch (Exception ex) { logHelper.Error(ex.Message.ToString()); } } /// /// 接收数据 /// /// /// static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { SerialPort serialPort = (SerialPort)sender; //开启接收数据线程 Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(ReceiveData)); threadReceiveSub.Start(serialPort); } catch (Exception ex) { throw; } } 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); } } } }