using Microsoft.Extensions.DependencyInjection; using SlnMesnac.Config; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; namespace SlnMesnac.Common { public sealed class GunHelper { #region 单例实现 private static readonly GunHelper lazy = new GunHelper(); #region 变量定义 private static SerialPort serialPort = new SerialPort(); #endregion /// /// 扫码委托 /// /// /// public delegate void RefreshMaterialCodeStr(string code); public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent; public static GunHelper Instance { get { return lazy; } } #endregion //初始化串口并启动接收数据 public static void InstanceSerialPort3() { try { string port = System.IO.Ports.SerialPort.GetPortNames().FirstOrDefault(); //实例化串行端口 //端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字 serialPort.PortName = port;// portName; //波特率 霍尼威尔扫码枪115200,普通9600 serialPort.BaudRate = 9600; //奇偶校验 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) { Console.WriteLine(ex.Message.ToString()); } } /// /// 接收数据 /// /// /// private static void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { 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", ""); // 业务处理 RefreshMaterialCodeStrEvent?.Invoke(str); sb.Clear(); } /// /// 发送数据方法 /// /// public static void SendData(string data) { try { if (serialPort.IsOpen) { // 将需要发送的数据转换成字节数组 byte[] sendData = Encoding.ASCII.GetBytes(data); // 向串口写入数据 serialPort.Write(sendData, 0, sendData.Length); } else { Console.WriteLine("串口未打开,请先初始化串口并打开连接。"); } } catch (Exception ex) { Console.WriteLine($"发送数据时发生错误:{ex.Message}"); } } } }