using HighWayIot.Log4net;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.SerialPorts;
using TouchSocket.Sockets;

namespace HighWayIot.TouchSocket
{
    public class TouchSocketCOM
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static LogHelper _logHelper = LogHelper.Instance;

        /// <summary>
        /// 懒加载
        /// </summary>
        private static readonly Lazy<TouchSocketCOM> lazy = new Lazy<TouchSocketCOM>(() => new TouchSocketCOM());

        public static TouchSocketCOM Instance => lazy.Value;

        public Action<string> ComAction;

        /// <summary>
        /// 创建串口连接
        /// </summary>
        public async Task CreateConnection()
        {
            try
            {
                var client = new SerialPortClient();
                client.Connecting = (c, e) => { return EasyTask.CompletedTask; };//即将连接到端口
                client.Connected = (c, e) => { return EasyTask.CompletedTask; };//成功连接到端口
                client.Closing = (c, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
                client.Closed = (c, e) => { return EasyTask.CompletedTask; };//从端口断开连接，当连接不成功时不会触发。
                client.Received = (c, e) =>
                {
                    //收到信息
                    string mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
                    ComAction.Invoke(mes);
                    return EasyTask.CompletedTask;
                };

                await client.SetupAsync(new TouchSocketConfig()
                     .SetSerialPortOption(new SerialPortOption()
                     {
                         BaudRate = 9600,//波特率
                         DataBits = 8,//数据位
                         Parity = System.IO.Ports.Parity.None,//校验位
                         PortName = "COM5",//COM
                         StopBits = System.IO.Ports.StopBits.One//停止位
                     })
                     .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
                     .ConfigurePlugins(a =>
                     {
                         //a.Add<MyPlugin>();
                     }));

                await client.ConnectAsync();
                _logHelper.Info("COM5连接成功");
            }
            catch (Exception ex)
            {
                _logHelper.Error("连接失败", ex);
            }
        }
    }
}
