码迷,mamicode.com
首页 > 其他好文 > 详细

自动立体车库控制应用系统

时间:2016-01-27 21:11:19      阅读:498      评论:0      收藏:0      [点我收藏+]

标签:

自动立体车库控制应用系统主要控制界面如下

技术分享

系统主要包含两个部分:

第一部分是系统与PLC系列进行通信,实时采集现场控制信息,控制提升机及运输小车,完成多个设备之间互锁,保证系统安全有效运行。实时采集现场2000多个点信息,同时保存在数据库。

第二部分是管理所有车位信息。高效规划入出库路径,最大化提高系统高效。

下面是数据库操作部分代码

using System;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;
using System.Data;
/*
 * CopyRight (c) 2016 北京软秀科技有限公司 保留所有权利 meslog@qq.com 
 */
namespace Jiankong
{
    class DataAccess
    {
        
        public SqlConnection Conn ;
        string str;

        public DataAccess() 
        {
            string dd = Environment.CurrentDirectory;
            IniFile ls_IniFile = new IniFile(Environment.CurrentDirectory + "\\log.ini");
            string connectString = ls_IniFile.ReadIniValue("Database", "connect");
             Conn = new SqlConnection(connectString);

        }
        public int getPortnum(string PortName)
        {
            int PortNum;
            str = "select PortNum from PortState where PortName =‘" + PortName + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            reader.Read();
            PortNum = Convert.ToInt32(reader[0].ToString());
            Conn.Close();
            return PortNum;
        }

        public void addcar(string CarNo,string CarCla,string  InTime,string PortNo)
        {

            string RegCarNo = "[\u4e00-\u9fa5][A-Z]-[0-9]{5}";
            string RegInTime = "([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";
            string RegCarCla = "(大卡|中货|小轿)";

            Conn.Open();
            str = "select CarNo from CarIn where CarNo=‘" + CarNo + "";
            SqlCommand command = new SqlCommand(str, Conn);
            SqlDataReader reader = command.ExecuteReader();
            if (!Regex.IsMatch(CarNo, RegCarNo) || CarNo.Length!=8)
            {
                MessageBox.Show("无效的车牌号码(正确的格式:京A-12345)!");
            }
            else if (!Regex.IsMatch(InTime, RegInTime) || InTime.Length != 8)
            {
                MessageBox.Show("无效的入库时间(正确的格式:12:34:00)!");
            }
            else if (!Regex.IsMatch(CarCla, RegCarCla))
            {
                MessageBox.Show("无效车辆类型(正确的格式:大卡|中货|小轿)!");
            }
            else if (PortNo == "")
            {
                MessageBox.Show("本车库已满,下次请早!");
            }
            else if (!reader.Read())
            {
                reader.Close();
                str = "insert into CarIn(CarNo,CarCla,InTime,PortNo) values (‘" + CarNo + "‘,‘" + CarCla + "‘,‘" + InTime + "‘,‘" + PortNo.Trim() + "‘)";
                SqlCommand Command = new SqlCommand(str, Conn);
                Command.ExecuteNonQuery();
            }
            else
            {
                MessageBox.Show("重复的车牌号码!");
            }
            Conn.Close(); 
        }

        public string recPortNo(string CarClass)
        {
            int NumA, NumB, NumC;
            string PortNo = "";
            NumA = getPortnum("PortA");
            NumB = getPortnum("PortB");
            NumC = getPortnum("PortC");
            Conn.Open();
            if (CarClass == "大卡")
            {  
                for (int i = 1; i < NumA; i++)
                {
                    str = "select PortNo from CarIn where PortNo = ‘A" + i + ""; 
                    SqlCommand datacommand = new SqlCommand(str, Conn);
                    SqlDataReader reader = datacommand.ExecuteReader();
                    if (! reader.Read())
                    { 
                        PortNo = "A" + i;
                        break;
                    }
                    reader.Close();
                }
            }
            else if (CarClass == "中货")
            {
                for (int i = 1; i < NumB; i++)
                {
                    str = "select PortNo from CarIn where PortNo = ‘B" + i + "";
                    SqlCommand datacommand = new SqlCommand(str, Conn);
                    SqlDataReader reader = datacommand.ExecuteReader();
                    if (!reader.Read())
                    {
                        PortNo = "B" + i;
                        break;
                    }
                    reader.Close();
                }
            }
            else
            {
                for (int i = 1; i < NumC; i++)
                {
                    str = "select PortNo from CarIn where PortNo = ‘C" + i + "";
                    SqlCommand datacommand = new SqlCommand(str, Conn);
                    SqlDataReader reader = datacommand.ExecuteReader();
                    if (!reader.Read())
                    {
                        PortNo = "C" + i;
                        break;
                    }
                    reader.Close();
                }
            } 
            Conn.Close();                 
            return PortNo;
        }

        //public void getRate(string CarClass, out int Time1, out int Time2, out int Time3, out double  Rate1, out double  Rate2, out double Rate3)
        //{
        //    str = "select * from Rate where CarCla =‘" + CarClass + "‘";
        //    Conn.Open();
        //    //SqlCommand command = new SqlCommand(str, Conn);
        //    //SqlDataReader reader = command.ExecuteReader();
        //    //reader.Read();
        //    //Time1 = Convert.ToInt32(reader[1]);
        //    //Rate1 = Convert.ToDouble(reader[2].ToString());
        //    //Time2 =  Convert.ToInt32(reader[3]);
        //    //Rate2 = Convert.ToDouble(reader[4].ToString());
        //    //Time3 =  Convert.ToInt32(reader[5]);
        //    //Rate3 = Convert.ToDouble(reader[6].ToString());
        //    Conn.Close();
        //}

        public void updaterage(string CarClass, int Time1, int Time2, int Time3, string Rate1, string Rate2, string Rate3)
        { 
            DialogResult MsgBoxResult;
            MsgBoxResult = MessageBox.Show("确定更新数据?", "请确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (MsgBoxResult == DialogResult.OK)
            {
                str = "update Rate set Time1=" + Time1 + ",Time2=" + Time2 + ",Time3=" + Time3 + ",Rate1=" + Rate1 + ",Rate2=" + Rate2 + ",Rate3=" + Rate3 + "where CarCla=‘" + CarClass + "";
                Conn.Open();
                SqlCommand Command = new SqlCommand(str, Conn);
                Command.ExecuteNonQuery();
                Conn.Close();
            }
        }

        public void getPortused(string PortName,out int PortNum, out int PortUsed)
        {
            str = "select PortNum,PortUsed from PortState where PortName =‘" + PortName + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            reader.Read();
            PortNum = Convert.ToInt32(reader[0].ToString());
            PortUsed = Convert.ToInt32(reader[1].ToString());
            Conn.Close();
        }

        public int getDataNum(string table)
        {
            int DataNum;
            str = "select COUNT(*) from " + table + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            reader.Read();
            DataNum = Convert.ToInt32(reader[0].ToString());
            Conn.Close();
            return DataNum;
        }

        public string[] getCarNo()
        {

            int arrayno = getDataNum("CarIn");
            string[] Carray = new string[arrayno];

            str = "select CarNo from CarIn ";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            int i = 0;
            while (reader.Read())
            {
                Carray[i] = reader[0].ToString();
                i++;
            }
            Conn.Close();
            return Carray;
        }

        public void getCardetail(string CarNo,out string carcla, out string intime, out string portno)
        {
            str = "select CarCla,InTime,PortNo from CarIn where CarNo=‘" + CarNo + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            reader.Read();
            carcla = reader[0].ToString();
            intime  =reader[1].ToString();
            portno  =reader[2].ToString();
            Conn.Close();  
        }

        public void delCar(string CarNo,string money)
        {
            DialogResult MsgBoxResult;
            MsgBoxResult = MessageBox.Show("车牌号码为:"+CarNo +",需要缴纳停车费用"+money+"元!确定离开车库?","请确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (MsgBoxResult == DialogResult.OK)
            {
                str = "update CarIn set OutTime =‘" + money + "‘where CarNo =‘" + CarNo + "";
                Conn.Open();
                SqlCommand Command = new SqlCommand(str, Conn);
                Command.ExecuteNonQuery();

                str = "delete from CarIn where CarNo =‘" + CarNo + "";
                SqlCommand Command2 = new SqlCommand(str, Conn);
                Command2.ExecuteNonQuery();
                Conn.Close();
            }
        }

        public int[] getPortstate(string Stano,string PortName, out int arrayno)
        {
            int temparrayno = getDataNum("CarIn");
            int[] temparray = new int[temparrayno];
            str = "select PortNo from CarIn where 1=1";
            str = str + " and stano =‘" + Stano + "";
            str = str + " and statu = ‘1‘";
            str = str + " and len(carno) <> 0 ";
            str = str + " order by PortNo";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            int i = 0;
            while (reader.Read())
            {
                if (reader[0].ToString().Substring(0, 1) == PortName.Substring(4, 1))
                {
                    temparray[i] = Convert.ToInt32(reader[0].ToString().Substring(1, reader[0].ToString().Length - 1));
                    i++;
                }
            }
            Conn.Close();

            arrayno = i;
            int[] Pnoarray = new int[arrayno];
            {
                for (int j = 0; j < arrayno; j++)
                {
                    Pnoarray[j] = temparray[j];
                }                 
            }
            return Pnoarray;
        }

        public void getCardetail2(string PortNo,string InStano,out string CarNo,out string InTime,out string CarCla,out string Stano)
        {
            str = "select CarNo,InTime,CarCla,Stano from CarIn where PortNo =‘" + PortNo + "";
            str = str + " and stano= ‘" + InStano + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            reader.Read();
            CarNo = reader[0].ToString();
            InTime = reader[1].ToString();
            CarCla = reader[2].ToString();
            Stano = reader[3].ToString();
            Conn.Close();         
        }

        public int getCarportnum(string CarCla)
        {
            int Carnum;
            str = "select COUNT(*) from CarIn where CarCla = ‘" + CarCla + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            reader.Read();
            Carnum = Convert.ToInt32(reader[0].ToString());
            Conn.Close();
            return Carnum;
        }

        public string[] getCarportno(string CarCla)
        {
            int arrayno = getCarportnum(CarCla);
            string[] Carray = new string[arrayno];

            str = "select PortNo from CarIn where CarCla = ‘" + CarCla + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();
            int i = 0;
            while (reader.Read())
            {
                Carray[i] = reader[0].ToString();
                i++;
            }
            Conn.Close();
            return Carray;
        }

        public void updatestate(string PortName, int PortNum)
        {
            DialogResult MsgBoxResult;
            MsgBoxResult = MessageBox.Show("确定更新数据?", "请确定", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (MsgBoxResult == DialogResult.OK)
            {
                string RegPortNum = "[0-9]{1,3}";

                if (!Regex.IsMatch(PortNum.ToString(), RegPortNum) || PortNum.ToString().Length > 3)
                {
                    MessageBox.Show("无效的车位数目!");
                }
                else
                { 
                    str = "update PortState set PortNum=" + PortNum + "where PortName=‘" + PortName + "";
                    Conn.Open();
                    SqlCommand Command = new SqlCommand(str, Conn);
                    Command.ExecuteNonQuery();
                    Conn.Close();                 
                }
            }
        }

        public DataSet getDataset(string sqlstr)
        {
            Conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(sqlstr,Conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            Conn.Close();
            return ds;
        }

        public void updatedata(DataSet ds,string sqlstr)
        {
            Conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(sqlstr, Conn);

            SqlCommandBuilder cb = new SqlCommandBuilder(da);

            da.Update(ds);

            Conn.Close();
        
        }

        public bool isEmpty(string portno)
        {
            bool empty = false;
            str = "select CarNo from CarIn where PortNo = ‘" + portno + "";
            Conn.Open();
            SqlCommand datacommand = new SqlCommand(str, Conn);
            SqlDataReader reader = datacommand.ExecuteReader();

            if(!reader.Read())
            {
                empty = true;
            }
            Conn.Close();
            return empty;
        }

        public void Dropit(string table)
        {
            str = "drop table " + table + "";
            Conn.Open();
            SqlCommand Command = new SqlCommand(str, Conn);
            Command.ExecuteNonQuery();
            Conn.Close();
        }

        public void Emptyit(string table)
        {
            str = "truncate table " + table + "";
            Conn.Open();
            SqlCommand Command = new SqlCommand(str, Conn);
            Command.ExecuteNonQuery();
            Conn.Close();
        }

        public void CarlogInitial()
        {
            str = "insert into Carlog(CarNo,CarCla,InTime,OutTime,PortNo,Action,Actiontime) select CarNo,CarCla,InTime,OutTime,PortNo,‘车库保持‘,CONVERT(varchar(100), GETDATE(), 8) from CarIn";
            Conn.Open();
            SqlCommand Command = new SqlCommand(str, Conn);
            Command.ExecuteNonQuery();
            Conn.Close();        
        }

        public void ResetCarIn()
        {
            //str = "insert into CarIn select * from BackUp_CarIn ";
            int arrayno = getDataNum("BackUp_CarIn");
            string[] carno = new string[arrayno];
            string[] carcla = new string[arrayno];
            string[] intime = new string[arrayno];
            string[] portno = new string[arrayno];
            
            str = "select * from BackUp_CarIn";
            Conn.Open();
            SqlCommand command = new SqlCommand(str, Conn);
            SqlDataReader reader = command.ExecuteReader();
            int i=0;
            while (reader.Read())
            {
                carno[i] = reader[0].ToString().Trim();
                carcla[i] = reader[1].ToString().Trim();
                intime[i] = reader[2].ToString().Trim();
                portno[i] = reader[4].ToString().Trim();
                i++;            
            } 
            Conn.Close();

            for (int j = 0; j < arrayno; j++)
            {
                addcar(carno[j], carcla[j], intime[j], portno[j]);           
            }
     
        }

        public void ResetPortState()
        {
            //str = "insert into PortState(PortName,PortNum,PortUsed) select PortName,PortNum,PortUsed from BackUp_PortState";
            str = "select * into PortState from BackUp_PortState";
            Conn.Open();
            SqlCommand Command = new SqlCommand(str, Conn);
            Command.ExecuteNonQuery();
            Conn.Close();
        }

        public void ResetRate()
        {
            //str = "insert into Rate(CarCla,Time1,Rate1,Time2,Rate2,Time3,Rate3) select CarCla,Time1,Rate1,Time2,Rate2,Time3,Rate3 from BackUp_Rate";
            str = "select * into Rate from BackUp_Rate";
            Conn.Open();
            SqlCommand Command = new SqlCommand(str, Conn);
            Command.ExecuteNonQuery();
            Conn.Close();
        }

    }
}

下面是与PLC操作代码,通过OPC的方式。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Data;
using System.Text;
using OPC.Common;
using OPC.Data.Interface;
using OPC.Data;

using OpcRcw.Comn;
using OpcRcw.Da;

using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.OleDb;
namespace Jiankong
{

    public class Plc : IOPCDataCallback
    {
        public IniFile ls_IniFile = new IniFile(Environment.CurrentDirectory + "\\log.ini");
        public Data objData = new Data();
        public DataSet dsData;
        public Thread objThread;
        public Thread objThreadFlash;
       // Mutex mutex;
    
        //private System.ComponentModel.IContainer components;
        const string serverProgID = "OPC.SimaticNET";        // ProgID of OPC server
        //const string serverProgID    = "Schneider-Aut.OFS";        // ProgID of OPC serve
        private OpcServer theSrv;
        private OpcGroup theGrp;
        //private SERVERSTATUS theStatu;

        public static int devicenum = 4606;
        public static int deviceno = 4606;
        public int devnum;
        public string[] devicesatu = new string[22] { "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B", "0B","0B","0B" };
        public string[] devicetrans = new string[30] { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };
        //public string[] errmsg = new string[1000];
        public string[] errmsg = new string[]
                                            {" ","F01    运行超限","F02    升降超限","F03    松绳过载","F04    运行停偏","F05    升降停偏",
                                            "F06    货偏","F07    货叉位错","F08    升降超速","F09    运行变频器故障","F10    升降变频器故障",
                                            "F11    货叉变频器故障","F12    制动空开跳闸","F13    命令非法","F14    作业超时","F15    微升降超时",
                                            "F16    微升降超限","F17    伸缩叉超时","F18    货叉超限","F19    空取货","F20    空出库","F21    双重入库",
                                            "F22    卸货双重","F23    货未卸","F24    升降未对准","F25    运行速度偏差","F26    升降速度偏差","F27    激光读数超限",
                                            "F28    升降读数超限","F29    货叉编码器故障","F30    升降编码器故障","F31    激光ATT","F32    激光TMP","F33    激光LSR",
                                            "F34    激光PLB","F35    激光ERR","F36    备用","F37    升降值读取错误","F38    激光值读取错误","F39    备用","F40    备用",
                                            "F41    运行站故障","F42    起升站故障","F43    货叉站故障","F44    激光站故障","F45    ET200M站故障","F46    编码器站故障",
                                            "F47    货叉与升降同时动作","F48    货叉与运行同时动作","F49    转弯超时","F50    转弯超速","F51    转弯处待机",
                                            "F52    带货转弯","F53    磁开关信号错","F54    CMV编码器故障","F55    备用","F56    近叉货位有货","F57     ",
                                            "F58     ","F59     ","F60     ","F61     ","F62     ","F63     ","F64     "
                                           };
        string[] objdevice = new string[devicenum];
        int[] handlesSrv = new int[devicenum];
        OPCItemDef[] itemDefs = new OPCItemDef[devicenum];



        /* Constants */
        internal const string SERVER_NAME = "OPC.SimaticNET";       // local server name
        internal const string ITEM1_NAME = "S7:[DEMO]DB10,STRING0.30";          // 1st item name
        internal const string ITEM2_NAME = "S7:[DEMO]DB10,STRING60.30";          // 2nd item name
        internal const string GROUP_NAME = "grp1";                  // Group name
        internal const int LOCALE_ID = 0x409;                       // LOCALE FOR ENGLISH.

        /* Global variables */
        IOPCServer pIOPCServer;
        IOPCAsyncIO2 pIOPCAsyncIO2 = null;                          // instance pointer for asynchronous IO.
        IOPCGroupStateMgt pIOPCGroupStateMgt = null;
        IConnectionPointContainer pIConnectionPointContainer = null;
        IConnectionPoint pIConnectionPoint = null;

        Object pobjGroup1 = null;
        int pSvrGroupHandle = 0;                                    // server group handle for the added group
        //int nTransactionID = 0;
        int[] ItemSvrHandleArray;
        Int32 dwCookie = 0;
        public string check()
        {
            Type svrComponenttyp;
            try
            {
                svrComponenttyp = Type.GetTypeFromProgID(SERVER_NAME);
                pIOPCServer = (IOPCServer)Activator.CreateInstance(svrComponenttyp);
                return "1";
            }
            catch
            {
                return "0";
            }
        }
        public void init_sim()
        {
            // Local variables
            Type svrComponenttyp;
            OPCITEMDEF[] ItemDeffArray;

            // Group properties
            Int32 dwRequestedUpdateRate = 250;
            Int32 hClientGroup = 1;
            Int32 pRevUpdateRate;
            float deadband = 0;

            int TimeBias = 0;

            GCHandle hTimeBias, hDeadband;
            hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned);
            hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned);


            // 1. Get the Type from the progID and create instance of the OPC Server COM component
            Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID;
            svrComponenttyp = Type.GetTypeFromProgID(SERVER_NAME);
            try
            {
                // Connect to the local server.
                pIOPCServer = (IOPCServer)Activator.CreateInstance(svrComponenttyp);
                try
                {
                    /* 2. Add a new group
                        Add a group object and querry for interface IOPCItemMgt
                        Parameter as following:
                        [in] not active, so no OnDataChange callback
                        [in] Request this Update Rate from Server
                        [in] Client Handle, not necessary in this sample
                        [in] No time interval to system UTC time
                        [in] No Deadband, so all data changes are reported
                        [in] Server uses english language to for text values
                        [out] Server handle to identify this group in later calls
                        [out] The answer from Server to the requested Update Rate
                        [in] requested interface type of the group object
                        [out] pointer to the requested interface
                    */

                    pIOPCServer.AddGroup(GROUP_NAME,
                        0,
                        dwRequestedUpdateRate,
                        hClientGroup,
                        hTimeBias.AddrOfPinnedObject(),
                        hDeadband.AddrOfPinnedObject(),
                        LOCALE_ID,
                        out pSvrGroupHandle,
                        out pRevUpdateRate,
                        ref iidRequiredInterface,
                        out pobjGroup1);
                    // Initialize all IO interface pointers.
                    InitReqIOInterfaces();                  

                    ItemDeffArray = new OPCITEMDEF[devicenum];
                    for (int i = 0; i < devicenum; i++)
                    {
                        
                        ItemDeffArray[i].szAccessPath = "";                   // Accesspath not needed for this sample
                        ItemDeffArray[i].szItemID = ls_IniFile.ReadIniValue("device", i.ToString());          // Item ID,
                        ItemDeffArray[i].bActive = 1;                    // item is active
                        ItemDeffArray[i].hClient = i;                    // client handle
                        ItemDeffArray[i].dwBlobSize = 0;                    // blob size
                        ItemDeffArray[i].pBlob = IntPtr.Zero;          // pointer to blob
                        ItemDeffArray[i].vtRequestedDataType = 0;                    // return values in native (cannonical) datatype

                    }
                    

                    IntPtr pResults = IntPtr.Zero;
                    IntPtr pErrors = IntPtr.Zero;

                    try
                    {
                        // Add items to group
                        ((IOPCItemMgt)pobjGroup1).AddItems(devicenum, ItemDeffArray, out pResults, out pErrors);

                        // Unmarshal to get the server handles out fom the m_pItemResult
                        // after checking the errors
                        int[] errors = new int[devicenum];
                        IntPtr pos = pResults;

                        ItemSvrHandleArray = new int[devicenum];
                        Marshal.Copy(pErrors, errors, 0, devicenum);

                        for (int i = 0; i < devicenum; i++)
                        {

                            OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
                            ItemSvrHandleArray[i] = result.hServer;
                            pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                            Marshal.DestroyStructure(pos, typeof(OPCITEMRESULT));

                        }
                        
                        if ((errors[0] == 0) && (errors[1] == 0))
                        {

                           //连接上了。
                        }
                    }
                    catch (System.Exception error) // catch for add items
                    {
                        MessageBox.Show(error.Message, "Result - Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        // Free the unmanaged COM memory
                        if (pResults != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pResults);
                            pResults = IntPtr.Zero;
                        }
                        if (pErrors != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pErrors);
                            pErrors = IntPtr.Zero;
                        }
                    }
                }
                catch (System.Exception error) // catch for group adding
                {
                    MessageBox.Show(String.Format("Error while creating group object:-{0}", error.Message),
                        "Result - Add group", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (hDeadband.IsAllocated) hDeadband.Free();
                    if (hTimeBias.IsAllocated) hTimeBias.Free();
                }
            }
            catch (System.Exception error) // catch for server instance creation
            {
                MessageBox.Show(String.Format("Error while creating server object:-{0}", error.Message),
                    "Result - Create Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void InitReqIOInterfaces()
        {
            try
            {
                //Query interface for async calls on group object
                pIOPCAsyncIO2 = (IOPCAsyncIO2)pobjGroup1;

                pIOPCGroupStateMgt = (IOPCGroupStateMgt)pobjGroup1;

                // Query interface for callbacks on group object
                pIConnectionPointContainer = (IConnectionPointContainer)pobjGroup1;

                // Establish Callback for all async operations
                Guid iid = typeof(IOPCDataCallback).GUID;
                pIConnectionPointContainer.FindConnectionPoint(ref iid, out pIConnectionPoint);

                // Creates a connection between the OPC servers‘s connection point and
                // this client‘s sink (the callback object).
                pIConnectionPoint.Advise(this, out dwCookie);
            }
            catch (System.Exception error) // catch for group adding
            {
                MessageBox.Show(String.Format("Error while advising callbacks:-{0}", error.Message),
                    "Result - Add group", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void PlcAct()
        {
            IntPtr pRequestedUpdateRate = IntPtr.Zero;
            int nRevUpdateRate = 0;
            IntPtr hClientGroup = IntPtr.Zero;
            IntPtr pTimeBias = IntPtr.Zero;
            IntPtr pDeadband = IntPtr.Zero;
            IntPtr pLCID = IntPtr.Zero;
            int nActive = 0;

            // activates or deactivates group according to checkbox status
            GCHandle hActive = GCHandle.Alloc(nActive, GCHandleType.Pinned);
            hActive.Target = 1;
            try
            {
                pIOPCGroupStateMgt.SetState(pRequestedUpdateRate, out nRevUpdateRate,
                    hActive.AddrOfPinnedObject(), pTimeBias, pDeadband, pLCID, hClientGroup);
            }
            catch (System.Exception error)
            {
                MessageBox.Show(error.Message,
                    "Result-Change Group State", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                hActive.Free();
            }
        }
        public virtual void OnDataChange(Int32 dwTransid,
          Int32 hGroup,
          Int32 hrMasterquality,
          Int32 hrMastererror,
          Int32 dwCount,
          int[] phClientItems,
          object[] pvValues,
          short[] pwQualities,
          OpcRcw.Da.FILETIME[] pftTimeStamps,
          int[] pErrors)
        {
            string trans = "0";
            int dev=0;
            string plc;
            string deviceno = "", devname = "",disp="";
            try
            {
                for (int nCount = 0; nCount < dwCount; nCount++)
                {
                  

                    if (pErrors[nCount] == 0)
                    {
                            ThreadExceptionDialog.CheckForIllegalCrossThreadCalls = false;
                            trans = Convert.ToString(pvValues[nCount]);
                            if (trans == "False")
                            {
                                trans = "0";
                            }
                            if (trans == "True")
                            {
                                trans = "1";
                            }
                            dev = phClientItems[nCount];
                            //work2(s.HandleClient.ToString(), s.DataValue.ToString());
                            plc = ls_IniFile.ReadIniValue("device", dev.ToString()); 
                             DataSet obj_device;
                             Main.pMainWin.devmsg[dev]=trans;
                             Main.pMainWin.objData.UpDevice(dev.ToString(), trans.ToString(),plc);  
                             obj_device=Main.pMainWin.objData.GetDevice(dev.ToString());
                           //  || plc == "771" || plc == "1527" || plc == "2283" || plc == "3039"||plc="3795")
                             if (plc == "16") 
                             {
                                 Main.pMainWin.objPlc.Writeplc(plc, "0");
                             }
                             if (plc == "771")
                             {
                                 Main.pMainWin.objPlc.Writeplc(plc, "0");
                             }
                             if (plc == "1527")
                             {
                                 Main.pMainWin.objPlc.Writeplc(plc, "0");
                             }
                             if (plc == "2283")
                             {
                                 Main.pMainWin.objPlc.Writeplc(plc, "0");
                             }
                             if (plc == "3039")
                             {
                                 Main.pMainWin.objPlc.Writeplc(plc, "0");
                             }
                             if (plc == "3795")
                             {
                                 Main.pMainWin.objPlc.Writeplc(plc, "0");
                             }
                             if (obj_device != null)
                             {
                                 if (obj_device.Tables["device"].Rows.Count > 0)
                                 {
                                     deviceno = obj_device.Tables["device"].Rows[0]["deviceno"].ToString();
                                     devname = obj_device.Tables["device"].Rows[0]["device"].ToString();
                                     disp =obj_device.Tables["device"].Rows[0]["typetext"].ToString();
                                     Main.pMainWin.fmainTcLbl(deviceno, devname, trans.ToString(), disp);
                                     Main.pMainWin.fmainTcLd(deviceno, devname, trans.ToString(), disp);
                                     Main.pMainWin.fmainTcLdem(deviceno, devname, trans.ToString(), disp);
                                     Main.pMainWin.fmainTcLB(deviceno, devname, trans.ToString(), disp);
                                 }
                             }
                           
                    }
                    else
                    {
                        String strItemErr;
                        pIOPCServer.GetErrorString(pErrors[0], LOCALE_ID, out strItemErr);
                       // MessageBox.Show(strItemErr,
                        //    "OnDataChange-Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(exp.Message,
                    "OnDataChange-Runtime Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        /// <summary>
        /// Callback IOPCDataCallback OnReadComplete event handler implementation.
        /// This callback function is call by the opc server when async read is compleat.
        /// </summary>
        public virtual void OnReadComplete(System.Int32 dwTransid,
            System.Int32 hGroup,
            System.Int32 hrMasterquality,
            System.Int32 hrMastererror,
            System.Int32 dwCount,
            int[] phClientItems,
            object[] pvValues,
            short[] pwQualities,
            OpcRcw.Da.FILETIME[] pftTimeStamps,
            int[] pErrors)
        {
            try
            {
                if (pErrors[0] == 0)
                {
                    ThreadExceptionDialog.CheckForIllegalCrossThreadCalls = false;
                    // Value
                    //strAReadVal.Text = String.Format("{0}", pvValues[0]);
                    // Quality
                    //strAReadQuality.Text = GetQuality(pwQualities[0]);
                    // Timestamp
                   // DateTime dt = ToDateTime(pftTimeStamps[0]);
                    //strAReadTimeStp.Text = dt.ToString();
                    ThreadExceptionDialog.CheckForIllegalCrossThreadCalls = true;
                }
                else
                {
                    String strResult = "";
                    pIOPCServer.GetErrorString(pErrors[0], LOCALE_ID, out strResult);
                    MessageBox.Show(strResult,
                        "Result - OnReadCOmpleate", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(exp.Message,
                    "OnReadComplete-Runtime Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Callback IOPCDataCallback OnWriteComplete event handler implementation.
        /// This callback function is call by the opc server when async write is compleat.
        /// </summary>
        public virtual void OnWriteComplete(System.Int32 dwTransid,
            System.Int32 hGroup,
            System.Int32 hrMastererr,
            System.Int32 dwCount,
            int[] pClienthandles,
            int[] pErrors)
        {
            ThreadExceptionDialog.CheckForIllegalCrossThreadCalls = false;
            String strResult = "";
            pIOPCServer.GetErrorString(pErrors[0], LOCALE_ID, out strResult);
            //strWriteResult.Text = strResult;
         
            ThreadExceptionDialog.CheckForIllegalCrossThreadCalls = true;
            System.Exception ex = new Exception(strResult);
            throw ex;
        }
        /// <summary>
        /// Callback IOPCDataCallback OnCancelComplete event handler implementation.
        /// <summary>
        public virtual void OnCancelComplete(System.Int32 dwTransid, System.Int32 hGroup)
        {
            // Not implemented in this sample.
        }
        /// <summary>
        ///  On Loading.
        /// </summary>
        /// 
        public void WritePlc5(string device, string trans, string oth1,string oth2,string oth3)
        {
            MessageBox.Show(oth1);
            return;
            int[] ItemSvrHandleArray_temp;
            int device_no;
            object[] itemValues = new object[1];
            int nCancelid;
            IntPtr pErrors = IntPtr.Zero;
            if (trans.Length != 30 && trans.Length != 18)
            {
                ls_IniFile.WriteLog("writeError" + device.ToString(), trans.ToString() + "dd" + trans.Length);
                return;
            }
            device_no = Convert.ToInt32(device);

            itemValues[0] = trans;
            ItemSvrHandleArray_temp = new int[1];
            ItemSvrHandleArray_temp[0] = ItemSvrHandleArray[device_no];
            itemValues[0] = trans;
            if (pIOPCAsyncIO2 != null)
            {
                try
                {   // Async write
                    pIOPCAsyncIO2.Write(1, ItemSvrHandleArray_temp, itemValues, 2, out nCancelid, out pErrors);
                    int[] errors = new int[5];
                    Marshal.Copy(pErrors, errors, 0, 1);
                    if (errors[4] != 0)
                    {
                        System.Exception ex = new Exception("Error in reading item");
                        throw ex;
                    }
                }
                catch (System.Exception error)
                {
                    MessageBox.Show(error.Message,
                        "Result-Async Read", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    // Free the unmanaged COM memory
                    if (pErrors != IntPtr.Zero)
                    {
                        Marshal.FreeCoTaskMem(pErrors);
                        pErrors = IntPtr.Zero;
                    }
                }
            }
        }
        public void Writeplc(string device, string trans)
        {
            int[] ItemSvrHandleArray_temp;
            int device_no;
            object[] itemValues = new object[1];
            int nCancelid;
            IntPtr pErrors = IntPtr.Zero;

            try
            {   // Async write
                device_no = Convert.ToInt32(device);

                itemValues[0] = trans;
                ItemSvrHandleArray_temp = new int[1];
                ItemSvrHandleArray_temp[0] = ItemSvrHandleArray[device_no];
                itemValues[0] = trans;
                if (pIOPCAsyncIO2 != null)
                {
                    pIOPCAsyncIO2.Write(1, ItemSvrHandleArray_temp, itemValues, 2, out nCancelid, out pErrors);
                    int[] errors = new int[5];
                    Marshal.Copy(pErrors, errors, 0, 1);
                    if (errors[4] != 0)
                    {
                        System.Exception ex = new Exception("Error in reading item");
                        throw ex;
                    }
                }
            }
            catch (System.Exception error)
            {
                MessageBox.Show(error.Message,
                    "Result-Async Read", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
                finally
                {
                    // Free the unmanaged COM memory
                    if (pErrors != IntPtr.Zero)
                    {
                        Marshal.FreeCoTaskMem(pErrors);
                        pErrors = IntPtr.Zero;
                    }
                }
        }
        public void Init()
        {  
            string file_name, file_work;
            IniFile ls_IniFile = new IniFile(Environment.CurrentDirectory + "\\log.ini");
            devnum = devicenum;
            file_work = ls_IniFile.ReadIniValue("Clear", "ClearWork");
            file_name = ls_IniFile.ReadIniValue("Clear", "ClearFile");
            System.Diagnostics.Process P = new System.Diagnostics.Process();
            P.StartInfo.FileName = file_name;
            P.StartInfo.WorkingDirectory = file_work;
            P.StartInfo.UseShellExecute = false;
            //P.StartInfo.RedirectStandardInput = true;
            P.StartInfo.RedirectStandardOutput = true;
            P.StartInfo.CreateNoWindow = true;
            P.Start();
            P.WaitForExit(6000);

            Control.CheckForIllegalCrossThreadCalls = false;
            objData.Clear();
            //ls_IniFile.DelFile();
            theSrv = new OpcServer();
            theSrv.Connect(serverProgID);
            Thread.Sleep(1500);                // we are faster then some servers!
            // add our only working group
            theGrp = theSrv.AddGroup("MyGroup", false, 200);

            // add two items and save server handles          
            for (int i = 0; i < devicenum; i ++)
            {
                objdevice[i] = ls_IniFile.ReadIniValue("device", i.ToString());

            }

            for (int i = 0; i < devicenum; i++)
            {
                itemDefs[i] = new OPCItemDef(objdevice[i], true, i + 1, VarEnum.VT_EMPTY);

            }

            OPCItemResult[] rItm;
            theGrp.AddItems(itemDefs, out rItm);

            if (rItm == null)
                return;


            for (int i = 0; i < devicenum; i++)
            {
                handlesSrv[i] = rItm[i].HandleServer;

            }
            // asynch read our two items
            try
            {
                theGrp.SetEnable(true);
                
               
                theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete);
                int CancelID;
                int[] aE;
                theGrp.Read(handlesSrv, 55667788, out CancelID, out aE);
                Thread.Sleep(1500);
                // asynch write
                object[] itemValues = new object[devicenum];
                theGrp.Write(handlesSrv, itemValues, 99887766, out CancelID, out aE);
                theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete);
                
                // some delay for asynch write-complete callback (simplification)
                Thread.Sleep(1500);
                theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange); 
                theGrp.Active = true;
            }
            catch (Exception e)
            {

                ls_IniFile.WriteLog("eee", e.ToString());
            }
        }
        public void Close()
        {
           

            if (theGrp != null)
            {
                theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange);
                theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete);
                theGrp.Remove(false);
                theGrp = null;
            }

            if (theSrv != null)
            {
                theSrv.Disconnect();
                theSrv = null;
            }
        }
        public void initerrormsg()
        {

        }
        public void Writeplc1(string device, string trans)
        {
            int device_no;
            object[] itemValues = new object[devicenum];
            int CancelID;
            int[] aE;
            device_no = Convert.ToInt32(device);
            for (int j = 0; j < devicenum; j++)
            { 
                itemValues[j] = null;
            }
            itemValues[device_no-1] = trans;
            theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete);
            theGrp.Write(handlesSrv, itemValues, 99887766, out CancelID, out aE);
        }
        public void theGrp_DataChange(object sender, DataChangeEventArgs e)
        {
            object[] itemValues = new object[devicenum];
            string trans = "";

            foreach (OPCItemState s in e.sts)
            {
                if (HRESULTS.Succeeded(s.Error))
                {                     
                    trans = s.DataValue.ToString();                    
                    ls_IniFile.WriteLog("All", s.DataValue.ToString());
                 
                }
                ;
            }
        }
        public void theGrp_ReadComplete(object sender, ReadCompleteEventArgs e)
        {
            //Console.WriteLine("ReadComplete event: gh={0} id={1} me={2} mq={3}", e.groupHandleClient, e.transactionID, e.masterError, e.masterQuality );
            foreach (OPCItemState s in e.sts)
            {
                if (HRESULTS.Succeeded(s.Error))
                { 
                }
                else
                {
                    ls_IniFile.WriteLog("OpcErrorRead", s.HandleClient.ToString()+"ddd"+s.Error.ToString()+"dd"+e.masterError.ToString()); 
                }
            }
        }
        public void theGrp_WriteComplete(object sender, WriteCompleteEventArgs e)
        {
            //Console.WriteLine("WriteComplete event: gh={0} id={1} me={2}", e.groupHandleClient, e.transactionID, e.masterError );
            foreach (OPCWriteResult r in e.res)
            {

                if (HRESULTS.Succeeded(r.Error))
                {
                   //ls_IniFile.WriteLog("OpcWrite",r.ToString());
                }
                else
                {
                    ls_IniFile.WriteLog("OpcErrorWrite", r.Error.ToString());
                }
                //Console.WriteLine(" ih={0}    ERROR=0x{1:x} !", r.HandleClient, r.Error );
            }
        }


    }
}

欢迎大家一起交流,一起进步,我的mail meslog@qq.com或qq 1153755352

 

自动立体车库控制应用系统

标签:

原文地址:http://www.cnblogs.com/meslog/p/5164335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!