using Admin.Core.Common; using Aucma.Core.Scanner; 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 { private static SerialPort serialPort = new SerialPort(); private static List allScanners = Appsettings.app("ScannerServer").ToList(); // 内胆扫码器ip private static string MesScannerIp = allScanners.First(x => x.Name == "mes扫码器").Ip; // 箱壳扫码器ip private static string SNScannerIp = allScanners.First(x => x.Name == "sn扫码器").Ip; /// /// code1扫码信息刷新 /// /// public delegate void BindingReceiveCode(string code, string ip); public static event BindingReceiveCode? BindingReceiveCodeEvent; #region 单例实现 private static readonly GunBusiness lazy = new GunBusiness(); /// /// 扫码委托 /// /// /// public delegate void RefreshMaterialCodeStr(string materialCodeStr, string ip); public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent; 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(); //实例化串行端口 //端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字 serialPort.PortName = port;// portName; //波特率 serialPort.BaudRate = 115200; //奇偶校验 serialPort.Parity = Parity.None; //停止位 serialPort.StopBits = StopBits.One; //数据位 serialPort.DataBits = 8; //忽略null字节 serialPort.DiscardNull = true; //接收事件 serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived); //开启串口 serialPort.Open(); } catch (Exception ex) { logHelper.Error(ex.Message.ToString()); } } private static void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { Thread.Sleep(50); int nums = serialPort.BytesToRead; byte[] receiveBytes = new byte[nums]; serialPort.Read(receiveBytes, 0, nums); StringBuilder sb = new StringBuilder(); string str = Encoding.ASCII.GetString(receiveBytes); if (str.Substring(0, 1) == "B") { // mes条码 RefreshMaterialCodeStrEvent?.Invoke(str, MesScannerIp); } else { //SN码 RefreshMaterialCodeStrEvent?.Invoke(str,SNScannerIp); } sb.Clear(); } } }