using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SlnMesnac.Common { public sealed class GunHelper { #region 单例实现 private static readonly GunHelper lazy = new GunHelper(); public static GunHelper Instance { get { return lazy; } } #endregion #region 变量定义 private static SerialPort serialPort = new SerialPort(); #endregion /// /// 喷码设备推送 /// /// /// public delegate void PushCode(string code); public static event PushCode PushCodeEvent; //初始化串口并启动接收数据 public void InstanceSerialPort() { try { //端口名 注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字 serialPort.PortName = "COM1";// portName; //波特率 霍尼威尔扫码枪115200,普通9600 serialPort.BaudRate = 9600; //奇偶校验 serialPort.Parity = Parity.None; //停止位 serialPort.StopBits = StopBits.One; //数据位 serialPort.DataBits = 0x8; //忽略null字节 serialPort.DiscardNull = true; //接收事件 serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived); //开启串口 serialPort.Open(); //SendData("202 407 16B1"); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } /// /// 接收数据 /// /// /// private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string result = ""; int bytesToRead = serialPort.BytesToRead; byte[] buf = new byte[bytesToRead]; serialPort.Read(buf, 0x0, bytesToRead); for (int i = 0x0; i < buf.Length; i++) { int num = (int)buf[i]; result =result+num.ToString("X2"); } Console.WriteLine(result); } /// /// 发送数据方法 /// /// public void SendData(string data) { byte[] buffer = GetBytesByCommand(data); serialPort.Write(buffer, 0, buffer.Length); } /// /// 条码转换为待发送字节数组 /// /// /// private byte[] GetBytesByCommand(string barCode) { byte[] buffer = null; byte[] SOI = new byte[] { 0x7E }; byte[] OrderID = new byte[] { 0x30, 0x32 }; byte[] MemoID = new byte[] { 0x30, 0x31 }; byte[] Info = GetInfoBytes(barCode); byte[] Length = GetLengthByte(Info.Length); byte[] CheckSum = GetCheckSumBytes(OrderID, MemoID, Info, Length); byte[] EOI = new byte[] { 0x0D }; using (MemoryStream stream = new MemoryStream()) { // 将所有数组依次写入 MemoryStream stream.Write(SOI, 0, SOI.Length); stream.Write(OrderID, 0, OrderID.Length); stream.Write(MemoID, 0, MemoID.Length); stream.Write(Length, 0, Length.Length); stream.Write(Info, 0, Info.Length); stream.Write(CheckSum, 0, CheckSum.Length); stream.Write(EOI, 0, EOI.Length); // 获取最终的合并后的字节数组 buffer = stream.ToArray(); } return buffer; } #region 计算Info数据 public byte[] GetInfoBytes(string input) { try { List bytes = new List(); // X bytes.Add(0x30); bytes.Add(0x30); bytes.Add(0x35); bytes.Add(0x38); //0 bytes.Add(0x30); bytes.Add(0x30); bytes.Add(0x33); bytes.Add(0x30); foreach (char c in input) { byte[] charBytes = ConvertCharToBytes(c); foreach (byte b in charBytes) { bytes.Add(b); } } // 固定尾部分隔符 bytes.Add(0x30); bytes.Add(0x30); bytes.Add(0x31); bytes.Add(0x46); return bytes.ToArray(); } catch (Exception ex) { // 处理异常,这里可以根据实际情况处理异常,例如记录日志等 Console.WriteLine($"Error in GetInfoBytes: {ex.Message}"); return null; } } // 将字符转换为符合规则的四字节表示 public byte[] ConvertCharToBytes(char c) { byte[] result = new byte[4]; // 获取字符的 ASCII 码 byte ascii = (byte)c; // 高4位的 ASCII 码表示 byte high4 = (byte)((ascii >> 4) + 0x30); // 低4位的 ASCII 码表示 byte low4 = (byte)((ascii & 0x0F) + 0x30); // 构建四字节表示,前两位和后两位 result[0] = 0x30; // 高位补 '0' result[1] = 0x30; // 高位补 '0' result[2] = high4; result[3] = low4; return result; } #endregion #region 计算Length 将十进制数转换为两个字节的 ASCII 表示 public byte[] GetLengthByte(int dec) { byte[] result = new byte[4]; // 将十进制数转换为十六进制字符串 string hexString = dec.ToString("X4"); for (int i = 0; i < hexString.Length; i++) { char c = hexString[i]; int asciiValue = (int)c; result[i] = Convert.ToByte(asciiValue.ToString("X2"), 16); } return result; } #endregion #region 计算校验码 public byte[] GetCheckSumBytes(byte[] OrderID, byte[] MemoID, byte[] Info, byte[] Length) { byte[] result = new byte[4]; // 始终返回四个字节 // 计算校验和 ushort checksum = CalculateLCheckSum(OrderID, MemoID, Info, Length); string checksumHex = checksum.ToString("X4"); for (int i = 0; i < checksumHex.Length; i++) { char c = checksumHex[i]; // 获取字符 c 的 ASCII 码 int asciiValue = (int)c; // 将 ASCII 码转换成十六进制表示,并存储到 result 数组中 result[i] = Convert.ToByte(asciiValue.ToString("X2"), 16); } return result; } private ushort CalculateLCheckSum(byte[] OrderID, byte[] MemoID, byte[] Info, byte[] Length) { // 计算除去 SOI、EOI 和 CheckSUM 外的数据的和 int sum = CalculateSumWithoutCheckSum(OrderID) + CalculateSumWithoutCheckSum(MemoID) + CalculateSumWithoutCheckSum(Info) + CalculateSumWithoutCheckSum(Length); // 取模 65536 ushort modResult = (ushort)(sum % 65536); // 求反加1 ushort checksum = (ushort)(((ushort)~modResult) + 1); return checksum; } private int CalculateSumWithoutCheckSum(byte[] data) { int sum = 0; foreach (byte b in data) { sum += b; } return sum; } #endregion } }