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;
        }
Example #2
0
        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();
        }
Example #3
0
        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);
        }
Example #4
0
        // --------------------------------- IOPCServerPublicGroups (indirect) -----------------
        public OpcGroup GetPublicGroup(string groupName)
        {
            if (ifServer == null)
            {
                Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT);
            }

            OpcGroup grp = new OpcGroup(ref ifServer, true, groupName, false, 1000);

            grp.internalAdd(null, null, 0);
            return(grp);
        }
        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!");
        }
Example #6
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder("OPCIST: ", 256);

            sb.AppendFormat("error=0x{0:x} hclt=0x{1:x}", Error, HandleClient);
            if (Error == HRESULTS.S_OK)
            {
                sb.AppendFormat(" val={0} time={1} qual=", DataValue, TimeStamp);
                sb.Append(OpcGroup.QualityToString(Quality));
            }

            return(sb.ToString());
        }
Example #7
0
        public OpcGroup AddGroup(string groupName, bool setActive, int requestedUpdateRate,
                                 int[] biasTime, float[] percentDeadband, int localeID)
        {
            if (ifServer == null)
            {
                Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT);
            }

            OpcGroup grp = new OpcGroup(ref ifServer, false, groupName, setActive, requestedUpdateRate);

            grp.internalAdd(biasTime, percentDeadband, localeID);
            return(grp);
        }
Example #8
0
        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");
                }
            }
        }
Example #9
0
        private void AddGroup(OpcGroup group,
                              int[] biasTime, float[] percentDeadband, int localeID)
        {
            if (ifServer == null)
            {
                Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT);
            }

            group.ifServer     = ifServer;
            group.state.Public = false;
            group.Server       = this;

            group.internalAdd(biasTime, percentDeadband, localeID);
            return;
        }
Example #10
0
 public OpcItemCollection(OPC.Data.OpcGroup Group)
 {
     this.Group = Group;
 }
        public bool CreateGroup()
        {
            try {
            // add our only working group
            theGrp = theSrv.AddGroup("OPCdotNET-Group",true,500);

            // add event handler for data changes
            theGrp.DataChanged += new DataChangeEventHandler(this.theGrp_DataChange);
            theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete);
            }
             catch (COMException exc) {
            AddLogg("connect error!Exception: " + exc.Message);
            MessageBox.Show(this,"create group error!","Exception",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            return false;
            }
             return true;
        }
 public bool Write(string adress, object value)
 {
     opcGroup = m_OPCServer.AddGroup("testGroup", true, 500);
     OPCItemResult[] arrRes;
     opcGroup.AddItems(new OPCItemDef[] { new OPCItemDef(adress, true, 1, VarEnum.VT_EMPTY) }, out arrRes);
     m_serverHandle = arrRes.Select(p => p.HandleServer).ToArray();
     int cancelID;
     opcGroup.HandleClient = 1;
     int[] errors;
     return opcGroup.Write(m_serverHandle, new object[] { value }, out errors);
 }
        public OpcGroup AddGroup(	string groupName, bool setActive, int requestedUpdateRate,
            int[] biasTime, float[] percentDeadband, int localeID)
        {
            if( ifServer == null )
            Marshal.ThrowExceptionForHR( HRESULTS.E_ABORT );

            OpcGroup	grp = new OpcGroup( ref ifServer, false, groupName, setActive, requestedUpdateRate );
            grp.internalAdd( biasTime, percentDeadband, localeID );
            return grp;
        }
Example #14
0
 internal void AddGroup(OpcGroup group)
 {
     AddGroup(group, new int[] { group.TimeBias }, new float[] { group.PercentDeadband }, 0);
 }
Example #15
0
        public OPCItemState[] Read(int[] arrHSrv)
        {
            OPCItemState[] arrStat;
            arrStat = null;
            int    count = arrHSrv.Length;
            IntPtr ptrStat;
            IntPtr ptrErr;



            int hresult = ifSync.Read(OPCDATASOURCE.OPC_DS_DEVICE, count, arrHSrv, out ptrStat, out ptrErr);

            if (HRESULTS.Failed(hresult))
            {
                #region 新建组读取
                values = new List <ItemValue>();
                readed = false;

                OPC.Data.OpcGroup grouop = new OpcGroup("wef2", true, 500, 500, 0);
                this.group = grouop;
                this.Server.OpcGroups.Add(grouop);
                grouop.DataChanged += new DataChangeEventHandler(grouop_DataChanged);
                int index = 0;

                foreach (int hid in arrHSrv)
                {
                    OPCItem item = this.Items.GetItemByServerHandler(hid);
                    values.Add(new ItemValue(item.ID, null));
                }

                foreach (int hid in arrHSrv)
                {
                    OPCItem item    = this.Items.GetItemByServerHandler(hid);
                    OPCItem newItem = new OPCItem(item.ID, index);
                    grouop.Items.Add(newItem);
                    index++;
                }

                while (true)
                {
                    if (readed)
                    {
                        OPCItemState[] states = new OPCItemState[arrHSrv.Length];
                        for (int i = 0; i < states.Length; i++)
                        {
                            states[i] = values[i].value;
                        }
                        this.group = null;
                        grouop.Items.Clear();
                        this.Server.OpcGroups.Remove(grouop);
                        return(states);
                    }
                    Thread.Sleep(20);
                }
                #endregion

                if (HRESULTS.Failed(hresult))
                {
                    throw (new Exception("读取Item值出错,public OPCItemState[] Read(int[] arrHSrv)函数ifSync.Read(OPCDATASOURCE.OPC_DS_CACHE, count, arrHSrv, out ptrStat, out ptrErr)语句"));
                }
            }

            int runErr  = (int)ptrErr;
            int runStat = (int)ptrStat;
            if ((runErr == 0) || (runStat == 0))
            {
                Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT);
            }

            arrStat = new OPCItemState[count];
            for (int i = 0; i < count; i++)
            {                                                                                                           // WORKAROUND !!!
                OPCItemState item = new OPCItemState();
                arrStat[i] = item;
                item.Error = Marshal.ReadInt32((IntPtr)runErr);
                runErr    += 4;

                item.HandleClient = Marshal.ReadInt32((IntPtr)runStat);

                if (HRESULTS.Succeeded(item.Error))
                {
                    short vt = Marshal.ReadInt16((IntPtr)(runStat + 16));
                    if (vt == (short)VarEnum.VT_ERROR)
                    {
                        item.Error = Marshal.ReadInt32((IntPtr)(runStat + 24));
                    }
                    try
                    {
                        item.TimeStamp = DateTime.FromFileTime(Marshal.ReadInt64((IntPtr)(runStat + 4)));
                    }
                    catch
                    {
                    }
                    try
                    {
                        item.QualityString = OpcGroup.QualityToString(Marshal.ReadInt16((IntPtr)(runStat + 12)));
                    }
                    catch
                    {
                    }
                    item.DataValue = Marshal.GetObjectForNativeVariant((IntPtr)(runStat + 16));
                    DUMMY_VARIANT.VariantClear((IntPtr)(runStat + 16));
                }
                else
                {
                    item.DataValue = null;
                }

                runStat += 32;
            }

            Marshal.FreeCoTaskMem(ptrStat);
            Marshal.FreeCoTaskMem(ptrErr);
            return(arrStat);
            //if (hresult == HRESULTS.S_OK)
            //{
            //    return arrStat;
            //}
            //else
            //{
            //    return null;
            //}
        }
        // --------------------------------- IOPCServerPublicGroups (indirect) -----------------
        public OpcGroup GetPublicGroup(	string groupName )
        {
            if( ifServer == null )
            Marshal.ThrowExceptionForHR( HRESULTS.E_ABORT );

            OpcGroup	grp = new OpcGroup( ref ifServer, true, groupName, false, 1000 );
            grp.internalAdd( null, null, 0 );
            return grp;
        }
        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");
            }
        }
        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;
        }
Example #19
0
        private void Connect()
        {
            try
            {
                this.server.Connect(this.serverId);

                RecordManager.DoSystemEventRecord(this, "Connected to CPU", RecordType.Event, true);

                this.group = this.server.AddGroup("Group1", true, 2000);

                this.OnConnect();

                this.Write(new HandleCode(1, this.Flow), new HandleCode(2, this.Hours));
                this.connected = true;

                this.timer = new System.Windows.Forms.Timer();
                this.timer.Interval = 3000;
                this.timer.Tick += this.OnDataTimer;
                this.timer.Start();
            }
            catch (Exception e)
            {
                RecordManager.DoSystemEventRecord(this, string.Format("Connect:{0}", e.Message), RecordType.Error);
            }
        }
 public void Reading(string adress)
 {
     opcGroup = m_OPCServer.AddGroup("testGroup", true, 500);
     OPCItemResult[] arrRes;
     opcGroup.AddItems(new OPCItemDef[] { new OPCItemDef(adress, true, 1, VarEnum.VT_EMPTY) }, out arrRes);
     opcGroup.DataChanged += new DataChangeEventHandler(GroupDataChange);
     int cancelID;
     opcGroup.HandleClient = 1;
     opcGroup.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, 7788, out cancelID);
 }