### Initialize and Start ZigBee Network Source: https://context7.com/mr-markus/zigbeenet/llms.txt Demonstrates the complete setup and initialization of the ZigBeeNetworkManager, including configuring logging, selecting a dongle, setting up persistence, adding extensions, registering clusters, and starting the network. Ensure the correct COM port and baud rate are used for your dongle. ```csharp using ZigBeeNet; using ZigBeeNet.Hardware.TI.CC2531; using ZigBeeNet.Tranport.SerialPort; using ZigBeeNet.Transport; using ZigBeeNet.App.Discovery; using ZigBeeNet.DataStore.Json; using Microsoft.Extensions.Logging; // 1. Configure logging (Microsoft.Extensions.Logging) ILoggerFactory factory = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug) .AddSimpleConsole(c => { c.SingleLine = true; c.TimestampFormat = "[HH:mm:ss] "; })); ZigBeeNet.Util.LogManager.SetFactory(factory); // 2. Create serial port and dongle ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort("COM4", 115200, FlowControl.FLOWCONTROL_OUT_NONE); IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort); // 3. Create the network manager ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle); // 4. Attach a JSON data store for persistence networkManager.SetNetworkDataStore(new JsonNetworkDataStore("devices")); // 5. Add the discovery extension (mesh update every 60 seconds) ZigBeeDiscoveryExtension discovery = new ZigBeeDiscoveryExtension(); discovery.SetUpdatePeriod(60); networkManager.AddExtension(discovery); // 6. Register supported client clusters networkManager.AddSupportedClientCluster(ZclOnOffCluster.CLUSTER_ID); // 0x0006 networkManager.AddSupportedClientCluster(ZclColorControlCluster.CLUSTER_ID); // 0x0300 // 7. Initialize (configure transport) then start ZigBeeStatus initStatus = networkManager.Initialize(); // Optionally configure network before startup: // networkManager.SetZigBeeChannel(ZigBeeChannel.CHANNEL_11); // networkManager.SetZigBeePanId(1); // networkManager.SetZigBeeNetworkKey(ZigBeeKey.CreateRandom()); ZigBeeStatus startStatus = networkManager.Startup(resetNetwork: false); if (startStatus == ZigBeeStatus.SUCCESS) Console.WriteLine("Network online."); else Console.WriteLine($"Startup failed: {startStatus}"); // 8. Graceful shutdown networkManager.Shutdown(); ``` -------------------------------- ### Implement Custom IZigBeeNetworkDataStore in C# Source: https://context7.com/mr-markus/zigbeenet/llms.txt This example shows how to create an in-memory implementation of IZigBeeNetworkDataStore. This can be useful for testing or simple applications where persistent storage is not required. ```csharp using ZigBeeNet; using ZigBeeNet.Database; public class InMemoryDataStore : IZigBeeNetworkDataStore { private readonly Dictionary _store = new(); public ISet ReadNetworkNodes() => new HashSet(_store.Keys); public ZigBeeNodeDao ReadNode(IeeeAddress address) => _store.TryGetValue(address, out var node) ? node : null; public void WriteNode(ZigBeeNodeDao node) => _store[node.IeeeAddress] = node; public void RemoveNode(IeeeAddress address) => _store.Remove(address); } networkManager.SetNetworkDataStore(new InMemoryDataStore()); ``` -------------------------------- ### Initialize ZigBee Network Manager Source: https://github.com/mr-markus/zigbeenet/blob/develop/README.md Basic C# example demonstrating how to initialize the ZigBee network manager with a specific serial port and dongle. Ensure the correct COM port is specified. ```csharp using System; namespace ZigBeeNet.PlayGround { class Program { static void Main(string[] args) { try { ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort("COM4"); IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort); ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle); // Initialise the network networkManager.Initialize(); 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; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } } ``` -------------------------------- ### Implement Custom CommandListener Source: https://github.com/mr-markus/zigbeenet/wiki/CommandListener Implement the IZigBeeCommandListener interface to handle incoming ZigBee commands. This example shows a basic listener that prints the received command to the console. ```csharp public class ConsoleCommandListener : IZigBeeCommandListener { public void CommandReceived(ZigBeeCommand command) { Console.WriteLine(command); } } ``` -------------------------------- ### Initialize ZigBee Network with CC2531 Dongle Source: https://github.com/mr-markus/zigbeenet/wiki/Getting-started Example demonstrating the initialization of the ZigBee network using a Texas Instruments CC2531 dongle and a serial port. Ensure the ZigBeeNet and ZigBeeNet.Transport.SerialPort NuGet packages are referenced. ```cs ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort("COM4"); IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort); ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle); // Initialise the network networkManager.Initialize(); 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; } ``` -------------------------------- ### Network Configuration Source: https://context7.com/mr-markus/zigbeenet/llms.txt Configure essential network settings like channel, PAN ID, and security keys. These settings must be applied after initialization and before starting the network. ```APIDOC ## Network Configuration — Channel, PAN ID, Keys All configuration must be called after `Initialize()` and before `Startup()`. ```csharp networkManager.Initialize(); // Set RF channel (11–26 for 2.4 GHz) networkManager.SetZigBeeChannel(ZigBeeChannel.CHANNEL_11); // Set PAN ID (0x0001–0x3FFE; 0xFFFF = random) networkManager.SetZigBeePanId(1); // Set Extended PAN ID networkManager.SetZigBeeExtendedPanId(new ExtendedPanId()); // Set network key (randomly generated) networkManager.SetZigBeeNetworkKey(ZigBeeKey.CreateRandom()); // Set Trust Centre link key (well-known ZigBee Alliance key) networkManager.SetZigBeeLinkKey(new ZigBeeKey(new byte[] { 0x5A, 0x69, 0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61, 0x6E, 0x63, 0x65, 0x30, 0x39 })); // Add install key for a specific device ZigBeeKey installKey = new ZigBeeKey(); installKey.Address = new IeeeAddress("0017880100A2B3C4"); networkManager.SetZigBeeInstallKey(installKey); // Read back current settings Console.WriteLine($"PAN ID = {networkManager.ZigBeePanId}"); Console.WriteLine($"Extended PAN ID = {networkManager.ZigBeeExtendedPanId}"); Console.WriteLine($"Channel = {networkManager.ZigbeeChannel}"); Console.WriteLine($"Network Key = {networkManager.ZigBeeNetworkKey}"); networkManager.Startup(reinitialize: true); // pass true to apply the new configuration ``` ``` -------------------------------- ### Implement IZigBeeNetworkNodeListener Source: https://github.com/mr-markus/zigbeenet/wiki/NodeListener Implement this interface to receive notifications about node additions, removals, and updates in the ZigBee network. The example logs events to the console. ```csharp public class ConsoleNetworkNodeListener : IZigBeeNetworkNodeListener { public void NodeAdded(ZigBeeNode node) { Console.WriteLine("Node " + node.IeeeAddress + " added " + node); if (node.NetworkAddress != 0) { Console.WriteLine("Node added " + node); } } public void NodeRemoved(ZigBeeNode node) { Console.WriteLine("Node removed " + node); } public void NodeUpdated(ZigBeeNode node) { Console.WriteLine("Node updated " + node); } } ``` -------------------------------- ### Register Command Listener Source: https://github.com/mr-markus/zigbeenet/wiki/CommandListener Add your custom command listener implementation to the ZigBeeNetworkManager to start receiving commands. ```csharp networkManager.AddCommandListener(new ConsoleCommandListener()); ``` -------------------------------- ### Get Node and Endpoint Address Source: https://github.com/mr-markus/zigbeenet/wiki/Get-node-and-endpoint-address Initializes the Zigbee network manager, retrieves a node by its network address, and gets the endpoint address. Use this to interact with specific devices on the network. ```cs // Initialize COM Port ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort("COM4"); // Initialize dongle hardware e.g. CC2531 IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort); // Initialize NetworkManager ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle); // Send OnCommand await networkManager.Send(endpointAddress, new OnCommand()); // Get node by it's network address // The network address can be stored in your database or another store var node = networkManager.GetNode(4711); // Create a endpoint address object ZigBeeEndpointAddress endpointAddress = null; // Get default endpoint var endpoint = node.Endpoints.Values.FirstOrDefault(); if (endpoint != null) { // Get endpoint address endpointAddress = endpoint.GetEndpointAddress(); } else { throw new Exception("No Endpoint found!"); } ``` -------------------------------- ### Add Network Node Listener Source: https://github.com/mr-markus/zigbeenet/wiki/NodeListener Register your custom listener with the ZigBeeNetworkManager to start receiving node events. ```csharp networkManager.AddNetworkNodeListener(new ConsoleNetworkNodeListener()); ``` -------------------------------- ### Implement Custom Data Store - ZigBeeNet Source: https://github.com/mr-markus/zigbeenet/wiki/DataStore Implement the `IZigBeeNetworkDataStore` interface and register your custom data store with the `NetworkManager` before startup. Devices will be loaded on startup and saved on node updates. ```cs IZigBeeNetworkDataStore dataStore = new JsonNetworkDataStore(database); networkManager.SetNetworkDataStore(dataStore); ``` -------------------------------- ### Control Zigbee Light On/Off and Brightness Source: https://github.com/mr-markus/zigbeenet/wiki/Turn-light-on-off This C# code snippet shows how to initialize a Zigbee serial port and dongle, then send commands to turn a light on, off, or set its brightness level. It includes error handling for finding an endpoint. ```cs // Initialize COM Port ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort("COM4"); // Initialize dongle hardware e.g. CC2531 IZigBeeTransportTransmit dongle = new ZigBeeDongleTiCc2531(zigbeePort); // Initialize NetworkManager ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle); // Send OnCommand await networkManager.Send(endpointAddress, new OnCommand()); // Get node by it's network address var node = networkManager.GetNode(4711); // Create a endpoint address object ZigBeeEndpointAddress endpointAddress = null; // Get default endpoint var endpoint = node.Endpoints.Values.FirstOrDefault(); if (endpoint != null) { // Get endpoint address endpointAddress = endpoint.GetEndpointAddress(); } else { throw new Exception("No Endpoint found!"); } // Send OffCommand await networkManager.Send(endpointAddress, new OffCommand()); // Send MoveToLevelCommand for setting brightness var command = new MoveToLevelWithOnOffCommand() { // Level from 0 to 255, where 255 = 100 % Level = byte.Parse(level), // Time for changing (smoothly overflow) TransitionTime = ushort.Parse(time) }; await networkManager.Send(endpointAddress, command); ``` -------------------------------- ### Configure Zigbee Network Settings Source: https://context7.com/mr-markus/zigbeenet/llms.txt Configure RF channel, PAN ID, Extended PAN ID, network key, and link key. Ensure this is called after Initialize() and before Startup(). ```csharp networkManager.Initialize(); // Set RF channel (11–26 for 2.4 GHz) networkManager.SetZigBeeChannel(ZigBeeChannel.CHANNEL_11); // Set PAN ID (0x0001–0x3FFE; 0xFFFF = random) networkManager.SetZigBeePanId(1); // Set Extended PAN ID networkManager.SetZigBeeExtendedPanId(new ExtendedPanId()); // Set network key (randomly generated) networkManager.SetZigBeeNetworkKey(ZigBeeKey.CreateRandom()); // Set Trust Centre link key (well-known ZigBee Alliance key) networkManager.SetZigBeeLinkKey(new ZigBeeKey(new byte[] { 0x5A, 0x69, 0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61, 0x6E, 0x63, 0x65, 0x30, 0x39 })); // Add install key for a specific device ZigBeeKey installKey = new ZigBeeKey(); installKey.Address = new IeeeAddress("0017880100A2B3C4"); networkManager.SetZigBeeInstallKey(installKey); // Read back current settings Console.WriteLine($"PAN ID = {networkManager.ZigBeePanId}"); Console.WriteLine($"Extended PAN ID = {networkManager.ZigBeeExtendedPanId}"); Console.WriteLine($"Channel = {networkManager.ZigbeeChannel}"); Console.WriteLine($"Network Key = {networkManager.ZigBeeNetworkKey}"); networkManager.Startup(reinitialize: true); // pass true to apply the new configuration ``` -------------------------------- ### Send Command — On/Off, Toggle, Level, Color Source: https://context7.com/mr-markus/zigbeenet/llms.txt Demonstrates how to send various commands to Zigbee devices, such as On/Off, Toggle, Level control, and Color control, using the `networkManager.Send` method. It returns a `Task` and waits for device acknowledgment. ```APIDOC ## Send Command — On/Off, Toggle, Level, Color `networkManager.Send(destination, command)` returns a `Task` and waits for the device acknowledgment. ```csharp using ZigBeeNet.ZCL.Clusters.OnOff; using ZigBeeNet.ZCL.Clusters.LevelControl; using ZigBeeNet.ZCL.Clusters.ColorControl; using ZigBeeNet.Util; ZigBeeNode node = networkManager.GetNode(4711); ZigBeeEndpointAddress addr = node.GetEndpoints().First().GetEndpointAddress(); // Turn on CommandResult onResult = await networkManager.Send(addr, new OnCommand()); Console.WriteLine($"On: {(onResult.IsSuccess() ? "OK" : "FAIL")}"); // Turn off await networkManager.Send(addr, new OffCommand()); // Toggle await networkManager.Send(addr, new ToggleCommand()); // Set brightness: Level 0–255 (255 = 100 %), transition time in 1/10 seconds await networkManager.Send(addr, new MoveToLevelWithOnOffCommand { Level = 128, // ~50 % brightness TransitionTime = 10 // 1 second }); // Move (continuous dimming): mode 0 = up, 1 = down; rate per second await networkManager.Send(addr, new MoveCommand { MoveMode = 0, Rate = 50 }); // Set RGB color (convert to CIE xy) CieColor xyY = ColorConverter.RgbToCie(255, 128, 0); // orange await networkManager.Send(addr, new MoveToColorCommand { ColorX = xyY.X, ColorY = xyY.Y, TransitionTime = 10 }); // Set hue await networkManager.Send(addr, new MoveToHueCommand { Hue = 120, // green hue Direction = 0, TransitionTime = 5 }); // Set color temperature (Mired scale) await networkManager.Send(addr, new MoveToColorTemperatureCommand { ColorTemperature = 370, // ~2700 K warm white TransitionTime = 10 }); ``` ``` -------------------------------- ### Implement IZigBeeNetworkNodeListener for Node Events Source: https://context7.com/mr-markus/zigbeenet/llms.txt Implement IZigBeeNetworkNodeListener to receive callbacks for node additions, updates, and removals. Register the listener before calling Startup. ```csharp using ZigBeeNet; public class MyNodeListener : IZigBeeNetworkNodeListener { public void NodeAdded(ZigBeeNode node) { Console.WriteLine($"[+] Node added: IEEE={node.IeeeAddress}, NWK=0x{node.NetworkAddress:X4}"); // Start application logic for the new device here } public void NodeUpdated(ZigBeeNode node) { Console.WriteLine($"[~] Node updated: IEEE={node.IeeeAddress}, State={node.NodeState}"); } public void NodeRemoved(ZigBeeNode node) { Console.WriteLine($"[-] Node removed: IEEE={node.IeeeAddress}"); } } // Register the listener before calling Startup networkManager.AddNetworkNodeListener(new MyNodeListener()); // Remove later if needed // networkManager.RemoveNetworkNodeListener(listener); ``` -------------------------------- ### Automatic Network Discovery with ZigBeeDiscoveryExtension Source: https://context7.com/mr-markus/zigbeenet/llms.txt Implement IZigBeeNetworkExtension with ZigBeeDiscoveryExtension for initial node discovery and periodic mesh refresh (routes and neighbors). Configure update intervals and specific tasks. ```csharp using ZigBeeNet.App.Discovery; ZigBeeDiscoveryExtension discovery = new ZigBeeDiscoveryExtension(); // Mesh update interval in seconds (0 = disabled) discovery.SetUpdatePeriod(60); // Optionally restrict mesh update tasks discovery.MeshUpdateTasks = new List { ZigBeeNodeServiceDiscoverer.NodeDiscoveryTask.NEIGHBORS, ZigBeeNodeServiceDiscoverer.NodeDiscoveryTask.ROUTES }; networkManager.AddExtension(discovery); // The extension is automatically started by networkManager.Startup() // and stopped by networkManager.Shutdown() ``` -------------------------------- ### Select ZigBee Hardware Dongle Transport Source: https://context7.com/mr-markus/zigbeenet/llms.txt Shows how to instantiate different hardware dongle drivers, all of which implement IZigBeeTransportTransmit. Each driver is constructed from a ZigBeeSerialPort. Specific configurations, like disabling polling for EZSP or LEDs for CC2531, are demonstrated. ```csharp ZigBeeSerialPort port = new ZigBeeSerialPort("COM4", 115200, FlowControl.FLOWCONTROL_OUT_NONE); // Texas Instruments CC2531 (Z-Stack 3.0.x, ZNP image) IZigBeeTransportTransmit tiDongle = new ZigBeeDongleTiCc2531(port); // Digi XBee S2C IZigBeeTransportTransmit xbeeDongle = new ZigBeeDongleXBee(port); // Dresden Elektronik ConBee / ConBee II (RaspBee) IZigBeeTransportTransmit conbeeDongle = new ZigbeeDongleConBee(port); // Silicon Labs EZSP (Ember EM35x / EFR32) — use software flow control at 57600 ZigBeeSerialPort emberPort = new ZigBeeSerialPort("COM5", 57600, FlowControl.FLOWCONTROL_OUT_XONOFF); IZigBeeTransportTransmit emberDongle = new ZigBeeDongleEzsp(emberPort); ((ZigBeeDongleEzsp)emberDongle).SetPollRate(0); // disable polling for EZSP // CC2531-specific: disable LEDs ((ZigBeeDongleTiCc2531)tiDongle).SetLedMode(1, false); // green LED off ((ZigBeeDongleTiCc2531)tiDongle).SetLedMode(2, false); // red LED off ``` -------------------------------- ### JSON Persistence for Network Data with JsonNetworkDataStore Source: https://context7.com/mr-markus/zigbeenet/llms.txt Use JsonNetworkDataStore to persist node data as separate JSON files in a specified directory. Node data is loaded at startup and saved automatically on updates. ```csharp using ZigBeeNet.DataStore.Json; // Create store pointing to a directory (created if not exists) JsonNetworkDataStore jsonStore = new JsonNetworkDataStore("./zigbee-devices"); networkManager.SetNetworkDataStore(jsonStore); // The store implements IZigBeeNetworkDataStore: // ISet ReadNetworkNodes() — called at startup // ZigBeeNodeDao ReadNode(IeeeAddress) — restore a node's data // void WriteNode(ZigBeeNodeDao) — called automatically on update // void RemoveNode(IeeeAddress) — called when node leaves // File layout: ./zigbee-devices/0017880100A2B3C4.json // ./zigbee-devices/001788010012ABCD.json ``` -------------------------------- ### Intercept Incoming ZCL/ZDO Commands with IZigBeeCommandListener Source: https://context7.com/mr-markus/zigbeenet/llms.txt Implement IZigBeeCommandListener to receive all inbound ZCL/ZDO commands before they are dispatched to clusters. Register this listener with the network manager. ```csharp using ZigBeeNet; public class MyCommandListener : IZigBeeCommandListener { public void CommandReceived(ZigBeeCommand command) { Console.WriteLine($"RX [{command.GetType().Name}] from {command.SourceAddress} -> {command.DestinationAddress}"); // Cast to specific types for deep inspection: // if (command is ReportAttributesCommand report) { ... } } } // Register before or after Startup networkManager.AddCommandListener(new MyCommandListener()); // ZigBeeTransaction is a built-in listener that must be added for Send() to work correctly networkManager.AddCommandListener(new ZigBeeTransaction(networkManager)); ``` -------------------------------- ### Turn Light On/Off and Set Brightness with ZigBeeNet Source: https://github.com/mr-markus/zigbeenet/wiki/How-to-control-devices Use this code to send commands to a Zigbee device to turn a light on or off, and to set its brightness level. Ensure you have the correct endpoint address and network manager instance. ```cs // Get endpoint address var endpointAddress = endpoint.GetEndpointAddress(); // Create a command object OnCommand onCmd = new OnCommand(); // Send command via network manager await networkManager.Send(endpointAddress, onCmd); // Create a command object with parameters var command = new MoveToLevelWithOnOffCommand() { // Level from 0 to 255, where 255 = 100 % Level = byte.Parse(level), // Time for changing (smoothly overflow) TransitionTime = ushort.Parse(time) }; await networkManager.Send(endpointAddress, command); ``` -------------------------------- ### IZigBeeNetworkNodeListener — Respond to Node Events Source: https://context7.com/mr-markus/zigbeenet/llms.txt Details how to implement the `IZigBeeNetworkNodeListener` interface to receive callbacks for node events such as addition, update, and removal. This allows for application logic to be triggered based on network changes. ```APIDOC ## IZigBeeNetworkNodeListener — Respond to Node Events Implement this interface to receive callbacks when nodes are added, updated, or removed. ```csharp using ZigBeeNet; public class MyNodeListener : IZigBeeNetworkNodeListener { public void NodeAdded(ZigBeeNode node) { Console.WriteLine($"[+] Node added: IEEE={node.IeeeAddress}, NWK=0x{node.NetworkAddress:X4}"); // Start application logic for the new device here } public void NodeUpdated(ZigBeeNode node) { Console.WriteLine($"[~] Node updated: IEEE={node.IeeeAddress}, State={node.NodeState}"); } public void NodeRemoved(ZigBeeNode node) { Console.WriteLine($"[-] Node removed: IEEE={node.IeeeAddress}"); } } // Register the listener before calling Startup networkManager.AddNetworkNodeListener(new MyNodeListener()); // Remove later if needed // networkManager.RemoveNetworkNodeListener(listener); ``` ``` -------------------------------- ### Monitor Network State Changes with IZigBeeNetworkStateListener Source: https://context7.com/mr-markus/zigbeenet/llms.txt Implement IZigBeeNetworkStateListener to receive notifications about network state changes such as ONLINE, OFFLINE, or SHUTDOWN. Register the listener with the network manager. ```csharp using ZigBeeNet; using ZigBeeNet.Transport; public class MyNetworkStateListener : IZigBeeNetworkStateListener { public void NetworkStateUpdated(ZigBeeNetworkState state) { switch (state) { case ZigBeeNetworkState.ONLINE: Console.WriteLine("Network is ONLINE."); break; case ZigBeeNetworkState.OFFLINE: Console.WriteLine("Network went OFFLINE."); break; case ZigBeeNetworkState.SHUTDOWN: Console.WriteLine("Network shut down."); break; } } } networkManager.AddNetworkStateListener(new MyNetworkStateListener()); ``` -------------------------------- ### Manage Zigbee Device Joining Source: https://context7.com/mr-markus/zigbeenet/llms.txt Control whether new devices can join the network. Joining can be permitted network-wide or on specific nodes for a set duration. ```csharp // Open joining for 60 seconds (network-wide broadcast) networkManager.PermitJoin(60); // Open joining only on the coordinator node ZigBeeNode coord = networkManager.GetNode(0); // 0 = coordinator NWK address coord.PermitJoin(true); // enable permanently (until explicitly disabled) coord.PermitJoin(false); // disable // Open joining at a specific router/destination for 30 seconds networkManager.PermitJoin(new ZigBeeEndpointAddress(0x1234), 30); // Close network-wide joining networkManager.PermitJoin(0); ``` -------------------------------- ### Send ZigBee Commands (On/Off, Level, Color) Source: https://context7.com/mr-markus/zigbeenet/llms.txt Use networkManager.Send to interact with ZigBee devices. This method returns a Task and waits for device acknowledgment. Ensure necessary cluster imports are included. ```csharp using ZigBeeNet.ZCL.Clusters.OnOff; using ZigBeeNet.ZCL.Clusters.LevelControl; using ZigBeeNet.ZCL.Clusters.ColorControl; using ZigBeeNet.Util; ZigBeeNode node = networkManager.GetNode(4711); ZigBeeEndpointAddress addr = node.GetEndpoints().First().GetEndpointAddress(); // Turn on CommandResult onResult = await networkManager.Send(addr, new OnCommand()); Console.WriteLine($"On: {(onResult.IsSuccess() ? "OK" : "FAIL")}"); // Turn off await networkManager.Send(addr, new OffCommand()); // Toggle await networkManager.Send(addr, new ToggleCommand()); // Set brightness: Level 0–255 (255 = 100 %), transition time in 1/10 seconds await networkManager.Send(addr, new MoveToLevelWithOnOffCommand { Level = 128, // ~50 % brightness TransitionTime = 10 // 1 second }); // Move (continuous dimming): mode 0 = up, 1 = down; rate per second await networkManager.Send(addr, new MoveCommand { MoveMode = 0, Rate = 50 }); // Set RGB color (convert to CIE xy) CieColor xyY = ColorConverter.RgbToCie(255, 128, 0); // orange await networkManager.Send(addr, new MoveToColorCommand { ColorX = xyY.X, ColorY = xyY.Y, TransitionTime = 10 }); // Set hue await networkManager.Send(addr, new MoveToHueCommand { Hue = 120, // green hue Direction = 0, TransitionTime = 5 }); // Set color temperature (Mired scale) await networkManager.Send(addr, new MoveToColorTemperatureCommand { ColorTemperature = 370, // ~2700 K warm white TransitionTime = 10 }); ``` -------------------------------- ### Remove a Device from the Network (Leave) Source: https://context7.com/mr-markus/zigbeenet/llms.txt Initiate a non-forced leave request for a device using its network and IEEE addresses. A forced removal option is available to remove the device from the local node list even if it doesn't respond. ```csharp // Request a device to leave (non-forced) await networkManager.Leave(node.NetworkAddress, node.IeeeAddress); // Force-remove from local node list even if device doesn't respond await networkManager.Leave(node.NetworkAddress, node.IeeeAddress, forceNodeRemoval: true); ``` -------------------------------- ### Permit Join Source: https://context7.com/mr-markus/zigbeenet/llms.txt Control whether new devices can join the Zigbee network. This can be done network-wide or targeted to specific nodes. ```APIDOC ## Permit Join — Allow New Devices onto the Network `PermitJoin` broadcasts a Management Permit Joining request to all routers and the coordinator. ```csharp // Open joining for 60 seconds (network-wide broadcast) networkManager.PermitJoin(60); // Open joining only on the coordinator node ZigBeeNode coord = networkManager.GetNode(0); // 0 = coordinator NWK address coord.PermitJoin(true); // enable permanently (until explicitly disabled) coord.PermitJoin(false); // disable // Open joining at a specific router/destination for 30 seconds networkManager.PermitJoin(new ZigBeeEndpointAddress(0x1234), 30); // Close network-wide joining networkManager.PermitJoin(0); ``` ``` -------------------------------- ### Read Attributes — Query Device Information Source: https://context7.com/mr-markus/zigbeenet/llms.txt Explains how to read cluster attributes from Zigbee devices asynchronously. It covers using typed cluster methods for quick reads and generic `ReadAttributeValue` for detailed inspection, including discovering all attributes and updating the binding table. ```APIDOC ## Read Attributes — Query Device Information Cluster attributes can be read asynchronously using typed cluster methods or the generic `ReadAttributeValue`. ```csharp using ZigBeeNet.ZCL.Clusters; using ZigBeeNet.ZCL.Protocol; ZigBeeNode node = networkManager.GetNode(4711); ZigBeeEndpoint endpoint = node.GetEndpoints().First(); // --- Quick read via typed cluster method --- ZclCluster basicCluster = endpoint.GetInputCluster(ZclBasicCluster.CLUSTER_ID); string manufacturerName = (string)(await basicCluster.ReadAttributeValue(ZclBasicCluster.ATTR_MANUFACTURERNAME)); string modelIdentifier = (string)(await basicCluster.ReadAttributeValue(ZclBasicCluster.ATTR_MODELIDENTIFIER)); Console.WriteLine($"Manufacturer: {manufacturerName}, Model: {modelIdentifier}"); // --- Detailed read with full response inspection --- if (basicCluster != null) { CommandResult result = await ((ZclBasicCluster)basicCluster).GetManufacturerNameAsync(); if (result.IsSuccess()) { ReadAttributesResponse response = result.GetResponse(); foreach (var record in response.Records) { if (record.Status == ZclStatus.SUCCESS) Console.WriteLine($"Attr {record.AttributeIdentifier} ({record.AttributeDataType}): {record.AttributeValue}"); else Console.WriteLine($"Attr {record.AttributeIdentifier} error: {record.Status}"); } } } // --- Discover all attributes on every input cluster --- foreach (int clusterId in endpoint.GetInputClusterIds()) { ZclCluster cluster = endpoint.GetInputCluster(clusterId); bool ok = await cluster.DiscoverAttributes(true); if (!ok) Console.WriteLine($"Attribute discovery failed for {cluster.GetClusterName()}"); } // --- Read binding table --- ZigBeeStatus status = await node.UpdateBindingTable(); if (status == ZigBeeStatus.SUCCESS) Console.WriteLine($"Binding table updated: {node.BindingTable.Count} entries"); ``` ``` -------------------------------- ### MongoDB Persistence for Network Data with MongoDbDataStore Source: https://context7.com/mr-markus/zigbeenet/llms.txt Utilize MongoDbDataStore to store all nodes in a MongoDB collection, indexed by IeeeAddress. Nodes are loaded at startup and saved on changes. ```csharp using ZigBeeNet.DataStore.MongoDb; MongoDbDatabaseSettings settings = new MongoDbDatabaseSettings { ConnectionString = "mongodb://localhost:27017", DatabaseName = "zigbee", NodesCollectionName = "nodes" }; MongoDbDataStore mongoStore = new MongoDbDataStore(settings); networkManager.SetNetworkDataStore(mongoStore); // Nodes are now automatically loaded from MongoDB at startup and // written back on every node change event. ``` -------------------------------- ### Read Manufacturer Name (Detailed) Source: https://github.com/mr-markus/zigbeenet/wiki/Read-attributes Performs a detailed read of the manufacturer name attribute from a Zigbee endpoint's basic cluster. Handles success and error responses, including checking for empty records and specific status codes. ```cs var cluster = endpoint.GetInputCluster(ZclBasicCluster.CLUSTER_ID); if (cluster != null) { var result = await ((ZclBasicCluster)cluster).GetManufacturerNameAsync(); if (result.IsSuccess()) { ReadAttributesResponse response = result.GetResponse(); if (response.Records.Count == 0) { Console.WriteLine("No records returned"); continue; } ZclStatus statusCode = response.Records[0].Status; if (statusCode == ZclStatus.SUCCESS) { Console.WriteLine("Cluster " + response + ", Attribute " + response.Records[0].AttributeIdentifier + ", type " + response.Records[0].AttributeDataType + ", value: " + response.Records[0].AttributeValue); } else { Console.WriteLine("Attribute value read error: " + statusCode); } } } ``` -------------------------------- ### Retrieve Zigbee Node and Endpoint Information Source: https://context7.com/mr-markus/zigbeenet/llms.txt Access Zigbee nodes using their network or IEEE address and inspect their endpoints and clusters. Nodes are identified by 16-bit network address or 64-bit IEEE address. ```csharp // Retrieve a node by its 16-bit network address ZigBeeNode node = networkManager.GetNode(4711); // Or retrieve by IEEE address ZigBeeNode nodeByIeee = networkManager.GetNode(new IeeeAddress("0017880100A2B3C4")); // List all known nodes foreach (ZigBeeNode n in networkManager.Nodes) Console.WriteLine($"{n.NetworkAddress}: {n.LogicalType} - {n.IeeeAddress}"); // Get the first (default) endpoint of a node ZigBeeEndpoint endpoint = node.GetEndpoints().FirstOrDefault() ?? throw new Exception("No endpoint found on node"); ZigBeeEndpointAddress endpointAddress = endpoint.GetEndpointAddress(); // Inspect endpoint clusters foreach (int clusterId in endpoint.GetInputClusterIds()) { ZclCluster cluster = endpoint.GetInputCluster(clusterId); Console.WriteLine($"Input cluster: {cluster.GetClusterName()} (0x{clusterId:X4})"); } foreach (int clusterId in endpoint.GetOutputClusterIds()) { ZclCluster cluster = endpoint.GetOutputCluster(clusterId); Console.WriteLine($"Output cluster: {cluster.GetClusterName()} (0x{clusterId:X4})"); } ``` -------------------------------- ### Retrieve Manufacturer Name (Cached) Source: https://github.com/mr-markus/zigbeenet/wiki/Read-attributes Reads the manufacturer name from the basic cluster of a Zigbee node, utilizing a cache for 60 seconds. Ensure the node and endpoint are accessible. ```cs ZigBeeNode node = _networkManager.GetNode(4711); string model = node.Endpoints.FirstOrDefault().Value .GetInputCluster(ZclBasicCluster.CLUSTER_ID)) .GetManufacturerName(60); // caches value for 60 secods ``` -------------------------------- ### Read ZigBee Device Attributes Source: https://context7.com/mr-markus/zigbeenet/llms.txt Read cluster attributes using typed cluster methods or the generic ReadAttributeValue. Detailed reads allow for full response inspection. Ensure ZCL cluster imports are present. ```csharp using ZigBeeNet.ZCL.Clusters; using ZigBeeNet.ZCL.Protocol; ZigBeeNode node = networkManager.GetNode(4711); ZigBeeEndpoint endpoint = node.GetEndpoints().First(); // --- Quick read via typed cluster method --- ZclCluster basicCluster = endpoint.GetInputCluster(ZclBasicCluster.CLUSTER_ID); string manufacturerName = (string)(await basicCluster.ReadAttributeValue(ZclBasicCluster.ATTR_MANUFACTURERNAME)); string modelIdentifier = (string)(await basicCluster.ReadAttributeValue(ZclBasicCluster.ATTR_MODELIDENTIFIER)); Console.WriteLine($"Manufacturer: {manufacturerName}, Model: {modelIdentifier}"); // --- Detailed read with full response inspection --- if (basicCluster != null) { CommandResult result = await ((ZclBasicCluster)basicCluster).GetManufacturerNameAsync(); if (result.IsSuccess()) { ReadAttributesResponse response = result.GetResponse(); foreach (var record in response.Records) { if (record.Status == ZclStatus.SUCCESS) Console.WriteLine($"Attr {record.AttributeIdentifier} ({record.AttributeDataType}): {record.AttributeValue}"); else Console.WriteLine($"Attr {record.AttributeIdentifier} error: {record.Status}"); } } } // --- Discover all attributes on every input cluster --- foreach (int clusterId in endpoint.GetInputClusterIds()) { ZclCluster cluster = endpoint.GetInputCluster(clusterId); bool ok = await cluster.DiscoverAttributes(true); if (!ok) Console.WriteLine($"Attribute discovery failed for {cluster.GetClusterName()}"); } // --- Read binding table --- ZigBeeStatus status = await node.UpdateBindingTable(); if (status == ZigBeeStatus.SUCCESS) Console.WriteLine($"Binding table updated: {node.BindingTable.Count} entries"); ``` -------------------------------- ### GetNode and Endpoint Address Source: https://context7.com/mr-markus/zigbeenet/llms.txt Retrieve information about Zigbee nodes and their endpoints using network addresses or IEEE addresses. ```APIDOC ## GetNode and Endpoint Address — Locate a Device Nodes are identified by their 16-bit network address or 64-bit IEEE address. Endpoints are numbered sub-devices within a node. ```csharp // Retrieve a node by its 16-bit network address ZigBeeNode node = networkManager.GetNode(4711); // Or retrieve by IEEE address ZigBeeNode nodeByIeee = networkManager.GetNode(new IeeeAddress("0017880100A2B3C4")); // List all known nodes foreach (ZigBeeNode n in networkManager.Nodes) Console.WriteLine($"{n.NetworkAddress}: {n.LogicalType} - {n.IeeeAddress}"); // Get the first (default) endpoint of a node ZigBeeEndpoint endpoint = node.GetEndpoints().FirstOrDefault() ?? throw new Exception("No endpoint found on node"); ZigBeeEndpointAddress endpointAddress = endpoint.GetEndpointAddress(); // Inspect endpoint clusters foreach (int clusterId in endpoint.GetInputClusterIds()) { ZclCluster cluster = endpoint.GetInputCluster(clusterId); Console.WriteLine($"Input cluster: {cluster.GetClusterName()} (0x{clusterId:X4})"); } foreach (int clusterId in endpoint.GetOutputClusterIds()) { ZclCluster cluster = endpoint.GetOutputCluster(clusterId); Console.WriteLine($"Output cluster: {cluster.GetClusterName()} (0x{clusterId:X4})"); } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.