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 smokesenorApp
{
    public partial class Form1 : Form
    {
        private SerialPort comm = new SerialPort();//我加的，新建一个串口变量
        string newstrdata = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            comboPortName.Items.AddRange(ports);
            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();

                newstrdata += serialdata;
                if (newstrdata.LastIndexOf("444444") >= 0)
                {
                    txtSmoke.Text = "无烟雾气体";
                    SmokeBaoJing.BackColor = Color.GreenYellow;//则保持绿色不变
                    newstrdata = "";
                }

                if (newstrdata.LastIndexOf("333333") >= 0)
                {
                    txtSmoke.Text = "有烟雾气体";
                    SmokeBaoJing.BackColor = Color.Red;//就变为红色
                    newstrdata = "";

                }

            }), null);
        }


        private void buttonOpenCloseCom_Click(object sender, EventArgs e)
        {
            //根据当前串口对象，来判断操作  
            if (comm.IsOpen)
            {
                comm.Close();
            }
            else
            {
                //关闭时点击，则设置好端口，波特率后打开  
                comm.PortName = comboPortName.Text;
                comm.BaudRate = 9600;
                try
                {
                    comm.Open();

                }
                catch (Exception ex)
                {
                    //捕获到异常信息，创建一个新的comm对象，之前的不能用了。  
                    comm = new SerialPort();
                    //现实异常信息给客户。  
                    MessageBox.Show(ex.Message);
                }
            }
            //设置按钮的状态  
            buttonOpenCloseCom.Text = comm.IsOpen ? "关闭串口" : "打开串口";
        }
    }
}
