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; private static string SNCode = string.Empty; private static string MESCode = string.Empty; /// /// code1扫码信息刷新 /// /// public delegate void BindingReceiveCode(string MesCode, string SnCode); 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条码 MESCode = str; RefreshMaterialCodeStrEvent?.Invoke(str, MesScannerIp); } else { //SN码 SNCode = str; RefreshMaterialCodeStrEvent?.Invoke(str,SNScannerIp); } if(!string.IsNullOrEmpty(MESCode) && !string.IsNullOrEmpty(SNCode)) { // 委托 BindingReceiveCodeEvent?.Invoke(MESCode, SNCode); SNCode = string.Empty; MESCode = string.Empty; } sb.Clear(); } } }