using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using ICommLayer;
using CommLayerFactory;
using DBFactory;
using System.Threading;

namespace ControlSystem
{
    /// <summary>
    /// Creator:Richard.liu
    /// 
    /// 命令开关等全局变量的定义
    /// </summary>
    public static class CStaticClass
    {
        static StringBuilder sss = new StringBuilder();
        static StringBuilder[] wv = {new StringBuilder("2") };
        static StringBuilder[] witemnames ={ new StringBuilder("") };
        static char[] dd = new char[1] { '.' };//20101124
        static string[] sp;//20101124
        
        static string _userID;
        /// <summary>
        /// 任务日志和设备故障记录的保存时间，默认为30天
        /// </summary>
        public static string SaveDays = "30";//20110603

        /// <summary>
        /// 用户编号
        /// </summary>

        public static bool isDisassembleTask = false;
        public static string UserID
        {
            get { return CStaticClass._userID; }
            set { CStaticClass._userID = value; }
        }


        static int _MessageIndex;
        static bool _Order;//
        static bool _InvStatus;//
        static bool _ObtainManageTask;//
        static bool _autoOrder;
        static bool _handOrder;
        static bool _tempOrder;

        // 20120619 南昌添加暂停获取任务开关
        static bool _tempStopObtainTask;
        static ISendDeviceOrder sdo;
        //20100108
        static IGetDeviceState gds;
        //20091102
        public static int gcCount = 0;
        //20091107
        
        static string _movedDeviceAheadTrigger = "1";
        /// <summary>
        /// 移动设备是否被提前触发将取
        /// </summary>
        public static string MovedDeviceAheadTrigger
        {
            get { return CStaticClass._movedDeviceAheadTrigger; }
            set 
            {
                if ((value == "0") || (value == "1"))
                {
                    CStaticClass._movedDeviceAheadTrigger = value;
                }
                else
                {
                    CStaticClass._movedDeviceAheadTrigger = "1";
                }
            }
        }
        
        static string _outDetectArrowIdleGoods = "1";
        /// <summary>
        /// 堆垛机出库是否检测目标输送机空闲和有物
        /// </summary>
        public static string OutDetectArrowIdleGoods
        {
            get { return CStaticClass._outDetectArrowIdleGoods; }
            set 
            {
                if ((value == "0") || (value == "1"))
                {
                    CStaticClass._outDetectArrowIdleGoods = value;
                }
                else
                {
                    CStaticClass._outDetectArrowIdleGoods = "1";
                }
            }
        }
        
        static string _deviceErrorAutoModifyRoutePath = "0";
        /// <summary>
        /// 设备发生故障自动变更路径
        /// </summary>
        public static string DeviceErrorAutoModifyRoutePath
        {
            get { return CStaticClass._deviceErrorAutoModifyRoutePath; }
            set 
            { 
                if ((value == "0") || (value == "1"))
                {
                    CStaticClass._deviceErrorAutoModifyRoutePath = value; 
                }
                else
                {
                    CStaticClass._deviceErrorAutoModifyRoutePath = "0";
                }
            }
        }

        static string _doubleForkWaitTime = "120";
        /// <summary>
        /// 双叉关联入库任务允许等待的时间单位（秒）：默认120秒
        /// </summary>
        public static string DoubleForkWaitTime
        {
            get { return CStaticClass._doubleForkWaitTime; }
            set 
            {
                if (Microsoft.VisualBasic.Information.IsNumeric(_doubleForkWaitTime)==true )
                {
                
                    CStaticClass._doubleForkWaitTime = value;
                }
                else
                {
                    CStaticClass._doubleForkWaitTime = "120";
                }
            }
        }
        static string _transportTimeout = "5";
        /// <summary>
        /// 输送超时最大允许时间单位（分）：默认5分钟//20110608
        /// </summary>
        public static string TransportTimeout
        {
            get { return CStaticClass._transportTimeout; }
            set
            {
                if (Microsoft.VisualBasic.Information.IsNumeric(_transportTimeout) == true)
                {

                    CStaticClass._transportTimeout = value;
                }
                else
                {
                    CStaticClass._transportTimeout = "5";
                }
            }
        }
        static string _stackTimeout = "5";
        /// <summary>
        /// 输送超时最大允许时间单位（分）：默认5分钟//20110608
        /// </summary>
        public static string StackTimeout
        {
            get { return CStaticClass._stackTimeout; }
            set
            {
                if (Microsoft.VisualBasic.Information.IsNumeric(_stackTimeout) == true)
                {

                    CStaticClass._stackTimeout = value;
                }
                else
                {
                    CStaticClass._stackTimeout = "5";
                }
            }
        }

        static string _agvAllowSingleFork = "0";
        /// <summary>
        /// AGV是否允许单叉动作，：默认双叉一起动作 0
        /// </summary>
        public static string AGVAllowSingleFork
        {
            get { return CStaticClass._agvAllowSingleFork; }
            set 
            {
                if ((value == "0") || (value == "1"))
                {
                    CStaticClass._agvAllowSingleFork = value; 
                }
                else
                {
                    CStaticClass._agvAllowSingleFork = "0";
                }
                
            }
        }

        //20100108

        /// <summary>
        /// 摄像头服务器IP
        /// </summary>
        public static string CameraIP = "1";
        /// <summary>
        /// 登陆摄像头服务器的用户标识
        /// </summary>
        public static string CameraUsername = "1";
        /// <summary>
        /// 登陆摄像头服务器的密码
        /// </summary>
        public static string CameraPassword = "1";
        public static bool IfRemind = false;

        public static DateTime routetime=DateTime.Now;
        public static DBOperator dbo =new DBOperator();
        public static DBOperator dbo1 = new DBOperator();
        public static DBOperator dboM = new DBOperator("ManConnString", "ManDBFactory");
        public static System.Windows.Forms.Form FormMonitor = null;
        static bool _deviceInit;
        static string _routeSearchMode="0";
        static bool _realRefresh=true;
        public static Model.MDevice devinfo28;
        //20100609
        public static Dictionary<int, System.IO.Ports.SerialPort> serialports=new Dictionary<int,System.IO.Ports.SerialPort>();

        static Model.MDevice devinfo;

        //20120519 nanchang 添加测试程序用的标志变量
        public static bool StopTestLane = true;

        public static bool LIKUSTATUS = true;

        static int _stackSafeDistance = 12; // 可以修改 货位数 == 6个大货格

        public static string BarcodeNull = "11111111111"; //表示未读到条码
        /// <summary>
        /// 堆垛机安全距离
        /// </summary>
        public static int StackSafeDistance
        {
            get { return CStaticClass._stackSafeDistance; }
            set
            {
                CStaticClass._stackSafeDistance = value;
            }
        }


        static StringBuilder manZWhere = new StringBuilder();
        /// <summary>
        /// 获取的任务的排（Z）的between条件OR关系
        /// </summary>
        public static StringBuilder ManZWhere
        {
            get { return CStaticClass.manZWhere; }
            set {
                CStaticClass.manZWhere = value;
                }
            
        }
        //20100607管理数据库类工厂初始化
        
        static string _manDBFactory = dboM.GetValue("ManDBFactory");
        /// <summary>
        /// 管理系统的数据库工厂：SQLServerDBFactory，OracleDBFactory，OleDBFactory
        /// </summary>
        public static string ManDBFactory
        {
            get { return CStaticClass._manDBFactory; }
            set 
            {
                if ((value == "SQLServerDBFactory") || (value == "OracleDBFactory") || (value == "OleDBFactory"))
                {

                    CStaticClass._manDBFactory = value;

                }
                else
                {
                    CStaticClass._manDBFactory = "SQLServerDBFactory";
                }
            }
        }


        static string _manstatus = " F_Status<>-1 ";//默认，显示调度任务全部队列
        static string _monstatus = " F_Status<>-1 ";//默认，显示设备指令全部队列


        /// <summary>
        /// 显示调度任务全部队列" F_Status<>-1 ";等待队列" F_Status=0 "；运行队列" F_Status=1 "；
        /// </summary>
        public static string Manstatus
        {
            get { return CStaticClass._manstatus; }
            set { CStaticClass._manstatus = value; }
        }
        
        /// <summary>
        /// 显示设备指令全部队列" F_Status<>-1 ";等待队列" F_Status=0 "；运行队列" F_Status=1 "；
        /// </summary>
        public static string  Monstatus
        {
            get { return CStaticClass._monstatus; }
            set { CStaticClass._monstatus = value; }
        }
        /// <summary>
        /// 是否实时刷新监控和调度任务列表
        /// </summary>
        public static bool RealRefresh
        {
            get { return CStaticClass._realRefresh; }
            set { CStaticClass._realRefresh = value; }
        }
        /// <summary>
        /// 路径搜索方式:0，按照最优路径选择固定路线；1，每个正在工作的节点作为起始点，向末端节点重新搜索下一个最优路径的节点
        /// </summary>
        public static string RouteSearchMode
        {
            get { return CStaticClass._routeSearchMode; }
            set {
                if ((value == "0") || (value == "1"))
                {
                    CStaticClass._routeSearchMode = value;
                }
                else
                {
                    CStaticClass._routeSearchMode = "0";
                }
            }
        }
        
        /// <summary>
        /// 执行自动命令开关
        /// </summary>
        public static bool AutoOrder
        {
            get { return CStaticClass._autoOrder; }
            set { CStaticClass._autoOrder = value; }
        }
        
        /// <summary>
        /// 执行手工命令开关
        /// </summary>
        public static bool HandOrder
        {
            get { return CStaticClass._handOrder; }
            set { CStaticClass._handOrder = value; }
        }
        /// <summary>
        /// 执行临时管理命令开关
        /// </summary>
        public static bool TempOrder
        {
            get { return CStaticClass._tempOrder; }
            set { CStaticClass._tempOrder = value; }
        }
        /// <summary>
        /// 监控发送消息索引
        /// </summary>
        public static int MessageIndex
        {
            get { return CStaticClass._MessageIndex; }
            set
            {
                if (value > 240)
                {
                    value = 1;
                }

                CStaticClass._MessageIndex = value;
            }
        }
        /// <summary>
        /// 命令开关是否打开
        /// </summary>
        public static bool Order
        {
            get { return CStaticClass._Order; }
            set { CStaticClass._Order = value; }
        }
        /// <summary>
        /// 盘库是否开始
        /// </summary>
        public static bool InvStatus
        {
            get { return CStaticClass._InvStatus; }
            set { CStaticClass._InvStatus = value; }
        }
        /// <summary>
        /// 是否获取调度任务
        /// </summary>
        public static bool ObtainManageTask
        {
            get { return _ObtainManageTask; }
            set { _ObtainManageTask = value; }
        }
        /// <summary>
        /// 20120619 是否暂停获取部分调度任务
        /// </summary>
        public static bool TempStopObtainTask
        {
            get { return _tempStopObtainTask; }
            set { _tempStopObtainTask = value; }
        }
        /// <summary>
        /// 是否执行设备初始化命令
        /// </summary>
        public static bool DeviceInit
        {
            get { return CStaticClass._deviceInit; }
            set { CStaticClass._deviceInit = value; }
        }

        public static void ReConnect()
        {
            //20100127
            //SimensProdave6.CSimensProdave6_S7.InitCount = 0;
            SocketsTCPIP.CClientTCPIP.TcpIPInitCount = 0;
            OPCClient.CCommonOPCClient.ConnectCount = 0;
            // 20120427 南昌 添加每个S7连接的计数清理
            OPCClient.CCommonOPCClient.ErrorCount = new int[11] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        }

        public static int LambDB2Add = 2016;
        static StringBuilder sql = new StringBuilder();
        public static int[] AllReturns;
        static string GetDeviceS7Connection(int deviceindex)
        {//20110216
            DataView dv = dbo.ExceSQL("SELECT F_S7Connection FROM T_Base_Device WHERE (F_DeviceIndex = " + deviceindex + ")").Tables[0].DefaultView;
            if (dv.Count > 0)
            {
                return dv[0]["F_S7Connection"].ToString();
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 20110216支持多个S7Connnection组态OPC
        /// </summary>
        public static Dictionary <string,int[]> MutiS7ConnReturns=new Dictionary<string,int[]>();
        /// <summary>
        /// 取得所有光电开关的信号
        /// </summary>
        public static void GetAllReturns()
        {//20110216
            
            try
            {
                // 20120420 调试时候，增加F_LockedState字段，没有上电的设备不读取。
                DataView dv = dbo.ExceSQL("SELECT F_DeviceIndex,F_S7Connection, F_LockedState FROM T_Base_Device WHERE (F_DeviceKindIndex = 28)").Tables[0].DefaultView;
                if (dv.Count > 0)
                {
                    for (int i = 0; i < dv.Count; i++)
                    {
                        // 20120425 nanchang 调试时候，把没有上电或调试好的S7链接设置成-1
                        if (Convert.ToInt32(dv[i]["F_LockedState"]) != -1)
                        {
                            gds = CommModeCreate.CreateGetDeviceState(Convert.ToInt32(dv[i]["F_DeviceIndex"]));
                            MutiS7ConnReturns[dv[i]["F_S7Connection"].ToString()] = gds.GetDeviceState(Convert.ToInt32(dv[i]["F_DeviceIndex"]), 0);
                            if (gds.CommLayerError != null)
                            {
                                //if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得所有光电开关的信号时：" + gds.CommLayerError) < 0)
                                //{

                                //    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得所有光电开关的信号时：" + gds.CommLayerError, true);
                                //}
                            }
                        }
                    }
                }
                else
                {
                    MutiS7ConnReturns = null;

                }
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得所有光电开关的信号时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得所有光电开关的信号时：" + ex.Message, true);
                }
                return;
            }
        }
        /// <summary>
        /// 取得指定光电开关（确认按钮）设备索引的信号（0，1）
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <returns>0，1</returns>

        public static int GetDevicePhotoelectric(int deviceIdx)
        {
            try
            {
                //20110216
                if (CStaticClass.MutiS7ConnReturns.Count > 0)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                }
                if (deviceIdx == 22001)
                {
                    deviceIdx = 22001;
                }
                if (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 ((devinfo.DeviceKind == 14) || (devinfo.DeviceKind == 18))
                        {
                            //20110216
                            devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));
                            int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                            if (Convert.ToInt32((devinfo.Dbw2Getlength * 8 - 1)) > 7)
                            {
                                glen = Convert.ToInt32((devinfo.Dbw2Getlength * 8 - 1)) - 8;
                                temp = temp + 1;
                            }
                            else
                            {
                                glen = Convert.ToInt32((devinfo.Dbw2Getlength * 8 - 1));
                            }
                            if (temp >= 0)
                            {
                                IfVis = CommonClassLib.CCarryConvert.GetBitFromInteger(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;
                    }
                
            }
            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
            {
                //20110216
                if (MutiS7ConnReturns.Count > 0)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                }
                if (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 (devinfo.SplitByte!=-1)
                        {
                            //20110216
                            devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));
                            int temp = devinfo.SplitByte - devinfo28.Dbw2Address;
                            if (abit > 7)
                            {
                                glen = abit - 8;
                                temp = temp + 1;
                            }
                            else
                            {
                                glen = abit;
                            }
                            if (temp >= 0)
                            {
                                IfVis = CommonClassLib.CCarryConvert.GetBitFromInteger(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;
                    }
                
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得指定光电开关的信号时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得指定光电开关的信号时：" + ex.Message, true);
                }
                return -1;
            }
        }
        /// <summary>
        /// //20101124根据【设备号.bit位】的字符串，取得F_SplitByte里的光电bit值：0,1
        /// </summary>
        /// <param name="deviceIdx"></param>
        /// <param name="bit"></param>
        /// <returns></returns>
        public static int GetDevicePhotoelectric(string devicebit)
        {
            sp = devicebit.Split(dd);//20101124
            if (sp.GetLength(0) <= 1) return -1;
            int deviceIdx,abit;
            int.TryParse(sp[0], out deviceIdx);
            int.TryParse(sp[1], out abit);
            try
            {
                //20110216

                if (CStaticClass.MutiS7ConnReturns.Count > 0)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                }
              
                if (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 (devinfo.SplitByte != -1)
                        {
                            //20110216
                            devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));
                            int temp = devinfo.SplitByte - devinfo28.Dbw2Address;
                            if (abit > 7)
                            {
                                glen = abit - 8;
                                temp = temp + 1;
                            }
                            else
                            {
                                glen = abit;
                            }
                            if (temp >= 0)
                            {
                                IfVis = CommonClassLib.CCarryConvert.GetBitFromInteger(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;
                    }
                
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得指定光电开关的信号时：" + ex.Message) < 0)
                {
                    
                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得指定光电开关的信号时：" + ex.Message, true);
                }
                return -2;
            }
        }
        /// <summary>
        /// 取得指定设备索引的设备状态:[0]读写标志;[1]状态;[2]任务号；[3]X坐标;[4]Y坐标;[5]设备索引
        /// </summary>
        /// <param name="deviceIdx">设备索引</param>
        /// <returns></returns>
        public static int[] GetDeviceState(int deviceIdx)
        {
            //20100108
            //DataView dv;
            //DataView dvM;
            Model.MDevice askdev;
            int[] states = new int[6];
            //string headstr;
            
            DataView dvbc;


            try
            {


                //20110216
                if (CStaticClass.MutiS7ConnReturns.Count > 0)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                }
                if (deviceIdx == 22001)
                {
                    deviceIdx = 22001;
                }
                if (AllReturns != null)
                {
                    #region 获取设备状态

                    devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                    if (devinfo.Dbw2Address != -1)
                    {
                        //20100108
                        //DataView dv;
                        //DataView dvM;
                        //Model.MDevice askdev;
                        //20110216
                        devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));
                        int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                        decimal glen = devinfo.Dbw2Getlength;

                        //20100108
                        states = new int[6];
                        wv[0].Remove(0, wv[0].Length);
                        wv[0].Append("2");
                        witemnames[0].Remove(0, witemnames[0].Length);
                        witemnames[0].Append(Model.CGeneralFunction.DBGet).Append(",byte").Append(Convert.ToString(devinfo.Dbw2Address + 0));
                        sdo = CommModeCreate.CreateSendDeviceOrder(deviceIdx);
                        switch (devinfo.DeviceKind.ToString())
                        {
                            #region 现场控制触摸屏申请信息（16个字节）
                            case "22":

                                if (AllReturns[temp] != 1) return null;
                                states = new int[16];
                                states[0] = 0;
                                states[1] = deviceIdx;
                                states[2] = AllReturns[temp + 1];//命令字
                                states[3] = (AllReturns[temp + 2] << 8) + AllReturns[temp + 3];//设备索引
                                states[4] = (AllReturns[temp + 4] << 8) + AllReturns[temp + 5];//任务号
                                askdev = Model.CGetInfo.GetDeviceInfo(states[3]);
                                //states[2];//命令字
                                //states[3];//设备索引（当前申请设备的索引）
                                //states[4];//任务号（需要修改目标位置的任务号）

                                //20091102
                                if (askdev == null)
                                {
                                    wv[0].Remove(0, wv[0].Length);
                                    wv[0].Append("37");
                                    sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex);//20091013
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "37申请的设备号不存在");
                                    return null;
                                }
                                int bcz = 0;

                                StringBuilder barcode = new StringBuilder();
                                for (int j = 6; j < 16; j++)
                                {
                                    bcz = bcz + AllReturns[temp + j];
                                    barcode.Append(Convert.ToChar(AllReturns[temp + j]).ToString().ToUpper());
                                    states[j - 1] = AllReturns[temp + j];
                                }
                                //20090902新增加arraylength
                                if (IsEquals(devinfo.ReturnMessage, states, 5) == false)
                                {
                                    devinfo.ReturnMessage = states;
                                    Model.CGetInfo.SetDeviceMessage(devinfo);
                                    sss.Remove(0, sss.Length);
                                    sss.Append("**触摸屏设备索引" + states[1]).Append("**命令字" + states[2])
                                        .Append("**申请的设备索引" + states[3]).Append("**申请的任务号" + states[4]).Append("**申请的条码" + barcode);
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "收到现场控制触摸屏申请信息", deviceIdx.ToString(), sss.ToString());

                                }
                                #region 申请重发当前设备指令(1)

                                if (states[2] == 1)//命令字
                                {
                                    if (states[4] == 0)//无任务号
                                    {
                                        if (bcz == 0)//无条码号
                                        {
                                            //32申请的任务号和条形码都不存在
                                            wv[0].Remove(0, wv[0].Length);
                                            wv[0].Append("32");

                                            sdo.WriteDBData(witemnames, wv, devinfo.DeviceIndex );//20091013
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "32申请的任务号和条形码都不存在");
                                            return null;
                                        }
                                        else//有条码号
                                        {
                                            #region 有条码号
                                            //DataView dv = dbo.ExceSQL("SELECT F_BarCode, F_Askkind, F_DeviceIndex FROM T_Base_PLC_Ask where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                                            //if (dv.Count > 0)
                                            //{
                                            //    if (barcode == dv[i]["F_BarCode"].ToString())
                                            //    {
                                            //        return null;
                                            //    }
                                            //    else
                                            //    {
                                            if (askdev.UseCommonDB == "1")
                                            {
                                                sql.Remove(0, sql.Length);
                                                sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                            "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_TxtParam = '").Append(
                                            barcode).Append("'  order by F_MonitorIndex asc");
                                            }
                                            else
                                            {//20090928 and F_DeviceIndex=" + states[3] + "
                                                sql.Remove(0, sql.Length);
                                                sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                            "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_TxtParam = '").Append(
                                            barcode).Append("' order by F_MonitorIndex asc");
                                            }
                                            //20100108
                                            dvbc = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;

                                            if (dvbc.Count > 0)
                                            {
                                                if (askdev.UseCommonDB == "1")
                                                {
                                                    //20090915
                                                    sql.Remove(0, sql.Length);
                                                    sql.Append("update T_Monitor_Task set  F_AheadDetect='',F_DeviceIndex=").Append(states[3]).Append(" where F_MonitorIndex=").Append(dvbc[0]["F_MonitorIndex"]).Append("");
                                                    dbo.ExceSQL(sql.ToString());
                                                }

                                                //wv[0] = "4";
                                                //sdo.WriteDBData(witemnames, wv);
                                                return states;
                                            }
                                            else
                                            {
                                                //35申请的设备号和条形码不匹配
                                                wv[0].Remove(0, wv[0].Length);
                                                wv[0].Append("35");
                                                sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex );//20091013
                                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "35申请的设备号和条形码不匹配");
                                                return null;
                                            }
                                            //    }
                                            //}
                                            #endregion
                                        }
                                    }
                                    else//有任务号
                                    {
                                        #region 有任务号
                                        //DataView dv = dbo.ExceSQL("SELECT F_TaskIndex, F_Askkind, F_DeviceIndex FROM T_Base_PLC_Ask where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                                        //if (dv.Count > 0)
                                        //{
                                        //    if (states[4] == dv[i]["F_TaskIndex"].ToString())
                                        //    {
                                        //        return null;
                                        //    }
                                        //    else
                                        //    {

                                        if (askdev.UseCommonDB == "1")
                                        {
                                            sql.Remove(0, sql.Length);
                                            sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                                    "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_MonitorIndex = '").Append(
                                                    states[4]).Append("' order by F_MonitorIndex asc");
                                        }
                                        else
                                        {//20090928 and F_DeviceIndex=" + states[3] + "
                                            sql.Remove(0, sql.Length);
                                            sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                                    "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_MonitorIndex = '").Append(
                                                    states[4]).Append("' order by F_MonitorIndex asc");
                                        }
                                        //20101008
                                        dvbc = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;

                                        if (dvbc.Count > 0)
                                        {
                                            if (askdev.UseCommonDB == "1")
                                            {
                                                //20090915
                                                sql.Remove(0, sql.Length);
                                                sql.Append("update T_Monitor_Task set F_AheadDetect='',F_DeviceIndex=").Append(states[3]).Append(" where F_MonitorIndex=").Append(dvbc[0]["F_MonitorIndex"]);
                                                dbo.ExceSQL(sql.ToString());
                                            }

                                            //RestoreDevice(Convert.ToInt32(dvbc[0]["F_MonitorIndex"]));
                                            //wv[0] = "4";
                                            //sdo.WriteDBData(witemnames, wv);
                                            ////记录任务号
                                            //dbo.ExceSQL("update T_Base_PLC_Ask set F_TaskIndex='" + states[4]
                                            //    + "' where F_DeviceIndex=" + DeviceIndex);
                                            return states;
                                        }
                                        else
                                        {
                                            //36申请的设备号和任务号不匹配
                                            wv[0].Remove(0, wv[0].Length);
                                            wv[0].Append("36");
                                            sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex);//20091013
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "36申请的设备号和任务号不匹配");
                                            return null;
                                        }
                                        //    }
                                        //}
                                        #endregion
                                    }

                                }

                                #endregion

                                #region 申请修改当前设备所执行任务目标位置(2)

                                else if (states[2] == 2)//命令字
                                {
                                    //申请修改当前设备所执行任务目标位置的F_TaskIndex重复时不允许相应申请
                                    return states;
                                }

                                #endregion

                                #region 上报完成(3)
                                else if (states[2] == 3)//命令字
                                {
                                    if (states[4] == 0)//无任务号
                                    {
                                        if (bcz == 0)//无条码号
                                        {
                                            //32申请的任务号和条形码都不存在
                                            wv[0].Remove(0, wv[0].Length);
                                            wv[0].Append("32");
                                            sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex);//20091013
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "32申请的任务号和条形码都不存在");
                                            return null;
                                        }
                                        else//有条码号
                                        {
                                            #region 有条码号
                                            //20100108
                                            sql.Remove(0, sql.Length);
                                            sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                                    "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_TxtParam = '").Append(
                                            barcode).Append("'  order by F_MonitorIndex asc");
                                            dvbc = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                            if (dvbc.Count > 0)
                                            {

                                                return states;
                                            }
                                            else
                                            {
                                                //30申请的条码号不存在
                                                wv[0].Remove(0, wv[0].Length);
                                                wv[0].Append("30");
                                                sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex);//20091013
                                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "30申请的条码号不存在");
                                                return null;
                                            }
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        #region 有任务号
                                        //DataView dv = dbo.ExceSQL("SELECT F_TaskIndex, F_Askkind, F_DeviceIndex FROM T_Base_PLC_Ask where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                                        //if (dv.Count > 0)
                                        //{
                                        //    if (states[4] == dv[i]["F_TaskIndex"].ToString())
                                        //    {
                                        //        return null;
                                        //    }
                                        //    else
                                        //    {
                                        //and F_DeviceIndex=" + states[3] + "

                                        //20100108
                                        sql.Remove(0, sql.Length);
                                        sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                                    "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_MonitorIndex = '").Append(
                                                    states[4]).Append("'  order by F_MonitorIndex asc");
                                        dvbc = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                        if (dvbc.Count > 0)
                                        {
                                            //wv[0] = "2";
                                            //sdo.WriteDBData(witemnames, wv);
                                            ////记录任务号
                                            //dbo.ExceSQL("update T_Base_PLC_Ask set F_TaskIndex='" + states[4]
                                            //    + "' where F_DeviceIndex=" + DeviceIndex);
                                            return states;
                                        }
                                        else
                                        {
                                            //31申请的任务号不存在
                                            wv[0].Remove(0, wv[0].Length);
                                            wv[0].Append("31");
                                            sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex);//20091013
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "31申请的任务号不存在");
                                            return null;
                                        }
                                        //    }
                                        //}
                                        #endregion
                                    }
                                }
                                #endregion

                                #region 删除当前设备所执行的任务(4)（托盘拿走）
                                else if (states[2] == 4)//命令字
                                {
                                    //20090915
                                    if (states[4] == 0)//无任务号
                                    {
                                        if (bcz == 0)//无条码号
                                        {
                                            //32申请的任务号和条形码都不存在
                                            wv[0].Remove(0, wv[0].Length);
                                            wv[0].Append("32");
                                            sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex);//20091013
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "32申请的任务号和条形码都不存在");
                                            return null;
                                        }
                                        else//有条码号
                                        {
                                            #region 有条码号
                                            //20100108
                                            sql.Remove(0, sql.Length);
                                            sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                                    "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_TxtParam = '").Append(
                                            barcode).Append("'  order by F_MonitorIndex asc");
                                            dvbc = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                            if (dvbc.Count > 0)
                                            {

                                                return states;
                                            }
                                            else
                                            {
                                                //30申请的条码号不存在
                                                wv[0].Remove(0, wv[0].Length);
                                                wv[0].Append("30");
                                                sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex);//20091013
                                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "30申请的条码号不存在");
                                                return null;
                                            }
                                            #endregion
                                        }
                                    }
                                    else
                                    {//20090915
                                        #region 有任务号
                                        //20100108
                                        sql.Remove(0, sql.Length);
                                        sql.Append("SELECT F_MonitorIndex,F_DeviceCommandIndex,F_NumParam1,F_NumParam2,").Append(
                                                            "F_NumParam3,F_NumParam4,F_NumParam5,F_NumParam6 FROM T_Monitor_Task WHERE F_MonitorIndex = '").Append(
                                                            states[4]).Append("' order by F_MonitorIndex asc");
                                        dvbc = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView;
                                        if (dvbc.Count > 0)
                                        {

                                            return states;
                                        }
                                        else
                                        {
                                            //31申请的任务号不存在
                                            wv[0].Remove(0, wv[0].Length);
                                            wv[0].Append("31");
                                            sdo.WriteDBData(witemnames, wv,devinfo .DeviceIndex );//20091013
                                            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "发送现场控制触摸屏申请的反馈信息", deviceIdx.ToString(), "31申请的任务号不存在");
                                            return null;
                                        }
                                        #endregion
                                    }
                                }
                                #endregion
                                break;
                            #endregion


                            #region 机器人码垛信息
                            case "24":

                                if (AllReturns[temp] != 1) return null;
                                states[0] = 0;
                                states[1] = deviceIdx;
                                states[2] = AllReturns[temp + 1];//机器人动作:1-取货完成;2-放货完成;3-托盘码垛完成
                                states[3] = AllReturns[temp + 2];//托盘码垛数量
                                //sdo.WriteDBData(witemnames, wv);
                                devinfo.ReturnMessage = states;
                                Model.CGetInfo.SetDeviceMessage(devinfo);
                                //string ssss = "";
                                //for (int j = 0; j <= 3; j++)
                                //{
                                //    ssss += "**" + states[j].ToString();
                                //}
                                //CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", deviceIdx.ToString(), ssss);


                                break;
                            #endregion


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

                                states[0] = AllReturns[temp];//读写标志
                                states[1] = AllReturns[temp + 1];//状态
                                states[2] = (AllReturns[temp + 2] << 8) + AllReturns[temp + 3];//任务号
                                states[3] = AllReturns[temp + 7] + (AllReturns[temp + 6] << 8) + (AllReturns[temp + 5] << 16) + (AllReturns[temp + 4] << 32);//X坐标
                                //states[4] = AllReturns[temp + 11] + (AllReturns[temp + 10] << 8) + (AllReturns[temp + 9] << 16) + (AllReturns[temp + 8] << 32);//Y坐标
                                states[4] = AllReturns[temp + 8] + AllReturns[temp + 9] + AllReturns[temp + 10] + AllReturns[temp + 11];//Y坐标
                                states[5] = deviceIdx;//设备号索引
                                if (IsEquals(devinfo.ReturnMessage, states, 3) == false)
                                {
                                    devinfo.ReturnMessage = states;
                                    Model.CGetInfo.SetDeviceMessage(devinfo);
                                    sss.Remove(0, sss.Length);
                                    sss.Append("**读标志" + states[0]).Append("**状态" + states[1]).Append("**任务号" + states[2])
                                        .Append("**列坐标" + states[3]).Append("**层坐标" + states[4]);
                                                                        
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "收到堆垛机状态", deviceIdx.ToString(), sss.ToString());
                                   

                                }
                                break;
                            case "2"://输送机
                                states[0] = AllReturns[temp];//读写标志
                                states[1] = AllReturns[temp + 1];//状态
                                states[2] = (AllReturns[temp + 2] << 8) + AllReturns[temp + 3];//任务号
                                states[3] = AllReturns[temp + 4];//20120506 南昌 检尺状态;
                                states[4] = AllReturns[temp + 5];//20120506 南昌 有货开关量检测;
                                states[5] = deviceIdx;//设备号索引
                                if (IsEquals(devinfo.ReturnMessage, states, 3) == false)
                                {
                                    devinfo.ReturnMessage = states;
                                    Model.CGetInfo.SetDeviceMessage(devinfo);

                                    //if (states[1] > 1) // 20120815 改成只记录完成和报警的黑匣子
                                    //{
                                        sss.Remove(0, sss.Length);
                                        sss.Append("**读标志" + states[0]).Append("**状态" + states[1]).Append("**任务号" + states[2]);
                                        if (deviceIdx == 14021 || deviceIdx == 14011)
                                        {
                                            int ssss = 0;
                                        }
                                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "收到输送机状态", deviceIdx.ToString(), sss.ToString());

                                  //  }
                                }
                                break;
                            case "4"://RGV
                                states[0] = AllReturns[temp];//读写标志
                                states[1] = AllReturns[temp + 1];//状态
                                states[2] = (AllReturns[temp + 2] << 8) + AllReturns[temp + 3];//任务号
                                states[3] = AllReturns[temp + 7] + (AllReturns[temp + 6] << 8) + (AllReturns[temp + 5] << 16) + (AllReturns[temp + 4] << 32);//X坐标
                                states[4] = 0;
                                states[5] = deviceIdx;//设备号索引
                                if (IsEquals(devinfo.ReturnMessage, states, 3) == false)
                                {
                                    
                                    devinfo.ReturnMessage = states;
                                    Model.CGetInfo.SetDeviceMessage(devinfo);
                                    sss.Remove(0, sss.Length);
                                    sss.Append("**读标志" + states[0]).Append("**状态" + states[1]).Append("**任务号" + states[2]).Append("**X坐标" + states[3]);
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", deviceIdx.ToString(), sss.ToString());
                                    
                                }
                                break;
                            case "8":// sanyi增加条码扫描仪的关联检尺判断-类型8。2010-4-2
                                states[0] = CStaticClass.AllReturns[temp];//读写标志, 
                                if (states[0] == 2 || states[0] == 0)// 电气初始化可能是0
                                {
                                    return null;
                                }
                                else// 当电气修改读写标志为:1才读取
                                {
                                    states[1] = CStaticClass.AllReturns[temp + 1];//状态,PLC 0:无货 1:低货 2：高货；50检尺错误  51:超重
                                    states[2] = 0;
                                    states[3] = 0;
                                    states[4] = 0;
                                    states[5] = deviceIdx;//设备号索引
                                    string sss = "";
                                    for (int j = 0; j <= 5; j++)
                                    {
                                        sss += "***" + states[j].ToString();
                                    }
                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "CGetDeviceState", deviceIdx.ToString(), sss);
                                    // 清理检尺数据区,读写标志改成2
                                    sdo.WriteDBData(witemnames, wv,devinfo.DeviceIndex);
                                }
                                break;
                            #endregion
                        }


                        return states;

                    }
                    else
                    {
                        return null;
                    }


                    #endregion


                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("CStaticClass取得指定设备状态时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "CStaticClass取得指定设备状态时：" + ex.Message+deviceIdx.ToString (), true);
                }
                return null;
            }
            finally
            {//20100108
                //dv=null;
                //dvM = null;
                askdev = null;
                states = null;
                
                dvbc = null;
            }
        }


        public static string GetStringData(int deviceIdx)
        {
            try
            {


                //20110216

                if (CStaticClass.MutiS7ConnReturns.Count > 0)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                }
                if (AllReturns != null)
                {
                    #region 获取设备状态

                    devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                    if (devinfo.Dbw2Address != -1)
                    {
                        int temp = devinfo.Dbw2Address + 4;
                        //int temp = devinfo.Dbw2Address;
                        decimal glen = devinfo.Dbw2Getlength;
                            
                        string headstr = AllReturns[devinfo.Dbw2Address].ToString();
                        string strdate = string.Empty;
                        if (headstr != "2") return null;
                      
                        switch (devinfo.DeviceKind.ToString())
                        {
                                
                            #region 字符串信息
                            case "7"://条形码
                                sss.Remove(0, sss.Length);
                                for (int i = 0; i < 6; i++)
                                {
                                    sss.Append( Convert.ToChar(AllReturns[temp+i]));

                                }
                                strdate = sss.ToString().TrimEnd('/');
                                CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "读PLC条码", deviceIdx.ToString(), "读标志1**条码：" + strdate);

                                break;
                            case "21"://箱条码群读
                                sss.Remove(0, sss.Length);
                                for (int i = 1; i <= 116; i++)
                                {
                                    sss.Append(Convert.ToChar(AllReturns[temp + i]));

                                }

                                    CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "读PLC群读条码",deviceIdx.ToString(), "读标志1**条码："+sss.ToString().ToUpper());
                                    break;
                                    
                                
                            #endregion
                        }


                        return strdate;

                    }
                    else
                    {
                        return null;
                    }


                    #endregion

                    #region 原获取设备状态

                    //devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);

                    //if (devinfo.Dbw2Address != -1)
                    //{
                    //    //20110216
                    //    devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));
                    //    int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                    //    decimal glen = devinfo.Dbw2Getlength;

                    //    string headstr = AllReturns[temp].ToString();
                    //    string strdate = string.Empty;
                    //    if (headstr != "1") return null;

                    //    switch (devinfo.DeviceKind.ToString())
                    //    {

                    //        #region 字符串信息
                    //        case "7"://条形码
                    //            sss.Remove(0, sss.Length);
                    //            temp = 253;
                    //            for (int i = 1; i <= 6; i++)
                    //            {
                    //                sss.Append(Convert.ToChar(AllReturns[temp + i]));

                    //            }
                    //            strdate = sss.ToString().TrimEnd('/');
                    //            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "读PLC条码", deviceIdx.ToString(), "读标志1**条码：" + strdate);

                    //            break;
                    //        case "21"://箱条码群读
                    //            sss.Remove(0, sss.Length);
                    //            for (int i = 1; i <= 116; i++)
                    //            {
                    //                sss.Append(Convert.ToChar(AllReturns[temp + i]));

                    //            }

                    //            CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "读PLC群读条码", deviceIdx.ToString(), "读标志1**条码：" + sss.ToString().ToUpper());
                    //            break;


                    //            #endregion
                    //    }


                    //    return strdate;

                    //}
                    //else
                    //{
                    //    return null;
                    //}


                    #endregion

                }
                else
                {
                    return null;
                }
               
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("CStaticClass取得设备字符串信息时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "CStaticClass取得设备字符串信息时：" + ex.Message, true);
                }
                return null;
            }
        }
        
        /// <summary> 
        /// 比较两个值型一维数组变量是否值相等 
        /// </summary> 
        /// <param name="array1">值型一维数组1</param> 
        /// <param name="array2">值型一维数组2</param> 
        /// <returns>比较结果，相等则true，否则false</returns> 
        public static bool IsEquals(Array array1, Array array2,int arraylength)
        {//20090902新增加arraylength
            //比较类型是否一样 
            if ((array1 == null) || (array2 == null)) return false;
            if (!Object.ReferenceEquals(array1.GetType(), array2.GetType()))
            {
                return false;
            }

            //比较长度是否一样 
            if (array1.GetLength(0) != array2.GetLength(0))
            {
                return false;
            }

            //比较成员是否对应相等 
            ValueType v1, v2;
            for (int i = 0; i < arraylength; i++)
            {
                v1 = (ValueType)array1.GetValue(i);
                v2 = (ValueType)array2.GetValue(i);

                if (!v1.Equals(v2))
                {
                    return false;
                }
            }
            return true;
        }

        private static void BeginListenAllReturns()
        {
            while (!exitThread)
            {
                try
                {
                    GetAllReturns();

                }
                catch (Exception ex)
                {
                    //
                }
                Thread.Sleep(600);
            }
        }

        public static void StartListenReturn()
        {
           
            //exitThread = false;
            //mythread = new Thread(new ThreadStart(BeginListenAllReturns));
            //mythread.IsBackground = true;
            //mythread.Start();

        }

        public static void EndListenReturn()
        {
            //exitThread = true;

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

            //    mythread.Abort();
            //    mythread = null;
            //}

        }

        private static Thread mythread;
        private static bool exitThread = false;

        public static int GetDeviceRunState(int deviceIdx)
        {
            int[] status = GetDeviceState(deviceIdx);
            if (status == null)
            {
                return -1;
            }
            else
            {
                return status[1];
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="deviceIdx">叠盘完成信号</param>
        /// <param name="recordedbarcode">叠盘机记录的条码</param>
        /// <returns></returns>
        public static int GetOverlapStatus(int deviceIdx)
        {
          
            try
            {
               
                if (devinfo28.DeviceKind == 28)
                {
                    if (CStaticClass.MutiS7ConnReturns.Count > 0)
                    {
                        AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                    }
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 叠盘完成信号

                       
                        devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);
                        devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));

                        int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                        int flag = CStaticClass.AllReturns[temp];//叠盘完成标志
                        int boxnumber = CStaticClass.AllReturns[temp + 1];//叠盘数量
                        if (flag !=1)
                        {
                            return flag;
                        }
                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "读叠盘完成", deviceIdx.ToString(), "读标志1**叠盘数量：" + boxnumber);
                        return flag;
                        #endregion


                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得叠盘完成信号时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得叠盘完成信号时：" + ex.Message, true);
                }
                return 0;
            }
        }


        /// <summary>
        /// 码垛完成信号
        /// </summary>
        /// <param name="deviceIdx"></param>
        /// <returns></returns>
        public static int GetRobotStatus(int deviceIdx ,out int boxsum)
        {
            boxsum = 0;
            
            try
            {

                if (devinfo28.DeviceKind == 28)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 叠盘完成信号


                        devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);
                        devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));

                        int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                        int flag = CStaticClass.AllReturns[temp];//码垛完成
                        boxsum = CStaticClass.AllReturns[temp + 1];//数量
                        if (flag != 1)
                        {
                            return flag;
                        }

                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码垛完成", deviceIdx.ToString(), "读标志1**箱数" + boxsum);

                        return flag;
                        #endregion


                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得码垛完成信号时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得码垛完成信号时：" + ex.Message, true);
                }
                return 0;
            }
        }

        /// <summary>
        /// 码箱完成信号
        /// </summary>
        /// <returns></returns>
        public static int GetPackBoxBarcodes(int deviceIdx, out  string packbarcodes)
        {
            packbarcodes = string.Empty;

            try
            {

                if (devinfo28.DeviceKind == 28)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 码箱完成信号


                        devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);
                        devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));

                        int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                        int flag = CStaticClass.AllReturns[temp];//码箱完成信号
                        if (flag != 1)
                        {
                            return flag;
                        }
                        int sum = CStaticClass.AllReturns[temp + 1];//数量

                        int sumlenght =Convert .ToInt32( devinfo.Dbw2Getlength);
                     
                        int boxlenght = CStaticClass.AllReturns[temp + 2];//箱长度
                        if (sum == 1)
                        {
                            sumlenght = 25;
                        }
                        else if (sum == 2)
                        {
                           // sumlenght = 47;
                        }
                      
                        sss.Remove(0, sss.ToString().Length);
                        StringBuilder sb = new StringBuilder();

                        for (int i = 3; i < sumlenght; i++)
                        {
                            //if ((i > 16 && i < 25) || (i > 38 && i < 47))
                            //{
                            //    sss.Append("0");

                            //}
                            //else
                            //{
                                sss.Append(Convert.ToChar(AllReturns[temp + i]));
                            //}

                            if (sss.Length == 22)
                            {
                                //if (sss.ToString().TrimEnd('0') != string.Empty)
                                //{
                                    sb.Append(sss.ToString()).Append("|");
                                //}
                                sss.Remove(0, sss.Length);
                            }
                        }
                        packbarcodes = sb.ToString().TrimEnd('|');

                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "码箱完成", deviceIdx.ToString(), "读标志1**箱数" + sum + "**条码长度" + boxlenght + "**条码值" + packbarcodes);

                        return flag;
                        #endregion

                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得码箱完成信号时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得码箱完成信号时：" + ex.Message, true);
                }
                return 0;
            }
        }


        /// <summary>
        /// 拆跺完成
        /// </summary>
        /// <param name="deviceIdx"></param>
        /// <returns></returns>
        public static int GetRobotUnpack(int deviceIdx)
        {
          
            try
            {

                if (devinfo28.DeviceKind == 28)
                {
                    AllReturns = CStaticClass.MutiS7ConnReturns[GetDeviceS7Connection(deviceIdx)];
                    if (CStaticClass.AllReturns != null)
                    {
                        #region 拆跺完成信号


                        devinfo = Model.CGetInfo.GetDeviceInfo(deviceIdx);
                        devinfo28 = Model.CGeneralFunction.GetDevice28AllDB1Data(new StringBuilder(devinfo.S7Connection));

                        int temp = devinfo.Dbw2Address - devinfo28.Dbw2Address;
                        int flag = CStaticClass.AllReturns[temp];//拆垛完成
                       
                        if (flag != 1)
                        {
                            return flag;
                        }

                        CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "拆垛完成", deviceIdx.ToString(), "读标志1");

                        return flag;
                        #endregion


                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                if (FrmControlMonitor.FormInstance.GetObjectText("tsStatus").IndexOf("取得码垛完成信号时：" + ex.Message) < 0)
                {

                    FrmControlMonitor.FormInstance.FlashPanit("tsStatus", "取得码垛完成信号时：" + ex.Message, true);
                }
                return 0;
            }
        }
        public static bool SetInLightOnOff()
        {
            DataView dv, dv1;
            string sql = string.Empty;
            int askkind = 44;
            int reader = 16004;
            char[] dd = new char[1] { ';' };//20101124
            string[] DS;//20101124
            try
            {
                sql = string.Format("select F_DeviceIndex  from T_Base_PLC_Ask  WHERE F_Askkind = {0} and F_DeviceIndex={1}", askkind, reader);
                dv = dbo.ExceSQL(sql).Tables[0].DefaultView;
                if (dv.Count > 0)
                {

                        int devidx =12605;//灯设备
                        int taskend = 12604;//判读出库执行任务的终点，判读任何站台移库任务的终点
                        string checklight = "12605.2";//灯状态存放区

                        string checkdevice = "12604";//输送机状态

                        int curlightstatus = GetDevicePhotoelectric(checklight);//灯现在状态
                        int setlightstatus;
                        int sendorder;

                        sql = string.Format("select FID from T_Manage_Task where  FENDDEVICE ={0} and  FCONTROLTASKTYPE=2 and FSTATUS>0 ", taskend);

                        dv1 = dbo.ExceSQL(sql).Tables[0].DefaultView;

                        if (dv1.Count > 0)
                        {
                            //灯灭
                            setlightstatus = 0;
                            sendorder = 8;

                        }
                        else
                        {
                           //灯亮
                            //只判断是否有出库任务，在亮绿灯的情况下，入库按钮才会生效
                            setlightstatus = 1;
                            sendorder = 7;
                            
                            //DS = checkdevice.Trim().Split(dd);
                            //string item;
                            //int value = 0;
                            //for (int k = 0; k < DS.Length; k++)
                            //{
                            //    item = DS[k];

                            //    int deviceindex = Convert.ToInt32(item);
                            //    devinfo = Model.CGetInfo.GetDeviceInfo(deviceindex);
                            //    if (devinfo != null)
                            //    {
                            //        if (devinfo.SplitByte_0 == 1 || devinfo.SplitByte_1 == 1 || devinfo.RunState == 1)
                            //        {
                            //            value++;
                            //        }
                            //    }


                            //}
                            //if (value > 0)
                            //{
                            //    //灯灭
                            //    setlightstatus = 0;
                            //    sendorder = 8;

                            //}
                            //else
                            //{
                            //    //灯亮
                            //    setlightstatus = 1;
                            //    sendorder = 7;
                            //}
                        }
                        if (curlightstatus!=-1 && setlightstatus != curlightstatus )
                        {


                            sdo = CommModeCreate.CreateSendDeviceOrder(devidx);


                            sdo.SendDeviceOrder(1, 30001, sendorder, devidx, 0);

                        }







                }

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //dv.Dispose();
            }
        }

    }
}
