Example #1
0
        private byte ChangeBrightness(int value)
        {
            var currentGroup = GroupDictionary[CurrentRoom.Value];

            var currentBrightness = currentGroup.Action.Brightness;
            var delta             = 5 * GetSign(value);
            var newBrightness     = currentBrightness + (byte)delta;
            var command           = new LightCommand {
                BrightnessIncrement = delta
            };

            var currentState = OnOffStateForGroups[currentGroup];

            if (!currentState)
            {
                command.On = true;
            }
            if (newBrightness <= 0)
            {
                command.On = false;
            }

            HueClient.SendGroupCommandAsync(command, currentGroup.Id);
            return((byte)newBrightness);
        }
Example #2
0
 public void Stop()
 {
     _hue = null;
     // this stop's UpdateLight from sending any more commands
     // but still continues to record the last/current color so it can be
     // sent when it's turned back on again
 }
Example #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}");
                }
            }
        }
Example #4
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;
            }
        }
Example #5
0
    public async Task CheckConnectionWrongKeyTest()
    {
      IHueClient client = new HueClient(ConfigurationManager.AppSettings["ip"].ToString(), "wrongkey123");

      var result = await client.CheckConnection();

      Assert.IsFalse(result);
    }
Example #6
0
        public async Task CheckConnectionWrongIpTest()
        {
            IHueClient client = new HueClient("42.1.1.1", ConfigurationManager.AppSettings["key"].ToString());

            var result = await client.CheckConnection();

            Assert.IsFalse(result);
        }
Example #7
0
        public async Task CheckConnectionWrongKeyTest()
        {
            IHueClient client = new HueClient(ConfigurationManager.AppSettings["ip"].ToString(), "wrongkey123");

            var result = await client.CheckConnection();

            Assert.IsFalse(result);
        }
Example #8
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);
 }
Example #9
0
    public async Task CheckConnectionWrongIpTest()
    {
      IHueClient client = new HueClient("42.1.1.1", ConfigurationManager.AppSettings["key"].ToString());

      var result = await client.CheckConnection();

      Assert.IsFalse(result);
    }
Example #10
0
        protected TestBase(ITestOutputHelper outputHelper)
        {
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new XunitLoggerProvider(outputHelper));
            _client = new HueClient(loggerFactory, DEV_USER, DEV_ADDRESS);
            _logger = loggerFactory.CreateLogger(GetType().Name);
        }
Example #11
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);
 }
Example #12
0
        public HueLightingSystem(string name, string ip)
        {
            //var bridges = GetBridges();


            _client = new HueClient(ip);
            _client.RegisterAsync("ubilight", "ubilightkey");
            _client.Initialize("ubilightkey");
            Name = name;
        }
Example #13
0
        public override void OnExecute()
        {
            Hue = Context.CredentialProvider.Get <HueCredential, LocalHueClient>();

            var lights = Hue.GetLightsAsync().Result;

            foreach (var light in lights)
            {
                Console.WriteLine(light.Id);
            }
        }
Example #14
0
        private async void LocateBridgeAction()
        {
            var result = await LocateBridgeDataLoader.LoadAsync(() => httpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5)));

            HttpBridges = string.Join(", ", result.ToArray());

            if (result.Count() > 0)
            {
                _hueClient = new HueClient(result.First());
            }
        }
Example #15
0
        private bool SwitchGroupOnOff()
        {
            var currentGroup = GroupDictionary[CurrentRoom.Value];
            var currentState = OnOffStateForGroups[currentGroup];
            var newState     = !currentState;
            var command      = new LightCommand {
                On = newState
            };

            HueClient.SendGroupCommandAsync(command, currentGroup.Id);
            return(newState);
        }
Example #16
0
        //private BridgeInfo _hueBridge;

        public ReleaseNight()
        {
            InitializeComponent();

            _navigationHelper            = new NavigationHelper(this);
            _navigationHelper.LoadState += NavigationHelperOnLoadState;
            _navigationHelper.SaveState += (sender, args) => { MediaSimple.MediaPlayer.Pause(); };

            //Task.Run(() => this.GetHueInfo()).Wait();
            //_hueClient = new LocalHueClient(_hueBridge.internalipaddress);
            //_hueClient.Initialize("");
            _hueClient = new LocalHueClient("10.10.10.193");
            _hueClient.Initialize("CqnjoQvPHKdy1IkFVJggaTdflgWBF1HWQTOZYf2p");
        }
        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;
            }
        }
Example #18
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);
 }
Example #19
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");
            }
        }
Example #20
0
        private async void SsdpLocateBridgeAction()
        {
            var result = await SsdpLocateBridgeDataLoader.LoadAsync(() => ssdpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5)));

            if (result == null)
            {
                result = new List <string>();
            }

            SsdpBridges = string.Join(", ", result.ToArray());

            if (result.Count() > 0)
            {
                _hueClient = new HueClient(result.First());
            }
        }
Example #21
0
        public void SetBridge(string bridgeIP, string appKey, bool alreadyRegistered)
        {
            _hue = new HueClient(bridgeIP);

            if (alreadyRegistered)
            {
                _hue.Initialize(appKey);
            }
            else
            {
                var retryCount = 0;
                var regOk      = false;
                while (!regOk || retryCount >= RETRY_MAX)
                {
                    var reg = _hue.RegisterAsync(APP_NAME, appKey);
                    reg.Wait();
                    if (!reg.Result)
                    {
                        ShowWarning("Please press the button on the bridge to register the application", 30);
                    }
                    else
                    {
                        regOk = true;
                    }

                    retryCount++;
                    if (!regOk && retryCount < RETRY_MAX)
                    {
                        Thread.Sleep(RETRY_DELAY);
                    }
                }

                if (!regOk)
                {
                    ShowError("Failed to register application with bridge", 30);
                }
            }

            var lights = _hue.GetLightsAsync();

            lights.Wait();

            var choices = lights.Result.Select(x => new Tuple <string, string>(x.Id, string.Format("{0} ({1})", x.Name, x.Type))).ToList();

            UpdateLightChoice(choices);
        }
Example #22
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("");
            }
        }
Example #23
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;
            }
        }
Example #24
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);
        }
Example #25
0
        //private BridgeInfo _hueBridge;

        public RedAlert()
        {
            InitializeComponent();

            _navigationHelper            = new NavigationHelper(this);
            _navigationHelper.LoadState += NavigationHelperOnLoadState;
            _navigationHelper.SaveState += (sender, args) => { MediaSimple.MediaPlayer.Pause(); };

            //Task.Run(() => this.GetHueInfo()).Wait();
            //_hueClient = new LocalHueClient(_hueBridge.internalipaddress);
            //_hueClient.Initialize("");

            //TODO: Complete Hue bridge self discovery
            //Until then I utilized the instructions at  https://developers.meethue.com/documentation/getting-started
            // to hard code my info gathered from my router.
            _hueClient = new LocalHueClient("10.10.10.193");
            _hueClient.Initialize("CqnjoQvPHKdy1IkFVJggaTdflgWBF1HWQTOZYf2p");
        }
Example #26
0
        /// <summary>
        /// Called when the package is started.
        /// </summary>
        public override void OnStart()
        {
            PackageHost.WriteInfo("Connecting to " + PackageHost.GetSettingValue <string>("BridgeAddress"));
            hueClient = new HueClient(PackageHost.GetSettingValue <string>("BridgeAddress"));
            hueClient.Initialize(PackageHost.GetSettingValue <string>("BridgeUsername"));

            PackageHost.WriteInfo("Getting configuration");
            var bridge = hueClient.GetBridgeAsync().GetAwaiter().GetResult();

            PackageHost.PushStateObject <BridgeConfig>("BridgeConfig", bridge.Config);
            foreach (Light light in bridge.Lights)
            {
                PackageHost.PushStateObject <Light>(light.Name, light);
            }

            PackageHost.WriteInfo("Starting query process");
            Task.Factory.StartNew(() =>
            {
                int pause = 1000;
                while (PackageHost.IsRunning)
                {
                    try
                    {
                        var lights = hueClient.GetLightsAsync().GetAwaiter().GetResult();
                        foreach (Light light in lights)
                        {
                            PackageHost.PushStateObject <Light>(light.Name, light);
                        }
                        pause = 1000;
                    }
                    catch (Exception ex)
                    {
                        if (pause < 60000)
                        {
                            pause *= 2;
                        }
                        PackageHost.WriteError("Error to query lights : {0}", ex.ToString());
                    }
                    Thread.Sleep(pause);
                }
            });

            PackageHost.WriteInfo("Connected to {0}", hueClient.ApiBase);
        }
Example #27
0
        private async Task SetupHue()
        {
            await SetupHueClient();

            var groups = await HueClient.GetGroupsAsync();

            FillGroupDictionary(groups);

            OnOffStateForGroups =
                groups.ToDictionary(group => group, group => group.State.AnyOn == true);

            Rooms       = new LinkedList <RoomClass>(GroupDictionary.Keys);
            CurrentRoom = Rooms.Find(RoomClass.LivingRoom);
            if (CurrentRoom == null)
            {
                CurrentRoom = Rooms.First;
            }
            IsInitialized = true;
        }
Example #28
0
        //private BridgeInfo _hueBridge;

        public Imperial()
        {
            InitializeComponent();

            _navigationHelper            = new NavigationHelper(this);
            _navigationHelper.LoadState += NavigationHelperOnLoadState;
            //_navigationHelper.SaveState += (sender, args) => { MediaSimple.MediaPlayer.Pause(); };

            //Task.Run(() => this.GetHueInfo()).Wait();
            //_hueClient = new LocalHueClient(_hueBridge.internalipaddress);
            //_hueClient.Initialize("");

            BitmapImage bitmapImage = new BitmapImage();

            // Call BaseUri on the root Page element and combine it with a relative path
            // to consruct an absolute URI.
            bitmapImage.UriSource = new Uri(BaseUri, "/Assets/vadar2.jpg");
            IMImage.Source        = bitmapImage;


            _hueClient = new LocalHueClient("10.10.10.193");
            _hueClient.Initialize("CqnjoQvPHKdy1IkFVJggaTdflgWBF1HWQTOZYf2p");
        }
Example #29
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;
            }
        }
Example #30
0
				private async void SsdpLocateBridgeAction()
				{
					var result = await SsdpLocateBridgeDataLoader.LoadAsync(() => ssdpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5)));

					SsdpBridges = string.Join(", ", result.ToArray());

					if (result.Count() > 0)
						_hueClient = new HueClient(result.First());
				}
Example #31
0
				internal void ManualRegister(string ip)
				{
					_hueClient = new HueClient(ip);
				}
Example #32
0
        public static async Task RunLightControl(Configuration configuration, HueClient hueClient)
        {
            var timeBetweenChecks = new TimeSpan(Math.Max(configuration.TransitionTime.Ticks, configuration.PollingFrequency.Ticks));

            await AsyncUtils.ContinuallyExecuteReportingExceptionsOnlyOnce(async() =>
            {
                var dmxUniverse = configuration.DMXConfiguration.Universe;

                RunningState runningState = RunningState.HueShift;
                using (var controller = new ArtNetController())
                {
                    controller.Address = IPAddress.Parse(configuration.DMXConfiguration.ListeningIPAddress);

                    var groups = await hueClient.GetGroupsAsync();

                    var dmxControlGroupName = "DmxControlGroup";
                    foreach (var item in groups)
                    {
                        if (item.Name == dmxControlGroupName)
                        {
                            await hueClient.DeleteGroupAsync(item.Id);
                            Console.WriteLine("Deleting existing control group: " + item.Id);
                        }
                    }

                    // var groupId = await hueClient.CreateGroupAsync(
                    //     configuration.DMXConfiguration.LightIdsInDmxGroup.Select(x => x.ToString()).ToList(),
                    //     dmxControlGroupName,
                    //     null,
                    //     Q42.HueApi.Models.Groups.GroupType.LightGroup);

                    var stateQueue = new ConcurrentQueue <LightState>();

                    var startingChannel           = configuration.DMXConfiguration.StartingChannel;
                    controller.DmxPacketReceived += (sender, packet) =>
                    {
                        if (packet.SubUniverse != dmxUniverse)
                        {
                            return;
                        }

                        LightState state = new LightState(
                            packet.Data[startingChannel] > 0,
                            packet.Data[startingChannel + 1],
                            packet.Data[startingChannel + 2]);

                        if (state.IsOn)
                        {
                            //Sanity check to prevent runawayqueu
                            const int maxQueueSize = 10000;
                            if (stateQueue.Count < maxQueueSize)
                            {
                                stateQueue.Enqueue(state);
                            }
                        }
                        else
                        {
                            //Console.Write("D");
                        }
                    };

                    controller.Start();

                    var lastApiSentTime           = DateTimeOffset.MinValue;
                    var lastTimeDmxPacketDetected = DateTimeOffset.MinValue;

                    // LightState lastSentLightState = new LightState();
                    Console.WriteLine("_------------------STARTING ");

                    var controlState = new Dictionary <string, LightControlStatus>();

                    var sunriseSunsetState = new AppState();
                    while (true)
                    {
                        switch (runningState)
                        {
                        case RunningState.HueShift:
                            var currentTime = DateTimeOffset.Now;

                            int colorTemperature = GetTargetColorTemperature(currentTime, configuration);

                            await PerformDayNightCycling(hueClient, colorTemperature, currentTime, sunriseSunsetState, configuration);

                            var timeStartedWaiting = DateTimeOffset.Now;
                            do
                            {
                                if (!stateQueue.IsEmpty)
                                {
                                    lastTimeDmxPacketDetected = DateTimeOffset.Now;
                                    runningState = RunningState.DMX;
                                    Console.WriteLine("DMX Mode detected");
                                    break;
                                }
                                else
                                {
                                    Thread.Sleep(configuration.DMXConfiguration.MillisToSleepBetweenQueueChecks);

                                    //await Task.Delay(.0).ConfigureAwait(false);
                                }
                            } while ((DateTimeOffset.Now - timeStartedWaiting) < timeBetweenChecks);

                            break;

                        default:
                            break;
                            // case RunningState.DMX:

                            //     var transitionDuration = configuration.DMXConfiguration.TransitionTime;
                            //     var minWaitDurationBetweenApiCalls = configuration.DMXConfiguration.MinWaitDurationBetweenApiCalls;

                            //     var timeSinceLastSend = DateTimeOffset.Now - lastApiSentTime;

                            //     var timeSinceLastReceivedDMXPacket = DateTimeOffset.Now - lastTimeDmxPacketDetected;

                            //     LightState mostCurrentLightState = new LightState();

                            //     bool haveReceivedNextDMXPacket = false;
                            //     while (timeSinceLastSend < minWaitDurationBetweenApiCalls)
                            //     {
                            //         Thread.Sleep(configuration.DMXConfiguration.MillisToSleepBetweenQueueChecks);

                            //         LightState latestLightState;
                            //         while (stateQueue.TryDequeue(out latestLightState))
                            //         {
                            //             mostCurrentLightState = latestLightState;
                            //             haveReceivedNextDMXPacket = true;
                            //             lastTimeDmxPacketDetected = DateTime.Now;
                            //         }

                            //         timeSinceLastSend = DateTimeOffset.Now - lastApiSentTime;
                            //     }

                            //     if (!haveReceivedNextDMXPacket)
                            //     {
                            //         LightState latestLightState;
                            //         while (!stateQueue.TryDequeue(out latestLightState))
                            //         {
                            //             Thread.Sleep(configuration.DMXConfiguration.MillisToSleepBetweenQueueChecks);

                            //             if ((DateTimeOffset.Now - lastTimeDmxPacketDetected) > configuration.DMXConfiguration.TimeAfterLastDmxPacketToReturnToShifting)
                            //             {
                            //                 runningState = RunningState.HueShift;
                            //                 break;
                            //             }
                            //         }

                            //         mostCurrentLightState = latestLightState;
                            //         haveReceivedNextDMXPacket = true;
                            //         lastTimeDmxPacketDetected = DateTime.Now;
                            //     }

                            //     if (runningState == RunningState.DMX)
                            //     {
                            //         if (!mostCurrentLightState.Equals(lastSentLightState))
                            //         {
                            //             Console.WriteLine();
                            //             var command = new LightCommand();

                            //             if (mostCurrentLightState.Brightness != lastSentLightState.Brightness)
                            //                 command.Brightness = mostCurrentLightState.Brightness;

                            //             //if (latest.ColorTemperature != last.ColorTemperature)
                            //             //    command.ColorTemperature = (int)map(latest.ColorTemperature, 0, 255, (float)ColorTemperature.Blue, (float)ColorTemperature.Red);

                            //             command.TransitionTime = transitionDuration;

                            //             Console.Write($"Setting: {mostCurrentLightState.IsOn} {mostCurrentLightState.Brightness} {mostCurrentLightState.ColorTemperature}");

                            //             var hueResults = await hueClient.SendGroupCommandAsync(command, groupId);

                            //             foreach (var error in hueResults.Errors)
                            //             {
                            //                 Console.WriteLine($"Error: {error}");
                            //             }

                            //             lastApiSentTime = DateTimeOffset.Now;
                            //             lastSentLightState = mostCurrentLightState;
                            //         }
                            //     }

                            //     break;
                        }
                    }
                }
            });
        }
Example #33
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());
            }
        }
Example #34
0
 static Task <HttpResponseMessage> StreamAsync(HueClient hueClient, CancellationToken cancellationToken = default)
 => hueClient.StreamEventAsync(cancellationToken);