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 WindowsApplication1
{
    public partial class Form_term : Form
    {
        public SerialPort port;
        public bool connected = false; 

        public Form_term(string PortName)
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            Text = "Terminal on " + PortName;
            try
            {
                port = new SerialPort(PortName);
                port.Open();
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Unable to open port "+PortName);
                port = null;
                connected = false;
                this.Close();
            }
            finally
            {
                if (port != null && port.IsOpen)
                {
                    port.BaudRate = 9600;
                    port.StopBits = StopBits.One;
                    port.Parity = Parity.None;
                    port.DataBits = 8;
                    port.NewLine = "\n\r";
                    connected = true;
                    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
                    this.FormClosed += new FormClosedEventHandler(Form2_FormClosed);
                    tb1.KeyPress += new KeyPressEventHandler(tb1_KeyPress);
                    tb1.Enabled = true;
                }
            } 
        }
        void tb1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                log(tb1.Text);
                port.Write(tb1.Text + "\n");
                tb1.Clear();
            }
        }


        void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(connected) port.Close();
        }



        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string s;
            while (port.BytesToRead > 0)
            {
                s = ((char)port.ReadChar()).ToString();
                if (s == "\r") { s = ""; }
                if (s == "\n") { rtb1.AppendText("\n"); rtb1.ScrollToCaret(); s = ""; }
                rtb1.AppendText(s);
            }
        }

        public void log(string ainp)
        {
            rtb1.AppendText(ainp + "\n");
            rtb1.ScrollToCaret();
        }

   
    }
}