Partial HueClient, contains requests to the /Groups/ url
Ejemplo n.º 1
0
        /// <summary>
        /// UpdateSceneAsync
        /// </summary>
        /// <param name="id"></param>
        /// <param name="scene"></param>
        /// <returns></returns>
        public async Task <HueResults> UpdateSceneAsync(string id, Scene scene)
        {
            CheckInitialized();

            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (id.Trim() == String.Empty)
            {
                throw new ArgumentException("id must not be empty", nameof(id));
            }
            if (scene == null)
            {
                throw new ArgumentNullException(nameof(scene));
            }

            //Set these fields to null
            scene.Id      = null;
            scene.Recycle = null;
            scene.FilterNonUpdatableProperties();

            string jsonString = JsonConvert.SerializeObject(scene, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client   = HueClient.GetHttpClient();
            var        response = await client.PutAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, id)), new StringContent(jsonString)).ConfigureAwait(false);

            var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Asynchronously gets all rules registered with the bridge.
        /// </summary>
        /// <returns>An enumerable of <see cref="Rule"/>s registered with the bridge.</returns>
        public async Task <IReadOnlyCollection <Rule> > GetRulesAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}rules", ApiBase))).ConfigureAwait(false);

#if DEBUG
            stringResult = "{\"1\": {    \"name\": \"Wall Switch Rule\",    \"lasttriggered\": \"2013-10-17T01:23:20\",    \"creationtime\": \"2013-10-10T21:11:45\",    \"timestriggered\": 27,    \"owner\": \"78H56B12BA\",    \"status\": \"enabled\",    \"conditions\": [        {            \"address\": \"/sensors/2/state/buttonevent\",            \"operator\": \"eq\",            \"value\": \"16\"        },        {            \"address\": \"/sensors/2/state/lastupdated\",            \"operator\": \"dx\"        }    ],    \"actions\": [        {            \"address\": \"/groups/0/action\",            \"method\": \"PUT\",            \"body\": {                \"scene\": \"S3\"            }        }    ]} }";
#endif


            List <Rule> results = new List <Rule>();

            JToken token = JToken.Parse(stringResult);
            if (token.Type == JTokenType.Object)
            {
                //Each property is a scene
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Rule rule = JsonConvert.DeserializeObject <Rule>(prop.Value.ToString());
                    rule.Id = prop.Name;

                    results.Add(rule);
                }
            }

            return(results);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Asynchronously gets all scenes registered with the bridge.
        /// </summary>
        /// <returns>An enumerable of <see cref="Scene"/>s registered with the bridge.</returns>
        public async Task <IReadOnlyCollection <Scene> > GetScenesAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}scenes", ApiBase))).ConfigureAwait(false);

#if DEBUG
            stringResult = "{    \"1\": {        \"name\": \"My Scene 1\",        \"lights\": [            \"1\",            \"2\",            \"3\"        ],        \"recycle\": true    },    \"2\": {        \"name\": \"My Scene 2\",        \"lights\": [            \"1\",            \"2\",            \"3\"        ],        \"recycle\": true    }}";
#endif


            List <Scene> results = new List <Scene>();

            JToken token = JToken.Parse(stringResult);
            if (token.Type == JTokenType.Object)
            {
                //Each property is a scene
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Scene scene = JsonConvert.DeserializeObject <Scene>(prop.Value.ToString());
                    scene.Id = prop.Name;

                    results.Add(scene);
                }
            }

            return(results);
        }
        public HueLightingServiceHandler(Q42.HueApi.HueClient client, Q42.HueApi.Light light)
        {
            //Doc on supported lights:
            // http://www.developers.meethue.com/documentation/supported-lights
            _light = light;
            var info  = new HueLampInfo(light);
            var state = light.State;

            _client = client;

            LampDetails_Color = info.SupportsColor;
            LampDetails_ColorRenderingIndex    = info.ColorRenderingIndex;
            LampDetails_Dimmable               = info.IsDimmable;
            LampDetails_HasEffects             = true;
            LampDetails_IncandescentEquivalent = info.IncandescentEquivalent;
            LampDetails_LampBaseType           = (uint)info.BaseType;
            LampDetails_LampBeamAngle          = info.LampBeamAngle;
            LampDetails_LampID            = light.Id;
            LampDetails_LampType          = (uint)info.LampType;
            LampDetails_Make              = (uint)AdapterLib.LsfEnums.LampMake.MAKE_OEM1;
            LampDetails_MaxLumens         = info.MaxLumens;
            LampDetails_MaxTemperature    = info.MaxTemperature;
            LampDetails_MaxVoltage        = 120;
            LampDetails_MinTemperature    = info.MinTemperature;
            LampDetails_MinVoltage        = 100;
            LampDetails_Model             = 1;
            LampDetails_Type              = (uint)AdapterLib.LsfEnums.DeviceType.TYPE_LAMP;
            LampDetails_VariableColorTemp = info.SupportsTemperature;
            LampDetails_Wattage           = info.Wattage;
        }
        /// <summary>
        /// Authorization request
        /// </summary>
        /// <param name="clientId">Identifies the client that is making the request. The value passed in this parameter must exactly match the value you receive from hue. Note that the underscore is not used in the clientid name of this parameter.</param>
        /// <param name="state">Provides any state that might be useful to your application upon receipt of the response. The Hue Authorization Server roundtrips this parameter, so your application receives the same value it sent. To mitigate against cross-site request forgery (CSRF), it is strongly recommended to include an anti-forgery token in the state, and confirm it in the response. One good choice for a state token is a string of 30 or so characters constructed using a high-quality random-number generator.</param>
        /// <param name="deviceId">The device identifier must be a unique identifier for the app or device accessing the Hue Remote API.</param>
        /// <param name="appId">Identifies the app that is making the request. The value passed in this parameter must exactly match the value you receive from hue.</param>
        /// <param name="deviceName">The device name should be the name of the app or device accessing the remote API. The devicename is used in the user's "My Apps" overview in the Hue Account (visualized as: "<app name> on <devicename>"). If not present, deviceid is also used for devicename. The <app name> is the application name you provided to us the moment you requested access to the remote API.</param>
        /// <param name="responseType">The response_type value must be "code".</param>
        /// <returns></returns>
        public async Task <string> Authorize(string clientId, string state, string deviceId, string appId, string deviceName = null, string responseType = "code")
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            if (string.IsNullOrEmpty(state))
            {
                throw new ArgumentNullException(nameof(state));
            }
            if (string.IsNullOrEmpty(deviceId))
            {
                throw new ArgumentNullException(nameof(deviceId));
            }
            if (string.IsNullOrEmpty(appId))
            {
                throw new ArgumentNullException(nameof(appId));
            }
            if (string.IsNullOrEmpty(responseType))
            {
                throw new ArgumentNullException(nameof(responseType));
            }

            string url = string.Format("https://api.meethue.com/oauth2/auth?clientid={0}&response_type={5}&state={1}&appid={3}&deviceid={2}&devicename={4}", clientId, state, deviceId, appId, deviceName, responseType);

            HttpClient client       = HueClient.GetHttpClient();
            var        stringResult = await client.GetStringAsync(new Uri(url)).ConfigureAwait(false);

            //TODO: get code parameter from returned redirect url?

            return(stringResult);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create a ResourceLink
        /// </summary>
        /// <param name="ResourceLink"></param>
        /// <returns></returns>
        public async Task <string> CreateResourceLinkAsync(ResourceLink resourceLink)
        {
            CheckInitialized();

            string command = JsonConvert.SerializeObject(resourceLink, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client = HueClient.GetHttpClient();

            //Create ResourceLink
            var result = await client.PostAsync(new Uri(ApiBase + "resourcelinks"), new StringContent(command)).ConfigureAwait(false);

            var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            DefaultHueResult[] resourceLinkResult = JsonConvert.DeserializeObject <DefaultHueResult[]>(jsonResult);

            if (resourceLinkResult.Length > 0 && resourceLinkResult[0].Success != null && !string.IsNullOrEmpty(resourceLinkResult[0].Success.Id))
            {
                return(resourceLinkResult[0].Success.Id);
            }

            return(null);
        }
        public async Task <string> RegisterAsync(string bridgeId, string appId)
        {
            if (string.IsNullOrEmpty(bridgeId))
            {
                throw new ArgumentNullException(nameof(bridgeId));
            }
            if (string.IsNullOrEmpty(appId))
            {
                throw new ArgumentNullException(nameof(appId));
            }

            JObject obj = new JObject();

            obj["linkbutton"] = true;

            HttpClient client         = HueClient.GetHttpClient();
            var        configResponse = await client.PutAsync(new Uri($"{_apiBase}{bridgeId}/0/config"), new StringContent(obj.ToString())).ConfigureAwait(false);

            JObject bridge = new JObject();

            bridge["devicetype"] = appId;

            var response = await client.PostAsync(new Uri($"{_apiBase}{bridgeId}/"), new StringContent(bridge.ToString())).ConfigureAwait(false);

            var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);


            JObject result;

            try
            {
                JArray jresponse = JArray.Parse(stringResponse);
                result = (JObject)jresponse.First;
            }
            catch
            {
                //Not an expected response. Return response as exception
                throw new Exception(stringResponse);
            }

            JToken error;

            if (result.TryGetValue("error", out error))
            {
                if (error["type"].Value <int>() == 101)                // link button not pressed
                {
                    throw new Exception("Link button not pressed");
                }
                else
                {
                    throw new Exception(error["description"].Value <string>());
                }
            }

            var key = result["success"]["username"].Value <string>();

            Initialize(key);

            return(key);
        }
        public HueLightingServiceHandler(Q42.HueApi.HueClient client, Q42.HueApi.Light light)
        {
            //Doc on supported lights:
            // http://www.developers.meethue.com/documentation/supported-lights
            _light = light;
            var info = new HueLampInfo(light);
            var state = light.State;
            _client = client;

            LampDetails_Color = info.SupportsColor;
            LampDetails_ColorRenderingIndex = info.ColorRenderingIndex;
            LampDetails_Dimmable = info.IsDimmable;
            LampDetails_HasEffects = false;
            LampDetails_IncandescentEquivalent = info.IncandescentEquivalent;
            LampDetails_LampBaseType = (uint)info.BaseType;
            LampDetails_LampBeamAngle = info.LampBeamAngle;
            LampDetails_LampID = light.Id;
            LampDetails_LampType = (uint) info.LampType;
            LampDetails_Make = (uint)AdapterLib.LsfEnums.LampMake.MAKE_OEM1;
            LampDetails_MaxLumens = info.MaxLumens;
            LampDetails_MaxTemperature = info.MaxTemperature;
            LampDetails_MaxVoltage = 120;
            LampDetails_MinTemperature = info.MinTemperature;
            LampDetails_MinVoltage = 100;
            LampDetails_Model = 1;
            LampDetails_Type = (uint)AdapterLib.LsfEnums.DeviceType.TYPE_LAMP;
            LampDetails_VariableColorTemp = info.SupportsTemperature;
            LampDetails_Version = 1;
            LampDetails_Wattage = info.Wattage;
        }
Ejemplo n.º 9
0
        public async Task <string> CreateSensorAsync(Sensor sensor)
        {
            CheckInitialized();

            string sensorJson = JsonConvert.SerializeObject(sensor, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client = HueClient.GetHttpClient();

            //Create schedule
            var result = await client.PostAsync(new Uri(String.Format("{0}sensors", ApiBase)), new StringContent(sensorJson)).ConfigureAwait(false);

            var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            DefaultHueResult[] sensorResult = JsonConvert.DeserializeObject <DefaultHueResult[]>(jsonResult);

            if (sensorResult.Length > 0 && sensorResult[0].Success != null && !string.IsNullOrEmpty(sensorResult[0].Success.Id))
            {
                return(sensorResult[0].Success.Id);
            }

            return(null);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Start searching for new lights
        /// </summary>
        /// <returns></returns>
        public async Task <HueResults> SearchNewLightsAsync(IEnumerable <string> deviceIds = null)
        {
            CheckInitialized();

            StringContent jsonStringContent = null;

            if (deviceIds != null)
            {
                dynamic jsonObj = new ExpandoObject();
                jsonObj.deviceid = deviceIds;

                string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

                jsonStringContent = new StringContent(jsonString);
            }

            HttpClient client   = HueClient.GetHttpClient();
            var        response = await client.PostAsync(new Uri(String.Format("{0}lights", ApiBase)), jsonStringContent).ConfigureAwait(false);

            var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Deletes a whitelist entry
        /// </summary>
        /// <returns></returns>
        public async Task <bool> DeleteWhiteListEntryAsync(string entry)
        {
            CheckInitialized();

            HttpClient client = HueClient.GetHttpClient();

            var response = await client.DeleteAsync(new Uri(string.Format("{0}config/whitelist/{1}", ApiBase, entry))).ConfigureAwait(false);

            var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            JArray  jresponse = JArray.Parse(stringResponse);
            JObject result    = (JObject)jresponse.First;

            JToken error;

            if (result.TryGetValue("error", out error))
            {
                if (error["type"].Value <int>() == 3) // entry not available
                {
                    return(false);
                }
                else
                {
                    throw new Exception(error["description"].Value <string>());
                }
            }

            return(true);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets a list of sensors that were discovered the last time a search for new sensors was performed. The list of new sensors is always deleted when a new search is started.
        /// </summary>
        /// <returns></returns>
        public async Task <IReadOnlyCollection <Sensor> > GetNewSensorsAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}sensors/new", ApiBase))).ConfigureAwait(false);

#if DEBUG
            //stringResult = "{\"7\": {\"name\": \"Hue Lamp 7\"},   \"8\": {\"name\": \"Hue Lamp 8\"},    \"lastscan\": \"2012-10-29T12:00:00\"}";
#endif

            List <Sensor> results = new List <Sensor>();

            JToken token = JToken.Parse(stringResult);
            if (token.Type == JTokenType.Object)
            {
                //Each property is a light
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    if (prop.Name != "lastscan")
                    {
                        Sensor newSensor = JsonConvert.DeserializeObject <Sensor>(prop.Value.ToString());
                        newSensor.Id = prop.Name;

                        results.Add(newSensor);
                    }
                }
            }

            return(results);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Asynchronously gets all lights registered with the bridge.
        /// </summary>
        /// <returns>An enumerable of <see cref="Light"/>s registered with the bridge.</returns>
        public async Task <IEnumerable <Light> > GetLightsAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}lights", ApiBase))).ConfigureAwait(false);

            List <Light> results = new List <Light>();

            JToken token = JToken.Parse(stringResult);

            if (token.Type == JTokenType.Object)
            {
                //Each property is a light
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Light newLight = JsonConvert.DeserializeObject <Light>(prop.Value.ToString());
                    newLight.Id = prop.Name;
                    results.Add(newLight);
                }
            }
            return(results);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Update a sensor
        /// </summary>
        /// <param name="id"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public async Task <HueResults> UpdateSensorAsync(string id, string newName)
        {
            CheckInitialized();

            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (id.Trim() == String.Empty)
            {
                throw new ArgumentException("id must not be empty", nameof(id));
            }
            if (string.IsNullOrEmpty(newName))
            {
                throw new ArgumentNullException(nameof(newName));
            }

            dynamic jsonObj = new ExpandoObject();

            jsonObj.name = newName;

            string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client = HueClient.GetHttpClient();

            //Create schedule
            var result = await client.PutAsync(new Uri(string.Format("{0}sensors/{1}", ApiBase, id)), new StringContent(jsonString)).ConfigureAwait(false);

            var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Asynchronously gets all sensors registered with the bridge.
        /// </summary>
        /// <returns>An enumerable of <see cref="Sensor"/>s registered with the bridge.</returns>
        public async Task <IReadOnlyCollection <Sensor> > GetSensorsAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}sensors", ApiBase))).ConfigureAwait(false);

#if DEBUG
            stringResult = "{    \"1\": {        \"state\": {            \"daylight\": false,            \"lastupdated\": \"2014-06-27T07:38:51\"        },        \"config\": {            \"on\": true,            \"long\": \"none\",            \"lat\": \"none\",            \"sunriseoffset\": 50,            \"sunsetoffset\": 50        },        \"name\": \"Daylight\",        \"type\": \"Daylight\",        \"modelid\": \"PHDL00\",        \"manufacturername\": \"Philips\",        \"swversion\": \"1.0\"    },    \"2\": {        \"state\": {            \"buttonevent\": 0,            \"lastupdated\": \"none\"        },        \"config\": {            \"on\": true        },        \"name\": \"Tap Switch 2\",        \"type\": \"ZGPSwitch\",        \"modelid\": \"ZGPSWITCH\",        \"manufacturername\": \"Philips\",        \"uniqueid\": \"00:00:00:00:00:40:03:50-f2\"    }}";
#endif


            List <Sensor> results = new List <Sensor>();

            JToken token = JToken.Parse(stringResult);
            if (token.Type == JTokenType.Object)
            {
                //Each property is a scene
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Sensor scene = JsonConvert.DeserializeObject <Sensor>(prop.Value.ToString());
                    scene.Id = prop.Name;

                    results.Add(scene);
                }
            }

            return(results);
        }
Ejemplo n.º 16
0
        public async Task <HueResults> ChangeSensorStateAsync(string id, SensorState state)
        {
            CheckInitialized();

            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (id.Trim() == String.Empty)
            {
                throw new ArgumentException("id must not be empty", "id");
            }
            if (state == null)
            {
                throw new ArgumentNullException("state");
            }

            string jsonString = JsonConvert.SerializeObject(state, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client = HueClient.GetHttpClient();

            //Create schedule
            var result = await client.PutAsync(new Uri(string.Format("{0}sensors/{1}/state", ApiBase, id)), new StringContent(jsonString)).ConfigureAwait(false);

            var jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 17
0
        private async Task Initialize()
        {
            string bridgeIP = await GetBridgeIP();

            _client = new HueClient(bridgeIP, AppKey);

            bool registered = false;

            while (!registered)
            {
                try
                {
                    await _client.GetBridgeAsync();
                    registered = true;
                }
                catch
                {
                }

                if (!registered)
                {
                    var md = new MessageDialog("Press the button on your Hue bridge then press Connect", "Connecting");
                    md.Commands.Add(new UICommand("Connect"));
                    await md.ShowAsync();
                    
                    registered = await _client.RegisterAsync(AppName, AppKey);
                }
            }
        }
Ejemplo n.º 18
0
        /// <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 = HueClient.GetHttpClient();
                    await client.PutAsync(new Uri(ApiBase + string.Format("lights/{0}/state", lightId)), new StringContent(command)).ConfigureAwait(false);
                }).ConfigureAwait(false);

                return(results);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Get all schedules
        /// </summary>
        /// <returns></returns>
        public async Task <IReadOnlyCollection <Schedule> > GetSchedulesAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}schedules", ApiBase))).ConfigureAwait(false);

            List <Schedule> results = new List <Schedule>();

            JToken token = JToken.Parse(stringResult);

            if (token.Type == JTokenType.Object)
            {
                //Each property is a light
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Schedule newSchedule = JsonConvert.DeserializeObject <Schedule>(prop.Value.ToString());
                    newSchedule.Id = prop.Name;

                    results.Add(newSchedule);
                }
            }

            return(results);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Delete a schedule
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <HueResults> DeleteScheduleAsync(string id)
        {
            HttpClient client = HueClient.GetHttpClient();
            //Delete schedule
            var result = await client.DeleteAsync(new Uri(ApiBase + string.Format("schedules/{0}", id))).ConfigureAwait(false);

            string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Deletes a scene
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <HueResults> DeleteSceneAsync(string sceneId)
        {
            CheckInitialized();

            HttpClient client = HueClient.GetHttpClient();
            var        result = await client.DeleteAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, sceneId))).ConfigureAwait(false);

            string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Get bridge info
        /// </summary>
        /// <returns></returns>
        public async Task <Bridge> GetBridgeAsync()
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            var        stringResult = await client.GetStringAsync(new Uri(ApiBase)).ConfigureAwait(false);

            BridgeState jsonResult = DeserializeResult <BridgeState>(stringResult);

            return(new Bridge(jsonResult));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Starts a search for new sensors.
        /// </summary>
        /// <returns></returns>
        public async Task <HueResults> FindNewSensorsAsync()
        {
            CheckInitialized();

            HttpClient client   = HueClient.GetHttpClient();
            var        response = await client.PostAsync(new Uri(String.Format("{0}sensors", ApiBase)), null).ConfigureAwait(false);

            var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Deletes a single ResourceLink
        /// </summary>
        /// <param name="resourceLinkId"></param>
        /// <returns></returns>
        public async Task <HueResults> DeleteResourceLinkAsync(string resourceLinkId)
        {
            CheckInitialized();

            HttpClient client = HueClient.GetHttpClient();
            //Delete resource link 1
            var result = await client.DeleteAsync(new Uri(ApiBase + string.Format("resourcelinks/{0}", resourceLinkId))).ConfigureAwait(false);

            string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Register your <paramref name="appName"/> and <paramref name="appKey"/> at the Hue Bridge.
        /// </summary>
        /// <param name="appKey">Secret key for your app. Must be at least 10 characters.</param>
        /// <param name="appName">The name of your app or device.</param>
        /// <returns><c>true</c> if success, <c>false</c> if the link button hasn't been pressed.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="appName"/> or <paramref name="appKey"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException"><paramref name="appName"/> or <paramref name="appKey"/> aren't long enough, are empty or contains spaces.</exception>
        public async Task <bool> RegisterAsync(string appName, string appKey)
        {
            if (appName == null)
            {
                throw new ArgumentNullException("appName");
            }
            if (appName.Trim() == String.Empty)
            {
                throw new ArgumentException("appName must not be empty", "appName");
            }
            if (appKey == null)
            {
                throw new ArgumentNullException("appKey");
            }
            if (appKey.Length < 10 || appKey.Trim() == String.Empty)
            {
                throw new ArgumentException("appKey must be at least 10 characters.", "appKey");
            }
            if (appKey.Contains(" "))
            {
                throw new ArgumentException("Cannot contain spaces.", "appName");
            }

            JObject obj = new JObject();

            obj["username"]   = appKey;
            obj["devicetype"] = appName;

            HttpClient client   = HueClient.GetHttpClient();
            var        response = await client.PostAsync(new Uri(string.Format("http://{0}/api", _ip)), new StringContent(obj.ToString())).ConfigureAwait(false);

            var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            JArray  jresponse = JArray.Parse(stringResponse);
            JObject result    = (JObject)jresponse.First;

            JToken error;

            if (result.TryGetValue("error", out error))
            {
                if (error["type"].Value <int>() == 101) // link button not pressed
                {
                    return(false);
                }
                else
                {
                    throw new Exception(error["description"].Value <string>());
                }
            }

            Initialize(result["success"]["username"].Value <string>());
            return(true);
        }
Ejemplo n.º 26
0
        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   = HueClient.GetHttpClient();
            var        response = await client.PostAsync(new Uri(String.Format("{0}scenes", ApiBase)), new StringContent(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);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// UpdateSceneAsync
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="lights"></param>
        /// <param name="storeLightState">If set, the lightstates of the lights in the scene will be overwritten by the current state of the lights. Can also be used in combination with transitiontime to update the transition time of a scene.</param>
        /// <param name="transitionTime">Can be used in combination with storeLightState</param>
        /// <returns></returns>
        public async Task <HueResults> UpdateSceneAsync(string id, string name, IEnumerable <string> lights, bool?storeLightState = null, TimeSpan?transitionTime = null)
        {
            CheckInitialized();

            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (id.Trim() == String.Empty)
            {
                throw new ArgumentException("id must not be empty", nameof(id));
            }
            if (lights == null)
            {
                throw new ArgumentNullException(nameof(lights));
            }

            dynamic jsonObj = new ExpandoObject();

            jsonObj.lights = lights;

            if (storeLightState.HasValue)
            {
                jsonObj.storelightstate = storeLightState.Value;

                //Transitiontime can only be used in combination with storeLightState
                if (transitionTime.HasValue)
                {
                    jsonObj.transitiontime = (uint)transitionTime.Value.TotalSeconds * 10;
                }
            }

            if (!string.IsNullOrEmpty(name))
            {
                jsonObj.name = name;
            }

            string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client   = HueClient.GetHttpClient();
            var        response = await client.PutAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, id)), new StringContent(jsonString)).ConfigureAwait(false);

            var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 28
0
        /// <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)
        {
            CheckInitialized();

            if (lights == null)
            {
                throw new ArgumentNullException("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.Room;
            }

            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}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);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Update bridge config
        /// </summary>
        /// <param name="update"></param>
        /// <returns></returns>
        public async Task <HueResults> UpdateBridgeConfigAsync(BridgeConfigUpdate update)
        {
            CheckInitialized();

            string command = JsonConvert.SerializeObject(update, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client = HueClient.GetHttpClient();
            var        result = await client.PutAsync(new Uri(string.Format("{0}config", ApiBase)), new StringContent(command)).ConfigureAwait(false);

            string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(DeserializeDefaultHueResult(jsonResult));
        }
Ejemplo n.º 30
0
        public HueBuildLight(string ip, IEnumerable<string> lights, string intensity)
        {
            _hueClient = new HueClient(ip);
            _hueClient.Initialize(AppKey);
            _lights = lights.ToList();

            int parsedInt;
            if (int.TryParse(intensity, out parsedInt))
            {
                _intensity = parsedInt;
            }
            else
            {
                _intensity = MAX_INTENSITY;
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Get the state of a single ResourceLink
        /// </summary>
        /// <returns></returns>
        public async Task <ResourceLink> GetResourceLinkAsync(string id)
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}resourcelinks/{1}", ApiBase, id))).ConfigureAwait(false);

            ResourceLink resourceLink = DeserializeResult <ResourceLink>(stringResult);

            if (string.IsNullOrEmpty(resourceLink.Id))
            {
                resourceLink.Id = id;
            }

            return(resourceLink);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Deletes a single light
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public async Task <IReadOnlyCollection <DeleteDefaultHueResult> > DeleteLightAsync(string id)
        {
            CheckInitialized();

            HttpClient client = HueClient.GetHttpClient();
            //Delete light
            var result = await client.DeleteAsync(new Uri(ApiBase + string.Format("lights/{0}", id))).ConfigureAwait(false);

            string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

#if DEBUG
            jsonResult = "[{\"success\":\"/lights/" + id + " deleted\"}]";
#endif

            return(DeserializeDefaultHueResult <DeleteDefaultHueResult>(jsonResult));
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Get a single scene
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <Scene> GetSceneAsync(string id)
        {
            CheckInitialized();

            HttpClient client       = HueClient.GetHttpClient();
            string     stringResult = await client.GetStringAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, id))).ConfigureAwait(false);

            Scene scene = DeserializeResult <Scene>(stringResult);

            if (string.IsNullOrEmpty(scene.Id))
            {
                scene.Id = id;
            }

            return(scene);
        }
Ejemplo n.º 34
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AutoMapperConfig.Configure();

            // Create the container builder.
            var builder = new ContainerBuilder();

            // Register the Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            // Register other dependencies.
            var client = new HueClient(HueConfig.HueIP);
            client.Initialize(HueConfig.HueMd5);
            builder.Register(c => client).As<IHueClient>().SingleInstance();

            var list = new List<Light>
                {
                    new Light {Id = "1"},
                    new Light {Id = "2"},
                    new Light {Id = "3"},
                    new Light {Id = "4"},
                    new Light {Id = "6"}
                };

            HueListConfig.UpdateLights(client, list);

            builder.Register(l => list).As<IList<Light>>().SingleInstance();

            // Build the container.
            var container = builder.Build();

            // Create the depenedency resolver.
            var webApiResolver = new AutofacWebApiDependencyResolver(container);

            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 35
0
        public override int Run(string[] remainingArguments)
        {
            var hueClient = new HueClient(_ip);
            var result = hueClient.RegisterAsync(HueBuildLight.AppName, HueBuildLight.AppKey).Result;

            if (result)
            {
                Console.WriteLine("Registered correctly.");
                return 0;
            }

            //If we failed to register, attempt to initialise and see if we succeed as we may already be registered.
            hueClient.Initialize(HueBuildLight.AppKey);
            var initialised = hueClient.IsInitialized;
            Console.WriteLine(initialised ? "Already registered." : "Failed to register");
            return initialised ? 0 : 1;
        }
Ejemplo n.º 36
0
    protected async void Bla(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
    {
      var bridges = await new Q42.HueApi.HttpBridgeLocator().LocateBridgesAsync(TimeSpan.FromMinutes(1));

      var bridge = bridges.Single();

      var client = new HueClient(bridge, "frUwREPr3m");

      var lights = await client.GetLightsAsync();

      var sorted = lights.OrderBy(l => l.Id);

      var random = new Random();

      var duration = TimeSpan.FromSeconds(random.Next(10, 25));

      var start = DateTime.Now;

      var end = start + duration;

      var offCommand = new LightCommand();

      offCommand.On = false;
      offCommand.TransitionTime = TimeSpan.Zero;

      await client.SendCommandAsync(offCommand);

      Q42.HueApi.Light previousLight = null;

      while (DateTime.Now < end)
      {
        foreach (var light in sorted)
        {
          if (DateTime.Now >= end)
          {
            break;
          }

          if (previousLight != null)
          {
            var offCommand1 = new LightCommand();

            offCommand1.On = false;
            offCommand1.TransitionTime = TimeSpan.FromTicks(1);

            client.SendCommandAsync(offCommand1, new[] { previousLight.Id });
          }

          var command = new LightCommand();
          command.Hue = 65280;
          command.Saturation = 255;
          command.Brightness = 255;
          command.On = true;
          command.TransitionTime = TimeSpan.FromTicks(1);

          await client.SendCommandAsync(command, new[] { light.Id });

          previousLight = light;
        }
      }

      var c = new LightCommand();
      c.Hue = 25500;
      c.Saturation = 255;
      c.Brightness = 255;
      c.On = true;
      c.TransitionTime = TimeSpan.FromTicks(1);

      await client.SendCommandAsync(c, new[] { previousLight.Id });


      base.ApplicationStartup(container, pipelines);
    }