From 23bd1119f287f960a95a42b90a10818e542abb40 Mon Sep 17 00:00:00 2001 From: Darth Affe Date: Wed, 17 Jan 2024 23:34:43 +0100 Subject: [PATCH] Added helper to auto discover WLED devices to the readme --- RGB.NET.Devices.WLED/README.md | 66 +++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/RGB.NET.Devices.WLED/README.md b/RGB.NET.Devices.WLED/README.md index da3eb5a..4ff284d 100644 --- a/RGB.NET.Devices.WLED/README.md +++ b/RGB.NET.Devices.WLED/README.md @@ -15,4 +15,68 @@ You can also override the manufacturer and device model in the DeviceDefinition. # Required SDK This provider does not require an additional SDK. -UDP realtime needs to be enabled on the WLED device. \ No newline at end of file +UDP realtime needs to be enabled on the WLED device. + +# Automatic device discovery +Due to the requirement of an additional dependency and the requirement to be able to configure devices manually anywy automatic discovery is not part of the provider. + +Using the nuget `Tmds.MDns` you can use the following Helper to do this: + +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Tmds.MDns; + +namespace RGB.NET.Devices.WLED; + +public static class WledDiscoveryHelper +{ + /// + /// Searches for WLED devices and returns a list of devices found. + /// + /// The time the discovery is waiting for responses. Choose this as short as possible as the method is blocking + /// The maximum amount of devices that are expected in the network. The discovery will stop early if the given amount of devices is found. + /// A list of addresses and device-infos. + public static IEnumerable<(string address, WledInfo info)> DiscoverDevices(int waitFor = 500, int maxDevices = -1) + { + List<(string address, WledInfo info)> devices = []; + using ManualResetEventSlim waitEvent = new(); + + int devicesToDetect = maxDevices <= 0 ? int.MaxValue : maxDevices; + + ServiceBrowser mdns = new(); + mdns.ServiceAdded += OnServiceAdded; + mdns.StartBrowse("_http._tcp"); + + waitEvent.Wait(TimeSpan.FromMilliseconds(waitFor)); + + mdns.StopBrowse(); + mdns.ServiceAdded -= OnServiceAdded; + + return devices; + + void OnServiceAdded(object? sender, ServiceAnnouncementEventArgs args) + { + string address = args.Announcement.Addresses.FirstOrDefault()?.ToString() ?? string.Empty; + if (!string.IsNullOrWhiteSpace(address)) + { + WledInfo? info = null; + try + { + info = WledAPI.Info(address); + } + catch { } + + if (info != null) + { + devices.Add((address, info)); + if (--devicesToDetect <= 0) + waitEvent.Set(); + } + } + } + } +} +``` \ No newline at end of file