#define SPEED_BY_MySelf
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ComponentModel;
using FObjBase;
using System.IO;
using Misc;
using System.Collections.ObjectModel;


namespace FlyADBase
{
    /// <summary>
    /// 执行顺序
    /// 1. IFlyAD flyad = new FlyAD7();//加载速度参数，IP地址
    /// 2. flyad.Connect();//flyad.Connect("192.168.251.10:20006");
    /// 3. 当连接上，会设置推送，获取flyad7控制器里面所有数据，设置速度参数到控制器
    /// </summary>
    public partial class FlyAD7 : FObj, IFlyADClient
    {
        #region MARKNO
        const int MARKNO_SET_VELOCITY = 1;
        const int MARKNO_SET_ZEROPOS = 2;
        const int MARKNO_SET_SYSPARAM = 3;
        #endregion
        #region 成员变量

        TCPCConn conn = null;
        /// <summary>
        /// 不设置服务器
        /// </summary>
        private bool bShieldSetValueEx = false;
        /// <summary>
        /// AD盒使用时间刷新
        /// </summary>
        private DateTime dt_surplus = DateTime.MinValue;

        class DtAndBool
        {
            bool bNeedGet;
            DateTime dt;
            public void Clear()
            {
                bNeedGet = true;
                dt = DateTime.Now;
            }

            public bool NeedGet(DateTime now, TimeSpan delay)
            {
                if (bNeedGet)
                {
                    if ((now - dt) >= delay)
                    {
                        bNeedGet = false;
                        return true;
                    }
                }
                return false;
            }
        }

        DtAndBool driveman_wait = new DtAndBool();
        DtAndBool sysinfo_wait = new DtAndBool();

        /// <summary>
        /// 没有收到timegrid的次数， 1秒加1次
        /// </summary>
        int noTGridCnt = 0;
        /// <summary>
        /// 3次收不到timegrid, 重连
        /// </summary>
        const int ReConnectTGridMaxCnt = 3;



        int last_position = int.MinValue;

        #endregion

        /// <summary>
        /// 
        /// </summary>
        public FlyAD7()
        {
            Now = DateTime.Now;

            this.PropertyChanged += new PropertyChangedEventHandler(FlyAD7_PropertyChanged);
            PollModule.Current.Poll_Config(PollModule.POLL_CONFIG.ADD, new PollModule.PollHandler(OnPoll));




            //3秒内收不到1个timegrid ，就会重连
            PollModule.Current.Poll_Config(PollModule.POLL_CONFIG.ADD,
                () =>
                {
                    if (!IsConnected)
                    {
                        noTGridCnt = 0;
                    }
                    else
                    {
                        noTGridCnt++;
                        if (noTGridCnt >= ReConnectTGridMaxCnt)
                        {
                            noTGridCnt = 0;
                            ReConnect();
                        }
                    }

                }, TimeSpan.FromSeconds(1));

            constructor2();
        }

        #region IFlyADClient
        /// <summary>
        /// 连接成功
        /// </summary>
        public bool IsConnected { get; private set; }

        /// <summary>
        /// 重连次数
        /// </summary>
        public int ConnectCnt { get; private set; }

        /// <summary>
        /// CRC
        /// </summary>
        public bool HasCRC { get; set; }
        /// <summary>
        /// 连接
        /// </summary>
        public void Connect()
        {
            Connect(LocalEP);
        }

        /// <summary>
        /// 连接 ep
        /// </summary>
        /// <param name="ep"></param>
        public void Connect(IPEndPoint ep)
        {
            LocalEP = ep;

            if (conn != null)
            {
                if (!conn.RemoteEP.Equals(LocalEP))
                {
                    //断开之前的连接
                    CurrObjSys.Disconnect_to_Another_OBJSys(conn.RemoteEP, ID);
                }
            }

            conn = CurrObjSys.Connect_to_Another_OBJSys(LocalEP, ID);
            conn.HasCRC = HasCRC;
        }

        /// <summary>
        /// 重连
        /// </summary>
        public void ReConnect()
        {
            if (conn != null)
            {
                //断开之前的连接
                CurrObjSys.Disconnect_to_Another_OBJSys(conn.RemoteEP, ID);
            }

            conn = CurrObjSys.Connect_to_Another_OBJSys(LocalEP, ID);
            conn.HasCRC = HasCRC;
        }

        /// <summary>
        /// 用于同步， 最后一次 纵向信号 0->1 时，主轴脉冲
        /// </summary>
        public bool IsSync { get; protected set; }
        /// <summary>
        /// 当前在同步状态
        /// </summary>
        public int LastPos2At01 { get; protected set; }
        /// <summary>
        /// 同步列表，完成后，会删除
        /// </summary>
        public ObservableCollection<SyncOrder> SyncOrders { get; } = new ObservableCollection<SyncOrder>();

        #endregion

        void FlyAD7_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "HasCRC")
            {
                if (conn != null)
                    conn.HasCRC = HasCRC;
            }

            if (bShieldSetValueEx)
                return;

            if ((e.PropertyName == "Velocity") ||
                (e.PropertyName == "SVelocity") ||
                (e.PropertyName == "ATime") ||
                (e.PropertyName == "DTime") ||
                (e.PropertyName == "HVelocity1") ||
                (e.PropertyName == "HVelocity2"))
            {
                FObjBase.PollModule.Current.Poll_JustOnce(
                    delegate ()
                    {
                        //TODO,不应该直接修改Velocity，SVelocity。。。。。。
                        //所以下面也不可能存在！！！
                        SetPosParam(Velocity, SVelocity, ATime, DTime, HVelocity1, HVelocity2);
                    }, this, MARKNO_SET_VELOCITY);
            }
            else if ((e.PropertyName == "PosOffset") ||
                (e.PropertyName == "JogVelocity"))
            {
                FObjBase.PollModule.Current.Poll_JustOnce(
                    delegate ()
                    {
                        CurrObjSys.SetValueEx(conn, FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                            ID, FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.SET_ZERO_POS,
                            new FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_ZeroPos()
                            {
                                zero_pos = PosOffset,
                                jog_velocity = JogVelocity
                            }.ToBytes());
                    }, this, MARKNO_SET_ZEROPOS);
            }
            else if ((e.PropertyName == "MotorType") ||
                    (e.PropertyName == "PosOfGrid") ||
                    (e.PropertyName == "Ratio01") ||
                    (e.PropertyName == "Ratio02"))
            {
                FObjBase.PollModule.Current.Poll_JustOnce(
                    delegate ()
                    {
                        SetSysParam(PosOfGrid, MotorType, Ratio01, Ratio02);
                    }, this, MARKNO_SET_SYSPARAM);
            }
            else if (e.PropertyName == "Pos1LCShift")
            {

                CurrObjSys.CallFunctionEx(
                   conn,
                   FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                   ID,
                   FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                   new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_Pos1LCShift()
                   {
                       pos1_LCShift = Pos1LCShift
                   }.ToBytes());
            }
            else if (e.PropertyName == "Position2")
            {
                CurrObjSys.CallFunctionEx(
                    conn,
                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                    ID,
                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                    new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_Pos2()
                    {
                        pos2 = Position2
                    }.ToBytes());
            }
            else if (e.PropertyName == "Pos2Comp")
            {
                CurrObjSys.CallFunctionEx(
                    conn,
                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                    ID,
                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                    new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_Pos2Comp()
                    {
                        comp = Pos2Comp
                    }.ToBytes());
            }
        }


        void Init()
        {
            //CurrObjSys.SenseConfigEx(
            //    conn,
            //    FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.ID,
            //    ID,
            //    Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_POS1)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_POS2)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_AD1)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_IO)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_TIMEGRID)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_GRID)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_STATUS)
            //    | Misc.MyBase.BIT(FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_MINIGRID)
            //    ,
            //    SENSE_CONFIG.ADD);

            //注册全部推送事件
            CurrObjSys.SenseConfigEx(
                conn,
                FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.ID,
                ID,
                0xffffffff,
                SENSE_CONFIG.ADD);
            UpdateParam();


            //DRIVE_MAN
            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_STATE);

            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_SYNC_ORDER_CNT);

            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_SYNC_STATUS);

            //FLYADC
            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.GET_POS1AD1);

            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.GET_POS2);

            //FLYIO
            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.GET_IO);

            NotifyPropertyChanged("Pos1LCShift");//写入到AD盒
            NotifyPropertyChanged("Pos2Comp");//写入到AD盒

            SyncPos2Clear();
            SyncClear();
            SyncEnd();


            mSysTick.Reset();



            Init2();
        }

        #region FObj
        public override void ConnectNotify(IFConn from)
        {
            IsConnected = from.IsConnected;
            if (IsConnected)
            {
                ConnectCnt++;

                Init();
            }
            else
            {
                DriveStatus = DRIVE_MAN_STATUS.STOP;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="from"></param>
        /// <param name="srcid"></param>
        /// <param name="memid"></param>
        /// <param name="infodata"></param>
        public override void PushGetValue(IFConn from, uint srcid, ushort memid, byte[] infodata)
        {
            bShieldSetValueEx = true;
            switch (srcid)
            {
                case FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.ID:
                    {
                        switch (memid)
                        {
                            case FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.GET_POS1AD1:
                                {
                                    var pack = new FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.Pack_GetPos1AD1();
                                    if (!pack.TryParse(infodata))
                                        break;
                                    Position = pack.pos;
                                    //AD = pack.ad;
                                    advGetPos1AD1(pack.ad);
                                } break;
                            case FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.GET_POS2:
                                {
                                    FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.Pack_GetPos2 pack = new FLYAD7_OBJ_INTERFACE.FLYADC_OBJ_INTERFACE.Pack_GetPos2();
                                    if (!pack.TryParse(infodata))
                                        break;

                                    Position2 = pack.pos2;

                                    if (!IsCalSpeed)
                                        Speed2 = pack.speed2;
                                }
                                break;
                        }
                    } break;
                case FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.ID:
                    {
                        switch (memid)
                        {
                            case FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.GET_IO:
                                {
                                    var pack = new FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.Pack_GetIO();
                                    if (!pack.TryParse(infodata))
                                        break;

                                    IStatus = pack.istatus;
                                    OStatus = pack.ostatus;
                                    advGetIo();
                                } break;
                        }
                    } break;
                case FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID:
                    {
                        switch (memid)
                        {
                            case FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_DRIVEPARAM:
                                {
                                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_DriveParam pack = new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_DriveParam();

                                    if (!pack.TryParse(infodata))
                                        break;
                                    Velocity = pack.Velocity;
                                    SVelocity = pack.SV;
                                    ATime = pack.ATime;
                                    DTime = pack.DTime;
                                    HVelocity1 = pack.hspeed1;
                                    HVelocity2 = pack.hspeed2;

                                } break;
                            case FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_STATE:
                                {
                                    //TODO ？？？？？
                                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_DriveState p = new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_DriveState();
                                    if (!p.TryParse(infodata))
                                        break;
                                    DriveOrder = p.order;//TODO
                                    DriveStatus = p.status;
                                    Marker = p.marker;
                                } break;
                            case FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_SYNC_STATUS:
                                {
                                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncStatus p = new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncStatus();
                                    if (!p.TryParse(infodata))
                                        break;
                                    //TODO
                                }
                                break;
                            case FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_SYNC_ORDER_CNT:
                                {
                                    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncOrderCnt p = new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncOrderCnt();
                                    if (!p.TryParse(infodata))
                                        break;
                                    //TODO

                                }
                                break;
                        }
                    } break;
                case FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID:
                    {
                        switch (memid)
                        {
                            case FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_IP:
                                break;
                            case FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_SYSPARAM:
                                {
                                    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_SysParam pack = new FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_SysParam();

                                    if (!pack.TryParse(infodata))
                                        break;
                                    PosOfGrid = pack.posOfGrid;//1个Grid=?脉冲数(2B)
                                    if ((pack.func_enable & 0x03) == 0x02)
                                        MotorType = MOTORTYPE.SERVO;
                                    else if ((pack.func_enable & 0x03) == 0x01)
                                        MotorType = MOTORTYPE.VF0;
                                    else
                                        MotorType = MOTORTYPE.NULL;

                                    Ratio01 = pack.ratio01;
                                    Ratio02 = pack.ratio02;
                                } break;
                            case FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_SYSINFO:
                                {
                                    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_SysInfo pack = new FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_SysInfo();

                                    if (!pack.TryParse(infodata))
                                        break;

                                    AreaStatus = pack.status;
                                    AreaRet = pack.ret;

                                    Array.Copy(pack.code, Code, pack.code.Length);
                                    Code[6] = 0x06;
                                    NotifyPropertyChanged("Code");

                                    Surplus = pack.surplus;

                                    Array.Copy(pack.access, Access, pack.access.Length);
                                    NotifyPropertyChanged("Access");

                                } break;
                            case FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_ZERO_POS:
                                {
                                    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_ZeroPos pack = new FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_ZeroPos();

                                    if (!pack.TryParse(infodata))
                                        break;

                                    PosOffset = pack.zero_pos;
                                    JogVelocity = pack.jog_velocity;
                                } break;
                        }
                    } break;
            }
            bShieldSetValueEx = false;
        }
        /// <summary>
        ///  systick 转 DateTime
        ///  不断把 从flyad7 获取的 systick 放入。  以每次systick 的差 加上 上一次 dt_1st, 得到时间。
        ///  如： 当前 获得 systick1, 之前是 systick0,   所以 dt = dt_1st+ (systick1-systick0);  dt_1st=dt;
        ///  
        /// 第1个 dt_1st, 是 从 DateTime.Now. 获取的。
        /// 
        /// 不会管 当前DateTime.Now 与 dt 差多少。 所以如果 flyad7 时间比较慢，可能会出现 3天后， DateTime.Now 与 dt 差了 1个小时。
        /// </summary>
        class TSysTick
        {
            Int32 systick_1st = 0;
            DateTime dt_1st = DateTime.MinValue;
            Int32 systick_last = 0;

            public void Reset()
            {
                dt_1st = DateTime.MinValue;
            }
            /// <summary>
            /// 输入从 flyad7 获取的 timemark, 转换为 本地 DateTime
            /// </summary>
            /// <param name="systick"></param>
            /// <returns></returns>
            public DateTime ToDateTime(int systick)
            {
                if (dt_1st == DateTime.MinValue)
                {
                    dt_1st = DateTime.Now;
                    systick_1st = systick;
                    systick_last = systick;
                    return dt_1st;
                }
                //记录与新的timemark 相差10秒，太大了,重新生成 timemark 与 dt 的关系
                else if (Math.Abs(systick - systick_last) > 10000)
                {
                    dt_1st = DateTime.Now;
                    systick_1st = systick;
                    systick_last = systick;
                    return dt_1st;
                }
                else
                {
                    int ms = systick - systick_1st;
                    systick_last = systick;


                    DateTime dt = dt_1st.AddMilliseconds(ms);

                    systick_1st = systick;
                    dt_1st = dt;

                    return dt;
                }

            }
        }
        TSysTick mSysTick = new TSysTick();

        private int pos1_version { get; set; } = 2;
        private int io_version { get; set; } = 2;
        private int timegrid_version { get; set; } = 2;
        private int grid_version { get; set; } = 2;
        public override void PushInfo(IFConn from, uint srcid, ushort infoid, byte[] infodata)
        {
            bShieldSetValueEx = true;
            switch (infoid)
            {
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_POS1:
                    {
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushPos1_2 pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushPos1_2();
                        int version;
                        if (!pack.TryParse_version(infodata, out version))
                            break;
                        pos1_version = version;

                        if (version == 1)
                        {
                            Position = pack.pos1;
                            if (!IsCalSpeed)
                                Speed = pack.speed1;
                        }
                        else if (version == 2)
                        {
                            Position = pack.pos1;
                            if (!IsCalSpeed)
                                Speed = pack.speed1;

                            DateTime dt = mSysTick.ToDateTime(pack.systick);
                            Now = dt;
                        }
                        advPushPos1();
                    } break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_POS2:
                    {
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushPos2_2 pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushPos2_2();
                        int version;
                        if (!pack.TryParse_version(infodata, out version))
                            break;
                        Position2 = pack.pos2;
                        if (!IsCalSpeed)
                            Speed2 = pack.speed2;
                    } break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_AD1:
                    {
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushAD1 pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushAD1();
                        if (!pack.TryParse(infodata))
                            break;

                        //AD = pack.AD;
                        advPushAd(pack.AD);
                    } break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_IO:
                    {
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushIO_2 pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushIO_2();
                        int version;
                        if (!pack.TryParse_version(infodata, out version))
                            break;
                        io_version = version;
                        if (version == 1)
                        {
                            UInt16 inchange = (UInt16)(IStatus ^ pack.istatus);
                            IStatus = pack.istatus;
                            OStatus = pack.ostatus;
                            Now = DateTime.Now;
                            pack.pos1 = Position;
                            pack.pos2 = Position2;
                            IStatusChangedEvent?.Invoke(
                                this,
                                new IStatusChangedEventArgs(
                                    Now,
                                    IStatus,
                                    inchange,
                                    Position,
                                    Position2));
                        }
                        else if (version == 2)
                        {
                            IStatus = pack.istatus;
                            OStatus = pack.ostatus;
                            DateTime dt = mSysTick.ToDateTime(pack.systick);
                            Now = dt;

                            IStatusChangedEvent?.Invoke(
                                this,
                                new IStatusChangedEventArgs(
                                    dt,
                                    pack.istatus,
                                    pack.inChange,
                                    pack.pos1,
                                    pack.pos2));

                        }
                        advPushIo(pack.pos1);
                    } break;

                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_AD2:
                    break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_TIMEGRID:
                    {
                        noTGridCnt = 0;//收到timegrid!!!!!!!!!!!

                        int version;
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushTGrid_2 pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushTGrid_2();

                        if (!pack.TryParse_version(infodata, out version))
                        {
                            break;
                        }
                        timegrid_version = version;

                        DateTime dt;
                        int[] data;
                        //怕数据发送出错
                        if (pack.data.Any(d => (d >> 16) != 0))
                        {
                            //异常
                            goto _end_push_info;
                        }

                        if (version == 1)
                        {
                            //怕数据发送出错
                            dt = DateTime.Now;
                        }
                        else// if (version == 2)
                        {
                            dt = mSysTick.ToDateTime(pack.systick);
                            Now = dt;
                        }
                        data = pack.data;
                        double ts_ms = 1.28;
                        long ticks = (long)((ts_ms * data.Length) * TimeSpan.TicksPerMillisecond);
                        dt -= TimeSpan.FromTicks(ticks);

                        advPushTimeGrid(dt, data);

                        TimeGridEvent?.Invoke(
                            this,
                            new TimeGridEventArgs(
                                dt,
                                TimeSpan.FromTicks((long)(ts_ms * TimeSpan.TicksPerMillisecond)),
                                data));
                    } break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_STATUS:
                    {
                        int version;
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushStatus_2 pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushStatus_2();
                        if (!pack.TryParse_version(infodata, out version))
                            break;
                        if (version == 1)
                        {
                            DriveOrder = pack.order;
                            DriveStatus = pack.status;
                        }
                        else if (version == 2)
                        {
                            DriveOrder = pack.order;

                            DriveStatus = pack.status;
                            Marker = pack.marker;
                            DateTime dt = mSysTick.ToDateTime(pack.systick);
                            Now = dt;
                        }
                    } break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_GRID:
                    {
                        int version;
                        var pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushGrid_2();
                        if (!pack.TryParse_version(infodata, out version))
                            break;
                        grid_version = version;
                        DateTime dt;
                        int marker;
                        if (version == 1)
                        {
                            dt = DateTime.Now;
                            marker = Marker;
                        }
                        else //if (version == 2)
                        {
                            dt = mSysTick.ToDateTime(pack.systick);
                            marker = pack.marker;
                        }

                        advPushGrid(dt, marker, pack.direction, pack.grid_start, pack.data);

                        GridEvent?.Invoke(this, new MiniGridEventArgs()
                        {
                            direction = pack.direction,
                            grid_start = pack.grid_start,
                            posOfGrid = PosOfGrid,
                            buf = pack.data,
                            marker = marker
                        });

                    } break;
                case FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.PUSH_MINIGRID:
                    {
                        FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushGrid pack = new FLYAD7_OBJ_INTERFACE.PUSH_DATA_INTERFACE.Pack_PushGrid();
                        if (!pack.TryParse(infodata))
                            break;

                        advPushMiniGrid(pack.direction, pack.grid_start, pack.data);

                        MiniGridEvent?.Invoke(this, new MiniGridEventArgs()
                        {
                            direction = pack.direction,
                            grid_start = pack.grid_start,
                            posOfGrid = PosOfGrid,
                            buf = pack.data,
                            marker = Marker
                        });

                    } break;
            }
        _end_push_info:
            bShieldSetValueEx = false;
        }





        #endregion

        /// <summary>
        /// 100ms 周期
        /// </summary>
        private void OnPoll()
        {
            if (!IsConnected)
                return;

            DateTime now = DateTime.Now;

            if (Surplus != 65535)
            {
                if (dt_surplus == DateTime.MinValue)
                {
                    dt_surplus = now - TimeSpan.FromMinutes(40);//再过20分钟，就会 执行 使用时间+1
                }
                else if ((now - dt_surplus).TotalHours >= 1) //每隔一个小时 执行 使用时间+1
                {
                    dt_surplus = now;
                    if (Surplus > 0)
                    {
                        Surplus--;
                        CurrObjSys.CallFunctionEx(conn, FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID, ID,
                            FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.CALL_SURPLUS_SUB,
                            null);
                    }

                }
            }

            if (sysinfo_wait.NeedGet(now, TimeSpan.FromSeconds(1)))
            {
                CurrObjSys.GetValueEx(
                    conn,
                    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                    ID,
                    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_SYSINFO);
            }

            if (DriveStatus == DRIVE_MAN_STATUS.RUNNING)
            {
                //if (Position == TargetPos) //已经到达位置，问AD卡是不是？
                //{
                //    if ((now - driveman_wait.dt).TotalSeconds >= 1)//每次发送必须间隔1s
                //    {
                //        driveman_wait.Clear();
                //        CurrObjSys.GetValueEx(
                //            conn,
                //            FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                //            ID,
                //            FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_STATE);
                //    }
                //}
                //else 
                if (driveman_wait.NeedGet(now, TimeSpan.FromSeconds(3)))//每3秒检查一次
                {
                    driveman_wait.Clear();
                    if (Position == last_position)//当前正在running，但脉冲在3秒内都没变化，问AD卡，现在什么情况。
                    {
                        CurrObjSys.GetValueEx(
                            conn,
                            FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                            ID,
                            FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_STATE);
                    }
                    last_position = Position;
                }
            }

        }


        #region INotifyPropertyChanged 成员
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion





        #region IFlyAD 成员
        private IPEndPoint localep = new IPEndPoint(IPAddress.Parse("192.168.251.10"), 20006);

        /// <summary>
        /// AD盒地址
        /// </summary>
        public IPEndPoint LocalEP
        {
            get
            {
                return localep;
            }
            set
            {
                if (value == null)
                    return;
                if (!IPEndPoint.Equals(localep, value))
                {
                    localep = new IPEndPoint(value.Address, value.Port);
                }
            }
        }

        /// <summary>
        /// 从flyad7 获取 的systick 转换的时间
        /// </summary>
        public DateTime Now { get; private set; }

        /// <summary>
        /// AD盒版本号 版本1 没有systick;版本2 有systick;
        /// </summary>
        public int Version 
        {
            get {
                if (pos1_version == 2
                    && timegrid_version == 2
                    && grid_version == 2)
                    return 2;
                else
                    return 1;
            }
        }

        /// <summary>
        /// 脉冲
        /// </summary>
        public int Position { get; private set; }

        /// <summary>
        /// 速度 pps
        /// </summary>
        public int Speed { get; private set; }

        /// <summary>
        /// 1000ms从AD卡获取(或推送)1个AD值。此AD值只用于调试，定点
        /// </summary>
        public int AD { get; private set; }


        /// <summary>
        /// AD值最大值 ，恒定返回65535
        /// </summary>
        public int ADMax { get; } = 65535;

        /// <summary>
        /// 输入口状态,只有12位有效
        /// </summary>
        public UInt16 IStatus { get; private set; } = 0xffff;

        /// <summary>
        /// 输出口状态,只有4位有效
        /// </summary>
        public UInt16 OStatus { get; private set; } = 0xffff;

        /// <summary>
        /// Out0 = 0, SetOutput(0x0001,0x0000);
        /// Out0 = 1, Out1 = 0, SetOutput(0x0003,0x0001);
        /// </summary>
        /// <param name="mask"></param>
        /// <param name="enable"></param>
        public void SetOutput(ushort mask, ushort enable)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.CALL_OUTPORT,
                new FLYAD7_OBJ_INTERFACE.FLYIO_OBJ_INTERFACE.Pack_CallOutPort()
                {
                    mask = mask,
                    port = enable
                }.ToBytes());
        }

        /// <summary>
        /// 读取参数, 全部！！！！
        /// </summary>
        public void UpdateParam()
        {
            //OBJ_SYS_DATA
            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_SYSPARAM);

            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_ZERO_POS);

            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_SYSINFO);

            //DRIVE_MAN
            CurrObjSys.GetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_DRIVEPARAM);
        }

        #region 运动参数
        /// <summary>
        /// 设置 运动参数
        /// </summary>
        /// <param name="posOfGrid">脉冲/grid</param>
        /// <param name="motortype">电机类型</param>
        /// <param name="ratio01">脉冲比例 分母(电机脉冲)</param>
        /// <param name="ratio02">脉冲比例 分子(编码器脉冲)</param>
        public void SetSysParam(UInt16 posOfGrid, MOTORTYPE motortype, UInt16 ratio01, UInt16 ratio02)
        {
            byte func_enable = 0x0e;
            if (motortype == MOTORTYPE.NULL)
                func_enable = 0x0e;
            else if (motortype == MOTORTYPE.SERVO)
                func_enable = 0x0e;
            else// if (motortype == MOTORTYPE.VF0)
                func_enable = 0x0d;

            CurrObjSys.SetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.SET_SYSPARAM,
                new FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_SysParam()
                {
                    posOfGrid = posOfGrid,
                    ad1_interval = 1000,
                    ad2_interval = 1000,
                    push_interval = 100,
                    func_setting = 0,
                    func_enable = func_enable,
                    ratio01 = ratio01,
                    ratio02 = ratio02
                }.ToBytes());
            //CurrObjSys.GetValueEx(
            //    conn,
            //    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
            //    ID,
            //    0x1234,
            //    FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.GET_SYSPARAM);
        }

        /// <summary>
        /// 电机类型
        /// </summary>
        public MOTORTYPE MotorType { get; set; } = MOTORTYPE.SERVO;

        private UInt16 posofgrid = 10;
        /// <summary>
        /// 脉冲/grid, 最大1000个grid
        /// </summary>
        public UInt16 PosOfGrid 
        {
            get { return posofgrid; }
            set
            {
                if (value < 1)
                    value = 1;
                
                if (posofgrid != value)
                    posofgrid = value;
                
            }
        }


        /// <summary>
        /// 脉冲比例 分母(电机脉冲)
        /// </summary>
        public UInt16 Ratio01 { get; set; } = 4;

        /// <summary>
        /// 脉冲比例 分子(编码器脉冲)
        /// </summary>
        public UInt16 Ratio02 { get; set; } = 1;

        #endregion


        /// <summary>
        /// 脉冲平移(0位处脉冲值)
        /// </summary>
        public Int16 PosOffset { get; set; }

        /// <summary>
        /// 手动速度 pps
        /// </summary>
        public UInt32 JogVelocity { get; set; } = 5000;

        #region 速度参数


        /// <summary>
        /// 设置速度参数
        /// </summary>
        /// <param name="velocity">runto 速度 pps</param>
        /// <param name="sv">开始速度 pps</param>
        /// <param name="atime">加速时间 ms</param>
        /// <param name="dtime">减速时间 ms</param>
        /// <param name="hspeed1">归0 第1段速 pps</param>
        /// <param name="hspeed2">归0 第2段速 pps</par
        public void SetPosParam(UInt32 velocity, UInt32 sv, UInt32 atime, UInt32 dtime, UInt32 hspeed1, UInt32 hspeed2)
        {
            bShieldSetValueEx = true;
            if (velocity != 0xffffffff)
                Velocity = velocity;
            if (sv != 0xffffffff)
                SVelocity = sv;
            if (atime != 0xffffffff)
                ATime = atime;
            if (dtime != 0xffffffff)
                DTime = dtime;
            if (hspeed1 != 0xffffffff)
                HVelocity1 = hspeed1;
            if (hspeed2 != 0xffffffff)
                HVelocity2 = hspeed2;
            bShieldSetValueEx = false;
            CurrObjSys.SetValueEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.SET_DRIVEPARAM,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_DriveParam()
                {
                    Velocity = velocity,
                    SV = sv,
                    ATime = atime,
                    DTime = dtime,
                    hspeed1 = hspeed1,
                    hspeed2 = hspeed2
                }.ToBytes());
            //CurrObjSys.GetValueEx(
            //    conn,
            //    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
            //    ID,
            //    0x1234,
            //    FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.GET_DRIVEPARAM);
        }

        /// <summary>
        /// 设置速度
        /// </summary>
        /// <param name="velocity"></param>
        public void SetVelocity(UInt32 velocity)
        {
            SetPosParam(velocity, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff);
        }
        /// <summary>
        /// runto 速度 pps
        /// </summary>
        public UInt32 Velocity { get; set; } = 8000;

        /// <summary>
        /// 开始速度 pps
        /// </summary>
        public UInt32 SVelocity { get; set; } = 200;

        /// <summary>
        /// 加速时间 ms
        /// </summary>
        public UInt32 ATime { get; set; } = 300;

        /// <summary>
        /// 减速时间 ms
        /// </summary>
        public UInt32 DTime { get; set; } = 200;

        /// <summary>
        /// 归0 第1段速 pps
        /// </summary>
        public UInt32 HVelocity1 { get; set; } = 4000;

        /// <summary>
        /// 归0 第2段速 pps
        /// </summary>
        public UInt32 HVelocity2 { get; set; } = 500;

        #endregion

        #region 密码
        /// <summary>
        /// 使用码区状态
        /// </summary>
        public AREA_STATUS AreaStatus { get; set; }

        /// <summary>
        /// 使用码区出错码
        /// </summary>
        public AREA_ERR AreaRet { get; set; }

        /// <summary>
        /// 序列码byte[6]
        /// </summary>
        public byte[] Code { get; } = new byte[7];


        /// <summary>
        /// //系统剩余时间
        /// </summary>
        public int Surplus { get; set; } = 0xffff;
        /// <summary>
        /// 系统授权码
        /// </summary>
        public byte[] Access { get; } = new byte[8];

        /// <summary>
        /// 输入系统授权码
        /// </summary>
        /// <param name="access">系统授权码access[8]</param>
        public void SetAccess(byte[] access)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.CALL_ACCESS,
                access);
            sysinfo_wait.Clear();
        }
        /// <summary>
        /// 初始化系统信息区
        /// </summary>
        public void InitArea()
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.CALL_INIT,
                new FLYAD7_OBJ_INTERFACE.SYS_DATA_INTERFACE.Pack_Init().ToBytes());
            sysinfo_wait.Clear();
        }
        #endregion

        /// <summary>
        /// timegrid 事件; 版本1: 1.28s 一次; 版本2: 0.2s一次， 
        /// </summary>
        public event TimeGridEventHandler TimeGridEvent;

        /// <summary>
        /// runto 中，每经过1个grid 推送数据
        /// </summary>
        public event MiniGridEventHandler MiniGridEvent;

        /// <summary>
        /// runto 的 grid事件
        /// </summary>
        public event MiniGridEventHandler GridEvent;

        /// <summary>
        /// 输入状态改变事件
        /// </summary>
        public event IStatusChangedEventHandler IStatusChangedEvent;

        #region 运行动作
        /// <summary>
        /// 运行至指定位置
        /// </summary>
        /// <param name="to">脉冲</param>
        public void Runto(int to)
        {
            Drive(DRIVE_MAN_ORDER.RUNTO, to);
        }
        /// <summary>
        /// 归原点
        /// </summary>
        public void Origin()
        {
            Drive(DRIVE_MAN_ORDER.ORIGIN);
        }
        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            Drive(DRIVE_MAN_ORDER.STOP);
        }
        /// <summary>
        /// 反向，直到撞了限位
        /// </summary>
        public void Backward()
        {
            Drive(DRIVE_MAN_ORDER.BACKWORD);
        }
        /// <summary>
        /// 正行，直到撞了限位
        /// </summary>
        public void Forward()
        {
            Drive(DRIVE_MAN_ORDER.FORWORD);
        }
        /// <summary>
        /// 当前运行指令
        /// </summary>
        public DRIVE_MAN_ORDER DriveOrder { get; set; } = DRIVE_MAN_ORDER.IDLE;

        /// <summary>
        /// 之前运行动作的状态
        /// </summary>
        public DRIVE_MAN_STATUS DriveStatus { get; set; }=DRIVE_MAN_STATUS.STOP;

        #endregion

        #endregion

        void Drive(DRIVE_MAN_ORDER order, object param)
        {
            
            switch (order)
            {
                case DRIVE_MAN_ORDER.RUNTO:
                    {
                        int TargetPos = (int)param;
                        if (Position == TargetPos)
                        {
                            //已经到了位置！！！！！， FLYAD7 是没有动作，没有推送的！！！
                            DriveStatus = DRIVE_MAN_STATUS.STOP;
                        }
                        else
                        {
                            DriveStatus = DRIVE_MAN_STATUS.RUNNING;
                            CurrObjSys.CallFunctionEx(
                                conn,
                                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                                ID,
                                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_CallRunto() { to = TargetPos }.ToBytes());

                        }
                    } break;
                case DRIVE_MAN_ORDER.ORIGIN:
                case DRIVE_MAN_ORDER.BACKWORD:
                case DRIVE_MAN_ORDER.FORWORD:
                case DRIVE_MAN_ORDER.STOP:
                    {
                        DriveStatus = DRIVE_MAN_STATUS.RUNNING;
                        CurrObjSys.CallFunctionEx(
                            conn,
                            FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                            ID,
                            FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                            new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_CallPXX() { order = order }.ToBytes());
                    } break;
                case DRIVE_MAN_ORDER.SYNC:
                    {
                        if (param != null)
                        {
                            CurrObjSys.CallFunctionEx(
                                conn,
                                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                                ID,
                                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncBeginWithPos2()
                                {
                                    pos2 = (int)param
                                }.ToBytes());
                        }
                        else
                        {

                            CurrObjSys.CallFunctionEx(
                                conn,
                                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                                ID,
                                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncBegin().ToBytes());
                        }
                    } break;
            }

            driveman_wait.Clear();
        }
        void Drive(DRIVE_MAN_ORDER order)
        {
            Drive(order, null);
        }

        #region 同步

        /// <summary>
        /// 同步用标示
        /// </summary>
        public Int32 Marker { get; protected set; }

        #region 横向脉冲
        /// <summary>
        /// 逻辑横向脉冲偏移  Pos1 + Pos1LCShift = Pos1LC
        /// </summary>
        public int Pos1LCShift { get; set; }

        #endregion
        #region 主轴脉冲

        /// <summary>
        /// 纵向脉冲速度, pps, 1秒脉冲数
        /// </summary>
        public int Speed2 { get; set; }


        /// <summary>
        /// 纵向脉冲，也叫主轴脉冲
        /// </summary>
        public int Position2 { get; set; }

        /// <summary>
        /// 纵向偏移
        /// </summary>
        public void SetPos2Offset(int offset) 
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_Pos2Shift()
                {
                    pos2_shift = offset
                }.ToBytes());
        }

        /// <summary>
        /// 纵向值补偿系数，补偿时，先乘除后加减 不应该有！！！
        /// </summary>
        public float Pos2Comp { get; set; } = 1;

        /// <summary>
        /// 纵向同步事件，0-1事件
        /// </summary>
        /// <param name="pos2"></param>
        /// <param name="immediately">只要是 01，就立刻修正</param>
        public void SetPos2At01(int pos2,bool immediately)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_Pos2_01()
                {
                    pos2 = pos2,
                    immediately = immediately
                }.ToBytes());
            LastPos2At01 = pos2;
        }

        #endregion
        #region 同步控制 同步状态转换规则
        /// <summary>
        /// 进入同步状态
        /// </summary>
        /// <param name="pos2"></param>
        public void SyncBegin(int pos2)
        {
            Drive(DRIVE_MAN_ORDER.SYNC, pos2);
            IsSync = true;
        }
        /// <summary>
        /// 进入同步状态
        /// </summary>
        public void SyncBegin()
        {
            Drive(DRIVE_MAN_ORDER.SYNC, null);
            IsSync = true;
        }
        /// <summary>
        /// 退出同步状态
        /// </summary>
        public void SyncEnd()
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncEnd().ToBytes());
            IsSync = false;
        }
        /// <summary>
        /// 清空同步指令
        /// </summary>
        public void SyncClear()
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncClear().ToBytes());
            
            SyncOrders.Clear();

        }
        /// <summary>
        /// 清空POS2同步列表
        /// </summary>
        public void SyncPos2Clear()
        {
            CurrObjSys.CallFunctionEx(
              conn,
              FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
              ID,
              FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
              new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncPos2Clear().ToBytes());
        }
        #endregion
        #region 同步扫描 脚本指令

        /// <summary>
        /// 同步扫描至;
        /// D+0xE0+开始主轴位置+结束主轴位置+结束横向脉冲位置（逻辑位置）+脉冲开关（1B）+命令识标号（4B）
        /// </summary>
        /// <param name="pos2_begin"></param>
        /// <param name="pos2_end"></param>
        /// <param name="pos1lc"></param>
        /// <param name="hasDataGrid"></param>
        /// <param name="marker"></param>public void SyncRunAtLC(int pos2_begin, int pos2_end, int pos1lc, bool hasDataGrid, Int32 marker)
        public void SyncRunAtLC(int pos2_begin, int pos2_end, int pos1lc, bool hasDataGrid, Int32 marker)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncRunAtLC()
                {
                    pos2_begin = pos2_begin,
                    pos2_end = pos2_end,
                    pos1lc = pos1lc,
                    hasDataGrid = hasDataGrid,
                    marker = marker
                }.ToBytes());

            SyncOrders.Add(new SyncOrder_SyncRunAtLC()
            {
                Pos2Begin = pos2_begin,
                Pos2End = pos2_end,
                Pos1LC = pos1lc,
                HasDataGrid = hasDataGrid,
                Marker = marker
            });
        }

        /// <summary>
        /// 位于队列头时运行，归零；
        /// D+0xE1+命令识标号（4B）
        /// </summary>
        /// <param name="marker"></param>
        public void SyncOrigin(Int32 marker)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncOrigin()
                {
                    marker = marker
                }.ToBytes());

            SyncOrders.Add(new SyncOrder_SyncOrigin()
            {
                Marker = marker
            });
        }


        /// <summary>
        /// 位于队列头时运行，以速度运行至物理位置；
        /// D+0xE2+横向脉冲位置（4B：int32，物理位置）+速度（4B：int32）+脉冲开关（1B）+命令识标号（4B）
        /// </summary>
        /// <param name="pos1"></param>
        /// <param name="velocity"></param>
        /// <param name="hasDataGrid"></param>
        /// <param name="marker"></param>
        public void SyncRunTo(int pos1, UInt32 velocity, bool hasDataGrid, Int32 marker)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncRunto()
                {
                    pos1 = pos1,
                    velocity = velocity,
                    hasDataGrid = hasDataGrid,
                    marker = marker
                }.ToBytes());

            SyncOrders.Add(new SyncOrder_SyncRunTo()
            {
                Pos1 = pos1,
                Velocity = velocity,
                HasDataGrid = hasDataGrid,
                Marker = marker
            });
        }

               /// <summary>
        /// 位于队列头时运行，以速度运行至逻辑位置；
        /// D+0xE3+横向脉冲位置（4B：int32，逻辑位置）+速度（4B：int32）+脉冲开关（1B）+命令识标号（4B）
        /// </summary>
        /// <param name="pos1lc"></param>
        /// <param name="velocity"></param>
        /// <param name="hasDataGrid"></param>
        /// <param name="marker"></param>
        public void SyncRunToLC(int pos1lc, UInt32 velocity, bool hasDataGrid, Int32 marker)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncRuntoLC()
                {
                    pos1 = pos1lc,
                    velocity = velocity,
                    hasDataGrid = hasDataGrid,
                    marker = marker
                }.ToBytes());
            SyncOrders.Add(new SyncOrder_SyncRunToLC()
            {
                Pos1 = pos1lc,
                Velocity = velocity,
                HasDataGrid = hasDataGrid,
                Marker = marker
            });
        }


        /// <summary>
        /// 等待，ms；
        /// D+0xE4+毫秒数（4B：int32）+命令识标号（4B）
        /// </summary>
        /// <param name="ms"></param>
        /// <param name="marker"></param>
        public void SyncWait(int ms, Int32 marker)
        {
            CurrObjSys.CallFunctionEx(
                conn,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.ID,
                ID,
                FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.CALL_PXX,
                new FLYAD7_OBJ_INTERFACE.DRIVE_MAN_INTERFACE.Pack_SyncWait()
                {
                    ms = ms,
                    marker = marker
                }.ToBytes());
            SyncOrders.Add(new SyncOrder_SyncWait()
            {
                MS = ms,
                Marker = marker
            });
        }
        #endregion
        #endregion






    }




}
