コード例 #1
0
        /// <summary>
        /// Builds the request that can be sent with a <see cref="Net.HueClient"/>.
        /// </summary>
        public IHueRequest Build()
        {
            var result = new SetLightStateRequest(_lightId);

            if (_isOn.HasValue)
            {
                result.Status.IsOn = _isOn.Value;
            }
            if (_hue.HasValue)
            {
                result.Status.Hue = _hue.Value;
            }
            if (_sat.HasValue)
            {
                result.Status.Saturation = _sat.Value;
            }
            if (_bri.HasValue)
            {
                result.Status.Brightness = _bri.Value;
            }
            if (_coordinates != null)
            {
                result.Status.Coordinates = _coordinates.ToArray();
            }
            if (_hueInc.HasValue)
            {
                ((SetLightState)result.Status).HueIncrement = _hueInc.Value;
            }
            if (_satInc.HasValue)
            {
                ((SetLightState)result.Status).SaturationIncrement = (short)_satInc.Value;
            }
            if (_briInc.HasValue)
            {
                ((SetLightState)result.Status).BrightnessIncrement = (short)_briInc.Value;
            }
            if (_colorTemperature.HasValue)
            {
                result.Status.ColorTemperature = _colorTemperature.Value;
            }
            if (_loop.HasValue)
            {
                result.Status.Effect = _loop.Value ? LightEffect.ColorLoop : LightEffect.None;
            }
            if (_alert == LightAlert.Once || _alert == LightAlert.Cycle)
            {
                result.Status.Alert = _alert;
            }

            if (result.Status.HasUnsavedChanges && _transitionTime.HasValue)
            {
                result.Status.TransitionTime = _transitionTime.Value;
            }
            return(result);
        }
コード例 #2
0
 public async Task Execute(SetLightStateRequest request)
 {
     try
     {
         await PostAsync("/api/lights/set-light-state", request);
     }
     catch (Exception exception)
     {
         var kek = 5;
     }
 }
コード例 #3
0
ファイル: LightsAPI.cs プロジェクト: preardon/HueController
        /// <summary>
        /// Allows the user to turn the light on and off, modify the hue and effects.
        /// </summary>
        /// <param name="id">Id of Light to be set</param>
        /// <param name="request">Request for the light</param>
        /// <returns></returns>
        public async Task <bool> SetStateAsync(string id, SetLightStateRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var requestContent = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
            var response       = await _httpClient.PutAsync($"/api/{_userName}/lights/{id}/state", requestContent, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                return(true);
            }

            return(false);
        }
コード例 #4
0
        public async Task <IActionResult> SetLightState([FromBody] SetLightStateRequest request)
        {
            try
            {
                await lighting.SetLightStateAsync(request);

                return(StandardResponse());
            }
            catch (Exception exception)
            {
                return(ErrorResponse(exception));
            }
        }
コード例 #5
0
        public async Task SetLightStateAsync(SetLightStateRequest request)
        {
            var client = await GetClientAsync();

            var command = new LightCommand
            {
                On             = request.PowerState,
                TransitionTime = request.TransitionTime ?? Config.TransitionTime,
                Brightness     = request.Brightness ?? 255
            };

            // TODO: Investigate the results to see what decent info could be returned e.g. errors
            await client.SendCommandAsync(command, request.LightIds);
        }
コード例 #6
0
        public async Task <JsonResult> SetGroupState(string user, string id, [FromBody] GroupActionRequest newGroupAction)
        {
            // authentication
            if (!_grp.AuthenticatorInstance.IsValidUser(user))
            {
                return(Json(_grp.AuthenticatorInstance.ErrorResponse(Request.Path.ToString())));
            }

            var lights = _grp.DatabaseInstance.GetCollection <Light>("lights");
            var groups = _grp.DatabaseInstance.GetCollection <Group>("groups");
            var group  = Convert.ToInt64(id) > 0 ? groups.FindById(Convert.ToInt64(id)) : new Group
            {
                Id     = 0, // special group that contains all lights: 0
                Class  = "Other",
                Name   = "All lights",
                Lights = lights.FindAll().Select(x => Convert.ToString(x.Id)).ToList(),
                State  = new GroupState(),
                Action = new GroupAction()
            };

            if (group == null)
            {
                return(Json(new
                {
                    failure = $"group {id} not found"
                }));
            }

            var ret = new List <Dictionary <string, object> >();

            if (newGroupAction.Scene != null)
            {
                // change scene on group
                var scenes = _grp.DatabaseInstance.GetCollection <Scene>("scenes");
                var scene  = scenes.FindById(Convert.ToInt64(newGroupAction.Scene));
                if (scene == null)
                {
                    return(Json(new
                    {
                        failure = $"scene {newGroupAction.Scene} not found"
                    }));
                }

                // find the lights and their lightstate in the scene
                var newLightStates = scene.LightStates.Where(x => group.Lights.Contains(x.Key));
                var tasks          = new List <Task <HttpResponseMessage> >();
                var settings       = new JsonSerializerSettings();
                settings.ContractResolver = new DefaultContractResolver {
                    NamingStrategy = new Utilities.LowercaseNamingStrategy()
                };
                foreach (var l in newLightStates)
                {
                    var lightstate_request_url = $"{Request.Scheme}://{Request.Host.ToString()}/api/{user}/lights/{l.Key}/state";
                    var content = new StringContent(JsonConvert.SerializeObject(l.Value, settings), Encoding.UTF8, "application/json");
                    tasks.Add(_client.PutAsync(lightstate_request_url, content));
                }

                try
                {
                    await Task.WhenAll(tasks.ToArray());

                    ret.Add(new Dictionary <string, object>
                    {
                        ["success"] = new Dictionary <string, object>
                        {
                            [$"/groups/{id}/state/scene"] = newGroupAction.Scene
                        }
                    });
                }
                catch (Exception ex)
                {
                    return(Json(new
                    {
                        failure = $"group {id} failed to change to new scene {ex.Message}"
                    }));
                }
            }
            else
            {
                var pp        = typeof(GroupAction).GetProperties().ToList();
                var ppp       = typeof(SetLightStateRequest).GetProperties().ToList();
                var colormode = "";
                var req       = new SetLightStateRequest();

                foreach (var p in typeof(GroupActionRequest).GetProperties())
                {
                    var pv = p.GetValue(newGroupAction, null);
                    if (pv != null)
                    {
                        if (p.Name.EndsWith("_inc"))
                        {
                            var pName      = p.Name.Replace("_inc", "");
                            var ppOrgValue = pp.Find(x => x.Name == pName).GetValue(group.Action, null);
                            if (ppOrgValue != null)
                            {
                                pp.Find(x => x.Name == pName).SetValue(group.Action, Convert.ToUInt32((uint)ppOrgValue + (int)pv));
                                ppp.Find(x => x.Name == pName).SetValue(req, Convert.ToUInt32((uint)ppOrgValue + (int)pv));
                            }

                            ret.Add(new Dictionary <string, object>
                            {
                                ["success"] = new Dictionary <string, object>
                                {
                                    [$"/groups/{id}/state/{pName.ToLower()}"] = Convert.ToUInt32((uint)ppOrgValue + (int)pv)
                                }
                            });
                        }
                        else
                        {
                            try
                            {
                                pp.Find(x => x.Name == p.Name).SetValue(group.Action, pv);
                                ppp.Find(x => x.Name == p.Name).SetValue(req, pv);
                                ret.Add(new Dictionary <string, object>
                                {
                                    ["success"] = new Dictionary <string, object>
                                    {
                                        [$"/groups/{id}/state/{p.Name.ToLower()}"] = pv
                                    }
                                });
                            }
                            catch
                            {
                                Console.WriteLine($"Cannot set group state: {p.Name}");
                            }
                        }

                        // colormode priority system: xy > ct > hs
                        switch (p.Name)
                        {
                        case nameof(SetLightStateRequest.Hue):
                        case nameof(SetLightStateRequest.Hue_inc):
                        case nameof(SetLightStateRequest.Sat):
                        case nameof(SetLightStateRequest.Sat_inc):
                            colormode = colormode == "" ? "hs" : colormode;
                            break;

                        case nameof(SetLightStateRequest.XY):
                        case nameof(SetLightStateRequest.XY_inc):
                            colormode = "xy";
                            break;

                        case nameof(SetLightStateRequest.CT):
                        case nameof(SetLightStateRequest.CT_inc):
                            colormode = colormode != "xy" ? "ct" : colormode;
                            break;

                        default:
                            break;
                        }
                    }
                }
                if (colormode != "")
                {
                    group.Action.ColorMode = colormode;
                }

                // find the lights and their lightstate in the scene
                var tasks    = new List <Task <HttpResponseMessage> >();
                var settings = new JsonSerializerSettings();
                settings.ContractResolver = new DefaultContractResolver {
                    NamingStrategy = new Utilities.LowercaseNamingStrategy()
                };
                foreach (var l in group.Lights)
                {
                    var lightstate_request_url = $"{Request.Scheme}://{Request.Host.ToString()}/api/{user}/lights/{l}/state";
                    var content = new StringContent(JsonConvert.SerializeObject(req, settings), Encoding.UTF8, "application/json");
                    tasks.Add(_client.PutAsync(lightstate_request_url, content));
                }
            }
            groups.Update(group);

            return(Json(ret));
        }
コード例 #7
0
        public async Task <JsonResult> SetLightState(string user, string id, [FromBody] SetLightStateRequest newState)
        {
            // authentication
            if (!_grp.AuthenticatorInstance.IsValidUser(user))
            {
                return(Json(_grp.AuthenticatorInstance.ErrorResponse(Request.Path.ToString())));
            }

            var lights = _grp.DatabaseInstance.GetCollection <Light>("lights");
            var light  = lights.FindById(Convert.ToInt64(id));

            if (light == null)
            {
                return(Json(new
                {
                    failure = $"light {id} not found"
                }));
            }
            var pp        = typeof(LightState).GetProperties().ToList();
            var ret       = new List <Dictionary <string, object> >();
            var colormode = "";

            foreach (var p in typeof(SetLightStateRequest).GetProperties())
            {
                var pv = p.GetValue(newState, null);
                if (pv != null)
                {
                    if (p.Name.EndsWith("_inc"))
                    {
                        var pName      = p.Name.Replace("_inc", "");
                        var ppOrgValue = pp.Find(x => x.Name == pName).GetValue(light.State, null);
                        if (ppOrgValue != null)
                        {
                            pp.Find(x => x.Name == pName).SetValue(light.State, Convert.ToUInt32((uint)ppOrgValue + (int)pv));
                        }

                        ret.Add(new Dictionary <string, object>
                        {
                            ["success"] = new Dictionary <string, object>
                            {
                                [$"/lights/{id}/state/{pName.ToLower()}"] = Convert.ToUInt32((uint)ppOrgValue + (int)pv)
                            }
                        });
                    }
                    else
                    {
                        try
                        {
                            pp.Find(x => x.Name == p.Name).SetValue(light.State, pv);
                            ret.Add(new Dictionary <string, object>
                            {
                                ["success"] = new Dictionary <string, object>
                                {
                                    [$"/lights/{id}/state/{p.Name.ToLower()}"] = pv
                                }
                            });
                        }
                        catch
                        {
                            Console.WriteLine($"Cannot set light state: {p.Name}");
                        }
                    }

                    // colormode priority system: xy > ct > hs
                    switch (p.Name)
                    {
                    case nameof(SetLightStateRequest.Hue):
                    case nameof(SetLightStateRequest.Hue_inc):
                    case nameof(SetLightStateRequest.Sat):
                    case nameof(SetLightStateRequest.Sat_inc):
                        colormode = colormode == "" ? "hs" : colormode;
                        break;

                    case nameof(SetLightStateRequest.XY):
                    case nameof(SetLightStateRequest.XY_inc):
                        colormode = "xy";
                        break;

                    case nameof(SetLightStateRequest.CT):
                    case nameof(SetLightStateRequest.CT_inc):
                        colormode = colormode != "xy" ? "ct" : colormode;
                        break;

                    default:
                        break;
                    }
                }
            }
            if (colormode != "")
            {
                light.State.ColorMode = colormode;
            }

            // call for light handlers
            var handler = _grp.LightHandlers.Where(x => x.SupportedModels.Contains(light.ModelId)).FirstOrDefault();

            if (handler == null)
            {
                return(Json(new
                {
                    failure = $"No handler found for /lights/{id}"
                }));
            }
            var result = await handler.SetLightState(light);

            if (result)
            {
                lights.Update(light);
                return(Json(ret));
            }
            else
            {
                return(Json(new
                {
                    failure = $"Failed to set light state for /lights/{id}"
                }));
            }
        }