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#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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 "";
}
}
}
}