From 7c3a84d4cf883ebbeda377f4d25bf91cb10941e9 Mon Sep 17 00:00:00 2001 From: Yorick Rommers Date: Mon, 30 Nov 2015 11:40:17 +0100 Subject: [PATCH] Toggle light working --- HueUWP/APIHandler.cs | 48 ++++++---- HueUWP/ColorUtil.cs | 197 +++++++++++++++++++++++++++++++++++++++ HueUWP/HueUWP.csproj | 1 + HueUWP/Light.cs | 6 +- HueUWP/MainPage.xaml | 4 +- HueUWP/MainPage.xaml.cs | 13 ++- HueUWP/NetworkHandler.cs | 18 +++- 7 files changed, 260 insertions(+), 27 deletions(-) create mode 100755 HueUWP/ColorUtil.cs diff --git a/HueUWP/APIHandler.cs b/HueUWP/APIHandler.cs index 915a0af..48362f9 100755 --- a/HueUWP/APIHandler.cs +++ b/HueUWP/APIHandler.cs @@ -10,7 +10,7 @@ using Windows.Storage; namespace HueUWP { - class APIHandler + public class APIHandler { @@ -22,28 +22,44 @@ namespace HueUWP public async void Register() { - var json = await nwh.RegisterName("Hue", "Kenneth&Yorick"); - json = json.Replace("[", "").Replace("]", ""); - JObject o = JObject.Parse(json); - string id= o["success"]["username"].ToString(); - MainPage.LOCAL_SETTINGS.Values["id"] = id; + try { + var json = await nwh.RegisterName("Hue", "Kenneth&Yorick"); + json = json.Replace("[", "").Replace("]", ""); + JObject o = JObject.Parse(json); + string id = o["success"]["username"].ToString(); + MainPage.LOCAL_SETTINGS.Values["id"] = id; } + catch(Exception e) + { + Debug.WriteLine("Could not register."); + } + } + + public async void SetLightData(Light l) + { + + var json = await nwh.ToggleLight(l.ID, $"{{\"on\": {((l.On) ? "true" : "false")},\"bri\": {l.Brightness},\"hue\": { l.Hue},\"sat\": {l.Saturation}}}"); + Debug.WriteLine(json); } public async void GetAllLights(ObservableCollection alllights) { List lightlist = new List(); + try { + var json = await nwh.AllLights(); + Debug.WriteLine(json); + JObject o = JObject.Parse(json); + Debug.WriteLine(o.ToString()); - var json = await nwh.AllLights(); - Debug.WriteLine(json); - JObject o = JObject.Parse(json); - Debug.WriteLine(o.ToString()); - - for(int i = 1; i <= o.Count; i++) + for (int i = 1; i <= o.Count; i++) + { + var light = o["" + i]; + var state = light["state"]; + alllights.Add(new Light() { api = this,ID = i, Brightness = (int)state["bri"], On = (bool)state["on"], Hue = (int)state["hue"], Saturation = (int)state["sat"], Name = (string)light["name"], Type = (string)light["type"] }); + Debug.WriteLine("Added light number " + i); + } } + catch(Exception e) { - var light = o["" + i]; - var state = light["state"]; - alllights.Add(new Light() { ID=i , Brightness = (int)state["bri"] , On = (bool) state["on"], Hue=(int)state["hue"], Saturation=(int)state["sat"],Name=(string)light["name"] , Type=(string)light["type"]}); - Debug.WriteLine("Added light number " + i); + Debug.WriteLine("Could not get all lights."); } } } diff --git a/HueUWP/ColorUtil.cs b/HueUWP/ColorUtil.cs new file mode 100755 index 0000000..f469c54 --- /dev/null +++ b/HueUWP/ColorUtil.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Windows.UI; + +namespace HueUWP +{ + public static class ColorUtil + { + + public static Color getColor(Light light) + { + double hue = ((double)light.Hue * 360.0f) / 65535.0f; + double sat = (double)light.Saturation / 255.0f; + double val = (double)light.Brightness/ 255.0f; + + int r, g, b; + HsvToRgb(hue, sat, val, out r, out g, out b); + return Color.FromArgb(255, Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b)); + } + + public static void RGBtoHSV(double r, double g, double b, out double h, out double s, out double v) + { + double min, max, delta; + + min = Math.Min(r, Math.Min(g, b)); + max = Math.Max(r, Math.Max(g, b)); + + v = max; // v + delta = max - min; + + if (max != 0) + s = delta / max; // s + else + { + // r = g = b = 0 // s = 0, v is undefined + s = 0; + h = -1; + return; + } + + if (r == max) + h = (g - b) / delta; // between yellow & magenta + else if (g == max) + h = 2 + (b - r) / delta; // between cyan & yellow + else + h = 4 + (r - g) / delta; // between magenta & cyan + + h *= 60; // degrees + + if (h < 0) + h += 360; + } + + private static void HsvToRgb(double h, double S, double V, out int r, out int g, out int b) + { + double H = h; + while (H < 0) + { + H += 360; + } + while (H >= 360) + { + H -= 360; + } + + double R, G, B; + if (V <= 0) + R = G = B = 0; + else if (S <= 0) + R = G = B = V; + else + { + double hf = H / 60.0; + int i = (int)Math.Floor(hf); + double f = hf - i; + double pv = V * (1 - S); + double qv = V * (1 - S * f); + double tv = V * (1 - S * (1 - f)); + switch (i) + { + // Red is the dominant color + case 0: + R = V; + G = tv; + B = pv; + break; + // Green is the dominant color + case 1: + R = qv; + G = V; + B = pv; + break; + case 2: + R = pv; + G = V; + B = tv; + break; + // Blue is the dominant color + case 3: + R = pv; + G = qv; + B = V; + break; + case 4: + R = tv; + G = pv; + B = V; + break; + // Red is the dominant color + case 5: + R = V; + G = pv; + B = qv; + break; + // Just in case we overshoot on our math by a little, we put these here. Since its a switch it won't slow us down at all to put these here. + case 6: + R = V; + G = tv; + B = pv; + break; + case -1: + R = V; + G = pv; + B = qv; + break; + // The color is not defined, we should throw an error. + default: + //LFATAL("i Value error in Pixel conversion, Value is %d", i); + R = G = B = V; // Just pretend its black/white + break; + } + } + + r = Clamp((int)(R * 255.0)); + g = Clamp((int)(G * 255.0)); + b = Clamp((int)(B * 255.0)); + } + + private static int Clamp(int i) + { + if (i < 0) return 0; + if (i > 255) return 255; + return i; + } + + public static Color HsvToRgb(double hue, double sat, double val) + { + + double h = ((double)hue * 360.0f) / 65535.0f; + double s = (double)sat / 255.0f; + double v = (double)val / 255.0f; + + int hi = (int)Math.Floor(h / 60.0) % 6; + double f = (h / 60.0) - Math.Floor(h / 60.0); + + double p = v * (1.0 - s); + double q = v * (1.0 - (f * s)); + double t = v * (1.0 - ((1.0 - f) * s)); + + Color ret; + + switch (hi) + { + case 0: + ret = GetRgb(v, t, p); + break; + case 1: + ret = GetRgb(q, v, p); + break; + case 2: + ret = GetRgb(p, v, t); + break; + case 3: + ret = GetRgb(p, q, v); + break; + case 4: + ret = GetRgb(t, p, v); + break; + case 5: + ret = GetRgb(v, p, q); + break; + default: + ret = Color.FromArgb(0xFF, 0x00, 0x00, 0x00); + break; + } + return ret; + } + + public static Color GetRgb(double r, double g, double b) + { + return Color.FromArgb(255, (byte)(r * 255.0), (byte)(g * 255.0), (byte)(b * 255.0)); + } + } +} diff --git a/HueUWP/HueUWP.csproj b/HueUWP/HueUWP.csproj index 7e815c2..6888c00 100644 --- a/HueUWP/HueUWP.csproj +++ b/HueUWP/HueUWP.csproj @@ -97,6 +97,7 @@ App.xaml + MainPage.xaml diff --git a/HueUWP/Light.cs b/HueUWP/Light.cs index 28b9c26..93caedc 100644 --- a/HueUWP/Light.cs +++ b/HueUWP/Light.cs @@ -20,10 +20,11 @@ namespace HueUWP public int Brightness{ get; set; } public int Hue { get; set; } public int Saturation { get; set; } + + public APIHandler api { get; set; } public Light() { - Debug.WriteLine("Get lamp data on creation or something"); //temp ID = 1; Name = "Lamp 1"; @@ -37,7 +38,8 @@ namespace HueUWP public void UpdateState(bool on) { NotifyPropertyChanged(nameof(UpdateState)); - Debug.WriteLine(on); + this.On = on; + api.SetLightData(this); } diff --git a/HueUWP/MainPage.xaml b/HueUWP/MainPage.xaml index ed6b860..6a44e7e 100644 --- a/HueUWP/MainPage.xaml +++ b/HueUWP/MainPage.xaml @@ -2,7 +2,7 @@ x:Class="HueUWP.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" - xmlns:local="using:BindingToCommandsUWP" + xmlns:local="using:HueUWP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" @@ -22,7 +22,7 @@ - + Off On diff --git a/HueUWP/MainPage.xaml.cs b/HueUWP/MainPage.xaml.cs index a6e5ab5..d1df858 100644 --- a/HueUWP/MainPage.xaml.cs +++ b/HueUWP/MainPage.xaml.cs @@ -59,13 +59,22 @@ namespace HueUWP light.UpdateColor(10, 10, 10); } - private void ToggleSwitch_Tapped(object sender, TappedRoutedEventArgs e) + public void ToggleSwitch_Tapped(object sender, TappedRoutedEventArgs e) { + Debug.WriteLine("Hello again"); ToggleSwitch button = ((ToggleSwitch)sender); Light light = (Light)button.DataContext; - + Debug.WriteLine("Hello"); light.UpdateState(button.IsOn); } + private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e) + { + Debug.WriteLine("Hello again"); + ToggleSwitch button = ((ToggleSwitch)sender); + Light light = (Light)button.DataContext; + Debug.WriteLine("Hello"); + light.UpdateState(button.IsOn); + } } } diff --git a/HueUWP/NetworkHandler.cs b/HueUWP/NetworkHandler.cs index c59fb8a..567d2e7 100755 --- a/HueUWP/NetworkHandler.cs +++ b/HueUWP/NetworkHandler.cs @@ -9,7 +9,7 @@ using Windows.Web.Http; namespace HueUWP { - class NetworkHandler + public class NetworkHandler { string ip; int port; @@ -24,13 +24,15 @@ namespace HueUWP var cts = new CancellationTokenSource(); cts.CancelAfter(5000); + //System.Diagnostics.Debug.WriteLine("PUT:\n" + path +"\n"+json); + try { HttpClient client = new HttpClient(); HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json"); - Uri uriLampState = new Uri($"http://{ip}:{port}/api" + path); - var response = await client.PostAsync(uriLampState, content).AsTask(cts.Token); + Uri uriLampState = new Uri($"http://{ip}:{port}/api/" + path); + var response = await client.PutAsync(uriLampState, content).AsTask(cts.Token); if (!response.IsSuccessStatusCode) { @@ -61,7 +63,7 @@ namespace HueUWP HttpClient client = new HttpClient(); HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json"); - Uri uriLampState = new Uri($"http://{ip}:{port}/api" + path); + Uri uriLampState = new Uri($"http://{ip}:{port}/api/" + path); var response = await client.PostAsync(uriLampState, content).AsTask(cts.Token); if (!response.IsSuccessStatusCode) @@ -113,6 +115,12 @@ namespace HueUWP } } + public async Task ToggleLight(int lightid, string json) + { + var response = await Put($"{(String)MainPage.LOCAL_SETTINGS.Values["id"]}/lights/{lightid}/state", json); + return response; + } + public async Task RegisterName(string AppName, string UserName) { @@ -126,7 +134,7 @@ namespace HueUWP { var response = await Get($"{(String)MainPage.LOCAL_SETTINGS.Values["id"]}/lights"); if (string.IsNullOrEmpty(response)) - await new MessageDialog("Error while getting all liights. ….").ShowAsync(); + await new MessageDialog("Error while getting all lights. ….").ShowAsync(); return response; }