Beispiel #1
0
        /// <summary>
        /// 创建父级目录(请确保对应的根目录已创建)
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="currentNode"></param>
        /// <returns></returns>
        public FolderState GetParentFolderState(IEnumerable <OpcuaNode> nodes, OpcuaNode currentNode)
        {
            FolderState folder = null;

            if (!_folderDic.TryGetValue(currentNode.ParentPath, out folder))
            {
                var parent = nodes.Where(d => d.NodePath == currentNode.ParentPath).FirstOrDefault();
                if (!string.IsNullOrEmpty(parent.ParentPath))
                {
                    var pFol = GetParentFolderState(nodes, parent);
                    folder = CreateFolder(pFol, parent.NodePath, parent.NodeName);
                    pFol.ClearChangeMasks(SystemContext, false);
                    AddPredefinedNode(SystemContext, folder);
                    _folderDic.Add(currentNode.ParentPath, folder);
                }
            }
            return(folder);
        }
Beispiel #2
0
 public AlarmConditionTypeHolder(
     AlarmNodeManager alarmNodeManager,
     FolderState parent,
     SourceController trigger,
     string name,
     SupportedAlarmConditionType alarmConditionType,
     Type controllerType,
     int interval,
     bool optional        = true,
     double maxShelveTime = AlarmDefines.NORMAL_MAX_TIME_SHELVED,
     bool create          = true) :
     base(alarmNodeManager, parent, trigger, name, alarmConditionType, controllerType, interval, optional, false)
 {
     if (create)
     {
         Initialize(Opc.Ua.ObjectTypes.AlarmConditionType, name, maxShelveTime);
     }
 }
Beispiel #3
0
        /// <summary>
        /// Creates OPC server child nodes.
        /// </summary>
        private void CreateChildNodes(FolderState rootFolder)
        {
            foreach (ILineContext lineContext in commContext.GetCommLines())
            {
                List <DeviceLogic> devices = new List <DeviceLogic>();
                devices.AddRange(deviceFilter == null ?
                                 lineContext.SelectDevices() :
                                 lineContext.SelectDevices(d => deviceFilter.Contains(d.DeviceNum)));

                if (devices.Count > 0)
                {
                    FolderState lineFolder = CreateFolder(rootFolder,
                                                          CommUtils.GetLineLogFileName(lineContext.CommLineNum, ""), lineContext.Title);

                    foreach (DeviceLogic deviceLogic in devices)
                    {
                        FolderState deviceFolder = CreateFolder(lineFolder,
                                                                CommUtils.GetDeviceLogFileName(deviceLogic.DeviceNum, ""), deviceLogic.Title);
                        DeviceVars deviceVars = new DeviceVars();
                        varByDevice[deviceLogic.DeviceNum] = deviceVars;

                        if (deviceLogic.DeviceTags.FlattenGroups)
                        {
                            foreach (TagGroup tagGroup in deviceLogic.DeviceTags.TagGroups)
                            {
                                CreateDeviceTagNodes(deviceFolder, deviceLogic, tagGroup, deviceVars);
                            }
                        }
                        else
                        {
                            int groupNum = 1;

                            foreach (TagGroup tagGroup in deviceLogic.DeviceTags.TagGroups)
                            {
                                FolderState groupFolder = CreateFolder(deviceFolder,
                                                                       "group" + groupNum.ToString("D3"), tagGroup.Name);
                                CreateDeviceTagNodes(groupFolder, deviceLogic, tagGroup, deviceVars);
                                groupNum++;
                            }
                        }
                    }
                }
            }
        }
Beispiel #4
0
        //// Folders
        //

        public FolderState CreateAddFolder(AasUaBaseEntity.CreateMode mode,
                                           NodeState parent, string browseDisplayName,
                                           NodeId extraParentNodeId = null,
                                           bool doNotAddToParent    = false)
        {
            var x = new FolderState(parent);

            x.BrowseName       = browseDisplayName;
            x.DisplayName      = browseDisplayName;
            x.NodeId           = nodeMgr.New(nodeMgr.SystemContext, mode, x);
            x.TypeDefinitionId = ObjectTypeIds.FolderType;
            nodeMgr.AddPredefinedNode(nodeMgr.SystemContext, x);
            if (parent != null && !doNotAddToParent)
            {
                parent.AddChild(x);
            }

            return(x);
        }
 public DiscreteHolder(
     AlarmNodeManager alarmNodeManager,
     FolderState parent,
     SourceController trigger,
     string name,
     SupportedAlarmConditionType alarmConditionType,
     Type controllerType,
     int interval,
     bool optional        = true,
     double maxShelveTime = AlarmDefines.NORMAL_MAX_TIME_SHELVED,
     bool create          = true) :
     base(alarmNodeManager, parent, trigger, name, alarmConditionType, controllerType, interval, optional, maxShelveTime, false)
 {
     Utils.LogTrace("{0} Discrete Constructor Optional = {1}", name, optional);
     if (create)
     {
         Initialize(ObjectTypes.DiscreteAlarmType, name, maxShelveTime);
     }
 }
Beispiel #6
0
    private IEnumerator MoveFolder(bool isUp)
    {
        if (!isUp)
        {
            transform.LeanMove(_basePosition, .2f);
            currentState = FolderState.MovingDown;
            yield return(new WaitForSeconds(.2f));

            currentState = FolderState.Down;
        }
        else
        {
            transform.LeanMove(_basePosition + new Vector3(0, .04f, 0), .2f);
            currentState = FolderState.MovingUp;
            yield return(new WaitForSeconds(.2f));

            currentState = FolderState.Up;
        }
    }
        /// <summary>
        /// Creates a new folder.
        /// </summary>
        private FolderState CreateFolder(NodeState parent, string path, string name)
        {
            FolderState folder = new FolderState(parent)
            {
                SymbolicName     = name,
                ReferenceTypeId  = ReferenceTypes.Organizes,
                TypeDefinitionId = ObjectTypeIds.FolderType,
                NodeId           = new NodeId(path, NamespaceIndex),
                BrowseName       = new QualifiedName(path, NamespaceIndex),
                DisplayName      = new LocalizedText("en", name),
                WriteMask        = AttributeWriteMask.None,
                UserWriteMask    = AttributeWriteMask.None,
                EventNotifier    = EventNotifiers.None
            };

            parent?.AddChild(folder);

            return(folder);
        }
        /// <summary>
        /// Does any initialization required before the address space can be used.
        /// </summary>
        /// <remarks>
        /// The externalReferences is an out parameter that allows the node manager to link to nodes
        /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
        /// should have a reference to the root folder node(s) exposed by this node manager.
        /// </remarks>
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            lock (Lock)
            {
                if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out IList <IReference> references))
                {
                    externalReferences[ObjectIds.ObjectsFolder] = references = new List <IReference>();
                }

                FolderState root = CreateFolder(null, ProgramName, ProgramName, NamespaceType.OpcPlcApplications);
                root.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
                references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, root.NodeId));
                root.EventNotifier = EventNotifiers.SubscribeToEvents;
                AddRootNotifier(root);

                var variables = new List <BaseDataVariableState>();

                try
                {
                    FolderState dataFolder = CreateFolder(root, "Telemetry", "Telemetry", NamespaceType.OpcPlcApplications);

                    AddChangingNodes(dataFolder);

                    AddSlowAndFastNodes(dataFolder);

                    FolderState methodsFolder = CreateFolder(root, "Methods", "Methods", NamespaceType.OpcPlcApplications);

                    AddMethods(methodsFolder);

                    AddUserConfigurableNodes(root);

                    AddComplexTypeBoiler(methodsFolder, externalReferences);

                    AddSpecialNodes(dataFolder);
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Error creating the address space.");
                }

                AddPredefinedNode(SystemContext, root);
            }
        }
Beispiel #9
0
        public HuiBoRobot(NodeState parent, string name, ushort NamespaceIndex, ServerSystemContext systemContext)
        {
            SystemContext = systemContext;
            FolderState myFolder = CreateFolder(parent, name, NamespaceIndex);


            RobotMode             = CreateVariable(myFolder, "RobotMode", DataTypeIds.Int32, ValueRanks.Scalar, 1, NamespaceIndex);
            RobotMode.Description = "机器人的数据模式,1:关节 2:基座标 3:工具坐标";

            RobotLocation             = CreateVariable(myFolder, "RobotLocation", DataTypeIds.Double, ValueRanks.OneDimension, new double[6], NamespaceIndex);
            RobotLocation.Description = "机器人的位置信息,该数据将根据模式不同而不一致";

            UserArrayBool              = CreateVariable(myFolder, "UserBool", DataTypeIds.Boolean, ValueRanks.OneDimension, new bool[16], NamespaceIndex);
            UserArrayBool.Description  = "备用的bool数据";
            UserArrayFloat             = CreateVariable(myFolder, "UserFloat", DataTypeIds.Float, ValueRanks.OneDimension, new float[16], NamespaceIndex);
            UserArrayFloat.Description = "备用的float数据";
            UserArrayInt             = CreateVariable(myFolder, "UserInt", DataTypeIds.Int32, ValueRanks.OneDimension, new int[16], NamespaceIndex);
            UserArrayInt.Description = "备用的int数据";
        }
Beispiel #10
0
        /// <summary>
        /// Creates a new area.
        /// </summary>
        private BaseObjectState CreateArea(SystemContext context, BaseObjectState platforms, string areaName)
        {
            System.Diagnostics.Contracts.Contract.Assume(context != null);
            var area = new FolderState(null)
            {
                NodeId     = new NodeId(areaName, NamespaceIndex),
                BrowseName = new QualifiedName(areaName, NamespaceIndex)
            };

            area.DisplayName      = area.BrowseName.Name;
            area.EventNotifier    = EventNotifiers.SubscribeToEvents | EventNotifiers.HistoryRead | EventNotifiers.HistoryWrite;
            area.TypeDefinitionId = Opc.Ua.ObjectTypeIds.FolderType;

            platforms.AddNotifier(SystemContext, ReferenceTypeIds.HasNotifier, false, area);
            area.AddNotifier(SystemContext, ReferenceTypeIds.HasNotifier, true, platforms);

            AddPredefinedNode(SystemContext, area);

            return(area);
        }
        private FolderState AddMethods(FolderState methodsFolder)
        {
            if (PlcSimulation.GeneratePosTrend || PlcSimulation.GenerateNegTrend)
            {
                MethodState resetTrendMethod = CreateMethod(methodsFolder, "ResetTrend", "ResetTrend", "Reset the trend values to their baseline value", NamespaceType.OpcPlcApplications);
                SetResetTrendMethodProperties(ref resetTrendMethod);
            }

            if (PlcSimulation.GenerateData)
            {
                MethodState resetStepUpMethod = CreateMethod(methodsFolder, "ResetStepUp", "ResetStepUp", "Resets the StepUp counter to 0", NamespaceType.OpcPlcApplications);
                SetResetStepUpMethodProperties(ref resetStepUpMethod);
                MethodState startStepUpMethod = CreateMethod(methodsFolder, "StartStepUp", "StartStepUp", "Starts the StepUp counter", NamespaceType.OpcPlcApplications);
                SetStartStepUpMethodProperties(ref startStepUpMethod);
                MethodState stopStepUpMethod = CreateMethod(methodsFolder, "StopStepUp", "StopStepUp", "Stops the StepUp counter", NamespaceType.OpcPlcApplications);
                SetStopStepUpMethodProperties(ref stopStepUpMethod);
            }

            return(methodsFolder);
        }
        private BaseDataVariableState[] CreateBaseLoadNodes(FolderState dataFolder, string name, uint count, NodeType type)
        {
            var nodes = new BaseDataVariableState[count];

            if (count > 0)
            {
                Logger.Information($"Creating {count} {name} nodes of type: {type}");
                Logger.Information("Node values will change every " + (name.Contains("Fast") ? PlcSimulation.FastNodeRate : PlcSimulation.SlowNodeRate) + " s");
                Logger.Information("Node values sampling rate is " + (name.Contains("Fast") ? PlcSimulation.FastNodeSamplingInterval : PlcSimulation.SlowNodeSamplingInterval) + " ms");
            }

            for (int i = 0; i < count; i++)
            {
                var(dataType, valueRank, defaultValue) = GetNodeType(type);

                string id = (i + 1).ToString();
                nodes[i] = CreateBaseVariable(dataFolder, $"{name}{type}{id}", $"{name}{type}{id}", dataType, valueRank, AccessLevels.CurrentReadOrWrite, "Constantly increasing value(s)", NamespaceType.OpcPlcApplications, defaultValue);
            }

            return(nodes);
        }
Beispiel #13
0
        /// <summary>
        /// Create a mechanism to create a folder
        /// </summary>
        public static FolderState CreateFolder(NodeState parent, ushort nameSpaceIndex, string path, string name)
        {
            FolderState folder = new FolderState(parent);

            folder.SymbolicName     = name;
            folder.ReferenceTypeId  = ReferenceTypes.Organizes;
            folder.TypeDefinitionId = ObjectTypeIds.FolderType;
            folder.NodeId           = new NodeId(path, nameSpaceIndex);
            folder.BrowseName       = new QualifiedName(path, nameSpaceIndex);
            folder.DisplayName      = new LocalizedText("en", name);
            folder.WriteMask        = AttributeWriteMask.None;
            folder.UserWriteMask    = AttributeWriteMask.None;
            folder.EventNotifier    = EventNotifiers.None;

            if (parent != null)
            {
                parent.AddChild(folder);
            }

            return(folder);
        }
Beispiel #14
0
        /// <summary>
        /// Creates node for Signal associated to Component in Visual Components.
        /// </summary>
        private BaseDataVariableState CreateVariableNode(FolderState parentFolder, string nodeName, NodeId nodeDataType)
        {
            string namespaceUri   = Namespaces.vc2opcua;
            string nodeNameParent = String.Format("{0}-{1}", nodeName, parentFolder.Parent.DisplayName);

            BaseDataVariableState variableNode = new BaseDataVariableState(parentFolder);
            NodeId nodeId = NodeId.Create(nodeNameParent, namespaceUri, uaServer.NamespaceUris);

            variableNode.Create(
                nodeManager.context,
                nodeId,
                new QualifiedName(nodeNameParent, (ushort)uaServer.NamespaceUris.GetIndex(namespaceUri)),
                new LocalizedText(nodeName),
                true);

            variableNode.DataType = nodeDataType;

            parentFolder.AddReference(ReferenceTypeIds.Organizes, false, variableNode.NodeId);
            variableNode.AddReference(ReferenceTypeIds.Organizes, true, parentFolder.NodeId);

            return(variableNode);
        }
Beispiel #15
0
        /// <summary>
        /// Does any initialization required before the address space can be used.
        /// </summary>
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            try
            {
                Monitor.Enter(dataLock);

                // create the root folder
                if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out IList <IReference> references))
                {
                    references = new List <IReference>();
                    externalReferences[ObjectIds.ObjectsFolder] = references;
                }

                FolderState rootFolder = CreateFolder(null, RootFolderName, RootFolderName);
                rootFolder.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
                references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, rootFolder.NodeId));
                rootFolder.EventNotifier = EventNotifiers.SubscribeToEvents;
                AddRootNotifier(rootFolder);

                // create child nodes
                varByDevice = new Dictionary <int, DeviceVars>();
                varByPath   = new Dictionary <string, VarItem>();
                CreateChildNodes(rootFolder);

                // recursively index the node
                AddPredefinedNode(SystemContext, rootFolder);
            }
            catch (Exception ex)
            {
                log.WriteException(ex, Locale.IsRussian ?
                                   "Ошибка при создании адресного пространства" :
                                   "Error creating address space");
                throw;
            }
            finally
            {
                Monitor.Exit(dataLock);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Gets the item configuration node.
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="namespaceIndex">Index of the namespace.</param>
        /// <returns></returns>
        public static BaseInstanceState GetItemConfigurationNode(string itemId, ushort namespaceIndex)
        {
            if (itemId == null)
            {
                return(null);
            }

            FolderState component = new FolderState(null);

            component.NodeId           = HdaParsedNodeId.Construct(HdaModelUtils.HdaItemConfiguration, itemId, null, namespaceIndex);
            component.SymbolicName     = Opc.Ua.BrowseNames.HAConfiguration;
            component.BrowseName       = new QualifiedName(component.SymbolicName);
            component.DisplayName      = component.BrowseName.Name;
            component.ReferenceTypeId  = Opc.Ua.ReferenceTypeIds.HasComponent;
            component.TypeDefinitionId = Opc.Ua.ObjectTypeIds.HistoricalDataConfigurationType;
            component.EventNotifier    = EventNotifiers.None;

            component.AddReference(ReferenceTypeIds.HasHistoricalConfiguration, true, HdaModelUtils.ConstructIdForHdaItem(itemId, namespaceIndex));
            component.AddReference(ReferenceTypeIds.HasComponent, false, HdaModelUtils.ConstructIdForInternalNode(Opc.Ua.BrowseNames.AggregateConfiguration, namespaceIndex));

            return(component);
        }
        private void AddUserConfigurableNodes(FolderState root)
        {
            if (!string.IsNullOrEmpty(_nodeFileName))
            {
                string json = File.ReadAllText(_nodeFileName);

                var cfgFolder = JsonConvert.DeserializeObject <ConfigFolder>(json, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All
                });

                Logger.Information($"Processing node information configured in {_nodeFileName}");
                Logger.Debug($"Create folder {cfgFolder.Folder}");
                FolderState userNodesFolder = CreateFolder(root, cfgFolder.Folder, cfgFolder.Folder, NamespaceType.OpcPlcApplications);

                foreach (var node in cfgFolder.NodeList)
                {
                    if (node.NodeId.GetType() != Type.GetType("System.Int64") && node.NodeId.GetType() != Type.GetType("System.String"))
                    {
                        Logger.Error($"The type of the node configuration for node with name {node.Name} ({node.NodeId.GetType()}) is not supported. Only decimal and string are supported. Default to string.");
                        node.NodeId = node.NodeId.ToString();
                    }
                    string typedNodeId = $"{(node.NodeId.GetType() == Type.GetType("System.Int64") ? "i=" : "s=")}{node.NodeId.ToString()}";
                    if (string.IsNullOrEmpty(node.Name))
                    {
                        node.Name = typedNodeId;
                    }
                    if (string.IsNullOrEmpty(node.Description))
                    {
                        node.Description = node.Name;
                    }
                    Logger.Debug($"Create node with Id '{typedNodeId}' and BrowseName '{node.Name}' in namespace with index '{NamespaceIndexes[(int)NamespaceType.OpcPlcApplications]}'");
                    CreateBaseVariable(userNodesFolder, node);
                }

                Logger.Information("Processing node information completed.");
            }
        }
        private void AddComplexTypeBoiler(FolderState methodsFolder, IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            if (PlcSimulation.AddComplexTypeBoiler)
            {
                // Load complex types from binary uanodes file.
                base.LoadPredefinedNodes(SystemContext, externalReferences);

                // Find the Boiler1 node that was created when the model was loaded.
                var passiveNode = (BaseObjectState)FindPredefinedNode(new NodeId(BoilerModel.Objects.Boiler1, NamespaceIndexes[(int)NamespaceType.Boiler]), typeof(BaseObjectState));

                // Convert to node that can be manipulated within the server.
                _boiler1 = new BoilerModel.BoilerState(null);
                _boiler1.Create(SystemContext, passiveNode);

                base.AddPredefinedNode(SystemContext, _boiler1);

                // Create heater on/off methods.
                MethodState heaterOnMethod = CreateMethod(methodsFolder, "HeaterOn", "HeaterOn", "Turn the heater on", NamespaceType.Boiler);
                SetHeaterOnMethodProperties(ref heaterOnMethod);
                MethodState heaterOffMethod = CreateMethod(methodsFolder, "HeaterOff", "HeaterOff", "Turn the heater off", NamespaceType.Boiler);
                SetHeaterOffMethodProperties(ref heaterOffMethod);
            }
        }
        public BaseObjectState addChildRootNode(string name, BaseObjectState parentNode = null)
        {
            if (parentNode == null)
            {
                parentNode = machines;
            }

            /*BaseObjectState objRoot = new BaseObjectState(parentNode);
             * objRoot.DisplayName = name;
             * objRoot.BrowseName = new QualifiedName(name, 3);
             * //objRoot.NodeId = getFreeNodeId(3,2000,1000);
             * objRoot.NodeId = new NodeId(name, 3);
             * objRoot.SymbolicName = name;
             * objRoot.ReferenceTypeId = ReferenceTypes.Organizes;
             * objRoot.TypeDefinitionId = ObjectTypeIds.BaseObjectType;
             * objRoot.WriteMask = AttributeWriteMask.None;
             * objRoot.UserWriteMask = AttributeWriteMask.None;
             * objRoot.EventNotifier = EventNotifiers.None;*/

            FolderState objfolder = new FolderState(parentNode);

            objfolder.SymbolicName     = name;
            objfolder.ReferenceTypeId  = ReferenceTypes.Organizes;
            objfolder.TypeDefinitionId = ObjectTypeIds.FolderType;
            objfolder.NodeId           = new NodeId(2003, NamespaceIndex);
            objfolder.BrowseName       = new QualifiedName(name, NamespaceIndex);
            objfolder.DisplayName      = new LocalizedText(name);
            objfolder.WriteMask        = AttributeWriteMask.None;
            objfolder.UserWriteMask    = AttributeWriteMask.None;
            objfolder.EventNotifier    = EventNotifiers.None;
            if (parentNode != null)
            {
                parentNode.AddChild(objfolder);
            }
            AddPredefinedNode(SystemContext, machines);
            return(objfolder);
        }
        private void AddDeviceCore(NodeState parent, XElement device)
        {
            if (device.Name == "DeviceNode")
            {
                // 提取名称和描述信息
                string name        = device.Attribute("Name").Value;
                string description = device.Attribute("Description").Value;

                // 创建OPC节点
                FolderState deviceFolder = CreateFolder(parent, device.Attribute("Name").Value, device.Attribute("Description").Value);
                // 添加Request
                foreach (var requestXml in device.Elements("DeviceRequest"))
                {
                    DeviceRequest deviceRequest = new DeviceRequest( );
                    deviceRequest.LoadByXmlElement(requestXml);


                    AddDeviceRequest(deviceFolder, deviceRequest);
                }


                IDeviceCore deviceReal = CreateNewByXml(device);
                if (deviceReal != null)
                {
                    deviceReal.OpcUaNode = deviceFolder.NodeId.ToString( );
                    AddDeviceCore(deviceReal);
                    deviceReal.WriteDeviceData = WriteDeviceData;
                    deviceReal.Name            = name;
                    deviceReal.StartRead( );

                    // 显示系统所有的设备数量
                    Interlocked.Increment(ref deviceCount);
                    this.logNet?.WriteInfo($"已发现 {deviceCount} 台设备,类型为{deviceReal.TypeName}");
                }
            }
        }
Beispiel #21
0
        /// <summary>
        /// Creates OPC server nodes that correspond to device tags.
        /// </summary>
        private void CreateDeviceTagNodes(FolderState folder, DeviceLogic deviceLogic, TagGroup tagGroup,
                                          DeviceVars deviceVars)
        {
            string pathPrefix = CommUtils.GetDeviceLogFileName(deviceLogic.DeviceNum, ".");

            foreach (DeviceTag deviceTag in tagGroup.DeviceTags)
            {
                if (!string.IsNullOrEmpty(deviceTag.Code))
                {
                    BaseDataVariableState variable = CreateVariable(folder, pathPrefix, deviceTag);
                    variable.OnSimpleWriteValue = OnSimpleWriteValue;

                    VarItem varItem = new VarItem
                    {
                        Variable  = variable,
                        DeviceTag = deviceTag,
                        DeviceNum = deviceLogic.DeviceNum
                    };

                    deviceVars[deviceTag.Code]            = varItem;
                    varByPath[variable.NodeId.ToString()] = varItem;
                }
            }
        }
        // any initialization required before the address space can be used.
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            lock (Lock)
            {
                if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out IList <IReference> references))
                {
                    externalReferences[ObjectIds.ObjectsFolder] = references = new List <IReference>();
                }
                FolderState root = CreateFolder(null, "CTT", "Test2");
                root.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
                references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, root.NodeId));
                root.EventNotifier = EventNotifiers.SubscribeToEvents;
                List <BaseDataVariableState> variables = new List <BaseDataVariableState>();

                try
                {
                    #region Scalar
                    FolderState           scalarFolder       = CreateFolder(root, "Scalar", "Scalar");
                    BaseDataVariableState scalarInstructions = CreateVariable(scalarFolder, "Scalar_Instructions", "Scalar_Instructions", DataTypeIds.String, ValueRanks.Scalar);
                    scalarInstructions.Value = "A library of Read/Write Variables of all supported data-types.";
                    variables.Add(scalarInstructions);
                    #endregion

                    #region Scalar_Static
                    FolderState  staticFolder = CreateFolder(root, "Scalar_Static", "Scalar_Static");
                    const string scalarStatic = "Scalar_Static_";
                    variables.Add(CreateVariable(staticFolder, scalarStatic + "Boolean", "Boolean", DataTypeIds.Boolean, ValueRanks.Scalar));
                    variables.Add(CreateVariable(staticFolder, scalarStatic + "Byte", "Byte", DataTypeIds.Byte, ValueRanks.Scalar));
                    variables.Add(CreateVariable(staticFolder, scalarStatic + "ByteString", "ByteString", DataTypeIds.ByteString, ValueRanks.Scalar));
                    variables.Add(CreateVariable(staticFolder, scalarStatic + "DateTime", "DateTime", DataTypeIds.DateTime, ValueRanks.Scalar));
                    variables.Add(CreateVariable(staticFolder, scalarStatic + "Double", "Double", DataTypeIds.Double, ValueRanks.Scalar));
                    BaseDataVariableState decimalVariable = CreateVariable(staticFolder, scalarStatic + "Decimal", "Decimal", DataTypeIds.DecimalDataType, ValueRanks.Scalar);
                    // Set an arbitrary precision decimal value.
                    BigInteger      largeInteger = BigInteger.Parse("1234567890123546789012345678901234567890123456789012345");
                    DecimalDataType decimalValue = new DecimalDataType
                    {
                        Scale = 100,
                        Value = largeInteger.ToByteArray()
                    };
                    decimalVariable.Value = decimalValue;
                    variables.Add(decimalVariable);
                    #endregion

                    #region Scalar_Simulation
                    FolderState  simulationFolder = CreateFolder(root, "Scalar_Smulation", "Simulation");
                    const string scalarSimulation = "Scalar_Simulation_";
                    CreateDynamicVariable(simulationFolder, scalarSimulation + "Boolean", "Boolean", DataTypeIds.Boolean, ValueRanks.Scalar);
                    CreateDynamicVariable(simulationFolder, scalarSimulation + "Byte", "Byte", DataTypeIds.Byte, ValueRanks.Scalar);
                    CreateDynamicVariable(simulationFolder, scalarSimulation + "ByteString", "ByteString", DataTypeIds.ByteString, ValueRanks.Scalar);
                    CreateDynamicVariable(simulationFolder, scalarSimulation + "DateTime", "DateTime", DataTypeIds.DateTime, ValueRanks.Scalar);
                    CreateDynamicVariable(simulationFolder, scalarSimulation + "Double", "Double", DataTypeIds.Double, ValueRanks.Scalar);
                    CreateDynamicVariable(simulationFolder, scalarSimulation + "Duration", "Duration", DataTypeIds.Duration, ValueRanks.Scalar);

                    BaseDataVariableState intervalVariable = CreateVariable(simulationFolder, scalarSimulation + "Interval", "Interval", DataTypeIds.UInt16, ValueRanks.Scalar);
                    intervalVariable.Value = m_simulationInterval;
                    intervalVariable.OnSimpleWriteValue = OnWriteInterval;

                    BaseDataVariableState enabledVariable = CreateVariable(simulationFolder, scalarSimulation + "Enabled", "Enabled", DataTypeIds.Boolean, ValueRanks.Scalar);
                    enabledVariable.Value = m_simulationEnabled;
                    enabledVariable.OnSimpleWriteValue = OnWriteEnabled;
                    #endregion
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Error creating the address space.");
                }

                AddPredefinedNode(SystemContext, root);
                m_simulationTimer = new Timer(DoSimulation, null, 3000, 1000);
            }
        }
        /// <summary>
        /// Does any initialization required before the address space can be used.
        /// </summary>
        /// <remarks>
        /// The externalReferences is an out parameter that allows the node manager to link to nodes
        /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
        /// should have a reference to the root folder node(s) exposed by this node manager.
        /// </remarks>
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            lock (Lock)
            {
                //Load DI nodeset
                LoadPredefinedNodes(SystemContext, externalReferences);

                //Add my variables to Address Space, under the DeviceSet object -----------------------
                //-------------------------------------------------------------------------------------

                //get the DeviceSet object of the Address Space
                NodeState DeviceSetobj = (NodeState)FindPredefinedNode(
                    ExpandedNodeId.ToNodeId(ObjectIds.DeviceSet, Server.NamespaceUris), typeof(NodeState));

                //-------------------------------------------------------------------------------------
                //create myDevice1 as a simple folder with a variable
                FolderState mydev1 = CreateFolder(DeviceSetobj, "myDevice1", "myDevice1");

                //create myDevice1/myVar1
                BaseDataVariableState myvar1 = CreateVariable(mydev1, "myVar1", "myVar1", Opc.Ua.DataTypeIds.Double, ValueRanks.Scalar);

                //create myDevice1/Actual_State
                BaseDataVariableState Actual_State = CreateVariable(mydev1, "Actual_State", "Actual_State", Opc.Ua.DataTypeIds.Double, ValueRanks.Scalar);

                //create myDevice1/Sensors_Data
                Sensors_Data = CreateVariable(mydev1, "Sensors_Data", "Sensors_Data", Opc.Ua.DataTypeIds.Double, ValueRanks.OneDimension);

                //create myDevice1/myVar2
                myvar2 = CreateVariable(mydev1, "myVar2", "myVar2", Opc.Ua.DataTypeIds.Int16, ValueRanks.Scalar);

                ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // Poject

                //create myDevice1/Start_Piece
                Start_Piece = CreateVariable(mydev1, "Start_Piece", "Start_Piece", Opc.Ua.DataTypeIds.Boolean, ValueRanks.Scalar);

                // create myDevice1/Mould_1
                Mould_1 = CreateVariable(mydev1, "Mould_1", "Mould_1", Opc.Ua.DataTypeIds.String, ValueRanks.Scalar);

                // create myDevice1/Mould_1_SN
                Mould_1_SN = CreateVariable(mydev1, "Mould_1_SN", "Mould_1_SN", Opc.Ua.DataTypeIds.String, ValueRanks.Scalar);

                // create myDevice1/Mould_2
                Mould_2 = CreateVariable(mydev1, "Mould_2", "Mould_2", Opc.Ua.DataTypeIds.String, ValueRanks.Scalar);

                // create myDevice1/Mould_2_SN
                Mould_2_SN = CreateVariable(mydev1, "Mould_2_SN", "Mould_2_SN", Opc.Ua.DataTypeIds.String, ValueRanks.Scalar);

                // create myDevice1/Piece_SN
                Piece_SN = CreateVariable(mydev1, "Piece_SN", "Piece_SN", Opc.Ua.DataTypeIds.Int32, ValueRanks.Scalar);

                // create myDevice1/Piece_SN
                Machine_SN = CreateVariable(mydev1, "Machine_SN", "Machine_SN", Opc.Ua.DataTypeIds.String, ValueRanks.Scalar);

                //create myDevice1/Change_Mould
                Change_Mould = CreateVariable(mydev1, "Change_Mould", "Change_Mould", Opc.Ua.DataTypeIds.Boolean, ValueRanks.Scalar);

                //create myDevice1/Mould_Changed
                Mould_Changed = CreateVariable(mydev1, "Mould_Changed", "Mould_Changed", Opc.Ua.DataTypeIds.Boolean, ValueRanks.Scalar);

                // create myDevice1/Actual_Mould
                Actual_Mould = CreateVariable(mydev1, "Actual_Mould", "Actual_Mould", Opc.Ua.DataTypeIds.Int32, ValueRanks.Scalar);

                // create myDevice1/Mould_tobeused
                Mould_tobeused = CreateVariable(mydev1, "Mould_tobeused", "Mould_tobeused", Opc.Ua.DataTypeIds.String, ValueRanks.Scalar);

                // create myDevice1/Operator_ID
                Operator_ID = CreateVariable(mydev1, "Operator_ID", "Operator_ID", Opc.Ua.DataTypeIds.Int32, ValueRanks.Scalar);

                // create myDevice1/Robot_Finished
                Robot_Finished = CreateVariable(mydev1, "Robot_Finished", "Robot_Finished", Opc.Ua.DataTypeIds.Boolean, ValueRanks.Scalar);

                //initialize var
                myvar1.Value         = (double)0.0;
                myvar2.Value         = (short)0;
                Actual_State.Value   = (double)0.0;
                Start_Piece.Value    = (bool)false;
                Mould_1.Value        = (string)"Mould 1";
                Mould_2.Value        = (string)"Mould 2";
                Mould_1_SN.Value     = (string)"1";
                Mould_2_SN.Value     = (string)"2";
                Piece_SN.Value       = (int)1;
                Machine_SN.Value     = (string)"1";
                Change_Mould.Value   = (bool)false;
                Robot_Finished.Value = (bool)true;
                Actual_Mould.Value   = (int)0;
                //Sensors_Data.Value = (int[])null;
                Mould_tobeused.Value = Mould_1_SN.Value;
                Mould_Changed.Value  = (bool)false;

                //store variable in my variable list for latter access (not necessary if variable is declare as a field of the class)
                m_dynamicNodes.Add(myvar1);
                m_dynamicNodes.Add(Actual_State);
                //add to Address Space
                AddPredefinedNode(SystemContext, mydev1);

                //-------------------------------------------------------------------------------------

                //Create a new object using the type "Device" defined by the DI specification
                //The class DeviceState is defined in the code generated by ModelCompiler
                myTemperatureSensor = new DeviceState(null);
                myTemperatureSensor.Create(SystemContext,
                                           null,
                                           new QualifiedName("myTemperatureSensor", m_namespaceIndex),
                                           null,
                                           true);

                //Object is created under DeviceSet
                DeviceSetobj.AddChild(myTemperatureSensor);

                //create a variable to hold the value of the temperature, of the type AnalogItem, under myTemperatureSensor
                TemperatureValue = new AnalogItemState(null);
                TemperatureValue.Create(SystemContext,
                                        null,
                                        new QualifiedName("Temperature", m_namespaceIndex),
                                        null,
                                        true);

                //Object is created under myTemperatureSensor
                myTemperatureSensor.AddChild(TemperatureValue);

                //initialize var
                TemperatureValue.Value = (double)0.0;

                //the type "Device" has a set of predefined info variables
                myTemperatureSensor.SerialNumber.Value = "AABB112233";
                myTemperatureSensor.Manufacturer.Value = "ACME";
                myTemperatureSensor.Model.Value        = new LocalizedText("PT", "MODEL 1.0");

                //add to Address Space
                AddPredefinedNode(SystemContext, myTemperatureSensor);


                //-------------------------------------------------------------------------------------
                //-------------------------------------------------------------------------------------

                //initialize Modbus client
                Modbus_client = new ModbusClient(Modbus_IP, Modbus_port);
                Modbus_client.ConnectionTimeout = 5000;

                // start periodic method to update my Address Space variables
                m_doprocessingTimer = new Timer(myDoProcessing, null, m_doprocessingInterval, m_doprocessingInterval);
            }
        }
        private void CreateBaseVariable(FolderState root, ConfigNode node)
        {
            BuiltInType tp;

            if (Enum.TryParse <BuiltInType>(node.DataType, out tp) == false)
            {
                throw new ArgumentException($"Value {node.DataType} of node {node.NodeId} cannot be parsed.");
            }

            byte accessLevel = 0;

            // We have to hard code conversion here, because AccessLevel is defined as byte in OPCUA lib.
            switch (node.AccessLevel)
            {
            case "None":
                accessLevel = AccessLevels.None;
                break;

            case "CurrentRead":
                accessLevel = AccessLevels.CurrentRead;
                break;

            case "CurrentWrite":
                accessLevel = AccessLevels.CurrentWrite;
                break;

            case "CurrentReadOrWrite":
                accessLevel = AccessLevels.CurrentReadOrWrite;
                break;

            case "HistoryRead":
                accessLevel = AccessLevels.HistoryRead;
                break;

            case "HistoryWrite":
                accessLevel = AccessLevels.HistoryWrite;
                break;

            case "HistoryReadOrWrite":
                accessLevel = AccessLevels.HistoryReadOrWrite;
                break;

            case "SemanticChange":
                accessLevel = AccessLevels.SemanticChange;
                break;

            case "StatusWrite":
                accessLevel = AccessLevels.StatusWrite;
                break;

            case "TimestampWrite":
                accessLevel = AccessLevels.TimestampWrite;
                break;

            default:
                throw new ArgumentException($"Unsupported AccessLevel '{node.AccessLevel}'");
            }
            ;

            CreateBaseVariable(root, node.NodeId, node.Name, tp, node.ValueRank, accessLevel, node.Description.ToString());
        }
Beispiel #25
0
        /// <summary>
        /// Finds the child with the specified browse name.
        /// </summary>
        protected override BaseInstanceState FindChild(
            ISystemContext context,
            QualifiedName browseName,
            bool createOrReplace,
            BaseInstanceState replacement)
        {
            if (QualifiedName.IsNull(browseName))
            {
                return(null);
            }

            BaseInstanceState instance = null;

            switch (browseName.Name)
            {
            case vc2opcua.BrowseNames.Signals:
            {
                if (createOrReplace)
                {
                    if (Signals == null)
                    {
                        if (replacement == null)
                        {
                            Signals = new FolderState(this);
                        }
                        else
                        {
                            Signals = (FolderState)replacement;
                        }
                    }
                }

                instance = Signals;
                break;
            }

            case vc2opcua.BrowseNames.Properties:
            {
                if (createOrReplace)
                {
                    if (Properties == null)
                    {
                        if (replacement == null)
                        {
                            Properties = new FolderState(this);
                        }
                        else
                        {
                            Properties = (FolderState)replacement;
                        }
                    }
                }

                instance = Properties;
                break;
            }
            }

            if (instance != null)
            {
                return(instance);
            }

            return(base.FindChild(context, browseName, createOrReplace, replacement));
        }
        /// <summary>
        /// Does any initialization required before the address space can be used.
        /// </summary>
        /// <remarks>
        /// The externalReferences is an out parameter that allows the node manager to link to nodes
        /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
        /// should have a reference to the root folder node(s) exposed by this node manager.
        /// </remarks>
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            lock (Lock)
            {
                base.CreateAddressSpace(externalReferences);

                #region Task #A1 - Create Root Folder
                // create the root folder.
                FolderState root = new FolderState(null);

                root.NodeId           = GenerateNodeId();
                root.BrowseName       = new QualifiedName("Root", NamespaceIndex);
                root.DisplayName      = root.BrowseName.Name;
                root.TypeDefinitionId = ObjectTypeIds.FolderType;

                // ensure root can be found via the server object.
                IList <IReference> references = null;

                if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out references))
                {
                    externalReferences[ObjectIds.ObjectsFolder] = references = new List <IReference>();
                }

                root.AddReference(ReferenceTypeIds.Organizes, true, ObjectIds.ObjectsFolder);
                references.Add(new NodeStateReference(ReferenceTypeIds.Organizes, false, root.NodeId));

                // save the node for later lookup.
                AddPredefinedNode(SystemContext, root);
                #endregion

                #region Task #A2 - Create Object Instance with a Property
                // create the folder object.
                BaseObjectState instance = new BaseObjectState(null);

                instance.NodeId           = GenerateNodeId();
                instance.BrowseName       = new QualifiedName("Object", NamespaceIndex);
                instance.DisplayName      = instance.BrowseName.Name;
                instance.TypeDefinitionId = ObjectTypeIds.BaseObjectType;

                // create a losely coupled relationship with the root object.
                root.AddReference(ReferenceTypeIds.Organizes, false, instance.NodeId);
                instance.AddReference(ReferenceTypeIds.Organizes, true, root.NodeId);

                // create a property.
                PropertyState <int> property = new PropertyState <int>(instance);

                property.NodeId                  = GenerateNodeId();
                property.BrowseName              = new QualifiedName("Property", NamespaceIndex);
                property.DisplayName             = property.BrowseName.Name;
                property.TypeDefinitionId        = VariableTypeIds.PropertyType;
                property.DataType                = DataTypeIds.Int32;
                property.ValueRank               = ValueRanks.Scalar;
                property.MinimumSamplingInterval = MinimumSamplingIntervals.Continuous;
                property.AccessLevel             = AccessLevels.CurrentReadOrWrite;
                property.UserAccessLevel         = AccessLevels.CurrentReadOrWrite;
                property.Historizing             = false;
                property.ReferenceTypeId         = ReferenceTypeIds.HasProperty;

                // create a property that is tightly coupled.
                instance.AddChild(property);

                // save the node for later lookup (all tightly coupled children are added with this call).
                AddPredefinedNode(SystemContext, instance);
                #endregion

                #region Task #A3 - Create a Variable using the Built-in Type Model
                // create the variable.
                AnalogItemState <double> variable = new AnalogItemState <double>(instance);

                // add optional properties.
                variable.InstrumentRange = new PropertyState <Range>(variable);

                // instantiate based on the type model. assigns ids automatically using SystemContext.NodeIdFactory
                variable.Create(
                    SystemContext,
                    GenerateNodeId(),
                    new QualifiedName("Variable", NamespaceIndex),
                    null,
                    true);

                // set default values.
                variable.EURange.Value         = new Range(90, 10);
                variable.InstrumentRange.Value = new Range(100, 0);

                // tightly coupled.
                instance.AddChild(variable);

                // need to add it manually since its parent was already added.
                AddPredefinedNode(SystemContext, variable);
                #endregion

                #region Task #A4 - Add Dynamic Behavoir by Updating In-Memory Nodes
                m_property        = property;
                m_simulationTimer = new Timer(DoSimulation, null, 1000, 1000);
                #endregion

                #region Task #A5 - Add Support for External Nodes
                // External nodes are nodes that reference an entity which stored elsewhere.
                // These nodes use no memory in the server unless they are accessed.
                // The NodeId is a string that is used to create the external node on demand.
                root.AddReference(ReferenceTypeIds.Organizes, false, CreateNodeId("Alpha"));
                root.AddReference(ReferenceTypeIds.Organizes, false, CreateNodeId("Omega"));
                #endregion

                #region Task #A7 - Add Support for Method
                MethodState method = new MethodState(instance);

                method.NodeId          = GenerateNodeId();
                method.BrowseName      = new QualifiedName("Method", NamespaceIndex);
                method.DisplayName     = method.BrowseName.Name;
                method.Executable      = true;
                method.UserExecutable  = true;
                method.ReferenceTypeId = ReferenceTypeIds.HasComponent;

                instance.AddChild(method);

                // create the input arguments.
                PropertyState <Argument[]> inputArguments = new PropertyState <Argument[]>(method);

                inputArguments.NodeId                  = GenerateNodeId();
                inputArguments.BrowseName              = new QualifiedName(BrowseNames.InputArguments);
                inputArguments.DisplayName             = inputArguments.BrowseName.Name;
                inputArguments.TypeDefinitionId        = VariableTypeIds.PropertyType;
                inputArguments.DataType                = DataTypeIds.Argument;
                inputArguments.ValueRank               = ValueRanks.OneDimension;
                inputArguments.MinimumSamplingInterval = MinimumSamplingIntervals.Continuous;
                inputArguments.AccessLevel             = AccessLevels.CurrentRead;
                inputArguments.UserAccessLevel         = AccessLevels.CurrentRead;
                inputArguments.Historizing             = false;
                inputArguments.ReferenceTypeId         = ReferenceTypeIds.HasProperty;

                inputArguments.Value = new Argument[]
                {
                    new Argument()
                    {
                        Name = "CurrentCount", Description = "The current count.", DataType = DataTypeIds.Int32, ValueRank = ValueRanks.Scalar
                    }
                };

                method.InputArguments = inputArguments;

                // create the output arguments.
                PropertyState <Argument[]> outputArguments = new PropertyState <Argument[]>(method);

                outputArguments.NodeId                  = GenerateNodeId();
                outputArguments.BrowseName              = new QualifiedName(BrowseNames.OutputArguments);
                outputArguments.DisplayName             = outputArguments.BrowseName.Name;
                outputArguments.TypeDefinitionId        = VariableTypeIds.PropertyType;
                outputArguments.DataType                = DataTypeIds.Argument;
                outputArguments.ValueRank               = ValueRanks.OneDimension;
                outputArguments.MinimumSamplingInterval = MinimumSamplingIntervals.Continuous;
                outputArguments.AccessLevel             = AccessLevels.CurrentRead;
                outputArguments.UserAccessLevel         = AccessLevels.CurrentRead;
                outputArguments.Historizing             = false;
                outputArguments.ReferenceTypeId         = ReferenceTypeIds.HasProperty;

                outputArguments.Value = new Argument[]
                {
                    new Argument()
                    {
                        Name = "NewCount", Description = "The new count.", DataType = DataTypeIds.Int32, ValueRank = ValueRanks.Scalar
                    }
                };

                method.OutputArguments = outputArguments;

                // save the node for later lookup (all tightly coupled children are added with this call).
                AddPredefinedNode(SystemContext, instance);

                // register handler.
                method.OnCallMethod = new GenericMethodCalledEventHandler(DoMethodCall);
                #endregion

                #region Task #D6 - Add Support for Notifiers
                // enable subscriptions.
                root.EventNotifier = EventNotifiers.SubscribeToEvents;

                // creating notifier ensures events propogate up the hierarchy when the are produced.
                AddRootNotifier(root);

                // add link to server object.
                if (!externalReferences.TryGetValue(ObjectIds.Server, out references))
                {
                    externalReferences[ObjectIds.Server] = references = new List <IReference>();
                }

                references.Add(new NodeStateReference(ReferenceTypeIds.HasNotifier, false, root.NodeId));

                // add sub-notifiers.
                instance.EventNotifier = EventNotifiers.SubscribeToEvents;
                instance.AddNotifier(SystemContext, ReferenceTypeIds.HasNotifier, true, root);
                root.AddNotifier(SystemContext, ReferenceTypeIds.HasNotifier, false, instance);
                #endregion
            }
        }
        /// <summary>
        /// Adds an aggregate function to the server capabilities object.
        /// </summary>
        public void AddAggregateFunction(NodeId aggregateId, string aggregateName, bool isHistorical)
        {
            lock (Lock)
            {
                FolderState state = new FolderState(null);

                state.SymbolicName = aggregateName;
                state.ReferenceTypeId = ReferenceTypes.HasComponent;
                state.TypeDefinitionId = ObjectTypeIds.AggregateFunctionType;
                state.NodeId = aggregateId;
                state.BrowseName = new QualifiedName(aggregateName, aggregateId.NamespaceIndex);
                state.DisplayName = state.BrowseName.Name;
                state.WriteMask = AttributeWriteMask.None;
                state.UserWriteMask = AttributeWriteMask.None;
                state.EventNotifier = EventNotifiers.None;

                NodeState folder = FindPredefinedNode(ObjectIds.Server_ServerCapabilities_AggregateFunctions, typeof(BaseObjectState));

                if (folder != null)
                {
                    folder.AddReference(ReferenceTypes.Organizes, false, state.NodeId);
                    state.AddReference(ReferenceTypes.Organizes, true, folder.NodeId);
                }

                if (isHistorical)
                {
                    folder = FindPredefinedNode(ObjectIds.HistoryServerCapabilities_AggregateFunctions, typeof(BaseObjectState));
                    
                    if (folder != null)
                    {
                        folder.AddReference(ReferenceTypes.Organizes, false, state.NodeId);
                        state.AddReference(ReferenceTypes.Organizes, true, folder.NodeId);
                    }
                }

                AddPredefinedNode(SystemContext, state);               
            }
        }
        private void ReadNative(Queue <FolderState> subdirs, CancellationToken token)
        {
            Win32FindData find        = new Win32FindData();
            FolderState   folderState = subdirs.Dequeue();
            ScanningState state       = folderState.State;
            FolderNode    parent      = folderState.Folder;
            bool          findResult;
            string        parentPath    = parent.Path;
            string        searchPattern = PathUtils.CombineNoChecks(parentPath, "*");

            if (!searchPattern.StartsWith(@"\\?\"))
            {
                searchPattern = @"\\?\" + searchPattern;
            }
            IntPtr hFind = FindFirstFileEx(searchPattern,
                                           FindExInfoLevels.Basic, out find,
                                           FindExSearchOps.NameMatch, IntPtr.Zero,
                                           FindExFlags.LargeFetch);

            if (hFind == InvalidHandle)
            {
                return;
            }

            FolderNode   fileCollection = null;
            FileNodeBase singleFile     = null;

            try {
                do
                {
                    string filePath = PathUtils.CombineNoChecks(parentPath, find.cFileName);
                    if (find.IsRelativeDirectory || SkipFile(state, find.cFileName, filePath))
                    {
                        // Skip these types of entries
                        findResult = FindNextFile(hFind, out find);
                        continue;
                    }
                    FileNodeBase child;
                    if (find.IsDirectory)
                    {
                        FolderNode folder = new FolderNode(find);
                        child = folder;
                        if (!find.IsSymbolicLink)
                        {
                            subdirs.Enqueue(new FolderState(folder, state));
                        }
                    }
                    else
                    {
                        FileNode file = new FileNode(find);
                        child = file;
                        if (!find.IsSymbolicLink)
                        {
                            state.ScannedSize += child.Size;
                            totalScannedSize  += child.Size;
                        }
                        file.extRecord = extensions.Include(GetExtension(file.Name), child.Size);
                    }
                    parent.AddChild(child, ref fileCollection, ref singleFile);

                    SuspendCheck();
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    findResult = FindNextFile(hFind, out find);
                } while (findResult);

                //if (parent.IsWatched)
                //	parent.RaiseChanged(FileNodeAction.ChildrenDone);
            }
            finally {
                FindClose(hFind);
            }
        }
        /// <summary>
        /// Does any initialization required before the address space can be used.
        /// </summary>
        /// <remarks>
        /// The externalReferences is an out parameter that allows the node manager to link to nodes
        /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
        /// should have a reference to the root folder node(s) exposed by this node manager.
        /// </remarks>
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            lock (Lock)
            {
                #region Setup

                IList <IReference> references = null;

                if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out references))
                {
                    externalReferences[ObjectIds.ObjectsFolder] = references = new List <IReference>();
                }

                #endregion

                try
                {
                    #region Initialize

                    string alarmsName     = "Alarms";
                    string alarmsNodeName = alarmsName;

                    Type   alarmControllerType = Type.GetType("Alarms.AlarmController");
                    int    interval            = 1000;
                    string intervalString      = interval.ToString();

                    int conditionTypeIndex = 0;
                    #endregion

                    #region Create Alarm Folder

                    FolderState alarmsFolder = CreateFolder(null, alarmsNodeName, alarmsName);
                    alarmsFolder.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
                    references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, alarmsFolder.NodeId));
                    alarmsFolder.EventNotifier = EventNotifiers.SubscribeToEvents;
                    AddRootNotifier(alarmsFolder);

                    #endregion

                    #region Create Methods
                    string      startMethodName     = "Start";
                    string      startMethodNodeName = alarmsNodeName + "." + startMethodName;
                    MethodState startMethod         = AlarmHelpers.CreateMethod(alarmsFolder, NamespaceIndex, startMethodNodeName, startMethodName);
                    AlarmHelpers.AddStartInputParameters(startMethod, NamespaceIndex);
                    startMethod.OnCallMethod = new GenericMethodCalledEventHandler(OnStart);

                    string      startBranchMethodName     = "StartBranch";
                    string      startBranchMethodNodeName = alarmsNodeName + "." + startBranchMethodName;
                    MethodState startBranchMethod         = AlarmHelpers.CreateMethod(alarmsFolder, NamespaceIndex, startBranchMethodNodeName, startBranchMethodName);
                    AlarmHelpers.AddStartInputParameters(startBranchMethod, NamespaceIndex);
                    startBranchMethod.OnCallMethod = new GenericMethodCalledEventHandler(OnStartBranch);

                    string      endMethodName     = "End";
                    string      endMethodNodeName = alarmsNodeName + "." + endMethodName;
                    MethodState endMethod         = AlarmHelpers.CreateMethod(alarmsFolder, NamespaceIndex, endMethodNodeName, endMethodName);
                    endMethod.OnCallMethod = new GenericMethodCalledEventHandler(OnEnd);
                    #endregion

                    #region Create Variables

                    string analogTriggerName            = "AnalogSource";
                    string analogTriggerNodeName        = alarmsNodeName + "." + analogTriggerName;
                    BaseDataVariableState analogTrigger = AlarmHelpers.CreateVariable(alarmsFolder,
                                                                                      NamespaceIndex, analogTriggerNodeName, analogTriggerName);
                    analogTrigger.OnWriteValue = OnWriteAlarmTrigger;
                    AlarmController  analogAlarmController  = (AlarmController)Activator.CreateInstance(alarmControllerType, analogTrigger, interval, false);
                    SourceController analogSourceController = new SourceController(analogTrigger, analogAlarmController);
                    m_triggerMap.Add("Analog", analogSourceController);

                    string booleanTriggerName            = "BooleanSource";
                    string booleanTriggerNodeName        = alarmsNodeName + "." + booleanTriggerName;
                    BaseDataVariableState booleanTrigger = AlarmHelpers.CreateVariable(alarmsFolder,
                                                                                       NamespaceIndex, booleanTriggerNodeName, booleanTriggerName, boolValue: true);
                    booleanTrigger.OnWriteValue = OnWriteAlarmTrigger;
                    AlarmController  booleanAlarmController  = (AlarmController)Activator.CreateInstance(alarmControllerType, booleanTrigger, interval, true);
                    SourceController booleanSourceController = new SourceController(booleanTrigger, booleanAlarmController);
                    m_triggerMap.Add("Boolean", booleanSourceController);

                    #endregion

                    #region Create Alarms

                    AlarmHolder mandatoryExclusiveLevel = new ExclusiveLevelHolder(
                        this,
                        alarmsFolder,
                        analogSourceController,
                        intervalString,
                        GetSupportedAlarmConditionType(ref conditionTypeIndex),
                        alarmControllerType,
                        interval,
                        optional: false);

                    m_alarms.Add(mandatoryExclusiveLevel.AlarmNodeName, mandatoryExclusiveLevel);

                    AlarmHolder mandatoryNonExclusiveLevel = new NonExclusiveLevelHolder(
                        this,
                        alarmsFolder,
                        analogSourceController,
                        intervalString,
                        GetSupportedAlarmConditionType(ref conditionTypeIndex),
                        alarmControllerType,
                        interval,
                        optional: false);
                    m_alarms.Add(mandatoryNonExclusiveLevel.AlarmNodeName, mandatoryNonExclusiveLevel);

                    AlarmHolder offNormal = new OffNormalAlarmTypeHolder(
                        this,
                        alarmsFolder,
                        booleanSourceController,
                        intervalString,
                        GetSupportedAlarmConditionType(ref conditionTypeIndex),
                        alarmControllerType,
                        interval,
                        optional: false);
                    m_alarms.Add(offNormal.AlarmNodeName, offNormal);


                    #endregion

                    AddPredefinedNode(SystemContext, alarmsFolder);
                    StartTimer();
                    m_allowEntry = true;
                }
                catch (Exception e)
                {
                    Utils.LogError(e, "Error creating the AlarmNodeManager address space.");
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Does any initialization required before the address space can be used.
        /// </summary>
        /// <remarks>
        /// The externalReferences is an out parameter that allows the node manager to link to nodes
        /// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
        /// should have a reference to the root folder node(s) exposed by this node manager.
        /// </remarks>
        public override void CreateAddressSpace(IDictionary <NodeId, IList <IReference> > externalReferences)
        {
            lock (Lock)
            {
                LoadPredefinedNodes(SystemContext, externalReferences);

                IList <IReference> references = null;

                if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out references))
                {
                    externalReferences[ObjectIds.ObjectsFolder] = references = new List <IReference>();
                }

                FolderState rootMy = CreateFolder(null, "Machines");
                rootMy.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
                references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, rootMy.NodeId));
                rootMy.EventNotifier = EventNotifiers.SubscribeToEvents;
                AddRootNotifier(rootMy);

                string[] machines = new string[] { "Machine A", "Machine B", "Machine C" };
                list = new List <BaseDataVariableState <int> >();

                for (int i = 0; i < machines.Length; i++)
                {
                    FolderState myFolder = CreateFolder(rootMy, machines[i]);

                    CreateVariable(myFolder, "Name", DataTypeIds.String, ValueRanks.Scalar, "测试数据").Description   = "设备的名称";
                    CreateVariable(myFolder, "IsFault", DataTypeIds.Boolean, ValueRanks.Scalar, true).Description = "设备是否启动";
                    CreateVariable(myFolder, "TestValueFloat", DataTypeIds.Float, ValueRanks.Scalar, 100.5f);
                    CreateVariable(myFolder, "AlarmTime", DataTypeIds.DateTime, ValueRanks.Scalar, DateTime.Now);
                    list.Add(CreateVariable(myFolder, "TestValueInt", DataTypeIds.Int32, ValueRanks.Scalar, 47123));



                    #region Add Method

                    MethodState addMethod = CreateMethod(myFolder, "Calculate");
                    // set input arguments
                    addMethod.InputArguments = new PropertyState <Argument[]>(addMethod)
                    {
                        NodeId     = new NodeId(addMethod.BrowseName.Name + "InArgs", NamespaceIndex),
                        BrowseName = BrowseNames.InputArguments
                    };
                    addMethod.InputArguments.DisplayName      = addMethod.InputArguments.BrowseName.Name;
                    addMethod.InputArguments.TypeDefinitionId = VariableTypeIds.PropertyType;
                    addMethod.InputArguments.ReferenceTypeId  = ReferenceTypeIds.HasProperty;
                    addMethod.InputArguments.DataType         = DataTypeIds.Argument;
                    addMethod.InputArguments.ValueRank        = ValueRanks.OneDimension;

                    addMethod.InputArguments.Value = new Argument[]
                    {
                        new Argument()
                        {
                            Name = "Int32 value", Description = "Int32 value", DataType = DataTypeIds.Int32, ValueRank = ValueRanks.Scalar
                        },
                        new Argument()
                        {
                            Name = "Int32 value", Description = "Int32 value", DataType = DataTypeIds.Int32, ValueRank = ValueRanks.Scalar
                        }
                    };

                    // set output arguments
                    addMethod.OutputArguments                  = new PropertyState <Argument[]>(addMethod);
                    addMethod.OutputArguments.NodeId           = new NodeId(addMethod.BrowseName.Name + "OutArgs", NamespaceIndex);
                    addMethod.OutputArguments.BrowseName       = BrowseNames.OutputArguments;
                    addMethod.OutputArguments.DisplayName      = addMethod.OutputArguments.BrowseName.Name;
                    addMethod.OutputArguments.TypeDefinitionId = VariableTypeIds.PropertyType;
                    addMethod.OutputArguments.ReferenceTypeId  = ReferenceTypeIds.HasProperty;
                    addMethod.OutputArguments.DataType         = DataTypeIds.Argument;
                    addMethod.OutputArguments.ValueRank        = ValueRanks.OneDimension;

                    addMethod.OutputArguments.Value = new Argument[]
                    {
                        new Argument()
                        {
                            Name = "Operater Result", Description = "Operater Result", DataType = DataTypeIds.String, ValueRank = ValueRanks.Scalar
                        }
                    };
                    addMethod.OnCallMethod = new GenericMethodCalledEventHandler(OnAddCall);

                    #endregion
                }

                SystemState = CreateVariable(rootMy, "Enable", DataTypeIds.Boolean, ValueRanks.Scalar, false);

                CreateVariable(rootMy, "Mat", DataTypeIds.Double, ValueRanks.TwoDimensions, new double[4, 4]);


                AddPredefinedNode(SystemContext, rootMy);



                FolderState robots = CreateFolder(null, "Robots");
                robots.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
                references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, robots.NodeId));
                robots.EventNotifier = EventNotifiers.SubscribeToEvents;
                AddRootNotifier(robots);


                RobotA = new HuiBoRobot(robots, "RobotA", NamespaceIndex, SystemContext);
                RobotB = new HuiBoRobot(robots, "RobotB", NamespaceIndex, SystemContext);
                RobotC = new HuiBoRobot(robots, "RobotC", NamespaceIndex, SystemContext);

                AddPredefinedNode(SystemContext, robots);
            }
        }
Beispiel #31
0
        public override void CopyFolderProperties(FolderRecWrapper sourceFolderRecWrapper, ISourceFolder sourceFolder, IDestinationFolder destFolder, FolderRecDataFlags dataToCopy, out bool wasPropertyCopyingSkipped)
        {
            Guid empty  = Guid.Empty;
            bool isRoot = base.IsRoot;
            bool flag   = false;

            wasPropertyCopyingSkipped = false;
            FolderMapping folderMapping = sourceFolderRecWrapper as FolderMapping;

            while (folderMapping.WKFType != WellKnownFolderType.Root)
            {
                if (folderMapping.IsLegacyPublicFolder)
                {
                    return;
                }
                folderMapping = (folderMapping.Parent as FolderMapping);
            }
            if (destFolder == null)
            {
                if (!isRoot || ((FolderMapping)sourceFolderRecWrapper).IsSystemPublicFolder)
                {
                    MrsTracer.Service.Debug("Skipping final property copying for \"{0}\" folder since it's contents don't reside in this mailbox", new object[]
                    {
                        sourceFolderRecWrapper.FullFolderName
                    });
                    return;
                }
                throw new FolderCopyFailedPermanentException(sourceFolderRecWrapper.FullFolderName);
            }
            else
            {
                PropValueData[] props = destFolder.GetProps(new PropTag[]
                {
                    PropTag.ReplicaList,
                    PropTag.IpmWasteBasketEntryId
                });
                IDataConverter <PropValue, PropValueData> dataConverter = new PropValueConverter();
                PropValue nativeRepresentation = dataConverter.GetNativeRepresentation(props[0]);
                byte[]    array = nativeRepresentation.Value as byte[];
                if (!nativeRepresentation.IsNull() && !nativeRepresentation.IsError() && array != null)
                {
                    StorePropertyDefinition replicaList = CoreFolderSchema.ReplicaList;
                    string[] stringArrayFromBytes       = ReplicaListProperty.GetStringArrayFromBytes(array);
                    if (stringArrayFromBytes.Length > 0 && GuidHelper.TryParseGuid(stringArrayFromBytes[0], out empty))
                    {
                        flag = (empty == base.TargetMailboxGuid);
                    }
                }
                FolderStateSnapshot folderStateSnapshot = base.ICSSyncState[sourceFolderRecWrapper.EntryId];
                FolderState         state = folderStateSnapshot.State;
                if (sourceFolder.GetFolderRec(this.GetAdditionalFolderPtags(), GetFolderRecFlags.None).IsGhosted)
                {
                    folderStateSnapshot.State |= FolderState.IsGhosted;
                }
                else
                {
                    folderStateSnapshot.State &= ~FolderState.IsGhosted;
                }
                if (state != folderStateSnapshot.State)
                {
                    base.SaveICSSyncState(false);
                }
                if (!isRoot && !flag)
                {
                    return;
                }
                List <PropValueData> list = new List <PropValueData>(2);
                bool flag2 = false;
                if (flag)
                {
                    PropValue nativeRepresentation2 = dataConverter.GetNativeRepresentation(sourceFolder.GetProps(new PropTag[]
                    {
                        PropTag.PfProxy
                    })[0]);
                    if (!nativeRepresentation2.IsNull() && !nativeRepresentation2.IsError())
                    {
                        byte[] array2 = nativeRepresentation2.Value as byte[];
                        if (array2 != null && array2.Length == 16 && new Guid(array2) != Guid.Empty)
                        {
                            Guid a     = Guid.Empty;
                            bool flag3 = base.Flags.HasFlag(MailboxCopierFlags.CrossOrg);
                            if (flag3)
                            {
                                a = destFolder.LinkMailPublicFolder(LinkMailPublicFolderFlags.EntryId, sourceFolderRecWrapper.EntryId);
                            }
                            else
                            {
                                a = destFolder.LinkMailPublicFolder(LinkMailPublicFolderFlags.ObjectGuid, array2);
                            }
                            if (a != Guid.Empty)
                            {
                                list.Add(new PropValueData(PropTag.PfProxy, a.ToByteArray()));
                                list.Add(new PropValueData(PropTag.PfProxyRequired, true));
                                flag2 = true;
                            }
                            else
                            {
                                base.Report.Append(new ReportEntry(MrsStrings.ReportFailedToLinkADPublicFolder(sourceFolderRecWrapper.FullFolderName, BitConverter.ToString(array2), BitConverter.ToString(sourceFolderRecWrapper.EntryId)), ReportEntryType.Warning));
                            }
                        }
                    }
                }
                if (!flag2)
                {
                    list.Add(new PropValueData(PropTag.PfProxy, Guid.Empty.ToByteArray()));
                    list.Add(new PropValueData(PropTag.PfProxyRequired, false));
                }
                List <PropValueData> list2 = new List <PropValueData>(9);
                if (isRoot)
                {
                    if (!flag)
                    {
                        dataToCopy &= (FolderRecDataFlags.SecurityDescriptors | FolderRecDataFlags.FolderAcls | FolderRecDataFlags.ExtendedAclInformation);
                    }
                    list2.AddRange(list);
                }
                else
                {
                    byte[] sessionSpecificEntryId = this.hierarchyMailbox.GetSessionSpecificEntryId(sourceFolderRecWrapper.EntryId);
                    using (IDestinationFolder folder = this.hierarchyMailbox.GetFolder(sessionSpecificEntryId))
                    {
                        if (folder == null)
                        {
                            MrsTracer.Service.Error("Something deleted destination hierarchy folder from under us", new object[0]);
                            throw new UnexpectedErrorPermanentException(-2147221238);
                        }
                        if (list.Count > 0)
                        {
                            folder.SetProps(list.ToArray());
                        }
                    }
                }
                base.CopyFolderProperties(sourceFolderRecWrapper, sourceFolder, destFolder, dataToCopy, out wasPropertyCopyingSkipped);
                PropTag[] pta = new PropTag[]
                {
                    PropTag.DisablePeruserRead,
                    PropTag.OverallAgeLimit,
                    PropTag.RetentionAgeLimit,
                    PropTag.PfQuotaStyle,
                    PropTag.PfOverHardQuotaLimit,
                    PropTag.PfStorageQuota,
                    PropTag.PfMsgSizeLimit
                };
                foreach (PropValueData propValueData in sourceFolder.GetProps(pta))
                {
                    PropValue nativeRepresentation3 = dataConverter.GetNativeRepresentation(propValueData);
                    if (!nativeRepresentation3.IsNull() && !nativeRepresentation3.IsError())
                    {
                        if (propValueData.PropTag == 1721303043 && (int)propValueData.Value > 0)
                        {
                            propValueData.Value = (int)EnhancedTimeSpan.FromDays((double)((int)propValueData.Value)).TotalSeconds;
                        }
                        list2.Add(propValueData);
                    }
                }
                if (list2.Count > 0)
                {
                    destFolder.SetProps(list2.ToArray());
                }
                return;
            }
        }