You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB
C#

1 month ago
using System;
using NewLife.Log;
using NewLife;
using System.IO.Ports;
using TouchSocket.Core;
using TouchSocket.SerialPorts;
using TouchSocket.Sockets;
namespace NDSD_Screwdriver.Tool
{
public class SerialPortFactory
{
SerialPortClient clientSerialPortClient = new SerialPortClient();
private IWaitingClient<ISerialPortClient, IReceiverResult> waitClient;
1 month ago
public SerialPortFactory(string portName)
1 month ago
{
clientSerialPortClient.Connecting = (client, e) => EasyTask.CompletedTask;//即将连接到端口
clientSerialPortClient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口
clientSerialPortClient.Setup(new TouchSocket.Core.TouchSocketConfig()
.SetSerialPortOption(new SerialPortOption()
{
BaudRate = 115200, //波特率
DataBits = 8, //数据位
Parity = System.IO.Ports.Parity.None, //校验位
1 month ago
PortName =portName,
1 month ago
StopBits = System.IO.Ports.StopBits.One //停止位
}).SetSerialDataHandlingAdapter(() => new MyFixedHeaderCustomDataHandlingAdapter()));
//clientSerialPortClient.Connect();
waitClient = clientSerialPortClient.CreateWaitingClient(new WaitingOptions()
{
FilterFunc = response => //设置用于筛选的fun委托当返回为true时才会响应返回
true
});
}
public string Read()
{
try
{
ResponsedData responsedData = waitClient.SendThenResponse(new byte[] { 0x00, 0x03, 0x00, 0x50, 0x00, 0x04, 0x45, 0xC9 });
IRequestInfo requestInfo = responsedData.RequestInfo;
var myFixedHeaderRequestInfo = requestInfo as MyFixedHeaderRequestInfo;
return myFixedHeaderRequestInfo.GetBody();
}
catch (Exception e)
{
return "";
}
}
}
}