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

using System.Management;

namespace SerialPort
{
    ///-----------------------------------------------------------------------------------
    ///FrmMain :KW01-A1工程的窗体                                                          
    ///目    的:
    ///日    期:                                             
    ///编 程 者:
    ///-----------------------------------------------------------------------------------
    public partial class FrmMain : Form
    {      
        //1. 窗体类的临时变量区
        private System.IO.Ports.SerialPort UARTport;   //声明系统工具-串口对象的变量声明
        private Uart uart1;                          //声明一个自定义的Uart类型（串口操作）的变量
        private PCNode pcNode1;                      //声明一个自定义的PCNode类型的变量
          
   
        //2. 构造函数（启动窗体最先执行程序）
        public FrmMain()
        {
            //系统生成的构造函数（初始化窗体的元素）
            InitializeComponent();        
            //禁止检测跨线程调用异常(
            CheckForIllegalCrossThreadCalls = false;  
            //初始化窗体类临时变量
            UARTport = null;          //初始化“系统工具-串口对象”
            uart1 = null;             //初始化“Uart类型（串口操作）对象”
            pcNode1 = new PCNode();   //
       }
        
        //3. 加载窗体事件程序（在构造函数之后执行的程序）
        private void FrmMain_Load(object sender, EventArgs e)
        {
            string s1;
            this.tb_statue.Text = "运行状态：FrmMain_Load开始,调用PCNode类内部函数，寻找PCNode...";
            this.tb_statue.Refresh();

            if (uart1 != null && uart1.IsOpen) uart1.close();
            s1 = pcNode1.findPCNode();           //调用PCNode类内部函数，寻找PCNode
            uart1 = pcNode1.PCNode_Uart1;

            this.tb_statue.Text = "运行状态：" + s1;
            this.tb_statue.Refresh();

            lbl_PC_Node_State.Text = s1;

            //保留编程参考：绑定DataReceived事件(即串口接收中断处理函数）
            if (uart1 != null)
            {
                UARTport = uart1.port;
                UARTport.DataReceived += new System.IO.Ports. //添加串口对象变量的接收事件的响应函数
                         SerialDataReceivedEventHandler(this.UARTport_recvData);
            }
            //uart1.setReceInt(2);           //设置触发DataRecieved事件的字节数（目的是关闭该事件）
            //uart1.sendData(B1, B1.Length); //发送握手数据
            
        }

        //========================以下是本窗体的各个事件响应函数==========================
       
        //------------------------单击“检测PC节点”按钮----------------------------------
        private void btnCheckPcNode_Click(object sender, EventArgs e)
        {

            //if (_port1.IsOpen) 
            this.tb_statue.Text = "运行状态：" + "单击“检测PC节点”按钮...";
            this.tb_statue.Refresh();

            FrmMain_Load(sender, e);

            this.tb_statue.Text = "运行状态：" + "单击“检测PC节点”按钮...退出";
        }

        //--------------------------单击窗口关闭“X”按钮---------------------------------
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {    
            this.Dispose();
            Application.Exit();
            //if (uart1 == null) return;
            ////如果串口未关闭，则关闭
            //if (uart1.IsOpen) uart1.close(); 


        }
        
        
       
 

        private void btnVerifyRF_Click(object sender, EventArgs e)
        {

            // 1. 临时变量声明
            byte n;             //测试数据字节数
            int i;
            byte len;           //[命令+数据]字节数（总帧长度-1B帧头 - 1B len - 1B帧尾）
            string s1;
         
            this.Txt_recv1.Text = "";
            this.Txt_recv2.Text = "";
            string sendtext = "1234567890123456789012345678901234567890123456789012345";
            this.Txt_recv1.Refresh();
            this.Txt_recv2.Refresh();
            s1="运行状态：" + "单击“验证RF收发”按钮...";
            this.tb_statue.Text =s1;
            this.tb_statue.Refresh();
                  
            btnVerifyRF.Enabled = false;

            // 2. 临时变量赋值
            n = 55;

            byte[] writeDataArray = System.Text.Encoding.Default.GetBytes(sendtext); //String转化为Byte[]

            //len = (byte)(n + 1);
            len = (byte)(n + 2);    //增加一个是否检测能量场的字节

            byte[] SendByteArray = new byte[len + 4];

            // 组帧
            try
            {
                SendByteArray[0] = (byte)'P';      //帧头

                SendByteArray[1] = len;            //帧长
                SendByteArray[2] = 0xFF;           //硬件地址


                for (i = 3; i <= n + 2; i++)
                {
                    SendByteArray[i] = writeDataArray[i - 3];
                }

                SendByteArray[n + 3] = (byte)'N';      //填充


                SendByteArray[n + 4] = (byte)'C';      //帧尾

                //
                //发送、接收、显示
                //sendRecv(SendByteArray,1,5500);
                uart1.setReceInt(60);   //测试串口接收中断使用，改为60。  2015.11.30
                uart1.sendData(SendByteArray, SendByteArray.Length);  // 通过串口发送数据
                //System.Threading.Thread.Sleep(time);
                s1 = s1 +"已经发送,等待接收中断...";
                this.tb_statue.Text = s1;
                this.tb_statue.Refresh();
               

                 btnVerifyRF.Enabled = true;
            }
            catch
            {
                this.Txt_recv1.Text = "有误:可能没串口！";
                this.tb_statue.Text = "运行状态：" + "单击“验证RF收发”按钮...可能没串口！";
                this.tb_statue.Refresh();
                btnVerifyRF.Enabled = true;
             }  
        }


        //-------------------------------串口接收事件的响应函数---------------------------
        private void UARTport_recvData(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string s1 = string.Empty;
            int i,value;
            double temp;

            s1 = "";

            Thread.Sleep(300);

            PublicVar.g_ReceiveByteArray = uart1.recvData();    //调用串口接收函数
            for (i = 0; i < PublicVar.g_ReceiveByteArray.Length; i++)
            {
                s1 = s1 + " " + Convert.ToString(PublicVar.g_ReceiveByteArray[i], 10);
            }
            if (s1 != "")
            {
                value = Convert.ToInt16(PublicVar.g_ReceiveByteArray[57]) * 256 + Convert.ToInt16(PublicVar.g_ReceiveByteArray[58]);
                temp = (value*3300.0)/65536.0;
                temp = 25-(temp-706)/1.62;
                this.Txt_recv1.Text = "当前物理量: Target芯片温度：" + temp.ToString(".##") + "度";//将封装在帧尾前两个字节的温度信息显示出来。
                this.Txt_recv2.Text = s1;//.Substring(0, 60);  2015.11.30改
                //MessageBox.Show("运行到此处1");
            }
            //this.Txt_recv2.Text = "Interrupt--- " + System.Text.Encoding.Default.GetString(PublicVar.g_ReceiveByteArray);
        }
            

        //-------------------------
        //private void sendRecv(byte[] SendByteArray,int cnt,int time)

        //{
        //    byte[] recvData;
        //    int i;
        //    this.tb_statue.Text += "正在发送...";
        //    this.tb_statue.Refresh();
        //    recvData = pcNode1.PCNodeSendReturn(SendByteArray, cnt, time);

        //    if (recvData.Length <= 0)
        //    {
        //        this.tb_statue.Text += "无数据返回";
        //        this.tb_statue.Refresh();
        //    }
        //    else
        //    {
        //        this.tb_statue.Text += "有数据返回";
        //        this.tb_statue.Refresh();
        //        this.Txt_recv1.Text = string.Empty;
        //        for (i = 0; i < recvData.Length; i++)
        //            // this.Txt_recv.Text += "-" + recvData[i].ToString("D3").ToUpper() + " ";
        //            this.Txt_recv1.Text += recvData[i].ToString("X2").ToUpper() + " ";
        //       // this.Txt_recv1.Text += "当前能量值" + Txt_recv1.Text.Substring(0, 2);
        //        //MessageBox.Show("运行到此处2");
        //        this.Txt_recv2.Text = System.Text.Encoding.Default.GetString(recvData);
        //    }
        //}
        

        //---------------------------单击“清空显示框”按钮-------------------------------
        private void btnClear1_Click(object sender, EventArgs e)
        {
            this.tb_statue.Text = "运行状态：" + "单击“清空显示框”按钮。";
            this.tb_statue.Refresh();
           
            this.Txt_recv1.Text = "";
            this.Txt_recv2.Text = "";
        }

        private void rBtnTargetComm_CheckedChanged(object sender, EventArgs e)
        {
           

            this.tb_statue.Text = "运行状态：" + "选择“与Target通信”单选框。";
            this.tb_statue.Refresh();

         
        }
        
       



       
    }
}
