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

namespace _7K87K_ai
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //Load com port data to comobox Object
            LoadComPort();
            btnCloseCOM.Enabled = false;
        }
        IntPtr hPort;
        private void btnOpenCOM_Click(object sender, EventArgs e)
        {
            //Open com port
            hPort = PACNET.UART.Open(cmbComPort.Text + "," + txtBaurdRate.Text);
           
            if (hPort == (IntPtr)(-1))
            {
                MessageBox.Show("error code" + PACNET.ErrHandling.GetLastError());
            }
            else
            {                
                btnOpenCOM.Enabled = false;
                btnCloseCOM.Enabled = true;
            }
        }
        private void LoadComPort()
        {          
            //Get number of COM port and  assign COM port name to list in cmbComPort.
            foreach (string s in SerialPort.GetPortNames())
            {               
                if(s != "COM1")cmbComPort.Items.Add(s);              
            }
            cmbComPort.SelectedIndex = 0;
        }
        private void btnCloseCOM_Click(object sender, EventArgs e)
        {
            //Close com port
            PACNET.UART.Close(hPort);
            btnOpenCOM.Enabled = true;
            btnCloseCOM.Enabled = false;
        }

        private void btnReadAI_Click(object sender, EventArgs e)
        {
            float fValue = 0;
            bool iRet;
            int iReadChannel = int.Parse(txtReadChannel.Text);
            int iChannel = int.Parse(txtChannel.Text);
                
            if (iReadChannel <= iChannel)
            {
                //Read data
                iRet = PACNET.PAC_IO.ReadAI(hPort, PACNET.PAC_IO.PAC_REMOTE_IO(Convert.ToInt32(txtAddress.Text)), iReadChannel, iChannel, ref fValue);
                if (iRet == false)
                {
                    MessageBox.Show("error code" + PACNET.ErrHandling.GetLastError());
                }
                else
                {
                    txtAIValue.Text = fValue.ToString();
                }
            }
            else
            {
                MessageBox.Show("Your read channel is error , please rewrite read channel");
            }
        }
    }
}