using Microsoft.VisualBasic;
using RGD.Common;
using RGD.DataService;
using RGD.DBUtility;
using System;
using System.Data;

namespace RGD.OPCClient
{
    public class CSendDeviceOrder : ISendDeviceOrder
    {
        private string _commLayerError;

        public string CommLayerError
        {
            get { return _commLayerError; }
            set { _commLayerError = value; }
        }

        private Model.MDevice devinfo;

        public CSendDeviceOrder()
        {
        }

        /// <summary>
        /// 带双叉的堆垛机通讯格式
        /// </summary>
        /// <param name="MessageIndex">指令头</param>
        /// <param name="TaskIndex">设备指令索引</param>
        /// <param name="Order">指令索引</param>
        /// <param name="DeviceIndex">设备索引</param>
        /// <param name="StartX">起点X列</param>
        /// <param name="StartY">起点Y层</param>
        /// <param name="StartZ">起点Z排</param>
        /// <param name="EndX">终点X列</param>
        /// <param name="EndY">终点Y层</param>
        /// <param name="EndZ">终点Z排</param>
        /// <param name="DoubleFork">双叉货位编码</param>
        /// <returns></returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex, int StartX, int StartY, int StartZ, int EndX, int EndY, int EndZ, string DoubleFork)
        {
            return true;
        }

        /// <summary>
        /// 发送堆垛机命令
        /// </summary>
        /// <param name="MessageIndex">消息编号</param>
        /// <param name="TaskIndex">任务编号</param>
        /// <param name="Order">堆垛机命令字</param>
        ///1-复位
        ///2-将取
        ///3-将送
        ///4-取货
        ///5-放货
        ///6-取放货
        /// <param name="DeviceIndex">设备编号</param>
        /// <param name="StartX">起始x坐标，排-沿轨道方向</param>
        /// <param name="StartY">起始y坐标，层-高度方向</param>
        /// <param name="StartZ">起始z坐标，列-面向堆垛机操作面板，1-左侧，2-右侧</param>
        /// <param name="EndX">目标x坐标，列-沿轨道方向</param>
        /// <param name="EndY">目标y坐标，层-高度方向</param>
        /// <param name="EndZ">目标z坐标，排-面向堆垛机操作面板，1-左侧，2-右侧</param>
        /// <returns>发送堆垛机命令是否成功</returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex, int StartX, int StartY, int StartZ, int EndX, int EndY, int EndZ)
        {
            string[] itemnames;
            string[] itemvalues;

            //if (MessageIndex == 2)//20101220
            //{
            //    Order = 100;
            //}
            try
            {
                int StartZ1 = 0; int EndZ1 = 0;
                int sn = 0;//int UseAwayFork=0;int UseAwayFork1=0;//dzf
                DataView dv = DbHelperSQL.Query("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (dv.Count == 0)
                {
                    _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：在设备表中没找到设备所引！";
                    return false;
                }
                else
                {
                    if ((dv[0]["F_DeviceKindIndex"].ToString() != "1"))
                    {//堆垛机使用此方法
                        _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：堆垛机以外的设备使用此方法不正确!";
                        return false;
                    }

                    #region 堆垛机

                    if (dv[0]["F_DeviceKindIndex"].ToString() == "1")
                    {
                        devinfo = BaseDeviceService.GetDeviceInfo(DeviceIndex);

                        #region 双叉时候

                        //if (devinfo.IfCorrelDoubleFork == "1")
                        //{
                        //    //堆垛机的双叉取货指令，在此决定分配货叉、同步还是异步发送20100323
                        //    if ((Order == 4) || (Order == 2))
                        //    {
                        //        #region 分配货叉
                        //             //20110707
                        //       int managetaskindex;
                        //       int  taskkindindex;
                        //            //如果不是双叉关联任务：ST_CELL的FDoubleFork=0，则奇数列使用近货叉，偶数列使用远货叉；否则货叉按照ST_CELL的FDoubleFork的值
                        //            string[] rr = Model.CGeneralFunction.GetDoubleForkMonitorInfo(TaskIndex, DeviceIndex);
                        //            if (rr == null)
                        //            {
                        //                //如果F_UseAwayFork='-',分配货叉，否则已经分配好货叉无需再分配
                        //                if (Model.CGeneralFunction.GetUseAwayFork(TaskIndex) == "-")
                        //                {
                        //                    switch (Model.CGeneralFunction.GetDoubleForkFromST_CELL(StartZ, StartX, StartY, Model.CGeneralFunction.GetWAREHOUSEFromSTCELL(DeviceIndex)))
                        //                    {
                        //                        case 1:
                        //                            UseAwayFork = 0;
                        //                            break;
                        //                        case 2:
                        //                            UseAwayFork = 1;
                        //                            break;
                        //                        case 0:
                        //                            if ((StartX % 2) == 0)
                        //                            {
                        //                                UseAwayFork = 1;
                        //                            }
                        //                            else
                        //                            {
                        //                                UseAwayFork = 0;
                        //                            }
                        //                            break;

                        //                    }
                        //                    managetaskindex = Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex);
                        //                    taskkindindex = Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex);

                        //                    dbo.ExceSQL("UPDATE T_Monitor_Task SET F_UseAwayFork = '" + UseAwayFork + "' WHERE (F_ManageTaskIndex = " +
                        //                        managetaskindex + ") AND (F_ManageTASKKINDINDEX = " +
                        //                        taskkindindex + ")");//20101220
                        //                    dbo.ExceSQL("update T_Manage_Task set FUseAwayFork= '" + UseAwayFork + "' where FID = " + managetaskindex + " and F_ManageTASKKINDINDEX= " + taskkindindex + "");
                        //                }
                        //                else
                        //                {
                        //                    UseAwayFork = Convert.ToInt32(Model.CGeneralFunction.GetUseAwayFork(TaskIndex));
                        //                }
                        //                if (UseAwayFork == 1)//远货叉列数减一，因为近货叉是主货叉
                        //                {
                        //                    if (StartX != 1)
                        //                    {
                        //                        StartX = StartX - 1;
                        //                    }
                        //                }

                        //            }
                        //            else
                        //            {
                        //                if (Model.CGeneralFunction.GetUseAwayFork(TaskIndex) == "-")
                        //                {
                        //                    //如果是双叉关联任务：ST_CELL的FDoubleFork=0，根据两个任务的列数大小来分配货叉
                        //                    UseAwayFork = Model.CGeneralFunction.GetUseAwayFork(TaskIndex, DeviceIndex, Order);

                        //                    managetaskindex = Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex);
                        //                    taskkindindex = Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex);
                        //                    dbo.ExceSQL("UPDATE T_Monitor_Task SET F_UseAwayFork = '" + UseAwayFork + "' WHERE (F_ManageTaskIndex = " +
                        //                        managetaskindex + ") AND (F_ManageTASKKINDINDEX = " +
                        //                        taskkindindex + ")");//20101220
                        //                    dbo.ExceSQL("update T_Manage_Task set FUseAwayFork= '" + UseAwayFork + "' where FID = " + managetaskindex + " and F_ManageTASKKINDINDEX= " + taskkindindex + "");

                        //                }
                        //                else
                        //                {
                        //                    UseAwayFork =Convert.ToInt32( Model.CGeneralFunction.GetUseAwayFork(TaskIndex));
                        //                }
                        //                    //关联任务分配货叉
                        //                if (UseAwayFork == 1)//远货叉列数减一，因为近货叉是主货叉
                        //                {
                        //                    UseAwayFork1 = 0;
                        //                    if (StartX != 1)
                        //                    {
                        //                        StartX = StartX - 1;
                        //                    }
                        //                }
                        //                else
                        //                {
                        //                    UseAwayFork1 = 1;

                        //                }
                        //                int TaskIndex1 = Convert.ToInt32(rr[0]);
                        //                managetaskindex = Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex1);
                        //                taskkindindex = Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex1);

                        //                dbo.ExceSQL("UPDATE T_Monitor_Task SET F_UseAwayFork = '" + UseAwayFork1 + "' WHERE (F_ManageTaskIndex = " +
                        //                    managetaskindex + ") AND (F_ManageTASKKINDINDEX = " +
                        //                    taskkindindex + ")");//20101220
                        //                dbo.ExceSQL("update T_Manage_Task set FUseAwayFork= '" + UseAwayFork1 + "' where FID = " + managetaskindex + " and F_ManageTASKKINDINDEX= " + taskkindindex + "");

                        //            }

                        //        #endregion

                        //        #region 同步还是异步发送
                        //            if (Model.CGeneralFunction.DoubleForkIfSync(TaskIndex, DeviceIndex, devinfo.DeviceKind) == true)
                        //            {
                        //                if (UseAwayFork == 1)//远货叉
                        //                {
                        //                    StartZ = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order);//远货叉
                        //                    EndZ = 0;//远货叉
                        //                    StartZ1 = Model.CGeneralFunction.GetDoubleForkZ(Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex),
                        //                    Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex), DeviceIndex, Order);  //近货叉
                        //                    EndZ1 = 0; //近货叉
                        //                }
                        //                else
                        //                {                   //近货叉
                        //                    StartZ1 = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order); //近货叉
                        //                    EndZ1 = 0; //近货叉
                        //                    StartZ = Model.CGeneralFunction.GetDoubleForkZ(Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex),
                        //                    Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex), DeviceIndex, Order);//远货叉
                        //                    EndZ = 0;//远货叉
                        //                }

                        //            }
                        //            else
                        //            {
                        //                if (UseAwayFork == 1)//远货叉
                        //                {
                        //                    StartZ = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex,DeviceIndex,Order);//远货叉
                        //                    EndZ = 0;//远货叉
                        //                    StartZ1 = 0; //近货叉
                        //                    EndZ1 = 0; //近货叉
                        //                }
                        //                else
                        //                {                   //近货叉
                        //                    StartZ1 = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order); //近货叉
                        //                    EndZ1 = 0; //近货叉
                        //                    StartZ =0;//远货叉
                        //                    EndZ = 0;//远货叉
                        //                }

                        //            }
                        //        #endregion

                        //    }
                        //    //堆垛机的双叉送货指令，在此决定同步还是异步发送20100323
                        //    if ((Order == 5) || (Order == 3))
                        //    {
                        //        UseAwayFork = Convert.ToInt32(Model.CGeneralFunction.GetUseAwayFork(TaskIndex));
                        //        #region 同步还是异步发送
                        //        if (Model.CGeneralFunction.DoubleForkIfSync(TaskIndex, DeviceIndex, devinfo.DeviceKind) == true)
                        //        {
                        //            if (UseAwayFork == 1)//远货叉
                        //            {
                        //                EndZ = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order);//远货叉
                        //                StartZ= 0;//远货叉
                        //                EndZ1 = Model.CGeneralFunction.GetDoubleForkZ(Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex),
                        //                Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex), DeviceIndex, Order);  //近货叉
                        //                StartZ1= 0; //近货叉
                        //            }
                        //            else
                        //            {                   //近货叉
                        //                EndZ1= Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order); //近货叉
                        //                StartZ1 = 0; //近货叉
                        //                EndZ = Model.CGeneralFunction.GetDoubleForkZ(Model.CGeneralFunction.GetManageTaskKindIndexFromMonitor(TaskIndex),
                        //                Model.CGeneralFunction.GetManageTaskIndexfromMonitor(TaskIndex), DeviceIndex, Order);//远货叉
                        //                StartZ = 0;//远货叉
                        //            }

                        //        }
                        //        else
                        //        {
                        //            if (UseAwayFork == 1)//远货叉
                        //            {
                        //                EndZ = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order);//远货叉
                        //                StartZ = 0;//远货叉
                        //                StartZ1 = 0; //近货叉
                        //                EndZ1 = 0; //近货叉
                        //            }
                        //            else
                        //            {                   //近货叉
                        //                EndZ1 = Model.CGeneralFunction.GetZCoorFromMonitor(TaskIndex, DeviceIndex, Order); //近货叉
                        //                StartZ1 = 0; //近货叉
                        //                StartZ = 0;//远货叉
                        //                EndZ = 0;//远货叉
                        //            }

                        //        }
                        //        #endregion
                        //        if (Model.CGeneralFunction.GetUseAwayFork(TaskIndex) == "1")//远货叉列数减一，因为近货叉是主货叉
                        //        {
                        //            if (EndX != 1)
                        //            {
                        //                EndX = EndX - 1;
                        //            }
                        //        }
                        //    }
                        //}

                        #endregion 双叉时候

                        itemnames = new string[9];//20101220
                        itemvalues = new string[9];

                        #region 管理任务的坐标在此转换为PLC能识别的坐标

                        #region 转换（Y）层坐标

                        ////01-29-23;01-30-23;01-24-23;01-23-23,[01-22-23,01-28-23]为三楼输送机保持不变，1排的其余列的货位层数+1；2排23层都加+1
                        //if ((((StartZ == 1) || (StartZ1 == 1)) && (StartY == 23) && ((StartX != 23) && (StartX != 22) && (StartX != 24) && (StartX != 28) && (StartX != 29) && (StartX != 30)))
                        //    || (((StartZ == 2) || (StartZ1 == 2)) && (StartY == 23)))
                        //{
                        //    StartY++;
                        //}

                        //if ((((EndZ == 1) || (EndZ1 == 1)) && (EndY == 23) && ((EndX != 23) && (EndX != 22) && (EndX != 24) && (EndX != 28) && (EndX != 29) && (EndX != 30)))
                        //    || (((EndZ == 2) || (EndZ1 == 2)) && (EndY == 23)))
                        //{
                        //    EndY++;
                        //}

                        #endregion 转换（Y）层坐标

                        #region 转换（Z）排坐标

                        if (StartZ != 0)
                        {
                            if (StartZ % 2 == 0)
                            {
                                StartZ = 2;
                            }
                            else
                            {
                                StartZ = 1;
                            }
                        }
                        if (EndZ != 0)
                        {
                            if (EndZ % 2 == 0)
                            {
                                EndZ = 2;
                            }
                            else
                            {
                                EndZ = 1;
                            }
                        }
                        ////////////////
                        if (StartZ1 != 0)
                        {
                            if (StartZ1 % 2 == 0)
                            {
                                StartZ1 = 2;
                            }
                            else
                            {
                                StartZ1 = 1;
                            }
                        }
                        if (EndZ1 != 0)
                        {
                            if (EndZ1 % 2 == 0)
                            {
                                EndZ1 = 2;
                            }
                            else
                            {
                                EndZ1 = 1;
                            }
                        }

                        #endregion 转换（Z）排坐标

                        #endregion 管理任务的坐标在此转换为PLC能识别的坐标

                        sn = Convert.ToInt32(dv[0]["F_DBW1Address"]);
                        itemnames[0] = "DB1,byte" + Convert.ToString(sn + 0);//消息头
                        itemvalues[0] = "0";
                        itemnames[1] = "DB1,byte" + Convert.ToString(sn + 1);//命令
                        itemvalues[1] = Order.ToString();

                        itemnames[2] = "DB1,int" + Convert.ToString(sn + 2);//任务号
                        itemvalues[2] = TaskIndex.ToString();

                        itemnames[3] = "DB1,byte" + Convert.ToString(sn + 4);
                        itemvalues[3] = StartX.ToString();

                        itemnames[4] = "DB1,byte" + Convert.ToString(sn + 5);
                        itemvalues[4] = StartY.ToString();

                        //itemnames[5] = "DB1,byte" + Convert.ToString(sn + 6);
                        //itemvalues[5] = StartZ1.ToString();//近货叉

                        itemnames[5] = "DB1,byte" + Convert.ToString(sn + 6);
                        itemvalues[5] = StartZ.ToString();

                        itemnames[6] = "DB1,byte" + Convert.ToString(sn + 7);
                        itemvalues[6] = EndX.ToString();

                        itemnames[7] = "DB1,byte" + Convert.ToString(sn + 8);
                        itemvalues[7] = EndY.ToString();

                        //itemnames[9] = "DB1,byte" + Convert.ToString(sn + 10);
                        //itemvalues[9] = EndZ1.ToString();//近货叉

                        itemnames[8] = "DB1,byte" + Convert.ToString(sn + 9);
                        itemvalues[8] = EndZ.ToString();//远货叉
                        CCommonOPCClient.Hostname = AppSettings.GetValue("HostName");//20090922 devinfo.RemoteIP;
                        CCommonOPCClient.ProgID = AppSettings.GetValue("OPCProgID");
                        if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                        {
                            return false;
                        }
                        itemnames[0] = "DB1,byte" + Convert.ToString(sn + 0);//消息头
                        itemvalues[0] = MessageIndex.ToString();

                        if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                        {
                            return false;
                        }
                        string sss = "";
                        for (int j = 0; j <= 8; j++)
                        {
                            sss += "**" + itemvalues[j];
                        }
                        CCarryConvert.WriteDarkCasket("OPCClient", "SendDeviceOrder", DeviceIndex.ToString(), sss);
                        if (WriteBarcode(DeviceIndex, TaskIndex) == false)
                        {
                            return false;
                        }
                    }

                    #endregion 堆垛机
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
            finally
            {
                itemnames = null;

                itemvalues = null;
            }
        }

        /// <summary>
        /// 发送穿梭车、输送机设备命令
        /// </summary>
        /// <param name="MessageIndex">消息编号</param>
        /// <param name="TaskIndex">任务编号</param>
        /// <param name="Order">命令字</param>
        /// 穿梭车命令字：
        ///1-复位
        ///2-左接货
        ///3-左送货
        ///4-右接货
        ///5-右送货
        ///6-停止
        ///7-运动（运动到第4、5字节指定的目标设备所引）
        ///输送机命令字：
        ///1-入库（朝向库）
        ///2-出库（背向库）
        ///3-送货
        ///4-接货
        ///5-停止
        /// <param name="DeviceIndex">设备编号</param>
        ///<param name="ArrowDeviceIndex">对于输送机、穿梭车代表目标设备所引，
        /// 0-代表单一设备控制，无目标设备所引；1…65535代表目标设备所引（终点输送机的设备所引）</param>
        /// <returns>发送穿梭车、输送机设备命令是否成功</returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex, int ArrowDeviceIndex)
        {
            Model.MDevice askdev;
            string[] itemnames;
            string[] itemvalues;
            //if (MessageIndex == 2) Order = 100;//20101220
            try
            {
                //20101220
                int neartaskno = 0, fartaskno = 0, outtimes = 0; //UseAwayFork = 0;  //dzf//近叉对应任务号，远叉对应任务号
                int sn = 0;
                //int floor = 0;//20110318 表箱层数dzf
                DataView dv = DbHelperSQL.Query("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (dv.Count == 0)
                {
                    _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：设备索引不存在!";
                    return false;
                }
                else
                {
                    askdev = BaseDeviceService.GetDeviceInfo(DeviceIndex);

                    itemnames = new string[4];
                    itemvalues = new string[4];
                    outtimes = 3;

                    if (dv[0]["F_DeviceKindIndex"].ToString() == "7")
                    {
                        return true;
                    }
                    if ((dv[0]["F_DeviceKindIndex"].ToString() == "1"))
                    {//堆垛机不允许使用此方法
                        _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：堆垛机不允许使用此方法!";
                        return false;
                    }
                    sn = Convert.ToInt32(dv[0]["F_DBW1Address"]);
                    itemnames[0] = "DB1,byte" + Convert.ToString(sn + 1);
                    itemvalues[0] = Order.ToString();

                    if (askdev.IfCorrelDoubleFork == "1")//20101220
                    {
                        itemnames[1] = "DB1,int" + Convert.ToString(sn + 2);
                        itemvalues[1] = neartaskno.ToString();
                        itemnames[2] = "DB1,int" + Convert.ToString(sn + 4);
                        itemvalues[2] = fartaskno.ToString();
                        itemnames[3] = "DB1,byte" + Convert.ToString(sn + 0);
                        itemvalues[3] = "0";
                        itemnames[4] = "DB1,int" + Convert.ToString(sn + 6);
                        itemvalues[4] = ArrowDeviceIndex.ToString();
                    }
                    else
                    {
                        itemnames[1] = "DB1,int" + Convert.ToString(sn + 2);
                        itemvalues[1] = TaskIndex.ToString();
                        itemnames[2] = "DB1,int" + Convert.ToString(sn + 4);
                        itemvalues[2] = ArrowDeviceIndex.ToString();
                        itemnames[3] = "DB1,byte" + Convert.ToString(sn + 0);
                        itemvalues[3] = "0";
                        if (askdev.UseCommonDB == "1")
                        {
                            itemnames[4] = "DB1,int" + Convert.ToString(sn + 6);
                            itemvalues[4] = DeviceIndex.ToString();
                        }
                    }
                    CCommonOPCClient.Hostname = AppSettings.GetValue("HostName");//20090922 devinfo.RemoteIP;
                    CCommonOPCClient.ProgID = AppSettings.GetValue("OPCProgID");
                    if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                    {
                        return false;
                    }
                    itemnames[3] = "DB1,byte" + Convert.ToString(sn + 0);
                    itemvalues[3] = MessageIndex.ToString();
                    if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                    {
                        return false;
                    }

                    string sss = "";
                    for (int j = 0; j <= outtimes; j++)
                    {
                        sss += "**" + itemvalues[j];
                    }
                    CCarryConvert.WriteDarkCasket("OPCClient", "SendDeviceOrder", DeviceIndex.ToString(), sss);
                    if (MessageIndex == 1)
                    {
                        if (WriteBarcode(DeviceIndex, TaskIndex) == false)
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
            finally
            {
                askdev = null;
                itemnames = null;
                itemvalues = null;
            }
        }

        /// <summary>
        /// 发送拣选设备命令
        /// </summary>
        /// <param name="MessageIndex">消息编号</param>
        /// <param name="TaskIndex">任务编号</param>
        /// <param name="Order">命令字</param>
        /// <param name="DeviceIndex">设备编号</param>
        ///<param name="GoodsLocation">十进制:抓1/9表，发送257(100000001)</param>
        /// <returns>发送命令是否成功</returns>
        public bool SendDeviceOrder(int MessageIndex, int TaskIndex, int Order, int DeviceIndex, string GoodsLocation)
        {
            Model.MDevice askdev;
            string[] itemnames;
            string[] itemvalues;
            //if (MessageIndex == 2) Order = 100;//20101220
            try
            {
                //20101220
                int outtimes = 0;
                int sn = 0;
                DataView dv = DbHelperSQL.Query("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (dv.Count == 0)
                {
                    _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：设备索引不存在!";
                    return false;
                }
                else
                {
                    askdev = BaseDeviceService.GetDeviceInfo(DeviceIndex);

                    itemnames = new string[4];
                    itemvalues = new string[4];
                    outtimes = 3;

                    if (dv[0]["F_DeviceKindIndex"].ToString() == "7")
                    {
                        return true;
                    }
                    if ((dv[0]["F_DeviceKindIndex"].ToString() == "1"))
                    {//堆垛机不允许使用此方法
                        _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：堆垛机不允许使用此方法!";
                        return false;
                    }
                    sn = Convert.ToInt32(dv[0]["F_DBW1Address"]);
                    itemnames[0] = "DB1,byte" + Convert.ToString(sn + 1);
                    itemvalues[0] = Order.ToString();

                    itemnames[1] = "DB1,int" + Convert.ToString(sn + 2);
                    itemvalues[1] = TaskIndex.ToString();
                    itemnames[2] = "DB1,int" + Convert.ToString(sn + 4);
                    itemvalues[2] = GoodsLocation;
                    itemnames[3] = "DB1,byte" + Convert.ToString(sn + 0);
                    itemvalues[3] = "0";

                    CCommonOPCClient.Hostname = AppSettings.GetValue("HostName");//20090922 devinfo.RemoteIP;
                    CCommonOPCClient.ProgID = AppSettings.GetValue("OPCProgID");
                    if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                    {
                        return false;
                    }
                    itemnames[3] = "DB1,byte" + Convert.ToString(sn + 0);
                    itemvalues[3] = MessageIndex.ToString();
                    if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                    {
                        return false;
                    }

                    string sss = "";
                    for (int j = 0; j <= outtimes; j++)
                    {
                        sss += "**" + itemvalues[j];
                    }
                    CCarryConvert.WriteDarkCasket("OPCClient", "SendDeviceOrder", DeviceIndex.ToString(), sss);
                    if (MessageIndex == 1)
                    {
                        if (WriteBarcode(DeviceIndex, TaskIndex) == false)
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
            finally
            {
                askdev = null;
                itemnames = null;
                itemvalues = null;
            }
        }

        /// <summary>
        /// 上位机给下位机发送烟箱按品牌码分道信息共15字节,有数据时写入实际数据，否则全部写零
        /// </summary>
        /// <param name="DeviceIndex">码垛位设备号索引</param>
        /// <param name="TobaccoCode">第3--15字节,烟箱码</param>
        /// <param name="HaveFirstProjectCode">第1字节,1-有一号工程码,0-无一号工程码</param>
        /// <param name="IfSmallTobacco">第2字节,1-异型烟箱,0-正常烟箱</param>
        /// <returns>发送烟箱按品牌码分道信息是否成功</returns>
        public bool SendDeviceOrder(int DeviceIndex, string TobaccoCode, bool HaveFirstProjectCode, bool IfSmallTobacco, int Count)
        {
            string[] itemnames = new string[16];
            string[] itemvalues = new string[16];
            try
            {
                int sn = 0;
                DataView dv = DbHelperSQL.Query("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + DeviceIndex).Tables[0].DefaultView;
                if (dv.Count == 0)
                {
                    _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：设备所引不存在!";
                    return false;
                }
                else
                {
                    sn = Convert.ToInt32(dv[0]["F_DBW1Address"]);

                    itemnames[0] = "DB1,byte" + (sn + 0).ToString();
                    if (HaveFirstProjectCode == true)
                    {
                        itemvalues[0] = "1";
                    }
                    else
                    {
                        itemvalues[0] = "0";
                    }
                    itemnames[1] = "DB1,byte" + (sn + 1).ToString();
                    if (IfSmallTobacco == true)
                    {
                        itemvalues[1] = "1";
                    }
                    else
                    {
                        itemvalues[1] = "0";
                    }
                    for (int i = 2; i <= 14; i++)
                    {
                        itemnames[i] = "DB1,byte" + (sn + i).ToString();
                        itemvalues[i] = Strings.Asc(TobaccoCode.Substring(i - 2, 1)).ToString();
                    }
                    itemnames[15] = "DB1,byte" + (sn + 15).ToString();
                    itemvalues[15] = Count.ToString();

                    CCommonOPCClient.Hostname = AppSettings.GetValue("HostName");//20090922 devinfo.RemoteIP;
                    CCommonOPCClient.ProgID = AppSettings.GetValue("OPCProgID");
                    if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：" + ex.Message;
                return false;
            }
            finally
            {
                itemnames = null;
                itemvalues = null;
            }
        }

        public bool WriteBarcode(int deviceindex, int taskindex)
        {
            Model.MDevice devinfo;
            string[] itemnames = new string[11];
            string[] itemvalues = new string[11];
            string barcode = "";
            int sn = 0;
            try
            {
                DataView dvb = DbHelperSQL.Query("SELECT F_MonitorIndex, F_TxtParam FROM T_Monitor_Task WHERE (F_MonitorIndex = " + taskindex + ")").Tables[0].DefaultView;
                if (dvb.Count > 0)
                {
                    barcode = dvb[0]["F_TxtParam"].ToString();
                    if ((barcode == "-") || (barcode == "")) return true;
                }
                else
                {
                    _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：写入附加条码时在调度任务表内没找到条码!";
                    return false;
                }
                devinfo = BaseDeviceService.GetDeviceInfo(deviceindex);
                if (devinfo.AppendBarcode > 0)
                {
                    Model.MDevice devinfo1 = BaseDeviceService.GetDeviceInfo(devinfo.AppendBarcode);
                    //DataView dv = dbo.ExceSQL("SELECT F_DBW1Address,F_DBWSendLength,F_DeviceIndex,F_DeviceKindIndex,F_OPCProgID, F_RemoteIP FROM T_Base_Device where F_DeviceIndex=" + Convert.ToInt32(dv0[0]["F_AppendBarcode"])).Tables[0].DefaultView;
                    if (devinfo1.DeviceIndex == 0)
                    {
                        _commLayerError = "OPCClient.CSendDeviceOrder.SendDeviceOrder发生错误：写入附加条码时设备索引不存在!";
                        return false;
                    }
                    else
                    {
                        //byte0,byte1,byte2,byte3,byte4
                        //      int1         int3
                        //int0(byte0,byte1);int1(byte1,byte2);int2(byte2,byte3);int3(byte3,byte4)
                        sn = Convert.ToInt32(devinfo1.Dbw1Address);

                        for (int i = 0; i <= 9; i++)
                        {
                            itemnames[i] = "DB1,byte" + Convert.ToString(sn + i + 1);
                            itemvalues[i] = Strings.Asc(barcode.Substring((i), 1)).ToString();
                        }
                        itemnames[10] = "DB1,byte" + Convert.ToString(sn + 0);
                        itemvalues[10] = "1";
                        CCommonOPCClient.Hostname = AppSettings.GetValue("HostName");//20090922 devinfo.RemoteIP;
                        CCommonOPCClient.ProgID = AppSettings.GetValue("OPCProgID");
                        if (CCommonOPCClient.SyncWriteAllItemValue(itemnames, itemvalues) == false)
                        {
                            return false;
                        }

                        CCarryConvert.WriteDarkCasket("OPCClient", "SendDeviceOrder", deviceindex.ToString(), barcode);
                    }
                    return true;
                }
                else
                {
                    return true; ;
                }
            }
            catch (Exception ex)
            {
                _commLayerError = "OPCClient.CSendDeviceOrder.WriteBarcode发生错误：" + ex.Message;
                return false;
            }
            finally
            {
                devinfo = null;
                itemnames = null;
                itemvalues = null;
                barcode = null;
            }
        }

        /// <summary>
        /// 向PLC的DB区写入数据
        /// </summary>
        /// <param name="ItemNames">标签变量名称数组</param>
        /// <param name="ItemValues">标签值数组</param>
        /// <returns></returns>
        public bool WriteDBData(string[] ItemNames, string[] ItemValues)
        {
            try
            {
                if (CCommonOPCClient.SyncWriteAllItemValue(ItemNames, ItemValues) == false)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                _commLayerError = "OPCClient.CSendDeviceOrder.WriteDBData发生错误：" + ex.Message;
                return false;
            }
            finally
            {
                ItemNames = null;
                ItemValues = null;
            }
        }
    }
}