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.

68 lines
2.1 KiB
C#

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