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 rentihongwaiApp
{
    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.comboPortName.Items.AddRange(ports);
             if(comboPortName.Items.Count>0)
             {
                 comboPortName.SelectedIndex = 0;
             }
             Comm.DataReceived += Comm_DataReceived;
        }


        void Comm_DataReceived(object sender,SerialDataReceivedEventArgs e) 
        {
            this.BeginInvoke(new Action(()=>
                {
                    string serialdata = Comm.ReadExisting();
                    strnewdata += serialdata;
                    if(strnewdata.LastIndexOf("555555")>=0)
                    {
                        txtPerson.Text = "当前无人";
                        HongwaiBaoJing.BackColor = Color.GreenYellow;
                        strnewdata = "";
                    }
                    if(strnewdata.LastIndexOf("666666")>=0)
                    {
                        txtPerson.Text = "当前有人";
                        HongwaiBaoJing.BackColor = Color.Red;
                        strnewdata = "";
                    }
                }),null);
        }
        private void buttonOpenCloseCom_Click(object sender, EventArgs e)
        {
            if (Comm.IsOpen)
            {
                Comm.Close();
            }
            else
            {
                Comm.PortName = this.comboPortName.Text;
                Comm.BaudRate = 9600;
                try
                {
                    Comm.Open();
                }
                catch(Exception  ex)
                {
                    MessageBox.Show(ex.Message);
                
                }
            }
        }
    }
}
