|
|
|
@ -0,0 +1,72 @@
|
|
|
|
|
using System;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using NewLife;
|
|
|
|
|
using TouchSocket.Core;
|
|
|
|
|
using TouchSocket.SerialPorts;
|
|
|
|
|
using TouchSocket.Sockets;
|
|
|
|
|
|
|
|
|
|
namespace NDSD_TouchSocket
|
|
|
|
|
{
|
|
|
|
|
public class SerialPortClientFactory
|
|
|
|
|
{
|
|
|
|
|
static SerialPortClient client = new SerialPortClient();
|
|
|
|
|
|
|
|
|
|
public static void Send(string str)
|
|
|
|
|
{
|
|
|
|
|
client.Send(str);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static void Send(ReadOnlyMemory<byte> memory)
|
|
|
|
|
{
|
|
|
|
|
client.Send(memory);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void Init()
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
client.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
|
|
|
|
|
client.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口
|
|
|
|
|
client.Received = (c, e) =>
|
|
|
|
|
{
|
|
|
|
|
var mes = e.ByteBlock.Span.ToArray();
|
|
|
|
|
byte[] subArray = null;
|
|
|
|
|
if (mes.Length == 12)
|
|
|
|
|
{
|
|
|
|
|
var i = mes[1].ToInt();
|
|
|
|
|
subArray = new byte[i];
|
|
|
|
|
Array.Copy(mes, 1, subArray, 3, i);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (mes.Length == 13)
|
|
|
|
|
{
|
|
|
|
|
var i = mes[2].ToInt();
|
|
|
|
|
subArray = new byte[i];
|
|
|
|
|
Array.Copy(mes, 2, subArray, 2, i);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (subArray != null)
|
|
|
|
|
{
|
|
|
|
|
string message = subArray.ToHex(" ");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
client.Setup(new TouchSocket.Core.TouchSocketConfig()
|
|
|
|
|
.SetSerialPortOption(new SerialPortOption()
|
|
|
|
|
{
|
|
|
|
|
BaudRate = 9600,//波特率
|
|
|
|
|
DataBits = 8,//数据位
|
|
|
|
|
Parity = System.IO.Ports.Parity.None,//校验位
|
|
|
|
|
PortName = "COM13",//COM
|
|
|
|
|
StopBits = System.IO.Ports.StopBits.One//停止位
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
client.Connect();
|
|
|
|
|
Console.WriteLine("连接成功");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|