using Aucma.Scada.Model.domain; using HighWayIot.Common; using HighWayIot.Config; using HighWayIot.Log4net; using HighWayIot.Plc; using HighWayIot.Repository.service; 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.Scada.Business { /// /// 入库任务处理 /// public sealed class GunBusiness { private static AppConfig appConfig = AppConfig.Instance; private static SerialPort serialPort = new SerialPort(); #region 单例实现 private static readonly GunBusiness lazy = new GunBusiness(); #region 变量定义 //箱体码 private static string ShellCode = string.Empty; // 内胆码 private static string LinerCode = string.Empty; #endregion /// /// 扫码委托 ,箱壳码1,内胆码2 /// /// /// public delegate void RefreshMaterialCodeStr(string code,int flag); public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent; public static GunBusiness Instance { get { return lazy; } } #endregion //初始化串口并启动接收数据 public static void InstanceSerialPort3() { try { // string port = System.IO.Ports.SerialPort.GetPortNames().FirstOrDefault(); string port = appConfig.Port; //实例化串行端口 //端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字 serialPort.PortName = port;// portName; //波特率 霍尼威尔扫码枪115200,普通9600 serialPort.BaudRate = int.Parse(appConfig.BaudRate); ; //奇偶校验 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) { } } 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).Replace("\r\n", "").Replace("\r", "").Replace("\n", ""); if (str.Substring(0, 1) == "B") { RefreshMaterialCodeStrEvent?.Invoke(str,1); } else if (str.Substring(0, 1) == "L") { RefreshMaterialCodeStrEvent?.Invoke(str, 2); } sb.Clear(); } } }