<sup id="6iiqm"><wbr id="6iiqm"></wbr></sup>
<sup id="6iiqm"><noscript id="6iiqm"></noscript></sup>
<sup id="6iiqm"><noscript id="6iiqm"></noscript></sup><sup id="6iiqm"><wbr id="6iiqm"></wbr></sup>
咨詢熱線

18621916738

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

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

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

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

1、 配置OPC服務(wù)器
  對于服務(wù)器的配置與同步通訊的配置一樣,這里不需再講解,若有不清楚的,可以參閱之前發(fā)布的<運(yùn)用VC#編程通過OPC方式實現(xiàn)PC機(jī)與西門子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)的組中的變量進(jìn)行監(jiān)控,同時這也是很有必要的,因為我們可以把不同界面中的變量編程不同的組,即同一界面中的變量規(guī)成一個組,而在某一時刻提供給用戶的只有一個界面,讓該界面中用到的組處于活動狀態(tài),這樣執(zhí)行委托調(diào)用時只會執(zhí)行于該界面中有關(guān)的變量檢測,而如果讓所有的組處于活動狀態(tài),則當(dāng)前沒有顯示給用戶的界面用到的變量若發(fā)生變化也會觸發(fā)對委托函數(shù)的調(diào)用,這根本是沒有必要的,同時會大大降低程序的性能,請嚴(yán)格控制組的激活。
///
/// 激活或者取消激活組
/// 
/// 組名
/// 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)站二維碼

寂寞的儿媳妇高清电影,久久99精品久久久久久水蜜桃,亚洲一区二区三区女厕偷拍,亚洲精品久久久久中文字幕二区
双辽市| 泰安市| 淄博市| 合江县| 新民市| 崇左市| 陆河县| 盐城市| 宜州市| 靖宇县| 大田县| 固安县| 绥中县| 稷山县| 木里| 大邑县| 台江县| 屯昌县| 黔江区| 清流县| 淳化县| 杨浦区| 柳州市| 兴和县| 泽州县| 呼伦贝尔市| 甘谷县| 景东| 定结县| 谷城县| 海口市| 凌源市| 马尔康县| 威远县| 定兴县| 固始县| 贞丰县| 贵定县| 蓬溪县| 德保县| 南雄市| http://www.h0080.com http://www.52a1.com http://www.zhg9.com http://www.8sff.com http://www.fzahaj.com http://www.17wds.com