public OpcConnector(string progId, string plcName, string opcAddressFmt) { m_The_srv = new OpcServer(); m_The_srv.Connect(progId); Thread.Sleep(500); // we are faster then some servers! // add our only working group m_The_grp = m_The_srv.AddGroup(plcName + "-strings", false, 900); // add two items and save server handles for (int i = 0; i < StrCount; i++) m_Item_defs[i] = new OPCItemDef(string.Format(opcAddressFmt, plcName, 272 + i*6), true, i + 1, VarEnum.VT_EMPTY); OPCItemResult[] rItm; m_The_grp.AddItems(m_Item_defs, out rItm); if (rItm == null) return; if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error)) { InstantLogger.msg("OPCDirectWriter: {0} -- AddItems - some failed", plcName); m_The_grp.Remove(true); m_The_srv.Disconnect(); return; } for (int i = 0; i < StrCount; i++) m_Handles_srv[i] = rItm[i].HandleServer; m_The_grp.WriteCompleted += TheGrpWriteComplete; }
public override void ReadValue(Command command, Action <int, PointValueType, object> onValueReceive) { int index = command.DeviceAddress.IndexOf("|"); string ip = command.DeviceAddress.Substring(0, index); string progid = command.DeviceAddress.Substring(index + 1); OPC.Data.OpcServer opcServer = new OPC.Data.OpcServer(); opcServer.Connect(progid, ip); OPC.Data.OpcGroup group1 = new OPC.Data.OpcGroup("g2", false, 1000, 1000, 0); opcServer.OpcGroups.Add(group1); int tranid = 0; foreach (var point in command.Points) { OPCItem item = new OPCItem(point, tranid++); group1.Items.Add(item); } var states = group1.Items.GetItemValues(); foreach (OPCItemState itemState in states) { pushValue(itemState, onValueReceive); } opcServer.Disconnect(); }
public void ListAllProperties( ref OpcServer theSrv, string itemid ) { listPropsView.Items.Clear(); string[] istrs = new string[ 5 ]; OPCProperty[] props; OPCPropertyData[] propdata; int[] propertyIDs = new int[1]; OPCPropertyItem[] propitm; try { theSrv.QueryAvailableProperties( itemid, out props ); if( props == null ) return; foreach( OPCProperty p in props ) { istrs[0] = p.PropertyID.ToString(); istrs[1] = p.Description; istrs[2] = DUMMY_VARIANT.VarEnumToString( p.DataType ); istrs[3] = ""; istrs[4] = ""; propertyIDs[0] = p.PropertyID; theSrv.GetItemProperties( itemid, propertyIDs, out propdata ); if( propdata != null ) { if( propdata[0].Error != HRESULTS.S_OK ) istrs[3] = "!Error 0x" + propdata[0].Error.ToString( "X" ); else istrs[3] = propdata[0].Data.ToString(); } if( p.PropertyID > 6 ) { theSrv.LookupItemIDs( itemid, propertyIDs, out propitm ); if( propitm != null ) { if( propitm[0].Error != HRESULTS.S_OK ) istrs[4] = "!Error 0x" + propitm[0].Error.ToString( "X" ); else istrs[4] = propitm[0].newItemID; } } listPropsView.Items.Add( new ListViewItem( istrs ) ); } } catch( COMException ) { MessageBox.Show( this, "QueryAvailableProperties failed!", "Item Properties", MessageBoxButtons.OK, MessageBoxIcon.Warning ); return; } // preselect top item in ListView listPropsView.Items[0].Selected = true; }
public override bool[] WriteValue(Command command) { int index = command.DeviceAddress.IndexOf("|"); string ip = command.DeviceAddress.Substring(0, index); string progid = command.DeviceAddress.Substring(index + 1); OPC.Data.OpcServer opcServer = new OPC.Data.OpcServer(); opcServer.Connect(progid, ip); OPC.Data.OpcGroup group1 = new OPC.Data.OpcGroup("g3", false, 1000, 1000, 0); opcServer.OpcGroups.Add(group1); int tranid = 0; foreach (var point in command.Points) { OPCItem item = new OPCItem(point, tranid++); group1.Items.Add(item); } bool[] result = new bool[command.Values.Length]; for (int i = 0; i < command.Values.Length; i++) { if (command.Values[i] is Newtonsoft.Json.Linq.JArray) { var jarray = (Newtonsoft.Json.Linq.JArray)command.Values[i]; if (jarray.Count > 0) { try { var newValue = Array.CreateInstance(((Newtonsoft.Json.Linq.JValue)jarray[0]).Value.GetType(), jarray.Count); for (int j = 0; j < jarray.Count; j++) { newValue.SetValue(((Newtonsoft.Json.Linq.JValue)jarray[j]).Value, j); } command.Values[i] = newValue; result[i] = true; } catch { } } else { result[i] = true; } } else { result[i] = true; } } group1.Items.WriteItemValues(command.Values); opcServer.Disconnect(); return(result); }
public Client(string ServerName, string configPath) { MainGates = new Dictionary<string, ConnectionProvider.Client>(); EventsToWrite = new Dictionary<string, EventsListener>(); this.OPCServerName = ServerName; m_OPCServer = new OpcServer(); m_OPCServer.ShutdownRequested += new ShutdownRequestEventHandler(ShutdownRequested); m_ClientGroups = new List<Group>(); m_AviableEvents = GetAviableEvents(); m_ConfigPath = configPath; }
private static void Main(string[] args) { MainConf = System.Configuration.ConfigurationManager.OpenExeConfiguration(""); Destination = MainConf.AppSettings.Settings["OPCDestination"].Value; CfgPath = MainConf.AppSettings.Settings["CfgPath"].Value; var reqUpdateRateMs = Convert.ToInt32(MainConf.AppSettings.Settings["OPCReqUpdateRate"].Value); MainGate = new ConnectionProvider.Client(new CoreListener()); MainGate.Subscribe(); var descriptionLoader = new LoaderCSV(Destination); descriptions = descriptionLoader.LoadAndGet(CfgPath); OpcServer_ = new OpcServer(); OpcServer_.Connect(MainConf.AppSettings.Settings["OPCServerProgID"].Value); OpcGroup_ = OpcServer_.AddGroup(Destination + "-flex-events", false, reqUpdateRateMs); OpcGroup_.DataChanged += OnDataChange; var hClient = 0; for (int dix = 0; dix < descriptions.Count; dix++) { var d = descriptions[dix]; foreach (var item in d.Arguments) { OpcItemDefs_.Add(new OPCItemDef(((Element) item.Value).opcItemID, true, ++hClient, VarEnum.VT_EMPTY)); ((Element) item.Value).cHandle = hClient; } } int[] aE; int addCount = 0; while (!OpcGroup_.AddItems(OpcItemDefs_.ToArray(), out OpcItemResults_)) { //if (++addCount > 1) throw new InvalidDataException("!!!AddItems failed"); for (var i = 0; i < OpcItemResults_.Count(); i++) { if (HRESULTS.Failed(OpcItemResults_[i].Error)) { OpcItemDefs_.RemoveAt(i); break; } } OpcGroup_.RemoveItems(OpcItemResults_.Select(ir => ir.HandleServer).ToArray(), out aE); } int k = 0; for (int j = 0; j < OpcItemDefs_.Count(); j++) SetServerHandle(OpcItemDefs_[j].HandleClient, OpcItemResults_[k++].HandleServer); for (int dix = 0; dix < descriptions.Count; dix++) Console.WriteLine(descriptions[dix]); OpcGroup_.Active = true; Console.WriteLine("OPCFlex is running, press enter to exit"); Console.ReadLine(); OpcGroup_.DataChanged -= OnDataChange; OpcGroup_.RemoveItems(OpcItemResults_.Select(ir => ir.HandleServer).ToArray(), out aE); OpcGroup_.Remove(false); OpcServer_.Disconnect(); Console.WriteLine("Bye!"); }
public override void AddPointToWatch(Command command, Action <int, PointValueType, object> onValueReceive) { int index = command.DeviceAddress.IndexOf("|"); string ip = command.DeviceAddress.Substring(0, index); string progid = command.DeviceAddress.Substring(index + 1); bool ready = false; OPC.Data.OpcServer opcServer = new OPC.Data.OpcServer(); opcServer.Connect(progid, ip); OPC.Data.OpcGroup group1 = new OPC.Data.OpcGroup("g1", true, command.Interval, command.Interval, 0); group1.DataChanged += new OPC.Data.DataChangeEventHandler((sender, e) => { if (ready) { foreach (OPCItemState itemState in e.sts) { pushValue(itemState, onValueReceive); } } }); opcServer.OpcGroups.Add(group1); int tranid = 0; foreach (var point in command.Points) { OPCItem item = new OPCItem(point, tranid++); group1.Items.Add(item); } var states = group1.Items.GetItemValues(); foreach (OPCItemState itemState in states) { pushValue(itemState, onValueReceive); } ready = true; while (true) { System.Threading.Thread.Sleep(5000); var opcState = opcServer.GetStatus(); if (opcState.eServerState != OPC.Data.Interface.OPCSERVERSTATE.OPC_STATUS_RUNNING) { throw new Exception("server error"); } } }
public override bool CheckDeviceExist(Command command) { int index = command.DeviceAddress.IndexOf("|"); string ip = command.DeviceAddress.Substring(0, index); string progid = command.DeviceAddress.Substring(index + 1); try { OPC.Data.OpcServer opcServer = new OPC.Data.OpcServer(); opcServer.Connect(progid, ip); opcServer.Disconnect(); } catch { return(false); } return(true); }
public override void EnumPoints(Command command, Action <string> onFindPoint) { int index = command.DeviceAddress.IndexOf("|"); string ip = command.DeviceAddress.Substring(0, index); string progid = command.DeviceAddress.Substring(index + 1); OPC.Data.OpcServer server = new OPC.Data.OpcServer(); server.Connect(progid, ip); server.AsyncGetNode += new OPC.Data.OpcServer.AsyncGetNodeHandler((tag, node) => { var obj = new PointInfomation { Path = node.ID, IsFolder = !node.IsItemProperty, Name = node.Name }; onFindPoint(Newtonsoft.Json.JsonConvert.SerializeObject(obj)); }); server.AsyncGetNodes(command.ParentPath, null, true); }
public override void Stop() { this.server = null; }
public override void Start(string address) { this.server = new OpcServer(); this.serverId = address; }
public OpcConnector(string progId, string opcDestination, string opcAddressFmt, int opcConvSchema = 0, int reqUpdateRate_ms = 500) { using (Logger l = new Logger("OpcConnector")) { string plcName = "NO-PLC"; m_The_srv = new OpcServer(); m_The_srv.Connect(progId); Thread.Sleep(500); // we are faster then some servers! // add our only working group m_The_grp = m_The_srv.AddGroup(opcDestination + "-items", false, reqUpdateRate_ms); // add all the items and save server handles int itemCounter = 0; EventsList = BaseEvent.GetEvents(); for (int eventCounter = 0; eventCounter < EventsList.Length; eventCounter++) { var heatEvent = EventsList[eventCounter]; l.msg(heatEvent.Name); // название события EventStore.Add((CommonTypes.BaseEvent) Activator.CreateInstance(heatEvent)); // создаем экземпляр события int plcpIndex = -1; bool opcRelated = false; for (int i = 0; i < heatEvent.GetCustomAttributes(false).Length; i++) { object x = heatEvent.GetCustomAttributes(false)[i]; if (x.GetType().Name == "PLCGroup") { PLCGroup p = (PLCGroup) x; if (p.Destination == opcDestination) { plcName = p.Location; l.msg(" {0} ==>> {1}", p.Location, p.Destination); opcRelated = true; break; } } } if (!opcRelated) continue; for (int propertyCounter = 0; propertyCounter < heatEvent.GetProperties().Length; propertyCounter++) { var prop = heatEvent.GetProperties()[propertyCounter]; object first = null; for (int index = 0; index < prop.GetCustomAttributes(false).Length; index++) { object x = prop.GetCustomAttributes(false)[index]; if (x.GetType().Name == "PLCPoint") { plcpIndex = index; first = x; break; } } var plcp = (PLCPoint) first; if (plcp == null) continue; string s = string.Format(opcAddressFmt, plcName, cnv(plcp.Location, opcConvSchema)); // add new OPC Item using itemCounter as client handle m_Item_defs.Add(new OPCItemDef(s, true, itemCounter, VarEnum.VT_EMPTY)); m_Item_props.Add(new FledgedItemDef(eventCounter, propertyCounter, plcpIndex)); l.msg("{0}: {1}", itemCounter, s); itemCounter++; } if (itemCounter >= maxItemCount) break; } l.msg("Counter is {0}", itemCounter); if (itemCounter == 0) throw new Exception("No items found"); // Validate Items (ignoring BLOBs OPCItemResult[] rItm; m_The_grp.ValidateItems(m_Item_defs.ToArray(), false, out rItm); if (rItm == null) throw new Exception("OPC ValidateItems: -- system error: arrRes is null"); List<int> itemExclude = new List<int>(); for (int i = 0; i < itemCounter; i++) { if (HRESULTS.Failed(rItm[i].Error)) { l.err( "Error 0x{1:x} while adding item {0} -- item EXCLUDED from monitoring", i, rItm[i].Error); itemExclude.Add(i); } } if (itemCounter == itemExclude.Count) throw new Exception("No items passed validation"); // Exclude invalid items // Add Items m_The_grp.AddItems(m_Item_defs.ToArray(), out rItm); if (rItm == null) return; for (int i = 0; i < itemCounter; i++) { if (HRESULTS.Failed(rItm[i].Error)) rItm[i].HandleServer = -1; } m_Handles_srv = new int[itemCounter]; for (int i = 0; i < itemCounter; i++) m_Handles_srv[i] = rItm[i].HandleServer; //m_The_grp.WriteCompleted += TheGrpWriteComplete; int cancelId; int[] aE; // l.msg("start read"); m_The_grp.SetEnable(true); m_The_grp.Active = true; m_The_grp.DataChanged += new DataChangeEventHandler(this.TheGrpDataChange); m_The_grp.ReadCompleted += new ReadCompleteEventHandler(this.TheGrpReadComplete); //m_The_grp.Read(m_Handles_srv, 55667788, out cancelId, out aE); //Thread.Sleep(500); // l.msg("end read"); } }
public PropsForm( ref OpcServer theSrv, string itemid ) { InitializeComponent(); ListAllProperties( ref theSrv, itemid ); }
public bool DoInit() { string[] itemstrings = new string[5]; string sPLC_Adr = "*UnDef*",sAlias = "*UnDef*",sGroup = "",sDesc = ""; int iPLCDataLength; sAliasToControl = "ACT_C1_STAHLMARKE0"; itemstrings[2] = itemstrings[3] = itemstrings[4] = "-"; try { selectedOpcSrv = "OPC.SimaticNET.1"; // ����� ���� �������� AddLogg("������� �� " + sCompName); AddLogg("LoadDefinitions()-Start"); LoadDefinitions(); AddLogg("LoadDefinitions()-End"); theSrv = new OpcServer(); if (!DoConnect(selectedOpcSrv)) { AddLogg("DoConnect(" + selectedOpcSrv + ")=false"); //////////return false; } // add event handler for server shutdown theSrv.ShutdownRequested += new ShutdownRequestEventHandler(this.theSrv_ServerShutDown); // precreate the only OPC group in this example if (!CreateGroup()) { AddLogg("CreateGroup()=false"); //////////return false; } AddLogg("DoInit: Start"); RemoveItem(); // first remove previous item if any cbCtrlAliases.Items.Clear(); groupLi = new List<clsGroupInfo>(); pointLi = new List<clsPointInfo>(); j = 0; for (i = 0; i < strItems_Alias.Count; i++) { try { itemclsPointInfo = new clsPointInfo(); itmHandleClient = j; sPLC_Adr = strItems_adrPLC[i]; // "LOCATION0 PLC13:DB2,STRING66,8" // S7:[PLC13]DB2,STRING66,8 sAlias = strItems_Alias[i]; sGroup = strItems_Groups[i]; sDesc = strItems_Desc[i]; //k = sPLC_Adr.IndexOf("STRING"); k = sPLC_Adr.IndexOf("CHAR"); if (k < 0) { itemclsPointInfo.iDataLength = 0; } else { string[] sSplitted = sPLC_Adr.Trim().Split(','); itemclsPointInfo.iDataLength = Convert.ToInt32(sSplitted[sSplitted.GetLength(0) - 1].Trim()); } OPCItemDef[] aD = new OPCItemDef[1]; aD[0] = new OPCItemDef(sPLC_Adr,true,itmHandleClient,VarEnum.VT_EMPTY); OPCItemResult[] arrRes; theGrp.AddItems(aD,out arrRes); if (arrRes == null) { AddLogg("DoInit:AddItem" + i + " " + sPLC_Adr + " arrRes == null"); //continue; } else { if (arrRes[0].Error != HRESULTS.S_OK) { AddLogg("DoInit:AddItem" + i + " " + sPLC_Adr + " arrRes[0].Error != HRESULTS.S_OK"); //continue; } else { itmHandleServer = arrRes[0].HandleServer; itmAccessRights = arrRes[0].AccessRights; itmTypeCode = VT2TypeCode(arrRes[0].CanonicalDataType); txbActPoint.Text = sPLC_Adr; txtItemDataType.Text = DUMMY_VARIANT.VarEnumToString(arrRes[0].CanonicalDataType); //if ((itmAccessRights & OPCACCESSRIGHTS.OPC_READABLE) != 0) { // int cancelID; // theGrp.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE,7788,out cancelID); // } //else { // txtItemValue.Text = "no read access"; // AddLogg("DoInit:AddItem" + i + " " + sPLC_Adr + " no read access"); // } if (itmTypeCode != TypeCode.Object) { // Object=failed! ////AddLogg("DoInit:AddItem" + i + " " + sPLC_Adr + " Object=failed"); // check if write is permitted if ((itmAccessRights & OPCACCESSRIGHTS.OPC_WRITEABLE) != 0) { //btnItemWrite.Enabled = true; ////AddLogg("DoInit:AddItem" + i + " " + sPLC_Adr + " write is permitted"); } } itemstrings[0] = sAlias; itemstrings[1] = sPLC_Adr; //listOpcView.Items.Add(new ListViewItem(itemstrings,0)); itemclsPointInfo.sAlias = sAlias; string[] sEvtNameSplitted = sAlias.Split('_'); //for (k = 0; k < sEvtNameSplitted.GetLength(0); k++){ // AddLogg("DEBUG sEvtNameSplitted[" + k + "] = '" + sEvtNameSplitted[k]+"'"); //} if (sEvtNameSplitted[0] == "ACT" || sEvtNameSplitted[0] == "SP") { // Fool-Proof if (sEvtNameSplitted[1] == "C1" || sEvtNameSplitted[1] == "C2" || sEvtNameSplitted[1] == "C3") { itemclsPointInfo.iCnvNr = Convert.ToInt32(sEvtNameSplitted[1].Substring(1,1)); if (sEvtNameSplitted[0] == "SP"){ itemclsPointInfo.sAliasInfoTeil = itemclsPointInfo.sAlias.Substring(6,itemclsPointInfo.sAlias.Length -6); } else{ itemclsPointInfo.sAliasInfoTeil = itemclsPointInfo.sAlias.Substring(7,itemclsPointInfo.sAlias.Length - 7); } } else { itemclsPointInfo.iCnvNr = 0; if (sEvtNameSplitted[0] == "SP"){ itemclsPointInfo.sAliasInfoTeil = itemclsPointInfo.sAlias.Substring(3,itemclsPointInfo.sAlias.Length -3); } else{ itemclsPointInfo.sAliasInfoTeil = itemclsPointInfo.sAlias.Substring(4,itemclsPointInfo.sAlias.Length - 4); } } if (sEvtNameSplitted[0] == "SP"){ itemclsPointInfo.bIsSetPoint = true; } } else { AddLogg("DoInit:AddItem" + i + " " + sAlias + " �� ���������� � 'ACT_'/'SP_'"); } itemclsPointInfo.sPLC_Adr = sPLC_Adr; itemclsPointInfo.sDesc = sDesc; itemclsPointInfo.CanonicalDataType = arrRes[0].CanonicalDataType; itemclsPointInfo.sCanonicalDataType = DUMMY_VARIANT.VarEnumToString(arrRes[0].CanonicalDataType); itemclsPointInfo.AccessRights = arrRes[0].AccessRights; itemclsPointInfo.itmTypeCode = itmTypeCode; pointLi.Add(itemclsPointInfo); cbCtrlAliases.Items.Add(sAlias + " " + sPLC_Adr); // ���� � ������ ���� //k = groupLi.FindIndex(delegate(clsGroupInfo lfdGroupInfo) { // ** ��� ��������� // return lfdGroupInfo.sName == sGroup; // } // ); string @group = sGroup; // ** ����� !!! k = groupLi.FindIndex(lfdGroupInfo => lfdGroupInfo.sName == group); if (k < 0) { // ��� ������ ����� ������, ��������������, ��� TAKE_OVER !! itemclsGroupInfo = new clsGroupInfo(); itemclsGroupInfo.sName = sGroup; groupLi.Add(itemclsGroupInfo); pointLi[pointLi.Count - 1].bIsTakeOver = true; // rueckwerts in PointLi schreiben } k = pointLi.Count - 1; // wegen DEBUG pointLi[k].iIdxInGroupLi = groupLi.Count - 1; // gehoert zu dieser Gruppe;rueckwerts in PointLi schreiben k = groupLi.Count - 1; // wegen DEBUG groupLi[k].iItemsCnt++; // so viele Punkte in der Gruppe groupLi[k].iIdxInPointLi.Add(pointLi.Count - 1); // eigentlisch Punkte(als pointLi[Index]) DoStoreToOracle(j); // AnfangsZustand in Oracle generieren AddLogg("�������� Pkt" + j + " group '" + groupLi[k].sName + "',Alias'" + sAlias + "' " + sPLC_Adr); j++; } } } catch (/*COMException*/ Exception comExc) { //MessageBox.Show(this,"AddItem " + sPLC_Adr + " OPC error!","DoInit",MessageBoxButtons.OK,MessageBoxIcon.Warning); AddLogg("DoInit:AddItem" + i + " '" + sPLC_Adr + "' OPC exception:" + comExc.Message); //return false; continue; } } int cancelID; theGrp.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE,7788,out cancelID); } catch (Exception e) { // exceptions MUST be handled //MessageBox.Show(this,"init error! " + e.ToString(),"Exception",MessageBoxButtons.OK,MessageBoxIcon.Warning); AddLogg("DoInit:AddItem" + i + " '" + sPLC_Adr + "' init error! " + e.Message); AddLogg("DoInit: Ende - false"); return false; } AddLogg("DoInit: Ende-true,� pointLi " + pointLi.Count + " � groupLi " + groupLi.Count); mainGate = new MainGateClient(new InstanceContext(new DummyListener())); return true; }
private void MainForm_Closing(object sender,System.ComponentModel.CancelEventArgs e) { if (!opc_connected) return; if (theGrp != null) { theGrp.DataChanged -= new DataChangeEventHandler(this.theGrp_DataChange); theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete); RemoveItem(); theGrp.Remove(false); theGrp = null; } if (theSrv != null) { theSrv.Disconnect(); // should clean up theSrv = null; } opc_connected = false; }
public OpcGroupCollection(OPC.Data.OpcServer Server) { this.Server = Server; }