public async Task <ActionResult> VariableRead(string jstreeNode)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            string   actionResult = string.Empty;
            string   endpointId   = Session["EndpointId"].ToString();

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            try
            {
                ValueReadRequestApiModel model = new ValueReadRequestApiModel();
                model.NodeId = node;
                var data = await TwinService.ReadNodeValueAsync(endpointId, model);

                string value = "";

                if (data.Value != null)
                {
                    if (data.Value.ToString().Length > 40)
                    {
                        value  = data.Value.ToString().Substring(0, 40);
                        value += "...";
                    }
                    else
                    {
                        value = data.Value.ToString();
                    }
                }
                // We return the HTML formatted content, which is shown in the context panel.
                actionResult = Strings.BrowserOpcDataValueLabel + ": " + value + @"<br/>" +
                               (data.ErrorInfo == null ? "" : (Strings.BrowserOpcDataStatusLabel + ": " + data.ErrorInfo.StatusCode + @"<br/>")) +
                               Strings.BrowserOpcDataSourceTimestampLabel + ": " + data.SourceTimestamp + @"<br/>" +
                               Strings.BrowserOpcDataServerTimestampLabel + ": " + data.ServerTimestamp;
                return(Content(actionResult));
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> VariableWriteFetch(string jstreeNode)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            string   actionResult = string.Empty;
            string   endpointId   = Session["EndpointId"].ToString();

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            try
            {
                ValueReadRequestApiModel model = new ValueReadRequestApiModel();
                model.NodeId = node;
                var data = await TwinService.ReadNodeValueAsync(endpointId, model);

                if (data.Value != null)
                {
                    if (data.Value.ToString().Length > 30)
                    {
                        actionResult  = data.Value.ToString().Substring(0, 30);
                        actionResult += "...";
                    }
                    else
                    {
                        actionResult = data.Value.ToString();
                    }
                }
                return(Content(actionResult));
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> GetRootNode()
        {
            List <object>         jsonTree   = new List <object>();
            string                endpointId = Session["EndpointId"].ToString();
            BrowseRequestApiModel model      = new BrowseRequestApiModel();

            model.NodeId          = "";
            model.TargetNodesOnly = true;

            try
            {
                var browseData = await TwinService.NodeBrowseAsync(endpointId, model);

                jsonTree.Add(new { id = browseData.Node.NodeId, text = browseData.Node.DisplayName, children = (browseData.References?.Count != 0) });

                return(Json(jsonTree, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                Session["EndpointId"] = null;
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> VariableWriteUpdate(string jstreeNode, string newValue)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            string   endpointId = Session["EndpointId"].ToString();

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            try
            {
                ValueWriteRequestApiModel model = new ValueWriteRequestApiModel();
                model.NodeId = node;
                model.Value  = newValue;
                var data = await TwinService.WriteNodeValueAsync(endpointId, model);

                if (data.ErrorInfo == null)
                {
                    return(Content(Strings.WriteSuccesfully));
                }
                else
                {
                    return(Content(data.ErrorInfo.ErrorMessage));
                }
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> MethodCall(string jstreeNode, string parameterData, string parameterValues, Session session = null)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            string   parentNode = null;
            string   endpointId = Session["EndpointId"].ToString();

            if (jstreeNodeSplit.Length == 1)
            {
                node       = jstreeNodeSplit[0];
                parentNode = null;
            }
            else
            {
                node       = jstreeNodeSplit[1];
                parentNode = (jstreeNodeSplit[0].Replace(delimiter[0], "")).Replace("__", "");
            }

            string actionResult = "";
            List <MethodCallParameterData> originalData = JsonConvert.DeserializeObject <List <MethodCallParameterData> >(parameterData);
            List <Variant> values = JsonConvert.DeserializeObject <List <Variant> >(parameterValues);
            List <MethodCallArgumentApiModel> argumentsList = new List <MethodCallArgumentApiModel>();

            try
            {
                MethodCallRequestApiModel model = new MethodCallRequestApiModel();
                model.MethodId = node;
                model.ObjectId = originalData[0].ObjectId;

                if (originalData.Count > 1)
                {
                    int count = 0;
                    foreach (var item in originalData)
                    {
                        MethodCallArgumentApiModel argument = new MethodCallArgumentApiModel();
                        argument.Value    = values[count].Value != null ? values[count].Value.ToString() : string.Empty;
                        argument.DataType = item.Datatype;
                        argumentsList.Add(argument);
                        count++;
                    }
                    model.Arguments = argumentsList;
                }

                var data = await TwinService.NodeMethodCallAsync(endpointId, model);

                if (data.ErrorInfo != null)
                {
                    actionResult = Strings.BrowserOpcMethodCallFailed + @"<br/><br/>" +
                                   Strings.BrowserOpcMethodStatusCode + ": " + data.ErrorInfo.StatusCode;
                    if (data.ErrorInfo.Diagnostics != null)
                    {
                        actionResult += @"<br/><br/>" + Strings.BrowserOpcDataDiagnosticInfoLabel + ": " + data.ErrorInfo.Diagnostics;
                    }
                }
                else
                {
                    if (data.Results.Count == 0)
                    {
                        actionResult = Strings.BrowserOpcMethodCallSucceeded;
                    }
                    else
                    {
                        actionResult = Strings.BrowserOpcMethodCallSucceededWithResults + @"<br/><br/>";
                        for (int ii = 0; ii < data.Results.Count; ii++)
                        {
                            actionResult += data.Results[ii].Value + @"<br/>";
                        }
                    }
                }
                return(Content(actionResult));
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> MethodCallGetParameter(string jstreeNode)
        {
            string[]      delimiter       = { "__$__" };
            string[]      jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string        node;
            List <object> jsonParameter  = new List <object>();
            int           parameterCount = 0;
            string        endpointId     = Session["EndpointId"].ToString();

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            try
            {
                MethodMetadataRequestApiModel model = new MethodMetadataRequestApiModel();
                model.MethodId = node;
                var data = await TwinService.NodeMethodGetMetadataAsync(endpointId, model);

                if (data.InputArguments == null)
                {
                    parameterCount = 0;
                    jsonParameter.Add(new { data.ObjectId });
                }
                else
                {
                    if (data.InputArguments.Count > 0)
                    {
                        foreach (var item in data.InputArguments)
                        {
                            jsonParameter.Add(new
                            {
                                objectId        = data.ObjectId,
                                name            = item.Name,
                                value           = item.DefaultValue,
                                valuerank       = item.ValueRank,
                                arraydimentions = item.ArrayDimensions,
                                description     = item.Description,
                                datatype        = item.Type.DataType,
                                typename        = item.Type.DisplayName
                            });
                        }
                    }
                    else
                    {
                        jsonParameter.Add(new { data.ObjectId });
                    }

                    parameterCount = data.InputArguments.Count;
                }

                return(Json(new { count = parameterCount, parameter = jsonParameter }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> VariablePublishUnpublish(string jstreeNode, string method)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            string   actionResult = "";
            string   endpointId   = Session["EndpointId"].ToString();

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            try
            {
                if (method == "unpublish")
                {
                    PublishStopRequestApiModel publishModel = new PublishStopRequestApiModel();
                    publishModel.NodeId = node;
                    var data = await TwinService.UnPublishNodeValuesAsync(endpointId, publishModel);

                    if (data.ErrorInfo != null)
                    {
                        actionResult = Strings.BrowserOpcUnPublishFailed + @"<br/><br/>" +
                                       Strings.BrowserOpcMethodStatusCode + ": " + data.ErrorInfo.StatusCode;
                        if (data.ErrorInfo.Diagnostics != null)
                        {
                            actionResult += @"<br/><br/>" + Strings.BrowserOpcDataDiagnosticInfoLabel + ": " + data.ErrorInfo.Diagnostics;
                        }
                    }
                    else
                    {
                        actionResult = Strings.BrowserOpcUnPublishSucceeded;
                    }
                }
                else
                {
                    PublishStartRequestApiModel publishModel = new PublishStartRequestApiModel();
                    PublishedItemApiModel       item         = new PublishedItemApiModel();
                    item.NodeId       = node;
                    publishModel.Item = item;
                    var data = await TwinService.PublishNodeValuesAsync(endpointId, publishModel);

                    if (data.ErrorInfo != null)
                    {
                        actionResult = Strings.BrowserOpcPublishFailed + @"<br/><br/>" +
                                       Strings.BrowserOpcMethodStatusCode + ": " + data.ErrorInfo.StatusCode;
                        if (data.ErrorInfo.Diagnostics != null)
                        {
                            actionResult += @"<br/><br/>" + Strings.BrowserOpcDataDiagnosticInfoLabel + ": " + data.ErrorInfo.Diagnostics;
                        }
                    }
                    else
                    {
                        actionResult = Strings.BrowserOpcPublishSucceeded;
                    }
                }
                return(Content(actionResult));
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
        public async Task <ActionResult> GetChildren(string jstreeNode)
        {
            // This delimiter is used to allow the storing of the OPC UA parent node ID together with the OPC UA child node ID in jstree data structures and provide it as parameter to
            // Ajax calls.
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            List <object> jsonTree    = new List <object>();
            string        endpointId  = Session["EndpointId"].ToString();
            string        endpointUrl = Session["EndpointUrl"].ToString();
            string        ProductUri  = Session["ProductUri"].ToString();

            // read the currently published nodes
            PublishedItemListResponseApiModel publishedNodes = new PublishedItemListResponseApiModel();

            try
            {
                PublishedItemListRequestApiModel publishModel = new PublishedItemListRequestApiModel();
                publishedNodes = await TwinService.GetPublishedNodesAsync(endpointId, publishModel);
            }
            catch (Exception e)
            {
                // do nothing, since we still want to show the tree
                Trace.TraceWarning("Can not read published nodes for endpoint '{0}'.", endpointUrl);
                string errorMessage = string.Format(Strings.BrowserOpcException, e.Message,
                                                    e.InnerException?.Message ?? "--", e?.StackTrace ?? "--");
                Trace.TraceWarning(errorMessage);
            }

            BrowseResponseApiModel browseData = new BrowseResponseApiModel();

            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                try
                {
                    BrowseRequestApiModel model = new BrowseRequestApiModel();
                    model.NodeId          = node;
                    model.TargetNodesOnly = false;

                    browseData = TwinService.NodeBrowse(endpointId, model);
                }
                catch (Exception e)
                {
                    // skip this node
                    Trace.TraceError("Can not browse node '{0}'", node);
                    string errorMessage = string.Format(Strings.BrowserOpcException, e.Message,
                                                        e.InnerException?.Message ?? "--", e?.StackTrace ?? "--");
                    Trace.TraceError(errorMessage);
                }

                Trace.TraceInformation("Browsing node '{0}' data took {0} ms", node.ToString(), stopwatch.ElapsedMilliseconds);

                if (browseData.References != null)
                {
                    var idList = new List <string>();
                    foreach (var nodeReference in browseData.References)
                    {
                        bool idFound = false;
                        foreach (var id in idList)
                        {
                            if (id == nodeReference.Target.NodeId.ToString())
                            {
                                idFound = true;
                            }
                        }
                        if (idFound == true)
                        {
                            continue;
                        }

                        Trace.TraceInformation("Browse '{0}' count: {1}", nodeReference.Target.NodeId, jsonTree.Count);

                        NodeApiModel currentNode = nodeReference.Target;

                        currentNode = nodeReference.Target;

                        byte currentNodeAccessLevel   = 0;
                        byte currentNodeEventNotifier = 0;
                        bool currentNodeExecutable    = false;

                        switch (currentNode.NodeClass)
                        {
                        case NodeClass.Variable:
                            currentNodeAccessLevel = (byte)currentNode.UserAccessLevel;
                            if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                            }
                            break;

                        case NodeClass.Object:
                            currentNodeEventNotifier = (byte)currentNode.EventNotifier;
                            break;

                        case NodeClass.View:
                            currentNodeEventNotifier = (byte)currentNode.EventNotifier;
                            break;

                        case NodeClass.Method:
                            if (PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = (bool)currentNode.UserExecutable;
                            }
                            break;

                        default:
                            break;
                        }

                        var isPublished = false;
                        var isRelevant  = false;
                        if (publishedNodes.Items != null)
                        {
                            foreach (var item in publishedNodes.Items)
                            {
                                if (item.NodeId == nodeReference.Target.NodeId.ToString())
                                {
                                    isPublished = true;
                                    ContosoOpcUaNode contosoOpcUaNode = Startup.Topology.GetOpcUaNode(ProductUri, item.NodeId);
                                    if (contosoOpcUaNode?.Relevance != null)
                                    {
                                        isRelevant = true;
                                    }
                                }
                            }
                        }

                        jsonTree.Add(new
                        {
                            id            = ("__" + node + delimiter[0] + nodeReference.Target.NodeId.ToString()),
                            text          = nodeReference.Target.DisplayName.ToString(),
                            nodeClass     = nodeReference.Target.NodeClass.ToString(),
                            accessLevel   = currentNodeAccessLevel.ToString(),
                            eventNotifier = currentNodeEventNotifier.ToString(),
                            executable    = currentNodeExecutable.ToString(),
                            children      = nodeReference.Target.HasChildren,
                            publishedNode = isPublished,
                            relevantNode  = isRelevant
                        });
                        idList.Add(nodeReference.Target.NodeId.ToString());
                    }
                }

                stopwatch.Stop();
                Trace.TraceInformation("Browing all childeren info of node '{0}' took {0} ms", node, stopwatch.ElapsedMilliseconds);

                return(Json(jsonTree, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exception)
            {
                return(Content(CreateOpcExceptionActionString(exception)));
            }
        }
Exemple #9
0
 public void ConfigureTwinService()
 {
     TwinService = new TwinService(TwinServiceUrl, Resource);
 }