Esempio n. 1
0
 /// <summary>
 /// Creates a new browser object with a set of filters.
 /// </summary>
 public Browser(
     ISystemContext context,
     ViewDescription view,
     NodeId referenceType,
     bool includeSubtypes,
     BrowseDirection browseDirection,
     QualifiedName browseName,
     IEnumerable <IReference> additionalReferences,
     bool internalOnly,
     Opc.Ua.Client.Session client,
     NamespaceMapper mapper,
     NodeState source,
     NodeId rootId)
     :
     base(
         context,
         view,
         referenceType,
         includeSubtypes,
         browseDirection,
         browseName,
         additionalReferences,
         internalOnly)
 {
     m_client = client;
     m_mapper = mapper;
     m_source = source;
     m_rootId = rootId;
     m_stage  = Stage.Begin;
 }
Esempio n. 2
0
        public static void GetHistory(TimeSeriesBlock tsb)
        {
            Console.WriteLine("Read OPC UA Historical Data:");
            try
            {
                ErrorMessage         = "";
                startTime            = tsb.opcLastTimeStamp;
                endTime              = DateTime.UtcNow + TimeSpan.FromMinutes(120);
                tsb.opcLastTimeStamp = endTime;
                if (session == null)
                {
                    Connect(tsb);
                }
                GetData(tsb);
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                session?.Close();
                session?.Dispose();
                session = null;
                opc     = null;
            }

            /*
             * session?.Close();
             * session?.Dispose();
             * session = null;
             */
        }
Esempio n. 3
0
        public override void Execute(OpcSession session)
        {
            LogExecutionStart(session);
            NormalizeNodeId(session);
            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection
            {
                new HistoryReadValueId {
                    NodeId = OpcUaNodeId
                }
            };

            Opc.Ua.Client.Session uaSession = session.OpcUaClientSession;
            Logger.Debug("About to perform a HistoryRead:");
            Logger.Debug("Details:");
            Logger.Debug($"  Start time:  {details.StartTime}");
            Logger.Debug($"  End time:  {details.EndTime}");
            Logger.Debug($"  Read modified:  {details.IsReadModified}");
            Logger.Debug($"  Values per node:  {details.NumValuesPerNode}");
            Logger.Debug($"  Return bounds:  {details.ReturnBounds}");
            Logger.Debug("Nodes to read:");
            nodesToRead.ForEach(n => Logger.Debug($"  {n}({n.NodeId})"));
            uaSession.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out HistoryReadResultCollection results,
                out DiagnosticInfoCollection diagnostics
                );
            Logger.Debug($"HistoryRead got {results.Count} results, {diagnostics.Count} diagnostics.");
            HistoryReadResult hrr      = results[0];
            HistoryData       histData = (HistoryData)ExtensionObject.ToEncodeable(hrr.HistoryData);

            if (StatusCode.IsBad(hrr.StatusCode))
            {
                Logger.Information($"Bad result ({hrr.StatusCode}) reading {OpcNodeId}");
            }
            else
            {
                if (StatusCode.IsGood(hrr.StatusCode))
                {
                    Logger.Debug($"Good result: {histData}, {histData.DataValues.Count} values.");
                }
                if (StatusCode.IsUncertain(hrr.StatusCode))
                {
                    Logger.Information($"Uncertain result: {hrr}");
                }
            }
            foreach (DataValue dv in histData.DataValues)
            {
                Logger.Debug($"  {dv} ({dv.SourceTimestamp})");
                dataValue1 = new DataValue();                 // Acá debería asignarse algo que viene desde «results».
                if (Program.HaveToWriteCsv)
                {
                    WriteDataValueToCsvFile(dv);
                }
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Fetches the event type information from the AE server.
 /// </summary>
 public void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, NamespaceMapper mapper)
 {
     TypeNodes = new NodeIdDictionary <ReferenceDescription>();
     LoadTypes(client, server, mapper, Opc.Ua.ObjectTypeIds.BaseObjectType);
     LoadTypes(client, server, mapper, Opc.Ua.VariableTypeIds.BaseVariableType);
     LoadTypes(client, server, mapper, Opc.Ua.DataTypeIds.BaseDataType);
     LoadTypes(client, server, mapper, Opc.Ua.ReferenceTypeIds.References);
 }
Esempio n. 5
0
 public static void Connect(TimeSeriesBlock tsb)
 {
     if (opc == null)
     {
         opc = new UASampleClient(tsb.sourceAddress, true, 10000, tsb.username, tsb.password);
     }
     opc.ConsoleSampleClient().Wait();
     session = opc.session;
 }
Esempio n. 6
0
 public void registerServer(string Name, object identifier, Opc.Ua.Client.Session client_session)
 {
     if (child_server.ContainsKey(identifier))
     {
         throw new Exception("Child Server with identifier already exist");
     }
     Client.Client client = new Client.Client(Name, identifier, client_session);
     child_server.Add(identifier, client);
     collectorNodeManager.addChildRootNode(Name, machineNode);
 }
 public void destroy()
 {
     try
     {
         if (opcSession != null)
         {
             //Call connect
             myClientHelperAPI.Disconnect();
             opcSession = null;
             log.Info("PLCHandler disconnect successfull");
         }
     }
     catch (Exception exp)
     {
         log.Error("Error in PLCHandler.destroy()", exp);
     }
 }
 public void destroy()
 {
     try
     {
         this.isRunning = false;
         if (opcSession != null)
         {
             //Call connect
             myClientHelperAPI.Disconnect();
             opcSession = null;
             log.Info("OPC disconnect successfull");
         }
     }
     catch (Exception exp)
     {
         log.Info("opcDisConnect error = " + exp);
     }
 }
        public void init()
        {
            try
            {
/*
 *              log.Debug
 *              log.Info
 *              log.Error
 *              log.Fatal
 */

                myClientHelperAPI = new UAClientHelperAPI();
                EndpointDescription mySelectedEndpoint = null;
                log.Info("Start OPC connection...");
                //mySelectedEndpoint = CreateEndpointDescription(endpointUrl, secPolicy, MessageSecurityMode.None);
                mySelectedEndpoint = getEndpointDescription(endpointUrl);
                if (opcSession == null && mySelectedEndpoint != null)
                {
                    myClientHelperAPI.KeepAliveNotification += new Opc.Ua.Client.KeepAliveEventHandler(plcKeepAliveEventHandler);
                    //myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate);

                    //Call connect
                    myClientHelperAPI.Connect(mySelectedEndpoint, opcuser.Length > 0, opcuser, opcpwd);
                    //myClientHelperAPI.Connect(mySelectedEndpoint.EndpointUrl, mySelectedEndpoint.SecurityPolicyUri, MessageSecurityMode.None, false, null, null);
                    opcSession = myClientHelperAPI.Session;
                    log.Info("OPC connect successfull");


                    //load jobs from database
                    loadJobsFromDb();

                    //Új szál indítása
                    this.plcMaxQSize = int.Parse(ConfigurationManager.AppSettings["plc_max_q_size"]);
                    this.sleepMillis = int.Parse(ConfigurationManager.AppSettings["thread_sleepmillis"]);
                    this.isRunning   = true;
                    this.mainThread  = new Thread(this.Ciklus);
                    this.mainThread.Start();
                }
            }
            catch (Exception exp)
            {
                log.Info("OPC not connected" + exp);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Fetches the event categories for the specified event type.
        /// </summary>
        private void LoadTypes(Opc.Ua.Client.Session client, IServerInternal server, NamespaceMapper mapper, NodeId parentId)
        {
            List <ReferenceDescription> references = null;

            // find references to subtypes.
            try
            {
                references = BrowseSubTypes(client, parentId);
            }
            catch (Exception e)
            {
                Utils.Trace("Could not browse subtypes of {0}. {1}", parentId, e.Message);
                return;
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                // ignore absolute references.
                if (reference.NodeId == null || reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                // recursively browse until a non-UA node is found.
                if (reference.NodeId.NamespaceIndex == 0)
                {
                    LoadTypes(client, server, mapper, (NodeId)reference.NodeId);
                    continue;
                }

                // map the node id and browse name to local indexes.
                NodeId targetId = mapper.ToLocalId((NodeId)reference.NodeId);

                reference.NodeId     = targetId;
                reference.BrowseName = mapper.ToLocalName(reference.BrowseName);

                // add non-UA node to the table.
                TypeNodes[targetId] = reference;
                server.TypeTree.AddSubtype(targetId, parentId);
            }
        }
 private void plcKeepAliveEventHandler(Opc.Ua.Client.Session sender, Opc.Ua.Client.KeepAliveEventArgs e)
 {
     try
     {
         // check for events from discarded sessions.
         if (!Object.ReferenceEquals(sender, opcSession))
         {
             return;
         }
         // check for disconnected session.
         if (!ServiceResult.IsGood(e.Status))
         {
             // try reconnecting using the existing session state
             opcSession.Reconnect();
         }
     }
     catch (Exception ex)
     {
         log.Error(ex);
     }
 }
        public void init(String endpointUrl, String opcuser, String opcpwd)
        {
            log.Debug("PLCHandler.init() begin");
            myClientHelperAPI = new UAClientHelperAPI();
            EndpointDescription mySelectedEndpoint = null;

            //mySelectedEndpoint = CreateEndpointDescription(endpointUrl, secPolicy, MessageSecurityMode.None);
            mySelectedEndpoint = getEndpointDescription(endpointUrl);
            if (opcSession == null && mySelectedEndpoint != null)
            {
                myClientHelperAPI.KeepAliveNotification += new Opc.Ua.Client.KeepAliveEventHandler(plcKeepAliveEventHandler);
                //myClientHelperAPI.CertificateValidationNotification += new CertificateValidationEventHandler(Notification_ServerCertificate);

                //Call connect
                myClientHelperAPI.Connect(mySelectedEndpoint, opcuser.Length > 0, opcuser, opcpwd);
                //myClientHelperAPI.Connect(mySelectedEndpoint.EndpointUrl, mySelectedEndpoint.SecurityPolicyUri, MessageSecurityMode.None, false, null, null);
                opcSession = myClientHelperAPI.Session;

                log.Debug("PLCHandler.init() end");
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Fetches the subtypes for the node.
        /// </summary>
        private List <ReferenceDescription> BrowseSubTypes(Opc.Ua.Client.Session client, NodeId nodeId)
        {
            List <ReferenceDescription> references = new List <ReferenceDescription>();

            // specify the references to follow and the fields to return.
            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId          = nodeId;
            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.NodeClassMask   = 0;
            nodeToBrowse.ResultMask      = (uint)BrowseResultMask.All;

            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            nodesToBrowse.Add(nodeToBrowse);

            // start the browse operation.
            BrowseResultCollection   results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = client.Browse(
                null,
                null,
                0,
                nodesToBrowse,
                out results,
                out diagnosticInfos);

            // these do sanity checks on the result - make sure response matched the request.
            ClientBase.ValidateResponse(results, nodesToBrowse);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse);

            // check status.
            if (StatusCode.IsBad(results[0].StatusCode))
            {
                // embed the diagnostic information in a exception.
                throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable);
            }

            // add first batch.
            references.AddRange(results[0].References);

            // check if server limited the results.
            while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0)
            {
                ByteStringCollection continuationPoints = new ByteStringCollection();
                continuationPoints.Add(results[0].ContinuationPoint);

                // continue browse operation.
                responseHeader = client.BrowseNext(
                    null,
                    false,
                    continuationPoints,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, continuationPoints);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints);

                // check status.
                if (StatusCode.IsBad(results[0].StatusCode))
                {
                    // embed the diagnostic information in a exception.
                    throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable);
                }

                // add next batch.
                references.AddRange(results[0].References);
            }

            return(references);
        }
Esempio n. 14
0
 public WriteOutput(Opc.Ua.Client.Session session) : base()
 {
     InitializeComponent();
     writeRequestListViewCtrl1.ChangeSession(session);
 }