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 TempHumApp
{
    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();
            this.comboBoxPortName.Items.AddRange(ports);
            this.comboBoxPortName.SelectedIndex = comboBoxPortName.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("0101")>=0)
                     {
                         int tempindex = strnewdata.LastIndexOf("0101");
                         if(strnewdata.Substring(tempindex).Length>=6)
                         {
                             txtTemp.Text = strnewdata.Substring(tempindex + 4, 2);
                         }
                     }

                     if (strnewdata.LastIndexOf("0102") >= 0)
                     {
                         int humindex = strnewdata.LastIndexOf("0102");
                         if (strnewdata.Substring(humindex).Length >= 6)
                         {
                             txtHum.Text = strnewdata.Substring(humindex + 4, 2);
                         }
                     }

                       }),null);
        }

        private void buttonOpenCloseCom_Click(object sender, EventArgs e)
        {
                  if(Comm.IsOpen)
                  {
                      Comm.Close();
                      txtHum.Text = "";
                      txtTemp.Text = "";
                  }
                  else
                  {
                      Comm.PortName = this.comboBoxPortName.Text;
                      Comm.BaudRate = 9600;
                      try
                      { 
                           Comm.Open();                     
                      }
                      catch(Exception ex)
                      {
                          Comm = new SerialPort();
                          MessageBox.Show(ex.Message);
                      }
                  }
                  this.buttonOpenCloseCom.Text = Comm.IsOpen ? "关闭串口" : "打开串口";
                

        }














    }
}
