示例#1
0
        public static async Task HueControlAsync()
        {
            IBridgeLocator loca = new HttpBridgeLocator();

            var bridgeIPs = await loca.LocateBridgesAsync(TimeSpan.FromSeconds(5)); // Locate bridges

            Q42.HueApi.Models.Bridge.LocatedBridge hachi = new Q42.HueApi.Models.Bridge.LocatedBridge();

            foreach (var item in bridgeIPs)
            {
                hachi = item; // Control most recent bridge found.
                Console.WriteLine(item + ": " + item.IpAddress);
            }
            Console.WriteLine(hachi.IpAddress + " Controlling! (hopefully) ID: " + hachi.BridgeId);

            ILocalHueClient client = new LocalHueClient(hachi.IpAddress);

            client.Initialize("appkey");

            var command1 = new LightCommand();

            command1.On = false;
            client.SendCommandAsync(command1);
            Console.WriteLine("Sent~");
        }
示例#2
0
        public static async void ConfigureIP(List <Account> accounts)
        {
            IBridgeLocator locator = new HttpBridgeLocator();

            //For Windows 8 and .NET45 projects you can use the SSDPBridgeLocator which actually scans your network.
            //See the included BridgeDiscoveryTests and the specific .NET and .WinRT projects
            IEnumerable <string> bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            if (bridgeIPs.ToList().Count > 0)
            {
                IP = bridgeIPs.ToList()[0];
                Console.WriteLine("Registered IP: " + IP);

                Account found = accounts.Find(account => account.IPAddress == IP);

                if (found != null)
                {
                    REGISTEREDUSERNAME = found.Username;
                    IPConfigured?.Invoke(true, EventArgs.Empty);
                }
                else
                {
                    IPConfigured?.Invoke(false, EventArgs.Empty);
                }
            }
            else
            {
                IP = null;
                Console.WriteLine("Failed to register IP: " + IP);

                FailedToRegisterIP?.Invoke(false, EventArgs.Empty);
            }
        }
示例#3
0
        public async static Task <List <GroupConfiguration> > GetGroupConfigurationsAsync()
        {
            IEnumerable <LocatedBridge> bridges = new List <LocatedBridge>();

            try
            {
                IBridgeLocator bridgeLocator = new HttpBridgeLocator();
                bridges = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(2));
            }
            catch { }

            var allConfig = Startup.Configuration.GetSection("HueSetup").Get <List <GroupConfiguration> >();

            if (bridges == null || !bridges.Any())
            {
                return(allConfig);
            }
            else
            {
                return(allConfig.Where(x =>
                                       x.Connections.Select(c => c.Ip).Intersect(bridges.Select(b => b.IpAddress)).Any() ||
                                       x.IsAlwaysVisible
                                       ).ToList());
            }
        }
示例#4
0
        async Task TurnLightRed()
        {
            Settings.IWasHere = Settings.IWasHere + 1;

            var bridgeLocator = new HttpBridgeLocator();
            var ips           = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(30));

            var client = new LocalHueClient(ips.First().IpAddress);

            if (!client.IsInitialized && !string.IsNullOrEmpty(Settings.HueKey))
            {
                client.Initialize(Settings.HueKey);
            }
            else
            {
                //await DisplayAlert("Not paired", "App not paired to a bridge, hit the register button.", "OK");

                return;
            }

            var command  = new LightCommand();
            var redColor = new RGBColor(220, 82, 74);

            command.TurnOn().SetColor(redColor);

            var allLights = await client.GetLightsAsync();

            foreach (var light in allLights)
            {
                if (light.Name.Equals("hue go 1", StringComparison.OrdinalIgnoreCase))
                {
                    await client.SendCommandAsync(command, new[] { light.Id });
                }
            }
        }
        public static async Task BridgeConnection()
        {
            //Checking Connection
            if (_client != null)
            {
                return;
            }

            //Finding Bridge
            IBridgeLocator locator = new HttpBridgeLocator();
            IEnumerable <LocatedBridge> bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10));

            var locatedBridges = bridgeIPs.ToList();

            if (!locatedBridges.Any())
            {
                LyokoLogger.Log("CodeHue", "No bridges found!");
                Connected = false;
                return;
            }
            else
            {
                LyokoLogger.Log("CodeHue", "Bridge located.");
            }

            //Checking Application Registering
            _client = new LocalHueClient(locatedBridges.First().IpAddress);
            var appKeyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                          "appKey.txt");

            if (System.IO.File.Exists(appKeyPath))
            {
                appKey = System.IO.File.ReadAllText(appKeyPath);
            }

            if (appKey.Length == 0)
            {
                LyokoLogger.Log("CodeHue", "Please press your Bridge's link button.");
                Timer myTimer = new Timer();
                myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
                myTimer.Interval = 5000;
                myTimer.Start();
                while (appKey.Length == 0)
                {
                }
                myTimer.Stop();
                System.IO.File.WriteAllText(appKeyPath, appKey);
                LyokoLogger.Log("CodeHue", "Key registered.");
            }

            //Connecting To Bridge
            _client.Initialize(appKey);
            var command = new LightCommand();

            command.Alert = Alert.Once;
            await _client.SendCommandAsync(command);

            LyokoLogger.Log("CodeHue", "Successfully connected to the Bridge.");
            Connected = true;
        }
示例#6
0
        private static async Task <StreamingHueClient> GetClient()
        {
            Console.WriteLine("Searching for bridge...");
            var locator = new HttpBridgeLocator();
            var bridge  = (await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5))).FirstOrDefault();

            if (bridge == null)
            {
                throw new InvalidOperationException("Could not find bridge! Giving up");
            }

            Console.WriteLine($"Found bridge! IP: {bridge.IpAddress}");

            var settings = GetSettings();

            var(appKey, entertainmentKey) = (settings.Value <string>("appKey"), settings.Value <string>("entertainmentKey"));
            if (appKey == null || entertainmentKey == null)
            {
                Console.WriteLine("Looks like I don't have the proper keys");
                Console.WriteLine("Please press bridge button. I'll wait");

                (appKey, entertainmentKey) = await GenerateKeys(bridge.IpAddress);

                Console.WriteLine("App keys generated. Saving");

                settings["appKey"]           = appKey;
                settings["entertainmentKey"] = entertainmentKey;

                SaveSettings(settings);
            }

            return(new StreamingHueClient(bridge.IpAddress, appKey, entertainmentKey));
        }
示例#7
0
        public async Task <LocatedBridge> FindAsync(string bridgeId)
        {
            var bridgeLocator = new HttpBridgeLocator();
            var bridgeIps     = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            return(bridgeIps.FirstOrDefault(bridge => bridge.BridgeId.Equals(bridgeId, StringComparison.InvariantCultureIgnoreCase)));
        }
示例#8
0
        public static async Task <HueUser> FindHueBridge(TokenBase token)
        {
            IBridgeLocator locator = new HttpBridgeLocator();
            var            bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            var bridge = (from item in bridges
                          where item.BridgeId == token.Id.ToLower()
                          select item).FirstOrDefault();

            if (bridge != null)
            {
                var client = new LocalHueClient(bridge.IpAddress);
                client.Initialize(token.AccessToken);

                var bridgeInfo = await client.GetBridgeAsync();

                var bridgeId = bridgeInfo.Config.BridgeId;

                var user = new HueUser(bridgeInfo);
                user.Token = token;

                return(user);
            }
            else
            {
                throw new InvalidOperationException("The Hue bridge with ID " + token.Id + " not found in current network.");
            }
        }
示例#9
0
        public async Task <ICollection <string> > GetBridges()
        {
            var locator = new HttpBridgeLocator();
            var bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            return(bridges.ToList());
        }
示例#10
0
        public async Task <IActionResult> Setup()
        {
            var bridgeLocator = new HttpBridgeLocator();
            var ips           = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(2));

            return(View(ips));
        }
示例#11
0
        public async Task UpdateExistingBridges()
        {
            IBridgeLocator       locator = new HttpBridgeLocator();
            List <LocatedBridge> bridges = (await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5))).ToList();

            // Lets try to find some more
            locator = new SsdpBridgeLocator();
            IEnumerable <LocatedBridge> extraBridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            foreach (LocatedBridge extraBridge in extraBridges)
            {
                if (bridges.All(b => b.BridgeId != extraBridge.BridgeId))
                {
                    bridges.Add(extraBridge);
                }
            }

            int updatedBridges = 0;

            foreach (LocatedBridge locatedBridge in bridges)
            {
                PhilipsHueBridge storedBridge = _storedBridgesSetting.Value.FirstOrDefault(s => s.BridgeId == locatedBridge.BridgeId);
                if (storedBridge != null && storedBridge.IpAddress != locatedBridge.IpAddress)
                {
                    storedBridge.IpAddress = locatedBridge.IpAddress;
                    updatedBridges++;
                }
            }

            if (updatedBridges > 0)
            {
                _storedBridgesSetting.Save();
                _logger.Information("Updated IP addresses of {updatedBridges} Hue Bridge(s)", updatedBridges);
            }
        }
示例#12
0
        /// <summary>
        /// Connect the controller to the light bridge.
        /// </summary>
        internal async Task <bool> Connect()
        {
            // Connect to the Philips Hue bridge.  If we ever change lights the Hue stuff can be abstracted out.
            if (Simulator != null)
            {
                Simulator.Log("Connection");
                return(true);
            }
            IBridgeLocator locator = new HttpBridgeLocator();
            IEnumerable <LocatedBridge> bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            if (bridges == null || bridges.Count() == 0)
            {
                ConnectionFailed?.Invoke(this, new EventArgs());
                return(false);
            }
            bridge = bridges.ElementAt(0);
            client = new LocalHueClient(bridge.IpAddress);
            // var appKey = await client.RegisterAsync("light-control", "fela");
            client?.Initialize(apiKey);
            bool connected = await client?.CheckConnection();

            if (client != null && connected)
            {
                Connected?.Invoke(this, new EventArgs());
            }
            else
            {
                ConnectionFailed?.Invoke(this, new EventArgs());
            }
            return(connected);
        }
示例#13
0
        async Task Connect()
        {
            IBridgeLocator locator   = new HttpBridgeLocator();
            var            bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            var ip = bridgeIPs.FirstOrDefault();

            if (ip == null)
            {
                _logger.LogError("Didn't find a HUE Bridge...");
                return;
            }
            _hueClient = new LocalHueClient(ip.IpAddress);
            try
            {
                if (string.IsNullOrEmpty(_apiToken))
                {
                    _apiToken = await _hueClient.RegisterAsync(Domain, "Rosie");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed Connect", ex);
                if (ex.Message == "Link button not pressed")
                {
                    _logger.LogWarning("Please press the button");
                }
            }
            _isConnected = !string.IsNullOrEmpty(_apiToken);
            _hueClient.Initialize(_apiToken);
            _logger.LogInformation("Connected");
        }
示例#14
0
        private static async Task <List <LocatedBridge> > DiscoverBridgesAsync(Configuration configuration)
        {
            List <LocatedBridge> locatedBridges = new List <LocatedBridge>();

            Console.WriteLine("Locating through HTTP.");
            HttpBridgeLocator locator = new HttpBridgeLocator();
            var bridges = (await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10))).ToList();

            locatedBridges.AddRange(bridges);


            if (locatedBridges.Count == 0)
            {
                Console.WriteLine("Http found nothing");
                // try
                // {
                //     Console.WriteLine("SSDP location attempt.");
                //     SSDPBridgeLocator locator = new SSDPBridgeLocator();
                //     var bridges = (await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10))).ToList();

                //     locatedBridges.AddRange(bridges);
                // }
                // catch
                // {
                //     Console.WriteLine("SSDP Failed");
                // }
            }

            return(locatedBridges);
        }
        /// <summary>
        /// Trys to locates all bridges in the network.
        /// </summary>
        /// <returns>The list of the found briges</returns>
        public static async Task <LocatedBridge[]> LocateAllBridges()
        {
            if (BridgeInformation.demoMode)
            {
                return(AddTestingBridges(new LocatedBridge[] { }, 50));
            }

            try
            {
                IBridgeLocator bridgeLocator = new HttpBridgeLocator();

                var bridges = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

                LocatedBridge[] bridgeList = bridges.Cast <LocatedBridge>().ToArray();

                if (BridgeInformation.demoMode)
                {
                    bridgeList = AddTestingBridges(bridgeList, 50);
                }

                return(bridgeList);
            }
            catch
            {
                return(new LocatedBridge[] { });
            }
        }
示例#16
0
        /// <summary>
        /// Return the command line IP address that was entered by the user or IP found by the bridge locater service
        /// </summary>
        /// <param name="ip"></param>
        static async Task <string> GetOrFindIP()
        {
            string ip = CmdLineOptions.ip;

            if (String.IsNullOrEmpty(CmdLineOptions.ip))
            {
                IBridgeLocator locator = new HttpBridgeLocator();
                IEnumerable <Q42.HueApi.Models.Bridge.LocatedBridge> bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10));

                ////For Windows 8 and .NET45 projects you can use the SSDPBridgeLocator which actually scans your network.
                ////See the included BridgeDiscoveryTests and the specific .NET and .WinRT projects
                //SSDPBridgeLocator locator = new SSDPBridgeLocator();
                //IEnumerable<string> bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10));

                if (bridgeIPs.Any())
                {
                    ip = bridgeIPs.First().IpAddress;
                    Console.WriteLine("Bridge found using IP address: " + ip);
                }
                else
                {
                    Console.WriteLine("Scan did not find a Hue Bridge. Try suppling a IP address for the bridge");
                    return(null);
                }
            }

            return(ip);
        }
示例#17
0
        public async Task HttpDiscovery()
        {
            IBridgeLocator locator = new HttpBridgeLocator();
            var            result  = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10));

            Assert.IsTrue(result.Any());
        }
示例#18
0
        public async Task Setup(ServiceConfig config)
        {
            Guard.NotNull(() => config, config);
            if (config.Bridges == null)
            {
                config.Bridges = new Dictionary <string, BridgeConfig>();
            }

            IBridgeLocator locator = new HttpBridgeLocator();
            var            bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);

            foreach (var bridge in bridges)
            {
                if (config.Bridges.TryGetValue(bridge.BridgeId, out var bridgeConfig))
                {
                    log.Info("Bridge {0} is already registered", bridge.BridgeId);
                    continue;
                }

                log.Info("Registering bridge: {0}. Please press button on it.", bridge.BridgeId);
                ILocalHueClient client = new LocalHueClient(bridge.IpAddress);
                var             appKey = await policy.ExecuteAsync(() => client.RegisterAsync("DashService", "DashHost")).ConfigureAwait(false);

                bridgeConfig                    = new BridgeConfig();
                bridgeConfig.AppKey             = appKey;
                bridgeConfig.Id                 = bridge.BridgeId;
                config.Bridges[bridge.BridgeId] = bridgeConfig;
            }
        }
示例#19
0
        private async Task <string> GetBridgeIp()
        {
            IBridgeLocator  locator         = new HttpBridgeLocator();
            SettingsManager settingsManager = new SettingsManager();
            string          ip;

            try
            {
                var ips = (await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5))).ToList();
                if (ips.Count > 0)
                {
                    ip = ips[0].IpAddress;
                    settingsManager.LastHueIp = ip;
                }
                else
                {
                    ip = null;
                }
            }
            catch (Exception ex) when(ex is HttpRequestException || ex is TaskCanceledException)
            {
                ip = settingsManager.LastHueIp;
            }

            if (string.IsNullOrEmpty(ip))
            {
                throw new Exception("Could not determine Hue bridge IP address");
            }

            return(ip);
        }
示例#20
0
        public async Task Start()
        {
            IBridgeLocator locator = new HttpBridgeLocator();
            var            bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false);

            var bridge = bridges.FirstOrDefault(item => item.BridgeId == config.Id);

            if (bridge == null)
            {
                throw new InvalidOperationException($"Bridge [{config.Id}] not found");
            }

            client = new LocalHueClient(bridge.IpAddress);
            client.Initialize(config.AppKey);
            var groups = await client.GetGroupsAsync().ConfigureAwait(false);

            groupsTable.Clear();
            foreach (var item in groups)
            {
                if (groupsTable.ContainsKey(item.Name))
                {
                    log.Error("{0} Groups is already registered", item.Name);
                    continue;
                }

                groupsTable[item.Name] = item;
            }
        }
示例#21
0
        private IEnumerable <string> GetBridges()
        {
            IBridgeLocator locator = new HttpBridgeLocator();

            //For Windows 8 and .NET45 projects you can use the SSDPBridgeLocator which actually scans your network.
            //See the included BridgeDiscoveryTests and the specific .NET and .WinRT projects
            return(locator.LocateBridgesAsync(TimeSpan.FromSeconds(3)).Result);
        }
        public async Task <IList <ILightSystem> > DiscoverAsync(int timeoutInMs = 5000)
        {
            var locator = new HttpBridgeLocator();

            var bridges = await locator.LocateBridgesAsync(TimeSpan.FromMilliseconds(timeoutInMs));

            return(bridges.Select(b => new HueLightSystem(new IPEndPoint(IPAddress.Parse(b.IpAddress), 0)) as ILightSystem).ToList());
        }
示例#23
0
        public object CreateClient()
        {
            var locator   = new HttpBridgeLocator();
            var bridgeIPs =
                locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)).Result;

            return(new LocalHueClient(bridgeIPs.First(), AppKey));
        }
示例#24
0
        public async Task <IEnumerable <HueBridge> > ListBridges()
        {
            IBridgeLocator locator = new HttpBridgeLocator();
            IEnumerable <LocatedBridge> bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            return(bridges.Select(b => new HueBridge {
                BridgeId = b.BridgeId, IpAddress = b.IpAddress
            }));
        }
        public async Task TestHttpBridgeLocator()
        {
            IBridgeLocator locator = new HttpBridgeLocator();

            var bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            Assert.IsNotNull(bridgeIPs);
            Assert.IsTrue(bridgeIPs.Count() > 0);
        }
示例#26
0
        public async Task TestHttpBridgeLocator()
        {
            var locator = new HttpBridgeLocator();

            // should not throw an exception
            var bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            Assert.NotNull(bridgeIPs);
        }
示例#27
0
        public override int Run(string[] remainingArguments)
        {
            if (_scan)
            {
                //TODO: Cant really assume /24 subnet...
                if (_ip != null && _ip.Split('.').Count() != 4)
                {
                    throw new ConsoleHelpAsException("Please provide valid IP address");
                }

                var initialIp = string.IsNullOrEmpty(_ip) ? GetIpAddresss() : _ip;
                var ip        = String.Join(".", initialIp.Split('.').Take(3));
                Parallel.ForEach(Enumerable.Range(0, 254), (lastByte, state) =>
                {
                    try
                    {
                        var testHost     = string.Format("{0}.{1}", ip, lastByte);
                        var hostResource = String.Format("http://{0}/debug/clip.html", testHost);
                        using (var client = new WebClient())
                        {
                            client.DownloadString(hostResource);
                            Console.WriteLine("Found host at: {0}", testHost);
                            state.Break();
                        }
                    }
                    catch (WebException)
                    {
                    }
                });
                Console.WriteLine("Failed to find any bridges via scan.  Ensure bridge is switched on and discoverable on your network segment.");
                return(1);
            }

            try
            {
                var locator = new HttpBridgeLocator();
                var result  = locator.LocateBridgesAsync(new TimeSpan(0, 0, GetTimeoutValue())).Result.ToList();
                if (result.Any())
                {
                    Console.WriteLine("Found {0} bridges:", result.Count);
                    Console.WriteLine();
                    foreach (var bridge in result)
                    {
                        Console.WriteLine("\t{0}", bridge);
                    }
                    return(0);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not locate bridges due to error: {0} : {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
                throw;
            }
            Console.WriteLine("Failed to find any bridges.  Ensure bridge Has internet access to register.");
            return(1);
        }
示例#28
0
        /// <summary>
        /// Asynchronously search for a bridge using the HttpLocator.
        /// </summary>
        /// <returns>The time it took to find the bridge(s).</returns>
        private async Task <TimeSpan> searchBridge()
        {
            DateTime       startTime = DateTime.Now;
            IBridgeLocator locator   = new HttpBridgeLocator(); //Or: LocalNetworkScanBridgeLocator, MdnsBridgeLocator, MUdpBasedBridgeLocator

            locBridges = (List <LocatedBridge>) await locator.LocateBridgesAsync(
                TimeSpan.FromSeconds(Properties.Settings.Default.SearchTimeout));

            return(DateTime.Now.Subtract(startTime));
        }
示例#29
0
        /// <inheritdoc />
        public async Task InitializeAsync()
        {
            IBridgeLocator locator         = new HttpBridgeLocator();
            var            bridgeAddresses = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(15));

            client = new LocalHueClient(bridgeAddresses.First());
            client.Initialize(appKey);

            await NotifyAsync(0, 0, 255, 1500);
        }
示例#30
0
    public async Task TestHttpBridgeLocator()
    {
      IBridgeLocator locator = new HttpBridgeLocator();

      var bridgIps = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

      Assert.IsNotNull(bridgIps);
      Assert.IsTrue(bridgIps.Count() > 0);

    }
示例#31
0
        public static async Task <IEnumerable <string> > Find()
        {
            IBridgeLocator locator = new HttpBridgeLocator();

            //For Windows 8 and .NET45 projects you can use the SSDPBridgeLocator which actually scans your network.
            //See the included BridgeDiscoveryTests and the specific .NET and .WinRT projects
            IEnumerable <string> bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            return(bridgeIPs);
        }