Пример #1
0
 public BT_Execute(BT_Node _c, BT_Node _p, NodeEvent _e)
 {
     nodeEvent = _e;
     children  = new List <BT_Node>();
     children.Add(_c);
     parent = _p;
 }
Пример #2
0
    private async Async.Task <HttpResponseData> Post(HttpRequestData req)
    {
        var request = await RequestHandling.ParseRequest <NodeStateEnvelope>(req);

        if (!request.IsOk)
        {
            return(await _context.RequestHandling.NotOk(req, request.ErrorV, context : "node event"));
        }

        var envelope = request.OkV;

        _log.Info($"node event: machine_id: {envelope.MachineId} event: {EntityConverter.ToJsonString(envelope)}");

        var error = envelope.Event switch {
            NodeStateUpdate updateEvent => await OnStateUpdate(envelope.MachineId, updateEvent),
            WorkerEvent workerEvent => await OnWorkerEvent(envelope.MachineId, workerEvent),
            NodeEvent nodeEvent => await OnNodeEvent(envelope.MachineId, nodeEvent),
            _ => new Error(ErrorCode.INVALID_REQUEST, new string[] { $"invalid node event: {envelope.Event.GetType().Name}" }),
        };

        if (error is Error e)
        {
            return(await _context.RequestHandling.NotOk(req, e, context : "node event"));
        }
        else
        {
            return(await RequestHandling.Ok(req, new BoolResult(true)));
        }
    }
Пример #3
0
 public static void ResendOnWakeUp(ZWaveNode node, byte[] msg)
 {
     int minCommandLength = 8;
     if (msg.Length >= minCommandLength)
     {
         byte[] command = new byte[minCommandLength];
         Array.Copy(msg, 0, command, 0, minCommandLength);
         // discard any message having same header and command (first 8 bytes = header + command class + command)
         var wakeUpResendQueue = GetResendQueueData(node);
         for (int i = wakeUpResendQueue.Count - 1; i >= 0; i--)
         {
             byte[] queuedCommand = new byte[minCommandLength];
             Array.Copy(wakeUpResendQueue[i], 0, queuedCommand, 0, minCommandLength);
             if (queuedCommand.SequenceEqual(command))
             {
                 Utility.logger.Trace("Removing old message {0}", BitConverter.ToString(wakeUpResendQueue[i]));
                 wakeUpResendQueue.RemoveAt(i);
             }
         }
         Utility.logger.Trace("Adding message {0}", BitConverter.ToString(msg));
         wakeUpResendQueue.Add(msg);
         var wakeUpStatus = (WakeUpStatus)node.GetData("WakeUpStatus", new WakeUpStatus()).Value;
         if (!wakeUpStatus.IsSleeping)
         {
             wakeUpStatus.IsSleeping = true;
             var nodeEvent = new NodeEvent(node, EventParameter.WakeUpSleepingStatus, 1 /* 1 = sleeping, 0 = awake */, 0);
             node.OnNodeUpdated(nodeEvent);
         }
     }
 }
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            byte      cmdType   = message[1];

            if (message.Length > 4 && cmdType == (byte)Command.ConfigurationReport)
            {
                byte paramId     = message[2];
                byte paramLength = message[3];
                //
                var nodeConfigParamsLength = GetConfigParamsData(node);
                if (!nodeConfigParamsLength.ContainsKey(paramId))
                {
                    nodeConfigParamsLength.Add(paramId, paramLength);
                }
                else
                {
                    // this shouldn't change on read... but you never know! =)
                    nodeConfigParamsLength[paramId] = paramLength;
                }
                //
                byte[] bval = new byte[4];
                // extract bytes value
                Array.Copy(message, 4, bval, 4 - (int)paramLength, (int)paramLength);
                uint paramValue = bval[0];
                Array.Reverse(bval);
                // convert it to uint
                paramValue = BitConverter.ToUInt32(bval, 0);
                nodeEvent  = new NodeEvent(node, EventParameter.Configuration, paramValue, paramId);
            }
            return(nodeEvent);
        }
Пример #5
0
        bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
        {
            var typeName = nodeEvent.Tag; // this is what gets the "!MyDotnetClass" tag from the yaml

            if (string.IsNullOrEmpty(typeName))
            {
                return(false);
            }

            var arrayType = false;

            if (typeName.EndsWith("[]")) // this handles tags for array types like "!MyDotnetClass[]"
            {
                arrayType = true;
                typeName  = typeName.Substring(0, typeName.Length - 2);
            }

            if (!_tagMappings.TryGetValue(typeName, out var predefinedType))
            {
                throw new YamlException(
                          $"I can't find the type '{nodeEvent.Tag}'. Is it spelled correctly? If there are" +
                          $" multiple types named '{nodeEvent.Tag}', you must used the fully qualified type name.");
            }

            currentType = arrayType ? predefinedType.MakeArrayType() : predefinedType;
            return(true);
        }
Пример #6
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            Command   type      = (Command)message[1];

            if (type == Command.VersionCommandClassReport)
            {
                CommandClass cmdClass = (CommandClass)message[2];
                VersionValue value    = new VersionValue(cmdClass, message[3]);
                // Update node CC data
                if (cmdClass != CommandClass.NotSet)
                {
                    var nodeCc = node.GetCommandClass(cmdClass);
                    if (nodeCc != null)
                    {
                        nodeCc.Version = value.Version;
                    }
                    // Set the VersionCommandClass event
                    nodeEvent = new NodeEvent(node, EventParameter.VersionCommandClass, value, 0);
                }
                else
                {
                    Utility.logger.Warn("Command Class {0} ({1}) not supported yet", message[3], message[3].ToString("X2"));
                }
            }

            return(nodeEvent);
        }
Пример #7
0
        public bool Resolve(NodeEvent nodeEvent, ref Type currentType)
        {
            if (currentType == typeof(object))
            {
                if (nodeEvent is Scalar scalar)
                {
                    if (Regex.IsMatch(scalar.Value, @"^(true|false)$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(bool);
                        return(true);
                    }

                    if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* )$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(int);
                        return(true);
                    }

                    if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]* )? ( [eE] [-+]? [0-9]+ )?$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(float);
                        return(true);
                    }
                }
            }

            return(false);
        }
        bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
        {
            if (currentType == typeof(object))
            {
                var scalar = nodeEvent as Scalar;
                if (scalar != null)
                {
                    if (scalar.Value.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        currentType = typeof(int);
                        return(true);
                    }
                    if (Regex.IsMatch(scalar.Value, @"^(true|false)$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(bool);
                        return(true);
                    }

                    if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* )$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(int);
                        return(true);
                    }

                    if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]* )? ( [eE] [-+]? [0-9]+ )?$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(float);
                        return(true);
                    }
                }
            }
            return(false);
        }
Пример #9
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            Command type = (Command)message[1];

            if (type == Command.VersionCommandClassReport)
            {
                if (!Enum.IsDefined(typeof(CommandClass), message[2]))
                {
                    return nodeEvent;
                }
                CommandClass cmdClass = (CommandClass)message[2];
                VersionValue value = new VersionValue(cmdClass, message[3]);
                // Update node CC data
                if (cmdClass != CommandClass.NotSet)
                {
                    var nodeCc = node.GetCommandClass(cmdClass);
                    if (nodeCc != null)
                        nodeCc.Version = value.Version;
                    // Set the VersionCommandClass event
                    nodeEvent = new NodeEvent(node, EventParameter.VersionCommandClass, value, 0);
                }
                else
                {
                    Utility.logger.Warn("Command Class {0} ({1}) not supported yet", message[3], message[3].ToString("X2"));
                }
            }

            return nodeEvent;
        }
Пример #10
0
            bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
            {
                if (nodeEvent == null || nodeEvent.Tag.IsEmpty)
                {
                    return(false);
                }

                string typeName  = nodeEvent.Tag.Value; // this is what gets the "!TargetingData" tag from the yaml
                bool   arrayType = false;

                if (typeName.EndsWith("[]")) // this handles tags for array types like "!TargetingData[]"
                {
                    arrayType = true;
                    typeName  = typeName.Substring(0, typeName.Length - 2);
                }

                if (tagMappings.TryGetValue(typeName, out var predefinedType))
                {
                    currentType = arrayType ? predefinedType.MakeArrayType() : predefinedType;
                    return(true);
                }
                else
                {
                    throw new YamlException(
                              $"I can't find the type '{nodeEvent.Tag}'. Is it spelled correctly? If there are" +
                              $" multiple types named '{nodeEvent.Tag}', you must used the fully qualified type name.");
                }
            }
Пример #11
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;

            if (message.Length > 7)
            {
                byte[] manufacturerId = new byte[2] {
                    message[2], message[3]
                };
                byte[] typeId = new byte[2] {
                    message[4], message[5]
                };
                byte[] productId = new byte[2] {
                    message[6], message[7]
                };

                var manufacturerSpecs = new ManufacturerSpecificInfo()
                {
                    TypeId         = BitConverter.ToString(typeId).Replace("-", ""),
                    ProductId      = BitConverter.ToString(productId).Replace("-", ""),
                    ManufacturerId = BitConverter.ToString(manufacturerId).Replace("-", "")
                };
                node.ManufacturerSpecific.ManufacturerId = manufacturerSpecs.ManufacturerId;
                node.ManufacturerSpecific.TypeId         = manufacturerSpecs.TypeId;
                node.ManufacturerSpecific.ProductId      = manufacturerSpecs.ProductId;
                nodeEvent = new NodeEvent(node, EventParameter.ManufacturerSpecific, manufacturerSpecs, 0);
            }

            return(nodeEvent);
        }
Пример #12
0
        bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
        {
            // TODO: should use the correct boolean parser (which accepts yes/no) instead of bool.tryparse
            if (currentType == typeof(object) && nodeEvent is Scalar)
            {
                var scalar = nodeEvent as Scalar;
                if (scalar.IsPlainImplicit)
                {
                    if (bool.TryParse(scalar.Value, out var boolValue))
                    {
                        currentType = typeof(bool);
                        return(true);
                    }

                    if (int.TryParse(scalar.Value, out var intValue))
                    {
                        currentType = typeof(int);
                        return(true);
                    }

                    if (double.TryParse(scalar.Value, out var doubleValue))
                    {
                        currentType = typeof(double);
                        return(true);
                    }
                }
            }

            return(false);
        }
        public bool Resolve(NodeEvent nodeEvent, ref Type currentType)
        {
#pragma warning disable 0618 // IYamlSerializable is obsolete
            return(typeof(IYamlSerializable).IsAssignableFrom(currentType));

#pragma warning restore 0618
        }
Пример #14
0
        public string GetDefaultTag(NodeEvent nodeEvent)
        {
            EnsureScalarRules();

            if (nodeEvent == null)
            {
                throw new ArgumentNullException("nodeEvent");
            }

            var mapping = nodeEvent as MappingStart;

            if (mapping != null)
            {
                return(GetDefaultTag(mapping));
            }

            var sequence = nodeEvent as SequenceStart;

            if (sequence != null)
            {
                return(GetDefaultTag(sequence));
            }

            var scalar = nodeEvent as Scalar;

            if (scalar != null)
            {
                object value;
                string tag;
                TryParse(scalar, false, out tag, out value);
                return(tag);
            }

            throw new NotSupportedException("NodeEvent [{0}] not supported".DoFormat(nodeEvent.GetType().FullName));
        }
Пример #15
0
        private NodeEvent HandleMultiChannelEncapReport(ZWaveNode node, byte[] message)
        {
            if (message.Length < 6)
            {
                Utility.logger.Error(String.Format("MultiChannel encapsulated message ERROR: message is too short: {0}", BitConverter.ToString(message)));
                return(null);
            }

            var instanceNumber   = message[2];
            var instanceCmdClass = message[4];
            var instanceMessage  = new byte[message.Length - 4]; //TODO

            Array.Copy(message, 4, instanceMessage, 0, message.Length - 4);

            Utility.logger.Debug(String.Format("MultiChannel encapsulated message: CmdClass: {0}; message: {1}", instanceCmdClass, BitConverter.ToString(instanceMessage)));

            var cc = CommandClassFactory.GetCommandClass(instanceCmdClass);

            if (cc == null)
            {
                Utility.logger.Error(String.Format("Can't find CommandClass handler for command class {0}", instanceCmdClass));
                return(null);
            }
            NodeEvent zevent = cc.GetEvent(node, instanceMessage);

            zevent.Instance    = instanceNumber;
            zevent.NestedEvent = GetNestedEvent(instanceCmdClass, zevent);
            return(zevent);
        }
Пример #16
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="changeHint"></param>
 /// <param name="index"></param>
 protected void SendOwnerNodeChanged(NodeEvent changeHint, int index)
 {
     if (_owner != null)
     {
         _owner.Root.SendNodeChanged(Owner, changeHint, index);
     }
 }
Пример #17
0
 /// <summary>
 /// Raises the event.
 /// </summary>
 /// <param name="e">Event to be raised.</param>
 void RaiseEvent(NodeEvent e)
 {
     if (e != null)
     {
         e(this);
     }
 }
Пример #18
0
        private NodeEvent HandleMultiInstanceEncapReport(ZWaveNode node, byte[] message)
        {
            if (message.Length < 5)
            {
                Utility.DebugLog(DebugMessageType.Warning, String.Format("MultiInstance encapsulated message ERROR: message is too short: {0}", BitConverter.ToString(message)));
                return(null);
            }

            byte instanceNumber   = message[2];
            var  instanceCmdClass = message[3];
            var  instanceMessage  = new byte[message.Length - 3]; //TODO:

            Array.Copy(message, 3, instanceMessage, 0, message.Length - 3);

            Utility.DebugLog(DebugMessageType.Information, String.Format("MultiInstance encapsulated message: CmdClass: {0}; message: {1}", instanceCmdClass, BitConverter.ToString(instanceMessage)));

            var cc = CommandClassFactory.GetCommandClass(instanceCmdClass);

            if (cc == null)
            {
                Utility.DebugLog(DebugMessageType.Warning, String.Format("Can't find CommandClass handler for command class {0}", instanceCmdClass));
                return(null);
            }
            NodeEvent zevent = cc.GetEvent(node, instanceMessage);

            zevent.Instance    = instanceNumber;
            zevent.NestedEvent = GetNestedEvent(instanceCmdClass, zevent);
            return(zevent);
        }
Пример #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="node"></param>
 /// <param name="change"></param>
 /// <param name="index"></param>
 public void SendNodeChanged(T node, NodeEvent change, int index)
 {
     if (NodeChanged != null)
     {
         NodeChanged(this, new TreeEventArgs <T>(node, change, index));
     }
 }
Пример #20
0
        public bool Resolve(NodeEvent nodeEvent, ref System.Type currentType)
        {
            var scalar = nodeEvent as Scalar;

            if ((scalar != null) && (scalar.Style == ScalarStyle.Plain))
            {
                var value = scalar.Value;

                if (value == falseString || value == trueString)
                {
                    currentType = typeof(bool);
                    return(true);
                }

                if (isIntRegex.IsMatch(value))
                {
                    currentType = typeof(int);
                    return(true);
                }

                if (isDoubleRegex.IsMatch(value))
                {
                    currentType = typeof(double);
                    return(true);
                }
            }

            return(false);
        }
Пример #21
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (message.Length > 4 && cmdType == (byte)Command.ConfigurationReport)
     {
         byte paramId = message[2];
         byte paramLength = message[3];
         //
         var nodeConfigParamsLength = GetConfigParamsData(node);
         if (!nodeConfigParamsLength.ContainsKey(paramId))
         {
             nodeConfigParamsLength.Add(paramId, paramLength);
         }
         else
         {
             // this shouldn't change on read... but you never know! =)
             nodeConfigParamsLength[paramId] = paramLength;
         }
         //
         byte[] bval = new byte[4];
         // extract bytes value
         Array.Copy(message, 4, bval, 4 - (int)paramLength, (int)paramLength);
         uint paramValue = bval[0];
         Array.Reverse(bval);
         // convert it to uint
         paramValue = BitConverter.ToUInt32(bval, 0);
         nodeEvent = new NodeEvent(node, EventParameter.Configuration, paramValue, paramId);
     }
     return nodeEvent;
 }
Пример #22
0
        public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
        {
            NodeEvent nodeEvent     = parser.Peek <NodeEvent>();
            Type      typeFromEvent = GetTypeFromEvent(nodeEvent, expectedType);

            try
            {
                foreach (INodeDeserializer deserializer in deserializers)
                {
                    if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out object value))
                    {
                        return(TypeConverter.ChangeType(value, expectedType));
                    }
                }
            }
            catch (YamlException)
            {
                throw;
            }
            catch (Exception innerException)
            {
                throw new YamlException(nodeEvent.Start, nodeEvent.End, "Exception during deserialization", innerException);
            }
            throw new YamlException(nodeEvent.Start, nodeEvent.End, $"No node deserializer was able to deserialize the node into type {expectedType.AssemblyQualifiedName}");
        }
        bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
        {
            if (currentType == typeof(string) || currentType == typeof(object))
            {
                var scalar = nodeEvent as Scalar;
                if (scalar != null && scalar.IsPlainImplicit)
                {
                    if (Regexes.BooleanLike.IsMatch(scalar.Value))
                    {
                        currentType = typeof(bool);
                        return(true);
                    }

                    if (Regexes.IntegerLike.IsMatch(scalar.Value))
                    {
                        currentType = typeof(int);
                        return(true);
                    }

                    if (Regexes.DoubleLike.IsMatch(scalar.Value))
                    {
                        currentType = typeof(double);
                        return(true);
                    }
                }
            }
            return(false);
        }
Пример #24
0
        public static void ResendOnWakeUp(ZWaveNode node, byte[] msg)
        {
            int minCommandLength = 8;

            if (msg.Length >= minCommandLength && !(msg[6] == (byte)CommandClass.WakeUp && msg[7] == (byte)Command.WakeUpNoMoreInfo))
            {
                byte[] command = new byte[minCommandLength];
                Array.Copy(msg, 0, command, 0, minCommandLength);
                // discard any message having same header and command (first 8 bytes = header + command class + command)
                var wakeUpResendQueue = GetResendQueueData(node);
                for (int i = wakeUpResendQueue.Count - 1; i >= 0; i--)
                {
                    byte[] queuedCommand = new byte[minCommandLength];
                    Array.Copy(wakeUpResendQueue[i], 0, queuedCommand, 0, minCommandLength);
                    if (queuedCommand.SequenceEqual(command))
                    {
                        Utility.logger.Trace("Removing old message {0}", BitConverter.ToString(wakeUpResendQueue[i]));
                        wakeUpResendQueue.RemoveAt(i);
                    }
                }
                Utility.logger.Trace("Adding message {0}", BitConverter.ToString(msg));
                wakeUpResendQueue.Add(msg);
                var wakeUpStatus = (WakeUpStatus)node.GetData("WakeUpStatus", new WakeUpStatus()).Value;
                if (!wakeUpStatus.IsSleeping)
                {
                    wakeUpStatus.IsSleeping = true;
                    var nodeEvent = new NodeEvent(node, EventParameter.WakeUpSleepingStatus, 1 /* 1 = sleeping, 0 = awake */, 0);
                    node.OnNodeUpdated(nodeEvent);
                }
            }
        }
Пример #25
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            byte      cmdType   = message[1];

            switch (cmdType)
            {
            case (byte)Command.WakeUpIntervalReport:
                if (message.Length > 4)
                {
                    uint interval = ((uint)message[2]) << 16;
                    interval |= (((uint)message[3]) << 8);
                    interval |= (uint)message[4];
                    nodeEvent = new NodeEvent(node, EventParameter.WakeUpInterval, interval, 0);
                }
                break;

            case (byte)Command.WakeUpNotification:
                // Resend queued messages while node was asleep
                var wakeUpResendQueue = GetResendQueueData(node);
                for (int m = 0; m < wakeUpResendQueue.Count; m++)
                {
                    node.SendMessage(wakeUpResendQueue[m]);
                }
                wakeUpResendQueue.Clear();
                nodeEvent = new NodeEvent(node, EventParameter.WakeUpNotify, 1, 0);
                break;
            }
            return(nodeEvent);
        }
Пример #26
0
            bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
            {
                if (currentType != typeof(object))
                {
                    return(false);
                }

                var scalar = nodeEvent as Scalar;

                if (scalar != null)
                {
                    // Expressions taken from https://github.com/aaubry/YamlDotNet/blob/feat-schemas/YamlDotNet/Core/Schemas/JsonSchema.cs

                    // Check if boolean.
                    if (Regex.IsMatch(scalar.Value, @"^(true|false)$", RegexOptions.IgnorePatternWhitespace))
                    {
                        currentType = typeof(bool);
                        return(true);
                    }

                    // Check if int or long.
                    if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* )$", RegexOptions.IgnorePatternWhitespace))
                    {
                        if (int.TryParse(scalar.Value, out var i))
                        {
                            currentType = typeof(int);
                            return(true);
                        }

                        if (long.TryParse(scalar.Value, out var l))
                        {
                            currentType = typeof(long);
                            return(true);
                        }
                    }

                    // Check if floating point number.
                    if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]* )? ( [eE] [-+]? [0-9]+ )?$", RegexOptions.IgnorePatternWhitespace))
                    {
                        // Check if the range and precision is float-like.
                        if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]{0,7} )? ( [eE] [-+]? [0-9]+ )?$", RegexOptions.IgnorePatternWhitespace) &&
                            float.TryParse(scalar.Value, out var s))
                        {
                            currentType = typeof(float);
                            return(true);
                        }

                        // If the number is in the range of a double (don't care about precision).
                        if (double.TryParse(scalar.Value, out var d))
                        {
                            currentType = typeof(double);
                            return(true);
                        }
                    }

                    // Add more cases here if needed
                }

                return(false);
            }
Пример #27
0
 public override void BroadcastEvent(NodeEvent eventValue)
 {
     if (FrameInterfaceNode != null)
     {
         FrameInterfaceNode.BroadcastEvent(eventValue);
     }
 }
    bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
    {
        if (currentType == typeof(object))
        {
            if (nodeEvent is Scalar scalar && !scalar.IsQuotedImplicit)
            {
                // Expressions taken from https://github.com/aaubry/YamlDotNet/blob/feat-schemas/YamlDotNet/Core/Schemas/JsonSchema.cs

                if (Regex.IsMatch(scalar.Value, @"^(true|false|True|False)$", RegexOptions.IgnorePatternWhitespace))
                {
                    currentType = typeof(bool);
                    return(true);
                }

                if (Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* )$", RegexOptions.IgnorePatternWhitespace))
                {
                    currentType = typeof(int);
                    return(true);
                }

                if (Regex.IsMatch(
                        scalar.Value,
                        @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]* )? ( [eE] [-+]? [0-9]+ )?$",
                        RegexOptions.IgnorePatternWhitespace))
                {
                    currentType = typeof(double);
                    return(true);
                }

                // Add more cases here if needed
            }
        }

        return(false);
    }
 bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
 {
     if (!string.IsNullOrEmpty(nodeEvent.Tag))
     {
         throw new YamlException(nodeEvent.Start, nodeEvent.End, "Encountered an unresolved tag '{" + nodeEvent.Tag + "}'");
     }
     return(false);
 }
Пример #30
0
 internal NodeEventArgs(Node node, NodeEvent eventType, string originalSourcePath, IEnumerable<ChangedData> changedData)
 {
     this.SourceNode = node;
     this.User = AccessProvider.Current.GetCurrentUser();
     this.Time = DateTime.Now;
     this.EventType = eventType;
     this.OriginalSourcePath = originalSourcePath;
     this.ChangedData = changedData;
 }
Пример #31
0
 internal NodeEventArgs(Node node, NodeEvent eventType, string originalSourcePath, IEnumerable <ChangedData> changedData)
 {
     this.SourceNode         = node;
     this.User               = AccessProvider.Current.GetCurrentUser();
     this.Time               = DateTime.Now;
     this.EventType          = eventType;
     this.OriginalSourcePath = originalSourcePath;
     this.ChangedData        = changedData;
 }
 bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
 {
     if (!string.IsNullOrEmpty(nodeEvent.Tag))
     {
         currentType = Type.GetType(nodeEvent.Tag.Substring(1), true);
         return(true);
     }
     return(false);
 }
Пример #33
0
 public bool Resolve(NodeEvent nodeEvent, ref Type currentType)
 {
     if (currentType == typeof(Dictionary <object, object>) || nodeEvent is MappingStart)
     {
         currentType = typeof(PSObject);
         return(true);
     }
     return(false);
 }
Пример #34
0
 bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
 {
     if (!string.IsNullOrEmpty(nodeEvent.Tag) && tagMappings.TryGetValue(nodeEvent.Tag, out Type value))
     {
         currentType = value;
         return(true);
     }
     return(false);
 }
Пример #35
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.SceneActivationSet)
     {
         nodeEvent = new NodeEvent(node, EventParameter.SensorGeneric, (double)message[2], 0);
     }
     return nodeEvent;
 }
Пример #36
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.DoorLockReport)
     {
         nodeEvent = new NodeEvent(node, EventParameter.DoorLockStatus, message[2], 0);
     }
     return nodeEvent;
 }
Пример #37
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.SwitchMultilevelReport || cmdType == (byte)Command.SwitchMultilevelSet) // some devices use this instead of report
     {
         int levelValue = (int)message[2];
         nodeEvent = new NodeEvent(node, EventParameter.SwitchMultilevel, (double)levelValue, 0);
     }
     return nodeEvent;
 }
Пример #38
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.BasicReport || cmdType == (byte)Command.BasicSet)
     {
         int levelValue = (int)message[2];
         nodeEvent = new NodeEvent(node, EventParameter.Basic, (double)levelValue, 0);
     }
     return nodeEvent;
 }
Пример #39
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.MeterReport)
     {
         EnergyValue energy = EnergyValue.Parse(message);
         nodeEvent = new NodeEvent(node, energy.EventType, energy.Value, 0);
     }
     return nodeEvent;
 }
Пример #40
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.AlarmReport)
     {
         var alarm = AlarmValue.Parse(message);
         nodeEvent = new NodeEvent(node, alarm.EventType, alarm.Value, 0);
     }
     return nodeEvent;
 }
Пример #41
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (message.Length > 0 && cmdType == (byte)Command.BatteryReport) // Battery Report
     {
         int batteryLevel = message[2];
         nodeEvent = new NodeEvent(node, EventParameter.Battery, batteryLevel, 0);
     }
     return nodeEvent;
 }
 public NodeEventEditor(CharEvents _chev, Object[] obj, NodeEvent ne)
 {
     InitializeComponent();
     chev = _chev;
     comboBox1.Items.AddRange(obj);
     comboBox2.Items.AddRange(obj);
     comboBox1.SelectedIndex =ne.parentNode.index;
     comboBox2.SelectedIndex = ne.associatedNode.index;
     textBox2.Text =ne.neededEvent;
     textBox1.Text = ne.description;
 }
Пример #43
0
        public byte[] GeneratePrivateNetworkKey()
        {
            privateNetworkKey = new byte[16];
            Random rnd = new Random();
            rnd.NextBytes(privateNetworkKey);

            // notify the controller that the privateNetworkKey was generated so that it can save it
            NodeEvent keyGenEvent = new NodeEvent(parentNode, EventParameter.SecurityGeneratedKey, 0, 0);
            parentNode.OnNodeUpdated(keyGenEvent);

            return privateNetworkKey;
        }
Пример #44
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.UserCodeReport)
     {
         var reportedUserCode = UserCodeValue.Parse(message);
         var userCode = GetUserCodeData(node);
         userCode.TagCode = reportedUserCode.TagCode;
         userCode.UserId = reportedUserCode.UserId;
         userCode.UserIdStatus = reportedUserCode.UserIdStatus;
         nodeEvent = new NodeEvent(node, EventParameter.UserCode, reportedUserCode, 0);
     }
     return nodeEvent;
 }
Пример #45
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;

            //byte cmdClass = message[0];
            byte cmdType = message[1];
            byte instanceCmdClass = message[2];

            switch (cmdType)
            {
            case (byte)Command.MultiInstanceEncapsulated:
                nodeEvent = HandleMultiInstanceEncapReport(node, message);
                break;

            //case (byte) Command.MultiInstanceReport:
            case (byte) Command.MultiChannelEncapsulated:
                nodeEvent = HandleMultiChannelEncapReport(node, message);
                //if (nodeEvent != null)
                //{
                //    nodeEvent.Instance = (int) message[2];
                //}
                break;

            case (byte) Command.MultiInstanceCountReport:
                byte instanceCount = message[3];
                switch (instanceCmdClass)
                {
                case (byte) CommandClass.SwitchBinary:
                    nodeEvent = new NodeEvent(node, EventParameter.MultiinstanceSwitchBinaryCount, instanceCount, 0);
                    break;
                case (byte) CommandClass.SwitchMultilevel:
                    nodeEvent = new NodeEvent(node, EventParameter.MultiinstanceSwitchMultilevelCount, instanceCount, 0);
                    break;
                case (byte) CommandClass.SensorBinary:
                    nodeEvent = new NodeEvent(node, EventParameter.MultiinstanceSensorBinaryCount, instanceCount, 0);
                    break;
                case (byte) CommandClass.SensorMultilevel:
                    nodeEvent = new NodeEvent(node, EventParameter.MultiinstanceSensorMultilevelCount, instanceCount, 0);
                    break;
                }
                break;

            }

            return nodeEvent;
        }
Пример #46
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     if (cmdType == (byte)Command.SensorMultilevelReport)
     {
         var sensor = SensorValue.Parse(message);
         if (sensor.Parameter == ZWaveSensorParameter.Unknown)
         {
             byte key = message[2];
             nodeEvent = new NodeEvent(node, EventParameter.SensorGeneric, sensor.Value, 0);
             Utility.DebugLog(DebugMessageType.Warning, "Unhandled sensor parameter type: " + key);
         }
         else
         {
             nodeEvent = new NodeEvent(node, sensor.EventType, sensor.Value, 0);
         }
     }
     return nodeEvent;
 }
Пример #47
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            var type = (Command)message[1];

            if (type == Command.VersionReport)
            {
                var nodeVersion = new NodeVersion {
                    LibraryType = message[2],
                    ProtocolVersion = message[3],
                    ProtocolSubVersion = message[4],
                    ApplicationVersion = message[5],
                    ApplicationSubVersion = message[6]
                };
                node.Version = nodeVersion;
                nodeEvent = new NodeEvent(node, EventParameter.VersionCommandClass, nodeVersion, 0);
            }

            if (type == Command.VersionCommandClassReport)
            {
                var cmdClass = (CommandClass)message[2];
                var value = new VersionValue(cmdClass, message[3]);
                // Update node CC data
                if (cmdClass != CommandClass.NotSet)
                {
                    var nodeCc = node.GetCommandClass(cmdClass);
                    if (nodeCc != null)
                        nodeCc.Version = value.Version;
                    // Set the VersionCommandClass event
                    nodeEvent = new NodeEvent(node, EventParameter.VersionCommandClass, value, 0);
                }
                else
                {
                    Utility.logger.Warn("Command Class {0} ({1}) not supported yet", message[3], message[3].ToString("X2"));
                }
            }

            return nodeEvent;
        }
Пример #48
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     switch (cmdType)
     {
     case (byte)Command.WakeUpIntervalReport:
         if (message.Length > 4)
         {
             uint interval = ((uint)message[2]) << 16;
             interval |= (((uint)message[3]) << 8);
             interval |= (uint)message[4];
             nodeEvent = new NodeEvent(node, EventParameter.WakeUpInterval, interval, 0);
         }
         break;
     case (byte)Command.WakeUpNotification:
         WakeUpNode(node);
         nodeEvent = new NodeEvent(node, EventParameter.WakeUpNotify, 1, 0);
         break;
     }
     return nodeEvent;
 }
Пример #49
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            byte cmdType = message[1];
            
            // we want to get in to that we can handle NO Associations
            if (message.Length > 4 && cmdType == (byte)Command.AssociationReport)
            {
                byte groupId = message[2];
                byte associationMax = message[3];
                byte associationCount = message[4]; // it is always zero ?!?
                string associationNodes = "";
                if (message.Length > 4)
                {
                    for (int a = 5; a < message.Length; a++)
                    {
                        associationNodes += message[a] + ",";
                    }
                }
                associationNodes = associationNodes.TrimEnd(',');

                // We don't want to send empty response since it will be handled as "timeout"
                // so setting it to "None"
                if (associationNodes.Length == 0)
                {
                    associationNodes = "None";
                }
                //
                var associationResponse = new AssociationResponse() {
                    Max = associationMax,
                    Count = associationCount,
                    NodeList = associationNodes,
                    GroupId = groupId
                };
                nodeEvent = new NodeEvent(node, EventParameter.Association, associationResponse, 0);
            }

            return nodeEvent;
        }
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;

            if (message.Length > 7)
            {
                byte[] manufacturerId = new byte[2] { message[2], message[3] };
                byte[] typeId = new byte[2] { message[4], message[5] };
                byte[] productId = new byte[2] { message[6], message[7] };

                var manufacturerSpecs = new ManufacturerSpecificInfo() {
                    TypeId = BitConverter.ToString(typeId).Replace("-", ""),
                    ProductId = BitConverter.ToString(productId).Replace("-", ""),
                    ManufacturerId = BitConverter.ToString(manufacturerId).Replace("-", "")
                };
                node.ManufacturerSpecific.ManufacturerId = manufacturerSpecs.ManufacturerId;
                node.ManufacturerSpecific.TypeId = manufacturerSpecs.TypeId;
                node.ManufacturerSpecific.ProductId = manufacturerSpecs.ProductId;
                nodeEvent = new NodeEvent(node, EventParameter.ManufacturerSpecific, manufacturerSpecs, 0);
            }

            return nodeEvent;
        }
Пример #51
0
		public NodeOperationEventArgs(Node sourceNode, Node targetNode, NodeEvent eventType)
            : base(sourceNode, eventType)
		{
			_targetNode = targetNode;
		}
Пример #52
0
 public NodeUpdatedEventArgs(byte nodeId, NodeEvent evt)
 {
     this.NodeId = nodeId;
     this.Event = evt;
 }
Пример #53
0
 public NodeEvent GetEvent(ZWaveNode node, byte[] message)
 {
     NodeEvent nodeEvent = null;
     byte cmdType = message[1];
     switch (cmdType)
     {
     case (byte)Command.WakeUpIntervalReport:
         if (message.Length > 4)
         {
             uint interval = ((uint)message[2]) << 16;
             interval |= (((uint)message[3]) << 8);
             interval |= (uint)message[4];
             nodeEvent = new NodeEvent(node, EventParameter.WakeUpInterval, interval, 0);
         }
         break;
     case (byte)Command.WakeUpNotification:
         // Resend queued messages while node was asleep
         var wakeUpResendQueue = GetResendQueueData(node);
         for (int m = 0; m < wakeUpResendQueue.Count; m++)
         {
             node.SendMessage(wakeUpResendQueue[m]);
         }
         wakeUpResendQueue.Clear();
         nodeEvent = new NodeEvent(node, EventParameter.WakeUpNotify, 1, 0);
         break;
     }
     return nodeEvent;
 }
Пример #54
0
 /// Last Modified: 9/18/10
 /// <summary>
 /// Allows for safe access of the OnNodeEvent callback method.
 /// </summary>
 /// -----------------------------------------------------
 /// PRECONDITIONS: Refer to the following arguments:
 /// -----------------------------------------------------
 /// Parameters:
 /// <param name="nodeEvent">
 /// The 
 /// </param>
 /// <param name="sEntityId">
 /// The name or id of the entity generating the event.
 /// </param>
 /// <param name="sData">
 /// A string that describes the data associated with the event.
 /// </param>
 /// -----------------------------------------------------
 /// POSTCONDITIONS: NA -- No postconditions exist.
 /// -----------------------------------------------------
 /// Return Value:
 protected void OnNodeEvent(NodeEvent nodeEvent, string sEntityId, string sData)
 {
     if (m_dOnNodeEvent != null) m_dOnNodeEvent(nodeEvent, sEntityId, sData);
 }
Пример #55
0
		/**
		@node If it's not null, it probably means we're on the top node and just
				got called from public Parse method
		@parent If it's null, it means we're on the top node
		@skip don't do a read, we're already on the next node and ready to process it

		If this method returns null, it means it has reached the end of the current
		xml subtree (the end element of the parent node)
		**/
		static XamlNode Parse (XmlReader reader, XamlNode parent, XamlNode node, 
								NodeEvent evstart, NodeEvent evend, 
								AttributeEvent evattr, bool skip = false)
		{
			if (!skip)
				reader.Read ();

			if (parent == null) {
				while (reader.NodeType != XmlNodeType.Element)
					if (!reader.Read ())
						return null;
			} else {
				do {
					while (reader.NodeType != XmlNodeType.Element &&
						   reader.NodeType != XmlNodeType.EndElement &&
						   reader.NodeType != XmlNodeType.Text) {
						if (!reader.Read ())
							return null;
					}
					if (reader.NodeType == XmlNodeType.Element &&
						parent.top.IgnorablePrefixes.Contains (reader.Prefix))
						reader.Skip ();
					else
						break;
				} while (true);
			}

			if (reader.NodeType == XmlNodeType.EndElement)
				return null;

			if (node == null)
				node = new XamlNode ();

			node.Parsed = false;
			node.Ignore = false;

			if (!node.Initialized) {
				node.parent = parent;

				if (parent != null)
					node.top = parent.top;
				else {
					node.ignorablePrefixes = new List<string> ();
					node.top = node;
				}

				node.type = reader.NodeType;
				node.namespaceURI = reader.NamespaceURI;
				node.prefix = reader.Prefix;
				node.name = reader.Name;
				node.localName = reader.LocalName;
				node.IsEmptyElement = reader.IsEmptyElement;
				node.HasValue = reader.HasValue;
				node.XmlSpace = reader.XmlSpace;
				node.LineNumber = -1;
				node.LinePosition = -1;
				node.IsNsXaml = node.NamespaceURI == XamlUri;
				node.IsNsClr = node.NamespaceURI.StartsWith ("clr-namespace");
				if (parent == null)
					node.DefaultXmlns = reader.GetAttribute ("xmlns");

				if (node.IsNsClr) {
					int end = node.NamespaceURI.IndexOf (';');
					if (end == -1)
						end = node.NamespaceURI.Length;
					node.ClrNamespace = node.NamespaceURI.Substring (14, end - 14);
				}

				if (node.IsNsClr && node.NamespaceURI.IndexOf (";assembly=") + 10 < node.NamespaceURI.Length)
					node.Assembly = node.NamespaceURI.Substring (node.NamespaceURI.IndexOf (";assembly=") + 10);

				if (node.HasValue)
					node.val = reader.Value;


				IXmlLineInfo linfo = reader as IXmlLineInfo;
				if (linfo != null) {
					node.LineNumber = linfo.LineNumber;
					node.LinePosition = linfo.LinePosition;
				}

				if (reader.HasAttributes) {
					string ig = reader.GetAttribute ("Ignorable", IgnorableUri);
					if (ig != null) {
						foreach (string s in ig.Split (' '))
							node.IgnorablePrefixes.Add (s);
					}

					reader.MoveToFirstAttribute ();

					int count = 0;
					do {
						// this filters out ignorable attributes
						if (node.IgnorablePrefixes.Contains (reader.Prefix))
							continue;

						XamlAttribute ai = new XamlAttribute (reader) {
							Index = count++,
						};

						// an x: or equivalent attribute
						ai.IsNsXaml = !ai.IsMapping && ai.NamespaceURI == XamlUri;
						// an mc: or equivalent attribute (this attribute defines the list of ignorable prefixes)
						ai.IsNsIgnorable = !ai.IsMapping && (ai.NamespaceURI == IgnorableUri || ai.Prefix == "mc");
						// an xmlns:my='clr-namespace...' attribute
						ai.IsNsClr = !ai.IsMapping && ai.NamespaceURI.StartsWith ("clr-namespace");
						if (ai.IsNsXaml && ai.LocalName == "Class")
							node.Class = ai.Value;

						if (ai.IsMapping) {
							if (node.top != node)
								ai.Index = node.top.Attributes.Count;
							node.top.Attributes [reader.Name] = ai;
						} else {
							if (ai.IsNsXaml) {
								if (ai.LocalName == "Key")
									node.X_Key = ai.Value;
								else if (ai.LocalName == "Name")
									node.X_Name = ai.Value;
							}
							node.Attributes [reader.Name] = ai;
						}
					} while (reader.MoveToNextAttribute ());

					reader.MoveToElement ();
				}
			
				node.Initialized = true;
			}

			if (evstart != null && (node.NodeType == XmlNodeType.Element || node.NodeType == XmlNodeType.Text))
				evstart (node);

			if (evattr != null) {
				foreach (XamlAttribute ai in node.Attributes.Values.Where (x => !x.IsNsIgnorable && !x.IsMapping))
					evattr (node, ai);
			}

			if (node.Ignore) {
				node.outerXml = reader.ReadOuterXml ();
				cache [node.outerXml] = node;
				if (evend != null && node.NodeType == XmlNodeType.Element)
					evend (node);
				return node;				
			}

			if (node.NodeType == XmlNodeType.Element && !node.IsEmptyElement) {
				XamlNode child = null;
				do {
					child = Parse (reader, node, null, evstart, evend, evattr, child != null ? child.Ignore : false);
					if (child != null) {
						child.Parsed = !child.Ignore;
						node.Children.Add (child);
					}
				} while (child != null);
			}

			if (evend != null && node.NodeType == XmlNodeType.Element)
				evend (node);

			return node;
		}
Пример #56
0
		public void Parse (NodeEvent evstart, NodeEvent evend, AttributeEvent evattr)
		{
#if LOGGING
			Log ("Looping: Ignored? {0} Parsed? {1} {2}", this.Ignore, this.Parsed, outerXml);
#endif
			Ignore = false;

			if (!Initialized) {
				XmlReader reader = XmlReader.Create (new StringReader (outerXml));
				Parse (reader, parent, this, evstart, evend, evattr);
				Parsed = !Ignore;
				return;
			}

			if (evstart != null && (NodeType == XmlNodeType.Element || NodeType == XmlNodeType.Text))
				evstart (this);
			
			if (evattr != null) {
				foreach (XamlAttribute ai in Attributes.Values.Where (x => !x.IsNsIgnorable && !x.IsMapping))
					evattr (this, ai);
			}

			if (NodeType == XmlNodeType.Element && !IsEmptyElement && !Ignore) {
				if (!Parsed) {
					XmlReader reader = XmlReader.Create (new StringReader (outerXml));
					reader.Read ();
					XamlNode child = null;
					do {
						child = Parse (reader, this, null, evstart, evend, evattr, child != null ? child.Ignore : false);
						if (child != null) {
							child.Parsed = !child.Ignore;
							Children.Add (child);
						}
					} while (child != null);
					Parsed = true;
				} else {
					foreach (XamlNode child in Children) {
						child.Parse (evstart, evend, evattr);
					}
				}
			}

			if (evend != null && NodeType == XmlNodeType.Element)
				evend (this);
			
			Ignore = false;
		}
Пример #57
0
		public static XamlNode Parse (string xml, NodeEvent evstart, NodeEvent evend, AttributeEvent evattr)
		{
			XamlNode root;
			bool exists = cache.TryGetValue (xml, out root);
			if (!exists)
				root = new XamlNode () { outerXml = xml };
			root.Parse (evstart, evend, evattr);
			if (!exists)
				cache[xml] = root;
			return root;
		}
Пример #58
0
 public NodeOperationEventArgs(Node sourceNode, Node targetNode, NodeEvent eventType, string originalSourcePath)
     : base(sourceNode, eventType, originalSourcePath)
 {
     _targetNode = targetNode;
 }
Пример #59
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            byte cmdType = message[1];
            byte[] decryptedMessage;
            NodeEvent nodeEvent = null;

            int startOffset = 1;
            switch (cmdType)
            {
            case (byte)SecurityCommand.SupportedReport:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_SUPPORTED_REPORT for node: " + node.Id);
                /* this is a list of CommandClasses that should be Encrypted.
                 * and it might contain new command classes that were not present in the NodeInfoFrame
                 * so we have to run through, mark existing Command Classes as SetSecured (so SendMsg in the Driver
                 * class will route the unecrypted messages to our SendMsg) and for New Command
                 * Classes, create them, and of course, also do a SetSecured on them.
                 *
                 * This means we must do a SecurityCmd_SupportedGet request ASAP so we dont have
                 * Command Classes created after the Discovery Phase is completed!
                 */
                byte[] securedClasses = new byte[message.Length - 3];
                Array.Copy(message, 3, securedClasses, 0, message.Length - 3);
                nodeEvent = new NodeEvent(node, EventParameter.SecurityNodeInformationFrame, securedClasses, 0);
                break;

            case (byte)SecurityCommand.SchemeReport:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_SCHEME_REPORT for node: " + node.Id + ", " + (startOffset + 1));
                int schemes = message[startOffset + 1];
                SecurityData nodeSecurityData = GetSecurityData(node);
                if (nodeSecurityData.SchemeAgreed)
                {
                    break;
                }
                else if (schemes == (byte)SecurityScheme.SchemeZero)
                {
                    SetNetworkKey(node);
                    nodeSecurityData.SchemeAgreed = true;
                }
                else
                {
                    Utility.DebugLog(DebugMessageType.Information, "   No common security scheme.  The device will continue as an unsecured node.");
                }
                break;

            case (byte)SecurityCommand.NonceGet:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_NONCE_GET for node: " + node.Id);

                /* the Device wants to send us a Encrypted Packet, and thus requesting for our latest NONCE */
                SendNonceReport(node);
                break;

            case (byte)SecurityCommand.MessageEncap:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_MESSAGE_ENCAP for node: " + node.Id);

                /* We recieved a Encrypted single packet from the Device. Decrypt it. */
                decryptedMessage = DecryptMessage(node, message, startOffset);
                if (decryptedMessage != null)
                    nodeEvent = new NodeEvent(node, EventParameter.SecurityDecriptedMessage, decryptedMessage, 0);
                break;

            case (byte)SecurityCommand.NonceReport:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_NONCE_REPORT for node: " + node.Id);

                /* we recieved a NONCE from a device, so assume that there is something in a queue to send out */
                ProcessNonceReport(node, message, startOffset);
                break;

            case (byte)SecurityCommand.MessageEncapNonceGet:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_MESSAGE_ENCAP_NONCE_GET for node: " + node.Id);

                /* we recieved a encrypted packet from the device, and the device is also asking us to send a
                     * new NONCE to it, hence there must be multiple packets.*/
                decryptedMessage = DecryptMessage(node, message, startOffset);
                if (decryptedMessage != null)
                    nodeEvent = new NodeEvent(node, EventParameter.SecurityDecriptedMessage, decryptedMessage, 0);
                /* Regardless of the success/failure of Decrypting, send a new NONCE */
                SendNonceReport(node);
                break;

            case (byte)SecurityCommand.NetworkKeySet:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_NETWORK_KEY_SET for node: " + node.Id + ", " + (startOffset + 1));

                /* we shouldn't get a NetworkKeySet from a node if we are the controller
                     * as we send it out to the Devices
                    */
                break;

            case (byte)SecurityCommand.NetworkKeyVerify:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_NETWORK_KEY_VERIFY for node: " + node.Id + ", " + (startOffset + 1));

                /*
                     * if we can decrypt this packet, then we are assured that our NetworkKeySet is successfull
                     * and thus should set the Flag referenced in SecurityCmd_SchemeReport
                    */
                GetSupported(node);
                break;

            case (byte)SecurityCommand.SchemeInherit:
                Utility.DebugLog(DebugMessageType.Information, "Received COMMAND_SCHEME_INHERIT for node: " + node.Id);
                /* only used in a Controller Replication Type enviroment. */
                break;

            }

            return nodeEvent;
        }
Пример #60
0
        public NodeEvent GetEvent(ZWaveNode node, byte[] message)
        {
            NodeEvent nodeEvent = null;
            byte cmdType = message[1];
            if (cmdType == (byte)Command.SensorBinaryReport)
            {
                var cc = node.GetCommandClass(GetClassId());
                int version = (cc != null ? cc.Version : 0);

                if (version == 1 || message.Length <= 3)
                {
                    nodeEvent = new NodeEvent(node, EventParameter.SensorGeneric, message[2], 0);
                }
                else
                {
                    byte tmp = message[3];
                    ZWaveSensorBinaryParameter sensorType = ZWaveSensorBinaryParameter.General;
                    EventParameter eventType;

                    if (Enum.IsDefined(typeof(ZWaveSensorBinaryParameter), tmp))
                    {
                        sensorType = (ZWaveSensorBinaryParameter)tmp;
                    }

                    switch (sensorType)
                    {
                    case ZWaveSensorBinaryParameter.Smoke:
                        eventType = EventParameter.AlarmSmoke;
                        break;
                    case ZWaveSensorBinaryParameter.CarbonMonoxide:
                        eventType = EventParameter.AlarmCarbonMonoxide;
                        break;
                    case ZWaveSensorBinaryParameter.CarbonDioxide:
                        eventType = EventParameter.AlarmCarbonDioxide;
                        break;
                    case ZWaveSensorBinaryParameter.Heat:
                        eventType = EventParameter.AlarmHeat;
                        break;
                    case ZWaveSensorBinaryParameter.Water:
                        eventType = EventParameter.AlarmFlood;
                        break;
                    case ZWaveSensorBinaryParameter.Tamper:
                        eventType = EventParameter.AlarmTampered;
                        break;
                    case ZWaveSensorBinaryParameter.DoorWindow:
                        eventType = EventParameter.AlarmDoorWindow;
                        break;
                    case ZWaveSensorBinaryParameter.Motion:
                        eventType = EventParameter.SensorMotion;
                        break;
                    case ZWaveSensorBinaryParameter.Freeze:
                    case ZWaveSensorBinaryParameter.Auxiliary:
                    case ZWaveSensorBinaryParameter.Tilt:
                    case ZWaveSensorBinaryParameter.General:
                    default:
                        // Catch-all for the undefined types above.
                        eventType = EventParameter.SensorGeneric;
                        break;
                    }

                    nodeEvent = new NodeEvent(node, eventType, message[2], 0);
                }
            }
            return nodeEvent;
        }