c#调用OPC自动化接口同步访问西门子PLC

 1 class OpcManager
 2     {
 3         OPCServer Server = new OPCServer();
 4         OPCGroup Group;
 5         public OPCItem Item1;
 6 
 7         public string Start()
 8         {
 9             try
10             {                
11                 Server.Connect("OPC.SimaticNet");
12                 Group = Server.OPCGroups.Add("Group1");
13                 Group.IsActive = true;              
14                 Item1 = Group.OPCItems.AddItem("S7:[S7_Connection_1]QX0.1", 1);               
15                 return "ok";                                              
16             }
17             catch (System.Exception ex)
18             {
19                 return ex.Message;
20             }           
21         }
22 
23         public void Write(OPCItem Item, object Value)
24         {
25             try
26             {
27                 Item.Write(Value);
28             }
29             catch (System.Exception ex)
30             {
31                 MessageBox.Show(ex.Message, "Error - OpcManager", MessageBoxButtons.OK, MessageBoxIcon.Error);
32             }    
33         }    
34 
35         public void Read(OPCItem Item,out object Value,out object Quality,out object TimeStamp)
36         {
37             try
38             {
39                 Item.Read(1, out Value, out Quality, out TimeStamp);
40             }
41             catch (System.Exception ex)
42             {
43                 Value = "";
44                 Quality = "";
45                 TimeStamp = "";
46                 MessageBox.Show(ex.Message, "Error - OpcManager", MessageBoxButtons.OK, MessageBoxIcon.Error);
47             }  
48         }
49 
50         public void Disconnect()
51         {
52             try
53             {
54                 if (Item1 != null) Item1 = null;
55                 if (Group != null) Group = null;
56                 Server.Disconnect();
57             }
58             catch (System.Exception error)
59             {
60                 MessageBox.Show(error.Message, "Error - OpcManager", MessageBoxButtons.OK,MessageBoxIcon.Error);
61             }
62         }
63     }

猜你喜欢

转载自www.cnblogs.com/ljsoftware/p/8371556.html