Exemplo n.º 1
0
        public void Connect(IPAddress lightIP, DoWorkEventArgs token = null)
        {
            if (light.IsConnected())
            {
                return;
            }

            //Can't reconnect using same device class instance
            light = new YeeLightAPI.YeeLightDevice();

            //Auto discover a device if the IP is 0.0.0.0 and auto-discovery is enabled
            if (lightIP.Equals(IPAddress.Parse("0.0.0.0")) && default_registry.GetVariable <bool>($"{devicename}_auto_discovery"))
            {
                var devices = DeviceLocator.DiscoverDevices(10000, 2);
                if (devices.Any())
                {
                    light   = devices.First();
                    lightIP = light.GetLightIPAddressAndPort().ipAddress;
                    default_registry.SetVariable($"{devicename}_IP", lightIP.ToString());
                }
                else
                {
                    throw new Exception("IP address is set to 0.0.0.0 and auto-discovery is enabled but no devices have been located.");
                }
            }
            //If it isn't then set the IP to the provided IP address
            else
            {
                light.SetLightIPAddressAndPort(lightIP, YeeLightAPI.YeeLightConstants.Constants.DefaultCommandPort);
            }

            IPAddress localIP;
            int       localMusicModeListenPort = GetFreeTCPPort(); // This can be any free port

            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect(lightIP, lightListenPort);
                localIP = ((IPEndPoint)socket.LocalEndPoint).Address;
            }

            light.Connect();
            light.SetMusicMode(localIP, (ushort)localMusicModeListenPort, true);
            isConnected = light.IsConnected();
        }