/// <summary> /// 命令分发上下文。单条命令 /// </summary> /// <param name="command"></param> /// <param name = "responder"></param> public DistributeContext(MessageBase command, NodeDescriptor responder) { if (command == null) { throw new ArgumentNullException("command"); } if (responder == null) { throw new ArgumentNullException("responder"); } this._acDomain = responder.AcDomain; this.Command = command; this.Responder = responder; #region 如果是head命令类型去掉信息值以减小体积 DataItem[] infoId = command.DataTuple.IdItems.Items; DataItem[] infoValue; // 使用ID映射字典转化ID,同时如果是head命令类型去掉信息值以减小体积 if (Verb.Get.Equals(command.Verb) || Verb.Head.Equals(command.Verb)) { infoValue = null; } else { infoValue = command.DataTuple.ValueItems.Items; } #endregion this.Result = new QueryResult(command); }
/// <summary> /// /// </summary> /// <param name="tuple"></param> /// <param name="toNode"></param> /// <returns></returns> public IList <MessageEntity> Produce(MessageTuple tuple, NodeDescriptor toNode) { if (tuple == null) { throw new ArgumentNullException("tuple"); } if (toNode == null) { throw new ArgumentNullException("toNode"); } if (!IsProduce(tuple.Context, toNode)) { return(new List <MessageEntity>()); } var list = new List <MessageEntity>(); var builder = new CommandBuilder(toNode); var result = builder.Build(tuple); if (result != null) { list.Add(result); } return(list); }
public void PutNode(NodeDescriptor node) { // Configure a node // enable/disable the node // disabling a node with running instances is allowed // set the port pool // adding or removing ports that are already associated with running or deployed instances is allowed // set the max instances // setting max instances to a value less than the number of currently deployed instances is allowed lock (_syncHandle) { var currentNode = _nodes.Nodes[node.HostName]; if (currentNode == null) { currentNode = node.Copy(); if (currentNode.IsEnabled) { _activeNodes.Add(currentNode); } _nodes.Nodes[node.HostName] = currentNode; } else { if (currentNode.IsEnabled && !node.IsEnabled) { _activeNodes.Remove(currentNode); } currentNode.CopyFrom(node); } _nodes.Save(); } }
public static NodeTr Create(NodeDescriptor node) { return(new NodeTr(node.AcDomain) { AnycmdApiAddress = node.Node.AnycmdApiAddress, AnycmdWsAddress = node.Node.AnycmdWsAddress, BeatPeriod = node.Node.BeatPeriod, Code = node.Node.Code, CreateOn = node.Node.CreateOn, Email = node.Node.Email, Icon = node.Node.Icon, Id = node.Node.Id, IsDistributeEnabled = node.Node.IsDistributeEnabled, IsEnabled = node.Node.IsEnabled, IsExecuteEnabled = node.Node.IsExecuteEnabled, IsProduceEnabled = node.Node.IsProduceEnabled, IsReceiveEnabled = node.Node.IsReceiveEnabled, Mobile = node.Node.Mobile, Name = node.Node.Name, Catalog = node.Node.Catalog, PublicKey = node.Node.PublicKey, QQ = node.Node.Qq, SortCode = node.Node.SortCode, Steward = node.Node.Steward, Telephone = node.Node.Telephone, TransferId = node.Node.TransferId }); }
public override void OnConfigure( IDescriptorContext context, IObjectTypeDescriptor descriptor, Type type) { var nodeDescriptor = new NodeDescriptor(descriptor, type); descriptor.Extend().OnBeforeCreate(definition => { // since we bind the id field late we need to hint to the type discovery // that we will need the ID scalar. definition.Dependencies.Add( TypeDependency.FromSchemaType( context.TypeInspector.GetType(typeof(IdType)))); }); descriptor.Extend().OnBeforeCompletion((descriptorContext, definition) => { // first we try to resolve the id field. if (IdField is not null) { MemberInfo?idField = type.GetMember(IdField).FirstOrDefault(); if (idField is null) { throw NodeAttribute_IdFieldNotFound(type, IdField); } nodeDescriptor.IdField(idField); } else if (context.TypeInspector.GetNodeIdMember(type) is { } id) { nodeDescriptor.IdField(id); }
private void CreateArrayInstanceTypes(NodeDescriptor descriptor) { if (descriptor.Instance != null) { IEnumerable collection = (IEnumerable)descriptor.Instance; foreach (object obj in collection) { NodeDescriptor child = Types.GetOrCreate(descriptor.Info, obj, descriptor); if (Types.Add(child, descriptor)) { FindTypes(child); } } } Type itemType = GetArrayItemType(descriptor); if (itemType != null) { NodeDescriptor child = Types.GetOrCreate(itemType); descriptor.CollectionItem = child; if (Types.Add(child, descriptor)) { FindTypes(child); } } }
/// <summary> /// /// </summary> /// <param name="cmdDto"></param> /// <param name="responseNode"></param> /// <returns></returns> public static AnyMessage ToAnyCommand(this IMessageDto cmdDto, NodeDescriptor responseNode) { if (cmdDto == null) { throw new ArgumentNullException("cmdDto"); } if (responseNode == null) { throw new ArgumentNullException("responseNode"); } return AnyMessage.Create(HecpRequest.Create(responseNode.AcDomain, cmdDto), responseNode); }
/// <summary> /// /// </summary> /// <param name = "actionType"></param> /// <param name="ontology"></param> /// <param name="isDumb"></param> /// <param name="client"></param> /// <param name="commandId"></param> /// <param name="localEntityId"></param> /// <param name="infoValue"></param> internal DbCmd(DbActionType actionType, OntologyDescriptor ontology, bool isDumb, NodeDescriptor client, string commandId, string localEntityId, InfoItem[] infoValue) { this.ActionType = actionType; this.Ontology = ontology; this.IsDumb = isDumb; this.Client = client; this.CommandId = commandId; this.LocalEntityId = localEntityId; this.InfoValue = infoValue; }
internal override void Deserialize(ZclFieldDeserializer deserializer) { base.Deserialize(deserializer); Status = deserializer.Deserialize <ZdoStatus>(ZclDataType.Get(DataType.ZDO_STATUS)); if (Status != ZdoStatus.SUCCESS) { // Don't read the full response if we have an error return; } NwkAddrOfInterest = deserializer.Deserialize <ushort>(ZclDataType.Get(DataType.NWK_ADDRESS)); NodeDescriptor = deserializer.Deserialize <NodeDescriptor>(ZclDataType.Get(DataType.NODE_DESCRIPTOR)); }
public LocalNodeDescriptor(NodeDescriptor endpoint, int ringLength) { Rnd = new Random(); Endpoint = endpoint; RingLength = ringLength; SuccessorCacheSize = 2; // dummy init for fingers table InitFingerTable(); // dummy init for successor cache InitSuccessorCache(); }
internal virtual PropertyDescriptorCollection GetPropertyDescriptors() { if (this.m_cache == null) { PropertyDescriptor[] properties = new PropertyDescriptor[this.m_names.Length]; for (int i = 0; i < this.m_names.Length; i++) { properties[i] = new NodeDescriptor(this.m_names[i]); } this.m_cache = new PropertyDescriptorCollection(properties); } return(this.m_cache); }
public void CreatorTest() { NodeDescriptor _newDescriptor = new NodeDescriptor() { BindingDescription = "BindingDescription", DataType = new System.Xml.XmlQualifiedName("DataType", m_Namespace), InstanceDeclaration = false, NodeClass = InstanceNodeClassesEnum.Object, NodeIdentifier = new System.Xml.XmlQualifiedName("Name1", m_Namespace) }; IComparable _comparer = _newDescriptor.CreateWrapper(); Assert.AreEqual <int>(0, _comparer.CompareTo(_comparer)); }
private static void Compare(NodeDescriptor item1, NodeDescriptor item2) { if (item1 == null && item2 == null) { return; } Assert.IsNotNull(item1); Assert.IsNotNull(item2); Assert.AreEqual <string>(item1.BindingDescription, item2.BindingDescription); Assert.AreEqual <XmlQualifiedName>(item1.DataType, item2.DataType); Assert.AreEqual <bool>(item1.InstanceDeclaration, item2.InstanceDeclaration); Assert.AreEqual <InstanceNodeClassesEnum>(item1.NodeClass, item2.NodeClass); Assert.AreEqual <XmlQualifiedName>(item1.NodeIdentifier, item2.NodeIdentifier); Assert.AreEqual <string>(item1.ToString(), item2.ToString()); }
public void InitNodeFromDescriptor(NodeDescriptor descriptor) { nodeType = descriptor.nodeType; nodeName = descriptor.nodeName; titleBarColor = descriptor.titleBarColor; timePointer = new TimePointer(); timePointer.hasTiming = descriptor.hasTiming; timePointer.InitTimePointer(descriptor.defaultAnimationLength); timePointer.parentNode = this; dragButton = new DragButton(); dragButton.InitDragButton(); parameters = new ParameterDictionary(); foreach (KeyValuePair<string, NodeParameter> pair in descriptor.parameters) { NodeParameter tempParameter = new NodeParameter(); tempParameter.floatParam = pair.Value.floatParam; tempParameter.stringParam = pair.Value.stringParam; tempParameter.vectorParam = new Vector3(pair.Value.vectorParam.x, pair.Value.vectorParam.y, pair.Value.vectorParam.z); tempParameter.type = pair.Value.type; parameters.Add(pair.Key, tempParameter); } for(int i = 0; i < descriptor.numberOfInputs; i++) { nodeInputs.Add(new NodeInput()); } numberOfInputs = descriptor.numberOfInputs; nodeInputsMin = descriptor.minInputs; nodeInputsMax = descriptor.maxInputs; for (int i = 0; i < descriptor.numberOfOutputs; i++) { nodeOutputs.Add(new NodeOutput()); if(nodeType != NodeType.Graph) nodeOutputs[i].outputNode = this; } numberOfOutputs = descriptor.numberOfOutputs; nodeOutputsMin = descriptor.minOutputs; nodeOutputsMax = descriptor.maxOutputs; multiInput = descriptor.isMultiInput; multiOutput = descriptor.isMultiOutput; nodeRect = new Rect(10f, 10f, 150f, 100f); }
private static void FillParents(IList <TreeNode <T> > parents, IReadOnlyList <IRow <T> > rows, int index, int currentLevel) { var result = new List <TreeNode <T> >(); for (int i = index; i < rows.Count; i++) { var descriptor = new NodeDescriptor(rows[i]); if (descriptor.Level != currentLevel) { FillParents(result, rows, i, descriptor.Level); return; } var treeNode = new TreeNode <T>(rows[i].Value); parents[descriptor.ParentIndex].Descendants.Add(treeNode); result.Add(treeNode); } }
public bool IsProduce(MessageContext context, NodeDescriptor toNode) { if (context == null) { throw new ArgumentNullException("context"); } if (toNode == null) { throw new ArgumentNullException("toNode"); } if (toNode.Node.IsEnabled != 1 || toNode.Node.IsProduceEnabled == false || !toNode.IsCareForOntology(context.Ontology) || (context.Command.Verb == Verb.Update && context.InfoTuplePair.ValueTuple.All(a => !toNode.IsCareforElement(a.Element)))) { return false; } return true; }
public bool IsProduce(MessageContext context, NodeDescriptor toNode) { if (context == null) { throw new ArgumentNullException("context"); } if (toNode == null) { throw new ArgumentNullException("toNode"); } if (toNode.Node.IsEnabled != 1 || toNode.Node.IsProduceEnabled == false || !toNode.IsCareForOntology(context.Ontology) || (context.Command.Verb == Verb.Update && context.InfoTuplePair.ValueTuple.All(a => !toNode.IsCareforElement(a.Element)))) { return(false); } return(true); }
public void PrecedenceTestMethod() { NodeDescriptor _FirstNewDescriptor = new NodeDescriptor() { BindingDescription = "BindingDescription", DataType = new System.Xml.XmlQualifiedName("DataType", m_Namespace), InstanceDeclaration = false, NodeClass = InstanceNodeClassesEnum.Object, NodeIdentifier = new System.Xml.XmlQualifiedName("Name1", m_Namespace) }; NodeDescriptor _SecondNewDescriptor = new NodeDescriptor() { BindingDescription = "BindingDescription", DataType = new System.Xml.XmlQualifiedName("DataType", m_Namespace), InstanceDeclaration = false, NodeClass = InstanceNodeClassesEnum.Object, NodeIdentifier = new System.Xml.XmlQualifiedName("Name2", m_Namespace) }; IComparable _FirstComparer = _FirstNewDescriptor.CreateWrapper(); IComparable _SecondComparer = _SecondNewDescriptor.CreateWrapper(); Assert.IsTrue(_FirstComparer.CompareTo(_SecondComparer) < 0); Assert.IsTrue(_SecondComparer.CompareTo(_FirstComparer) > 0); }
private static IEvaluatorDescriptor CreateEvaluatorDescriptor(EvaluatorDescriptorInfo descriptorInfo) { var runtimeName = RuntimeName.Local; if (!string.IsNullOrWhiteSpace(descriptorInfo.RuntimeName) && !Enum.TryParse(descriptorInfo.RuntimeName, true, out runtimeName)) { throw new ArgumentException($"Unknown runtime name received {descriptorInfo.RuntimeName}"); } if (descriptorInfo.NodeDescriptorInfo == null) { Logger.Log(Level.Warning, "Node Descriptor not present in Evalautor Descriptor"); return(null); } var nodeDescriptor = new NodeDescriptor( descriptorInfo.NodeDescriptorInfo.IpAddress, descriptorInfo.NodeDescriptorInfo.Port, descriptorInfo.NodeDescriptorInfo.HostName, new CPU(descriptorInfo.Cores), new RAM(descriptorInfo.Memory)); return(new EvaluatorDescriptor(nodeDescriptor, descriptorInfo.Memory, descriptorInfo.Cores, runtimeName)); }
public void ProcessEvent(Event e, Rect shelfNodeRect, Rect shelfGroupRect, NodeDescriptor d, bool close) { base.ProcessEvents(e); if (viewRect.Contains(e.mousePosition)) { if (e.button == 0) { if (e.type == EventType.MouseDown) { currentNodeGraph.DeselectAllNodes(); if (!shelfNodeRect.Contains(e.mousePosition) && shelfGroupRect.Contains(e.mousePosition)) { drawBasicNodes = close; } if(currentNodeGraph != null) currentNodeGraph.selectionFlag = true; if (shelfNodeRect.Contains(e.mousePosition) && d != null) { currentNodeToInstantiate = d; createANode = true; Debug.Log(d.nodeName + " was clicked at: " + e.mousePosition); } } } if (Event.current.type == EventType.ScrollWheel) { panY -= e.delta.y; } } if (panY > 1000) panY = 1000f; if (panY < 0) panY = 0f; if (e.button == 0) { if (e.type == EventType.MouseUp && createANode) { Debug.Log("creatng Node2"); createANode = false; if (!viewRect.Contains(e.mousePosition)) { if (currentNodeToInstantiate.nodeType != NodeType.Graph) NodeUtilities.CreateNode(currentNodeGraph, currentNodeToInstantiate, currentNodeGraph.mousePos); if(currentNodeToInstantiate.nodeType == NodeType.Graph) { if (currentNodeGraph != null) { NodeBase currentNode = NodeUtilities.CreateNode(getGroupNodeDescriptor()); NodeGraphPopupWindow.InitNodePopup(currentNode, currentNodeGraph); currentNode.InitNodeFromDescriptor(getGroupNodeDescriptor()); NodeUtilities.positionNode(currentNode, currentNodeGraph, currentNodeGraph.mousePos); NodeUtilities.saveNode(currentNode, currentNodeGraph); } } } } } }
public static NodeTr Create(NodeDescriptor node) { return new NodeTr(node.AcDomain) { AnycmdApiAddress = node.Node.AnycmdApiAddress, AnycmdWsAddress = node.Node.AnycmdWsAddress, BeatPeriod = node.Node.BeatPeriod, Code = node.Node.Code, CreateOn = node.Node.CreateOn, Email = node.Node.Email, Icon = node.Node.Icon, Id = node.Node.Id, IsDistributeEnabled = node.Node.IsDistributeEnabled, IsEnabled = node.Node.IsEnabled, IsExecuteEnabled = node.Node.IsExecuteEnabled, IsProduceEnabled = node.Node.IsProduceEnabled, IsReceiveEnabled = node.Node.IsReceiveEnabled, Mobile = node.Node.Mobile, Name = node.Node.Name, Catalog = node.Node.Catalog, PublicKey = node.Node.PublicKey, QQ = node.Node.Qq, SortCode = node.Node.SortCode, Steward = node.Node.Steward, Telephone = node.Node.Telephone, TransferId = node.Node.TransferId }; }
/// <summary> /// {@inheritDoc} /// </summary> public T ReadZigBeeType <T>(DataType type) { if (index == payload.Length) { return(default(T)); } object[] value = new object[1]; switch (type) { case DataType.BOOLEAN: value[0] = payload[index++] == 0 ? false : true; break; case DataType.OCTET_STRING: int octetSize = payload[index++]; value[0] = new ByteArray(payload, index, index + octetSize); index += octetSize; break; case DataType.CHARACTER_STRING: int stringSize = payload[index++]; if (stringSize == 255) { value[0] = null; break; } byte[] bytes = new byte[stringSize]; int length = stringSize; for (int cnt = 0; cnt < stringSize; cnt++) { bytes[cnt] = (byte)payload[index + cnt]; if (payload[index + cnt] == 0) { length = cnt; break; } } try { int len = length - 0; byte[] dest = new byte[len]; // note i is always from 0 for (int i = 0; i < len; i++) { dest[i] = bytes[0 + i]; // so 0..n = 0+x..n+x } value[0] = Encoding.Default.GetString(dest); } catch (Exception e) { value[0] = null; break; } index += stringSize; break; case DataType.ENDPOINT: case DataType.BITMAP_8_BIT: case DataType.DATA_8_BIT: case DataType.ENUMERATION_8_BIT: value[0] = (byte)((byte)payload[index++] & 0xFF); break; case DataType.EXTENDED_PANID: byte[] panId = new byte[8]; for (int iCnt = 7; iCnt >= 0; iCnt--) { panId[iCnt] = payload[index + iCnt]; } index += 8; value[0] = new ExtendedPanId(panId); break; case DataType.IEEE_ADDRESS: byte[] address = new byte[8]; for (int iCnt = 7; iCnt >= 0; iCnt--) { address[iCnt] = payload[index + iCnt]; } index += 8; value[0] = new IeeeAddress(address); break; case DataType.N_X_ATTRIBUTE_INFORMATION: break; case DataType.N_X_ATTRIBUTE_RECORD: break; case DataType.N_X_ATTRIBUTE_REPORT: break; case DataType.N_X_ATTRIBUTE_REPORTING_CONFIGURATION_RECORD: break; case DataType.N_X_ATTRIBUTE_SELECTOR: break; case DataType.N_X_ATTRIBUTE_STATUS_RECORD: break; case DataType.N_X_EXTENSION_FIELD_SET: break; case DataType.N_X_NEIGHBORS_INFORMATION: break; case DataType.N_X_READ_ATTRIBUTE_STATUS_RECORD: List <ReadAttributeStatusRecord> records = new List <ReadAttributeStatusRecord>(); while (IsEndOfStream() == false) { ReadAttributeStatusRecord statusRecord = new ReadAttributeStatusRecord(); statusRecord.Deserialize(this); records.Add(statusRecord); } value[0] = records; break; case DataType.N_X_UNSIGNED_16_BIT_INTEGER: int cntN16 = (byte)(payload[index++] & 0xFF); List <ushort> arrayN16 = new List <ushort>(cntN16); for (int arrayIndex = 0; arrayIndex < cntN16; arrayIndex++) { arrayN16.Add(BitConverter.ToUInt16(payload, index)); index += 2; } value[0] = arrayN16; break; case DataType.N_X_UNSIGNED_8_BIT_INTEGER: int cntN8 = (byte)(payload[index++] & 0xFF); List <byte> arrayN8 = new List <byte>(cntN8); for (int arrayIndex = 0; arrayIndex < cntN8; arrayIndex++) { arrayN8.Add(payload[index++]); } value[0] = arrayN8; break; case DataType.X_UNSIGNED_8_BIT_INTEGER: int cntX8 = payload.Length - index; List <byte> arrayX8 = new List <byte>(cntX8); for (int arrayIndex = 0; arrayIndex < cntX8; arrayIndex++) { arrayX8.Add((byte)(payload[index++])); } value[0] = arrayX8; break; case DataType.N_X_ATTRIBUTE_IDENTIFIER: int cntX16 = (payload.Length - index) / 2; List <ushort> arrayX16 = new List <ushort>(cntX16); for (int arrayIndex = 0; arrayIndex < cntX16; arrayIndex++) { arrayX16.Add(BitConverter.ToUInt16(payload, index)); index += 2; } value[0] = arrayX16; break; case DataType.UNSIGNED_8_BIT_INTEGER_ARRAY: int cnt8Array = payload.Length - index; byte[] intarray8 = new byte[cnt8Array]; for (int arrayIndex = 0; arrayIndex < cnt8Array; arrayIndex++) { intarray8[arrayIndex] = payload[index++]; } value[0] = intarray8; break; case DataType.N_X_WRITE_ATTRIBUTE_RECORD: break; case DataType.N_X_WRITE_ATTRIBUTE_STATUS_RECORD: break; case DataType.SIGNED_16_BIT_INTEGER: short s = (short)(payload[index++] | (payload[index++] << 8)); value[0] = s; break; case DataType.CLUSTERID: case DataType.NWK_ADDRESS: case DataType.BITMAP_16_BIT: case DataType.ENUMERATION_16_BIT: case DataType.UNSIGNED_16_BIT_INTEGER: ushort us = (ushort)(payload[index++] | (payload[index++] << 8)); value[0] = us; break; case DataType.UNSIGNED_24_BIT_INTEGER: value[0] = payload[index++] + (payload[index++] << 8) | (payload[index++] << 16); break; case DataType.BITMAP_32_BIT: case DataType.SIGNED_32_BIT_INTEGER: case DataType.UNSIGNED_32_BIT_INTEGER: value[0] = payload[index++] + (payload[index++] << 8) | (payload[index++] << 16) + (payload[index++] << 24); break; case DataType.UNSIGNED_48_BIT_INTEGER: value[0] = (payload[index++]) + ((long)(payload[index++]) << 8) | ((long)(payload[index++]) << 16) + ((long)(payload[index++]) << 24) | ((long)(payload[index++]) << 32) + ((long)(payload[index++]) << 40); break; case DataType.SIGNED_8_BIT_INTEGER: value[0] = (sbyte)(payload[index++]); break; case DataType.UNSIGNED_8_BIT_INTEGER: value[0] = (byte)(payload[index++] & 0xFF); break; case DataType.UTCTIME: //TODO: Implement date deserialization break; case DataType.ROUTING_TABLE: RoutingTable routingTable = new RoutingTable(); routingTable.Deserialize(this); value[0] = routingTable; break; case DataType.NEIGHBOR_TABLE: NeighborTable neighborTable = new NeighborTable(); neighborTable.Deserialize(this); value[0] = neighborTable; break; case DataType.NODE_DESCRIPTOR: NodeDescriptor nodeDescriptor = new NodeDescriptor(); nodeDescriptor.Deserialize(this); value[0] = nodeDescriptor; break; case DataType.POWER_DESCRIPTOR: PowerDescriptor powerDescriptor = new PowerDescriptor(); powerDescriptor.Deserialize(this); value[0] = powerDescriptor; break; case DataType.BINDING_TABLE: BindingTable bindingTable = new BindingTable(); bindingTable.Deserialize(this); value[0] = bindingTable; break; case DataType.SIMPLE_DESCRIPTOR: SimpleDescriptor simpleDescriptor = new SimpleDescriptor(); simpleDescriptor.Deserialize(this); value[0] = simpleDescriptor; break; case DataType.ZCL_STATUS: value[0] = (ZclStatus)(payload[index++]); break; case DataType.ZDO_STATUS: value[0] = (ZdoStatus)(payload[index++]); break; case DataType.ZIGBEE_DATA_TYPE: value[0] = ZclDataType.Get(payload[index++]); break; case DataType.BYTE_ARRAY: int cntB8 = (byte)(payload[index++] & 0xFF); byte[] arrayB8 = new byte[cntB8]; for (int arrayIndex = 0; arrayIndex < cntB8; arrayIndex++) { arrayB8[arrayIndex] = (byte)(payload[index++] & 0xff); } value[0] = new ByteArray(arrayB8); break; default: throw new ArgumentException("No reader defined in " + this.GetType().Name + " for " + type.ToString() + " (" + (byte)type + ")"); } return((T)value[0]); }
/// <summary> /// /// </summary> /// <param name="actor"></param> /// <returns></returns> public abstract string GetAddress(NodeDescriptor actor);
/// <summary> /// 构造 /// </summary> /// <param name="toNode">向该节点建造待分发命令</param> public CommandBuilder(NodeDescriptor toNode) { this.ToNode = toNode; }
private static void ProcessCommands(IList<Tuple<IOverlayNodeService, IOverlayStorageService>> services) { Func<string, IOverlayNodeService, OverlayData[]> getStoragePutKeyValuesFromCmd = (string arg, IOverlayNodeService srv) => { var res = new List<OverlayData>(); foreach (var pair in arg.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)) { var pairAttrVal = pair.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); // assume we have only one overlay level as for now res.Add(new OverlayData { AttrValue = new KeyValuePair<string,object>(pairAttrVal[0].Trim(), pairAttrVal[1].Trim()), OwnerNode = new NodeDescriptor(srv.Node) }); } return res.ToArray(); }; Func<string, string[]> getStorageRemoveKeysFromCmd = (string arg) => { return arg .Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()) .ToArray(); }; while (true) { var cmd = System.Console.ReadLine(); var operatingSrv = services[Rnd.Next(0, services.Count)]; if (cmd.StartsWith("join")) { var existingNodesInOverlay = services.Select(s => s.Item1.Node).ToArray(); // chord service var nodeWhoJoinsInitInfo = new NodeDescriptor.NodeInitInfo( NetworkHelper.GetLocalIpAddress(), OverlayHelper.GetRandomPortNumber(existingNodesInOverlay.Select(n => n.Port).ToArray()), 1 ); var hashPrv = (IProvider<byte[], long>)SrvPrv.GetService("sha1KeyPrv"); var nodeWhoJoins = new NodeDescriptor( nodeWhoJoinsInitInfo, hashPrv.Provide(OverlayHelper.GetNodeHashArgument(nodeWhoJoinsInitInfo)) ); var nodeWhoJoinsChordService = (IOverlayNodeService)SrvPrv.GetService("chordOverlayNodeService"); nodeWhoJoinsChordService.Bind(new LocalNode(nodeWhoJoins)); nodeWhoJoinsChordService.Join( existingNodesInOverlay[Rnd.Next(0, existingNodesInOverlay.Length)] ); // respective storage service var nodeWhoJoinsStorageService = (IOverlayStorageService)SrvPrv.GetService("mongoDbOverlayStorageService"); nodeWhoJoinsStorageService.Bind(new[] { nodeWhoJoinsChordService }.ToList()); nodeWhoJoinsStorageService.Start(); } else if (cmd == "leave") { var cmdParts = cmd.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); var srvToLeave = services.FirstOrDefault(s => s.Item1.Node.Id == Convert.ToInt64(cmdParts[1])); if (srvToLeave != null) { srvToLeave.Item2.Stop(); srvToLeave.Item1.SendMessage(new OverlayNodeServiceMessage { MsgType = OverlayNodeServiceMessage.MessageType.ExitRequested, WaitForProcessing = true }); } else { System.Console.WriteLine("No such node"); } } else if (cmd == "stop") { break; } else if (cmd.StartsWith("stats")) { var cmdParts = cmd.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); using (var fs = File.Create("generated_stats_" + DateTime.Now.Ticks + ".xml")) { using (var writer = new StreamWriter(fs)) { foreach (var stats in Stats) { writer.WriteLine(String.Join( ";", stats.NodesCount, stats.AVPairsCount, stats.ServiceRegistrationFailsCount, stats.NodesOverAVThresholdCount, stats.AvgRegistrationsPerSecond )); } } } } else if (cmd.StartsWith("populate")) { var cmdParts = cmd.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); PopulateStorage( services, GetServiceDescriptions(cmdParts[1]), cmdParts.Length > 2 ? (int?)Convert.ToInt32(cmdParts[2]) : null ); } else if (cmd.StartsWith("put")) { Func<string, IOverlayNodeService, ServiceDescription> f = (string srvDescr, IOverlayNodeService overlaySrv) => { var res = new ServiceDescription { Name = srvDescr.Substring(0, srvDescr.IndexOf(":")), OwnerNode = overlaySrv.Node, Data = new List<OverlayData>() }; foreach (var pair in srvDescr.Substring(srvDescr.IndexOf(":") + 1).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)) { var pairAttrVal = pair.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); // assume we have only one overlay level as for now res.Data.Add( new OverlayData { AttrValue = new KeyValuePair<string,object>(pairAttrVal[0].Trim(), pairAttrVal[1].Trim()), ServiceName = res.Name, OwnerNode = res.OwnerNode } ); } return res; }; var cmdParts = cmd.Substring("put".Length).Trim().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); var ownerSrv = services.FirstOrDefault(s => s.Item1.Node.Id == Convert.ToInt64(cmdParts[1])); if (ownerSrv != null) { ownerSrv.Item2.PutService(f( cmdParts[1], ownerSrv.Item1 )); } else { System.Console.WriteLine("No such node"); } } else if (cmd.StartsWith("remove")) { operatingSrv.Item2.RemoveService(cmd.Substring("remove".Length).Trim()); } else if (cmd.StartsWith("update")) { var cmdParts = cmd.Substring("update".Length).Split(':', ';'); var addCmdPart = cmdParts[1]; var removeCmdPart = cmd.IndexOf(";") > 0 ? cmdParts[2] : null; operatingSrv.Item2.UpdateService( cmdParts[0].Trim(), String.IsNullOrWhiteSpace(addCmdPart) ? null : getStoragePutKeyValuesFromCmd(addCmdPart, operatingSrv.Item1), String.IsNullOrWhiteSpace(removeCmdPart) ? null : getStorageRemoveKeysFromCmd(removeCmdPart) ); } else if (cmd.StartsWith("get")) { var res = operatingSrv.Item2.GetServices(Query.FromRelex(cmd.Substring("get".Length).Trim()), true); if (res != null && res.IsSuccessful && res.ServicesData.Any()) { System.Console.WriteLine("**************************************************"); System.Console.WriteLine("RESULTS:"); foreach (var r in res.ServicesData) { System.Console.WriteLine("\r\n=============================================================="); System.Console.WriteLine(String.Format("Service name: {0}", r.Name)); foreach (var d in r.Data) { System.Console.WriteLine(String.Format("{0} = {1} (Responsible node: {2})", d.AttrValue.Key, d.GetFormattedValue(), d.ResponsibleNode.ToString())); } System.Console.WriteLine(String.Format("Service owner: {0}", r.OwnerNode.ToString())); System.Console.WriteLine("==============================================================\r\n"); } } else { System.Console.WriteLine(res != null && !res.IsSuccessful ? "Failed" : "No data"); } } } }
private void RunMessageProcessor() { var tFactory = new TaskFactory(TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent, TaskContinuationOptions.None); MsgProcessor.InnerTask = tFactory.StartNew( () => { var taskFinished = false; while (!taskFinished) { // run background threads if (MaintenanceSrv.Status == MaintenanceStatus.WaitingForStart) { MaintenanceSrv.Start(); } // wait until event is received MsgProcessor.WaitingForMsgHandle.Wait(); Log.Write(LogEvent.Debug, "Processing message {0} at node {1}", MsgProcessor.CurrentMsg, LocalNode); if (MsgProcessor.CurrentMsg.MsgType == OverlayNodeServiceMessage.MessageType.JoinedSuccessfully) { // allow to resume maintenance MaintenanceSrv.Status = MaintenanceStatus.WaitingForStart; // and simply proceed MsgProcessor.MarkCurrentMsgAsProcessed(); } else if (MsgProcessor.CurrentMsg.MsgType == OverlayNodeServiceMessage.MessageType.RejoinRequested && !Params.TreatRejoinRequestedAsExit) { if (LocalNode.InitNode == null) { Log.Write(LogEvent.Warn, "Not possible to rejoin for node {0} because the bootstrapper node is empty or not accessible, leaving the network", LocalNode); // cannot rejoin - simply request leaving MsgProcessor.SetCurrentMsg(new OverlayNodeServiceMessage { MsgType = OverlayNodeServiceMessage.MessageType.LeaveRequested }); } else { // try to rejoin using cached bootstraper node var localInitEndpoint = new NodeDescriptor(LocalNode); Log.Write(LogEvent.Info, "Trying to rejoin for node {0}"); Leave(); Rejoin(localInitEndpoint); if (LocalNode.State != NodeState.Connected) { // still couldn't join the network for some reason - request leaving MsgProcessor.SetCurrentMsg(new OverlayNodeServiceMessage { MsgType = OverlayNodeServiceMessage.MessageType.LeaveRequested }); } else { MsgProcessor.MarkCurrentMsgAsProcessed(); } } } else if (MsgProcessor.CurrentMsg.MsgType == OverlayNodeServiceMessage.MessageType.LeaveRequested || MsgProcessor.CurrentMsg.MsgType == OverlayNodeServiceMessage.MessageType.ExitRequested || (Params.TreatRejoinRequestedAsExit && MsgProcessor.CurrentMsg.MsgType == OverlayNodeServiceMessage.MessageType.RejoinRequested)) { Leave(); // there may be some events pending -> discard them MsgProcessor.MarkCurrentMsgAsProcessed(); // if it was exit -> finish this thread if (MsgProcessor.CurrentMsg.MsgType == OverlayNodeServiceMessage.MessageType.ExitRequested) { taskFinished = true; } } } } ); Log.Write(LogEvent.Debug, "Started listening for messages at node {0}", LocalNode); }
public LocalNode(NodeDescriptor node) : base(node.IpAddress, node.Port, node.OverlayLevel, node.Id) { }
private void handleDeviceMessage(Telegram telegram) { int num = telegram.data[0]; int nodeIndex = telegram.data[1] & 7; viewEZMacNetwork1.blinkNodeCommunication(nodeIndex); viewEZMacNetwork1.setNodeConnectionUpdate(nodeIndex); switch (num) { case 0x80: _log.Debug("RF_To_USB_Network_Demo: handleDeviceMessage: NwD_iSlaveAssoc"); viewEZMacNetwork1.nodeConnected(nodeIndex, ViewEZMacNetwork.NodeLook.Henrietta); send_Ack(); return; case 0x81: _log.Debug("RF_To_USB_Network_Demo: handleDeviceMessage: NwD_iSlaveDisAc"); viewEZMacNetwork1.nodeDisconnected(nodeIndex); viewRssi1.setData(nodeIndex, 0.0); if ((nodeIndex >= 1) && (nodeIndex <= 4)) { NodeControls[nodeIndex - 1].groupBox.Enabled = false; } send_Ack(); return; case 130: { _log.Debug("RF_To_USB_Network_Demo: handleDeviceMessage: NwD_iPacRec"); NodeDescriptor descriptor = new NodeDescriptor(0, telegram.data); if ((descriptor.Address >= 1) && (descriptor.Address <= 4)) { if (!viewEZMacNetwork1.isNodeConnected(nodeIndex)) { viewEZMacNetwork1.nodeConnected(nodeIndex, ViewEZMacNetwork.NodeLook.Henrietta); } viewEZMacNetwork1.setNodeBatteryStatus(nodeIndex, descriptor.Battery); viewEZMacNetwork1.setNodeTemperature(nodeIndex, (float) descriptor.Temperature); if ((nodeIndex >= 1) && (nodeIndex <= 4)) { NodeControls[nodeIndex - 1].groupBox.Enabled = true; NodeControls[nodeIndex - 1].temperature.Value = descriptor.Temperature; NodeControls[nodeIndex - 1].potentiometer.Value = descriptor.Potentiometer; } viewDataReceiver1.messageReceived(telegram.data.Buf, telegram.data.NumItems); double data = telegram.data[2]; data = (data - 230.0) / 2.0; viewRssi1.setData(nodeIndex, data); send_Ack(); return; } send_Nack(); return; } case 0x83: _log.Debug("RF_To_USB_Network_Demo: handleDeviceMessage: NwD_iADC"); send_Ack(); return; case 0x85: { _log.Debug("RF_To_USB_Network_Demo: handleDeviceMessage: NwD_MStatInd"); MasterStatus status = (MasterStatus) telegram.data[1]; if ((status < MasterStatus.MasterNonArmed) || (status == MasterStatus.Undefined)) { viewEZMacNetwork1.nodeDisconnected(1); viewEZMacNetwork1.nodeDisconnected(2); viewEZMacNetwork1.nodeDisconnected(3); viewEZMacNetwork1.nodeDisconnected(4); } send_Ack(); return; } } _log.Debug("RF_To_USB_Network_Demo: handleDeviceMessage: Unknown ComandID=" + num); send_Nack(); }
/// <summary> /// /// </summary> /// <param name="cmdDto"></param> /// <param name="toNode"></param> /// <returns></returns> public static IMessageDto RequestNode(this IMessageDto cmdDto, NodeDescriptor toNode) { if (cmdDto == null) { throw new ArgumentNullException("cmdDto"); } if (toNode == null) { throw new ArgumentNullException("toNode"); } if (cmdDto.Credential == null) { throw new AnycmdException("非法状态的命令,没有设置证书"); } if (string.IsNullOrEmpty(cmdDto.Credential.Password)) { CredentialType credentialType; if (!cmdDto.Credential.CredentialType.TryParse(out credentialType)) { throw new AnycmdException("意外的证书类型" + cmdDto.Credential.CredentialType); } ClientType clientType; if (!cmdDto.Credential.ClientType.TryParse(out clientType)) { throw new AnycmdException("意外的客户端类型" + cmdDto.Credential.ClientType); } switch (clientType) { case ClientType.Undefined: break; case ClientType.Node: NodeDescriptor clientNode; if (!toNode.AcDomain.NodeHost.Nodes.TryGetNodeByPublicKey(cmdDto.Credential.ClientId, out clientNode)) { throw new AnycmdException("意外的客户节点标识" + cmdDto.Credential.ClientId); } switch (credentialType) { case CredentialType.Undefined: break; case CredentialType.Token: cmdDto.Credential.Password = TokenObject.Token(cmdDto.Credential.ClientId, cmdDto.Credential.Ticks, clientNode.Node.SecretKey); break; case CredentialType.Signature: cmdDto.Credential.Password = Signature.Sign(cmdDto.ToOrignalString(cmdDto.Credential), clientNode.Node.SecretKey); break; case CredentialType.OAuth: break; default: break; } break; case ClientType.App: break; case ClientType.Monitor: break; default: break; } } return cmdDto.ToAnyCommand(toNode).Request(); }
private static List<NodeDescriptor> ProcessNodes(XmlNodeList nodes) { List<NodeDescriptor> list = new List<NodeDescriptor>(); NodeDescriptor nodeDescriptor = null; foreach (XmlNode node in nodes) { nodeDescriptor = new NodeDescriptor(); nodeDescriptor.nodeType = (NodeType)Convert.ToInt16(node.Attributes.GetNamedItem("type").Value); nodeDescriptor.nodeName = node.Attributes.GetNamedItem("name").Value; nodeDescriptor.numberOfInputs = Convert.ToInt16(node.SelectSingleNode("numberOfInputs").Attributes.GetNamedItem("default").Value); nodeDescriptor.minInputs = Convert.ToInt16(node.SelectSingleNode("numberOfInputs").Attributes.GetNamedItem("min").Value); nodeDescriptor.maxInputs = Convert.ToInt16(node.SelectSingleNode("numberOfInputs").Attributes.GetNamedItem("max").Value); nodeDescriptor.numberOfOutputs = Convert.ToInt16(node.SelectSingleNode("numberOfOutputs").Attributes.GetNamedItem("default").Value); nodeDescriptor.minOutputs= Convert.ToInt16(node.SelectSingleNode("numberOfOutputs").Attributes.GetNamedItem("min").Value); nodeDescriptor.maxOutputs = Convert.ToInt16(node.SelectSingleNode("numberOfOutputs").Attributes.GetNamedItem("max").Value); nodeDescriptor.titleBarColor = node.SelectSingleNode("color").InnerText; nodeDescriptor.hasTiming = "true" == node.SelectSingleNode("defaultAnimationLength").Attributes.GetNamedItem("hasTiming").Value; nodeDescriptor.isHidden = "true" == node.SelectSingleNode("isHidden").InnerText; if (nodeDescriptor.hasTiming) nodeDescriptor.defaultAnimationLength = Convert.ToSingle(node.SelectSingleNode("defaultAnimationLength").InnerText); nodeDescriptor.isMultiInput = "true" == node.SelectSingleNode("inputType").Attributes.GetNamedItem("multiInput").Value; nodeDescriptor.isMultiOutput = "true" == node.SelectSingleNode("inputType").Attributes.GetNamedItem("multiOutput").Value; nodeDescriptor.parameters = new ParameterDictionary(); //Loop the parameters foreach (XmlNode parameter in node.SelectNodes("parameters/parameter")) { string key = parameter.Attributes.GetNamedItem("key").Value; Type type = Type.GetType(parameter.Attributes.GetNamedItem("type").Value); NodeParameter value = new NodeParameter(); if(type == typeof(float)) { float temp = Convert.ToSingle(parameter.Attributes.GetNamedItem("value").Value); value.floatParam = temp; value.type = parameter.Attributes.GetNamedItem("type").Value; } if(type == typeof(string)) { string temp = parameter.Attributes.GetNamedItem("value").Value; value.stringParam = temp; value.type = parameter.Attributes.GetNamedItem("type").Value; } if (type == typeof(bool)) { value.boolParam = "true" == parameter.Attributes.GetNamedItem("value").Value; value.type = parameter.Attributes.GetNamedItem("type").Value; } if (parameter.Attributes.GetNamedItem("type").Value == "UnityEngine.Vector3") { float x = Convert.ToSingle(parameter.Attributes.GetNamedItem("x").Value); float y = Convert.ToSingle(parameter.Attributes.GetNamedItem("y").Value); float z = Convert.ToSingle(parameter.Attributes.GetNamedItem("z").Value); value.vectorParam = new Vector3(x,y,z); value.type = "UnityEngine.Vector3"; } nodeDescriptor.parameters.Add(key,value); } list.Add(nodeDescriptor); } return list; }
/// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="dataTuple">数据项集合对</param> /// <param name="id">信息标识</param> /// <param name = "responseNode"></param> private AnyMessage(MessageTypeKind type, Guid id, DataItemsTuple dataTuple, NodeDescriptor responseNode) : base(type, id, dataTuple) { this._responseNode = responseNode; }
public void InitSuccessorCache() { SuccessorCache = new NodeDescriptor[Params.SuccessorCacheSize]; for (int i = 0; i < Params.SuccessorCacheSize; ++i) { SuccessorCache[i] = new NodeDescriptor(this); } }
public override void Handle(AddBatchCommand command) { var batchRepository = _acDomain.RetrieveRequiredService<IRepository<Batch>>(); OntologyDescriptor ontology; if (!_acDomain.NodeHost.Ontologies.TryGetOntology(command.Input.OntologyId, out ontology)) { throw new ValidationException("非法的本体标识" + command.Input.OntologyId); } BatchType type; if (!command.Input.Type.TryParse(out type)) { throw new ValidationException("意外的批类型" + command.Input.Type); } var entity = Batch.Create(command.Input); var descriptor = new BatchDescriptor(_acDomain, entity); const int pageSize = 1000; const int pageIndex = 0; bool includeDescendants = entity.IncludeDescendants.HasValue && entity.IncludeDescendants.Value; NodeDescriptor toNode = null; if (!_acDomain.NodeHost.Nodes.TryGetNodeById(entity.NodeId.ToString(), out toNode)) { throw new AnycmdException("意外的节点标识" + entity.NodeId); } string thisNodeId = _acDomain.NodeHost.Nodes.ThisNode.Node.Id.ToString(); Verb actionCode; switch (descriptor.Type) { case BatchType.BuildCreateCommand: actionCode = Verb.Create; break; case BatchType.BuildUpdateCommand: actionCode = Verb.Update; break; case BatchType.BuildDeleteCommand: actionCode = Verb.Delete; break; default: throw new AnycmdException("意外的批类型" + entity.Type); } var commandFactory = _acDomain.NodeHost.MessageProducer; bool goOn = true; int count = 0; var pagingData = new PagingInput(pageIndex, pageSize, ontology.IncrementIdElement.Element.Code, "asc"); var selectElements = new OrderedElementSet {ontology.IdElement}; foreach (var item in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1)) { if (toNode.IsCareforElement(item) || toNode.IsInfoIdElement(item)) { selectElements.Add(item); } } var filters = new List<FilterData>(); if (ontology.Ontology.IsCataloguedEntity && !string.IsNullOrEmpty(entity.CatalogCode)) { filters.Add(includeDescendants ? FilterData.Like("ZZJGM", entity.CatalogCode + "%") : FilterData.EQ("ZZJGM", entity.CatalogCode)); } do { IDataTuples entities = ontology.EntityProvider.GetPlist(ontology, selectElements, filters, pagingData); if (entities != null && entities.Columns != null) { int idIndex = -1; for (int i = 0; i < entities.Columns.Count; i++) { if (entities.Columns[i] == ontology.IdElement) { idIndex = i; break; } } if (entities.Columns.Count == 0) { throw new AnycmdException("意外的查询列数"); } if (idIndex == -1) { throw new AnycmdException("未查询得到实体标识列"); } var products = new List<MessageEntity>(); foreach (var item in entities.Tuples) { var idItems = new InfoItem[] { InfoItem.Create(ontology.IdElement, item[idIndex].ToString()) }; var valueItems = new InfoItem[entities.Columns.Count - 1]; for (int i = 0; i < entities.Columns.Count; i++) { if (i < idIndex) { valueItems[i] = InfoItem.Create(entities.Columns[i], item[i].ToString()); } else if (i > idIndex) { valueItems[i - 1] = InfoItem.Create(entities.Columns[i], item[i].ToString()); } } var commandContext = new MessageContext(_acDomain, new MessageRecord( MessageTypeKind.Received, Guid.NewGuid(), DataItemsTuple.Create(_acDomain, idItems, valueItems, null, "json")) { Verb = actionCode, ClientId = thisNodeId, ClientType = ClientType.Node, TimeStamp = DateTime.Now, CreateOn = DateTime.Now, Description = entity.Type, LocalEntityId = item[idIndex].ToString(), Ontology = ontology.Ontology.Code, CatalogCode = null,// 如果按照目录分片分发命令的话则目录为空的分发命令是由专门的分发器分发的 MessageId = Guid.NewGuid().ToString(), MessageType = MessageType.Action, ReasonPhrase = "Ok", Status = 200, EventSourceType = string.Empty, EventSubjectCode = string.Empty, UserName = command.AcSession.Account.Id.ToString(), IsDumb = false, ReceivedOn = DateTime.Now, Version = ApiVersion.V1.ToName() }); products.AddRange(commandFactory.Produce(new MessageTuple(commandContext, valueItems), toNode)); } ontology.MessageProvider.SaveCommands(ontology, products.ToArray()); count = count + products.Count; pagingData.PageIndex++;// 注意这里不要引入bug。 } if (entities == null || entities.Tuples.Length == 0) { goOn = false; } } while (goOn); entity.Total = count; batchRepository.Add(entity); batchRepository.Context.Commit(); _acDomain.PublishEvent(new BatchAddedEvent(command.AcSession, entity)); _acDomain.CommitEventBus(); }
/// <summary> /// /// </summary> /// <param name="tuple"></param> /// <param name="toNode"></param> /// <returns></returns> public IList<MessageEntity> Produce(MessageTuple tuple, NodeDescriptor toNode) { if (tuple == null) { throw new ArgumentNullException("tuple"); } if (toNode == null) { throw new ArgumentNullException("toNode"); } if (!IsProduce(tuple.Context, toNode)) { return new List<MessageEntity>(); } var list = new List<MessageEntity>(); var builder = new CommandBuilder(toNode); var result = builder.Build(tuple); if (result != null) { list.Add(result); } return list; }
public ProcessResult Validate(MessageContext context) { if (context == null) { return(new ProcessResult(false, Status.NoneCommand, "空命令")); } MessageType type = context.Command.MessageType; #region 非法的表述类型 if (type == MessageType.Undefined || type == default(MessageType)) { return(new ProcessResult(false, Status.InvalidMessageType, "非法的表述类型")); } #endregion #region 验证事件 if (type == MessageType.Event) { #region 非法的事件源类型 EventSourceType eventSourceType; if (!context.Command.EventSourceType.TryParse(out eventSourceType) || eventSourceType == EventSourceType.Invalid || eventSourceType == default(EventSourceType)) { return(new ProcessResult(false, Status.InvalidEventSourceType, "非法的事件源类型")); } #endregion #region 非法的事件主题码 if (!EventSubjectCode.Contains(context.Command.EventSubjectCode)) { return(new ProcessResult(false, Status.InvalidEventSubject, "非法的事件主题码")); } #endregion #region 非法的状态码或原因短语 Status outStateCode; if (!context.Command.Status.TryParse(out outStateCode)) { return(new ProcessResult(false, Status.InvalidStatus, "非法的状态码")); } if (!string.IsNullOrEmpty(context.Command.ReasonPhrase) && context.Command.ReasonPhrase.Length > 50) { return(new ProcessResult(false, Status.OutOfLength, "原因短语超过50个字符长度")); } #endregion #region 本节点分发的命令的请求标识是Guid型的 if (eventSourceType == EventSourceType.Command) { Guid requestId; if (!Guid.TryParse(context.Command.MessageId, out requestId)) { return(new ProcessResult(false, Status.InvalidArgument, @"参数MessageID错误:服务端的请求标识是Guid类型的。当EventSourceType取值Command时该MessageID是服务端分发该条命令时使用的MessageId")); } } #endregion } #endregion #region 发起人验证 if (!string.IsNullOrEmpty(context.Command.UserName) && context.Command.UserName.Length > 50) { return(new ProcessResult(false, Status.OutOfLength, "发起人超过最大50个字符长度。一条命令至多由一个人发起,这个人就是责任人,不存在联名发起命令一说。")); } #endregion #region 时间戳验证 if (context.Command.TimeStamp < SystemTime.Now().AddYears(-1) || // TODO:配置消息的左时间 context.Command.TimeStamp > SystemTime.Now().AddSeconds(context.Host.Config.TicksTimeout)) { return(new ProcessResult(false, Status.InvalidCommandTicks, "非法的命令时间戳,命令时间戳不能是一年前或将来。")); } #endregion #region 客户端类型验证 if (context.Command.ClientType == ClientType.Undefined) { return(new ProcessResult(false, Status.InvalidClientType, "非法的客户端类型")); } #endregion #region 节点验证 NodeDescriptor requestNode = null; if (context.Command.ClientType == ClientType.Node) { if (!context.Host.NodeHost.Nodes.TryGetNodeById(context.Command.ClientId, out requestNode)) { return(new ProcessResult(false, Status.InvalidClientId, "非法的节点")); } } #endregion #region 本体码验证 if (string.IsNullOrEmpty(context.Command.Ontology)) { return(new ProcessResult(false, Status.InvalidOntology, "必须通过本体码界定命令的上下文,本体码不能为空。")); } OntologyDescriptor ontology; if (!context.Host.NodeHost.Ontologies.TryGetOntology(context.Command.Ontology, out ontology)) { return(new ProcessResult(false, Status.InvalidOntology, "非法的本体码。本体列表中不存在编码为" + context.Ontology + "的本体码")); } if (ontology.Ontology.IsEnabled != 1) { return(new ProcessResult(false, Status.InvalidOntology, "该本体已被禁用")); } #endregion #region 动作码验证 if (string.IsNullOrEmpty(context.Command.Verb.Code)) { return(new ProcessResult(false, Status.InvalidVerb, "必须通过本体动作码来表明您的命令是要做什么,本体动作码不能为空。")); } if (!ontology.Actions.ContainsKey(context.Command.Verb)) { return(new ProcessResult(false, Status.InvalidVerb, "非法的动作码," + ontology.Ontology.Name + "未定义编码为" + context.Command.Verb + "的动作")); } if (context.Command.ClientType == ClientType.Node) { var nodeActions = requestNode.Node.NodeActions; if (!nodeActions.ContainsKey(ontology) || !nodeActions[ontology].ContainsKey(context.Command.Verb)) { return(new ProcessResult(false, Status.NoPermission, "您的节点没有" + ontology.Actions[context.Command.Verb].Name + ontology.Ontology.Name + "的权限")); } } #endregion #region 本体元素码验证器 if (context.Command.DataTuple.IdItems == null || context.Command.DataTuple.IdItems.IsEmpty) { return(new ProcessResult(false, Status.InvalidInfoId, "信息标识不能为空")); } var elementDic = ontology.Elements; var failDescription = new List <DataItem>(); var infoIdItems = new List <InfoItem>(); if (context.Command.DataTuple.IdItems != null) { foreach (var item in context.Command.DataTuple.IdItems.Items) { if (item.Key == null || !elementDic.ContainsKey(item.Key) || elementDic[item.Key].Element.IsEnabled != 1) { failDescription.Add(item); } else { infoIdItems.Add(InfoItem.Create(elementDic[item.Key], item.Value)); } } } var infoValueItems = new List <InfoItem>(); if (context.Command.DataTuple.ValueItems != null) { foreach (var item in context.Command.DataTuple.ValueItems.Items) { if (item.Key != null && !elementDic.ContainsKey(item.Key)) { failDescription.Add(item); } else { infoValueItems.Add(InfoItem.Create(elementDic[item.Key], item.Value)); } } } if (failDescription.Count > 0) { return(new ProcessResult(false, Status.InvalidElement, "非法的本体元素码" + failDescription[0].Key)); } #endregion #region 信息标识验证 if (context.Command.DataTuple.IdItems.IsEmpty) { return(new ProcessResult(false, Status.InvalidInfoId, "非法的信息标识")); } else if (ontology.Ontology.IsCataloguedEntity) { if (Verb.Create.Equals(context.Command.Verb) && type != MessageType.Event) { if (requestNode != context.Host.NodeHost.Nodes.CenterNode && context.Command.DataTuple.IdItems.Items.Any(a => string.Equals(a.Key, "Id", StringComparison.OrdinalIgnoreCase))) { return(new ProcessResult(false, Status.InvalidInfoId, "非中心节点的create型命令不能提供Id")); } else if ((ontology.Ontology.IsCataloguedEntity && !context.Command.DataTuple.IdItems.Items.Any(a => string.Equals(a.Key, "ZZJGM", StringComparison.OrdinalIgnoreCase))) || !context.Command.DataTuple.IdItems.Items.Any(a => string.Equals(a.Key, "XM", StringComparison.OrdinalIgnoreCase))) { return(new ProcessResult(false, Status.InvalidInfoId, "没有提供姓名或目录")); } } } #endregion #region 信息标识项验证 ProcessResult result; foreach (var infoItem in infoIdItems) { if (!this.ValidInfoItem(infoItem, out result)) { return(result); } } #endregion #region 信息值项验证 if (Verb.Create.Equals(context.Command.Verb) || Verb.Update.Equals(context.Command.Verb)) { if (context.Command.DataTuple.ValueItems.IsEmpty) { return(new ProcessResult(false, Status.InvalidInfoValue, "Create和Update型动作必须提供InfoValue输入")); } foreach (var infoItem in infoValueItems) { if (!this.ValidInfoItem(infoItem, out result)) { return(result); } } } #endregion return(new ProcessResult(true, Status.Ok, "命令输入验证通过")); }
public void InitSuccessorCache() { SuccessorCache = new NodeDescriptor[SuccessorCacheSize]; for (int i = 0; i <= SuccessorCacheSize - 1; ++i) { SuccessorCache[i] = Endpoint; } }
/// <summary> /// /// </summary> /// <param name="cmdDto"></param> /// <param name="toNode"></param> /// <returns></returns> public static IMessageDto RequestNode(this IMessageDto cmdDto, NodeDescriptor toNode) { if (cmdDto == null) { throw new ArgumentNullException("cmdDto"); } if (toNode == null) { throw new ArgumentNullException("toNode"); } if (cmdDto.Credential == null) { throw new GeneralException("非法状态的命令,没有设置证书"); } if (string.IsNullOrEmpty(cmdDto.Credential.Password)) { CredentialType credentialType; if (!cmdDto.Credential.CredentialType.TryParse(out credentialType)) { throw new GeneralException("意外的证书类型" + cmdDto.Credential.CredentialType); } ClientType clientType; if (!cmdDto.Credential.ClientType.TryParse(out clientType)) { throw new GeneralException("意外的客户端类型" + cmdDto.Credential.ClientType); } switch (clientType) { case ClientType.Undefined: break; case ClientType.Node: NodeDescriptor clientNode; if (!toNode.AcDomain.NodeHost.Nodes.TryGetNodeByPublicKey(cmdDto.Credential.ClientId, out clientNode)) { throw new GeneralException("意外的客户节点标识" + cmdDto.Credential.ClientId); } switch (credentialType) { case CredentialType.Undefined: break; case CredentialType.Token: cmdDto.Credential.Password = TokenObject.Token(cmdDto.Credential.ClientId, cmdDto.Credential.Ticks, clientNode.Node.SecretKey); break; case CredentialType.Signature: cmdDto.Credential.Password = Signature.Sign(cmdDto.ToOrignalString(cmdDto.Credential), clientNode.Node.SecretKey); break; case CredentialType.OAuth: break; default: break; } break; case ClientType.App: break; case ClientType.Monitor: break; default: break; } } return cmdDto.ToAnyCommand(toNode).Request(); }
private Type GetArrayItemType(NodeDescriptor descriptor) { Type itemType = null; Type[] argTypes = descriptor.ObjectType.GetBaseGenericArguments(); if (argTypes != null && argTypes.Length > 0) { itemType = argTypes[0]; if (itemType.IsPrimitive || itemType == typeof(Guid) || itemType == typeof(string)) { itemType = null; } } return itemType; }
/// <summary> /// /// </summary> /// <param name="node"></param> /// <param name="request"></param> public BeatContext(NodeDescriptor node, BeatRequest request) { this.Node = node; this.Request = request; this.Response = new BeatResponse(); }
public static void CreateNode(NodeGraph currentGraph, NodeDescriptor nodeDescriptor, Vector2 mousePos) { if (currentGraph != null) { NodeBase currentNode = CreateNode(nodeDescriptor); positionNode(currentNode, currentGraph, mousePos); saveNode(currentNode, currentGraph); } }
private void handleDeviceMessage(Telegram telegram) { int num = telegram.data[0]; int nodeIndex = telegram.data[1] & 7; viewEZMacNetwork1.blinkNodeCommunication(nodeIndex); viewEZMacNetwork1.setNodeConnectionUpdate(nodeIndex); switch (num) { case 0x80: _log.Debug("EnergyHarvesting_Demo: handleDeviceMessage: NwD_iSlaveAssoc"); viewEZMacNetwork1.nodeConnected(nodeIndex, ViewEZMacNetwork.NodeLook.EnergyHarvester); send_Ack(); return; case 0x81: _log.Debug("EnergyHarvesting_Demo: handleDeviceMessage: NwD_iSlaveDisAc"); viewEZMacNetwork1.nodeDisconnected(nodeIndex); viewRssi1.setData(nodeIndex, 0.0); if ((nodeIndex >= 1) && (nodeIndex <= 4)) { _landscapeControls[nodeIndex - 1].group.Enabled = false; _nodeInfoControls[nodeIndex - 1].group.Enabled = false; _nodeInfoControls[nodeIndex - 1].vbat.Text = ""; _nodeInfoControls[nodeIndex - 1].temp.Text = ""; _nodeInfoControls[nodeIndex - 1].light.Text = ""; } send_Ack(); return; case 130: { _log.Debug("EnergyHarvesting_Demo: handleDeviceMessage: NwD_iPacRec"); NodeDescriptor descriptor = new NodeDescriptor(0, telegram.data); if ((descriptor.Address >= 1) && (descriptor.Address <= 4)) { if (!viewEZMacNetwork1.isNodeConnected(nodeIndex)) { viewEZMacNetwork1.nodeConnected(nodeIndex, ViewEZMacNetwork.NodeLook.EnergyHarvester); } if ((nodeIndex >= 1) && (nodeIndex <= 4)) { if (descriptor.NHDR == 7) { _landscapeControls[nodeIndex - 1].group.Enabled = true; _nodeInfoControls[nodeIndex - 1].group.Enabled = true; viewEZMacNetwork1.setNodeBatteryStatus(nodeIndex, descriptor.BatteryPercent); viewEZMacNetwork1.setNodeTemperature(nodeIndex, (float)descriptor.Temperature); _landscapeControls[nodeIndex - 1].landscape.Charge = descriptor.BatteryPercent; _landscapeControls[nodeIndex - 1].landscape.Temperature = descriptor.TemperatureString; _nodeInfoControls[nodeIndex - 1].vbat.Text = descriptor.BatteryPercent.ToString() + "%"; _nodeInfoControls[nodeIndex - 1].temp.Text = descriptor.TemperatureString; } else if (descriptor.NHDR == 8) { _landscapeControls[nodeIndex - 1].group.Enabled = true; _nodeInfoControls[nodeIndex - 1].group.Enabled = true; _landscapeControls[nodeIndex - 1].landscape.Lux = descriptor.Light.ToString() + " lux"; if (descriptor.Light < 250) { _landscapeControls[nodeIndex - 1].landscape.Image = ViewLandscape.ImageSelection.Night; } else if (descriptor.Light < 500) { _landscapeControls[nodeIndex - 1].landscape.Image = ViewLandscape.ImageSelection.Sunset; } else if (descriptor.Light < 750) { _landscapeControls[nodeIndex - 1].landscape.Image = ViewLandscape.ImageSelection.Midday; } else { _landscapeControls[nodeIndex - 1].landscape.Image = ViewLandscape.ImageSelection.Day; } _nodeInfoControls[nodeIndex - 1].light.Text = descriptor.Light + " lux"; } } viewDataReceiver1.messageReceived(telegram.data.Buf, telegram.data.NumItems); double data = telegram.data[2]; data = (data - 230.0) / 2.0; viewRssi1.setData(nodeIndex, data); send_Ack(); return; } send_Nack(); return; } case 0x83: _log.Debug("EnergyHarvesting_Demo: handleDeviceMessage: NwD_iADC"); send_Ack(); return; case 0x85: { _log.Debug("EnergyHarvesting_Demo: handleDeviceMessage: NwD_MStatInd"); MasterStatus status = (MasterStatus)telegram.data[1]; if ((status < MasterStatus.MasterNonArmed) || (status == MasterStatus.Undefined)) { viewEZMacNetwork1.nodeDisconnected(1); viewEZMacNetwork1.nodeDisconnected(2); viewEZMacNetwork1.nodeDisconnected(3); viewEZMacNetwork1.nodeDisconnected(4); } send_Ack(); return; } } _log.Debug("EnergyHarvesting_Demo: handleDeviceMessage: Unknown ComandID=" + num); send_Nack(); }
public static NodeBase CreateNode(NodeDescriptor descriptor) { NodeBase currentNode = null; if(descriptor.nodeType == NodeType.Graph) { currentNode = ScriptableObject.CreateInstance<NodeBase>(); } else { currentNode = ScriptableObject.CreateInstance<NodeBase>(); currentNode.InitNodeFromDescriptor(descriptor); } return currentNode; }
public override void OnConfigure( IDescriptorContext context, IObjectTypeDescriptor descriptor, Type type) { INodeDescriptor nodeDescriptor = new NodeDescriptor(descriptor, type); if (IdField is not null) { MemberInfo?idField = type.GetMember(IdField).FirstOrDefault(); if (idField is null) { throw NodeAttribute_IdFieldNotFound(type, IdField); } nodeDescriptor.IdField(idField); } else if (context.TypeInspector.GetNodeIdMember(type) is { } id) { nodeDescriptor.IdField(id); } if (NodeResolverType is not null) { if (NodeResolver is not null) { MethodInfo?method = NodeResolverType.GetMethod(NodeResolver); if (method is null) { throw NodeAttribute_NodeResolverNotFound( NodeResolverType, NodeResolver); } nodeDescriptor.ResolveNodeWith(method); } else { nodeDescriptor.ResolveNodeWith(NodeResolverType); } } else if (NodeResolver is not null) { MethodInfo?method = type.GetMethod(NodeResolver); if (method is null) { throw NodeAttribute_NodeResolverNotFound( type, NodeResolver); } nodeDescriptor.ResolveNodeWith(method); } else { nodeDescriptor.ResolveNodeWith(type); } }
/// <summary> /// Updates the node. This will copy data from another node into this node. Updated elements are checked for equality /// and the method will only return true if the node data has been changed. /// /// <param name="node">the <see cref="ZigBeeNode"> that contains the newer node data.</param> /// <returns>true if there were changes made as a result of the update</returns> /// </summary> public bool UpdateNode(ZigBeeNode node) { if (!node.IeeeAddress.Equals(IeeeAddress)) { Log.Debug("{IeeeAddress}: Ieee address inconsistent during update <>{NodeIeeeAddress}", IeeeAddress, node.IeeeAddress); return(false); } bool updated = false; if (NetworkAddress != 0 && !NetworkAddress.Equals(node.NetworkAddress)) { Log.Debug("{IeeeAddress}: Network address updated from {NetworkAddress} to {NodeNetworkAddress}", IeeeAddress, NetworkAddress, node.NetworkAddress); updated = true; NetworkAddress = node.NetworkAddress; } if (node.NodeDescriptor != null && (NodeDescriptor == null || !NodeDescriptor.Equals(node.NodeDescriptor))) { Log.Debug("{IeeeAddress}: Node descriptor updated", IeeeAddress); updated = true; NodeDescriptor = node.NodeDescriptor; } if (node.PowerDescriptor != null && (PowerDescriptor == null || !PowerDescriptor.Equals(node.PowerDescriptor))) { Log.Debug("{IeeeAddress}: Power descriptor updated", IeeeAddress); updated = true; PowerDescriptor = node.PowerDescriptor; } lock (_associatedDevices) { if (!_associatedDevices.SetEquals(node._associatedDevices)) { Log.Debug("{IeeeAddress}: Associated devices updated", IeeeAddress); updated = true; _associatedDevices.Clear(); _associatedDevices.UnionWith(node._associatedDevices); } } lock (_bindingTable) { if (!_bindingTable.SetEquals(node._bindingTable)) { Log.Debug("{IeeeAddress}: Binding table updated", IeeeAddress); updated = true; _bindingTable.Clear(); _bindingTable.UnionWith(node._bindingTable); } } lock (_neighbors) { if (!_neighbors.SetEquals(node._neighbors)) { Log.Debug("{IeeeAddress}: Neighbors updated", IeeeAddress); updated = true; _neighbors.Clear(); _neighbors.UnionWith(node._neighbors); } } lock (_routes) { if (!_routes.SetEquals(node._routes)) { Log.Debug("{IeeeAddress}: Routes updated", IeeeAddress); updated = true; _routes.Clear(); _routes.UnionWith(node._routes); } } // Endpoints are only copied over if they don't exist in the node // The assumption here is that endpoints are only set once, and not changed. // This should be valid as they are set through the SimpleDescriptor. foreach (var endpoint in node._endpoints) { if (_endpoints.ContainsKey(endpoint.Key)) { continue; } Log.Debug("{IeeeAddress}: Endpoint {EndpointId} added", IeeeAddress, endpoint.Key); updated = true; _endpoints[endpoint.Key] = endpoint.Value; } return(updated); }
/// <summary> /// Updates the node. This will copy data from another node into this node. Updated elements are checked for equality /// and the method will only return true if the node data has been changed. /// /// <param name="node">the <see cref="ZigBeeNode"> that contains the newer node data.</param> /// <returns>true if there were changes made as a result of the update</returns> /// </summary> public bool UpdateNode(ZigBeeNode node) { if (!node.IeeeAddress.Equals(IeeeAddress)) { return(false); } bool updated = false; if (!NetworkAddress.Equals(node.NetworkAddress)) { updated = true; NetworkAddress = node.NetworkAddress; } if (!NodeDescriptor.Equals(node.NodeDescriptor)) { updated = true; NodeDescriptor = node.NodeDescriptor; } if (!PowerDescriptor.Equals(node.PowerDescriptor)) { updated = true; PowerDescriptor = node.PowerDescriptor; } lock (AssociatedDevices) { if (!AssociatedDevices.Equals(node.AssociatedDevices)) { updated = true; AssociatedDevices.Clear(); AssociatedDevices.AddRange(node.AssociatedDevices); } } lock (BindingTable) { if (!BindingTable.Equals(node.BindingTable)) { updated = true; BindingTable.Clear(); BindingTable.AddRange(node.BindingTable); } } lock (Neighbors) { if (!Neighbors.Equals(node.Neighbors)) { updated = true; Neighbors.Clear(); Neighbors.AddRange(node.Neighbors); } } lock (Routes) { if (!Routes.Equals(node.Routes)) { updated = true; Routes.Clear(); Routes.AddRange(node.Routes); } } // Endpoints are only copied over if they don't exist in the node // The assumption here is that endpoints are only set once, and not changed. // This should be valid as they are set through the SimpleDescriptor. foreach (var endpoint in node.Endpoints) { if (Endpoints.ContainsKey(endpoint.Key)) { continue; } updated = true; Endpoints[endpoint.Key] = endpoint.Value; } return(updated); }
public void ProcessContextEvent(Event e) { if (viewRect.Contains(e.mousePosition)) { if (e.button == 1) // Right Mouseclick { if (e.type == EventType.MouseDown) { selectedNodeShelfGroup = null; selectedNodeShelfNode = null; selectedBasicNode = null; foreach (NodeShelfGroup g in typesOfShelfGroups) { if (g.groupRect.Contains(e.mousePosition)) { selectedNodeShelfGroup = g; foreach (NodeShelfGroupNode n in selectedNodeShelfGroup.shelfNodes) { if (n.shelfNodeRect.Contains(e.mousePosition)) { selectedNodeShelfNode = n; } } } } for (int i = 0; i < currentNodeGraph.typesOfNodes.Count; i++) { if (basicNodeRects != null) { if (basicNodeRects[i].Contains(e.mousePosition)) { selectedBasicNode = currentNodeGraph.typesOfNodes[i]; } } } ProcessContextMenu(e); } } } }
public ReplacementParameters(NodeDescriptor descriptor) { this.Descriptor = descriptor; Fillin(); }
private void UpdateAttachTo(NodeDescriptor descriptor) { descriptor.Visited = true; AttachToPath.Add(descriptor); foreach (NodeDescriptor child in descriptor.Children) { if (!AttachToPath.Contains(child) || child.Equals(descriptor.CollectionItem)) { child.AttachTo.Append(descriptor); if (!child.Visited) { UpdateAttachTo(child); } } else { //child.Excludes.Append(descriptor); //if(child.AttachTo.Contains( } } AttachToPath.Remove(descriptor); }
/// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="dataTuple"></param> /// <param name = "responseNode"></param> private AnyMessage(MessageTypeKind type, DataItemsTuple dataTuple, NodeDescriptor responseNode) : this(type, Guid.NewGuid(), dataTuple, responseNode) { }
public override string GetAddress(NodeDescriptor actor) { return(actor.AnycmdApiAddress); }
/// <summary> /// 创建给定的节点的命令 /// </summary> /// <param name="request"></param> /// <param name="responseNode"></param> /// <returns></returns> public static AnyMessage Create(HecpRequest request, NodeDescriptor responseNode) { if (request == null) { throw new ArgumentNullException("request"); } if (responseNode == null) { throw new ArgumentNullException("responseNode"); } var acDomain = responseNode.AcDomain; var clientId = string.Empty; var credential = request.Credential; if (credential == null) { throw new InvalidOperationException(); } switch (credential.ClientType) { case ClientType.Undefined: break; case ClientType.Node: NodeDescriptor requester; if (acDomain.NodeHost.Nodes.TryGetNodeByPublicKey(credential.ClientId, out requester)) { clientId = requester.Id.ToString(); } break; case ClientType.App: break; case ClientType.Monitor: break; default: break; } var dataTuple = DataItemsTuple.Create( acDomain, request.InfoId, request.InfoValue, request.QueryList, acDomain.Config.InfoFormat); MessageType requestType; request.MessageType.TryParse(out requestType); return(new AnyMessage(MessageTypeKind.AnyCommand, Guid.NewGuid(), dataTuple, responseNode) { Version = request.Version, IsDumb = request.IsDumb, Ontology = request.Ontology, ReceivedOn = DateTime.Now, CreateOn = DateTime.Now, MessageId = request.MessageId, ClientId = clientId, Verb = request.Verb, MessageType = requestType, ClientType = credential.ClientType, TimeStamp = SystemTime.ParseUtcTicksToLocalTime(request.TimeStamp), ReasonPhrase = request.EventReasonPhrase, Status = request.EventStatus, UserName = request.Credential.UserName, EventSourceType = request.EventSourceType, EventSubjectCode = request.EventSubject, LocalEntityId = null, Description = null, CatalogCode = null, From = request.From, RelatesTo = request.RelatesTo, To = request.To, SessionId = request.SessionId }); }
private void updateNodeWindow(int nodeIndex, NodeDescriptor a_node) { ViewNodeInfo info = viewEZMacNetwork1.getAssociatedNodeWindow(nodeIndex); if (info != null) { info.Activate = true; info.Temperature = a_node.Temperature; if (a_node.Analog != 0xffff) { info.ADCValue = a_node.Analog.ToString(); } else { info.ADCValue = "n.a."; } info.Trigger = a_node.Button.ToString(); } else { info.Activate = false; } }
internal virtual PropertyDescriptorCollection GetPropertyDescriptors() { if (this.m_cache == null) { PropertyDescriptor[] properties = new PropertyDescriptor[this.m_names.Length]; for (int i = 0; i < this.m_names.Length; i++) { properties[i] = new NodeDescriptor(this.m_names[i]); } this.m_cache = new PropertyDescriptorCollection(properties); } return this.m_cache; }
private void handleDeviceMessage(Telegram telegram) { int num = telegram.data[0]; int nodeIndex = telegram.data[1] & 7; int num3 = telegram.data[2]; viewEZMacNetwork1.blinkNodeCommunication(nodeIndex); viewEZMacNetwork1.setNodeConnectionUpdate(nodeIndex); if (((_ioph is IOPH_DCP) && (num == 0x80)) || ((_ioph is IOPH_DATA) && (num == 11))) { _log.Debug("Security_Demo: handleDeviceMessage: NwD_iSlaveAssoc"); _log.Error("Assoc: " + num.ToString("X2")); ViewEZMacNetwork.NodeLook ezLink = ViewEZMacNetwork.NodeLook.EzLink; int num5 = num3; if ((num5 != 1) && (num5 == 11)) { ezLink = ViewEZMacNetwork.NodeLook.SensorNode; } else { ezLink = ViewEZMacNetwork.NodeLook.EzLink; } viewEZMacNetwork1.nodeConnected(nodeIndex, ezLink); viewDataReceiver1.messageReceived(telegram.data.Buf, telegram.data.NumItems); send_Ack(); } else if (((_ioph is IOPH_DCP) && (num == 0x81)) || ((_ioph is IOPH_DATA) && (num == 12))) { _log.Debug("Security_Demo: handleDeviceMessage: NwD_iSlaveDisAc"); viewEZMacNetwork1.nodeDisconnected(nodeIndex); viewRssi1.setData(nodeIndex, 0.0); send_Ack(); } else if (((_ioph is IOPH_DCP) && (num == 130)) || ((_ioph is IOPH_DATA) && (num == 13))) { _log.Debug("Security_Demo: handleDeviceMessage: NwD_iPacRec"); _log.Error("Data"); NodeDescriptor descriptor = new NodeDescriptor(0, telegram.data); if ((descriptor.Address < 1) || (descriptor.Address > 4)) { send_Nack(); } else { if (!viewEZMacNetwork1.isNodeConnected(nodeIndex)) { if ((telegram.data.NumItems > 9) && (telegram.data[9] == 0x33)) { viewEZMacNetwork1.nodeConnected(nodeIndex, ViewEZMacNetwork.NodeLook.SensorNode); } else { viewEZMacNetwork1.nodeConnected(nodeIndex, ViewEZMacNetwork.NodeLook.EzLink); } } updateNodeWindow(nodeIndex, descriptor); viewEZMacNetwork1.setNodeBatteryStatus(nodeIndex, descriptor.Battery); viewEZMacNetwork1.setNodeTemperature(nodeIndex, descriptor.TemperatureFloat); viewEZMacNetwork1.setNodeHumidity(nodeIndex, descriptor.Humidity); viewDataReceiver1.messageReceived(telegram.data.Buf, telegram.data.NumItems); double data = telegram.data[2]; data = (data - 230.0) / 2.0; viewRssi1.setData(nodeIndex, data); if (descriptor.Button) { viewHouse.motionSensor(nodeIndex, descriptor.Button); } if (_masterStatus == MasterStatus.MasterArmed) { viewHouse.setAlertingNode(nodeIndex); } send_Ack(); } } else if ((_ioph is IOPH_DCP) && (num == 0x83)) { _log.Debug("Security_Demo: handleDeviceMessage: NwD_iADC"); send_Ack(); } else if (((_ioph is IOPH_DCP) && (num == 0x85)) || ((_ioph is IOPH_DATA) && (num == 14))) { _log.Debug("Security_Demo: handleDeviceMessage: NwD_MStatInd"); MasterStatus status = (MasterStatus) telegram.data[1]; if ((status < MasterStatus.MasterNonArmed) || (status == MasterStatus.Undefined)) { viewEZMacNetwork1.nodeDisconnected(1); viewEZMacNetwork1.nodeDisconnected(2); viewEZMacNetwork1.nodeDisconnected(3); viewEZMacNetwork1.nodeDisconnected(4); } MasterStatusUpdate(status, nodeIndex); send_Ack(); } else { _log.Debug("Security_Demo: handleDeviceMessage: Unknown ComandID=" + num); send_Nack(); } }
/// <summary> /// Updates the node. This will copy data from another node into this node. Updated elements are checked for equality /// and the method will only return true if the node data has been changed. /// /// @param node the {@link ZigBeeNode} that contains the newer node data. /// @return true if there were changes made as a result of the update /// </summary> public bool UpdateNode(ZigBeeNode node) { if (!node.IeeeAddress.Equals(IeeeAddress)) { return(false); } bool updated = false; if (!NetworkAddress.Equals(node.NetworkAddress)) { updated = true; NetworkAddress = node.NetworkAddress; } if (!NodeDescriptor.Equals(node.NodeDescriptor)) { updated = true; NodeDescriptor = node.NodeDescriptor; } if (!PowerDescriptor.Equals(node.PowerDescriptor)) { updated = true; PowerDescriptor = node.PowerDescriptor; } lock (AssociatedDevices) { if (!AssociatedDevices.Equals(node.AssociatedDevices)) { updated = true; AssociatedDevices.Clear(); AssociatedDevices.AddRange(node.AssociatedDevices); } } lock (BindingTable) { if (!BindingTable.Equals(node.BindingTable)) { updated = true; BindingTable.Clear(); BindingTable.AddRange(node.BindingTable); } } lock (Neighbors) { if (!Neighbors.Equals(node.Neighbors)) { updated = true; Neighbors.Clear(); Neighbors.AddRange(node.Neighbors); } } lock (Routes) { if (!Routes.Equals(node.Routes)) { updated = true; Routes.Clear(); Routes.AddRange(node.Routes); } } // TODO: How to deal with endpoints return(updated); }
public static byte[] GetNodeHashArgument(NodeDescriptor.NodeInitInfo node) { return GetHashArgument(node.IpAddress + ":" + node.Port + "," + node.OverlayLevel); }