ArXen42 / Sunricher.Wifi

C# API for controlling LED devices from Sunricher (SR-2818WiN).
MIT License
1 stars 0 forks source link

Implement scan for devices #3

Open ArXen42 opened 6 years ago

ArXen42 commented 6 years ago

Sunricher android application can find wi-fi device in local network automatically. This library can't.

ArXen42 commented 6 years ago

In a simple networks the following implementation may work :

        /// <summary>
        ///     Attempt to discover device IP address in LAN.
        /// </summary>
        public async Task<String> DiscoverDeviceAsync()
        {
            using (var udp = new UdpClient(48899) {EnableBroadcast = true})
            {
                udp.Client.ReceiveTimeout = 200;
                udp.Client.SendTimeout    = 200;

                const String messageStr = "HF-A11ASSISTHREAD"; //Say friend and enter
                var          message    = Encoding.ASCII.GetBytes(messageStr);

                // ReSharper disable once AccessToDisposedClosure
                await Task.Run(() => udp.Send(message, message.Length, new IPEndPoint(System.Net.IPAddress.Broadcast, 48899)));

                for (Int32 attempt = 0; attempt < 5; attempt++)
                {
                    var endpoint = new IPEndPoint(System.Net.IPAddress.Any, 0);
                    // ReSharper disable once AccessToDisposedClosure
                    var received = await Task.Run(() => udp.Receive(ref endpoint));

                    String receivedString = Encoding.ASCII.GetString(received);

                    var split = receivedString.Split(',');
                    if (split.Length == 0)
                        continue;

                    return split[0];
                }

                throw new InvalidOperationException("All attempts to discover device failed");
            }
        }