public async Task <bool> BridgeEntryAsync() { client = new LocalHueClient(LocalHost); try { var appKey = await client.RegisterAsync("mypersonalappname", "mydevicename"); Bridge bridge = new Bridge() { IpAddress = LocalHost }; Dispatcher.Invoke(() => { model.Bridges.Add(bridge); }); IEnumerable <Light> lights = await client.GetLightsAsync(); foreach (Light light in lights) { Console.WriteLine(light); bridge.Lights.Add(light); } return(true); } catch (Exception) { } return(false); }
public void Initialize() { string ip = ConfigurationManager.AppSettings["ip"].ToString(); string key = ConfigurationManager.AppSettings["key"].ToString(); _client = new LocalHueClient(ip, key); }
public async Task ConnectToBridge() { if (_config.Model.hueSettings.hueType == HueType.Basic) { _client = new LocalHueClient(_config.Model.hueSettings.ip); _client.Initialize(_config.Model.hueSettings.appKey); IsConnectedToBridge = true; if (!string.IsNullOrWhiteSpace(_config.Model.hueSettings.roomId)) { var Groups = await _client.GetGroupsAsync(); if (Groups != null && Groups.Count != 0) { UseRoom = Groups.FirstOrDefault(x => x.Id == _config.Model.hueSettings.roomId); } } } else if (_config.Model.hueSettings.hueType == HueType.Entertainment) { _streamClient = new StreamingHueClient(_config.Model.hueSettings.ip, _config.Model.hueSettings.appKey, _config.Model.hueSettings.entertainmentKey); IsConnectedToBridge = true; if (!string.IsNullOrWhiteSpace(_config.Model.hueSettings.roomId)) { var Groups = await _streamClient.LocalHueClient.GetEntertainmentGroups(); if (Groups != null && Groups.Count != 0) { UseRoom = Groups.FirstOrDefault(x => x.Id == _config.Model.hueSettings.roomId); } } } }
public static async void HUEInitialize() { bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)); client = new LocalHueClient(bridgeIPs.First()); if (File.Exists(dirPath + @"\appKey.txt")) { appKey = File.ReadAllText(dirPath + @"\appKey.txt"); } if (appKey != null) { client.Initialize(appKey); Connected?.Invoke(); MessageBox.Show("기존의 휴 브릿지에 연결되었습니다."); } else { MessageBox.Show("10초 이내에 휴 브릿지의 링크 버튼을 눌러주세요."); Timer timer = new Timer(); timer.Interval = 1000; timer.Elapsed += Timer_Elapsed; timer.Start(); } }
public HueController(ILogger logger, IConfigurationSection config, ILocalHueClient hueClient) { _logger = logger; _config = config; _hueClient = hueClient; _hueClient.Initialize(config["UserName"]); }
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; }
public FrmLightSetup(ILocalHueClient client) { InitializeComponent(); this._client = client; this._lights = new List <Light>(); _oldSelected = new HashSet <int>(); }
public static void ColorsCycle(ILocalHueClient client, int transitionMs, int msToStay, decimal brightness, List <XYColor> colors) { foreach (var color in colors) { ChangeColor(client, transitionMs, msToStay, color, brightness); } }
static void UpdateHueLegacy(ILocalHueClient hue) { /* IBridgeLocator locator = new HttpBridgeLocator(); * var locateBridges = locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)); * IEnumerable<LocatedBridge> bridgeIPs = locateBridges.Result; * * if (bridgeIPs.Where(B => B.BridgeId == "001788fffe678124").Count() > 0) * { * bridge = new LocalHueClient(bridgeIPs.Where(B => B.BridgeId == "001788fffe678124").First().IpAddress); * var registerOne = bridge.RegisterAsync("LightingLink", "WarMachine"); * //string appKeyOne = registerOne.Result; * bridge.Initialize("NnmhRXVqLmBUw93kmIwi8PPCt6QHgWlHwkTYT9NC"); * }*/ do { for (int lightNum = 1; lightNum <= 13; lightNum++) { Color color = colors[lightNum % 4]; var com1 = new LightCommand(); com1.TransitionTime = TimeSpan.FromMilliseconds(150); com1.SetColor(new RGBColor(color.R, color.G, color.B)); var send1 = hue.SendCommandAsync(com1, new List <string> { lightNum.ToString() }); System.Threading.Thread.Sleep(70); } } while (running); }
public async Task <(string IpAddress, string Key)> Setup() { int retries = HueSetupOptions.MaxAttempts; var ip = ipAddress; if (key == null) { ip = ip ?? await GetBridgeIpForSetup(); string appKey = String.Empty; _logger.LogInformation("Please click on the hue button."); while (string.IsNullOrEmpty(key) && retries >= 0) { Task.Delay(HueSetupOptions.WaitPeriodInMs).Wait(); try { key = await GetAppKeyForSetup(ip); retries--; } catch (Exception) { retries--; _logger.LogInformation($"Waiting... patience level down to {retries}"); } } } _client = new LocalHueClient(ip, key); return(ip, key); }
/// <summary> /// Check if a certain 'user' is already a registered user of the bridge. /// </summary> /// <param name="bridge">The bridge for which to check.</param> /// <param name="appKey">The appkey for the user.</param> /// <returns></returns> public async static Task <bool> ClientAlreadyRegistered(LocatedBridge bridge, string appKey) { ILocalHueClient client = null; try { // see if initialized if ((bridge == null) || String.IsNullOrEmpty(appKey)) { return(false); } client = new LocalHueClient(bridge.IpAddress); client.Initialize(appKey); // Only initializing is not enough to check the appKey, so check: bool isConnected = await client.CheckConnection(); return(isConnected); } catch (Exception ex) { MessageBox.Show(String.Format("Something went while connecting. The error was '{0}'.", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } }
public static void ColorsBreathing(ILocalHueClient client, List <XYColor> colors, decimal lowBrightness, decimal highBrightness) { foreach (var color in colors) { Breathing(client, color, color, lowBrightness, highBrightness); } }
/// <summary> /// Neuen User auf Bridge anlegen /// </summary> /// <param name="bridge">Bridge</param> /// <returns></returns> public async Task <BridgeResult> CreateUser(BridgeInfo bridge) { if (ConnectBridge(bridge) == BridgeResult.SuccessfulConnected) { //TODO Muss Client wieder getrennt werden? return(BridgeResult.UserAlreadyExists); } try { m_HueClient = new LocalHueClient(bridge.IpAddress); var appKey = await m_HueClient.RegisterAsync(APP_NAME, Environment.MachineName); m_AppKeyManager.AddKey(bridge.BridgeId, appKey); m_HueClient.Initialize(appKey); ApiCaller.Host = bridge.IpAddress; ApiCaller.AppKey = appKey; return(BridgeResult.UserCreated); } catch (Exception ex) { if (ex.Message.Contains("Link button not pressed")) { return(BridgeResult.LinkButtonNotPressed); } else { throw ex; } } }
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; } }
public async Task Setup() { string ip = await GetBridgeIp(); hueClient = new LocalHueClient(ip, Secrets.HueUsername); var lights = await hueClient.GetLightsAsync(); foreach (var light in lights) { lightToId.Add(light.Name, light.Id); Lights.Add(light.Name); } var groups = await hueClient.GetGroupsAsync(); foreach (var group in groups) { var name = group.Name; if (name.Contains("Group for")) { continue; } if (Lights.Contains(name)) { name = $"{name} (group)"; } groupToId.Add(name, group.Id); Lights.Add(name); } }
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"); }
public async void InitializeHue() { _isInitialized = false; //initialize client with bridge IP and app GUID _client = new LocalHueClient(BRIDGE_IP); _client.Initialize(APP_ID); //only working with light #1 in this demo _light = await _client.GetLightAsync("1"); _lightList = new List<string>() { "1" }; //initialize UI this.toggle_Power.IsOn = _light.State.On; string hexColor = _light.State.ToHex(); byte brightness = _light.State.Brightness; this.slider_Brightness.Value = brightness; //there seems to be a defect with the color picker, the initial color isn't visually changing the control //from code-behind. I'm leaving this code here in case it is fixed in the future. var rgb = HexToRGB(hexColor); this.color_Picker.SelectedColor = new SolidColorBrush(Color.FromArgb(brightness, rgb[0], rgb[1], rgb[2])); _isInitialized = true; _timer.Start(); }
private async Task WatchButtonPressed(string bridgeIp) { _localHueClient = new LocalHueClient(bridgeIp); while (!_linkedButtonPressed) { try { await Task.Delay(10000); var key = await _localHueClient.RegisterAsync("Neon", "Neon"); Logger.LogInformation($"Button pressed"); _philipHueVault.LocalApiKey = key; SaveVault(_philipHueVault); _linkedButtonPressed = true; Config.LocalConfig.BridgeIpAddress = bridgeIp; SaveConfig(); _localHueClient = new LocalHueClient(bridgeIp, _philipHueVault.LocalApiKey); _isPhilipConfigured = true; } catch { } } }
public async static Task <XYColor> CurrentColor(this ILocalHueClient client) { var light = await client.GetLightAsync(await Utils.GetSingleId(client)); var colorCoords = light.State.ColorCoordinates; return(new XYColor(colorCoords[0], colorCoords[1])); }
public LightManager(ILogger <LightManager> logger, IOptionsMonitor <HueShiftOptions> appOptionsDelegate, IHueClientManager clientManager, ILocalHueClient client) { this.logger = logger; this.appOptionsDelegate = appOptionsDelegate; this.clientManager = clientManager; this.client = client; this.lights = new Dictionary <string, LightControlPair>(); }
public HomeController(ILocalHueClient hueClient, ILoggerFactory loggerFactory, Microsoft.Extensions.Hosting.IHostedService backgroundService, IStorageService storageService, IOptionsMonitor <Options> optionsAccessor) { _hueClient = hueClient; _loggerFactory = loggerFactory; _backgroundService = (BackgroundService)backgroundService; _storageService = storageService; _options = optionsAccessor.CurrentValue; }
public BackgroundService(ILoggerFactory loggerFactory, IStorageService storageService, ILocalHueClient hueClient) { _loggerFactory = loggerFactory; _logger = loggerFactory.CreateLogger <BackgroundService>(); _storageService = storageService; _hueClient = hueClient; _logger.LogDebug("ctor"); }
private async void LocateBridgeAction() { //IEnumerable<string> bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)); client = new LocalHueClient("ip"); var appKey = await client.RegisterAsync("mypersonalappname", "mydevicename"); }
public CustomLightScheduler(ILogger <CustomLightScheduler> logger, IOptionsMonitor <HueShiftOptions> appOptionsDelegate, IOptionsMonitor <CustomScheduleOptions> scheduleOptionsDelegate, IHueClientManager clientManager, ILocalHueClient client) { this.mode = HueShiftMode.Auto; this.logger = logger; this.appOptionsDelegate = appOptionsDelegate; this.clientManager = clientManager; this.client = client; }
public void Disconnect() { hueClient = null; appName = string.Empty; deviceName = string.Empty; hueAppKey = string.Empty; isCompleted = false; isConnected = false; }
public async Task RegisterIfNeeded() { _client = new LocalHueClient(Settings.DefaultBridgeIp); if (string.IsNullOrEmpty(Settings.TheAppKey)) { Settings.TheAppKey = await _client.RegisterAsync(AppName, DeviceName); } }
public Worker(DatabaseContext context, string ipAdress, string appKey) { _context = context; _client = new LocalHueClient(ipAdress); _client.Initialize(appKey); Lights = new List <HueLight>(); Groups = new List <HueScene>(); }
public LocalHueClientManager(ILogger <LocalHueClientManager> logger, IConfiguration configuration, IOptionsMonitor <HueShiftOptions> optionsDelegate, ILocalHueClient client, IConfigFileHelper configHelper) { this.logger = logger; this.configuration = configuration; this.optionsDelegate = optionsDelegate; this.client = client; this.configHelper = configHelper; }
public Q42HueNetwork(HomeAutomationNetworkContext context, string ip, IAppData appData, Action notifyPressLinkButton) : base(context) { _devices = new List <Q42HueDevice>(); Devices = _devices; _client = new LocalHueClient(ip); Connect(appData, notifyPressLinkButton); }
public async Task <string> GetBridgeIpForSetup() { IEnumerable <Q42.HueApi.Models.Bridge.LocatedBridge> bridgeIPs = await _locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)); var ip = bridgeIPs.FirstOrDefault()?.IpAddress; _client = new LocalHueClient(ip); return(ip); }
public Q42HueNetwork(HomeAutomationNetworkContext context, string ip, IAppData appData, Action notifyPressLinkButton) : base(context) { _devices = new List<Q42HueDevice>(); Devices = _devices; _client = new LocalHueClient(ip); Connect(appData, notifyPressLinkButton); }
public RangingVC (IntPtr handle) : base (handle) { SetUpHue (); //set up sqlite db var documents = Environment.GetFolderPath (Environment.SpecialFolder.Personal); _pathToDatabase = Path.Combine (documents, "db_sqlite-net.db"); region = new CLBeaconRegion (AppDelegate.BeaconUUID, "BeaconSample");//ushort.Parse ("26547"), ushort.Parse ("56644"), region.NotifyOnEntry = true; region.NotifyOnExit = true; locationManager = new CLLocationManager (); locationManager.RequestWhenInUseAuthorization (); locationManager.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs e) => { if (e.Beacons.Length > 0) { CLBeacon beacon = e.Beacons [0]; switch (beacon.Proximity) { case CLProximity.Immediate: SetImmediateColor(); message = "Immediate"; break; case CLProximity.Near: message = "Near"; SetNearColor(); break; case CLProximity.Far: message = "Far"; SetFarColor(); break; case CLProximity.Unknown: message = "Unknown"; SetUnknownColor(); break; } if (previousProximity != beacon.Proximity) { Console.WriteLine (message); } previousProximity = beacon.Proximity; } }; locationManager.StartRangingBeacons (region); var db = new SQLite.SQLiteConnection (_pathToDatabase); var bridgeIp = db.Table<HueBridge> ().ToArray (); client = new LocalHueClient (bridgeIp [0].HueBridgeIpAddress); client.Initialize ("pooberry"); }
private async void button4_Click(object sender, EventArgs e) { bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(10)); try { client = new LocalHueClient(bridgeIPs.First().IpAddress); if (!string.IsNullOrEmpty(Properties.Settings.Default.appkey)) { client.Initialize(Properties.Settings.Default.appkey); logEvent("Connected with previous Hue Auth"); } else { string messageBoxText = "Press the button on your Hue bridge and then click Ok."; string caption = "Action Required"; MessageBoxButtons button = MessageBoxButtons.OK; DialogResult result = MessageBox.Show(messageBoxText, caption, button); switch (result) { case DialogResult.OK: var appKey = await client.RegisterAsync("HueLightBot", Environment.MachineName); Properties.Settings.Default.appkey = appKey; Properties.Settings.Default.Save(); logEvent("Connected with new Hue Auth"); break; } } groups = await client.GetGroupsAsync(); List <string> groupNames = groups.Select(x => x.Name).ToList(); comboBox6.DataSource = groupNames; } catch (Exception exception) { string messageBoxText; string caption; if (exception.Message == "Link button not pressed") { messageBoxText = "Link Button not pressed or pairing didn't occur in time. Please try again."; caption = "Error"; } else { messageBoxText = string.Format("An uncaught exception occured. Please let the devs know the following: {0}", Environment.NewLine + exception.Message); caption = "Error"; } MessageBoxButtons button = MessageBoxButtons.OK; DialogResult result = MessageBox.Show(messageBoxText, caption, button); } }
public void ValidHueIpTest() { _client = new LocalHueClient("127.0.0.1"); Assert.IsNotNull(_client); }
async void TryToConnectToBridge () { IBridgeLocator locator = new HttpBridgeLocator (); IEnumerable<string> bridgeIPs = await locator.LocateBridgesAsync (TimeSpan.FromSeconds (5)); var db = new SQLite.SQLiteConnection (_pathToDatabase); try { var bridgeIp = db.Table<HueBridge> ().ToArray (); var appKey = db.Table<HueAppKey> ().ToArray (); client = new LocalHueClient (bridgeIp [0].HueBridgeIpAddress); client.Initialize (appKey [0].AppId); } catch { var alert = new UIAlertView ("Hangon!", "First, press the button on the Hue bridge. Then tap 'Connect' in the app.", null, "OK"); alert.Show (); Console.WriteLine ("First, connect to bridge"); } }
async void ConnectBridgeClicked (object sender, EventArgs e) { IBridgeLocator locator = new HttpBridgeLocator (); IEnumerable<string> bridgeIPs = await locator.LocateBridgesAsync (TimeSpan.FromSeconds (5)); IpAddress = bridgeIPs.FirstOrDefault (); client = new LocalHueClient (IpAddress); var appKey = new HueAppKey{ AppId = await client.RegisterAsync ("pooberry", "iphone") }; var bridgeIp = new HueBridge { HueBridgeIpAddress = IpAddress }; var conn = new SQLite.SQLiteConnection (_pathToDatabase); //set up bridge table conn.CreateTable<HueBridge> (); conn.DeleteAll<HueBridge> (); //set up app key table conn.CreateTable<HueAppKey> (); conn.DeleteAll<HueAppKey> (); //insert app key and bridge ip into database var db = new SQLite.SQLiteConnection (_pathToDatabase); db.Insert (bridgeIp); db.Insert (appKey); var alert = new UIAlertView ("Success!", "Feel free to play with your lights!", null, "OK"); alert.Show (); }
public void InValidHueIpTest() { _client = new LocalHueClient("//127.0.0@@.1in.v.alid"); }