using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.Thick.Base.UI
{
    public class LCUS1 : INotifyPropertyChanged
    {
        public string PortName { get; set; } = "COM6";
        public string ErrMsg { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void On()
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    SerialPort serial = new SerialPort();
                    serial.PortName = PortName;
                    serial.BaudRate = 9600;
                    serial.Open();
                    byte[] buf = new byte[] { 0xa0, 0x01, 0x01, 0xa2 };
                    serial.Write(buf, 0, buf.Length);
                    //等0.5s确保发送出去了
                    Task.Delay(500).Wait();
                    serial.Close();
                    ErrMsg = $"{DateTime.Now} ON";
                }
                catch (Exception e)
                {
                    ErrMsg = e.Message;
                }
            });
        }
        public void Off()
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    SerialPort serial = new SerialPort();
                    serial.PortName = PortName;
                    serial.BaudRate = 9600;
                    serial.Open();
                    byte[] buf = new byte[] { 0xa0, 0x01, 0x00, 0xa1 };
                    serial.Write(buf, 0, buf.Length);
                    //等0.5s确保发送出去了
                    Task.Delay(500).Wait();
                    serial.Close();
                    ErrMsg = $"{DateTime.Now} OFF";
                }
                catch (Exception e)
                {
                    ErrMsg = e.Message;
                }
            });
        }
    }
}
