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;

namespace Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //CheckForIllegalCrossThreadCalls = false;

            this.Load += new EventHandler(Form1_Load);

            button1.Click += new EventHandler(button1_Click);
            button2.Click += new EventHandler(button2_Click);
            button3.Click += new EventHandler(button3_Click);
            button4.Click += new EventHandler(button4_Click);
            button5.Click += new EventHandler(button5_Click);
        }

        Communication.Communication com = new Communication.Communication();

        void Form1_Load(object sender, EventArgs e)
        {
            com.localIPAddress = com.GetLocalIPAddressList()[0];

            com.DataArrival += new Communication.Communication.DataArrivalHandler(com_DataArrival);
        }

        void button1_Click(object sender, EventArgs e)
        {
            com.InitSocket(Communication.Communication.PortType.PT_LAN);

            button1.Enabled = false;
        }

        void button2_Click(object sender, EventArgs e)
        {
            com.InitSocket(Communication.Communication.PortType.PT_WAN);

            button2.Enabled = false;
        }

        void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
        }

        void button4_Click(object sender, EventArgs e)
        {
            com.LAN_Scan_Device_Online();
        }

        void button5_Click(object sender, EventArgs e)
        {
            com.LAN_Scan_Device_Online(byte.Parse(textBox1.Text), byte.Parse(textBox2.Text));
        }

        void com_DataArrival(byte subnetID, byte deviceID, int deviceType, int operateCode, int lengthOfAddtional, ref byte[] addtional)
        {
            this.Invoke(new Action(delegate
            {
                dataGridView1.Rows.Add(1);

                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["colSubnetID"].Value = subnetID.ToString();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["colDeviceID"].Value = deviceID.ToString();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["colDeviceType"].Value = deviceType.ToString();
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["colOperateCode"].Value = "0x" + operateCode.ToString("X4");
                dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["colLengthOfAddtional"].Value = lengthOfAddtional.ToString();
            }));
        }
    }
}
