/// <summary> /// 写入值 /// </summary> /// <param name="group"></param> public override bool SyncWrite(OPCGroup group) { /// 写入条码信息 int[] SyncItemServerHandles = new int[2]; object[] SyncItemValues = new object[2]; Array SyncItemServerErrors; // 条码 index 是2 SyncItemServerHandles[1] = (int)this.ItemServerHandles.GetValue(2); // OPCItem AnOpcItem = group.OPCItems.GetOPCItem((int)this.ItemServerHandles.GetValue(2)); SyncItemValues[1] = this.ScanGetInposiBarcode; group.SyncWrite(1, SyncItemServerHandles, SyncItemValues, out SyncItemServerErrors); if (SyncItemServerErrors != null && ((int)SyncItemServerErrors.GetValue(1) == 0)) { if (this.SyncSetReadableFlag(group)) { return(true); } } else { this.ScanGetInposiBarcode = this.ScanGetInposiBarcodeWas; } return(false); }
public OPCGroup AddGroup(string groupName, int updateRate) { OPCGroup opcGroup = new OPCGroup(this, groupName, updateRate); this.AddGroup(opcGroup); this.groups.Add(groupName, opcGroup); return opcGroup; }
public void Activate() { if (IsActive) { throw new OpcValueException("Двойная активация OPC тега: " + Name); } if (string.IsNullOrEmpty(Name)) { throw new OpcValueException("Имя OPC параметра не задано."); } if (server.ServerState != (int)OPCServerState.OPCRunning) { throw new OpcValueException( "Ошибка при активации тега: OPC сервер не подключен."); } GroupName = Guid.NewGuid().ToString(); opcGroup = server.OPCGroups.Add(GroupName); opcItem = opcGroup.OPCItems.AddItem(Name, opcGroup.ClientHandle); if (isListenValueChanging) { opcGroup.DataChange += ValueChanged; opcGroup.UpdateRate = UpdateRate; opcGroup.IsActive = true; opcGroup.IsSubscribed = true; } IsActive = true; }
////组名 private static bool readgroup() { try { if (connected == true && groupadd == false) { opc_group = OPC_server.OPCGroups.Add("First one"); opc_group.IsActive = true; opc_group.IsSubscribed = false; opc_group.DeadBand = 0; opc_group.UpdateRate = 10; int i = 0; foreach (var a in allitem) { i++; opc_group.OPCItems.AddItem((string)a, i); } groupadd = true; return(true); } return(false); } catch (Exception ex) { connected = false; groupadd = false; MessageBox.Show("写入标签列表失败\n" + ex.Message); return(false); } }
/// <summary> /// 设置组的属性 /// </summary> /// <param name="opcGroup"></param> /// <param name="updateRate"></param> private void SetGroupProperty(OPCGroup opcGroup, int updateRate) { opcGroup.IsActive = true; opcGroup.DeadBand = 0; opcGroup.UpdateRate = updateRate; opcGroup.IsSubscribed = true; }
private void CommForm_Load(object sender, EventArgs e) { //1读服务器与地址值 this.ReadAddress(); try { //2连接OPC MyOpcServer = new OPCServer(); MyOpcServer.Connect("OPC.SimaticNet", dtAddress.Rows[0]["Item"].ToString().Trim());//服务器名或者IP地址 //MyOpcServer.Connect("OPCServer.WinCC", "192.168.1.12");//服务器名或者IP地址 MyOpcGroup = MyOpcServer.OPCGroups.Add("MyGroup1"); { MyOpcServer.OPCGroups.DefaultGroupIsActive = true; //激活组 MyOpcServer.OPCGroups.DefaultGroupDeadband = 0; //死区值,设为0 MyOpcServer.OPCGroups.DefaultGroupUpdateRate = 1000; //默认族群的刷新频率为200ms MyOpcGroup.UpdateRate = 100; // MyOpcGroup.IsSubscribed = true; // 使用订阅功能,可以异步,默认为false } } catch (Exception ex) { Common.RecordCommLog(ex); } //3添加地址值 this.AddGroupItems(); //值改变出发的动作 // MyGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); }
/// <summary> /// 设置服务器和客户端的句柄对应的点位名 /// 将点位集合存入对应的服务器和客户端的句柄 /// </summary> /// <param name="bindingData">点位集合</param> /// <param name="opcItems"></param> /// <param name="opcGroup"></param> /// <param name="dic">客户端句柄点位字典</param> /// <param name="serviceDic">服务器句柄点位字典</param> public void SetServerHandle(List <OpcData> bindingData, OPCItems opcItems, OPCGroup opcGroup, Dictionary <int, string> dic, Dictionary <int, string> serviceDic) { for (int i = 0; i < bindingData.Count; i++) { try { OPCItem item = opcItems.AddItem(bindingData[i].OpcName, i); if (item != null) { dic.Add(item.ClientHandle, bindingData[i].OpcName); serviceDic.Add(item.ServerHandle, bindingData[i].OpcName); } } catch (Exception e) { throw; } foreach (KeyValuePair <int, string> keyValuePair in serviceDic) { try { ReadOpcValue(keyValuePair.Key, opcItems, opcGroup, bindingData, serviceDic); } catch (Exception e) { // ignored } } } }
/// <summary> /// 卸载数据改变事件 /// </summary> /// <param name="opcGroup">OPCGroup卸载DataChange事件</param> public void RemoveDataChangeEvent(OPCGroup opcGroup, ReadDataEventHandler eventHandler) { if (opcGroup != null) { opcGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(eventHandler); } }
//连接 private void buttonConnect_Click(object sender, EventArgs e) { lock (lockobj) { if (OPCServer == null) { OPCServer = new OPCServer(); } if (OPCServer.ServerState == (int)OPCServerState.OPCRunning) { return; } OPCServer.Connect((string)jo["OPCServerName"]); int i = 1; foreach (KeyValuePair <string, JToken> kvp in (JObject)jo["Groups"]) { OPCGroup G = OPCServer.OPCGroups.Add(kvp.Key); G.UpdateRate = 10000; G.IsActive = false; G.IsSubscribed = false; foreach (KeyValuePair <string, JToken> kvpp in (JObject)kvp.Value) { //OPCItem oItem = G.OPCItems.AddItem((string)kvpp.Value, i); i++; //LocalOPCItems.Add(kvp.Key + "_" + kvpp.Key, oItem); } } string[] items = LocalOPCItems.Keys.ToArray <string>(); listBox1.Items.AddRange(items); } }
/// <summary> /// 初始化OPCGroups和OPCItems /// </summary> /// <param name="opcGroups">OPCGroups对象</param> /// <param name="GroupName">自定义组名字</param> /// <param name="opcGroup">OPCGroup对象</param> /// <param name="opcItems">OPCItems对象</param> /// <param name="groupPropertiesModel">GroupPropertiesModel对象</param> public void SetGroupsAndItems(out OPCGroups opcGroups, string GroupName, out OPCGroup opcGroup, out OPCItems opcItems, GroupPropertiesModel groupPropertiesModel) { opcGroups = _opcSerialInfo.OpcServer.OPCGroups; opcGroup = opcGroups.Add(GroupName); SetGroupProperty(opcGroup, groupPropertiesModel); opcItems = opcGroup.OPCItems; }
public ServerController(ISoftwareController p_SoftwareController, AbstractViewFactory p_Factory, string p_MachineName, string p_ServerID) { m_SoftwareController = p_SoftwareController; m_ServerModel = new ServerModel(); m_ServerView = p_Factory.CreateServerView(this, p_ServerID); m_ServerModel.ModelChanged += new ModelChangeEventHandler(m_ServerView.ServerModelChange); m_MachineName = p_MachineName; m_ServerID = p_ServerID; string[] ID_Spilts = p_ServerID.Split(new char[] { '.' }); if (ID_Spilts[0] == "Veriteq") { VeriteqOPCServer = true; System.Console.WriteLine("Connect to a Veriteq Server\n"); } m_DescriptionDictionary = new Dictionary <string, string>(); m_UnitDictionary = new Dictionary <string, string>(); m_ItemAccessMutex = new Mutex(); m_Server = null; m_Group = null; }
//结束并断开opc server private void button4_Click(object sender, EventArgs e) { //释放所有组资源 if (null != objGroup) { objGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange); objGroup.AsyncWriteComplete -= new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(AsyncWriteComplete); objGroup = null; objServer.OPCGroups.RemoveAll(); } if (null != objServer) { objServer.Disconnect(); objServer = null; objItems = null; this.Data1.Text = "0"; this.Data2.Text = "0"; this.Data3.Text = State.ToString(); GC.Collect(); } //关闭kepserver进程,这个跟OPC操作无关 /* * foreach ( Process oneProcess in Process.GetProcesses()) * { * if (oneProcess.ProcessName == "ServerMain") * oneProcess.Kill(); * } */ }
/// <summary> /// 移除项,注意:此接口目前未能实现,需要继续调试 /// </summary> /// <param name="groupName"></param> /// <param name="itemName"></param> /// <param name="reStr"></param> /// <returns></returns> public bool RemoveItem(string groupName, string itemName, out string reStr) { reStr = ""; try { OPCGroup myGroup = GetGroup(groupName); if (myGroup == null) { reStr = "组:" + groupName + "不存在 "; return(false); } OPCItems items = myGroup.OPCItems; OPCItem item = items.Item(itemName); Array itemHandles = Array.CreateInstance(typeof(int), 1); itemHandles.SetValue(item.ServerHandle, 0); Array errors = null;// Array.CreateInstance(typeof(long), 10); items.Remove((int)1, ref itemHandles, out errors); reStr = "移除项:" + itemName + "成功!"; return(true); } catch (System.Exception ex) { reStr = "移除项:" + itemName + "失败,返回异常:" + ex.Message; return(false); } }
public bool Write(string groupName, string itemID, object val) { bool re = false; try { OPCGroup myGroup = myServer.OPCGroups.GetOPCGroup(groupName); if (myGroup == null) { return(false); } OPCItem myItem = myGroup.OPCItems.Item(itemID); if (myItem == null) { return(false); } myItem.Write(val); re = true; } catch (System.Exception ex) { re = false; } return(re); }
public bool AddItem(string groupName, string itemName, out string reStr) { reStr = ""; try { int itemHandle = 0; OPCGroup myGroup = GetGroup(groupName); if (myGroup == null) { reStr = "添加项:" + itemName + "失败,组名不存在"; return(false); } OPCItem item = myGroup.OPCItems.AddItem(itemName, itemHandle); if (item == null) { reStr = "添加项:" + itemName + "失败"; return(false); } reStr = groupName + " 添加项:" + itemName + "成功"; // Console.WriteLine(reStr); return(true); } catch (System.Exception ex) { reStr = groupName + "添加项:" + itemName + "失败,返回异常:" + ex.Message; return(false); } }
public bool GetItems(string groupName, out string[] itemNames, out string reStr) { reStr = ""; itemNames = null; try { OPCGroups myGroups = myServer.OPCGroups; if (myGroups == null) { reStr = "得到项列表失败,组名:" + groupName + "不存在"; return(false); } OPCGroup myGroup = myGroups.GetOPCGroup(groupName); if (myGroup == null) { reStr = "得到项列表失败"; return(false); } OPCItems items = myGroup.OPCItems; itemNames = new string[items.Count]; for (int i = 0; i < itemNames.Count(); i++) { itemNames[i] = items.Item(i + 1).ItemID; } reStr = "得到项列成功!"; return(true); } catch (System.Exception ex) { reStr = "得到项列表失败,返回异常:" + ex.Message; return(false); } }
public void initOPC() { KepServer = new OPCServer(); try { KepServer.Connect("KEPware.KEPServerEx.V6", ""); } catch (Exception err1) { KepServer.Connect("KEPware.KEPServerEx.V4", ""); } connected = true; try { KepGroups = KepServer.OPCGroups; KepGroup = KepGroups.Add("OPCDOTNETGROUP"); SetGroupProperty(); KepItems = KepGroup.OPCItems; } catch (Exception err) { string errtxt = "创建组出现错误:" + err.Message; Logger.logwrite(errtxt); Console.ReadKey(); Environment.Exit(0); } InitOPCItem(); }
private void frmMonitor_Load(object sender, EventArgs e) { Cranes.OnCrane += new CraneEventHandler(Monitor_OnCrane); //picCrane1.Parent = pictureBox1; //InitialP1 = picCrane1.Location; //picCrane1.BackColor = Color.Transparent; InitialP2 = picCar01.Location; picCar01.Parent = pictureBox1; picCar01.BackColor = Color.Transparent; InitialP3 = picCar02.Location; picCar02.Parent = pictureBox1; picCar02.BackColor = Color.Transparent; //InitialP4 = picCrane2.Location; //picCrane2.Parent = pictureBox1; //picCrane2.BackColor = Color.Transparent; AddDicKeyValue(); try { ServerInfo[] Servers = new MonitorConfig("Monitor.xml").Servers; Conveyors.OnConveyor += new ConveyorEventHandler(Monitor_OnConveyor); Cars.OnCar += new CarEventHandler(Monitor_OnCar); Miniloads.OnMiniload += new MiniloadEventHandler(Monitor_OnMiniload); for (int i = 0; i < Servers.Length; i++) { OPCServer opcServer = new OPCServer(Servers[i].Name); opcServer.Connect(Servers[i].ProgID, Servers[i].ServerName);// opcServer.Connect(config.ConnectionString); OPCGroup group = opcServer.AddGroup(Servers[i].GroupName, Servers[i].UpdateRate); foreach (ItemInfo item in Servers[i].Items) { group.AddItem(item.ItemName, item.OpcItemName, item.ClientHandler, item.IsActive); } if (Servers[i].Name == "TranLineServer") { opcServer.Groups.DefaultGroup.OnDataChanged += new OPCGroup.DataChangedEventHandler(Conveyor_OnDataChanged); } if (Servers[i].Name == "Car0101Server" || Servers[i].Name == "Car0102Server") { opcServer.Groups.DefaultGroup.OnDataChanged += new OPCGroup.DataChangedEventHandler(Car_OnDataChanged); } if (Servers[i].Name == "MiniloadServer") { opcServer.Groups.DefaultGroup.OnDataChanged += new OPCGroup.DataChangedEventHandler(Miniload_OnDataChanged); } } } catch (Exception ex) { Logger.Error(ex.Message); } //tmCrane1.Interval = 3000; //tmCrane1.Elapsed += new System.Timers.ElapsedEventHandler(tmCraneWorker1); //tmCrane1.Start(); }
/// <summary> /// 初始化OPC服务 /// </summary> public void connectOPC() { KepServer = new OPCServer(); try { if (type == 0) { // KepServer.Connect("OPC.SimaticNET", "192.168.48.232"); KepServer.Connect("KEPware.KEPServerEx.V6", "192.168.36.113"); } else if (type == 1) { KepServer.Connect("OPCServer.WinCC", "192.168.36.135"); } else if (type == 2) { KepServer.Connect("OPCServer.WinCC", "192.168.48.135"); } else if (type == 3) { KepServer.Connect("OPCServer.WinCC", "192.168.36.125"); } else if (type == 4) { KepServer.Connect("OPCServer.WinCC", "192.168.48.125"); } else if (type == 5) { //KepServer.Connect("KEPware.KEPServerEx.V5", "192.168.48.232"); KepServer.Connect("KEPware.KEPServerEx.V6", "192.168.48.233"); } opc_connected = true; KepGroups = KepServer.OPCGroups; KepGroup = KepGroups.Add("myGroup"); KepGroup.IsSubscribed = true; KepGroup.DataChange += Group_DataChange; KepEventGroup = KepGroups.Add("myEventGroup"); KepEventGroup.IsSubscribed = true; foreach (var item in listTag) { if (item.scanrate > 0) { OPCItem myItem = KepGroup.OPCItems.AddItem(item.name, item.id); myItem.ClientHandle = item.id; item.itmHandleServer = myItem.ServerHandle; } else { OPCItem myItem = KepEventGroup.OPCItems.AddItem(item.name, item.id); item.itmHandleServer = myItem.ServerHandle; } } } catch (Exception ex) { throw new Exception("初始化OPC服务时,出现错误:" + type + ex.ToString()); } }
/// <summary> /// 读取OPC的值 /// </summary> /// <param name="opcGroup">OPC组名</param> /// <param name="opcItem">OPC点名</param> /// <returns>OPC的值</returns> private string ReadOpc(OPCGroup opcGroup, string opcItem) { string result = ""; try { object value, quality, timestamp; opcGroup.OPCItems.Item(opcItem).Read(2, out value, out quality, out timestamp); if (value != null) { result = value.ToString(); } else { result = ""; } } catch (Exception ex) { // log.writeTxt(Application.StartupPath, ErrorLog.logType.ERRORLOG, "读取OPC失败(ReadOpc):opcItem=" + opcItem + ":" + ex.Message); //throw new Exception("读取OPC失败(ReadOpc):opcItem=" + opcItem + " :" + ex.Message); } return(result); }
//创建组 private bool CreateGroup() { try { MyGroups = MyServer.OPCGroups; MyGroup = MyServer.OPCGroups.Add("测试"); //添加组 MyGroup2 = MyGroups.Add("测试2"); OPCGroup MyGroup3 = MyGroups.Add("测试3"); //测试删除组 //以下设置组属性 { MyServer.OPCGroups.DefaultGroupIsActive = true; //激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0; // 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyServer.OPCGroups.DefaultGroupUpdateRate = 200; //默认组群的刷新频率为200ms MyGroup.UpdateRate = 100; //刷新频率为1秒。 MyGroup.IsSubscribed = true; //使用订阅功能,即可以异步,默认false } MyGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); MyGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); MyGroup.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(GroupAsyncReadComplete); //由于MyGroup2.IsSubscribed是false,即没有订阅,所以以下的DataChange回调事件不会发生! MyGroup2.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange2); MyGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); MyServer.OPCGroups.Remove("测试3"); //移除组 AddGroupItems(); //设置组内items } catch (Exception err) { Console.WriteLine("创建组出现错误:{0}", err.Message); return(false); } return(true); }
protected override void OnStop() { try { //释放所有组资源 if (null != objGroup) { objGroup.DataChange -= new DIOPCGroupEvent_DataChangeEventHandler(KepGroup_DataChange); objGroup.AsyncWriteComplete -= new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(AsyncWriteComplete); objGroup = null; objServer.OPCGroups.RemoveAll(); SystemLogs.InsertPLCLog("Order2PLC", "释放所有组资源!"); } if (null != objServer) { objServer.Disconnect(); objServer = null; objItems = null; GC.Collect(); SystemLogs.InsertPLCLog("Order2PLC", "断开连接OPC释放所有组资源!"); } } catch (Exception ex) { SystemLogs.InsertPLCLog("Order2PLC", ex.Message); } }
public override OPCGroup.OPCGroupStatisticsInternal GetGroupStatistics(uint Identifier) { OPCGroup stats = OPCGroup.GroupList[Identifier]; stats.UpdateInternals(); return(stats.StatisticsInternal); }
void runme() { int[] ServerHandle = new int[2]; // const int READASYNC_ID = 1; const int WRITEASYNC_ID = 2; MyOpcServer = new OPCServer(); MyOpcServer.Connect("Kepware.KEPServerEX.V6", "127.0.0.1"); groups = MyOpcServer.OPCGroups; MyOpcGroup = MyOpcServer.OPCGroups.Add("MyGroup1"); MyOpcGroup.IsActive = true; MyOpcGroup.IsSubscribed = true; MyOpcGroup.DeadBand = 0; MyOpcGroup.UpdateRate = 1000; MyOpcItem1 = MyOpcGroup.OPCItems.AddItem("通道 1.设备 1.标记 1", 0); MyOpcItem2 = MyOpcGroup.OPCItems.AddItem("通道 1.设备 1.TAG1", 1); ServerHandle[0] = MyOpcItem1.ServerHandle; ServerHandle[1] = MyOpcItem2.ServerHandle; MyOpcGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(MyOpcGroup_AsyncWriteComplete); MyOpcGroup.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(MyOpcGroup_AsyncReadComplete); MyOpcGroup.AsyncCancelComplete += new DIOPCGroupEvent_AsyncCancelCompleteEventHandler(MyOpcGroup_AsyncCancelComplete); MyOpcGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(MyOpcGroup_DataChange); }
public void setTags(string[] oTagsNames) { this.nOPCItemsCount = 0; try { if ((this.bConnect) && (oTagsNames.Length > 0)) { oOpcGroupNames = oOPCServer.OPCGroups.Add("Group01"); oOpcGroupNames.DeadBand = 0; oOpcGroupNames.UpdateRate = 100; oOpcGroupNames.IsSubscribed = true; oOpcGroupNames.IsActive = true; foreach (string oTagName in oTagsNames) { oOPCItemIDs.SetValue(oTagName, (this.nOPCItemsCount + 1)); this.nOPCItemsCount++; } oOpcGroupNames.OPCItems.AddItems(this.nOPCItemsCount, ref oOPCItemIDs, ref oClientHandles, out oItemServerHandles, out oItemServerErrors, oRequestedDataTypes, oAccessPaths); } } catch (Exception) { } }
public static OPCGroup CreateGroup(OPCServer opcServer, OPCItems opcItems, string opcGroupName, GroupProperty groupProperty) { try { OPCGroup opcGroup = opcServer.OPCGroups.Add(opcGroupName); opcServer.OPCGroups.DefaultGroupIsActive = groupProperty.DefaultGroupIsActive; opcServer.OPCGroups.DefaultGroupDeadband = groupProperty.DefaultGroupDeadband; opcGroup.UpdateRate = groupProperty.UpdateRate; opcGroup.IsActive = groupProperty.IsActive; opcGroup.IsSubscribed = groupProperty.IsSubscribed; //opcGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OpcGroupDataChange); //opcGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete); //opcItems = opcGroup.OPCItems; return(opcGroup); } catch (Exception err) { throw err; } }
public OPCGroup CreateGroup(OPCServer opcServer, string opcGroupName) { try { //opcServer.OPCGroups.DefaultGroupIsActive = true; //opcServer.OPCGroups.DefaultGroupDeadband = 0; //opcServer.OPCGroups.DefaultGroupUpdateRate = 1000; KepGroups = opcServer.OPCGroups; KepGroup = KepGroups.Add(opcGroupName); KepGroup.IsActive = true; KepGroup.DeadBand = 0; KepGroup.UpdateRate = 1000; KepGroup.IsSubscribed = true; //KepGroup.AsyncReadComplete += KepGroup_AsyncReadComplete; KepGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OpcGroup_DataChange); KepGroup.IsActive = true; KepGroup.IsSubscribed = true; //AsyncRead(); return(KepGroup); } catch (Exception ex) { SimpleLogHelper.Instance.WriteLog(LogType.Error, ex); return(null); } }
public OPCGroup CreateGroup(OPCServer opcServer, OPCItems opcItems, string opcGroupName, GroupProperty groupProperty) { try { OPCGroup opcGroup = opcServer.OPCGroups.Add(opcGroupName); //opcServer.OPCGroups.DefaultGroupIsActive = groupProperty.DefaultGroupIsActive; //opcServer.OPCGroups.DefaultGroupDeadband = groupProperty.DefaultGroupDeadband; //opcGroup.UpdateRate = groupProperty.UpdateRate; //opcGroup.IsActive = groupProperty.IsActive; //opcGroup.IsSubscribed = groupProperty.IsSubscribed; opcServer.OPCGroups.DefaultGroupIsActive = true; opcServer.OPCGroups.DefaultGroupDeadband = 0; opcGroup.UpdateRate = 1000; opcGroup.DataChange += OpcGroup_DataChange; //opcGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(OpcGroupDataChange); //opcGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(KepGroup_AsyncWriteComplete); //opcItems = opcGroup.OPCItems; return(opcGroup); } catch (Exception ex) { SimpleLogHelper.Instance.WriteLog(LogType.Error, ex); return(null); } }
//连接 private void buttonConnect_Click(object sender, EventArgs e) { lock (lockobj) { if (OPCServer == null) { OPCServer = new OPCServer(); } if (OPCServer.ServerState == (int)OPCServerState.OPCRunning) { return; } OPCServer.Connect((string)jo["OPCServerName"]); int i = 1; foreach (KeyValuePair <string, JToken> kvp in (JObject)jo["Groups"]) { OPCGroup G = OPCServer.OPCGroups.Add(kvp.Key); foreach (KeyValuePair <string, JToken> kvpp in (JObject)kvp.Value) { OPCItem oItem = G.OPCItems.AddItem((string)kvpp.Value, i); i++; LocalOPCItems.Add(kvp.Key + "_" + kvpp.Key, oItem); } } } }
/// <summary> /// 创建组 /// </summary> /// <returns></returns> public bool CreateGroups() { if (OpcGroup != null) { return(true); } bool isCreate = false; try { OpcGroups = OpcServer.OPCGroups; OpcGroup = OpcGroups.Add("ZZHGROUP" + DateTime.Now.ToString("yyyyMMddHHmmssfff")); //设置组属性 OpcServer.OPCGroups.DefaultGroupIsActive = true; OpcServer.OPCGroups.DefaultGroupDeadband = 0; OpcItems = OpcGroup.OPCItems; isCreate = true; } catch (Exception ex) { Log.Info(ex.ToString()); isCreate = false; } return(isCreate); }
protected void AddGroup(string groupName, OPCGroup group) { if (this.defaultGroup == null) { this.defaultGroup = groupName.ToUpper(); } this.groupTable.Add(groupName.ToUpper(), group); }
internal OPCItem(OPCGroup opcGroup, string itemName, string opcItemName, int clientHandler, bool isActive) { this.parent = opcGroup; this.ItemName = itemName; this.opcItemName = opcItemName; this.clientHandler = clientHandler; this.isActive = isActive; }
public OPCConnection(string ProgID) { server = new OPCServer(); server.ClientName = ClientName; server.Connect(ProgID, null); group = server.OPCGroups.Add(GroupName); group.IsSubscribed = true; }
public Form1() { try { InitializeComponent(); OPCServerName = "{Here comes your OPC server’s name}"; ObjOPCServer = new OPCServer(); ObjOPCServer.Connect(OPCServerName, "";); ObjOPCGroups = ObjOPCServer.OPCGroups; ObjOPCGroup = ObjOPCGroups.Add("OPCGroup1"); ObjOPCGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(ObjOPCGroup_DataChange); ObjOPCGroup.OPCItems.AddItem("{tag name or address (like {plc name on server}!%mw0)}", 1); ObjOPCGroup.UpdateRate = 10; ObjOPCGroup.IsActive = true; ObjOPCGroup.IsSubscribed = true; } catch (Exception e){ MessageBox.Show(e.ToString()); } }
/// <summary> /// Инициализация. Настройка группы, установка асинхронного метода чтения данных для указанного тега. /// </summary> protected override void DoInitialize() { try { Logger.Debug("Инициализация"); var server = opcConnection.GetOpcServer(); opcGroup = server.OPCGroups.Add(Guid.NewGuid().ToString()); opcItem = opcGroup.OPCItems.AddItem(activationItemName, 0); opcGroup.UpdateRate = 100; opcGroup.IsActive = true; opcGroup.IsSubscribed = true; opcGroup.DataChange += ActivationItemValueChanged; dataReader.Initialize(); ReadItemFirstTime(); } catch (Exception ex) { opcConnection.ProcessError(ex); } }
public Branch(String Name, OPCServer Server = null, Branch Parent = null) { this._Name = Name; this._Children = new List<Branch>(); this._Leafs = new List<Leaf>(); if (Parent != null) { this._HasParent = true; this._Parent = Parent; Parent.addChildren(this); this.DataChanged += Parent.Branch_DataChanged; } else { this._HasParent = false; this._Parent = null; } if (Server != null) { this._OPCGroup = Server.OPCGroups.Add(this._Name); this._OPCGroup.UpdateRate = 200; //ms this._OPCGroup.IsActive = true; //Grupo activo this._OPCGroup.IsSubscribed = false; this._HasOPCGroup = true; } else { this._HasOPCGroup = false; this._OPCGroup = null; } this._HasChildren = false; this._HasLeafs = false; }
/// <summary> /// Инициализация. /// </summary> protected override void DoInitialize() { try { Logger.Debug("Инициализация LiveBit..."); var server = opcConnection.GetOpcServer(); inGroup = server.OPCGroups.Add(Guid.NewGuid().ToString()); outGroup = server.OPCGroups.Add(Guid.NewGuid().ToString()); inItem = inGroup.OPCItems.AddItem(topicName + ITEMID_LIVEBIT_IN, 0); outItem = outGroup.OPCItems.AddItem(topicName + ITEMID_LIVEBIT_OUT, 0); outGroup.UpdateRate = 100; outGroup.IsActive = true; outGroup.IsSubscribed = true; outGroup.DataChange += OutDataChanged; liveBitTestThread = new Thread(LiveBitTest); liveBitTestThread.Start(); Logger.Debug("Инициализация LiveBit завершена."); } catch (Exception ex) { opcConnection.ProcessError(ex); } }
public bool Connect() { try { IPHostEntry ipHostEntry = Dns.GetHostByAddress(strHostIP); strHostName = ipHostEntry.HostName.ToString(); MyServer = new OPCServer(); try { MyServer.Connect(serverProgID, strHostIP);//连接服务器:服务器名+主机名或IP if ((MyServer.ServerState == (int)OPCServerState.OPCFailed) && (MyServer.ServerState == (int)OPCServerState.OPCDisconnected)) { Console.WriteLine("已连接到:{0}::{1}",strHostIP, MyServer.ServerName); Console.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); try { sw = File.AppendText(logfile); sw.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); sw.WriteLine("已连接到:{0}::{1}", strHostIP, MyServer.ServerName); sw.Close(); } catch { } opc_connected = true; } else { //这里你可以根据返回的状态来自定义显示信息,请查看自动化接口API文档 Console.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); opc_connected = false; try { sw = File.AppendText(logfile); sw.WriteLine("服务器状态:{0}", MyServer.ServerState.ToString()); sw.Close(); } catch { } } //MyServer.ServerShutDown += DisConnect;//服务器断开事件 } catch (Exception err) { Console.WriteLine("连接远程服务器出现错误:{0}" + err.Message); try { sw = File.AppendText(logfile); sw.WriteLine("连接远程服务器出现错误:{0}" + err.Message); sw.Close(); } catch { } opc_connected = false; return false; } try { MyGroup = MyServer.OPCGroups.Add("sac_opc");//添加组 //以下设置组属性 { MyServer.OPCGroups.DefaultGroupIsActive = true;//激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0;// 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyServer.OPCGroups.DefaultGroupUpdateRate = 200;//默认组群的刷新频率为200ms MyGroup.UpdateRate = 1000;//刷新频率为1秒。 //MyGroup.IsSubscribed = true;//使用订阅功能,即可以异步,默认false } MyGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); //MyGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); MyGroup.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(GroupAsyncReadComplete); } catch (Exception err) { Console.WriteLine("创建组出现错误:{0}", err.Message); try { sw = File.AppendText(logfile); sw.WriteLine("创建组出现错误:{0}", err.Message); sw.Close(); } catch { } return false; } return true; } catch (Exception e) { Console.WriteLine(e.ToString()); Console.ReadLine(); return false; } tmConnect = new System.Timers.Timer(); tmConnect.AutoReset = true; tmConnect.Interval = connectRate; tmConnect.Elapsed += new System.Timers.ElapsedEventHandler(tm_Connect); tmConnect.Start(); return true; }
void init() { server = new OPCServer(); server.Connect(opcname); statusGroup= server.OPCGroups.Add(); statusGroup.OPCItems.AddItem(VB30ITEM, 1); statusGroup.OPCItems.AddItem(VB80ITEM, 2); resultGroup = server.OPCGroups.Add(); resultGroup.OPCItems.AddItem(I04_I15,1); CommandGroup = server.OPCGroups.Add(); CommandGroup.OPCItems.AddItem(START,1); CommandGroup.OPCItems.AddItem(PAUSE, 2); CommandGroup.OPCItems.AddItem(RESET, 3); statusGroup.DataChange += statusGroup_DataChange; //resultGroup.DataChange += resultGroup_DataChange; CommandGroup.DataChange += CommandGroup_DataChange; #region statusGroup.IsSubscribed = true; //resultGroup.IsSubscribed = true; CommandGroup.IsSubscribed = true; resultGroup.IsActive = true; statusGroup.IsActive = true; CommandGroup.IsActive = true; resultGroup.UpdateRate = 10; statusGroup.UpdateRate = 10; CommandGroup.UpdateRate = 10; #endregion toolStripProgressBar1.Step = 1; toolStripProgressBar1.Maximum = 19; }
public void Activate() { if (IsActive) { throw new OpcValueException("Двойная активация OPC тега: " + Name); } if (string.IsNullOrEmpty(Name)) { throw new OpcValueException("Имя OPC параметра не задано."); } if (server.ServerState != (int) OPCServerState.OPCRunning) { throw new OpcValueException( "Ошибка при активации тега: OPC сервер не подключен."); } GroupName = Guid.NewGuid().ToString(); opcGroup = server.OPCGroups.Add(GroupName); opcItem = opcGroup.OPCItems.AddItem(Name, opcGroup.ClientHandle); if (isListenValueChanging) { opcGroup.DataChange += ValueChanged; opcGroup.UpdateRate = UpdateRate; opcGroup.IsActive = true; opcGroup.IsSubscribed = true; } IsActive = true; }
private bool CreateGroup() { try { MyGroups = MyServer.OPCGroups; MyGroup = MyServer.OPCGroups.Add("测试");//添加组 MyGroup2 = MyServer.OPCGroups.Add("测试2"); //MyGroup2 = MyGroups.Add("测试2"); //以下设置组属性 { MyServer.OPCGroups.DefaultGroupIsActive = true;//激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0;// 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyServer.OPCGroups.DefaultGroupUpdateRate = 200;//默认组群的刷新频率为200ms MyGroup.UpdateRate = 100;//刷新频率为1秒。 MyGroup.IsSubscribed = true;//禁用订阅功能,即可以异步,默认false } MyGroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); MyGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); MyGroup.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(GroupAsyncReadComplete); MyGroup.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); { MyServer.OPCGroups.DefaultGroupIsActive = true;//激活组。 MyServer.OPCGroups.DefaultGroupDeadband = 0;// 死区值,设为0时,服务器端该组内任何数据变化都通知组。 MyServer.OPCGroups.DefaultGroupUpdateRate = 200;//默认组群的刷新频率为200ms MyGroup2.UpdateRate = 100;//刷新频率为1秒。 MyGroup2.IsSubscribed = true;//使用订阅功能,即可以异步,默认false } MyGroup2.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(GroupDataChange); MyGroup2.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); MyGroup2.AsyncReadComplete += new DIOPCGroupEvent_AsyncReadCompleteEventHandler(GroupAsyncReadComplete); MyGroup2.AsyncWriteComplete += new DIOPCGroupEvent_AsyncWriteCompleteEventHandler(GroupAsyncWriteComplete); AddGroupItems();//设置组内items } catch (Exception err) { Console.WriteLine("创建组出现错误:{0}", err.Message); return false; } return true; }
internal void Add(string groupName, OPCGroup group) { this.AddGroup(groupName, group); }
private bool AddGroup(OPCGroup opcGroup) { bool flag = true; float num2 = 0f; int phServerGroup = 0; GCHandle handle = GCHandle.Alloc(num2, GCHandleType.Pinned); IntPtr zero = IntPtr.Zero; try { int num; object obj2; IConnectionPoint point; int num4; this.pIOPCServer.AddGroup(opcGroup.GroupName, 1, opcGroup.UpdateRate, 0, zero, IntPtr.Zero, 0x86, out phServerGroup, out num, ref this.itemMgtInterface, out obj2); opcGroup.UpdateRate = num; opcGroup.ServerHandler = phServerGroup; IConnectionPointContainer container = (IConnectionPointContainer) obj2; Guid gUID = typeof(IOPCDataCallback).GUID; container.FindConnectionPoint(ref gUID, out point); point.Advise(opcGroup, out num4); opcGroup.SetParam(num4, obj2); } catch (Exception) { flag = false; } finally { if (handle.IsAllocated) { handle.Free(); } } return flag; }
//创建组 private bool CreatGroup() { try { _kepGroups = _kepServer.OPCGroups; _kepGroup = _kepGroups.Add("OPCDOTNETGROUP"); String(); _kepGroup.DataChange += KepGroup_DataChange; _kepItems = _kepGroup.OPCItems; } catch (Exception err) { MessageBox.Show("创建组出现错误:" + err.Message, "提示信息", MessageBoxButton.OK, MessageBoxImage.Warning); return false; } return true; }
/// <summary> /// Инициализация. Сосздание группы, ее настройка. /// </summary> protected override void DoInitialize() { try { Logger.Debug("Инициализация"); var server = opcConnection.GetOpcServer(); opcGroup = server.OPCGroups.Add(Guid.NewGuid().ToString()); items = new OPCItem[data.Length]; for (var dataIndex = 0; dataIndex < data.Length; ++dataIndex) { var item = opcGroup.OPCItems.AddItem(data[dataIndex].OpcItemName, dataIndex); items[dataIndex] = item; } } catch (Exception ex) { opcConnection.ProcessError(ex); } }
/// <summary> /// 创建组 /// </summary> public bool CreateGroup(string name) { try { s7Group = s7.OPCGroups.Add(name); SetGroupProperty(); } catch (Exception) { //MessageBox.Show("创建组出现错误:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } return true; }
/// <summary> /// 初始化OPC服务器 /// </summary> void InitOpc() { connected = false; connecteds = false; isfirstuse = true; try { string severname = "KEPware.KEPServerEx.V4"; string groupname = "S7-200.S7-200-1"; string outname = "S7-200.S7-200-1.OUT"; string inname = "S7-200.S7-200-1.IN"; string chuanname = "S7-200.S7-200-1.CHUAN"; string confname = "S7-200.S7-200-1.CONF"; myserver = new OPCServer(); myserver.Connect(severname); mygroups = myserver.OPCGroups; mygroup = mygroups.Add(groupname); mygroup.DataChange += new DIOPCGroupEvent_DataChangeEventHandler(ObjOPCGroup_DataChange); myitems = mygroup.OPCItems; item_out = myitems.AddItem(outname, 1);//opcitem标识,1out,2config,3in,4chuan item_conf = myitems.AddItem(confname, 2); item_in = myitems.AddItem(inname.ToString(), 3); item_chuan = myitems.AddItem(chuanname.ToString(), 4); mygroup.UpdateRate = 10; mygroup.IsActive = true; mygroup.IsSubscribed = true; connected = true; } catch (Exception e) { MessageBox.Show(e.ToString());//如果连接不上,说明运行库有问题,关了软件重新安装必要组件再运行 } }