123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248 |
- using DefaultEdit.Enums;
- using System;
- using System.Collections.Generic;
- using System.IO.Ports;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using TouchSocket.Core;
- using TouchSocket.SerialPorts;
- using TouchSocket.Sockets;
- namespace DefaultEdit.Communication
- {
- public class SerialCommunication : IDisposable
- {
- /// <summary>
- /// 串口名称
- /// </summary>
- public string PortName { get; private set; }
- /// <summary>
- /// 波特率
- /// </summary>
- public int BaudRate { get; private set; }
- /// <summary>
- /// 奇偶校验位
- /// </summary>
- public Parity Parity { get; private set; }
- /// <summary>
- /// 停止位
- /// </summary>
- public StopBits StopBits { get; private set; }
- /// <summary>
- /// 数据位
- /// </summary>
- public int DataBits { get; private set; }
- public Encoding Encoding { get; set; } = Encoding.ASCII;
- /// <summary>
- /// 当前连接状态
- /// </summary>
- public bool IsConnected
- {
- get
- {
- if ( client != null )
- {
- return client.Online;
- }
- else
- {
- return false;
- }
- }
- }
- private SerialPortClient client;
- private IWaitingClient<ISerialPortClient, IReceiverResult> WaitClient;
- /// <summary>
- /// 接收到的数据
- /// </summary>
- public string Data { get; private set; }
- /// <summary>
- /// 连接状态变化事件
- /// </summary>
- public event Action<SerialCommunication, bool> ConnectionChanged;
- /// <summary>
- /// 数据接收事件
- /// </summary>
- public event Action<SerialCommunication, string> DataReceived;
- /// <summary>
- /// 发送数据事件
- /// </summary>
- public event Action<SerialCommunication, string> SendData;
- public Terminator terminator;
- public SerialCommunication(Terminator terminator, string portName, int baudRate = 9600, Parity parity = Parity.None, StopBits stopBits = StopBits.One, int dataBits = 8)
- {
- PortName = portName;
- BaudRate = baudRate;
- Parity = parity;
- StopBits = stopBits;
- DataBits = dataBits;
- client = new SerialPortClient();
- client.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口
- client.Connected = (client, e) =>
- {
- ConnectionChanged?.Invoke(this, IsConnected);
- return EasyTask.CompletedTask;
- };//成功连接到端口
- client.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
- client.Closed = (client, e) =>
- {
- ConnectionChanged?.Invoke(this, IsConnected);
- return EasyTask.CompletedTask;
- };//从端口断开连接,当连接不成功时不会触发。
- client.Received = async (c, e) =>
- {
- Data = e.ByteBlock.Span.ToString(Encoding); //接收到数据
- DataReceived?.Invoke(this, Data);
- };
- TouchSocketConfig touchSocket = new TouchSocketConfig();
- touchSocket.SetSerialPortOption(new SerialPortOption()
- {
- BaudRate = BaudRate,//波特率
- DataBits = DataBits,//数据位
- Parity = Parity,//校验位
- PortName = PortName,//COM
- StopBits = StopBits//停止位
- });
- if ( terminator == Terminator.None )
- {
- touchSocket.SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromSeconds(0.8) });
- }
- if ( terminator == Terminator.CRLF )
- {
- touchSocket.SetSerialDataHandlingAdapter(() => new TerminatorPackageAdapter("\r\n"));
- }
- client.Setup(touchSocket);
- }
- /// <summary>
- /// 异步连接到串口扫描枪
- /// </summary>
- /// <returns></returns>
- public async Task<bool> ConnectAsync()
- {
- if ( ( await client.TryConnectAsync() ).IsSuccess )
- {
- ConnectionChanged?.Invoke(this, IsConnected);
- //调用CreateWaitingClient获取到IWaitingClient的对象。
- WaitClient = client.CreateWaitingClient(new WaitingOptions()
- {
- FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
- {
- return true;
- }
- });
- return true;
- }
- return false;
- }
- /// <summary>
- /// 连接到串口扫描枪
- /// </summary>
- /// <returns></returns>
- public bool Connect()
- {
- if ( client.TryConnect().IsSuccess )//尝试连接到端口
- {
- //调用CreateWaitingClient获取到IWaitingClient的对象。
- WaitClient = client.CreateWaitingClient(new WaitingOptions()
- {
- FilterFunc = response => //设置用于筛选的fun委托,当返回为true时,才会响应返回
- {
- return true;
- }
- });
- return true;
- }
- return false;
- }
- /// <summary>
- /// 断开连接到串口扫描枪
- /// </summary>
- public void Disconnect()
- {
- if ( IsConnected )
- {
- client.Close();
- ConnectionChanged?.Invoke(this, IsConnected);
- }
- }
- /// <summary>
- /// 发送数据到串口扫描枪,并等待返回数据。
- /// </summary>
- /// <param name="msg"></param>
- /// <param name="millisecondsTimeout"></param>
- /// <returns></returns>
- public string SendThenReturn(string msg, int millisecondsTimeout = 5000)
- {
- //然后使用SendThenReturn。
- SendData?.Invoke(this, msg);
- byte[] returnData = WaitClient.SendThenReturn(Encoding.GetBytes(msg), millisecondsTimeout);
- DataReceived?.Invoke(this, Encoding.GetString(returnData));
- return Encoding.GetString(returnData);
- }
- /// <summary>
- /// 异步发送数据到串口扫描枪,并等待返回数据。
- /// </summary>
- /// <param name="msg"></param>
- /// <param name="millisecondsTimeout"></param>
- /// <returns></returns>
- public async Task<string> SendThenReturnAsync(string msg, int millisecondsTimeout = 5000)
- {
- SendData?.Invoke(this, msg);
- byte[] returnData = await WaitClient.SendThenReturnAsync(Encoding.GetBytes(msg), millisecondsTimeout);
- DataReceived?.Invoke(this, Encoding.GetString(returnData));
- return Encoding.GetString(returnData);
- }
- /// <summary>
- /// 发送数据到串口扫描枪
- /// </summary>
- /// <param name="msg"></param>
- public void Send(string msg)
- {
- if ( IsConnected )
- {
- SendData?.Invoke(this, msg);
- client.Send(Encoding.GetBytes(msg)); //发送数据到串口扫描枪
- }
- }
- public void Dispose()
- {
- if ( WaitClient != null )
- {
- WaitClient = null;
- }
- if ( client != null )
- {
- client.Dispose();
- client = null;
- }
- }
- }
- }
|