/// <summary> /// If the app key is already know to the bridge, only initialize the client. /// Otherwise register the client and initialize. /// </summary> private async void buttonRegister_Click(object sender, EventArgs e) { foreach (var b in checkedListBoxBridges.CheckedItems) { LocatedBridge bridge = (LocatedBridge)b; // Check if already registered: bool ok = await Util.ClientAlreadyRegistered(bridge, appKey); ILocalHueClient client = new LocalHueClient(bridge.IpAddress); if (ok) { client.Initialize(appKey); } else { string computerName = System.Environment.MachineName; // Make sure the user has pressed the button on the bridge before calling RegisterAsync // It will throw an LinkButtonNotPressedException if the user did not press the button appKey = await client.RegisterAsync("Q42", computerName); client.Initialize(appKey); saveAppKey(appKey); } } }
private async Task <string> GetApiKeyWithBridgeButtonClick(PhilipsHueBridge bridge) { var endTime = DateTime.UtcNow.AddSeconds(30); var client = new LocalHueClient(bridge.IpAddress); while (DateTime.UtcNow < endTime) { try { var machineName = Environment.MachineName.Replace(' ', '_'); if (machineName.Length > 19) { machineName = machineName.Substring(0, 19); } var appKey = await client.RegisterAsync("Xpressive.Home", machineName); return(appKey); } catch { } await Task.Delay(TimeSpan.FromSeconds(1)); } return(null); }
public static async Task <List <MultiBridgeLightLocation> > GetLocationsAsync(string groupName) { var configSection = await GetGroupConfigurationsAsync(); var currentGroup = configSection.Where(x => x.Name == groupName).FirstOrDefault(); var locations = new List <MultiBridgeLightLocation>(); if (currentGroup == null) { return(locations); } foreach (var bridgeConfig in currentGroup.Connections) { var localClient = new LocalHueClient(bridgeConfig.Ip, bridgeConfig.Key); var group = await localClient.GetGroupAsync(bridgeConfig.GroupId); if (group?.Type != GroupType.Entertainment) { continue; } locations.AddRange(group.Locations.Select(x => new MultiBridgeLightLocation() { Bridge = bridgeConfig.Ip, GroupId = bridgeConfig.GroupId, Id = x.Key, X = x.Value.X, Y = x.Value.Y })); } return(locations); }
public async Task <string> PairAsync(string id, CancellationToken cancellation) { if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentException($"'{nameof (id)}' cannot be null or whitespace", nameof(id)); } string pairing; var client = new LocalHueClient(id); while (true) { cancellation.ThrowIfCancellationRequested(); try { pairing = await client.RegisterAsync("Aura", Environment.MachineName); break; } catch (LinkButtonNotPressedException) { await Task.Delay(100); } } lock (this.clients) { this.clients.Add(client); } return(pairing); }
public static async Task syncAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); Debug.Log("Scanning network for bridge"); string bridge; try { bridge = await FindBridge(); if (bridge == null) { Debug.Log("No bridge found!"); return; } token.ThrowIfCancellationRequested(); Debug.Log(bridge); Debug.Log("Found bridge, pairing..."); var keys = await LocalHueClient.RegisterAsync(bridge, "Chroma", "BeatSaber", true); Debug.Log("Bridge paired!"); token.ThrowIfCancellationRequested(); Settings.ChromaConfig.Instance.setAppKey(keys.Username); Settings.ChromaConfig.Instance.setClientKey(keys.StreamingClientKey); Debug.Log(keys.Username); Debug.Log(keys.StreamingClientKey); await connect(token, bridge); } catch (Exception) { Debug.Log("Something went wrong!"); throw; } }
private async Task UpdateBulbVariablesAsync(LocalHueClient client, List <PhilipsHueBulb> bulbs) { var lights = await client.GetLightsAsync(); foreach (var light in lights) { var bulb = bulbs.SingleOrDefault(b => IsEqual(b, light)); if (bulb == null) { continue; } var state = light.State; var brightness = state.Brightness / 255d; var temperature = state.ColorTemperature ?? 0; if (temperature != 0) { temperature = MirekToKelvin(temperature); } bulb.IsOn = state.On; UpdateVariable($"{Name}.{bulb.Id}.Brightness", Math.Round(brightness, 2), "%"); UpdateVariable($"{Name}.{bulb.Id}.IsOn", state.On); UpdateVariable($"{Name}.{bulb.Id}.IsReachable", state.IsReachable); UpdateVariable($"{Name}.{bulb.Id}.Name", light.Name); UpdateVariable($"{Name}.{bulb.Id}.ColorTemperature", (double)temperature); } }
public static async Task <Light> GetLight(string id) { ILocalHueClient client = new LocalHueClient(AppSettings.Instance.DeviceIPAddress, AppSettings.Instance.UserKey); var light = await client.GetLightAsync(id); return(light); }
public HueClient(HueUser user) { this.user = user; bridge = user.Bridge; client = new LocalHueClient(bridge.Config.IpAddress); client.Initialize(user.Token.AccessToken); }
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 <IEnumerable <Light> > GetLights() { ILocalHueClient client = new LocalHueClient(AppSettings.Instance.DeviceIPAddress, AppSettings.Instance.UserKey); var lights = await client.GetLightsAsync(); return(lights); }
private async Task Register() { await Policy .Handle <LinkButtonNotPressedException>() .WaitAndRetryAsync( 30, i => TimeSpan.FromSeconds(2)) .ExecuteAsync(async() => { var registered = await LocalHueClient.RegisterAsync(this.bridge.IpAddress, nameof(HueGame), "JuniorGameBox", true); var connectionProperties = new HueConnectionProperties { AppKey = registered.Username, StreamingKey = registered.StreamingClientKey }; File.WriteAllText( this.FileName, JsonConvert.SerializeObject(connectionProperties)); await this.Connect(); }); }
/// <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); }
public void TryRegister() { Debug.Log("Trying to register"); try { var result = LocalHueClient.RegisterAsync(ApplicationState.Instance.HueBridgeIp, ApplicationName, DeviceName, true).Result; ApplicationState.Instance.Profile.HueKey = result.Username; ApplicationState.Instance.Profile.HueStreamingKey = result.StreamingClientKey; CancelInvoke("TryRegister"); // Save registration keys to profile ApplicationState.Instance.SaveProfile(); Debug.Log($"Registered: user - {result.Username}, streaming key - {result.StreamingClientKey}"); // Move to entertainment group selection ExecuteEvents.ExecuteHierarchy <ISwitchScreenHandler>(gameObject, null, (x, y) => x.SwitchScreen(ScreenType.EntertainmentGroupSelection)); } catch (Exception ex) { Debug.Log(ex.ToString()); } }
private async Task <LocalHueClient> RegisterAsync(string appName, string deviceName) { try { var locatedBridge = await LocateAsync(); if (locatedBridge == null) { Log.Error($"Failed to locate bridge with ip '{Options.Value.PhilipsHue.BridgeIp}' ... won't connect."); return(null); } var client = new LocalHueClient(locatedBridge.IpAddress); var appKey = await client.RegisterAsync(appName, deviceName); if (!m_Credentials.TryPersistHueAppKey(appKey)) { return(null); } return(client); } catch (LinkButtonNotPressedException linkButtonNotPressedException) { Log.Error(linkButtonNotPressedException, $"You must press button on bridge first time before connecting!"); throw; } catch (Exception exception) { Log.Error(exception, $"Failed to register app to bridge '{exception.Message}'"); return(null); } }
public static async Task AlertLight(MultiBridgeLightLocation light) { var configSection = await GetGroupConfigurationsAsync(); var config = configSection.Where(x => x.Connections.Any(c => c.Ip == light.Bridge)).FirstOrDefault(); if (config != null) { foreach (var conn in config.Connections) { var client = new LocalHueClient(conn.Ip, conn.Key); var allCommand = new LightCommand().TurnOn().SetColor(new RGBColor("0000FF")); //All blue await client.SendGroupCommandAsync(allCommand, conn.GroupId); //Only selected light red if (conn.Ip == light.Bridge) { var alertCommand = new LightCommand().TurnOn().SetColor(new RGBColor("FF0000"));; alertCommand.Alert = Alert.Once; await client.SendCommandAsync(alertCommand, new List <string> { light.Id }); } } } }
/// <summary> /// Registers an app to a device and returns the appKey /// </summary> /// <param name="bridgeIp"></param> /// <param name="appName">Must not contain spaces</param> /// <param name="device">Must not contain spaces</param> public async static Task <string> RegisterApp(string bridgeIp, string appName, string device) { ILocalHueClient client = new LocalHueClient(bridgeIp); var appKey = await client.RegisterAsync(appName, device); return(appKey); }
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~"); }
static async Task RunLightCommand02() { LocalHueClient client = await HueManager.GetClient(); if (client == null) { return; } var command = new LightCommand(); // some random settings for tests command.SetColor(new RGBColor(255, 255, 255)); client.SendCommandAsync(command); Thread.Sleep(1000); command.TurnOff(); client.SendCommandAsync(command); Thread.Sleep(1000); command.TurnOn(); client.SendCommandAsync(command); Thread.Sleep(1000); command.TurnOff(); client.SendCommandAsync(command); Thread.Sleep(1000); command.TurnOn(); client.SendCommandAsync(command); Thread.Sleep(1000); command.SetColor(new RGBColor(127, 0, 255)); client.SendCommandAsync(command); }
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; } }
ILocalHueClient Initialize(LocatedBridge bridge) { var client = new LocalHueClient(bridge.IpAddress); client.Initialize(_key); return(client); }
public HueUtils() { //LocateBridgeAction(); ILocalHueClient client = new LocalHueClient("192.168.1.92"); GetAppKey(); }
public async Task <IEnumerable <Light> > GetLights() { try { if (_client == null) { _client = new LocalHueClient(_options.LightSettings.Hue.HueIpAddress); _client.Initialize(_options.LightSettings.Hue.HueApiKey); } var lights = await _client.GetLightsAsync(); // if there are no lights, get some if (!lights.Any()) { await _client.SearchNewLightsAsync(); Thread.Sleep(40000); lights = await _client.GetNewLightsAsync(); } return(lights); } catch (Exception e) { _logger.LogError(e, "Error Occurred Getting Bridge", e); throw; } }
private async Task FindSensorsAsync(LocalHueClient client, PhilipsHueBridge bridge) { var sensors = await client.GetSensorsAsync(); if (sensors != null) { foreach (var sensor in sensors) { switch (sensor.Type.ToLowerInvariant()) { case "zllpresence": HandleZllPresenceSensor(sensor, bridge); break; case "zgpswitch": HandleZgpSwitch(sensor, bridge); break; case "zllswitch": HandleZllSwitch(sensor, bridge); break; default: Debug.WriteLine(sensor.Type); break; } } } }
public async Task <IActionResult> SelectBridge([FromBody] HueBridge hueBridge) { if (hueBridge == null || string.IsNullOrWhiteSpace(hueBridge.Ip)) { return(BadRequest("invalid hue bridge settings")); } var client = new LocalHueClient(hueBridge.Ip); for (int i = 0; i <= 10; i++) { try { var appKey = await client.RegisterAsync("NuimoHub", Environment.GetEnvironmentVariable("COMPUTERNAME")); hueBridge.AppKey = appKey; var newHueOptions = new HueOptions { Bridge = hueBridge }; _nuimoOptionsWriter.SetHueOptions(newHueOptions); return(Ok($"hue bridge at {hueBridge.Ip} added; appKey is {appKey}")); } catch (System.Exception) { Debug.WriteLine("Button was not pressed."); await Task.Delay(3000); } } return(Unauthorized()); }
public async Task <ConnectionConfiguration> Register([FromForm] string ip) { var hueClient = new LocalHueClient(ip); var result = await hueClient.RegisterAsync("HueLightDJ", "Web", generateClientKey : true); if (result == null) { throw new Exception("No result from bridge"); } var allLights = await hueClient.GetLightsAsync(); string?groupId = "GroupId"; if (allLights.Any()) { groupId = await hueClient.CreateGroupAsync(allLights.Take(10).Select(x => x.Id), "Hue Light DJ group", Q42.HueApi.Models.Groups.RoomClass.TV, Q42.HueApi.Models.Groups.GroupType.Entertainment); } var connection = new ConnectionConfiguration() { Ip = ip, UseSimulator = false, Key = result.Username, EntertainmentKey = result.StreamingClientKey, GroupId = groupId }; return(connection); }
private async Task SetPausedLighting() { var bridge = (await new BridgeDiscoveryService().DiscoverBridges()).First(); var client = new LocalHueClient(bridge, hueUser); await client.SetSceneAsync(stoppedScene, theatreRoom); }
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."); } }
public async Task Sync(CancellationToken token) { string bridge; try { token.ThrowIfCancellationRequested(); bridge = await FindBridge(); if (bridge == null) { log.Error("No bridge found!"); return; } token.ThrowIfCancellationRequested(); log.Info("Found bridge, pairing..."); var keys = await LocalHueClient.RegisterAsync(bridge, "HueSaber", "BeatSaber", true); log.Info("Successfully paired!"); token.ThrowIfCancellationRequested(); prefs.SetString("HueSaber", "appKey", keys.Username); prefs.SetString("HueSaber", "clientKey", keys.StreamingClientKey); log.Info("Starting HueSaber..."); } catch (Exception ex) { log.Error(ex); throw; } await Run(token, bridge); }
/// <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 async Task GetConfig() { var result = await FindBridge(); SetConfig("ip", result); //user not set up if (ConfigurationManager.AppSettings["key"].Length == 0) { try { ILocalHueClient client = new LocalHueClient(result); var appKey = await client.RegisterAsync("LightEQ", System.Net.Dns.GetHostName()); SetConfig("key", appKey); HueKey = appKey; } catch { MessageBox.Show("Press thue Hue Bridge push-link button."); ILocalHueClient client = new LocalHueClient(result); var appKey = await client.RegisterAsync("LightEQ", System.Net.Dns.GetHostName()); SetConfig("key", appKey); HueKey = appKey; } //Save the app key for later use } }
public async Task CheckConnectionWrongIpTest() { ILocalHueClient client = new LocalHueClient("42.1.1.1", ConfigurationManager.AppSettings["key"].ToString()); var result = await client.CheckConnection(); Assert.IsFalse(result); }
public async Task CheckConnectionWrongKeyTest() { ILocalHueClient client = new LocalHueClient(ConfigurationManager.AppSettings["ip"].ToString(), "wrongkey123"); var result = await client.CheckConnection(); Assert.IsFalse(result); }
internal void ManualRegister(string ip) { _hueClient = new LocalHueClient(ip); }
private async void LocateBridgeAction() { var result = await LocateBridgeDataLoader.LoadAsync(() => httpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5))); HttpBridges = string.Join(", ", result.ToArray()); if (result.Count() > 0) _hueClient = new LocalHueClient(result.First()); }
private async void SsdpLocateBridgeAction() { var result = await SsdpLocateBridgeDataLoader.LoadAsync(() => ssdpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5))); if (result == null) result = new List<string>(); SsdpBridges = string.Join(", ", result.ToArray()); if (result.Count() > 0) _hueClient = new LocalHueClient(result.First()); }