using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
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 = "COM3";// 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();
}
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);
}
///
/// 发送数据方法
/// OK-校验成功关闭灯光,NG-校验失败闪烁红灯
///
///
public void SendData(string data)
{
//try
//{
// if (serialPort.IsOpen)
// {
// if (data == "NG")
// {
// byte[] buffer = GetBytesByCommand("CloseRed");
// serialPort.Write(buffer, 0x0, 0x4);
// byte[] buffer1 = GetBytesByCommand("OpenRed");
// serialPort.Write(buffer1, 0x0, 0x4);
// }
// else if (data == "OK")
// {
// byte[] buffer = GetBytesByCommand("CloseRed");
// serialPort.Write(buffer, 0x0, 0x4);
// byte[] buffer1 = GetBytesByCommand("OpenGreen");
// serialPort.Write(buffer1, 0x0, 0x4);
// }
// else if (data == "Exit")
// {
// byte[] buffer = GetBytesByCommand("CloseRed");
// serialPort.Write(buffer, 0x0, 0x4);
// }
// }
// else
// {
// Console.WriteLine("串口未打开,请先初始化串口并打开连接。");
// }
//}
//catch (Exception ex)
//{
// Console.WriteLine($"发送数据时发生错误:{ex.Message}");
//}
}
///
/// 条码根据通信协议转换
///
///
///
private byte[] GetBytesByCommand(string barCode)
{
byte[] buffer = null;
//byte[] SOI = new byte[] { 0x7E };
//byte[] OrderID = new byte[] { 0x02 };
//byte[] MemoID = new byte[] { 0x00 };
//byte[] Info = EncodeInfoData(barCode);
//byte[] Length = GetLength(Info.Length);
//byte CheckSum = GetCheckSum(OrderID,MemoID,Length,Info);
//byte[] EOI = new byte[] { 0x0D };
// 起始结束:7E\0D; SOI OrderID MemoID Length Info CheckSum EOI
// buffer = new byte[] { 0x7E, 0x01, 0x00, Length, iNFO, CheckSum, 0x0D };
return buffer ;
}
//private byte[] GetLength(int length)
//{
//}
private byte[] GetCheckSum(byte[] OrderID, byte[] MemoID, byte[] Length, byte[] Info)
{
// 合并所有数据部分,除去 SOI 和 EOI
List dataList = new List();
dataList.AddRange(OrderID);
dataList.AddRange(MemoID);
dataList.AddRange(Length);
dataList.AddRange(Info);
// 计算数据的总和
int sum = 0;
foreach (byte b in dataList)
{
sum += b;
}
// 取模 65536
int moduloResult = sum % 65536;
// 求反并加1
ushort lCheckSUM = (ushort)((~moduloResult & 0xFFFF) + 1);
// 转换为字节数组,传输时用4个字节
byte[] checkSumBytes = new byte[4];
checkSumBytes[0] = (byte)((lCheckSUM >> 8) & 0xFF); // 高位
checkSumBytes[1] = (byte)(lCheckSUM & 0xFF); // 低位
checkSumBytes[2] = 0; // 额外的两个字节可以填充为0
checkSumBytes[3] = 0;
return checkSumBytes;
}
public byte[] EncodeInfoData(string data)
{
// 分隔符
byte separator = 0x1F;
// 将数据和useFileName转换成字节序列
byte[] dataBytes = EncodeDataForTransmission(data);
// 组合所有字节序列
List encodedBytes = new List();
encodedBytes.AddRange(dataBytes);
encodedBytes.Add(separator);
return encodedBytes.ToArray();
}
byte[] EncodeDataForTransmission(string input)
{
byte[] encodedBytes = new byte[input.Length * 2]; // 每个字符转换为两个字节
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
// 将字符转换为ASCII码
byte asciiValue = (byte)c;
// 将ASCII码拆分为高4位和低4位
byte highNibble = (byte)((asciiValue >> 4) & 0xF); // 高4位
byte lowNibble = (byte)(asciiValue & 0xF); // 低4位
// 转换成ASCII码形式
byte highNibbleAscii = (byte)(highNibble + 0x30); // 转成ASCII码
byte lowNibbleAscii = (byte)(lowNibble + 0x30); // 转成ASCII码
// 存储到结果数组中
encodedBytes[2 * i] = highNibbleAscii;
encodedBytes[2 * i + 1] = lowNibbleAscii;
}
return encodedBytes;
}
}
}