using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FlyADBase;
using FObjBase;

using System.Net;
using System.ComponentModel;
using Misc;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Forms.DataVisualization.Charting;

namespace Flyad7_WPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        FlyAD7 flyad;
        DebugAppParam param;
        AutoForwBackw autofb;
        FlyADClientUI flyad_clientui;
        AutoSync mAutoSync;

        public MainWindow()
        {
            InitializeComponent();
            InitializeComponent2();
            InitializeComponent3();
            InitializeComponent4();

            flyad = new FlyAD7();
            param = new DebugAppParam();
            param.Load();

            autofb = new AutoForwBackw(flyad);
            flyad_clientui = new FlyADClientUI(flyad);

            mAutoSync = new AutoSync();
            mAutoSync.Init(flyad);

            Misc.BindingOperations.SetBinding(param, "HasCRC", flyad, "HasCRC");
            Misc.BindingOperations.SetBinding(param, "FB_Pos1", autofb, "FB_Pos1", Misc.BindingOperations.BindingMode.TwoWay);
            Misc.BindingOperations.SetBinding(param, "FB_Pos2", autofb, "FB_Pos2", Misc.BindingOperations.BindingMode.TwoWay);

            this.DataContext = flyad;
            this.grid_param.DataContext = param;
            this.groupBox_fb.DataContext = autofb;
            this.groupBox_adpos.DataContext = flyad_clientui;

            flyad.GridEvent += flyad_GridEvent;
            flyad.TimeGridEvent += flyad_TimeGridEvent;
            flyad.TimeGridAdvEvent += flyad_TimeGridAdvEvent;

            flyad.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == "OStatus") 
                {
                    Button[] bit = new Button[4] { button_bit0, button_bit1, button_bit2, button_bit3 };
                    for (int i = 0; i < bit.Length; i++)
                    {
                        if (Misc.MyBase.CHECKBIT(flyad.OStatus, i))
                        {
                            bit[i].Content = "1";
                        }
                        else 
                        {
                            bit[i].Content = "0";
                        }
                    }
                }
            };
            param.PropertyChanged += (s, e) =>
            {
                param.Save();
            };

            FObjBase.PollModule.Current.Start();
            //Thread t = new Thread(() =>
            //{
            //    while (true)
            //    {
            //        FObjBase.PollModule.Current.OnPoll();
            //        Thread.Sleep(10);
            //    }
            //});
            //t.IsBackground = true;
            //t.Start();
        }


        private void flyad_TimeGridAdvEvent(object sender, TimeGridAdvEventArgs e)
        {
            Series series_pos = chart3.Series[0];
            Series series_ad = chart3.Series[1];

            while (series_pos.Points.Count() > 5000)
            {
                series_pos.Points.RemoveAt(0);
            }
            while (series_ad.Points.Count() > 5000)
            {
                series_ad.Points.RemoveAt(0);
            }
            
            foreach (var data in e.Data)
            {
                int pos = data.pos;
                int ad = data.ad;
                DateTime dt = data.dt;

                series_pos.Points.AddY(pos);
                DataPoint p = series_pos.Points.Last();
                p.AxisLabel = $"{dt:ss.ff}";

                series_ad.Points.AddY(ad);
                p = series_ad.Points.Last();
                p.AxisLabel = $"{dt:ss.ff}";
            }

            chart3.ChartAreas[0].AxisX.Minimum = 0;
            chart3.ChartAreas[0].AxisX.Maximum = e.Data.Count();
            
        }

        /// <summary>
        /// grid图
        /// </summary>
        void InitializeComponent2()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // chart1
            // 

            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BackColor = System.Drawing.Color.OldLace;
            //chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.Name = "Default";
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart1.ChartAreas.Add(chartArea1);



            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.Alignment = System.Drawing.StringAlignment.Near;
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Right;
            legend1.IsDockedInsideChartArea = true;
            legend1.DockedToChartArea = chartArea1.Name;
            //legend1.IsTextAutoFit = false;
            legend1.Name = "Default";
            chart1.Legends.Add(legend1);

            series1.Name = "Series 1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = chartArea1.Name;
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = legend1.Name;
            series1.LegendText = "正向";
            series1.ShadowColor = System.Drawing.Color.Black;
            series1.ShadowOffset = 2;
            series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            chart1.Series.Add(series1);

            series2.Name = "Series 2";
            series2.BorderColor = System.Drawing.Color.Pink;
            series2.BorderWidth = 3;
            series2.ChartArea = chartArea1.Name;
            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series2.Color = System.Drawing.Color.Red;
            series2.Legend = legend1.Name;
            series2.LegendText = "反向";
            series2.ShadowColor = System.Drawing.Color.Black;
            series2.ShadowOffset = 2;
            series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            chart1.Series.Add(series2);

            //this.chart1.Location = new System.Drawing.Point(16, 32);
            chart1.Name = "chart1";

            chart1.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent3()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // chart1
            // 

            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BackColor = System.Drawing.Color.OldLace;
            //chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.Name = "Default";
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;
            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart2.ChartAreas.Add(chartArea1);



            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = false;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.IsTextAutoFit = false;
            legend1.Name = "Default";
            this.chart2.Legends.Add(legend1);
            //this.chart2.Location = new System.Drawing.Point(16, 32);
            this.chart2.Name = "chart2";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = "Default";
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = "Default";
            //series1.MarkerSize = 8;
            //series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series1.Name = "Series 1";
            series1.ShadowColor = System.Drawing.Color.Black;
            series1.ShadowOffset = 2;
            series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;

            this.chart2.Series.Add(series1);

            this.chart2.BackColor = System.Drawing.Color.Transparent;
        }
        void InitializeComponent4()
        {
            System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
            System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
            System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
            System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();

            // 
            // chart1
            // 
            chartArea1.Name = "chartArea1";
            chartArea1.AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisX.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisX.IsLabelAutoFit = true;
            chartArea1.AxisX.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont;
            chartArea1.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;

            chartArea1.AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));

            chartArea1.AxisY2.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            chartArea1.AxisY2.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.AxisY2.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));

            chartArea1.BackColor = System.Drawing.Color.OldLace;
            //chartArea1.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            //chartArea1.BackSecondaryColor = System.Drawing.Color.White;
            chartArea1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
            chartArea1.BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            chartArea1.ShadowColor = System.Drawing.Color.Transparent;


            chartArea1.CursorX.IsUserEnabled = true;
            chartArea1.CursorX.IsUserSelectionEnabled = true;
            chartArea1.CursorX.SelectionColor = System.Drawing.SystemColors.Highlight;
            //chartArea1.CursorY.IsUserEnabled = true;
            //chartArea1.CursorY.IsUserSelectionEnabled = true;
            //chartArea1.CursorY.SelectionColor = System.Drawing.SystemColors.Highlight;

            //对数坐标
            //chartArea1.AxisY.IsLogarithmic = true;
            //chartArea1.AxisY.LogarithmBase = Math.E;
            this.chart3.ChartAreas.Add(chartArea1);


            legend1.Name = "Default";
            legend1.BackColor = System.Drawing.Color.Transparent;
            legend1.Enabled = true;
            legend1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            legend1.Alignment = System.Drawing.StringAlignment.Near;
            legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Right;
            legend1.IsDockedInsideChartArea = true;
            legend1.DockedToChartArea = chartArea1.Name;
            //legend1.IsTextAutoFit = false;
            chart3.Legends.Add(legend1);



            series1.Name = "Series 1";
            series1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(26)))), ((int)(((byte)(59)))), ((int)(((byte)(105)))));
            series1.BorderWidth = 3;
            series1.ChartArea = chartArea1.Name;
            series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series1.Color = System.Drawing.Color.FromArgb(((int)(((byte)(220)))), ((int)(((byte)(65)))), ((int)(((byte)(140)))), ((int)(((byte)(240)))));
            series1.Legend = legend1.Name;
            series1.LegendText = "脉冲";
            //series1.MarkerSize = 8;
            //series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series1.ShadowColor = System.Drawing.Color.Black;
            series1.ShadowOffset = 2;
            series1.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series1.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;

            series2.Name = "Series 2";
            series2.BorderColor = System.Drawing.Color.DarkRed;
            series2.BorderWidth = 3;
            series2.ChartArea = chartArea1.Name;
            series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            series2.Color = System.Drawing.Color.Red;
            series2.Legend = legend1.Name;
            series2.LegendText = "AD";
            //series1.MarkerSize = 8;
            //series1.MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
            series2.ShadowColor = System.Drawing.Color.Black;
            series2.ShadowOffset = 2;
            series2.XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series2.YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
            series2.YAxisType = AxisType.Secondary;

            chart3.Series.Add(series1);
            chart3.Series.Add(series2);
            chart3.BackColor = System.Drawing.Color.Transparent;

            chart3.Name = "chart3";
        }
        #region grid
        void flyad_GridEvent(object sender, MiniGridEventArgs e)
        {
            if (param.HasGrid) 
            {
                
                run_gridmarker.Text = e.marker.ToString();

                System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
                System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];
                System.Windows.Forms.DataVisualization.Charting.Series series;

                if (e.direction == DIRECTION.FORWARD)
                {
                    series = series_forw;
                }
                else
                {
                    series = series_backw;
                }
                series.Points.Clear();

                int gridLen = flyad.PosLen / flyad.PosOfGrid;



                for (int i = 0; i < e.buf.Length; i++)
                {
                    int pos = (e.grid_start + i) * flyad.PosOfGrid;
                    int ad = e.buf[i];
                    series.Points.AddXY(pos, ad);
                    if (ad == Misc.MyBase.NULL_VALUE)
                        series.Points[i].IsEmpty = true;
                }
                
                chart1.ChartAreas[0].AxisX.Minimum = 0;
                chart1.ChartAreas[0].AxisX.Maximum = flyad.PosLen;
            }
        }
        private void button_cleargrid_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
            System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];
            
            series_forw.Points.Clear();
            series_backw.Points.Clear();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            GetGrid(Misc.DIRECTION.FORWARD);
        }
        private void GetGrid(Misc.DIRECTION dir)
        {
            System.Windows.Forms.DataVisualization.Charting.Series series_forw = chart1.Series["Series 1"];
            System.Windows.Forms.DataVisualization.Charting.Series series_backw = chart1.Series["Series 2"];
            System.Windows.Forms.DataVisualization.Charting.Series series;

            if (dir == DIRECTION.FORWARD)
                series = series_forw;
            else
                series = series_backw;
            int[] data;
            int gridLen = flyad.PosLen / flyad.PosOfGrid;
            flyad.GetGrid(dir, 0, gridLen, out data);
            series.Points.Clear();
            for (int i = 0; i < data.Length; i++)
            {
                int ad = data[i];
                int pos = i * flyad.PosOfGrid;
                series.Points.AddXY(pos, ad);
                if (ad == Misc.MyBase.NULL_VALUE)
                    series.Points[i].IsEmpty = true;
                else
                    series.Points[i].IsEmpty = false;
            }
            series.Points.Add(30000);

            int max = Misc.MyMath.Max(data, 0, data.Length - 1);
            int min = Misc.MyMath.Min(data, 0, data.Length - 1);
            if (max == Misc.MyBase.NULL_VALUE)
            {
                max = 60000;
                min = 0;
            }

            int mid = max;
            max += 10;
            min -= 10;
            chart1.ChartAreas[0].AxisY.Maximum = max;
            chart1.ChartAreas[0].AxisY.Minimum = min;

            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.ChartAreas[0].AxisX.Maximum = flyad.PosLen;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            GetGrid(Misc.DIRECTION.BACKWARD);
        }
        #endregion

        int timecnt = 0;
        class MaxMin 
        {
            /// <summary>
            /// 最大值
            /// </summary>
            public int max;
            /// <summary>
            /// 最小值
            /// </summary>
            public int min;
            /// <summary>
            /// 数量
            /// </summary>
            public int len;
        }
        List<MaxMin> mMMList = new List<MaxMin>();

        void flyad_TimeGridEvent(object sender, TimeGridEventArgs e)
        {
            if (!param.HasTimeGrid)
                return;
            MaxMin mm;
            while (timecnt > 5000)
            {
                //被删除对象
                mm = mMMList.First();
                for (int i = 0; i < mm.len; i++)
                {
                    chart2.Series["Series 1"].Points.RemoveAt(0);
                }
                timecnt -= mm.len;
                mMMList.RemoveAt(0);
            }
            mMMList.Add(
                new MaxMin(){
                    len = e.Data.Length, 
                    min = e.Data.Min(),
                    max = e.Data.Max()});

            for (int i = 0; i < mMMList.Last().len; i++)
            {
                int ad = e.Data[i];
                chart2.Series["Series 1"].Points.Add(ad);
            }

            int max = (from i in mMMList select i.max).Max();
            int min = (from i in mMMList select i.min).Min();

            if (max == min)
            {
                min -= 10;
                max += 10;
            }
            chart2.ChartAreas[0].AxisY.Maximum = max;
            chart2.ChartAreas[0].AxisY.Minimum = min;
            timecnt += mMMList.Last().len;
        }




        private void button_connect1_Click(object sender, RoutedEventArgs e)
        {
            IPEndPoint result = Misc.StringConverter.ToIPEndPoint(param.EPStr);
            
            flyad.Connect(result);
            button_connect.IsEnabled = false;
            textbox_ip.IsEnabled = false;
        }

        private void button_output_Click(object sender, RoutedEventArgs e)
        {
            string output = textbox_output.Text;
            flyad.SetOutput(UInt16.MaxValue, Convert.ToUInt16(output, 2));
        }

        private void button_runto_Click(object sender, RoutedEventArgs e)
        {
            int pos;

            if (int.TryParse(textBox_to.Text, out pos)) 
            {
                flyad.Runto(pos);
            }
        }

        private void button_org_Click(object sender, RoutedEventArgs e)
        {
            flyad.Origin();
        }

        private void button_stop_Click(object sender, RoutedEventArgs e)
        {
            flyad.Stop();
        }

        private void button_backw_Click(object sender, RoutedEventArgs e)
        {
            flyad.Backward();
        }

        private void button_forw_Click(object sender, RoutedEventArgs e)
        {
            flyad.Forward();
        }
        


        private void button3_Click(object sender, RoutedEventArgs e)
        {
            flyad.UpdateParam();
        }


        private void button_initarea_Click(object sender, RoutedEventArgs e)
        {
            
            Window_InitArea w = new Window_InitArea();
            w.Init(flyad);
            w.Show();
        }

        private void button_setaccess_Click(object sender, RoutedEventArgs e)
        {
            
            Window_setAccess w = new Window_setAccess();
            w.Init(flyad);
            w.Show();
        }

        private void button_sync_Click(object sender, RoutedEventArgs e)
        {
            if (!Window_sync.HasOpen)
            {
                Window_sync w = new Window_sync();
                w.Init(flyad, mAutoSync);
                w.Show();
            }
        }

        private void button_save_velocity_Click(object sender, RoutedEventArgs e)
        {
            param.Velocity = flyad.Velocity;
            param.SVelocity = flyad.SVelocity;
            param.ATime = flyad.ATime;
            param.DTime = flyad.DTime;
            param.HVelocity1 = flyad.HVelocity1;
            param.HVelocity2 = flyad.HVelocity2;
            param.PosLen = flyad.PosLen;
            param.ADLag = flyad.ADLag;
            param.Save();
            MessageBox.Show("保存成功");
        }

        private void button_load_velocity_Click(object sender, RoutedEventArgs e)
        {
            param.Load();
            flyad.Velocity = param.Velocity;
            flyad.SVelocity = param.SVelocity;
            flyad.ATime = param.ATime;
            flyad.DTime = param.DTime;
            flyad.HVelocity1 = param.HVelocity1;
            flyad.HVelocity2 = param.HVelocity2;

            flyad.PosLen = param.PosLen;
            flyad.ADLag = param.ADLag;

            MessageBox.Show("加载成功");
        }

        private void button_setbit_Click(object sender, RoutedEventArgs e)
        {
            Button[] bit = new Button[4] { button_bit0, button_bit1, button_bit2, button_bit3 };
            for (int i = 0; i < bit.Length; i++)
            {
                if (sender == bit[i]) 
                {
                    if (Misc.MyBase.CHECKBIT(flyad.OStatus, i))
                        flyad.SetOutputBit(i, false);
                    else
                        flyad.SetOutputBit(i, true);
                    break;
                }
            }
            
        }

        private void button_runto0_Click(object sender, RoutedEventArgs e)
        {
            flyad.RuntoMin();
        }

        private void button_runtoPosLen_Click(object sender, RoutedEventArgs e)
        {
            flyad.RuntoMax();
        }



    }



    public class IO2BinConverter : IValueConverter
    {
        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            UInt16 io = (UInt16)value;
            string str = System.Convert.ToString(io, 2);

            return str.PadLeft(16, '0');
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return System.Convert.ToUInt16((string)value, 2);
        }

        #endregion
    }
    public class BytesConverter : IValueConverter
    {
        #region IValueConverter 成员

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            byte[] bs = (byte[])value;
            string str = "";
            for (int i = 0; i < bs.Length; i++)
                str += bs[i].ToString("X2");
            return str;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string str = (string)value;
            string h="";
            List<byte> bs=new List<byte>();
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] != ' ')
                    h += str[i];
                


                if (((str[i] == ' ') && (h.Length != 0)) ||
                    (h.Length >= 2) )
                {
                    byte b=0;
                    if (byte.TryParse(h, System.Globalization.NumberStyles.AllowHexSpecifier, null, out b))
                    {
                        bs.Add(b);
                    }
                    else 
                    {
                        break;
                    }
                    h = "";
                }
            }
            return bs.ToArray();
        }

        #endregion
    }
}
