private async void DoBlinkLoop() { if (await client.CheckConnection() == true) { var commandLoopOn = new LightCommand(); commandLoopOn.Effect = Effect.ColorLoop; var commandLoopOff = new LightCommand(); commandLoopOff.Effect = Effect.None; var commandBlink = new LightCommand(); commandBlink.Alert = Alert.Multiple; Q42.HueApi.Models.Groups.Group selectedGroup = getSelectedGroup(); await client.SendCommandAsync(commandLoopOn, selectedGroup.Lights); await client.SendCommandAsync(commandBlink, selectedGroup.Lights); int loopDuration = Convert.ToInt32(Properties.Settings.Default.colorLoopDuration) * 1000; Thread.Sleep(loopDuration); await client.SendCommandAsync(commandLoopOff, selectedGroup.Lights); logEvent("Doing a Color Looping blink", true); } }
public void SetBulbColor(int redComponent, int greenComponent, int blueComponent, string bulbID = "", Action callbackMethod = null) { try { Task setColorTask = new Task(async() => { if ((hueClient != null) && (await hueClient.CheckConnection() == true)) { if (colorBulbs.Count > 0) { List <string> bulbIDs = new List <string>(); LightCommand lightCommand = new LightCommand(); if (bulbID == string.Empty) { for (int i = 0; i < colorBulbs.Count; i++) { bulbIDs.Add(colorBulbs[i].Id); } } else { bulbIDs.Add(bulbID); } lightCommand.TurnOn(); lightCommand.SetColor(HueColorConverter.XyFromColor(redComponent, greenComponent, blueComponent).x, HueColorConverter.XyFromColor(redComponent, greenComponent, blueComponent).y); lightCommand.Brightness = 200; await hueClient.SendCommandAsync(lightCommand, bulbIDs); } callbackMethod?.Invoke(); } else { errorLog += "\r\n\r\n" + DateTime.Now.ToString() + ": Philips Hue bridge is not connected."; callbackMethod?.Invoke(); } }); setColorTask.Start(); } catch (Exception setColorException) { errorLog += "\r\n\r\n" + DateTime.Now.ToString() + ": " + setColorException; callbackMethod?.Invoke(); } }
/// <summary> /// Checks connection and adjusts communication delay dynamically. /// </summary> /// <returns></returns> public async Task CheckConnection() { long startTimestamp = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); long deltaTimestamp = 0; long adjustedPing = 0; bool connectionResult = await hueClient.CheckConnection(); //update connection status BridgeConnected = connectionResult; if (connectionResult == true) { deltaTimestamp = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) - startTimestamp; adjustedPing = (int)Math.Round((int)deltaTimestamp * bridgecommunicationdelayFactor); if (adjustedPing > bridgecommunicationminimumDelay) { bridgecommunicationDelay = (int)adjustedPing; Log.Write("PhilipsHueController.CheckConnection IP=" + BridgeIP + "... current connection lag =" + deltaTimestamp + "ms, recalibrating from " + bridgecommunicationDelay + "ms -> " + deltaTimestamp + "ms, buffer factor=" + bridgecommunicationdelayFactor + " -> " + adjustedPing + "ms"); } else { bridgecommunicationDelay = bridgecommunicationminimumDelay; Log.Write("PhilipsHueController.CheckConnection IP=" + BridgeIP + "... current connection lag =" + deltaTimestamp + "ms, ignoring and using minimum " + bridgecommunicationminimumDelay + "ms to avoid bridge overload"); } } else { Log.Write("PhilipsHueController.CheckConnection... lost connection, or unable to connect to bridge using BridgeIP=" + BridgeIP + " and BridgeKey=" + BridgeKey + "... will ignore for now and attempt reconnecting every " + bridgecommunicationPing + "ms"); } }
public async Task AssertConnected() { if (!await client.CheckConnection()) { if (string.IsNullOrEmpty(optionsDelegate.CurrentValue.BridgeProperties.ApiKey)) { var cts = new CancellationTokenSource(); const int cancelAfter = 120; const double retryInterval = 10.0; try { cts.CancelAfter(cancelAfter * 1000); optionsDelegate.CurrentValue.BridgeProperties.ApiKey = await RegisterApplication(retryInterval, cts.Token); } catch (Exception e) { logger.LogError(e, $"Application failed to register with bridge: timed out after {cancelAfter}s"); throw; } } try { client.Initialize(optionsDelegate.CurrentValue.BridgeProperties.ApiKey); logger.LogInformation("Hue client initialised."); } catch (Exception e) { logger.LogError($"Failed to initialise Hue client", e); throw; } } return; }
public async void HueRestoreState() { var connect = await _client.CheckConnection(); if (connect) { foreach (var d in _HueBulbsRestore) { try { var state = d.Value; var command = new LightCommand(); command.Brightness = state.Brightness; command.ColorCoordinates = state.ColorCoordinates; command.ColorTemperature = state.ColorTemperature; command.Hue = state.Hue; command.On = state.On; command.Saturation = state.Saturation; await _client.SendCommandAsync(command, new List <string> { d.Key.Id }); //Unsure if Id or UniqueId should be used Write.WriteConsole(ConsoleTypes.Hue, @"Restoring HUE Bulb " + d.Key.Name); //Thread.Sleep(500); } catch (Exception ex) { Write.WriteConsole(ConsoleTypes.Hue, "An Error occurred while restoring HUE Bulb " + d.Key.Name + ". Error: " + ex.Message); } } } else { Write.WriteConsole(ConsoleTypes.Hue, @"Unable to connect to HUE Hub."); } }
public void clientConnection() { if (ip != null) //If the user has selected a hub. { if (client == null) //If the user has selected a hub but the connection hasnt been attempted yet then make one. { client = new LocalHueClient(ip); } else if (client.CheckConnection().Result == false) //If the connection has been made already check to ensure the user is still connected. { txtResults.BackColor = Color.Red; //Show error. txtResults.Show(); txtResults.Text = "Connection failed, please make sure you are connected to the internet and have pressed connect."; } } else //If their is no hubs available then display an error. { txtResults.BackColor = Color.Red; txtResults.Show(); txtResults.Text = "No hubs found, please try again."; } }
/// <summary> /// When the OK button is pressed, try to connect a bridge. If there is a checked /// item in the listbox, use that. Otherwise use the first item. /// </summary> private async void buttonOK_Click(object sender, EventArgs e) { try { LocatedBridge bridge = null; if (checkedListBoxBridges.CheckedItems.Count > 0) { bridge = checkedListBoxBridges.CheckedItems[0] as LocatedBridge; } else if (checkedListBoxBridges.Items.Count > 0) { bridge = checkedListBoxBridges.Items[0] as LocatedBridge; } if (bridge != null) { client = new LocalHueClient(bridge.IpAddress); client.Initialize(appKey); if (!await client.CheckConnection()) { MessageBox.Show("Could not connect client. This might be caused by an invalid application key.\n\n" + "Other parts of the application will not work.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); client = null; } this.Close(); } else { if (MessageBox.Show("No client connected. Other parts of the application will not work. Continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { this.Close(); } } } catch (Exception ex) { MessageBox.Show(String.Format("Something went wrong while connecting. The error was '{0}'.", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Connect(Action callbackMethod) { Task connectionTask; deviceName = (String.IsNullOrWhiteSpace(deviceName) ? "iOS_" + CCRandom.GetRandomInt(0, 100) : deviceName); isCompleted = false; isConnected = false; connectionTask = new Task(async() => { int locatorTimeout = bridgeLocatorTimeout; Exception currentException = new Exception(); IBridgeLocator bridgeLocator = new HttpBridgeLocator(); IEnumerable <LocatedBridge> locatedBridges = new List <LocatedBridge>(); try { locatedBridges = await bridgeLocator.LocateBridgesAsync(TimeSpan.FromSeconds(locatorTimeout)); if (((List <LocatedBridge>)locatedBridges).Count > 0) { while (((currentException.Source == null) || (currentException.Message == "Link button not pressed")) && (locatorTimeout >= 0)) { try { hueClient = new LocalHueClient(((List <LocatedBridge>)locatedBridges)[0].IpAddress); if (hueClient != null) { if (await hueClient.CheckConnection() == false) { if (String.IsNullOrWhiteSpace(hueAppKey) == true) { hueAppKey = await hueClient.RegisterAsync(appName, deviceName); } if (String.IsNullOrWhiteSpace(hueAppKey) == false) { hueClient.Initialize(hueAppKey); colorBulbs = ((List <Light>) await hueClient.GetLightsAsync()); for (int i = 0; i < colorBulbs.Count; i++) { if (colorBulbs[i].Type != "Extended color light") { colorBulbs.RemoveAt(i); i--; } } isConnected = true; break; } } else { break; } } } catch (Exception connectionException) { currentException = connectionException; } await Task.Delay(1000); locatorTimeout--; } } } catch (Exception bridgeLocatorException) { currentException = bridgeLocatorException; } isCompleted = true; callbackMethod(); }); connectionTask.Start(); }
public async Task CheckConnectionTest() { var result = await _client.CheckConnection(); Assert.IsTrue(result); }