咨詢熱線

        18621916738

        當(dāng)前位置:首頁  >  技術(shù)文章  >  運用VC#編程通過OPC方式實現(xiàn)PC機與西門子PLC通訊

        運用VC#編程通過OPC方式實現(xiàn)PC機與西門子PLC通訊

        更新時間:2016-01-06      點擊次數(shù):1607

        運用VC#編程通過OPC方式實現(xiàn)PC機與西門子PLC通訊

        1、 配置OPC服務(wù)器
          對于服務(wù)器的配置與同步通訊的配置一樣,這里不需再講解,若有不清楚的,可以參閱之前發(fā)布的<運用VC#編程通過OPC方式實現(xiàn)PC機與西門子PLC通訊>

        2、 OPC編程
          變量組、項的命名規(guī)則與同步通訊的一樣,這里不再描敘,下面主要就開發(fā)一個異步通訊類 AsynServer來講解如何編程。

        <1>、引用
          在VC#開發(fā)環(huán)境中添加對OpcRcw.Da庫以及OpcRcw.Comn庫的引用,該庫屬于.NET庫,不屬于COM庫,西門子雖然編寫了類庫,以提供對.NET平臺的支持,但這些類庫仍然難于編程,里面包含了大量的在托管和非托管區(qū)傳輸數(shù)據(jù),因此我們需要在它的基礎(chǔ)上再開發(fā)一個類庫,以簡化以后的編程,首先在類的開頭使用命名空間:
        using OpcRcw.Comn;
        using OpcRcw.Da;
        using System.Runtime.InteropServices;
        using System.Collections;

        <2>、編程
          異步編程的原理就是在OPC服務(wù)器那邊檢測當(dāng)前活動的變量組,一但檢測到某一個變量,譬如變量Q0.0從1變成0,就會執(zhí)行一個回調(diào)函數(shù),以實現(xiàn)針對變量發(fā)生變化時需要實現(xiàn)的動作,在這里可以采用委托來實現(xiàn)該功能。

          1、 在命名空間的內(nèi)部、類 AsynServer聲明之前添加委托的申明:
        // 定義用于返回發(fā)生變化的項的值和其對應(yīng)的客戶句柄
        public delegate void DataChange(object[] values,int[] itemsID);

          2、 該類繼承于西門子提供的庫接口IOPCDataCallback
        public class AsynServer:IOPCDataCallback
        在類的開頭部分聲明變量:
        struct groupStru
        {
        public int groupID;
        public object groupObj;
        }
        internal const int LOCALE_ID = 0x407; //本地語言
        private Guid iidRequiredInterface;
        private string serverType="";
        private int hClientGroup = 0; //客戶組號
        private int nSvrGroupID; // server group handle for the added group 
        private Hashtable hashGroup; //用于把組收集到一起
        private int hClientItem=0; //Item號

           3、編寫構(gòu)造函數(shù),接收委托參數(shù)已確定當(dāng)數(shù)據(jù)發(fā)生變化時需要執(zhí)行的方法入口點:
        //創(chuàng)建服務(wù)器
        //svrType 服務(wù)器類型的枚舉
        //dataChange 提供用于在數(shù)據(jù)發(fā)生變化時需要執(zhí)行的函數(shù)入口
        public AsynServer(ServerType svrType,DataChange dataChange)
        {
        switch(svrType)
        {
        case ServerType.OPC_SimaticHMI_PTPR
        serverType="OPC.SimaticHMI.PTPro";break;
        case ServerType.OPC_SimaticNET:
        serverType="OPC.SimaticNET";break;
        case ServerType.OPC_SimaticNET_DP:
        serverType="OPC.SimaticNET.DP";break;
        case ServerType.OPC_SimaticNET_PD:
        serverType="OPC.SimaticNET.PD";break;
        case ServerType.OPCServer_WinCC:
        serverType="OPCServer.WinCC";break;

        }
        hashGroup=new Hashtable(11);
        dtChange=dataChange;
        }
          
          4、創(chuàng)建服務(wù)器
        // 創(chuàng)建一個OPC Server接口
        //error 返回錯誤信息
        //若為true,創(chuàng)建成功,否則創(chuàng)建失敗
        public bool Open(out string error)
        {
        error="";bool success=true;
        Type svrComponenttyp ;
        //獲取 OPC Server COM 接口
        iidRequiredInterface = typeof(IOPCItemMgt).GUID;
        svrComponenttyp = System.Type.GetTypeFromProgID(serverType);
        try
        {
        //創(chuàng)建接口
        pIOPCServer =(IOPCServer)System.Activator.CreateInstance(svrComponenttyp);
        error="";
        }
        catch (System.Exception err) //捕捉失敗信息
        {
        error="錯誤信息:"+err.Message;success=false;
        }
        return success;
        }

          5、 編寫添加Group的函數(shù)
        ///


        /// 添加組
        /// 
        /// 組名
        /// /創(chuàng)建時,組是否被激活
        /// //組的刷新頻率,以ms為單位
        /// 返回錯誤信息
        /// 若為true,添加成功,否則添加失敗
        public bool AddGroup(string groupName,int bActive,int updateRate,out string error)

        error="";bool success=true;
        int dwLCID = 0x407; //本地語言為英語 
        int pRevUpdateRate;
        float deadband = 0;
        // 處理非托管COM內(nèi)存
        GCHandle hDeadband;
        IntPtr pTimeBias = IntPtr.Zero;
        hDeadband = GCHandle.Alloc(deadband,GCHandleType.Pinned);
        try
        {
        pIOPCServer.AddGroup(groupName, //組名
        bActive, //創(chuàng)建時,組是否被激活
        updateRate, //組的刷新頻率,以ms為單位
        hClientGroup, //客戶號
        pTimeBias, //這里不使用
        (IntPtr)hDeadband,
        dwLCID, //本地語言
        out nSvrGroupID, //移去組時,用到的組ID號
        out pRevUpdateRate, //返回組中的變量改變時的zui短通知時間間隔
        ref iidRequiredInterface,
        out pobjGroup1); //指向要求的接口
        hClientGroup=hClientGroup+1; 
        groupStru grp=new groupStru();
        grp.groupID=nSvrGroupID;grp.groupObj=pobjGroup1;
        this.hashGroup.Add(groupName,grp);//儲存組信息
        // 對異步操作設(shè)置回調(diào),初始化接口
        pIConnectionPointContainer = (IConnectionPointContainer)pobjGroup1;
        Guid iid = typeof(IOPCDataCallback).GUID;
        pIConnectionPointContainer.FindConnectionPoint(ref iid,out pIConnectionPoint);
        pIConnectionPoint.Advise(this,out dwCookie);
        }
        catch (System.Exception err) //捕捉失敗信息
        {
        error="錯誤信息:"+err.Message;success=false;
        }
        finally
        {
        if (hDeadband.IsAllocated) hDeadband.Free();
        }
        return success;
        }

          6、 編寫激活、或者取消激活組的函數(shù)

          在同步編程中對于組的激活或者取消激活沒有實質(zhì)的意義,但在異步通訊編程中卻異常重要,這是因為OPC服務(wù)器只對當(dāng)前處于活動狀態(tài)的組中的變量進行監(jiān)控,同時這也是很有必要的,因為我們可以把不同界面中的變量編程不同的組,即同一界面中的變量規(guī)成一個組,而在某一時刻提供給用戶的只有一個界面,讓該界面中用到的組處于活動狀態(tài),這樣執(zhí)行委托調(diào)用時只會執(zhí)行于該界面中有關(guān)的變量檢測,而如果讓所有的組處于活動狀態(tài),則當(dāng)前沒有顯示給用戶的界面用到的變量若發(fā)生變化也會觸發(fā)對委托函數(shù)的調(diào)用,這根本是沒有必要的,同時會大大降低程序的性能,請嚴格控制組的激活。
        ///
        /// 激活或者取消激活組
        /// 
        /// 組名
        /// true為激活,false為取消激活
        /// 若有錯誤,返回錯誤信息
        /// 若為true,添加成功,否則添加失敗
        public bool AciveGroup(string groupName,bool toActive,out string error)
        {
        error="";bool success=true;
        //通過名稱獲取組
        object grp=((groupStru)hashGroup[groupName]).groupObj;
        IOPCGroupStateMgt groupStateMgt=(IOPCGroupStateMgt)grp;
        //初始化傳遞參數(shù)
        IntPtr pRequestedUpdateRate = IntPtr.Zero; //由客戶的Item更新間隔時間
        int nRevUpdateRate = 0; //由服務(wù)器返回的能夠更新的zui短時間間隔
        IntPtr hClientGroup = IntPtr.Zero; //客戶組
        IntPtr pTimeBias = IntPtr.Zero;
        IntPtr pDeadband = IntPtr.Zero;
        IntPtr pLCID = IntPtr.Zero; 

        // 激活或者取消激活組
        int nActive = 0; 
        GCHandle hActive = GCHandle.Alloc(nActive,GCHandleType.Pinned);
        if(toActive)
        hActive.Target = 1;
        else
        hActive.Target = 0;
        try 
        {
        groupStateMgt.SetState(pRequestedUpdateRate,out nRevUpdateRate,hActive.AddrOfPinnedObject(),pTimeBias,pDeadband,pLCID,hClientGroup); 
        }
        catch(System.Exception err)
        {
        error="錯誤信息:"+err.Message;success=false;
        }
        finally
        {
        hActive.Free(); 
        }
        return success;
        }

        7、 向的組中添加變量的函數(shù)
        ///
        /// 向的組添加一系列項
        /// 
        /// 組名
        /// 完整的item名數(shù)組
        /// 由服務(wù)器返回讀寫數(shù)據(jù)時需要使用的item號
        /// 無錯誤,返回true,否則返回false
        public bool AddItems(string groupName,string[] iteame,int[] itemsID)
        {
        bool success=true;
        OPCITEMDEF[] ItemDefArray=new OPCITEMDEF[iteame.Length];
        for(int i=0;i {
        hClientItem=hClientItem+1; //客戶項自動加1
        ItemDefArray[i].szAccessPath = ""; // 可選的通道路徑,對于Simatiic Net不需要。
        ItemDefArray[i].szItemID = iteame[i]; // ItemID, see above
        ItemDefArray[i].bActive = 1; // item is active
        ItemDefArray[i].hClient = hClientItem; // client handle ,在OnDataChange中會用到
        ItemDefArray[i].dwBlobSize = 0; // blob size
        ItemDefArray[i].pBlob = IntPtr.Zero; // pointer to blob 
        ItemDefArray[i].vtRequestedDataType = 4; //DWord數(shù)據(jù)類型
        }
        //初始化輸出參數(shù)
        IntPtr pResults = IntPtr.Zero;
        IntPtr pErrors = IntPtr.Zero;
        try 
        {
        // 添加項到組
        object grp=((groupStru)hashGroup[groupName]).groupObj;
        ((IOPCItemMgt)grp).AddItems(iteame.Length,ItemDefArray,out pResults,out pErrors);

        int[] errors = new int[iteame.Length]; 
        IntPtr pos = pResults;
        Marshal.Copy(pErrors, errors, 0,iteame.Length);
        for(int i=0;i {
        if (errors[i] == 0)
        {
        OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
        itemsID[i] = result.hServer; 
        pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
        }
        else
        {
        String pstrError;
        pIOPCServer.GetErrorString(errors[0],0x407,out pstrError); 
        success=false;
        break;
        }
        }
        SetItenClient(groupName,itemsID,itemsID); //要求始終只有一個組被激活,才不會引起沖突。
        }
        catch (System.Exception err) // catch for error in adding items.
        {
        success=false;
        //error="錯誤信息:"+error+err.Message;
        }
        finally
        {
        // 釋放非托管內(nèi)存
        if(pResults != IntPtr.Zero)
        {
        Marshal.FreeCoTaskMem(pResults);
        pResults = IntPtr.Zero;
        }
        if(pErrors != IntPtr.Zero)
        {
        Marshal.FreeCoTaskMem(pErrors);
        pErrors = IntPtr.Zero; 
        }
        }
        return success;
        }

        聯(lián)系我們

        上海翰粵自動化系統(tǒng)有限公司 公司地址:上海市松江區(qū)思賢路2399弄137號   技術(shù)支持:化工儀器網(wǎng)
        • 聯(lián)系人:黃政武
        • QQ:76868608
        • 公司傳真:021-57657276
        • 郵箱:76868608@qq.com

        掃一掃 更多精彩

        微信二維碼

        網(wǎng)站二維碼

        五级黄无遮挡免费看| 亚洲AV无码久久精品狠狠爱浪潮 | 亚洲精品福利视频| 国产成人精品久久一区二区三区av | 老汉精品免费AV在线播放| 又爽又黄又无遮挡的视频| 三级在线免费观看| 四虎国产成人永久精品免费| 2022年国产精品久久久久| 国产精品99在线播放| 影音先锋能看的网站| 国内精品久久久久伊人av| 国产成人久久久精品二区三区| 亚洲精品综合久久| 国产精品v片在线观看不卡 | 合区精品中文字幕| 国产精品国产三级国产av品爱网| 国产A级毛片久久久精品毛片| 中文字幕在线永久在线视频2020 | 国产精品岛国久久久久| 久久久精品人妻无码专区不卡| 男人把女人捅爽视频| 在线精品亚洲| 国产成人精品手机在线观看| 99热这里只有精品国产66| 影音先锋色先锋资源在线| 免费视频精品一区二区三区| 欧美精品亚洲精品日韩精品| 久久99国产综合精品女同| 国产精品色视频ⅹxxx | 亚洲国产精品人久久| 亚洲美女自拍视频| 日韩精品一区二区三区四区| 日韩午夜高清福利片在线观看欧美亚洲精品suv | 精品人妻人人做人人爽| 国产精品视频不卡| 精品人妻中文av一区二区三区| 精品国产婷婷久久久| 国产精品日韩AV在线播放 | 色婷婷在线精品国自产拍| 国产精品污WWW一区二区三区|