Exemplo n.º 1
0
 /// <summary>
 /// Serializes a ZigBeeKey <seealso cref="ZigBeeKey"/>
 /// </summary>
 /// <param name="key">The ZigBeeKey <seealso cref="ZigBeeKey"/></param>
 protected void SerializeZigBeeKey(ZigBeeKey key)
 {
     for (int cnt = 0; cnt <= 15; cnt++)
     {
         _buffer[_length++] = key.Key[cnt];
     }
 }
Exemplo n.º 2
0
        public ZigBeeStatus SetZigBeeNetworkKey(ZigBeeKey key)
        {
            byte[] keyData = new byte[16];
            int    cnt     = 0;

            foreach (byte keyVal in key.Key)
            {
                keyData[cnt++] = keyVal;
            }
            return(_networkManager.SetNetworkKey(keyData) ? ZigBeeStatus.SUCCESS : ZigBeeStatus.FAILURE);
        }
Exemplo n.º 3
0
        /**
         * This function updates an existing entry in the key table or adds a new one. It first searches the table for an
         * existing entry that matches the passed EUI64 address. If no entry is found, it searches for the first free entry.
         * If successful, it updates the key data and resets the associated incoming frame counter. If it fails to find an
         * existing entry and no free one exists, it returns a failure.
         *
         * @param address the {@link IeeeAddress}
         * @param key the {@link ZigBeeKey}
         * @param linkKey This indicates whether the key is a Link or a Master Key
         * @return the returned {@link EmberStatus} of the request
         */
        public EmberStatus AddOrUpdateKeyTableEntry(IeeeAddress address, ZigBeeKey key, bool linkKey)
        {
            EmberKeyData keyData = new EmberKeyData();

            keyData.SetContents(Array.ConvertAll(key.Key, c => (int)c));

            EzspAddOrUpdateKeyTableEntryRequest request = new EzspAddOrUpdateKeyTableEntryRequest();

            request.SetAddress(address);
            request.SetKeyData(keyData);
            request.SetLinkKey(linkKey);
            IEzspTransaction transaction = _protocolHandler.SendEzspTransaction(new EzspSingleResponseTransaction(request, typeof(EzspAddOrUpdateKeyTableEntryResponse)));
            EzspAddOrUpdateKeyTableEntryResponse response = (EzspAddOrUpdateKeyTableEntryResponse)transaction.GetResponse();

            return(response.GetStatus());
        }
        /**
         * Utility function to join an existing network as a Router
         *
         * @param networkParameters the required {@link EmberNetworkParameters}
         * @param linkKey the {@link ZigBeeKey} with the initial link key. This cannot be set to all 00 or all FF.
         */
        public void JoinNetwork(EmberNetworkParameters networkParameters, ZigBeeKey linkKey)
        {
            Log.Debug("Joining Ember network with configuration {Parameters}", networkParameters);

            // Leave the current network so we can initialise a new network
            EmberNcp ncp = new EmberNcp(_protocolHandler);

            if (CheckNetworkJoined())
            {
                ncp.LeaveNetwork();
            }

            ncp.ClearKeyTable();

            // Initialise security - no network key as we'll get that from the coordinator
            SetSecurityState(linkKey, null);

            DoJoinNetwork(networkParameters);
        }
Exemplo n.º 5
0
        /**
         * Adds a transient link key to the NCP
         *
         * @param partner the {@link IeeeAddress} to set
         * @param transientKey the {@link ZigBeeKey} to set
         * @return the {@link EmberStatus} of the response
         */
        public EmberStatus AddTransientLinkKey(IeeeAddress partner, ZigBeeKey transientKey)
        {
            EmberKeyData emberKey = new EmberKeyData();

            emberKey.SetContents(Array.ConvertAll(transientKey.Key, c => (int)c));
            EzspAddTransientLinkKeyRequest request = new EzspAddTransientLinkKeyRequest();

            request.SetPartner(partner);
            request.SetTransientKey(emberKey);
            IEzspTransaction transaction             = _protocolHandler.SendEzspTransaction(new EzspSingleResponseTransaction(request, typeof(EzspAddTransientLinkKeyResponse)));
            EzspAddTransientLinkKeyResponse response = (EzspAddTransientLinkKeyResponse)transaction.GetResponse();

            _lastStatus = response.GetStatus();
            Log.Debug(response.ToString());
            if (response.GetStatus() != EmberStatus.EMBER_SUCCESS)
            {
                Log.Debug("Error setting transient key: {}", response);
            }

            return(response.GetStatus());
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            _nodes = new List <ZigBeeNode>();

            // Configure Serilog
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .CreateLogger();
            try
            {
                TransportConfig transportOptions = new TransportConfig();

                Console.Write("Please enter your COM Port: ");

                var port = Console.ReadLine();

                ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort(port);

                IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort);

                ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle);

                ZigBeeDiscoveryExtension discoveryExtension = new ZigBeeDiscoveryExtension();
                discoveryExtension.setUpdatePeriod(60);
                networkManager.AddExtension(discoveryExtension);

                // Initialise the network
                networkManager.Initialize();

                networkManager.AddCommandListener(new ConsoleCommandListener());
                networkManager.AddNetworkNodeListener(new ConsoleNetworkNodeListener());

                Log.Logger.Information("PAN ID: {PanId}", networkManager.ZigBeePanId);
                Log.Logger.Information("Extended PAN ID: {ExtendenPanId}", networkManager.ZigBeeExtendedPanId);
                Log.Logger.Information("Channel: {Channel}", networkManager.ZigbeeChannel);

                byte channel = 11;

                byte pan = 1;

                ExtendedPanId extendedPan = new ExtendedPanId();

                ZigBeeKey nwkKey = ZigBeeKey.CreateRandom();

                ZigBeeKey linkKey = new ZigBeeKey(new byte[] { 0x5A, 0x69, 0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61,
                                                               0x6E, 0x63, 0x65, 0x30, 0x39 });


                Console.WriteLine("*** Resetting network");
                Console.WriteLine("  * Channel                = " + channel);
                Console.WriteLine("  * PAN ID                 = " + pan);
                Console.WriteLine("  * Extended PAN ID        = " + extendedPan);
                Console.WriteLine("  * Link Key               = " + linkKey);

                networkManager.SetZigBeeChannel((ZigBeeChannel)channel);
                networkManager.SetZigBeePanId(pan);
                networkManager.SetZigBeeExtendedPanId(extendedPan);
                networkManager.SetZigBeeNetworkKey(nwkKey);
                networkManager.SetZigBeeLinkKey(linkKey);

                transportOptions.AddOption(TransportConfigOption.TRUST_CENTRE_LINK_KEY, new ZigBeeKey(new byte[] { 0x5A, 0x69,
                                                                                                                   0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61, 0x6E, 0x63, 0x65, 0x30, 0x39 }));

                dongle.UpdateTransportConfig(transportOptions);

                networkManager.AddSupportedCluster(0x06);

                ZigBeeStatus startupSucceded = networkManager.Startup(false);

                if (startupSucceded == ZigBeeStatus.SUCCESS)
                {
                    Log.Logger.Information("ZigBee console starting up ... [OK]");
                }
                else
                {
                    Log.Logger.Information("ZigBee console starting up ... [FAIL]");
                    return;
                }

                ZigBeeNode coord = networkManager.GetNode(0);

                coord.PermitJoin(true);

                Console.WriteLine("Joining enabled...");

                string cmd = Console.ReadLine();

                while (cmd != "exit")
                {
                    if (cmd == "toggle")
                    {
                        Console.WriteLine("Destination Address: ");
                        string nwkAddr = Console.ReadLine();

                        if (ushort.TryParse(nwkAddr, out ushort addr))
                        {
                            var node = networkManager.GetNode(addr);

                            if (node != null)
                            {
                                ZigBeeEndpoint ep = new ZigBeeEndpoint(node, 0);
                                node.AddEndpoint(ep);

                                ZclOnOffCluster onOff = new ZclOnOffCluster(node.GetEndpoint(0));

                                onOff.ToggleCommand();
                            }
                        }
                    }

                    cmd = Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// The Gp Pairing
        ///
        /// The GP Pairing command is generated by the sink to manage pairing information. The
        /// GP Pairing command is typically sent using network-wide broadcast. If the
        /// CommunicationMode sub-field is set to 0b11, GP Pairing command may be sent in
        /// unicast to the selected proxy.
        ///
        /// <param name="options" <see cref="int"> Options</ param >
        /// <param name="gpdSrcId" <see cref="uint"> Gpd Src ID</ param >
        /// <param name="gpdIeee" <see cref="IeeeAddress"> Gpd IEEE</ param >
        /// <param name="endpoint" <see cref="byte"> Endpoint</ param >
        /// <param name="sinkIeeeAddress" <see cref="IeeeAddress"> Sink IEEE Address</ param >
        /// <param name="sinkNwkAddress" <see cref="ushort"> Sink NWK Address</ param >
        /// <param name="sinkGroupId" <see cref="ushort"> Sink Group ID</ param >
        /// <param name="deviceId" <see cref="byte"> Device ID</ param >
        /// <param name="gpdSecurityFrameCounter" <see cref="uint"> Gpd Security Frame Counter</ param >
        /// <param name="gpdKey" <see cref="ZigBeeKey"> Gpd Key</ param >
        /// <param name="assignedAlias" <see cref="ushort"> Assigned Alias</ param >
        /// <param name="forwardingRadius" <see cref="byte"> Forwarding Radius</ param >
        /// <returns> the command result Task </returns>
        /// </summary>
        public Task <CommandResult> GpPairing(int options, uint gpdSrcId, IeeeAddress gpdIeee, byte endpoint, IeeeAddress sinkIeeeAddress, ushort sinkNwkAddress, ushort sinkGroupId, byte deviceId, uint gpdSecurityFrameCounter, ZigBeeKey gpdKey, ushort assignedAlias, byte forwardingRadius)
        {
            GpPairing command = new GpPairing();

            // Set the fields
            command.Options                 = options;
            command.GpdSrcId                = gpdSrcId;
            command.GpdIeee                 = gpdIeee;
            command.Endpoint                = endpoint;
            command.SinkIeeeAddress         = sinkIeeeAddress;
            command.SinkNwkAddress          = sinkNwkAddress;
            command.SinkGroupId             = sinkGroupId;
            command.DeviceId                = deviceId;
            command.GpdSecurityFrameCounter = gpdSecurityFrameCounter;
            command.GpdKey           = gpdKey;
            command.AssignedAlias    = assignedAlias;
            command.ForwardingRadius = forwardingRadius;

            return(Send(command));
        }
Exemplo n.º 8
0
        /// <summary>
        /// The Gp Pairing Configuration
        ///
        /// The command is generated to configure the Sink Table of a sink, to
        /// create/update/replace/remove a pairing to a GPD and/or trigger the sending of GP
        /// Pairing command.
        /// In the current version of the specification, a device shall only send GP Pairing
        /// Configuration command with the Number of paired endpoints field set to 0xfe, if the
        /// CommunicationMode is equal to Pre-Commissioned Groupcast.
        ///
        /// <param name="actions" <see cref="byte"> Actions</ param >
        /// <param name="options" <see cref="ushort"> Options</ param >
        /// <param name="gpdSrcId" <see cref="uint"> Gpd Src ID</ param >
        /// <param name="gpdIeee" <see cref="IeeeAddress"> Gpd IEEE</ param >
        /// <param name="endpoint" <see cref="byte"> Endpoint</ param >
        /// <param name="deviceId" <see cref="byte"> Device ID</ param >
        /// <param name="groupListCount" <see cref="byte"> Group List Count</ param >
        /// <param name="groupList" <see cref="GpPairingConfigurationGroupList"> Group List</ param >
        /// <param name="gpdAssignedAlias" <see cref="ushort"> Gpd Assigned Alias</ param >
        /// <param name="forwardingRadius" <see cref="byte"> Forwarding Radius</ param >
        /// <param name="securityOptions" <see cref="byte"> Security Options</ param >
        /// <param name="gpdSecurityFrameCounter" <see cref="uint"> Gpd Security Frame Counter</ param >
        /// <param name="gpdSecurityKey" <see cref="ZigBeeKey"> Gpd Security Key</ param >
        /// <param name="numberOfPairedEndpoints" <see cref="byte"> Number Of Paired Endpoints</ param >
        /// <param name="pairedEndpoints" <see cref="byte"> Paired Endpoints</ param >
        /// <param name="applicationInformation" <see cref="byte"> Application Information</ param >
        /// <param name="manufacturerId" <see cref="ushort"> Manufacturer ID</ param >
        /// <param name="modeId" <see cref="ushort"> Mode ID</ param >
        /// <param name="numberOfGpdCommands" <see cref="byte"> Number Of Gpd Commands</ param >
        /// <param name="gpdCommandIdList" <see cref="byte"> Gpd Command ID List</ param >
        /// <param name="clusterIdListCount" <see cref="byte"> Cluster ID List Count</ param >
        /// <param name="clusterListServer" <see cref="ushort"> Cluster List Server</ param >
        /// <param name="clusterListClient" <see cref="ushort"> Cluster List Client</ param >
        /// <returns> the command result Task </returns>
        /// </summary>
        public Task <CommandResult> GpPairingConfiguration(byte actions, ushort options, uint gpdSrcId, IeeeAddress gpdIeee, byte endpoint, byte deviceId, byte groupListCount, GpPairingConfigurationGroupList groupList, ushort gpdAssignedAlias, byte forwardingRadius, byte securityOptions, uint gpdSecurityFrameCounter, ZigBeeKey gpdSecurityKey, byte numberOfPairedEndpoints, byte pairedEndpoints, byte applicationInformation, ushort manufacturerId, ushort modeId, byte numberOfGpdCommands, byte gpdCommandIdList, byte clusterIdListCount, ushort clusterListServer, ushort clusterListClient)
        {
            GpPairingConfiguration command = new GpPairingConfiguration();

            // Set the fields
            command.Actions                 = actions;
            command.Options                 = options;
            command.GpdSrcId                = gpdSrcId;
            command.GpdIeee                 = gpdIeee;
            command.Endpoint                = endpoint;
            command.DeviceId                = deviceId;
            command.GroupListCount          = groupListCount;
            command.GroupList               = groupList;
            command.GpdAssignedAlias        = gpdAssignedAlias;
            command.ForwardingRadius        = forwardingRadius;
            command.SecurityOptions         = securityOptions;
            command.GpdSecurityFrameCounter = gpdSecurityFrameCounter;
            command.GpdSecurityKey          = gpdSecurityKey;
            command.NumberOfPairedEndpoints = numberOfPairedEndpoints;
            command.PairedEndpoints         = pairedEndpoints;
            command.ApplicationInformation  = applicationInformation;
            command.ManufacturerId          = manufacturerId;
            command.ModeId = modeId;
            command.NumberOfGpdCommands = numberOfGpdCommands;
            command.GpdCommandIdList    = gpdCommandIdList;
            command.ClusterIdListCount  = clusterIdListCount;
            command.ClusterListServer   = clusterListServer;
            command.ClusterListClient   = clusterListClient;

            return(Send(command));
        }
Exemplo n.º 9
0
 public ZigBeeStatus SetZigBeeNetworkKey(ZigBeeKey key)
 {
     _conbeeInterface.NetworkKey = key.Key;
     return(ZigBeeStatus.SUCCESS);
 }
Exemplo n.º 10
0
 public ZigBeeStatus SetZigBeeNetworkKey(ZigBeeKey key)
 {
     NetworkKey = key;
     return(ZigBeeStatus.SUCCESS);
 }
Exemplo n.º 11
0
        static async Task Main(string[] args)
        {
            // Configure Serilog
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .CreateLogger();

            bool         showHelp     = false;
            ZigBeeDongle zigBeeDongle = ZigBeeDongle.TiCc2531;
            string       port         = "";
            int          baudrate     = 115200;
            string       flow         = "";
            FlowControl  flowControl  = FlowControl.FLOWCONTROL_OUT_NONE;
            bool         resetNetwork = false;
            string       store        = "json";
            string       database     = "devices";
            string       connection   = "";
            string       collection   = "";

            OptionSet options = new OptionSet
            {
                { "h|help", "show this message and exit", h => showHelp = h != null },
                { "zbd|zigbeeDongle=", "the zigbee dongle to use. 0 = TiCc2531 | 1 = DigiXBee | 2 = Conbee | 3 = Ember ", (ZigBeeDongle zbd) => zigBeeDongle = zbd },
                { "p|port=", "the COM port to use", p => port = p },
                { "b|baud=", $"the port baud rate to use. default is {baudrate}", b => int.TryParse(b, out baudrate) },
                { "f|flow=", $"the flow control (none | hardware | software)", f => flow = f },
                { "r|reset", $"Reset the Zigbee network", r => resetNetwork = r != null },
                { "s|store=", $"The store for network state", s => store = s },
                { "c|connection=", $"The mongoDb connection string", c => connection = c },
                { "d|database=", $"The mongoDb database or json directory", d => database = d },
                { "mc|mongoCollection=", $"The mongoDb collection", mc => collection = mc },
            };

            try
            {
                IList <string> extraArgs = options.Parse(args);
                foreach (string extraArg in extraArgs)
                {
                    Console.WriteLine($"Error: Unknown option: {extraArg}");
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return;
                }

                if (string.IsNullOrEmpty(port))
                {
                    Console.Write("Enter COM Port: ");
                    port = Console.ReadLine();
                }

                if (string.IsNullOrEmpty(flow))
                {
                    // Default the flow control based on the dongle
                    switch (zigBeeDongle)
                    {
                    case ZigBeeDongle.Ember:
                        flowControl = FlowControl.FLOWCONTROL_OUT_XONOFF;
                        break;

                    default:
                        flowControl = FlowControl.FLOWCONTROL_OUT_NONE;
                        break;
                    }
                }
                else
                {
                    switch (flow)
                    {
                    case "software":
                        flowControl = FlowControl.FLOWCONTROL_OUT_XONOFF;
                        break;

                    case "hardware":
                        flowControl = FlowControl.FLOWCONTROL_OUT_RTSCTS;
                        break;

                    case "none":
                        flowControl = FlowControl.FLOWCONTROL_OUT_NONE;
                        break;

                    default:
                        Console.WriteLine($"Unknown flow control option used: {flow}");
                        break;
                    }
                }

                ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort(port, baudrate, flowControl);

                IZigBeeTransportTransmit dongle;
                switch (zigBeeDongle)
                {
                case ZigBeeDongle.TiCc2531:
                {
                    dongle = new ZigBeeDongleTiCc2531(zigbeePort);
                }
                break;

                case ZigBeeDongle.DigiXbee:
                {
                    dongle = new ZigBeeDongleXBee(zigbeePort);
                }
                break;

                case ZigBeeDongle.ConBee:
                {
                    dongle = new ZigbeeDongleConBee(zigbeePort);
                }
                break;

                case ZigBeeDongle.Ember:
                {
                    dongle = new ZigBeeDongleEzsp(zigbeePort);
                    ((ZigBeeDongleEzsp)dongle).SetPollRate(0);
                }
                break;

                default:
                {
                    dongle = new ZigBeeDongleTiCc2531(zigbeePort);
                }
                break;
                }

                ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle);

                if (store == "json")
                {
                    JsonNetworkDataStore dataStore = new JsonNetworkDataStore(database);
                    networkManager.SetNetworkDataStore(dataStore);
                }
                else if (store == "mongo")
                {
                    MongoDbDatabaseSettings settings = new MongoDbDatabaseSettings()
                    {
                        ConnectionString    = connection,
                        DatabaseName        = database,
                        NodesCollectionName = collection
                    };

                    MongoDbDataStore mongoStore = new MongoDbDataStore(settings);
                    networkManager.SetNetworkDataStore(mongoStore);
                }

                ZigBeeDiscoveryExtension discoveryExtension = new ZigBeeDiscoveryExtension();
                discoveryExtension.SetUpdatePeriod(60);
                networkManager.AddExtension(discoveryExtension);

                // Initialise the network
                networkManager.Initialize();

                /* Network (de)serialization */
                //networkManager.AddCommandListener(new ZigBeeNetworkDiscoverer(networkManager));
                //networkManager.AddCommandListener(new ZigBeeNodeServiceDiscoverer(networkManager));

                networkManager.AddCommandListener(new ZigBeeTransaction(networkManager));
                networkManager.AddCommandListener(new ConsoleCommandListener());

                networkManager.AddNetworkNodeListener(new ConsoleNetworkNodeListener());

                networkManager.AddSupportedCluster(ZclOnOffCluster.CLUSTER_ID);
                networkManager.AddSupportedCluster(ZclColorControlCluster.CLUSTER_ID);

                networkManager.AddExtension(new ZigBeeBasicServerExtension());

                if (zigBeeDongle == ZigBeeDongle.TiCc2531)
                {
                    ((ZigBeeDongleTiCc2531)dongle).SetLedMode(1, false); // green led
                    ((ZigBeeDongleTiCc2531)dongle).SetLedMode(2, false); // red led
                }
                Console.WriteLine($"PAN ID           = {networkManager.ZigBeePanId}");
                Console.WriteLine($"Extended PAN ID  = {networkManager.ZigBeeExtendedPanId}");
                Console.WriteLine($"Channel          = {networkManager.ZigbeeChannel}");
                Console.WriteLine($"Network Key      = {networkManager.ZigBeeNetworkKey}");
                Console.WriteLine($"Link Key         = {networkManager.ZigBeeLinkKey}");

                if (resetNetwork)
                {
                    //TODO: make the network parameters configurable
                    ushort        panId         = 1;
                    ExtendedPanId extendedPanId = new ExtendedPanId();
                    ZigBeeChannel channel       = ZigBeeChannel.CHANNEL_11;
                    ZigBeeKey     networkKey    = ZigBeeKey.CreateRandom();
                    ZigBeeKey     linkKey       = new ZigBeeKey(new byte[] { 0x5A, 0x69, 0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61, 0x6E, 0x63, 0x65, 0x30, 0x39 });

                    Console.WriteLine($"*** Resetting network");
                    Console.WriteLine($"  * PAN ID           = {panId}");
                    Console.WriteLine($"  * Extended PAN ID  = {extendedPanId}");
                    Console.WriteLine($"  * Channel          = {channel}");
                    Console.WriteLine($"  * Network Key      = {networkKey}");
                    Console.WriteLine($"  * Link Key         = {linkKey}");

                    networkManager.SetZigBeeChannel(channel);
                    networkManager.SetZigBeePanId(panId);
                    networkManager.SetZigBeeExtendedPanId(extendedPanId);
                    networkManager.SetZigBeeNetworkKey(networkKey);
                    networkManager.SetZigBeeLinkKey(linkKey);
                }

                ZigBeeStatus startupSucceded = networkManager.Startup(resetNetwork);

                if (startupSucceded == ZigBeeStatus.SUCCESS)
                {
                    Log.Logger.Information("ZigBee console starting up ... [OK]");
                }
                else
                {
                    Log.Logger.Information("ZigBee console starting up ... [FAIL]");
                    Log.Logger.Information("Press any key to exit...");
                    Console.ReadKey();
                    return;
                }

                ZigBeeNode coord = networkManager.GetNode(0);

                Console.WriteLine("Joining enabled...");

                string cmd = string.Empty;

                while (cmd != "exit")
                {
                    if (cmd == "join")
                    {
                        coord.PermitJoin(true);
                    }
                    else if (cmd == "unjoin")
                    {
                        coord.PermitJoin(false);
                    }
                    else if (cmd == "endpoints")
                    {
                        var tmp = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.Write("Destination Address: ");
                        Console.ForegroundColor = tmp;
                        string nwkAddr = Console.ReadLine();

                        if (ushort.TryParse(nwkAddr, out ushort addr))
                        {
                            var node = networkManager.Nodes.FirstOrDefault(n => n.NetworkAddress == addr);

                            if (node != null)
                            {
                                Console.WriteLine(new string('-', 20));

                                foreach (var endpoint in node.GetEndpoints())
                                {
                                    Console.ForegroundColor = ConsoleColor.Blue;
                                    Console.WriteLine("Input Cluster:" + Environment.NewLine);
                                    Console.ForegroundColor = tmp;

                                    foreach (var inputClusterId in endpoint.GetInputClusterIds())
                                    {
                                        var cluster     = endpoint.GetInputCluster(inputClusterId);
                                        var clusterName = cluster.GetClusterName();
                                        Console.WriteLine($"{clusterName}");
                                    }
                                }

                                Console.WriteLine();

                                foreach (var endpoint in node.GetEndpoints())
                                {
                                    Console.ForegroundColor = ConsoleColor.Blue;
                                    Console.WriteLine("Output Cluster:" + Environment.NewLine);
                                    Console.ForegroundColor = tmp;

                                    foreach (var outputClusterIds in endpoint.GetOutputClusterIds())
                                    {
                                        var cluster     = endpoint.GetOutputCluster(outputClusterIds);
                                        var clusterName = cluster.GetClusterName();
                                        Console.WriteLine($"{clusterName}");
                                    }
                                }

                                Console.WriteLine(new string('-', 20));
                            }
                        }
                    }
                    else if (cmd == "add")
                    {
                        var tmp = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.Write("Destination Address: ");
                        Console.ForegroundColor = tmp;
                        string nwkAddr = Console.ReadLine();

                        if (ushort.TryParse(nwkAddr, out ushort addr))
                        {
                            Console.Write("IeeeAddress: ");
                            Console.ForegroundColor = tmp;
                            string ieeeAddr = Console.ReadLine();

                            networkManager.UpdateNode(new ZigBeeNode()
                            {
                                NetworkAddress = addr, IeeeAddress = new IeeeAddress(ieeeAddr)
                            });
                        }
                    }
                    else if (!string.IsNullOrEmpty(cmd))
                    {
                        var tmp = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.Write("Destination Address: ");
                        Console.ForegroundColor = tmp;
                        string nwkAddr = Console.ReadLine();

                        if (ushort.TryParse(nwkAddr, out ushort addr))
                        {
                            var node = networkManager.GetNode(addr);

                            if (node != null)
                            {
                                ZigBeeEndpointAddress endpointAddress = null;
                                var endpoint = node.GetEndpoints().FirstOrDefault();

                                if (endpoint != null)
                                {
                                    endpointAddress = endpoint.GetEndpointAddress();
                                }

                                if (endpointAddress == null)
                                {
                                    Console.WriteLine("No endpoint found");

                                    continue;
                                }

                                try
                                {
                                    if (cmd == "leave")
                                    {
                                        await networkManager.Leave(node.NetworkAddress, node.IeeeAddress);
                                    }
                                    else if (cmd == "toggle")
                                    {
                                        await networkManager.Send(endpointAddress, new ToggleCommand());
                                    }
                                    else if (cmd == "level")
                                    {
                                        Console.WriteLine("Level between 0 and 255: ");
                                        string level = Console.ReadLine();

                                        Console.WriteLine("time between 0 and 65535: ");
                                        string time = Console.ReadLine();

                                        var command = new MoveToLevelWithOnOffCommand()
                                        {
                                            Level          = byte.Parse(level),
                                            TransitionTime = ushort.Parse(time)
                                        };

                                        await networkManager.Send(endpointAddress, command);
                                    }
                                    else if (cmd == "move")
                                    {
                                        await networkManager.Send(endpointAddress, new MoveCommand()
                                        {
                                            MoveMode = 1, Rate = 100
                                        });
                                    }
                                    else if (cmd == "on")
                                    {
                                        await networkManager.Send(endpointAddress, new OnCommand());
                                    }
                                    else if (cmd == "off")
                                    {
                                        await networkManager.Send(endpointAddress, new OffCommand());
                                    }
                                    else if (cmd == "effect")
                                    {
                                        await networkManager.Send(endpointAddress, new OffCommand());

                                        bool state = false;
                                        for (int i = 0; i < 10; i++)
                                        {
                                            if (state)
                                            {
                                                await networkManager.Send(endpointAddress, new OffCommand());
                                            }
                                            else
                                            {
                                                await networkManager.Send(endpointAddress, new OnCommand());
                                            }

                                            state = !state;
                                            await Task.Delay(1000);
                                        }
                                    }
                                    else if (cmd == "stress")
                                    {
                                        await networkManager.Send(endpointAddress, new OffCommand());

                                        bool state = false;
                                        for (int i = 0; i < 100; i++)
                                        {
                                            if (state)
                                            {
                                                await networkManager.Send(endpointAddress, new OffCommand());
                                            }
                                            else
                                            {
                                                await networkManager.Send(endpointAddress, new OnCommand());
                                            }

                                            state = !state;

                                            await Task.Delay(1);
                                        }
                                    }
                                    else if (cmd == "desc")
                                    {
                                        NodeDescriptorRequest nodeDescriptorRequest = new NodeDescriptorRequest()
                                        {
                                            DestinationAddress = endpointAddress,
                                            NwkAddrOfInterest  = addr
                                        };

                                        networkManager.SendTransaction(nodeDescriptorRequest);
                                    }
                                    else if (cmd == "color")
                                    {
                                        Console.WriteLine("Red between 0 and 255: ");
                                        string r = Console.ReadLine();

                                        Console.WriteLine("Green between 0 and 255: ");
                                        string g = Console.ReadLine();

                                        Console.WriteLine("Blue between 0 and 255: ");
                                        string b = Console.ReadLine();

                                        if (int.TryParse(r, out int _r) && int.TryParse(g, out int _g) && int.TryParse(b, out int _b))
                                        {
                                            CieColor xyY = ColorConverter.RgbToCie(_r, _g, _b);

                                            MoveToColorCommand command = new MoveToColorCommand()
                                            {
                                                ColorX         = xyY.X,
                                                ColorY         = xyY.Y,
                                                TransitionTime = 10
                                            };

                                            await networkManager.Send(endpointAddress, command);
                                        }
                                    }
                                    else if (cmd == "hue")
                                    {
                                        Console.WriteLine("Red between 0 and 255: ");
                                        string hue = Console.ReadLine();

                                        if (byte.TryParse(hue, out byte _hue))
                                        {
                                            MoveToHueCommand command = new MoveToHueCommand()
                                            {
                                                Hue            = _hue,
                                                Direction      = 0,
                                                TransitionTime = 10
                                            };

                                            await networkManager.Send(endpointAddress, command);
                                        }
                                    }
                                    else if (cmd == "read")
                                    {
                                        var cluster = endpoint.GetInputCluster(ZclBasicCluster.CLUSTER_ID);
                                        if (cluster != null)
                                        {
                                            string manufacturerName = (string)(await cluster.ReadAttributeValue(ZclBasicCluster.ATTR_MANUFACTURERNAME));
                                            string model            = (string)(await cluster.ReadAttributeValue(ZclBasicCluster.ATTR_MODELIDENTIFIER));

                                            Console.WriteLine($"Manufacturer Name = {manufacturerName}");
                                            Console.WriteLine($"Model identifier = {model}");
                                        }
                                    }
                                    else if (cmd == "discover attributes")
                                    {
                                        foreach (int clusterId in endpoint.GetInputClusterIds())
                                        {
                                            ZclCluster cluster = endpoint.GetInputCluster(clusterId);
                                            if (!await cluster.DiscoverAttributes(true))
                                            {
                                                Console.WriteLine("Error while discovering attributes for cluster {0}", cluster.GetClusterName());
                                            }
                                        }
                                    }
                                    else if (cmd == "update binding table")
                                    {
                                        ZigBeeStatus statusCode = await node.UpdateBindingTable();

                                        if (statusCode != ZigBeeStatus.SUCCESS)
                                        {
                                            Console.WriteLine("Error while reading binding table: " + statusCode);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Logger.Error(ex, "Error while executing cmd {Command}", cmd);
                                }
                            }
                            else
                            {
                                Console.WriteLine($"Node {addr} not found");
                            }
                        }
                    }

                    await Task.Delay(100);

                    Console.WriteLine(Environment.NewLine + networkManager.Nodes.Count + " node(s)" + Environment.NewLine);

                    for (int i = 0; i < networkManager.Nodes.Count; i++)
                    {
                        var node = networkManager.Nodes[i];
                        Console.WriteLine($"{i}. {node.LogicalType}: {node.NetworkAddress}");
                    }

                    Console.WriteLine();
                    var currentForeGroundColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.Write("cmd> ");
                    Console.ForegroundColor = currentForeGroundColor;
                    cmd = Console.ReadLine();
                }
                networkManager.Shutdown();
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                ShowHelp(options);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }
Exemplo n.º 12
0
 /// <summary>
 /// The networkKey to set as </summary>
 /// <seecref="ZigBeeKey"
 ///>
 ///  </see>
 public void SetNetworkKey(ZigBeeKey networkKey)
 {
     _networkKey = networkKey;
 }
Exemplo n.º 13
0
 /// <summary>
 /// The linkKey to set as </summary>
 /// <seecref="ZigBeeKey"
 ///>
 ///  </see>
 public void SetLinkKey(ZigBeeKey linkKey)
 {
     _linkKey = linkKey;
 }
        /**
         * This utility function uses emberStartScan, emberStopScan, emberScanCompleteHandler, emberEnergyScanResultHandler,
         * and emberNetworkFoundHandler to discover other networks or determine the background noise level. It then uses
         * emberFormNetwork to create a new network with a unique PAN-ID on a channel with low background noise.
         * <p>
         * Setting the PAN-ID or Extended PAN-ID to 0 will set these values to a random value.
         * <p>
         * If channel is set to 0, the quietest channel will be used.
         *
         * @param networkParameters the required {@link EmberNetworkParameters}
         * @param linkKey the {@link ZigBeeKey} with the link key. This can not be set to all 00 or all FF.
         * @param networkKey the {@link ZigBeeKey} with the network key. This can not be set to all 00 or all FF.
         */
        public void FormNetwork(EmberNetworkParameters networkParameters, ZigBeeKey linkKey, ZigBeeKey networkKey)
        {
            if (networkParameters.GetExtendedPanId() == null)
            {
                networkParameters.SetExtendedPanId(new ExtendedPanId());
            }

            Log.Debug("Initialising Ember network with configuration {NetworkParameters}", networkParameters);

            EmberNcp ncp = new EmberNcp(_protocolHandler);

            // Leave the current network so we can initialise a new network
            if (CheckNetworkJoined())
            {
                ncp.LeaveNetwork();
            }

            ncp.ClearKeyTable();

            // Perform an energy scan to find a clear channel
            int?quietestChannel = DoEnergyScan(ncp, _scanDuration);

            Log.Debug("Energy scan reports quietest channel is {QuietestChannel}", quietestChannel);

            // Check if any current networks were found and avoid those channels, PAN ID and especially Extended PAN ID
            ncp.DoActiveScan(ZigBeeChannelMask.CHANNEL_MASK_2GHZ, _scanDuration);

            // Read the current network parameters
            GetNetworkParameters();

            // Create a random PAN ID and Extended PAN ID
            if (networkParameters.GetPanId() == 0 || networkParameters.GetExtendedPanId().Equals(new ExtendedPanId()))
            {
                Random random = new Random();
                int    panId  = random.Next(65535);
                networkParameters.SetPanId(panId);
                Log.Debug("Created random PAN ID: {PanId}", panId);

                byte[] extendedPanIdBytes = new byte[8];
                random.NextBytes(extendedPanIdBytes);
                ExtendedPanId extendedPanId = new ExtendedPanId(extendedPanIdBytes);
                networkParameters.SetExtendedPanId(extendedPanId);
                Log.Debug("Created random Extended PAN ID: {ExtendedPanId}", extendedPanId.ToString());
            }

            if (networkParameters.GetRadioChannel() == 0 && quietestChannel.HasValue)
            {
                networkParameters.SetRadioChannel(quietestChannel.Value);
            }

            // If the channel set is empty, use the single channel defined above
            if (networkParameters.GetChannels() == 0)
            {
                networkParameters.SetChannels(1 << networkParameters.GetRadioChannel());
            }

            // Initialise security
            SetSecurityState(linkKey, networkKey);

            // And now form the network
            DoFormNetwork(networkParameters);
        }
        /**
         * Sets the initial security state
         *
         * @param linkKey the initial {@link ZigBeeKey}
         * @param networkKey the initial {@link ZigBeeKey}
         * @return true if the security state was set successfully
         */
        private bool SetSecurityState(ZigBeeKey linkKey, ZigBeeKey networkKey)
        {
            EzspSetInitialSecurityStateRequest securityState = new EzspSetInitialSecurityStateRequest();
            EmberInitialSecurityState          state         = new EmberInitialSecurityState();

            state.AddBitmask(EmberInitialSecurityBitmask.EMBER_TRUST_CENTER_GLOBAL_LINK_KEY);

            EmberKeyData networkKeyData = new EmberKeyData();

            if (networkKey != null)
            {
                networkKeyData.SetContents(Array.ConvertAll(networkKey.Key, c => (int)c));
                state.AddBitmask(EmberInitialSecurityBitmask.EMBER_HAVE_NETWORK_KEY);
                if (networkKey.SequenceNumber.HasValue)
                {
                    state.SetNetworkKeySequenceNumber(networkKey.SequenceNumber.Value);
                }
            }
            state.SetNetworkKey(networkKeyData);

            EmberKeyData linkKeyData = new EmberKeyData();

            if (linkKey != null)
            {
                linkKeyData.SetContents(Array.ConvertAll(linkKey.Key, c => (int)c));
                state.AddBitmask(EmberInitialSecurityBitmask.EMBER_HAVE_PRECONFIGURED_KEY);
                state.AddBitmask(EmberInitialSecurityBitmask.EMBER_REQUIRE_ENCRYPTED_KEY);
            }
            state.SetPreconfiguredKey(linkKeyData);

            state.SetPreconfiguredTrustCenterEui64(new IeeeAddress());

            securityState.SetState(state);
            EzspSingleResponseTransaction transaction = new EzspSingleResponseTransaction(securityState, typeof(EzspSetInitialSecurityStateResponse));

            _protocolHandler.SendEzspTransaction(transaction);
            EzspSetInitialSecurityStateResponse securityStateResponse = (EzspSetInitialSecurityStateResponse)transaction.GetResponse();

            Log.Debug(securityStateResponse.ToString());
            if (securityStateResponse.GetStatus() != EmberStatus.EMBER_SUCCESS)
            {
                Log.Debug("Error during retrieval of network parameters: {Response}", securityStateResponse);
                return(false);
            }

            EmberNcp ncp = new EmberNcp(_protocolHandler);

            if (networkKey != null && networkKey.OutgoingFrameCounter.HasValue)
            {
                EzspSerializer serializer = new EzspSerializer();
                serializer.SerializeUInt32(networkKey.OutgoingFrameCounter.Value);
                if (ncp.SetValue(EzspValueId.EZSP_VALUE_NWK_FRAME_COUNTER, serializer.GetPayload()) != EzspStatus.EZSP_SUCCESS)
                {
                    return(false);
                }
            }
            if (linkKey != null && linkKey.OutgoingFrameCounter.HasValue)
            {
                EzspSerializer serializer = new EzspSerializer();
                serializer.SerializeUInt32(linkKey.OutgoingFrameCounter.Value);
                if (ncp.SetValue(EzspValueId.EZSP_VALUE_APS_FRAME_COUNTER, serializer.GetPayload()) != EzspStatus.EZSP_SUCCESS)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 16
0
        public void AppendZigBeeType(object data, DataType type)
        {
            if (data == null)
            {
                throw new ArgumentException("You can not append null data to a stream");
            }

            switch (type)
            {
            case DataType.BOOLEAN:
                _buffer[_length++] = (bool)data ? (byte)0x01 : (byte)0x00;
                break;

            case DataType.NWK_ADDRESS:
            case DataType.BITMAP_16_BIT:
            case DataType.SIGNED_16_BIT_INTEGER:
            case DataType.UNSIGNED_16_BIT_INTEGER:
            case DataType.ENUMERATION_16_BIT:
            case DataType.CLUSTERID:
                ushort shortValue = Convert.ToUInt16(data);
                _buffer[_length++] = (byte)(shortValue & 0xFF);
                _buffer[_length++] = (byte)((shortValue >> 8) & 0xFF);
                break;

            case DataType.ENDPOINT:
            case DataType.DATA_8_BIT:
            case DataType.BITMAP_8_BIT:
            case DataType.SIGNED_8_BIT_INTEGER:
            case DataType.UNSIGNED_8_BIT_INTEGER:
            case DataType.ENUMERATION_8_BIT:
                byte byteValue = Convert.ToByte(data);
                _buffer[_length++] = (byte)(byteValue & 0xFF);
                break;

            case DataType.EXTENDED_PANID:
                byte[] panId = BitConverter.GetBytes(((ExtendedPanId)data).Value);
                _buffer[_length++] = panId[0];
                _buffer[_length++] = panId[1];
                _buffer[_length++] = panId[2];
                _buffer[_length++] = panId[3];
                _buffer[_length++] = panId[4];
                _buffer[_length++] = panId[5];
                _buffer[_length++] = panId[6];
                _buffer[_length++] = panId[7];
                break;

            case DataType.IEEE_ADDRESS:
                byte[] address = BitConverter.GetBytes(((IeeeAddress)data).Value);
                _buffer[_length++] = address[0];
                _buffer[_length++] = address[1];
                _buffer[_length++] = address[2];
                _buffer[_length++] = address[3];
                _buffer[_length++] = address[4];
                _buffer[_length++] = address[5];
                _buffer[_length++] = address[6];
                _buffer[_length++] = address[7];
                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:
                break;

            case DataType.N_X_UNSIGNED_16_BIT_INTEGER:
                List <ushort> intArray16 = (List <ushort>)data;
                _buffer[_length++] = (byte)intArray16.Count;
                foreach (ushort value in intArray16)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                    _buffer[_length++] = (byte)((value >> 8) & 0xFF);
                }
                break;

            case DataType.N_X_UNSIGNED_8_BIT_INTEGER:
                List <byte> intArrayNX8 = (List <byte>)data;
                _buffer[_length++] = (byte)intArrayNX8.Count;
                foreach (byte value in intArrayNX8)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                }
                break;

            case DataType.UNSIGNED_8_BIT_INTEGER_ARRAY:
                byte[] intArrayN8 = (byte[])data;
                foreach (byte value in intArrayN8)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                }
                break;

            case DataType.X_UNSIGNED_8_BIT_INTEGER:
                List <byte> intArrayX8 = (List <byte>)data;
                foreach (byte value in intArrayX8)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                }
                break;

            case DataType.N_X_ATTRIBUTE_IDENTIFIER:
                List <ushort> intArrayX16 = (List <ushort>)data;
                foreach (ushort value in intArrayX16)
                {
                    _buffer[_length++] = (byte)(value & 0xFF);
                    _buffer[_length++] = (byte)((value >> 8) & 0xFF);
                }
                break;

            case DataType.N_X_WRITE_ATTRIBUTE_RECORD:
                break;

            case DataType.N_X_WRITE_ATTRIBUTE_STATUS_RECORD:
                break;

            case DataType.OCTET_STRING:
                ByteArray array = (ByteArray)data;
                _buffer[_length++] = ((byte)(array.Size() & 0xFF));
                foreach (byte arrayByte in array.Get())
                {
                    _buffer[_length++] = arrayByte;
                }
                break;

            case DataType.CHARACTER_STRING:
                string str = (string)data;
                _buffer[_length++] = ((byte)(str.Length & 0xFF));
                foreach (byte strByte in Encoding.ASCII.GetBytes((str)))
                {
                    _buffer[_length++] = strByte;
                }
                break;

            case DataType.LONG_OCTET_STRING:
                ByteArray longArray = (ByteArray)data;
                _buffer[_length++] = ((byte)(longArray.Size() & 0xFF));
                _buffer[_length++] = (byte)((longArray.Size() >> 8) & 0xFF);
                foreach (byte arrayByte in longArray.Get())
                {
                    _buffer[_length++] = arrayByte;
                }
                break;

            case DataType.SECURITY_KEY:
                ZigBeeKey securityKey = (ZigBeeKey)data;
                foreach (byte arrayByte in securityKey.Key)
                {
                    _buffer[_length++] = arrayByte;
                }
                break;

            case DataType.BITMAP_24_BIT:
            case DataType.SIGNED_24_BIT_INTEGER:
            case DataType.UNSIGNED_24_BIT_INTEGER:
                uint uint24Value = (uint)data;
                _buffer[_length++] = (byte)(uint24Value & 0xFF);
                _buffer[_length++] = (byte)((uint24Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((uint24Value >> 16) & 0xFF);
                break;

            case DataType.ENUMERATION_32_BIT:
            case DataType.SIGNED_32_BIT_INTEGER:
                int intValue = (int)data;
                _buffer[_length++] = (byte)(intValue & 0xFF);
                _buffer[_length++] = (byte)((intValue >> 8) & 0xFF);
                _buffer[_length++] = (byte)((intValue >> 16) & 0xFF);
                _buffer[_length++] = (byte)((intValue >> 24) & 0xFF);
                break;

            case DataType.BITMAP_32_BIT:
            case DataType.UNSIGNED_32_BIT_INTEGER:
                uint uint32Value = (uint)data;
                _buffer[_length++] = (byte)(uint32Value & 0xFF);
                _buffer[_length++] = (byte)((uint32Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((uint32Value >> 16) & 0xFF);
                _buffer[_length++] = (byte)((uint32Value >> 24) & 0xFF);
                break;

            case DataType.UNSIGNED_48_BIT_INTEGER:
                ulong uint48Value = (ulong)data;
                _buffer[_length++] = (byte)(uint48Value & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 16) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 24) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 32) & 0xFF);
                _buffer[_length++] = (byte)((uint48Value >> 40) & 0xFF);
                break;

            case DataType.UTCTIME:
                break;

            case DataType.ZDO_STATUS:
                _buffer[_length++] = (byte)((ZdoStatus)data);
                break;

            case DataType.ZCL_STATUS:
                _buffer[_length++] = (byte)((ZclStatus)data);
                break;

            case DataType.BYTE_ARRAY:
                ByteArray byteArray = (ByteArray)data;
                _buffer[_length++] = (byte)(byteArray.Size());
                foreach (byte valByte in byteArray.Get())
                {
                    _buffer[_length++] = (byte)(valByte & 0xff);
                }
                break;

            case DataType.ZIGBEE_DATA_TYPE:
                _buffer[_length++] = (byte)((ZclDataType)data).Id;
                break;

            case DataType.FLOAT_32_BIT:
                float  float32      = (float)data;
                byte[] floatBytes   = BitConverter.GetBytes(float32);
                int    float32Value = BitConverter.ToInt32(floatBytes, 0);
                _buffer[_length++] = (byte)(float32Value & 0xFF);
                _buffer[_length++] = (byte)((float32Value >> 8) & 0xFF);
                _buffer[_length++] = (byte)((float32Value >> 16) & 0xFF);
                _buffer[_length++] = (byte)((float32Value >> 24) & 0xFF);
                break;

            default:
                throw new ArgumentException("No writer defined in " + this.GetType().Name
                                            + " for " + type.ToString() + " (" + (byte)type + ")");
            }
        }
Exemplo n.º 17
0
 public ZigBeeStatus SetTcLinkKey(ZigBeeKey key)
 {
     return(ZigBeeStatus.FAILURE);
 }
Exemplo n.º 18
0
        /// <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.RAW_OCTET:
                int rawSize = payload.Length - index;
                value[0] = new ByteArray(payload, index, index + rawSize);
                index   += rawSize;
                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.LONG_OCTET_STRING:
                int longOctetSize = (short)(payload[index++] + (payload[index++] << 8));
                value[0] = new ByteArray(payload, index, index + longOctetSize);
                index   += longOctetSize;
                break;

            case DataType.SECURITY_KEY:
                byte[] keyBytes = new byte[16];
                Array.Copy(payload, index, keyBytes, 0, 16);
                value[0] = new ZigBeeKey(keyBytes);
                index   += 16;
                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:
                try
                {
                    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;
                } catch (Exception ex)
                {
                    string sTest = ex.Message;
                }
                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.BITMAP_24_BIT:
            case DataType.UNSIGNED_24_BIT_INTEGER:
                value[0] = (uint)(payload[index++] + (payload[index++] << 8) | (payload[index++] << 16));
                break;

            case DataType.SIGNED_24_BIT_INTEGER:
                value[0] = payload[index++] + (payload[index++] << 8) | (payload[index++] << 16);
                break;

            case DataType.BITMAP_32_BIT:
            case DataType.UNSIGNED_32_BIT_INTEGER:
            case DataType.ENUMERATION_32_BIT:
                value[0] = (uint)(payload[index++] + (payload[index++] << 8) | (payload[index++] << 16)
                                  + (payload[index++] << 24));
                break;

            case DataType.SIGNED_32_BIT_INTEGER:
                value[0] = payload[index++] + (payload[index++] << 8) | (payload[index++] << 16)
                           + (payload[index++] << 24);
                break;

            case DataType.UNSIGNED_40_BIT_INTEGER:
                value[0] = (payload[index++]) + ((long)(payload[index++]) << 8) | ((long)(payload[index++]) << 16)
                           + ((long)(payload[index++]) << 24) | ((long)(payload[index++]) << 32);
                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;

            case DataType.FLOAT_32_BIT:
                int    val      = payload[index++] + (payload[index++] << 8) + (payload[index++] << 16) + (payload[index++] << 24);
                byte[] valBytes = BitConverter.GetBytes(val);
                value[0] = BitConverter.ToSingle(valBytes, 0);
                break;

            default:
                throw new ArgumentException("No reader defined in " + this.GetType().Name + " for " + type.ToString() + " (" + (byte)type + ")");
            }
            return((T)value[0]);
        }
Exemplo n.º 19
0
 public ZigBeeStatus SetTcLinkKey(ZigBeeKey key)
 {
     LinkKey = key;
     return(ZigBeeStatus.SUCCESS);
 }
Exemplo n.º 20
0
 public ZigBeeStatus SetTcLinkKey(ZigBeeKey key)
 {
     throw new NotImplementedException();
 }