Esempio n. 1
0
        private void SetColour(string colour)
        {
            var command = new LightCommand();

            command.TurnOn().SetColor(colour);
            command.Alert      = Alert.Once;
            command.Brightness = (byte)(((double)_intensity / (double)MAX_INTENSITY) * (double)(byte.MaxValue));
            command.Effect     = Effect.None;
            _hueClient.SendCommandAsync(command, _lights);
        }
Esempio n. 2
0
        private async void SendGroupCommand(int delay = 0)
        {
            lastCommand = DateTime.Now;
            await Task.Delay(delay);

            if (delay == 0 || DateTime.Now - lastCommand >= new TimeSpan(0, 0, 0, 0, delay))
            {
                IsLoading = true;
                var appliance = Appliances.FirstOrDefault() as Light;
                if (appliance != null)
                {
                    try
                    {
                        var client = new HueClient(appliance.HueUser);
                        await client.SendCommandAsync(HueGroup);
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.Debugger.WriteErrorLog("Error occurred while sending group command.", ex);
                        await new MessageDialog("Error occurred while sending group command: " + ex.Message).ShowAsync();
                    }
                }
                IsLoading = false;
            }
        }
Esempio n. 3
0
        /// <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}");
                }
            }
        }
Esempio n. 4
0
 public void UpdateLight(LightCommand cmd)
 {
     _lastCmd = cmd;
     if (_hue != null)
     {
         _hue.SendCommandAsync(cmd, new string[] { _lightID });
     }
 }
Esempio n. 5
0
 private async Task UpdateSaturation(int sat, IReadOnlyCollection <string> lightIds)
 {
     _logger.LogDebug("Setting saturation to {sat} for light(s) {lights}...", sat, string.Join(',', lightIds));
     var command = new LightCommand {
         Saturation = sat
     };
     await HueClient.SendCommandAsync(command, lightIds);
 }
Esempio n. 6
0
 private async Task SetColorRed(IReadOnlyCollection <string> lightIds)
 {
     _logger.LogDebug("Setting color to red for light(s) {lights}...", string.Join(',', lightIds));
     // "xy":[0.675,0.322]is red.
     var command = new LightCommand {
         ColorCoordinates = new[] { 0.675, 0.322 }
     };
     await HueClient.SendCommandAsync(command, lightIds);
 }
Esempio n. 7
0
        private void RedAction()
        {
            LightCommand command = new LightCommand();

            command.TurnOn().SetColor("FF0000");

            _hueClient.SendCommandAsync(command);
        }
        private async void SendCommand()
        {
            lastCommand = DateTime.Now;
            await Task.Delay(1000);

            if (DateTime.Now - lastCommand >= new TimeSpan(0, 0, 1))
            {
                IsLoading = true;
                var client = new HueClient(Light.HueUser);
                await client.SendCommandAsync(Light.HueLight);

                IsLoading = false;
            }
        }
Esempio n. 9
0
 private async Task RestoreOriginalValues(IEnumerable <Light> colorLights, IEnumerable <Light> ambianceLights)
 {
     var colorTasks = colorLights.Select(light => HueClient.SendCommandAsync(new LightCommand
     {
         On = light.State.On, ColorCoordinates = light.State.ColorCoordinates, Hue = light.State.Hue
     },
                                                                             new[] { light.Id }));
     var ambianceTasks = ambianceLights.Select(light => HueClient.SendCommandAsync(new LightCommand
     {
         On = light.State.On, ColorTemperature = light.State.ColorTemperature
     },
                                                                                   new[] { light.Id }));
     var tasks = Enumerable.Union(colorTasks, ambianceTasks).ToList();
     await Task.WhenAll(tasks);
 }
Esempio n. 10
0
        private async void SendCommand(RGBColor?color = null)
        {
            lastCommand = DateTime.Now;
            await Task.Delay(1000);

            if (DateTime.Now - lastCommand >= new TimeSpan(0, 0, 1))
            {
                IsLoading = true;
                var client = new HueClient(Light.HueUser);
                Light.HueLight = await client.SendCommandAsync(Light.HueLight, color);

                IsLoading = false;
                RaisePropertyChanged("Light");
                RaisePropertyChanged("ColorBrush");
            }
        }
Esempio n. 11
0
        public override void OnExecute()
        {
            Hue = Context.CredentialProvider.Get <HueCredential, LocalHueClient>();

            var cmd = new LightCommand();

            cmd.TurnOn();

            var result = Hue.SendCommandAsync(
                cmd,
                new string[] { LightId }).Result;

            if (result.HasErrors())
            {
                throw new InvalidOperationException("");
            }
        }
Esempio n. 12
0
        private async void SendSceneCommand()
        {
            if (SelectedHueScene != null)
            {
                IsLoading = true;
                var appliance = Appliances.FirstOrDefault() as Light;
                if (appliance != null && SelectedHueScene != null)
                {
                    try
                    {
                        var client = new HueClient(appliance.HueUser);
                        await client.SendCommandAsync(SelectedHueScene);

                        HueGroup = await client.GetHueGroupByIdAsync(HueGroup.Id);
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.Debugger.WriteErrorLog("Error occurred while sending scene command.", ex);
                        await new MessageDialog("Error occurred while sending scene command: " + ex.Message).ShowAsync();
                    }
                }
                IsLoading = false;
            }
        }
Esempio n. 13
0
        private static async Task PerformDayNightCycling(HueClient hueClient, int colorTemperature, DateTimeOffset currentTime, AppState appState, Configuration configuration)
        {
            var allLights = await hueClient.GetLightsAsync();

            var lights = allLights.ToList();

            var idToLights = allLights.ToDictionary(x => x.Id, x => x);

            var nameToLights            = allLights.ToDictionary(x => x.Name, x => x);
            var namesOfLightsToExclude  = configuration.NamesOfLightsToExclude.ToHashSet();
            var lightsAvailableToChange = allLights.Where(x => x.State.On && x.State.ColorTemperature != colorTemperature && !namesOfLightsToExclude.Contains(x.Name));

            var lightsToChange = new List <Light>();

            foreach (var light in lights)
            {
                if (!appState.Lights.TryGetValue(light.Id, out var state))
                {
                    state = appState.Lights[light.Id] = new LightControlStatus(DateTimeOffset.MinValue, currentTime, DateTimeOffset.MinValue, DateTimeOffset.MinValue, TimeSpan.Zero, LightControlState.Off, light);
                }
            }

            var sunriseAndSunset = GetSunriseAndSunset(currentTime, configuration);

            var shouldDoSlowTransitionAtSunriseOrSunset = (appState.LastRunTime <sunriseAndSunset.sunrise && currentTime> sunriseAndSunset.sunrise) || (appState.LastRunTime <sunriseAndSunset.sunset && currentTime> sunriseAndSunset.sunset);

            var transitionTimeForBatch = configuration.TransitionTime;

            if (shouldDoSlowTransitionAtSunriseOrSunset)
            {
                Console.WriteLine($"{DateTime.Now}: all lights -> { colorTemperature }.  sunrise: {sunriseAndSunset.sunrise} sunset: {sunriseAndSunset.sunrise}");
                Console.WriteLine();

                transitionTimeForBatch = configuration.TransitionTimeAtSunriseAndSunset;
                foreach (var light in lights)
                {
                    var state = appState.Lights[light.Id];
                    if (!light.State.On)
                    {
                        state.LightControlState           = LightControlState.Off;
                        state.HueShiftTookControlTime     = DateTimeOffset.MinValue;
                        state.TransitionRequestedTime     = DateTimeOffset.MinValue;
                        state.RequestedTransitionDuration = TimeSpan.Zero;
                        state.DetectedOnTime = DateTimeOffset.MinValue;
                    }
                    else
                    {
                        lightsToChange.Add(light);
                        state.LightControlState           = LightControlState.Transitioning;
                        state.HueShiftTookControlTime     = currentTime;
                        state.TransitionRequestedTime     = currentTime;
                        state.RequestedTransitionDuration = configuration.TransitionTimeAtSunriseAndSunset;
                        state.DetectedOnTime = currentTime;
                    }
                }
            }
            else
            {
                foreach (var light in lights)
                {
                    var state = appState.Lights[light.Id];

                    if (!light.State.On)
                    {
                        state.LightControlState           = LightControlState.Off;
                        state.HueShiftTookControlTime     = DateTimeOffset.MinValue;
                        state.TransitionRequestedTime     = DateTimeOffset.MinValue;
                        state.RequestedTransitionDuration = TimeSpan.Zero;
                        state.DetectedOnTime = DateTimeOffset.MinValue;
                    }
                    else
                    {
                        switch (state.LightControlState)
                        {
                        case LightControlState.Off:
                            lightsToChange.Add(light);
                            state.LightControlState           = LightControlState.Transitioning;
                            state.HueShiftTookControlTime     = currentTime;
                            state.TransitionRequestedTime     = currentTime;
                            state.RequestedTransitionDuration = configuration.TransitionTime;
                            state.DetectedOnTime = currentTime;
                            break;

                        case LightControlState.Transitioning:
                            TimeSpan transitionTimeElapsed = currentTime - state.TransitionRequestedTime;
                            var      allowedTolerance      = TimeSpan.FromSeconds(10);

                            bool hasTransitionTimeElapsed = transitionTimeElapsed > (state.RequestedTransitionDuration + allowedTolerance);

                            if ((light.State.ColorTemperature == colorTemperature) || hasTransitionTimeElapsed)
                            {
                                state.LightControlState           = LightControlState.HueShiftAutomated;
                                state.TransitionRequestedTime     = DateTimeOffset.MinValue;
                                state.RequestedTransitionDuration = TimeSpan.Zero;
                            }
                            break;

                        case LightControlState.HueShiftAutomated:
                            if (light.State.ColorTemperature != colorTemperature)
                            {
                                state.LightControlState = LightControlState.ManualControl;
                            }
                            break;

                        case LightControlState.ManualControl:
                            break;
                        }
                    }
                }
            }

            appState.LastRunTime = currentTime;
            foreach (var onLight in lightsToChange)
            {
                Console.WriteLine($"{DateTime.Now}: Light { onLight.Name } switching { onLight.State.ColorTemperature } -> { colorTemperature }");
            }

            if (lightsToChange.Count > 0)
            {
                var command = new LightCommand();
                command.ColorTemperature = colorTemperature;
                command.TransitionTime   = transitionTimeForBatch;

                await hueClient.SendCommandAsync(command, lightsToChange.Select(x => x.Id).ToList());
            }
        }
Esempio n. 14
0
        public void SetColor(LightSource ls, Color c)
        {
            var colorHex = Helpers.ColorToHex(c);

            _client.SendCommandAsync(new LightCommand().SetColor(colorHex), new[] { ls.SystemId });
        }