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_do
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            btnCloseCom.Enabled = false;
            LoadComPort();
        }
        IntPtr hPort;
        private void btnOpenCom_Click(object sender, EventArgs e)
        {
            //Open com port
            hPort = PACNET.UART.Open(cmbComPort.Text + "," + txtBaudRate.Text);
            if (hPort == (IntPtr)(-1))
                MessageBox.Show("Open port is error,error code " + PACNET.ErrHandling.GetLastError());
            else
            {
                btnCloseCom.Enabled = true;
                btnOpenCom.Enabled = false;
            }
        }
        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 btnWriteDO_Click(object sender, EventArgs e)
        {
            bool iRet;

            //Write DO data
            iRet = PACNET.PAC_IO.WriteDO(hPort, PACNET.PAC_IO.PAC_REMOTE_IO(Convert.ToInt16(txtAddress.Text)), Convert.ToInt16(txtChannel.Text), Convert.ToUInt32(txtWriteData.Text, 16));

            if (iRet == false)
                MessageBox.Show("write do data error");
        }

        private void btnWriteDO_MF_Click(object sender, EventArgs e)
        {
            bool iRet;

            //Write DO data
            iRet = PACNET.PAC_IO.WriteDO_MF(hPort, PACNET.PAC_IO.PAC_REMOTE_IO(Convert.ToInt16(txtAddress.Text)), Convert.ToInt16(txtChannel.Text), Convert.ToUInt32(txtWriteData.Text, 16));

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