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 Test_BMS
{
    public partial class Form1 : Form
    {
        arDev.BMS bms;
        public Form1()
        {
            InitializeComponent();
            bms = new arDev.BMS();
            bms.BMSDataReceive += Bms_BMSDataReceive;
            //bms.Message += Bms_Message;
        }

        private void Bms_Message(object sender, arDev.arRS232.MessageEventArgs e)
        {
            var sb = new System.Text.StringBuilder();
            if (e.Data != null)
            {
                foreach (var b in e.Data)
                    sb.Append(" " + b.ToString("X2"));
            }
            else sb.Append(e.Message);
            addmsg($"{e.MsgType}:{sb}");
        }

        private void Bms_BMSDataReceive(object sender, EventArgs e)
        {
            //최종 데이터가 수신되는 경우
            string msg = $"{bms.Current_Volt}v,{bms.Current_Level}%,{bms.Current_Amp}/{bms.Current_MaxAmp}";
            addmsg("Recv:" + msg);
        }

     
        void addmsg(string m)
        {
            if (logTextBox1.InvokeRequired)
            {
                logTextBox1.BeginInvoke(new Action(() => {
                    logTextBox1.AddMsg(m);
                }));
            }
            else
            {
                logTextBox1.AddMsg(m);
            }
        }

        private void Bms_RxData(object sender, arDev.BMS.ReceiveDataEventArgs e)
        {
            addmsg("Rx:" + e.StrValue);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.comboBox1.Items.Clear();
            foreach (var port in System.IO.Ports.SerialPort.GetPortNames())
                this.comboBox1.Items.Add(port);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bms.BaudRate = int.Parse(this.comboBox2.Text);
            bms.PortName = comboBox1.Text;
            bms.Open();
            addmsg($"open:{bms.IsOpen}");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bms.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            bms.SendQuery();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            comboBox1.Text = "COM41";
        }
    }
}
