private async Task <HueResults> ChangeBrightness(double brightness = -1) { double b = 0; HueResults retVal = null; if (brightness != -1) { b = brightness; } else { b = this.Brightness; } if (brightness == 0) { retVal = await TurnOff(); } else { retVal = await SwitchState(brightness : b); } return(retVal); }
/// <summary> /// /// </summary> /// <param name="client"></param> /// <param name="lightsToScan"></param> /// <param name="colorTemperature"></param> /// <param name="transitiontime"></param> private async Task ModifyFluxLights( HueClient hueClient, IEnumerable <Light> lights, Primitives.ColorTemperature newColorTemperature, Primitives.Brightness newBrightness) { lights = lights.Where(light => light.State.On && light.IsFluxControlled()); Dictionary <LightCommand, IList <string> > lightGroups = CalculateLightCommands(lights, newColorTemperature, newBrightness); // Send the light update command foreach (KeyValuePair <LightCommand, IList <string> > lightGroup in lightGroups) { try { HueResults result = await hueClient.SendCommandAsync(lightGroup.Key, lightGroup.Value); IEnumerable <string> lightNames = lightGroup.Value .Select(lightId => lights.Single(light => light.Id.Equals(lightId, StringComparison.OrdinalIgnoreCase)).Name) ?.Take(4); Log.Info($"'{nameof(ModifyFluxLights)}' set '{lightGroup.Value.Count()}' lights to color temperature {(lightGroup.Key.ColorTemperature.HasValue ? $"'{lightGroup.Key.ColorTemperature}'" : "'null'")} and brightness {(lightGroup.Key.Brightness.HasValue ? $"'{lightGroup.Key.Brightness}'" : "'null'")} for lights '{string.Join(", ", lightNames)}', IDs '{string.Join(", ", lightGroup.Value)}'."); } catch (Exception exception) { Log.Error($"Exception: '{nameof(ModifyFluxLights)}' exception for '{string.Join(", ", lightGroup.Value)}'. {exception.Message}"); } } }
private async Task <HueResults> MouseHue() { HueResults retVal = null; if (IsOn && Mouse.LeftButton == System.Windows.Input.MouseButtonState.Pressed) { float lHue = 0; float mX = 0; //mX = System.Windows.Forms.Control.MousePosition.X; // gets mouse position on screen Point position = Mouse.GetPosition(MainGrid); mX = (float)position.X; Console.WriteLine(mX); Console.WriteLine("MarginLeft: " + (float)MainGrid.Margin.Left); Console.WriteLine("MarginRight: " + ((float)MainGrid.Width + (float)MainGrid.Margin.Left)); lHue = map(mX, (float)MainGrid.Margin.Left, (float)MainGrid.Width - (float)BulbEmitingLight.Margin.Right, 10, 1000); Console.WriteLine(lHue); Console.WriteLine(); colorSlider.Value = lHue; retVal = await ChangeHue(); } return(retVal); }
/// <summary> /// Send a json command to a list of lights /// </summary> /// <param name="command"></param> /// <param name="lightList">if null, send command to all lights</param> /// <returns></returns> public async Task <HueResults> SendCommandRawAsync(string command, IEnumerable <string> lightList = null) { if (command == null) { throw new ArgumentNullException(nameof(command)); } CheckInitialized(); if (lightList == null || !lightList.Any()) { //Group 0 always contains all the lights return(await SendGroupCommandAsync(command).ConfigureAwait(false)); } else { HueResults results = new HueResults(); await lightList.ForEachAsync(_parallelRequests, async (lightId) => { HttpClient client = await GetHttpClient().ConfigureAwait(false); var result = await client.PutAsync(new Uri(ApiBase + string.Format("lights/{0}/state", lightId)), new JsonContent(command)).ConfigureAwait(false); string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); results.AddRange(DeserializeDefaultHueResult(jsonResult)); }).ConfigureAwait(false); return(results); } }
/// <summary> /// Create a group for a list of lights /// </summary> /// <param name="lights"></param> /// <returns></returns> public async Task<string> CreateGroupAsync(IEnumerable<string> lights, string name = null) { CheckInitialized(); if (lights == null) throw new ArgumentNullException("lights"); dynamic jsonObj = new ExpandoObject(); jsonObj.lights = lights; if (!string.IsNullOrEmpty(name)) jsonObj.name = name; string jsonString = JsonConvert.SerializeObject(jsonObj); HttpClient client = new HttpClient(); //Create group with the lights we want to target var response = await client.PostAsync(new Uri(String.Format("{0}groups", ApiBase)), new StringContent(jsonString)).ConfigureAwait(false); var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); HueResults groupResult = DeserializeDefaultHueResult(jsonResult); if (groupResult.Count > 0 && groupResult[0].Success != null && !string.IsNullOrEmpty(groupResult[0].Success.Id)) { return groupResult[0].Success.Id.Replace("/groups/", string.Empty); } if (groupResult.HasErrors()) throw new Exception(groupResult.Errors.First().Error.Description); return null; }
public async Task <HueResults> TurnOn() { HueResults retVal = null; if (!IsOn) { retVal = await SwitchState(true); } return(retVal); }
private async Task <HueResults> TurnOff() { HueResults retVal = null; if (IsOn) { retVal = await SwitchState(false); } return(retVal); }
private async Task <HueResults> ChangeHue() { HueResults retVal = null; //colorSlider.SelectedColor RGBColor hue = new RGBColor(colorSlider.SelectedColor.R, colorSlider.SelectedColor.G, colorSlider.SelectedColor.B); retVal = await SwitchState(hue : hue); return(retVal); }
public async Task <string> CreateSceneAsync(Scene scene) { CheckInitialized(); if (scene == null) { throw new ArgumentNullException(nameof(scene)); } if (scene.Lights == null) { throw new ArgumentNullException(nameof(scene.Lights)); } if (scene.Name == null) { throw new ArgumentNullException(nameof(scene.Name)); } //Filter non updatable properties scene.FilterNonUpdatableProperties(); //It defaults to false, but fails when omitted //https://github.com/Q42/Q42.HueApi/issues/56 if (!scene.Recycle.HasValue) { scene.Recycle = false; } string jsonString = JsonConvert.SerializeObject(scene, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); var response = await client.PostAsync(new Uri(String.Format("{0}scenes", ApiBase)), new JsonContent(jsonString)).ConfigureAwait(false); var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); HueResults sceneResult = DeserializeDefaultHueResult(jsonResult); if (sceneResult.Count > 0 && sceneResult[0].Success != null && !string.IsNullOrEmpty(sceneResult[0].Success.Id)) { return(sceneResult[0].Success.Id); } if (sceneResult.HasErrors()) { throw new Exception(sceneResult.Errors.First().Error.Description); } return(null); }
public async Task ApplyScene(string id, CancellationToken cancellationToken) { SceneCommand sceneCommand = new SceneCommand(id); HueResults results = await _hueClient.SendGroupCommandAsync(sceneCommand); DefaultHueResult?defaultHueResult = results.Errors.FirstOrDefault(); if (defaultHueResult != null) { throw new HueCommandException(defaultHueResult.Error.Description, HttpStatusCode.BadRequest); } }
/// <summary> /// Create a group for a list of lights /// </summary> /// <param name="lights">List of lights in the group</param> /// <param name="name">Optional name</param> /// <param name="roomClass">for room creation the room class has to be passed, without class it will get the default: "Other" class.</param> /// <returns></returns> public async Task <string> CreateGroupAsync(IEnumerable <string> lights, string name = null, RoomClass?roomClass = null, GroupType groupType = GroupType.Room) { CheckInitialized(); if (lights == null) { throw new ArgumentNullException(nameof(lights)); } CreateGroupRequest jsonObj = new CreateGroupRequest(); jsonObj.Lights = lights; if (!string.IsNullOrEmpty(name)) { jsonObj.Name = name; } if (roomClass.HasValue) { jsonObj.Class = roomClass.Value; } jsonObj.Type = groupType; string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); //Create group with the lights we want to target var response = await client.PostAsync(new Uri(String.Format("{0}groups", ApiBase)), new JsonContent(jsonString)).ConfigureAwait(false); var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); HueResults groupResult = DeserializeDefaultHueResult(jsonResult); if (groupResult.Count > 0 && groupResult[0].Success != null && !string.IsNullOrEmpty(groupResult[0].Success.Id)) { return(groupResult[0].Success.Id.Replace("/groups/", string.Empty)); } if (groupResult.HasErrors()) { throw new Exception(groupResult.Errors.First().Error.Description); } return(null); }
/// <summary> /// Send a json command to a list of lights /// </summary> /// <param name="command"></param> /// <param name="lightList">if null, send command to all lights</param> /// <returns></returns> public async Task <HueResults> SendCommandRawAsync(string command, IEnumerable <string>?lightList = null) { if (command == null) { throw new ArgumentNullException(nameof(command)); } CheckInitialized(); if (lightList == null || !lightList.Any()) { //Group 0 always contains all the lights return(await SendGroupCommandAsync(command).ConfigureAwait(false)); } else { BlockingCollection <DefaultHueResult> results = new BlockingCollection <DefaultHueResult>(); HttpClient client = await GetHttpClient().ConfigureAwait(false); await lightList.ForEachAsync(_parallelRequests, async (lightId) => { try { var result = await client.PutAsync(new Uri(ApiBase + $"lights/{lightId}/state"), new JsonContent(command)).ConfigureAwait(false); string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); var hueResults = DeserializeDefaultHueResult(jsonResult); foreach (var hueResult in hueResults) { results.Add(hueResult); } } catch (Exception ex) { results.Add(new DefaultHueResult() { Error = new ErrorResult() { Address = $"lights/{lightId}/state", Description = ex.ToString() } });; } }).ConfigureAwait(false); HueResults hueResults = new HueResults(); hueResults.AddRange(results); return(hueResults); } }
private async void allLightsOn() { var command = new LightCommand(); command.On = true; command.Brightness = 254; // to avoid switching on and still see nothing HueResults results = await client.SendCommandAsync(command); statusLabel.Text = gatherResults(results); foreach (System.Windows.Forms.Control control in flowLayoutPanel.Controls) { LightControl lc = (LightControl)control; lc.Resync(); } }
private async void allLightsOff() { var command = new LightCommand(); command.On = false; Task <HueResults> task = client.SendCommandAsync(command); HueResults results = await task; statusLabel.Text = gatherResults(results); foreach (System.Windows.Forms.Control control in flowLayoutPanel.Controls) { LightControl lc = (LightControl)control; lc.Resync(); } }
protected static HueResults DeserializeDefaultHueResult(string json) { HueResults result = new HueResults(); try { result = JsonConvert.DeserializeObject <HueResults>(json); } catch (JsonSerializationException) { //Ignore JsonSerializationException } return(result); }
public async Task SwitchLights(IEnumerable <string> ids, bool on, CancellationToken cancellationToken) { LightCommand onCommand = new LightCommand() { On = @on }; HueResults hueResults = await _hueClient.SendCommandAsync(onCommand, ids); DefaultHueResult?defaultHueResult = hueResults.Errors.FirstOrDefault(); if (defaultHueResult != null) { throw new HueCommandException(defaultHueResult.Error.Description, HttpStatusCode.BadRequest); } }
public async Task <HueResults> SendCommandRawAsync(string command, string specifiedLight) { if (command == null) { throw new ArgumentNullException(nameof(command)); } HueResults results = new HueResults(); HttpResponseMessage result = await client.PutAsync(new Uri(ApiBase + string.Format("lights/{0}/state", specifiedLight)), new JsonContent(command)).ConfigureAwait(false); string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false); return(DeserializeDefaultHueResult(jsonResult)); }
//Blink lightes to test if connection was possible private async Task BlinkLights() { try { var command = new LightCommand(); command.Alert = Alert.Once; if (client != null) { HueResults results = await client.SendCommandAsync(command); } } catch (Exception e) { return; } }
private string gatherResults(HueResults results) { StringBuilder sb = new StringBuilder("Results:"); foreach (var res in results) { if (res.Error != null) { sb.Append(String.Format("Error: {0} at {1} : {2} ", res.Error.Type, res.Error.Address, res.Error.Description)); } if (res.Success != null) { sb.Append(String.Format("Success: {0} ", res.Success.Id)); } } return(sb.ToString()); }
public async Task <HueResults> SwitchState(bool?isOn = null, double?brightness = null, RGBColor?hue = null) { //string state = "lights/" + LSwitch.Key + "/state"; //await LREST.Put(base_url + state, "{\"on\":" + isOn.ToString().ToLower() + ", \"transitiontime\":0}", "", ".json"); HueResults retVal = null; try { var command = new LightCommand(); command.TransitionTime = TimeSpan.FromMilliseconds(9); if (brightness == null) { if (Brightness != 0) { command.Brightness = (byte)map(Convert.ToInt16(Brightness), 0, 100, 0, 254); } } else { command.Brightness = (byte)map(Convert.ToInt16(brightness), 0, 100, 0, 254); } try { if (hue != null) { if (((RGBColor)hue).ToHex() != "000000") { command.SetColor(((RGBColor)hue).ToHex().Substring(2, 6)); command.TransitionTime = TimeSpan.FromMilliseconds(44); } } } catch (Exception error) { Console.WriteLine(error.Message); } if (isOn != null) { command.On = isOn; } else { if (brightness == 0) { command.On = false; } else { command.On = true; } } retVal = await CurrentBridge.Client.SendCommandAsync(command, new List <string> { LSwitch.Id }); if (retVal.Count > 0 && retVal[0].Success != null && !string.IsNullOrEmpty(retVal[0].Success.Id)) { // TODO: Error Control //MessageBox.Show("Woot!"); } //var u = await UpdateView(refresh: true); } catch (Exception error) { try { jarvisWPF.PublicClass.MainControlCenter.TextToDebugWindow(error.Message); } catch { } } return(retVal); }
public async Task <string> CreateRule(string name, IEnumerable <RuleCondition> conditions, IEnumerable <InternalBridgeCommand> actions) { CheckInitialized(); if (conditions == null || !conditions.Any()) { throw new ArgumentNullException("lights"); } if (actions == null || !actions.Any()) { throw new ArgumentNullException("actions"); } if (conditions.Count() > 8) { throw new ArgumentException("Max 8 conditions allowed", "conditions"); } if (actions.Count() > 8) { throw new ArgumentException("Max 8 actions allowed", "actions"); } dynamic jsonObj = new ExpandoObject(); if (conditions != null && conditions.Any()) { jsonObj.conditions = conditions; } if (actions != null && actions.Any()) { jsonObj.actions = actions; } if (!string.IsNullOrEmpty(name)) { jsonObj.name = name; } string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = HueClient.GetHttpClient(); //Create group with the lights we want to target var response = await client.PostAsync(new Uri(String.Format("{0}rules", ApiBase)), new StringContent(jsonString)).ConfigureAwait(false); var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); HueResults rulesResult = DeserializeDefaultHueResult(jsonResult); if (rulesResult.Count > 0 && rulesResult[0].Success != null && !string.IsNullOrEmpty(rulesResult[0].Success.Id)) { return(rulesResult[0].Success.Id); } if (rulesResult.HasErrors()) { throw new Exception(rulesResult.Errors.First().Error.Description); } return(null); }
public async Task <string?> CreateSceneAsync(Scene scene) { CheckInitialized(); if (scene == null) { throw new ArgumentNullException(nameof(scene)); } if ((scene.Type == null || scene.Type == SceneType.LightScene) && (scene.Lights == null || !scene.Lights.Any())) { throw new ArgumentNullException(nameof(scene.Lights)); } if (scene.Type == SceneType.GroupScene && string.IsNullOrEmpty(scene.Group)) { throw new ArgumentNullException(nameof(scene.Group)); } if (scene.Name == null) { throw new ArgumentNullException(nameof(scene.Name)); } //It defaults to false, but fails when omitted //https://github.com/Q42/Q42.HueApi/issues/56 if (!scene.Recycle.HasValue) { scene.Recycle = false; } //Filter non updatable properties //Set these fields to null var sceneJson = JObject.FromObject(scene, new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore }); sceneJson.Remove("Id"); sceneJson.Remove("version"); sceneJson.Remove("lastupdated"); sceneJson.Remove("locked"); sceneJson.Remove("owner"); sceneJson.Remove("lightstates"); string jsonString = JsonConvert.SerializeObject(sceneJson, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); HttpClient client = await GetHttpClient().ConfigureAwait(false); var response = await client.PostAsync(new Uri(String.Format("{0}scenes", ApiBase)), new JsonContent(jsonString)).ConfigureAwait(false); var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); HueResults sceneResult = DeserializeDefaultHueResult(jsonResult); if (sceneResult.Count > 0 && sceneResult[0].Success != null && !string.IsNullOrEmpty(sceneResult[0].Success.Id)) { return(sceneResult[0].Success.Id); } if (sceneResult.HasErrors()) { throw new HueException(sceneResult.Errors.First().Error.Description); } return(null); }
private async void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs <double> e) { if (CurrentBridge == null) { return; } SwitchView currentSwitchWindow = ((SwitchView)((Viewbox)((Grid)((CheckBox)sender).Parent).Parent).Parent); if ((bool)currentSwitchWindow.CheckBox_LINKS.IsChecked) { return; } try { double bri = Brightness; if (bri % 10 == 0) { //if (bri == 0 && isOn) //{ // isOn = false; // lights off // await toggleSwitch(currentSwitchWindow.pbar_switch); //} //else if (bri > 0 && !isOn) //{ // isOn = true; // lights on // await toggleSwitch(currentSwitchWindow.pbar_switch); //} //if (bri > 0) //{ if (bri == 250) { bri = 254; } //string state = "lights/" + LSwitch.Id + "/state"; //await LREST.Put(base_url + state, "{\"bri\":" + bri + "}", "", ".json"); var command = new LightCommand(); command.On = LSwitch.State.On; //command.On = true; command.Brightness = (byte)bri; command.TransitionTime = TimeSpan.FromSeconds(9); HueResults retVal = null; retVal = await CurrentBridge.Client.SendCommandAsync(command, new List <string> { LSwitch.Id }); if (retVal.Count > 0 && retVal[0].Success != null && !string.IsNullOrEmpty(retVal[0].Success.Id)) { //LSwitch.State.On =retVal[0].Success.Id } else if (retVal.Count == 0) { isOn = (bool)command.On; //AnimateProperty(currentSwitchWindow.pbar_switch); } //} } } catch (Exception error) { MessageBox.Show(error.Message); } }
/// <summary> /// /// </summary> /// <param name="client"></param> /// <param name="lightsToSet"></param> /// <param name="colorTemperature"></param> internal async Task ModifyFluxSwitchScenes( HueClient client, IEnumerable <Light> lights, Primitives.ColorTemperature colorTemperature, Primitives.Brightness newBrightness) { Dictionary <string, int> scenesModified = new Dictionary <string, int>(); IEnumerable <Scene> scenes = null; try { scenes = await client.GetScenesAsync(); } catch (Exception e) { Log.Debug($"'{nameof(ModifyFluxSwitchScenes)}' exception attempting to get all scenes from client. '{e.Message}' '{e.InnerException}'."); return; } scenes = scenes.Where(x => x.Name.ToLowerInvariant().Contains("flux") && (!x.Recycle.HasValue || !x.Recycle.Value)); // Scenes to update foreach (Scene sceneId in scenes) { Scene scene = null; try { scene = await client.GetSceneAsync(sceneId.Id); } catch (Exception e) { Log.Debug($"'{nameof(ModifyFluxSwitchScenes)}' exception attempting to get scene info from client. '{e.Message}' '{e.InnerException}'."); } if (null != scene) { Dictionary <string, State> lightStates = scene.LightStates; // Update scenes to use the new color temperature and brightness foreach (string lightId in scene.LightStates.Keys) { Light light = lights.Get(lightId); if (lightStates[lightId].On && light.IsFluxControlled()) { LightCommand lightCommand = new LightCommand() { On = true, }; if (light.ControlTemperature()) { lightCommand.ColorTemperature = colorTemperature.NormalizeColorForAllowedColorRange(light.GetLightType()); } if (light.ControlBrightness() && LastBrightnesses.Contains(lightStates[lightId].Brightness)) { lightCommand.Brightness = newBrightness; } else { lightCommand.Brightness = lightStates[lightId].Brightness; } try { if ((lightCommand.ColorTemperature.HasValue && lightStates[lightId].ColorTemperature != lightCommand.ColorTemperature.Value) || (lightCommand.Brightness.HasValue && lightStates[lightId].Brightness != lightCommand.Brightness.Value)) { HueResults result = await client.ModifySceneAsync(sceneId.Id, lightId, lightCommand); // Increment the number of lights modified per scene if (scenesModified.ContainsKey(scene.Name)) { scenesModified[scene.Name]++; } else { scenesModified.Add(scene.Name, 1); } // Limit hub requests await Task.Delay(TimeSpan.FromMilliseconds(15)); } } catch (Exception exception) { Log.Error($"Exception: '{nameof(ModifyFluxSwitchScenes)}' unable to modify scene ID '{sceneId.Id}' named '{scene.Name}' for light id '{lightId}' with color temperature set to '{lightCommand.ColorTemperature}' and brightness '{lightCommand.Brightness}'. {exception.Message}"); // Limit hub requests await Task.Delay(TimeSpan.FromMilliseconds(100)); } } } } } Log.Info($"'{nameof(ModifyFluxSwitchScenes)}' modified '{scenesModified.Count()}' scenes to color temperature '{colorTemperature}' and brightness '{newBrightness.ToString()}'."); }
/// <summary> /// Send a json command to a list of lights /// </summary> /// <param name="command"></param> /// <param name="lightList">if null, send command to all lights</param> /// <returns></returns> public async Task<HueResults> SendCommandRawAsync(string command, IEnumerable<string> lightList = null) { if (command == null) throw new ArgumentNullException("command"); CheckInitialized(); if (lightList == null || !lightList.Any()) { //Group 0 always contains all the lights return await SendGroupCommandAsync(command).ConfigureAwait(false); } else { HueResults results = new HueResults(); await lightList.ForEachAsync(_parallelRequests, async (lightId) => { HttpClient client = new HttpClient(); await client.PutAsync(new Uri(ApiBase + string.Format("lights/{0}/state", lightId)), new StringContent(command)).ConfigureAwait(false); }).ConfigureAwait(false); return results; } }