using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DBFactory;
using System.Threading;
namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 解析PLC返回的数据
    /// </summary>
    public static class CParseStack
    {
        static string _CParsePLCError = "";//监控调度类错误说明
        static private object LockData = new object();
        static private object LockStack = new object();
        static StringBuilder sql = new StringBuilder();

        public static string CParsePLCError
        {
            get { return _CParsePLCError; }
            set { _CParsePLCError = value; }
        }
        static DBOperator dbo = new DBOperator();
        static DBOperator dboRoute = new DBOperator();
        static DBOperator dboMan = new DBOperator("ManConnString", "ManDBFactory");
        static Model.MDevice devinfo28 = Model.CGetInfo.GetDeviceInfo(65534);
        //static Model.MDevice devinfo;
        static Model.MDevice devinfoRoute;
        //static Thread mythreadRoute;
        static Thread mystackthread;
        static bool exitThread = false;//20091107


       // static Thread stackthread;
        private static void BeginListen()
        {//20091107
            while (!exitThread)
            {
                try
                {
                    SetDeviceState();

                }
                catch (Exception ex)
                {
                    _CParsePLCError = ex.Message;
                }
                Thread.Sleep(200);//20100710
            }
        }

        //private static void BeginListenStack()
        //{
        //    while (!exitThread)
        //    {
        //        try
        //        {
        //            SetStackState();
        //        }
        //        catch (Exception ex)
        //        {
        //            _CParsePLCError = ex.Message;
        //        }
        //        Thread.Sleep(500);
        //    }
        //}
        private static void BeginListenRoute()
        {//20091107
            while (!exitThread)
            {
                try
                {
                    SetRouteStatus();

                }
                catch (Exception ex)
                {
                    _CParsePLCError = ex.Message;
                }
            }
        }
        public static void EndListen()
        {//20091107
            exitThread = true;

            if (mystackthread != null)
            {

                mystackthread.Abort();
                mystackthread = null;
            }
            //if (mystackthread != null)
            //{
            //    mystackthread.Abort();
            //    mystackthread = null;
            //}

            //if (mythreadRoute != null)
            //{

            //    mythreadRoute.Abort();
            //    mythreadRoute = null;
            //}
        }
        public static void StartListen()
        {
            //20091107
            exitThread = false;
            mystackthread = new Thread(new ThreadStart(BeginListen));
            mystackthread.IsBackground = true;
            mystackthread.Start();

            //stackthread = new Thread(new ThreadStart(BeginListenStack));
            //stackthread.IsBackground = true;
            //stackthread.Start();

            //mythreadRoute = new Thread(new ThreadStart(BeginListenRoute));
            //mythreadRoute.IsBackground = true;
            //mythreadRoute.Start();
        }

        /// <summary>
        /// 取得指定光电开关（确认按钮）设备索引的信号（0，1）
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <returns>0，1</returns>

        public static int GetDevicePhotoelectric(int deviceIdx)
        {

            try
            {
                if (devinfo28.DeviceKind == 28)
                {
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 获取开关量的值


                        DataView dvle = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceKindIndex,F_DBWGetLength," +
                            " F_DBW2Address FROM T_Base_Device WHERE ((F_DeviceKindIndex = 14)" +
                            " OR (F_DeviceKindIndex = 18)) and (F_DBW2Address is not NULL) and F_DeviceIndex=" + deviceIdx + "").Tables[0].DefaultView;
                        //devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                        int glen = 0;
                        int IfVis = 0;
                        if (dvle.Count > 0)//(devinfo.DeviceKind == 14) || (devinfo.DeviceKind == 18)
                        {
                            int temp = Convert.ToInt32(dvle[0]["F_DBW2Address"]) - devinfo28.Dbw2Address;
                            if (Convert.ToInt32((Convert.ToDecimal(dvle[0]["F_DBWGetLength"]) * 8 - 1)) > 7)//devinfo.Dbw2Getlength
                            {
                                glen = Convert.ToInt32((Convert.ToDecimal(dvle[0]["F_DBWGetLength"]) * 8 - 1)) - 8;
                                temp = temp + 1;
                            }
                            else
                            {
                                glen = Convert.ToInt32((Convert.ToDecimal(dvle[0]["F_DBWGetLength"]) * 8 - 1));
                            }
                            if (temp >= 0)
                            {
                                IfVis = CommonClassLib.CCarryConvert.GetBitFromInteger(CStaticClass.AllReturns[temp], glen);
                                //if (dvle[0]["F_DeviceKindIndex"].ToString() == "18")
                                //{//配合孙宇光电开关0有探物，1无探物，在这里取反符合正常逻辑
                                //    if (IfVis == 1)
                                //    {
                                //        IfVis = 0;
                                //    }
                                //    else
                                //    {
                                //        IfVis = 1;
                                //    }
                                //}
                                return IfVis;
                            }
                            else
                            {
                                return -1;
                            }

                        }
                        else
                        {
                            return -1;
                        }


                        #endregion


                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch //(Exception ex)
            {
                //if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得指定光电开关的信号时：" + ex.Message) < 0)
                //{

                //    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得指定光电开关的信号时：" + ex.Message, true);
                //}
                return -1;
            }
        }
        /// <summary>
        /// 20101118根据设备号和bit位，取得F_SplitByte里的光电bit值：0,1
        /// </summary>
        /// <param name="deviceIdx"></param>
        /// <param name="bit"></param>
        /// <returns></returns>
        public static int GetDevicePhotoelectric(int deviceIdx, int abit)
        {

            try
            {
                if (devinfo28.DeviceKind == 28)
                {
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 获取开关量的值


                        DataView dvle = dbo.ExceSQL("SELECT F_SplitByte  FROM T_Base_Device WHERE  F_DeviceIndex=" + deviceIdx + " and F_SplitByte>=0").Tables[0].DefaultView;

                        int glen = 0;
                        int IfVis = 0;
                        if (dvle.Count > 0)
                        {
                            int temp = Convert.ToInt32(dvle[0]["F_SplitByte"]) - devinfo28.Dbw2Address;
                            if (abit > 7)
                            {
                                glen = abit - 8;
                                temp = temp + 1;
                            }
                            else
                            {
                                glen = abit;
                            }
                            if (temp >= 0)
                            {
                                IfVis = CommonClassLib.CCarryConvert.GetBitFromInteger(CStaticClass.AllReturns[temp], glen);
                                //if (dvle[0]["F_DeviceKindIndex"].ToString() == "18")
                                //{//配合孙宇光电开关0有探物，1无探物，在这里取反符合正常逻辑
                                //    if (IfVis == 1)
                                //    {
                                //        IfVis = 0;
                                //    }
                                //    else
                                //    {
                                //        IfVis = 1;
                                //    }
                                //}
                                return IfVis;
                            }
                            else
                            {
                                return -1;
                            }

                        }
                        else
                        {
                            return -1;
                        }


                        #endregion


                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch (Exception ex)
            {

                return -1;
            }
        }
        /// <summary>
        /// 取得指定设备索引的设备状态:[0]读写标志;[1]状态;[2]任务号；[3]X坐标;[4]Y坐标;[5]设备索引
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <returns></returns>

        public static int[] GetDeviceState(int deviceIdx)
        {

            try
            {


                if (devinfo28.DeviceKind == 28)
                {
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 获取设备状态
                        DataView dvle = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceKindIndex,F_DBWGetLength," +
                            " F_DBW2Address FROM T_Base_Device WHERE (F_DBW2Address is not NULL) and F_DeviceIndex=" + deviceIdx + "").Tables[0].DefaultView;
                        //devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                        if (dvle.Count > 0)//devinfo.Dbw2Address != -1
                        {
                            int temp = Convert.ToInt32(dvle[0]["F_DBW2Address"]) - devinfo28.Dbw2Address;//devinfo.Dbw2Address
                            decimal glen = Convert.ToDecimal(dvle[0]["F_DBWGetLength"]);//devinfo.Dbw2Getlength
                            int[] states = new int[6];
                            switch (dvle[0]["F_DeviceKindIndex"].ToString())//devinfo.DeviceKind.ToString()
                            {

                                #region 其他设备
                                case "1"://堆垛机

                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = (CStaticClass.AllReturns[temp + 2] << 8) + CStaticClass.AllReturns[temp + 3];//任务号
                                    states[3] = CStaticClass.AllReturns[temp + 7] + (CStaticClass.AllReturns[temp + 6] << 8) + (CStaticClass.AllReturns[temp + 5] << 16) + (CStaticClass.AllReturns[temp + 4] << 32);//X坐标
                                    states[4] = CStaticClass.AllReturns[temp + 11] + (CStaticClass.AllReturns[temp + 10] << 8) + (CStaticClass.AllReturns[temp + 9] << 16) + (CStaticClass.AllReturns[temp + 8] << 32);//Y坐标
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                case "3":
                                case "2"://输送机
                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = (CStaticClass.AllReturns[temp + 2] << 8) + CStaticClass.AllReturns[temp + 3];//任务号
                                    states[3] = 0;
                                    states[4] = 0;
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                case "4"://RGV
                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = (CStaticClass.AllReturns[temp + 2] << 8) + CStaticClass.AllReturns[temp + 3];//任务号
                                    states[3] = CStaticClass.AllReturns[temp + 7] + (CStaticClass.AllReturns[temp + 6] << 8) + (CStaticClass.AllReturns[temp + 5] << 16) + (CStaticClass.AllReturns[temp + 4] << 32);//X坐标
                                    states[4] = 0;
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                case "5"://拆盘机和叠盘机
                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = 0;
                                    states[3] = 0;
                                    states[4] = 0;
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                #endregion
                            }


                            return states;
                        }
                        else
                        {
                            return null;
                        }


                        #endregion


                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch //(Exception ex)
            {
                //if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得指定光电开关的信号时：" + ex.Message) < 0)
                //{

                //    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得指定光电开关的信号时：" + ex.Message, true);
                //}
                return null;
            }
        }

        /// <summary>
        /// 取得指定光电开关（确认按钮）设备索引的信号（0，1）
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <returns>0，1</returns>

        public static int GetDevicePhotoelectricRoute(int deviceIdx)
        {
            try
            {
                if (devinfo28.DeviceKind == 28)
                {
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 获取开关量的值


                        //DataView dvle = dbo.ExceSQL("SELECT F_DeviceIndex, F_DeviceKindIndex,F_DBWGetLength," +
                        //    " F_DBW2Address FROM T_Base_Device WHERE ((F_DeviceKindIndex = 14)" +
                        //    " OR (F_DeviceKindIndex = 18)) and (F_DBW2Address is not NULL) and F_DeviceIndex=" + deviceIdx + "").Tables[0].DefaultView;
                        devinfoRoute = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                        int glen = 0;
                        int IfVis = 0;
                        if ((devinfoRoute.DeviceKind == 14) || (devinfoRoute.DeviceKind == 18))
                        {
                            int temp = devinfoRoute.Dbw2Address - devinfo28.Dbw2Address;
                            if (Convert.ToInt32((devinfoRoute.Dbw2Getlength * 8 - 1)) > 7)
                            {
                                glen = Convert.ToInt32((devinfoRoute.Dbw2Getlength * 8 - 1)) - 8;
                                temp = temp + 1;
                            }
                            else
                            {
                                glen = Convert.ToInt32((devinfoRoute.Dbw2Getlength * 8 - 1));
                            }
                            if (temp >= 0)
                            {
                                IfVis = CommonClassLib.CCarryConvert.GetBitFromInteger(CStaticClass.AllReturns[temp], glen);
                                //if (dvle[0]["F_DeviceKindIndex"].ToString() == "18")
                                //{//配合孙宇光电开关0有探物，1无探物，在这里取反符合正常逻辑
                                //    if (IfVis == 1)
                                //    {
                                //        IfVis = 0;
                                //    }
                                //    else
                                //    {
                                //        IfVis = 1;
                                //    }
                                //}
                                return IfVis;
                            }
                            else
                            {
                                return -1;
                            }

                        }
                        else
                        {
                            return -1;
                        }


                        #endregion


                    }
                    else
                    {
                        return -1;
                    }
                }
                else
                {
                    return -1;
                }
            }
            catch //(Exception ex)
            {
                //if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得指定光电开关的信号时：" + ex.Message) < 0)
                //{

                //    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得指定光电开关的信号时：" + ex.Message, true);
                //}
                return -1;
            }
        }
        /// <summary>
        /// 取得指定设备索引的设备状态:[0]读写标志;[1]状态;[2]任务号；[3]X坐标;[4]Y坐标;[5]设备索引
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <returns></returns>
        public static int[] GetDeviceStateRoute(int deviceIdx)
        {
            try
            {


                if (devinfo28.DeviceKind == 28)
                {
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 获取设备状态

                        devinfoRoute = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                        if (devinfoRoute.Dbw2Address != -1)
                        {
                            int temp = devinfoRoute.Dbw2Address - devinfo28.Dbw2Address;
                            decimal glen = devinfoRoute.Dbw2Getlength;
                            int[] states = new int[6];
                            switch (devinfoRoute.DeviceKind.ToString())
                            {

                                #region 其他设备
                                case "1"://堆垛机

                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = (CStaticClass.AllReturns[temp + 2] << 8) + CStaticClass.AllReturns[temp + 3];//任务号
                                    states[3] = CStaticClass.AllReturns[temp + 7] + (CStaticClass.AllReturns[temp + 6] << 8) + (CStaticClass.AllReturns[temp + 5] << 16) + (CStaticClass.AllReturns[temp + 4] << 32);//X坐标
                                    states[4] = CStaticClass.AllReturns[temp + 11] + (CStaticClass.AllReturns[temp + 10] << 8) + (CStaticClass.AllReturns[temp + 9] << 16) + (CStaticClass.AllReturns[temp + 8] << 32);//Y坐标
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                case "2"://输送机
                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = (CStaticClass.AllReturns[temp + 2] << 8) + CStaticClass.AllReturns[temp + 3];//任务号
                                    states[3] = 0;
                                    states[4] = 0;
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                case "4"://RGV
                                    states[0] = CStaticClass.AllReturns[temp];//读写标志
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态
                                    states[2] = (CStaticClass.AllReturns[temp + 2] << 8) + CStaticClass.AllReturns[temp + 3];//任务号
                                    states[3] = CStaticClass.AllReturns[temp + 7] + (CStaticClass.AllReturns[temp + 6] << 8) + (CStaticClass.AllReturns[temp + 5] << 16) + (CStaticClass.AllReturns[temp + 4] << 32);//X坐标
                                    states[4] = 0;
                                    states[5] = deviceIdx;//设备号索引

                                    break;
                                #endregion
                            }


                            return states;
                        }
                        else
                        {
                            return null;
                        }


                        #endregion


                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch //(Exception ex)
            {
                //if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得指定光电开关的信号时：" + ex.Message) < 0)
                //{

                //    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得指定光电开关的信号时：" + ex.Message, true);
                //}
                return null;
            }
        }
        /// <summary>
        ///设置所有堆垛机的当前动态属性
        /// </summary>
        public static void SetStackState()
        {
            lock (LockStack)
            {
                try
                {
                    DateTime dt1 = DateTime.Now;
                    bool updateroute = false;
                    bool reportstatus = true;
                    if (CStaticClass.routetime.AddSeconds(30) <= DateTime.Now)
                    {
                        updateroute = false;
                        CStaticClass.routetime = DateTime.Now;
                    }
                    //if (CStaticClass.reporttime.AddSeconds(3) <= DateTime.Now)
                    //{
                    //    //DateTime dt2 = DateTime.Now;

                    //    //System.Diagnostics.Trace.WriteLine("更新设备状态周期:" + Convert.ToString(dt2));

                    //    reportstatus = true;
                    //    CStaticClass.reporttime = DateTime.Now;
                    //}
                    //else
                    //{
                    //    reportstatus = false;
                    //}

                    //string ss3 = "";
                    //string ss = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                    //bool updateroute = false;
                    //if (CStaticClass.routetime.AddSeconds(10) <= DateTime.Now)
                    //{
                    //    updateroute = true;
                    //    CStaticClass.routetime = DateTime.Now;
                    //}
                    int[] States;
                    foreach (Model.MDevice devinfo1 in Model.CGetInfo.DeviceInfo.Values)
                    {

                        DateTime dt3 = DateTime.Now;
                        //ss = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                        if (devinfo1.DeviceKind != 1)
                        {
                            continue;
                        }
                        //DataView dvv = dbo.ExceSQL("SELECT F_DeviceIndex FROM T_Base_Device WHERE (F_LockedState = - 1) and F_DeviceIndex=" + devinfo1.DeviceIndex + "").Tables[0].DefaultView;
                        //if (dvv.Count > 0)
                        //{

                        //    if (updateroute == true)
                        //    {//20100131
                        //        UpdateErrorCode(devinfo1.DeviceIndex, 98);
                        //        AlterRoute(devinfo1.DeviceIndex, 98);
                        //    }
                        //    //20090926
                        //    if (devinfo1.ErrorCode != 98)
                        //    {
                        //        UpdateErrorCode(devinfo1.DeviceIndex, 98);
                        //        AlterRoute(devinfo1.DeviceIndex, 98);
                        //        devinfo1.RunState = 4;

                        //    }
                        //    devinfo1.ErrorCode = 98;
                        //}
                        //else
                        //{
                        if (devinfo1.DeviceIndex == 11003)
                        {
                            devinfo1.DeviceIndex = 11003;
                        }
                        if ((devinfo1.DeviceKind == 14) || (devinfo1.DeviceKind == 18))
                        {
                            //devinfo1.DeviceVisual = GetDevicePhotoelectric(devinfo1.DeviceIndex);
                            //continue;
                        }
                        if ((devinfo1.DeviceKind == 2) || (devinfo1.DeviceKind == 3) || (devinfo1.DeviceKind == 5) || (devinfo1.DeviceKind == 17))
                        {
                            ////有些输送机、提升机在调度路径中存在，但是不需要调度来下指令，电器自己控制，只考察是否运行和故障位就可以了
                            //if (devinfo1.OnlyDetectIO == "1")
                            //{

                            //    #region 运行位（设备索引+7）
                            //    devinfo1.RunState = GetDevicePhotoelectric(Convert.ToInt32(devinfo1.DeviceIndex.ToString() + "7"));
                            //    if (updateroute == true)
                            //    {//20100131
                            //        UpdateErrorCode(devinfo1.DeviceIndex, 0);
                            //        AlterRoute(devinfo1.DeviceIndex, 0);
                            //    }
                            //    if (devinfo1.ErrorCode != 0)
                            //    {
                            //        AlterRoute(devinfo1.DeviceIndex, 0);
                            //    }
                            //    //20090926
                            //    int err = 0;
                            //    //devinfo1.ErrorCode = 0;
                            //    #endregion



                            //    #region 故障位（设备索引+6）
                            //    if (GetDevicePhotoelectric(Convert.ToInt32(devinfo1.DeviceIndex.ToString() + "6")) == 1)
                            //    {
                            //        if (updateroute == true)
                            //        {//20100131
                            //            UpdateErrorCode(devinfo1.DeviceIndex, 97);
                            //            AlterRoute(devinfo1.DeviceIndex, 97);
                            //        }
                            //        devinfo1.RunState = 2;
                            //        if (devinfo1.ErrorCode != 97)
                            //        {
                            //            UpdateErrorCode(devinfo1.DeviceIndex, 97);
                            //            AlterRoute(devinfo1.DeviceIndex, 97);
                            //        }
                            //        err = 97;
                            //        //devinfo1.ErrorCode = 97;

                            //    }

                            //    //20100131
                            //    if (updateroute == true)
                            //    {//20100131
                            //        UpdateErrorCode(devinfo1.DeviceIndex, err);
                            //        AlterRoute(devinfo1.DeviceIndex, err);
                            //    }
                            //    if (devinfo1.ErrorCode != err)
                            //    {
                            //        UpdateErrorCode(devinfo1.DeviceIndex, err);
                            //        AlterRoute(devinfo1.DeviceIndex, err);
                            //    }
                            //    //20100131


                            //    devinfo1.ErrorCode = err;
                            //    //20090926

                            //    #endregion


                            //}
                            //else
                            //{

                            //    States = GetDeviceState(devinfo1.DeviceIndex);
                            //    if (States == null) continue;

                            //    if (States[1] >= 30)
                            //    {
                            //        if (updateroute == true)
                            //        {//20100131
                            //            UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                            //            AlterRoute(devinfo1.DeviceIndex, States[1]);
                            //        }
                            //        //20100131

                            //        //修改路径表
                            //        if (States[1] != devinfo1.ErrorCode)
                            //        {
                            //            UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                            //            AlterRoute(devinfo1.DeviceIndex, States[1]);
                            //        }

                            //        devinfo1.ErrorCode = States[1];
                            //        devinfo1.RunState = 2;
                            //    }

                            //    else if ((States[1] == 0) || (States[1] == 1) || (States[1] == 2))
                            //    {
                            //        if (updateroute == true)
                            //        {//20100131
                            //            UpdateErrorCode(devinfo1.DeviceIndex, 0);
                            //            AlterRoute(devinfo1.DeviceIndex, States[1]);
                            //        }
                            //        //20100131

                            //        //修改路径表
                            //        if (States[1] != devinfo1.ErrorCode)
                            //        {
                            //            //UpdateErrorCode(devinfo1.DeviceIndex, 0);
                            //            //AlterRoute(devinfo1.DeviceIndex, States[1]);
                            //        }
                            //        //20090926

                            //        if (States[1] == 2)
                            //        {
                            //            //20090920
                            //            devinfo1.RunState = 5;
                            //        }
                            //        else
                            //        {
                            //            devinfo1.RunState = States[1];
                            //        }
                            //        //20100131


                            //        //20091006
                            //        devinfo1.ErrorCode = States[1];
                            //        //20090926
                            //    }
                            //    devinfo1.TaskNo = States[2];
                            //    //20101118
                            //    if (devinfo1.SplitByte != -1)
                            //    {
                            //        devinfo1.SplitByte_0 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 0);
                            //        devinfo1.SplitByte_1 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 1);
                            //        devinfo1.SplitByte_2 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 2);
                            //        devinfo1.SplitByte_3 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 3);
                            //    }
                            //}

                        }
                        if ((devinfo1.DeviceKind == 1) || (devinfo1.DeviceKind == 4))
                        {
                            States = GetDeviceState(devinfo1.DeviceIndex);

                            if (States == null) continue;


                            if (States[1] >= 30)
                            {
                                if (updateroute == true)
                                {//20100131
                                    UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                    AlterRoute(devinfo1.DeviceIndex, States[1]);
                                }
                                //修改路径表
                                if (States[1] != devinfo1.ErrorCode)
                                {
                                    //20100131
                                    UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                    AlterRoute(devinfo1.DeviceIndex, States[1]);
                                }
                                devinfo1.ErrorCode = States[1];
                                devinfo1.RunState = 2;
                            }
                            else if ((States[1] == 0) || (States[1] == 1) || (States[1] == 2))
                            {
                                if (updateroute == true)
                                {//20100131
                                    UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                    AlterRoute(devinfo1.DeviceIndex, States[1]);
                                }
                                //修改路径表
                                if (States[1] != devinfo1.ErrorCode)
                                {
                                    //20100131
                                    UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                    AlterRoute(devinfo1.DeviceIndex, States[1]);
                                }
                                //20090926

                                if (States[1] == 2)
                                {
                                    //20090920
                                    devinfo1.RunState = 5;
                                }
                                else
                                {
                                    devinfo1.RunState = States[1];
                                }
                                //20100131
                                devinfo1.ErrorCode = States[1];

                            }
                            devinfo1.TaskNo = States[2];
                            devinfo1.XCoor = States[3];
                            devinfo1.YCoor = States[4];

                        }
                        int bdv = 0, bdov = 0;
                        //20101118
                        string[] DS; char[] dd = new char[1] { '.' };
                        int devicebyte = 0; int devbit = 0;

                        if (devinfo1.BindingDevice != null)
                        {
                            DS = devinfo1.BindingDevice.Split(dd);
                            int.TryParse(DS[0], out devicebyte);
                            int.TryParse(DS[1], out devbit);
                            bdv = GetDevicePhotoelectric(devicebyte, devbit);
                        }
                        if (devinfo1.BindingDeviceOut != null)
                        {
                            DS = devinfo1.BindingDeviceOut.Split(dd);
                            int.TryParse(DS[0], out devicebyte);
                            int.TryParse(DS[1], out devbit);
                            bdov = GetDevicePhotoelectric(devicebyte, devbit);

                        }
                        //20101118
                        if ((bdv + bdov) >= 1)
                        {
                            devinfo1.HaveGoods = true;
                        }
                        else
                        {
                            devinfo1.HaveGoods = false;
                        }
                        DataView dvb = dbo.ExceSQL("SELECT F_MonitorIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6, F_TxtParam FROM T_Monitor_Task WHERE (F_MonitorIndex = " + devinfo1.TaskNo + ")").Tables[0].DefaultView;
                        if (dvb.Count > 0)
                        {
                            if (devinfo1.DeviceKind == 1)
                            {
                                devinfo1.ArrowLocation = dvb[0]["F_NumParam4"].ToString() + "排" + dvb[0]["F_NumParam5"].ToString() + "列" + dvb[0]["F_NumParam6"].ToString() + "层";
                            }
                            if (devinfo1.DeviceKind == 4)
                            {
                                devinfo1.ArrowLocation = dvb[0]["F_NumParam1"].ToString();
                            }
                            if (devinfo1.DeviceKind == 2)
                            {
                                devinfo1.ArrowLocation = dvb[0]["F_NumParam4"].ToString();
                            }
                            devinfo1.Barcode = dvb[0]["F_TxtParam"].ToString();

                        }
                        else
                        {
                            devinfo1.Barcode = "";
                            devinfo1.ArrowLocation = "";
                        }
                        //20091107
                        dvb = null;

                        //}
                        //ss3 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                        Model.CGetInfo.SetDeviceInfo(devinfo1);
                        //20091107
                        //dvv = null;
                        //20110427 上报管理系统设备状态

                        if (reportstatus == true)
                        {

                            if (devinfo1.DeviceKind == 1 || devinfo1.DeviceKind == 2 || devinfo1.DeviceKind == 3 || devinfo1.DeviceKind == 5)
                            {
                                int CurRunState = 0;
                                if (devinfo1.RunState == 0 || devinfo1.RunState == 5)
                                {
                                    CurRunState = 0;
                                }
                                else
                                    if (devinfo1.RunState == 4)
                                    {
                                        CurRunState = 3;
                                    }
                                    else
                                    {
                                        CurRunState = devinfo1.RunState;
                                    }


                                if (devinfo1.LastRunState != CurRunState)
                                {

                                    try
                                    {
                                        //上报设备状态和当前时间
                                        string dtime = DateTime.Now.ToString("u");
                                        dtime = dtime.Substring(0, dtime.Length - 1);
                                        //  int  CurRunState= devinfo.RunState==
                                        //string sql = string.Format("Update DEVICE_MONITOR set DEVICE_CUR_STATUS={0}, DEVICE_PRE_STATUS={1},UPDATE_TIME='{2}' where DEVICE_CODE ={3}", CurRunState,devinfo.LastRunState,dtime, devinfo.DeviceIndex);
                                        //    string sql = string.Format("Update DEVICE_MONITOR set DEVICE_CUR_STATUS={0},UPDATE_TIME='{1}' where DEVICE_CODE ={2}", CurRunState, dtime, devinfo1.DeviceIndex);
                                        devinfo1.LastRunState = CurRunState;
                                        Model.CGetInfo.SetDeviceLastRunState(devinfo1);

                                        //  dboMan.ExceSQL(sql);

                                        //更新LastRunState


                                    }
                                    catch (Exception ex)
                                    {
                                        _CParsePLCError = string.Format("上报设备{0}的设备状态时发生错误:{1}", devinfo1.DeviceIndex, ex.Message);


                                    }

                                }

                            }

                        }


                        DateTime dt4 = DateTime.Now;
                        System.Diagnostics.Trace.WriteLine(devinfo1.DeviceName + "*****" + (dt4 - dt3).ToString());
                    }
                    //string ss2 = ss;
                    //string ss1 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                    DateTime dt2 = DateTime.Now;
                    System.Diagnostics.Trace.WriteLine("SetStackState" + (dt2 - dt1).ToString());

                }

                catch (Exception exa)
                {

                    _CParsePLCError = "解析PLC反馈数据的记录设备状态时发生错误：" + exa.Message;

                }
            }
        }

        /// <summary>
        /// 设置所有设备的当前动态属性
        /// </summary>
        public static void SetDeviceState()
        {
            lock (LockData)
            {

                try
                {
                    DateTime dt1 = DateTime.Now;
                    bool updateroute = false;
                    bool reportstatus = true;
                    if (CStaticClass.routetime.AddSeconds(30) <= DateTime.Now)
                    {
                        updateroute = true;
                        CStaticClass.routetime = DateTime.Now;
                    }
                    //if (CStaticClass.reporttime.AddSeconds(3) <= DateTime.Now)
                    //{
                    //    //DateTime dt2 = DateTime.Now;

                    //    //System.Diagnostics.Trace.WriteLine("更新设备状态周期:" + Convert.ToString(dt2));

                    //    reportstatus = true;
                    //    CStaticClass.reporttime = DateTime.Now;
                    //}
                    //else
                    //{
                    //    reportstatus = false;
                    //}

                    //string ss3 = "";
                    //string ss = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                    //bool updateroute = false;
                    //if (CStaticClass.routetime.AddSeconds(10) <= DateTime.Now)
                    //{
                    //    updateroute = true;
                    //    CStaticClass.routetime = DateTime.Now;
                    //}
                    int[] States;
                    foreach (Model.MDevice devinfo1 in Model.CGetInfo.DeviceInfo.Values)
                    {

                        DateTime dt3 = DateTime.Now;
                        //ss = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                        if (devinfo1.DeviceKind != 1)
                        {
                            continue;
                        }
                        DataView dvv = dbo.ExceSQL("SELECT F_DeviceIndex FROM T_Base_Device WHERE (F_LockedState = - 1) and F_DeviceIndex=" + devinfo1.DeviceIndex + "").Tables[0].DefaultView;
                        if (dvv.Count > 0)
                        {

                            if (updateroute == true)
                            {//20100131
                                UpdateErrorCode(devinfo1.DeviceIndex, 98);
                                AlterRoute(devinfo1.DeviceIndex, 98);
                            }
                            //20090926
                            if (devinfo1.ErrorCode != 98)
                            {
                                UpdateErrorCode(devinfo1.DeviceIndex, 98);
                                AlterRoute(devinfo1.DeviceIndex, 98);
                                devinfo1.RunState = 4;

                            }
                            devinfo1.ErrorCode = 98;
                        }
                        else
                        {
                            if (devinfo1.DeviceIndex == 11003)
                            {
                                devinfo1.DeviceIndex = 11003;
                            }
                            if ((devinfo1.DeviceKind == 14) || (devinfo1.DeviceKind == 18))
                            {
                                //devinfo1.DeviceVisual = GetDevicePhotoelectric(devinfo1.DeviceIndex);
                                //continue;
                            }
                            if ((devinfo1.DeviceKind == 2) || (devinfo1.DeviceKind == 3) || (devinfo1.DeviceKind == 5) || (devinfo1.DeviceKind == 17))
                            {
                                //有些输送机、提升机在调度路径中存在，但是不需要调度来下指令，电器自己控制，只考察是否运行和故障位就可以了
                                if (devinfo1.OnlyDetectIO == "1")
                                {

                                    #region 运行位（设备索引+7）
                                    devinfo1.RunState = GetDevicePhotoelectric(Convert.ToInt32(devinfo1.DeviceIndex.ToString() + "7"));
                                    if (updateroute == true)
                                    {//20100131
                                        UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                        AlterRoute(devinfo1.DeviceIndex, 0);
                                    }
                                    if (devinfo1.ErrorCode != 0)
                                    {
                                        AlterRoute(devinfo1.DeviceIndex, 0);
                                    }
                                    //20090926
                                    int err = 0;
                                    //devinfo1.ErrorCode = 0;
                                    #endregion



                                    #region 故障位（设备索引+6）
                                    if (GetDevicePhotoelectric(Convert.ToInt32(devinfo1.DeviceIndex.ToString() + "6")) == 1)
                                    {
                                        if (updateroute == true)
                                        {//20100131
                                            UpdateErrorCode(devinfo1.DeviceIndex, 97);
                                            AlterRoute(devinfo1.DeviceIndex, 97);
                                        }
                                        devinfo1.RunState = 2;
                                        if (devinfo1.ErrorCode != 97)
                                        {
                                            UpdateErrorCode(devinfo1.DeviceIndex, 97);
                                            AlterRoute(devinfo1.DeviceIndex, 97);
                                        }
                                        err = 97;
                                        //devinfo1.ErrorCode = 97;

                                    }

                                    //20100131
                                    if (updateroute == true)
                                    {//20100131
                                        UpdateErrorCode(devinfo1.DeviceIndex, err);
                                        AlterRoute(devinfo1.DeviceIndex, err);
                                    }
                                    if (devinfo1.ErrorCode != err)
                                    {
                                        UpdateErrorCode(devinfo1.DeviceIndex, err);
                                        AlterRoute(devinfo1.DeviceIndex, err);
                                    }
                                    //20100131


                                    devinfo1.ErrorCode = err;
                                    //20090926

                                    #endregion


                                }
                                else
                                {

                                    States = GetDeviceState(devinfo1.DeviceIndex);
                                    if (States == null) continue;

                                    if (States[1] >= 30)
                                    {
                                        if (updateroute == true)
                                        {//20100131
                                            UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                            AlterRoute(devinfo1.DeviceIndex, States[1]);
                                        }
                                        //20100131

                                        //修改路径表
                                        if (States[1] != devinfo1.ErrorCode)
                                        {
                                            UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                            AlterRoute(devinfo1.DeviceIndex, States[1]);
                                        }

                                        devinfo1.ErrorCode = States[1];
                                        devinfo1.RunState = 2;
                                    }

                                    else if ((States[1] == 0) || (States[1] == 1) || (States[1] == 2))
                                    {
                                        if (updateroute == true)
                                        {//20100131
                                            UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                            AlterRoute(devinfo1.DeviceIndex, States[1]);
                                        }
                                        //20100131

                                        //修改路径表
                                        if (States[1] != devinfo1.ErrorCode)
                                        {
                                            //UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                            //AlterRoute(devinfo1.DeviceIndex, States[1]);
                                        }
                                        //20090926

                                        if (States[1] == 2)
                                        {
                                            //20090920
                                            devinfo1.RunState = 5;
                                        }
                                        else
                                        {
                                            devinfo1.RunState = States[1];
                                        }
                                        //20100131


                                        //20091006
                                        devinfo1.ErrorCode = States[1];
                                        //20090926
                                    }
                                    devinfo1.TaskNo = States[2];
                                    //20101118
                                    if (devinfo1.SplitByte != -1)
                                    {
                                        devinfo1.SplitByte_0 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 0);
                                        devinfo1.SplitByte_1 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 1);
                                        devinfo1.SplitByte_2 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 2);
                                        devinfo1.SplitByte_3 = GetDevicePhotoelectric(devinfo1.DeviceIndex, 3);
                                    }
                                }

                            }
                            if ((devinfo1.DeviceKind == 1) || (devinfo1.DeviceKind == 4))
                            {
                                States = GetDeviceState(devinfo1.DeviceIndex);

                                if (States == null) continue;


                                if (States[1] >= 30)
                                {
                                    if (updateroute == true)
                                    {//20100131
                                        UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                        AlterRoute(devinfo1.DeviceIndex, States[1]);
                                    }
                                    //修改路径表
                                    if (States[1] != devinfo1.ErrorCode)
                                    {
                                        //20100131
                                        UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                        AlterRoute(devinfo1.DeviceIndex, States[1]);
                                    }
                                    devinfo1.ErrorCode = States[1];
                                    devinfo1.RunState = 2;
                                }
                                else if ((States[1] == 0) || (States[1] == 1) || (States[1] == 2))
                                {
                                    if (updateroute == true)
                                    {//20100131
                                        UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                        AlterRoute(devinfo1.DeviceIndex, States[1]);
                                    }
                                    //修改路径表
                                    if (States[1] != devinfo1.ErrorCode)
                                    {
                                        //20100131
                                        UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                        AlterRoute(devinfo1.DeviceIndex, States[1]);
                                    }
                                    //20090926

                                    if (States[1] == 2)
                                    {
                                        //20090920
                                        devinfo1.RunState = 5;
                                    }
                                    else
                                    {
                                        devinfo1.RunState = States[1];
                                    }
                                    //20100131
                                    devinfo1.ErrorCode = States[1];

                                }
                                devinfo1.TaskNo = States[2];
                                devinfo1.XCoor = States[3];
                                devinfo1.YCoor = States[4];

                            }
                            int bdv = 0, bdov = 0;
                            //20101118
                            string[] DS; char[] dd = new char[1] { '.' };
                            int devicebyte = 0; int devbit = 0;

                            if (devinfo1.BindingDevice != null)
                            {
                                DS = devinfo1.BindingDevice.Split(dd);
                                int.TryParse(DS[0], out devicebyte);
                                int.TryParse(DS[1], out devbit);
                                bdv = GetDevicePhotoelectric(devicebyte, devbit);
                            }
                            if (devinfo1.BindingDeviceOut != null)
                            {
                                DS = devinfo1.BindingDeviceOut.Split(dd);
                                int.TryParse(DS[0], out devicebyte);
                                int.TryParse(DS[1], out devbit);
                                bdov = GetDevicePhotoelectric(devicebyte, devbit);

                            }
                            //20101118
                            if ((bdv + bdov) >= 1)
                            {
                                devinfo1.HaveGoods = true;
                            }
                            else
                            {
                                devinfo1.HaveGoods = false;
                            }
                            DataView dvb = dbo.ExceSQL("SELECT F_MonitorIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6, F_TxtParam FROM T_Monitor_Task WHERE (F_MonitorIndex = " + devinfo1.TaskNo + ")").Tables[0].DefaultView;
                            if (dvb.Count > 0)
                            {
                                if (devinfo1.DeviceKind == 1)
                                {
                                    devinfo1.ArrowLocation = dvb[0]["F_NumParam4"].ToString() + "排" + dvb[0]["F_NumParam5"].ToString() + "列" + dvb[0]["F_NumParam6"].ToString() + "层";
                                }
                                if (devinfo1.DeviceKind == 4)
                                {
                                    devinfo1.ArrowLocation = dvb[0]["F_NumParam1"].ToString();
                                }
                                if (devinfo1.DeviceKind == 2)
                                {
                                    devinfo1.ArrowLocation = dvb[0]["F_NumParam4"].ToString();
                                }
                                devinfo1.Barcode = dvb[0]["F_TxtParam"].ToString();

                            }
                            else
                            {
                                devinfo1.Barcode = "";
                                devinfo1.ArrowLocation = "";
                            }
                            //20091107
                            dvb = null;

                        }
                        //ss3 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                        Model.CGetInfo.SetDeviceInfo(devinfo1);
                        //20091107
                        dvv = null;
                        //20110427 上报管理系统设备状态

                        if (reportstatus == true)
                        {

                            if (devinfo1.DeviceKind == 1 || devinfo1.DeviceKind == 2 || devinfo1.DeviceKind == 3 || devinfo1.DeviceKind == 5)
                            {
                                int CurRunState = 0;
                                if (devinfo1.RunState == 0 || devinfo1.RunState == 5)
                                {
                                    CurRunState = 0;
                                }
                                else
                                    if (devinfo1.RunState == 4)
                                    {
                                        CurRunState = 3;
                                    }
                                    else
                                    {
                                        CurRunState = devinfo1.RunState;
                                    }


                                if (devinfo1.LastRunState != CurRunState)
                                {

                                    try
                                    {
                                        //上报设备状态和当前时间
                                        string dtime = DateTime.Now.ToString("u");
                                        dtime = dtime.Substring(0, dtime.Length - 1);
                                        //  int  CurRunState= devinfo.RunState==
                                        //string sql = string.Format("Update DEVICE_MONITOR set DEVICE_CUR_STATUS={0}, DEVICE_PRE_STATUS={1},UPDATE_TIME='{2}' where DEVICE_CODE ={3}", CurRunState,devinfo.LastRunState,dtime, devinfo.DeviceIndex);
                                        //    string sql = string.Format("Update DEVICE_MONITOR set DEVICE_CUR_STATUS={0},UPDATE_TIME='{1}' where DEVICE_CODE ={2}", CurRunState, dtime, devinfo1.DeviceIndex);
                                        devinfo1.LastRunState = CurRunState;
                                        Model.CGetInfo.SetDeviceLastRunState(devinfo1);

                                        //  dboMan.ExceSQL(sql);

                                        //更新LastRunState


                                    }
                                    catch (Exception ex)
                                    {
                                        _CParsePLCError = string.Format("上报设备{0}的设备状态时发生错误:{1}", devinfo1.DeviceIndex, ex.Message);


                                    }

                                }

                            }

                        }


                        DateTime dt4 = DateTime.Now;
                        // System.Diagnostics.Trace.WriteLine(devinfo1.DeviceName + "*****" + (dt4 - dt3).ToString());
                    }
                    //string ss2 = ss;
                    //string ss1 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
                    DateTime dt2 = DateTime.Now;
                    System.Diagnostics.Trace.WriteLine("CPARSEStack" + (dt2 - dt1).ToString());

                }

                catch (Exception exa)
                {

                    _CParsePLCError = "解析PLC反馈数据的记录设备状态时发生错误：" + exa.Message;

                }
            }
        }
        /// <summary>
        /// 设置所有路径状态
        /// </summary>
        public static void SetRouteStatus()
        {
            try
            {
                bool updateroute = false;
                if (CStaticClass.routetime.AddSeconds(60) <= DateTime.Now)
                {
                    updateroute = true;
                    CStaticClass.routetime = DateTime.Now;
                }
                int[] States;
                foreach (Model.MDevice devinfo1 in Model.CGetInfo.DeviceInfo.Values)
                {
                    DataView dvv = dboRoute.ExceSQL("SELECT F_DeviceIndex FROM T_Base_Device WHERE (F_LockedState = - 1) and F_DeviceIndex=" + devinfo1.DeviceIndex + "").Tables[0].DefaultView;
                    if (dvv.Count > 0)
                    {
                        if (updateroute == true) AlterRoute(devinfo1.DeviceIndex, 98);
                        devinfo1.RunState = 4;
                        if (devinfo1.ErrorCode != 98)
                        {
                            AlterRoute(devinfo1.DeviceIndex, 98);
                        }
                        //UpdateErrorCode(devinfo1.DeviceIndex, 98);
                    }
                    else
                    {
                        if ((devinfo1.DeviceKind == 14) || (devinfo1.DeviceKind == 18))
                        {
                            devinfo1.DeviceVisual = GetDevicePhotoelectricRoute(devinfo1.DeviceIndex);
                            continue;
                        }
                        if ((devinfo1.DeviceKind == 2) || (devinfo1.DeviceKind == 3))
                        {
                            //有些输送机、提升机在调度路径中存在，但是不需要调度来下指令，电器自己控制，只考察是否运行和故障位就可以了
                            if (devinfo1.OnlyDetectIO == "1")
                            {
                                #region 运行位（设备索引+4）
                                devinfo1.RunState = GetDevicePhotoelectricRoute(Convert.ToInt32(devinfo1.DeviceIndex.ToString() + "4"));
                                if (devinfo1.ErrorCode != 0)
                                {
                                    AlterRoute(devinfo1.DeviceIndex, 0);
                                }
                                devinfo1.ErrorCode = 0;
                                #endregion
                                #region 故障位（设备索引+10）
                                if (GetDevicePhotoelectricRoute(Convert.ToInt32(devinfo1.DeviceIndex.ToString() + "10")) == 1)
                                {
                                    //20091006
                                    if (updateroute == true) AlterRoute(devinfo1.DeviceIndex, 97);
                                    devinfo1.RunState = 2;
                                    if (devinfo1.ErrorCode != 97)
                                    {
                                        AlterRoute(devinfo1.DeviceIndex, 97);
                                    }
                                    //devinfo1.ErrorCode = 97;


                                }
                                else
                                {
                                    //20091006
                                    if (updateroute == true) AlterRoute(devinfo1.DeviceIndex, 0);
                                }
                                //UpdateErrorCode(devinfo1.DeviceIndex, devinfo1.ErrorCode);
                                #endregion
                            }
                            else
                            {
                                States = GetDeviceStateRoute(devinfo1.DeviceIndex);
                                if (States == null) continue;
                                if (updateroute == true) AlterRoute(devinfo1.DeviceIndex, States[1]);
                                if (States[1] >= 30)
                                {
                                    //修改路径表
                                    if (States[1] != devinfo1.ErrorCode)
                                    {
                                        AlterRoute(devinfo1.DeviceIndex, States[1]);
                                    }
                                    //devinfo1.ErrorCode = States[1];
                                    //devinfo1.RunState = 2;
                                    //UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                                }

                                else if ((States[1] == 0) || (States[1] == 1) || (States[1] == 2))
                                {
                                    //修改路径表
                                    if (States[1] != devinfo1.ErrorCode)
                                    {
                                        AlterRoute(devinfo1.DeviceIndex, States[1]);
                                    }
                                    //devinfo1.ErrorCode = 0;
                                    //if (States[1] == 2)
                                    //{
                                    //    devinfo1.RunState = 0;
                                    //}
                                    //else
                                    //{
                                    //    devinfo1.RunState = States[1];
                                    //}
                                    //UpdateErrorCode(devinfo1.DeviceIndex, 0);
                                }
                                //devinfo1.TaskNo = States[2];
                            }

                        }
                        if ((devinfo1.DeviceKind == 1) || (devinfo1.DeviceKind == 4))
                        {
                            States = GetDeviceStateRoute(devinfo1.DeviceIndex);

                            if (States == null) continue;
                            if (updateroute == true) AlterRoute(devinfo1.DeviceIndex, States[1]);
                            //修改路径表
                            if (States[1] != devinfo1.ErrorCode)
                            {
                                AlterRoute(devinfo1.DeviceIndex, States[1]);
                            }
                            //if (States[1] >= 30)
                            //{
                            //    devinfo1.ErrorCode = States[1];
                            //    devinfo1.RunState = 2;
                            //    UpdateErrorCode(devinfo1.DeviceIndex, States[1]);
                            //}
                            else if ((States[1] == 0) || (States[1] == 1) || (States[1] == 2))
                            {
                                //修改路径表
                                if (States[1] != devinfo1.ErrorCode)
                                {
                                    AlterRoute(devinfo1.DeviceIndex, States[1]);
                                }
                                //devinfo1.ErrorCode = 0;
                                //if (States[1] == 2)
                                //{
                                //    devinfo1.RunState = 0;
                                //}
                                //else
                                //{
                                //    devinfo1.RunState = States[1];
                                //}
                                //UpdateErrorCode(devinfo1.DeviceIndex, 0);
                            }
                            //devinfo1.TaskNo = States[2];
                            //devinfo1.XCoor = States[3];
                            //devinfo1.YCoor = States[4];

                        }
                        //int bdv = 0, bdov = 0;
                        //if (devinfo1.BindingDevice != null)
                        //{
                        //    bdv = GetDevicePhotoelectric(Convert.ToInt32(devinfo1.BindingDevice));
                        //}
                        //if (devinfo1.BindingDeviceOut != null)
                        //{
                        //    bdov = GetDevicePhotoelectric(Convert.ToInt32(devinfo1.BindingDeviceOut));
                        //}
                        //if ((bdv + bdov) >= 1)
                        //{
                        //    devinfo1.HaveGoods = true;
                        //}
                        //else
                        //{
                        //    devinfo1.HaveGoods = false;
                        //}
                        //DataView dvb = dbo.ExceSQL("SELECT F_MonitorIndex,F_NumParam1,F_NumParam2,F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6, F_TxtParam FROM T_Monitor_Task WHERE (F_MonitorIndex = " + devinfo1.TaskNo + ")").Tables[0].DefaultView;
                        //if (dvb.Count > 0)
                        //{
                        //    if (devinfo1.DeviceKind == 1)
                        //    {
                        //        devinfo1.ArrowLocation = dvb[0]["F_NumParam4"].ToString() + "排" + dvb[0]["F_NumParam5"].ToString() + "列" + dvb[0]["F_NumParam6"].ToString() + "层";
                        //    }
                        //    if (devinfo1.DeviceKind == 4)
                        //    {
                        //        devinfo1.ArrowLocation = dvb[0]["F_NumParam1"].ToString();
                        //    }
                        //    if (devinfo1.DeviceKind == 2)
                        //    {
                        //        devinfo1.ArrowLocation = dvb[0]["F_NumParam4"].ToString();
                        //    }
                        //    devinfo1.Barcode = dvb[0]["F_TxtParam"].ToString();

                        //}
                        //else
                        //{
                        //    devinfo1.Barcode = "";
                        //    devinfo1.ArrowLocation = "";
                        //}

                    }
                    //Model.CGetInfo.SetDeviceInfo(devinfo1);


                }
                //string ss2 = ss;
                //string ss1 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();

            }

            catch (Exception exa)
            {

                _CParsePLCError = "解析PLC反馈数据，修改路径时发生错误：" + exa.Message;

            }
        }
        /// <summary>
        /// 修改本地路径表、反馈给管理的路径表以及提出修改申请
        /// </summary>
        /// <param name="devInx">发生故障的设备索引</param>
        /// <returns></returns>
        //public static bool AlterRoute(int devInx, int state)
        //{


        //    //string ss1 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
        //    try
        //    {
        //        DataView dv = dboRoute.ExceSQL("select distinct F_RouteID from T_Base_Route_Device where F_DeviceIndex=" + devInx).Tables[0].DefaultView;
        //        for (int i = 0; i < dv.Count; i++)
        //        {
        //            if (state >= 30)
        //            {
        //                //所有子路径都不可用时，方才设定此路径真的不可用
        //                string sql = " SELECT T_Base_Route_Device.F_RouteIDSub, SUM(T_Base_Device.F_ErrorCode) AS ErrorCodes " +
        //                            " FROM T_Base_Route_Device,T_Base_Device where T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex" +
        //                            " and T_Base_Route_Device.F_RouteID=" + dv[i]["F_RouteID"] + " GROUP BY T_Base_Route_Device.F_RouteIDSub ";
        //                DataView dvr = dboRoute.ExceSQL(sql).Tables[0].DefaultView;
        //                bool ifUsable = false;
        //                for (int kk = 0; kk < dvr.Count; kk++)
        //                {
        //                    if (Convert.ToInt32(dvr[kk]["ErrorCodes"]) <= 0)
        //                    {
        //                        ifUsable = true;
        //                        break;
        //                    }
        //                }
        //                if (ifUsable == false)
        //                {
        //                    //20101011
        //                    int ups = dboRoute.ExecuteSql("update t_base_route set F_Status=0 where f_routeid=" + dv[i]["F_RouteID"] + " and F_Status=1 and F_AutoUpdate=1 ");
        //                    if (ups > 0)
        //                        dboMan.ExceSQL("update IO_CONTROL_ROUTE set CONTROL_ROUTE_STATUS=0 where CONTROL_ROUTE_ID='" + dv[i]["F_RouteID"] + "' and CONTROL_ROUTE_STATUS=1");
        //                }

        //            }
        //            else
        //            {
        //                DataView dv1 = dboRoute.ExceSQL("SELECT SUM(T_Base_Device.F_ErrorCode) as errcode FROM T_Base_Device ,T_Base_Route_Device" +
        //                    " where T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and T_Base_Route_Device.F_RouteID=" + dv[i]["F_RouteID"]).Tables[0].DefaultView;
        //                if (dv1.Count > 0)
        //                {
        //                    int errcode = 0;
        //                    if (Microsoft.VisualBasic.Information.IsNumeric(dv1[0]["errcode"]) == true)
        //                    {
        //                        errcode = Convert.ToInt32(dv1[0]["errcode"]);
        //                    }

        //                    if (errcode <= 0)
        //                    {
        //                        //20101011
        //                        int ups = dboRoute.ExecuteSql("update t_base_route set F_Status=1 where f_routeid=" + dv[i]["F_RouteID"] + " and F_Status=0 and F_AutoUpdate=1 ");
        //                        if (ups > 0)
        //                            dboMan.ExceSQL("update IO_CONTROL_ROUTE set CONTROL_ROUTE_STATUS=1 where CONTROL_ROUTE_ID='" + dv[i]["F_RouteID"] + "' and CONTROL_ROUTE_STATUS=0");
        //                    }
        //                }


        //            }
        //        }

        //        //string ss11 = DateTime.Now.Second.ToString() + "-" + DateTime.Now.Millisecond.ToString();
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        _CParsePLCError = "解析PLC反馈数据的修改路径时发生错误：" + ex.Message;
        //        return false;
        //    }
        //}

        public static bool AlterRoute(int devInx, int state)
        {


            try
            {
                //SELECT T_Base_Route_Device.F_RouteIDSub, T_Base_Route_Device.F_RouteID, T_Base_Route_Device.F_DeviceIndex FROM T_Base_Route_Device,T_Base_Device where  T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex GROUP BY T_Base_Route_Device.F_RouteIDSub, T_Base_Route_Device.F_RouteID, T_Base_Route_Device.F_DeviceIndex HAVING (SUM(T_Base_Device.F_ErrorCode) <= 0) AND (T_Base_Route_Device.F_DeviceIndex = 12030)
                sql.Remove(0, sql.Length);
                sql.Append("select distinct F_RouteID from T_Base_Route_Device where F_DeviceIndex=").Append(devInx);
                DataView dv = dboRoute.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                for (int i = 0; i < dv.Count; i++)
                {
                    if (state >= 30)
                    {
                        //所有子路径都不可用时，方才设定此路径真的不可用
                        sql.Remove(0, sql.Length);
                        sql.Append(" SELECT T_Base_Route_Device.F_RouteIDSub, SUM(T_Base_Device.F_ErrorCode) AS ErrorCodes ").Append(
                                    " FROM T_Base_Route_Device,T_Base_Device where T_Base_Route_Device.F_DeviceIndex = T_Base_Device.F_DeviceIndex").Append(
                                    " and T_Base_Route_Device.F_RouteID=").Append(dv[i]["F_RouteID"]).Append(" GROUP BY T_Base_Route_Device.F_RouteIDSub ");
                        DataView dvr = dboRoute.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        bool ifUsable = false;
                        for (int kk = 0; kk < dvr.Count; kk++)
                        {
                            if (Convert.ToInt32(dvr[kk]["ErrorCodes"]) <= 0)
                            {
                                ifUsable = true;
                                break;
                            }
                        }
                        if (ifUsable == false)
                        {
                            //20101011
                            sql.Remove(0, sql.Length);
                            sql.Append("update t_base_route set F_Status=0 where f_routeid=").Append(dv[i]["F_RouteID"]).Append(" and F_Status=1 and F_AutoUpdate=1 ");
                            int ups = dboRoute.ExecuteSql(sql.ToString());
                            sql.Remove(0, sql.Length);
                            sql.Append("update IO_CONTROL_ROUTE set CONTROL_ROUTE_STATUS=0 where CONTROL_ROUTE_ID='").Append(dv[i]["F_RouteID"]).Append("' and CONTROL_ROUTE_STATUS=1");
                            if (ups > 0) dboMan.ExceSQL(sql.ToString());
                        }

                    }
                    else
                    {
                        sql.Remove(0, sql.Length);
                        sql.Append("SELECT SUM(T_Base_Device.F_ErrorCode) as errcode FROM T_Base_Device ,T_Base_Route_Device").Append(
                            " where T_Base_Device.F_DeviceIndex = T_Base_Route_Device.F_DeviceIndex and T_Base_Route_Device.F_RouteID=").Append(dv[i]["F_RouteID"]);
                        DataView dv1 = dboRoute.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                        if (dv1.Count > 0)
                        {
                            int errcode = 0;
                            if (Microsoft.VisualBasic.Information.IsNumeric(dv1[0]["errcode"]) == true)
                            {
                                errcode = Convert.ToInt32(dv1[0]["errcode"]);
                            }

                            if (errcode <= 0)
                            {
                                //20101011
                                sql.Remove(0, sql.Length);
                                sql.Append("update t_base_route set F_Status=1 where f_routeid=").Append(dv[i]["F_RouteID"]).Append(" and F_Status=0 and F_AutoUpdate=1 ");
                                int ups = dboRoute.ExecuteSql(sql.ToString());
                                sql.Remove(0, sql.Length);
                                sql.Append("update IO_CONTROL_ROUTE set CONTROL_ROUTE_STATUS=1 where CONTROL_ROUTE_ID='").Append(dv[i]["F_RouteID"]).Append("' and CONTROL_ROUTE_STATUS=0");
                                if (ups > 0) dboMan.ExceSQL(sql.ToString());
                            }
                        }


                    }
                }


                return true;
            }
            catch (Exception ex)
            {
                _CParsePLCError = "解析PLC反馈数据的修改路径时发生错误：" + ex.Message;
                return false;
            }
        }
        static void UpdateErrorCode(int devInx, int errorCode)
        {// and (F_ErrorCode <> " + errorCode + ")

            dbo.ExceSQL("UPDATE T_Base_Device SET F_ErrorCode = " + errorCode + " WHERE (F_DeviceIndex = " + devInx + ")and (F_ErrorCode <> " + errorCode + ")");
        }
    }
}
