|
|
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;
|
|
|
public SerialPortFactory(string portName)
|
|
|
{
|
|
|
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, //校验位
|
|
|
PortName =portName,
|
|
|
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 "";
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
} |