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_di
{
    public partial class Form1 : Form
    {
        IntPtr hPort;
        public Form1()
        {
            InitializeComponent();
            btnCloseCom.Enabled = false;
            LoadComPort();
        }

        private void btnOpenCom_Click(object sender, EventArgs e)
        {
            //Open com port
            this.hPort = PACNET.UART.Open(cmbComPort.Text + "," + txtBaurdRate.Text);

            if (hPort == (IntPtr)(-1))
            {
                MessageBox.Show("Open port is error,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 btnRead_Click(object sender, EventArgs e)
        {
            uint DiValue = 0;
            bool iRet;
          
            //Read module data
            iRet = PACNET.PAC_IO.ReadDI(hPort, PACNET.PAC_IO.PAC_REMOTE_IO(Convert.ToInt32(txtAddress.Text)), Convert.ToInt16(txtChannel.Text), ref DiValue);

            if (iRet == false)
                MessageBox.Show("Read error");
            else 
                txtReadData.Text = DiValue.ToString("X");
        }

        private void btnRead_MF_Click(object sender, EventArgs e)
        {
            uint DiValue = 0;
            bool iRet;

            //Read module data
            iRet = PACNET.PAC_IO.ReadDI_MF(hPort, PACNET.PAC_IO.PAC_REMOTE_IO(Convert.ToInt32(txtAddress.Text)), Convert.ToInt16(txtChannel.Text), ref DiValue);

            if (!iRet)
            {
                uint ec = PACNET.ErrHandling.GetLastError();
                MessageBox.Show(((PACNET.ErrCode)ec).ToString() + "\nError Code: 0x" + ec.ToString("X"));
            }

            txtReadData.Text = DiValue.ToString();
        }
    }
}