Ejemplo n.º 1
0
        public void Start()
        {
            EEP_Client_WS.EEP_Client_WS wsEEP_Client_WS = new EEP_Client_WS.EEP_Client_WS();
            DataTable dttIPPort = new DataTable(); //存放ModbusTCP之設備IP與Port
            DataTable dttACPara = new DataTable();//存放空調狀況讀取程式所需參數
            DataTable dttExist = null;
            DataRow[] dtwPointsDatafilter = null;
            DataSet dtsPointsVlue = null; //存放讀取設備的讀值
            DataEncryption.DataEncryption objDataEncryption = new DataEncryption.DataEncryption();
            //DataSet dtsEquipments = new DataSet("Equipments");
            //DataSet dtsPoints = new DataSet("Points");
            DataSet dtsPointsData = new DataSet("PointsData");
            int iCount = 0;////
            int retAffectedRows = 0;
            string sSQLCmd = "";
            string sSQLCmd2 = "";
            string sTableName = "";
            try
            {
                try
                {
                    //SqlConnection conn = new SqlConnection(sConnString);
                    //conn.Open();
                    //dtsEquipments.ReadXml(@gsEquipmentsFilePath);
                    //dtsPoints.ReadXml(@gsPointsFilePath);
                    sTableName = "ACStatusPara";
                    sSQLCmd = string.Format("SELECT * FROM {0} ", sTableName);
                    sSQLCmd2 = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sTableName);
                    DataTable dataTable2 = Utility.execDataTable(sSQLCmd2, sConnString);
                    if (dataTable2.Rows.Count > 0)
                    {
                        dttACPara = Utility.execDataTable(sSQLCmd, sConnString);
                    }

                    //SqlCommand cmd = new SqlCommand("Select * From  ACStatusPara", conn);

                    //dttACPara.Load(cmd.ExecuteReader());
                    //cmd.Dispose();
                    //conn.Close();
                    //conn.Dispose();

                    //dtsPointsData = wsEEP_Client_WS.Get_PointsData_ModbusTCP(g_sCompanyID, "", "");
                }
                catch (Exception ex)
                {
                    g_oLogger.ErrorException("讀取異常-- ", ex);
                }

                //if (dtsEquipments.Tables[0].Rows.Count == 0)
                if (dttACPara.Rows.Count == 0)
                {
                    g_oLogger.Info("---------------ModbusTCP之設備檔異常,請檢查(DB)檔案---------------");
                }
                //if (dtsEquipments.Tables[0].Rows.Count > 0)
                if (dttACPara.Rows.Count > 0)
                {
                    //dttIPPort = dtsEquipments.Tables[0].DefaultView.ToTable(true, new string[] { "IP", "Port" });
                    //dttIPPort = dttACPara.DefaultView.ToTable(true, new string[] { "IP", "Port" });
                    dttIPPort = dttACPara.DefaultView.ToTable(true, new string[] { "IP" });
                    foreach (DataRow dtwIPPort in dttIPPort.Rows)
                    {
                        DataTable dttPointsValue = new DataTable("ACRealTimeData");
                        dttPointsValue.Columns.Add("PointID", typeof(string));
                        dttPointsValue.Columns.Add("Status", typeof(string));
                        dttPointsValue.Columns.Add("RecTime", typeof(DateTime));
                        string sIP = dtwIPPort["IP"].ToString();
                        //string sPort = dtwIPPort["Port"].ToString();
                        string sPort = "502";
                        objSocketLink = new SocketLink.SocketLink();
                        gWorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        //104.2.4 ping不到設備就往下一個ip設備詢問
                        g_oLogger.Debug(sIP + "進行連線------------------------------------------------------");
                        if (ping.Send(sIP, 1000).Status != System.Net.NetworkInformation.IPStatus.Success)
                        {
                            g_oLogger.Debug(sIP + "的設備連線TimeOut-----------------------------------------");
                            continue;
                        }
                        objSocketLink.LinkEQP(0, sIP, sPort, gWorkSocket);
                        //dtwPointsDatafilter = dtsEquipments.Tables[0].Select("IP = '" + sIP + "' and Port = '" + sPort + "'"); //dtsEquipments.Tables[0].Select("IP = '" + sIP + "' and Port = '" + sPort + "'", "Address DESC");
                        dtwPointsDatafilter = dttACPara.Select("IP = '" + sIP + "'");
                        foreach (DataRow dtw in dtwPointsDatafilter)
                        {
                            try
                            {
                                if (gWorkSocket.Connected) //0:表連線,1:表斷線
                                {
                                    //string sCommand = string.Format("0,0,0,0,0,6,1,{0},{1},{2},0,{3}"
                                    //    , Convert.ToDouble(dtw["Function"])
                                    //    , Math.Floor(Convert.ToDouble(dtw["Address"]) / 256)
                                    //    , Convert.ToDouble(dtw["Address"]) % 256 - 1
                                    //    , dtw["DataLength"].ToString());
                                    string sCommand = string.Format("0,0,0,0,0,6,{0},3,0,3,0,1"
                                        , Convert.ToDouble(dtw["DeviceID"]));
                                    //,Convert.ToString(Convert.ToInt32(dtw["DeviceID"]),16));
                                    //104.1.19新增剛好整除問題,adress會出現負值
                                    //if (Convert.ToDouble(dtw["Address"]) % 256 == 0)
                                    //{
                                    //    sCommand = string.Format("0,0,0,0,0,6,1,{0},{1},{2},0,{3}"
                                    //        , Convert.ToDouble(dtw["Function"])
                                    //        , Math.Floor((Convert.ToDouble(dtw["Address"])-1) / 256)
                                    //        , (Convert.ToDouble(dtw["Address"])-1) % 256
                                    //        , dtw["DataLength"].ToString());
                                    //}

                                    g_oLogger.Trace(string.Format("Point:{0} ID:{1} ({2}-{3}) Command: {4}", dtw["PointID"].ToString(), dtw["DeviceID"].ToString(), sIP, sPort, sCommand));
                                    //byte[] byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, int.Parse(dtw["DataLength"].ToString()));
                                    byte[] byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                    if (byReceived == null)
                                        continue;

                                    iCount++;
                                    if (iCount % 100 == 0)
                                    {
                                        objSocketLink.LinkEQP(1, sIP, sPort, gWorkSocket);
                                        if (objSocketLink != null) { objSocketLink = null; }

                                        objSocketLink = new SocketLink.SocketLink();
                                        gWorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                        objSocketLink.LinkEQP(0, sIP, sPort, gWorkSocket);
                                    }

                                    //SolveValue(ref dttPointsValue, int.Parse(dtw["Address"].ToString()), byReceived, dtsPoints.Tables[0], sIP, int.Parse(sPort), g_sEquipmentType);
                                    //SolveValue(ref dttPointsValue, int.Parse(dtw["Address"].ToString()), byReceived, dtsPointsData.Tables[0], sIP, int.Parse(sPort), g_sEquipmentType, dtw["PointID"].ToString(), dtw["EquipmentID"].ToString());
                                    //新增dtw參數
                                    //SolveValue(ref dttPointsValue, int.Parse(dtw["Address"].ToString()), byReceived, dtsPointsData.Tables[0], sIP, int.Parse(sPort), g_sEquipmentType, dtw["PointID"].ToString(), dtw["EquipmentID"].ToString(),dtw);
                                    SolveValueAC(ref dttPointsValue, byReceived, dtw["PointID"].ToString());

                                    //for (int i = 0; i < dttPointsValue.Rows.Count; i++)
                                    //{
                                    //    gLogger.Trace(string.Format("{0}, {1}, {2}, {3}"
                                    //        , dttPointsValue.Rows[i][0].ToString()
                                    //        , dttPointsValue.Rows[i][1].ToString()
                                    //        , dttPointsValue.Rows[i][2].ToString()
                                    //        , ((DateTime)dttPointsValue.Rows[i][3]).ToString("yyyy-MM-dd HH:mm:ss.fff")));
                                    //}
                                }
                            }
                            catch (Exception ex)
                            {
                                g_oLogger.ErrorException(dtw["PointID"].ToString() + " 讀取異常", ex);
                                gWorkSocket.Shutdown(SocketShutdown.Both);
                                System.Threading.Thread.Sleep(500);
                                gWorkSocket.Disconnect(false);
                                gWorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                objSocketLink.LinkEQP(0, sIP, sPort, gWorkSocket);
                            }
                        }

                        objSocketLink.LinkEQP(1, sIP, sPort, gWorkSocket);

                        dtsPointsVlue = new DataSet("PointsVlue");
                        dtsPointsVlue.Tables.Add(dttPointsValue);
                        //dtsPointsVlue.WriteXml(@"C:\EEP System\HeatPump\Adapter\Data.xml");
                        //if (!wsEEP_Client_WS.Set_PointValueToRealTimeTable(objDataEncryption.DataSetToByte(dtsPointsVlue), g_sProjectID))
                        //{
                        //    CSV.CSV objCSV = new CSV.CSV();
                        //    objCSV.WriteToCSV(dttPointsValue, Convert.ToDateTime(dttPointsValue.Rows[0]["RecTime"]).ToString("yyyyMMdd"));
                        //    if (objCSV != null) { objCSV = null; }
                        //}
                        string sDefTableName = "ACRealTimeData";
                        string sCmdExistSQL = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sDefTableName);
                        dttExist = Utility.execDataTable(sCmdExistSQL, sConnString);
                        if (dttExist.Rows.Count == 0)
                        {
                            string cmdSQL = string.Format("CREATE TABLE [dbo].[{0}]([PointID] " +
                            "[nvarchar](5) NOT NULL, [Status] [nvarchar](10) NOT NULL,  " +
                            "[RecTime] [datetime] NULL, CONSTRAINT " +
                            "[PK_ACRealTimeData] PRIMARY KEY CLUSTERED ([PointID] ASC " +
                            ")WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, " +
                            "ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]"
                            , sDefTableName);
                            int i = Utility.execNonQuery(cmdSQL, sConnString);

                            g_oLogger.Trace("產生新的EEP_RealTimeData的Table");
                        }
                        foreach (DataRow dtw in dttPointsValue.Rows)
                        {
                            try
                            {
                                string cmdSQL = "";
                                cmdSQL = string.Format("DELETE {0} WHERE PointID = '{1}'", sDefTableName, dtw["PointID"].ToString());
                                Utility.execNonQuery(cmdSQL, sConnString);

                                cmdSQL = "";
                                cmdSQL = string.Format("INSERT INTO {0} (PointID, Status, RecTime) " +
                                    "VALUES ('{1}', '{2}', '{3}');"
                                    , sDefTableName
                                    , dtw["PointID"].ToString()
                                    , dtw["Status"].ToString()
                                    , ((DateTime)dtw["RecTime"]).ToString("yyyy-MM-dd HH:mm:ss.fff"));

                                retAffectedRows += Utility.execNonQuery(cmdSQL, sConnString);

                            }
                            catch (Exception ex)
                            {
                                g_oLogger.ErrorException("insert RealTimeTable異常:", ex);
                            }
                            finally
                            {
                                // if (Utility != null) { Utility = null; }
                            }
                        }

                        g_iRunCount++;
                        g_oLogger.Debug("Count:" + g_iRunCount.ToString());
                        g_oLogger.Debug(DateTime.Now + ": Insert RealTime Table");

                        //Service alive 狀態紀錄
                        sDefTableName = "ACServiceAlive";
                        sCmdExistSQL = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sDefTableName);
                        dttExist = Utility.execDataTable(sCmdExistSQL, sConnString);
                        if (dttExist.Rows.Count == 0)
                        {
                            string cmdSQL = string.Format("CREATE TABLE [dbo].[{0}]([ServiceName] " +
                            "[nvarchar](20) NOT NULL, " +
                            "[RecTime] [datetime] NULL, CONSTRAINT " +
                            "[PK_ACServiceAlive] PRIMARY KEY CLUSTERED ([ServiceName] ASC " +
                            ")WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, " +
                            "ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]"
                            , sDefTableName);
                            int i = Utility.execNonQuery(cmdSQL, sConnString);

                            g_oLogger.Trace("產生新的ACServiceAlive的Table");
                        }

                        try
                        {
                            string cmdSQL = "";
                            cmdSQL = string.Format("DELETE {0} WHERE ServiceName = '{1}'", sDefTableName, "ACStatus");
                            Utility.execNonQuery(cmdSQL, sConnString);

                            cmdSQL = "";
                            cmdSQL = string.Format("INSERT INTO {0} (ServiceName , RecTime) " +
                                "VALUES ('{1}', '{2}');"
                                , sDefTableName
                                , "ACStatus"
                                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                            Utility.execNonQuery(cmdSQL, sConnString);

                        }
                        catch (Exception ex)
                        {
                            g_oLogger.ErrorException("insert ACServiceAliveTable異常:", ex);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                g_oLogger.ErrorException("ModbusRTU.讀取設備參數階段", ex);
            }
            finally
            {
                if (gWorkSocket != null && gWorkSocket.Connected) { gWorkSocket.Shutdown(SocketShutdown.Both); gWorkSocket.Close(1); ; gWorkSocket = null; }
                if (objSocketLink != null) { objSocketLink = null; }
                if (dtsPointsData != null) { dtsPointsData.Clear(); dtsPointsData.Dispose(); dtsPointsData = null; }
                if (dtsPointsVlue != null) { dtsPointsVlue.Clear(); dtsPointsVlue.Dispose(); dtsPointsVlue = null; }
                if (wsEEP_Client_WS != null) { wsEEP_Client_WS.Dispose(); wsEEP_Client_WS = null; }
                if (Utility != null) { Utility = null; }
            }
        }
Ejemplo n.º 2
0
        public void Start()
        {
            EEP_Client_WS.EEP_Client_WS wsEEP_Client_WS = new EEP_Client_WS.EEP_Client_WS();
            DataTable dttIPPort = new DataTable(); //存放ModbusTCP之設備IP與Port
            DataTable dttACList = new DataTable();//存放空調狀況改變排程作業
            DataTable dttACListPara = new DataTable();
            DataTable dttExist = null;
            DataRow[] dtwPointsDatafilter = null;
            DataSet dtsPointsVlue = null; //存放讀取設備的讀值
            DataEncryption.DataEncryption objDataEncryption = new DataEncryption.DataEncryption();
            //DataSet dtsEquipments = new DataSet("Equipments");
            //DataSet dtsPoints = new DataSet("Points");
            DataSet dtsPointsData = new DataSet("PointsData");
            int iCount = 0;////
            int iInsertCount = 0;
            int retAffectedRows = 0;
            string sSQLCmd = "";
            string sSQLCmd2 = "";
            string sTableName = "";
            string sTableName2 = "";
            try
            {
                try
                {
                    //SqlConnection conn = new SqlConnection(sConnString);
                    //conn.Open();
                    //dtsEquipments.ReadXml(@gsEquipmentsFilePath);
                    //dtsPoints.ReadXml(@gsPointsFilePath);
                    sTableName = "ACCommandList";
                    sSQLCmd = string.Format("SELECT * FROM {0} Where convert(varchar (10), RecTime,120 ) = convert(varchar (10), getdate(),120  ) and Result IS NULL ", sTableName);
                    sSQLCmd2 = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sTableName);
                    DataTable dataTable2 = Utility.execDataTable(sSQLCmd2, sConnString);
                    if (dataTable2.Rows.Count > 0)
                    {
                        dttACList = Utility.execDataTable(sSQLCmd, sConnString);
                    }

                    //SqlCommand cmd = new SqlCommand("Select * From  ACStatusPara", conn);

                    //dttACPara.Load(cmd.ExecuteReader());
                    //cmd.Dispose();
                    //conn.Close();
                    //conn.Dispose();

                    //dtsPointsData = wsEEP_Client_WS.Get_PointsData_ModbusTCP(g_sCompanyID, "", "");
                }
                catch (Exception ex)
                {
                    g_oLogger.ErrorException("讀取異常-- ", ex);
                }

                //if (dtsEquipments.Tables[0].Rows.Count == 0)
                if (dttACList.Rows.Count == 0)
                {
                    g_oLogger.Info("---------------ModbusTCP之設備檔異常,請檢查(DB)檔案---------------");
                }
                //if (dtsEquipments.Tables[0].Rows.Count > 0)
                if (dttACList.Rows.Count > 0)
                {
                    //dttIPPort = dtsEquipments.Tables[0].DefaultView.ToTable(true, new string[] { "IP", "Port" });
                    //dttIPPort = dttACPara.DefaultView.ToTable(true, new string[] { "IP", "Port" });

                    sTableName = "ACCommandList";
                    sTableName2 = "ACStatusPara";
                    sSQLCmd = string.Format("SELECT AL.[RecTime] ,AL.[PointID] ,AL.[SetMode] ,AL.[Result] ,AL.[FinishTime] ,AP.[IP] ,AP.[DeviceID] FROM {0} as AL, {1} as AP Where convert(varchar (10), AL.RecTime,120 ) = convert(varchar (10), getdate(),120 ) And AL.PointID = AP.PointID", sTableName, sTableName2);
                    sSQLCmd2 = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sTableName2);
                    DataTable dataTable3 = Utility.execDataTable(sSQLCmd2, sConnString);
                    if (dataTable3.Rows.Count > 0)
                    {
                        dttACListPara = Utility.execDataTable(sSQLCmd, sConnString);
                    }
                    dttIPPort = dttACListPara.DefaultView.ToTable(true, new string[] { "IP" });

                    foreach (DataRow dtwIPPort in dttIPPort.Rows)
                    {
                        DataTable dttPointsValue = new DataTable("ACRealTimeData");
                        //dttPointsValue.Columns.Add("PointID", typeof(string));
                        //dttPointsValue.Columns.Add("Status", typeof(string));
                        //dttPointsValue.Columns.Add("RecTime", typeof(DateTime));
                        string sIP = dtwIPPort["IP"].ToString();
                        //string sPort = dtwIPPort["Port"].ToString();
                        string sPort = "502";
                        objSocketLink = new SocketLink.SocketLink();
                        gWorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        //104.2.4 ping不到設備就往下一個ip設備詢問
                        g_oLogger.Debug(sIP + "進行連線------------------------------------------------------");
                        if (ping.Send(sIP, 1000).Status != System.Net.NetworkInformation.IPStatus.Success)
                        {
                            g_oLogger.Debug(sIP + "的設備連線TimeOut-----------------------------------------");
                            continue;
                        }
                        objSocketLink.LinkEQP(0, sIP, sPort, gWorkSocket);
                        //dtwPointsDatafilter = dtsEquipments.Tables[0].Select("IP = '" + sIP + "' and Port = '" + sPort + "'"); //dtsEquipments.Tables[0].Select("IP = '" + sIP + "' and Port = '" + sPort + "'", "Address DESC");
                        dtwPointsDatafilter = dttACListPara.Select("IP = '" + sIP + "'");
                        foreach (DataRow dtw in dtwPointsDatafilter)
                        {
                            try
                            {
                                if (gWorkSocket.Connected) //0:表連線,1:表斷線
                                {
                                    string sCommand = "";
                                    byte[] byReceived = null;
                                    bool bResult = false;

                                    switch (dtw["SetMode"].ToString())
                                    {
                                        //卡機模式
                                        case "Auto":
                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,10,0,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("Auto模式設定:第一階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("Auto模式設定:第一階段設定失敗"); }

                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,2,0,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("Auto模式設定:第二階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("Auto模式設定:第二階段設定失敗"); }

                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,10,255,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("Auto模式設定:第三階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("Auto模式設定:第三階段設定失敗"); }

                                        //驗證是否設定成功
                                        sCommand = string.Format("0,0,0,0,0,6,{0},3,0,3,0,1", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        {
                                            switch (byReceived[10].ToString("00"))
                                            {
                                                //卡機模式
                                                case "00":
                                                    g_oLogger.Debug("模式設定ok:現在是Auto模式");
                                                    bResult = true;
                                                    break;
                                                //強開模式
                                                case "161":
                                                    g_oLogger.Debug("模式設定Fail:現在是FOn模式");
                                                    break;
                                                //強關模式
                                                case "128":
                                                    g_oLogger.Debug("模式設定Fail:現在是FOff模式");
                                                    break;
                                            }
                                        }
                                        break;

                                        //強開模式
                                        case "FOn":
                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,10,0,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("FOn模式設定:第一階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("FOn模式設定:第一階段設定失敗"); }

                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,2,255,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("FOn模式設定:第二階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("FOn模式設定:第二階段設定失敗"); }

                                        //驗證是否設定成功
                                        sCommand = string.Format("0,0,0,0,0,6,{0},3,0,3,0,1", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        {
                                            switch (byReceived[10].ToString("00"))
                                            {
                                                //卡機模式
                                                case "00":
                                                    g_oLogger.Debug("模式設定Fail:現在是Auto模式");
                                                    break;
                                                //強開模式
                                                case "161":
                                                    g_oLogger.Debug("模式設定ok:現在是FOn模式");
                                                    bResult = true;
                                                    break;
                                                //強關模式
                                                case "128":
                                                    g_oLogger.Debug("模式設定Fail:現在是FOff模式");
                                                    break;
                                            }
                                        }

                                            break;

                                        //強關模式
                                        case "FOff":
                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,10,0,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("FOff模式設定:第一階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("FOff模式設定:第一階段設定失敗"); }

                                        sCommand = string.Format("0,0,0,0,0,6,{0},5,0,2,0,0", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        { g_oLogger.Debug("FOff模式設定:第二階段設定成功"); }
                                        else
                                        { g_oLogger.Debug("FOff模式設定:第二階段設定失敗"); }

                                        //驗證是否設定成功
                                        sCommand = string.Format("0,0,0,0,0,6,{0},3,0,3,0,1", Convert.ToDouble(dtw["DeviceID"]));
                                        byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                        if (byReceived != null)
                                        {
                                            switch (byReceived[10].ToString("00"))
                                            {
                                                //卡機模式
                                                case "00":
                                                    g_oLogger.Debug("模式設定Fail:現在是Auto模式");
                                                    break;
                                                //強開模式
                                                case "161":
                                                    g_oLogger.Debug("模式設定Fail:現在是FOn模式");
                                                    break;
                                                //強關模式
                                                case "128":
                                                    g_oLogger.Debug("模式設定ok:現在是FOff模式");
                                                    bResult = true;
                                                    break;
                                            }

                                        }

                                            break;

                                        default:
                                            bResult = false;
                                            g_oLogger.Debug("模式設定參數錯誤");
                                            break;

                                    }

                                    //byReceived = ModbusTCP_Operate(sCommand, gWorkSocket, sIP, 1);
                                    //if (byReceived == null)
                                    //    continue;

                                    iCount++;
                                    if (iCount % 100 == 0)
                                    {
                                        objSocketLink.LinkEQP(1, sIP, sPort, gWorkSocket);
                                        if (objSocketLink != null) { objSocketLink = null; }

                                        objSocketLink = new SocketLink.SocketLink();
                                        gWorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                        objSocketLink.LinkEQP(0, sIP, sPort, gWorkSocket);
                                    }

                                    sTableName = "ACCommandList";
                                    sSQLCmd = string.Format("Update {0} Set Result = '{1}' ,  FinishTime ='{2}' Where RecTime ='{3}' and PointID ='{4}'", sTableName, bResult.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), Convert.ToDateTime(dtw["RecTime"]).ToString("yyyy-MM-dd HH:mm:ss.fff"), dtw["PointID"]);
                                    sSQLCmd2 = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sTableName);
                                    DataTable dataTable4 = Utility.execDataTable(sSQLCmd2, sConnString);
                                    if (dataTable3.Rows.Count > 0)
                                    {

                                        iInsertCount += Utility.execNonQuery(sSQLCmd, sConnString);
                                        g_oLogger.Debug("更新任務狀態:第" + iInsertCount.ToString() +"次");
                                    }

                                    //SolveValue(ref dttPointsValue, int.Parse(dtw["Address"].ToString()), byReceived, dtsPoints.Tables[0], sIP, int.Parse(sPort), g_sEquipmentType);
                                    //SolveValue(ref dttPointsValue, int.Parse(dtw["Address"].ToString()), byReceived, dtsPointsData.Tables[0], sIP, int.Parse(sPort), g_sEquipmentType, dtw["PointID"].ToString(), dtw["EquipmentID"].ToString());
                                    //新增dtw參數
                                    //SolveValue(ref dttPointsValue, int.Parse(dtw["Address"].ToString()), byReceived, dtsPointsData.Tables[0], sIP, int.Parse(sPort), g_sEquipmentType, dtw["PointID"].ToString(), dtw["EquipmentID"].ToString(),dtw);
                                    //SolveValueAC(ref dttPointsValue, byReceived, dtw["PointID"].ToString());

                                    //for (int i = 0; i < dttPointsValue.Rows.Count; i++)
                                    //{
                                    //    gLogger.Trace(string.Format("{0}, {1}, {2}, {3}"
                                    //        , dttPointsValue.Rows[i][0].ToString()
                                    //        , dttPointsValue.Rows[i][1].ToString()
                                    //        , dttPointsValue.Rows[i][2].ToString()
                                    //        , ((DateTime)dttPointsValue.Rows[i][3]).ToString("yyyy-MM-dd HH:mm:ss.fff")));
                                    //}
                                }
                            }
                            catch (Exception ex)
                            {
                                g_oLogger.ErrorException(dtw["PointID"].ToString() + " 讀取異常", ex);
                                gWorkSocket.Shutdown(SocketShutdown.Both);
                                System.Threading.Thread.Sleep(500);
                                gWorkSocket.Disconnect(false);
                                gWorkSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                objSocketLink.LinkEQP(0, sIP, sPort, gWorkSocket);
                            }
                        }

                        objSocketLink.LinkEQP(1, sIP, sPort, gWorkSocket);

                        dtsPointsVlue = new DataSet("PointsVlue");
                        dtsPointsVlue.Tables.Add(dttPointsValue);
                        //dtsPointsVlue.WriteXml(@"C:\EEP System\HeatPump\Adapter\Data.xml");
                        //if (!wsEEP_Client_WS.Set_PointValueToRealTimeTable(objDataEncryption.DataSetToByte(dtsPointsVlue), g_sProjectID))
                        //{
                        //    CSV.CSV objCSV = new CSV.CSV();
                        //    objCSV.WriteToCSV(dttPointsValue, Convert.ToDateTime(dttPointsValue.Rows[0]["RecTime"]).ToString("yyyyMMdd"));
                        //    if (objCSV != null) { objCSV = null; }
                        //}

                        g_iRunCount++;
                        g_oLogger.Debug("Count:" + g_iRunCount.ToString());
                        g_oLogger.Debug(DateTime.Now + ": Insert RealTime Table");

                        //Service alive 狀態紀錄
                        string sDefTableName = "ACServiceAlive";
                        string sCmdExistSQL = string.Format("IF EXISTS(SELECT name FROM sys.objects WHERE name = '{0}') SELECT 'True'", sDefTableName);
                        dttExist = Utility.execDataTable(sCmdExistSQL, sConnString);
                        if (dttExist.Rows.Count == 0)
                        {
                            string cmdSQL = string.Format("CREATE TABLE [dbo].[{0}]([ServiceName] " +
                            "[nvarchar](20) NOT NULL, " +
                            "[RecTime] [datetime] NULL, CONSTRAINT " +
                            "[PK_ACServiceAlive] PRIMARY KEY CLUSTERED ([ServiceName] ASC " +
                            ")WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, " +
                            "ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]"
                            , sDefTableName);
                            int i = Utility.execNonQuery(cmdSQL, sConnString);

                            g_oLogger.Trace("產生新的ACServiceAlive的Table");
                        }

                        try
                        {
                            string cmdSQL = "";
                            cmdSQL = string.Format("DELETE {0} WHERE ServiceName = '{1}'", sDefTableName, "ACChange");
                            Utility.execNonQuery(cmdSQL, sConnString);

                            cmdSQL = "";
                            cmdSQL = string.Format("INSERT INTO {0} (ServiceName , RecTime) " +
                                "VALUES ('{1}', '{2}');"
                                , sDefTableName
                                , "ACChange"
                                , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

                            Utility.execNonQuery(cmdSQL, sConnString);

                        }
                        catch (Exception ex)
                        {
                            g_oLogger.ErrorException("insert ACServiceAliveTable異常:", ex);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                g_oLogger.ErrorException("ModbusRTU.讀取設備參數階段", ex);
            }
            finally
            {
                if (gWorkSocket != null && gWorkSocket.Connected) { gWorkSocket.Shutdown(SocketShutdown.Both); gWorkSocket.Close(1); ; gWorkSocket = null; }
                if (objSocketLink != null) { objSocketLink = null; }
                if (dtsPointsData != null) { dtsPointsData.Clear(); dtsPointsData.Dispose(); dtsPointsData = null; }
                if (dtsPointsVlue != null) { dtsPointsVlue.Clear(); dtsPointsVlue.Dispose(); dtsPointsVlue = null; }
                if (wsEEP_Client_WS != null) { wsEEP_Client_WS.Dispose(); wsEEP_Client_WS = null; }
                if (Utility != null) { Utility = null; }
            }
        }