using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace LightApp
{
    public partial class Form1 : Form
    {
        SerialPort Comm = new SerialPort();
        string strnewdata = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            this.comboPortName.Items.AddRange(ports);
            this.comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
            Comm.DataReceived += Comm_DataReceived;
         }

        void Comm_DataReceived(object sender,SerialDataReceivedEventArgs e)
        {
            this.BeginInvoke(new Action(()=>
                {
                    string serialdata = Comm.ReadExisting();
                    strnewdata += serialdata;
                    if(strnewdata.LastIndexOf("111111")>=0)
                    {
                        txtLight.Text = "无光照";
                        this.pictureBox1.Image = LightApp.Resource1.lightOff;
                        strnewdata = "";
                    }
                    if(strnewdata.LastIndexOf("222222")>=0)
                    {
                        txtLight.Text = "有光照";
                        this.pictureBox1.Image = LightApp.Resource1.lightOn;
                        strnewdata = "";
                    }
                }
                ),null);
        }

        private void buttonOpenCloseCom_Click(object sender, EventArgs e)
        {
            if (Comm.IsOpen)
            {
                Comm.Close();
                this.txtLight.Text = "";
            }
            else
            {
                Comm.PortName = comboPortName.Text;
                Comm.BaudRate = 9600;
                try
                { 
                  Comm.Open();
                }
                catch(Exception ex)
                {
                    Comm = new SerialPort();
                    MessageBox.Show(ex.Message);
                }
            }

            buttonOpenCloseCom.Text = Comm.IsOpen ? "关闭串口" : "打开串口";
        }
    }
}
