using Modbus;
using Modbus.Device;
using System.IO.Ports;
using System.Net.Sockets;
using System;
using System.Threading.Tasks;
using vmsnet.Configures;
using AR;
using System.Windows.Media.Animation;
using System.Security.Cryptography;

namespace vmsnet
{
    public class JdModbusRTU : IDisposable
    {
        protected ModbusSerialMaster master;

        public string PortName { get; private set; }
        public string ErrorMessage { get; protected set; }
        public RtuConfigure Configure;

        protected SerialPort port;


        public bool IsOpen
        {
            get
            {
                return port?.IsOpen ?? false;
            }
        }
        public JdModbusRTU(string comPort, RtuConfigure configure)
        {
            this.PortName = comPort;
            this.Configure = configure;
            ErrorMessage = "";
        }

        public void Dispose()
        {
            Task.Run(() =>
            {
                if (port != null)
                    port.Dispose();

            });
        }
        public void Close()
        {
            if (port != null) port.Close();
        }

        public bool Open(string pname = "")
        {
            if (pname.isEmpty() == false) this.PortName = pname;
            if (string.IsNullOrEmpty(this.PortName))
            {
                ErrorMessage = "포트명이 입력되지 않았습니다";
                return false;
            }
            
            if (port != null && port.IsOpen) port.Close();
            //if (port == null) port = new SerialPort(this.PortName);
            port = new SerialPort(this.PortName);
            port.BaudRate = Configure.BaudRate;
            port.Parity = Configure.Parity;
            port.DataBits = Configure.DataBits;
            port.StopBits = Configure.StopBits;
            port.ReadTimeout = 1000;
            port.WriteTimeout = 1000;

            try
            {
                port.Open();
                if (port.IsOpen == false) ErrorMessage = "포트가 열리지 않았습니다";
                else ErrorMessage = string.Empty;

                if (port.IsOpen)
                    master = ModbusSerialMaster.CreateRtu(port);

                return port.IsOpen;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                return false;
            }
        }

    }
}
