using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SLZ_4
{
    public partial class ConfigPLC : Form
    {
        public ConfigPLC()
        {
            InitializeComponent();
        }

        private void CodeCon_Click(object sender, EventArgs e)
        {
            FormMain.form.updatePLC(CodePort.Text, Convert.ToInt32(CodeBaud.Text));
            Thread.Sleep(100);
            UpdateStatus(FormMain.form.plcObj.PLC.IsOpen());
        }

        public void refreshPort()
        {
            CodePort.Items.Clear();
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            CodePort.Items.AddRange(ports);
        }
        private void CodeRefresh_Click(object sender, EventArgs e)
        {
            refreshPort();
        }

        private void CodeBreak_Click(object sender, EventArgs e)
        {
            if (FormMain.form.plcObj != null)
            {
                FormMain.form.plcObj.closePLC();

                Thread.Sleep(100);
                UpdateStatus(FormMain.form.plcObj.PLC.IsOpen());
            }
        }

        public void UpdateStatus(bool status)
        {
            if (status)
            {
                CodeIsComm.Text = "已打开";
                CodeIsComm.BackColor = Color.Green;
                CodeCon.Enabled = false;
                CodeBreak.Enabled = true;
            }
            else
            {
                CodeIsComm.Text = "未打开";
                CodeIsComm.BackColor = Color.Red;
                CodeCon.Enabled = true;
                CodeBreak.Enabled = false;
            }
        }
        public void setConfig(ref PLC_PARAM plcParam)
        {
            refreshPort();
            CodeBaud.Text = plcParam.iBaudrate.ToString();
            CodePort.Text = plcParam.sPort;
            if (FormMain.form.plcObj != null)
            {
                UpdateStatus(FormMain.form.plcObj.PLC.IsOpen());
            }
            else
            {
                UpdateStatus(false);
            }
        }
    }
}
