Example #1
0
        public override int Run(string[] remainingArguments)
        {
            var parsedRemainingArgs = remainingArguments.Select(a =>
            {
                int i;
                var parsed = int.TryParse(a, out i);
                return new { Success = parsed, Value = i };
            });

            if (parsedRemainingArgs.Any(a => !a.Success) || parsedRemainingArgs.Select(a => a.Value).Except(ValidLightNumbers).Any())
            {
                var message = string.Format("Invalid light number specified. Valid lights are: [{0}]", string.Join(",", ValidLightNumbers));
                throw new ConsoleHelpAsException(message);
            }
            var lightNumbers = parsedRemainingArgs.Select(a => a.Value).ToArray();

            var affectedLights = lightNumbers.Any() ? lightNumbers : null;

            var command = new LightCommand { On = true };
            command.SetColor(this.Color ?? "FFFFFF");

            var whichLights = affectedLights != null ? ("lights " + string.Join(",", affectedLights)) : "all lights";
            this._outputStream.WriteLine("Sending light command to {0}...", whichLights);
            this._executor.ExecuteCommand(command, affectedLights);
            this._outputStream.WriteLine("Command successfully sent!");

            return 0;
        }
Example #2
0
        void monitor_AvailabilityChanged(Microsoft.Lync.Model.ContactAvailability availability, string activityId)
        {
            Q42.HueApi.LightCommand cmd = null;
            switch (availability)
            {
            case Microsoft.Lync.Model.ContactAvailability.Away:
            case Microsoft.Lync.Model.ContactAvailability.TemporarilyAway:
                cmd = _lightTheme.Away;
                break;

            case Microsoft.Lync.Model.ContactAvailability.Busy:
            case Microsoft.Lync.Model.ContactAvailability.BusyIdle:
            case Microsoft.Lync.Model.ContactAvailability.DoNotDisturb:
                cmd = _lightTheme.Busy;
                break;

            case Microsoft.Lync.Model.ContactAvailability.Free:
            case Microsoft.Lync.Model.ContactAvailability.FreeIdle:
                cmd = _lightTheme.Available;
                break;

            case Microsoft.Lync.Model.ContactAvailability.Invalid:
            case Microsoft.Lync.Model.ContactAvailability.None:
            case Microsoft.Lync.Model.ContactAvailability.Offline:
                cmd = _lightTheme.Off;
                break;
            }

            if (cmd != null)
            {
                UpdateLight(cmd);
            }
        }
        public override LightCommand GetLightCommand(IDictionary<string, string> values, PhilipsHueDevice bulb)
        {
            string hexColor;
            if (!values.TryGetValue("Color", out hexColor))
            {
                throw new ArgumentException("Color");
            }

            // TODO: http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
            var rgb = new RGBColor(hexColor);
            var xy = RgbToCieConverter.Convert(bulb.Model, rgb.R, rgb.G, rgb.B);

            if (Equals(xy, default(RgbToCieConverter.CieResult)))
            {
                return new LightCommand();
            }

            var command = new LightCommand
            {
                On = true,
                ColorCoordinates = new[] {xy.X, xy.Y}
            };

            TimeSpan transitionTime;
            if (TryGetTransitionTime(values, out transitionTime))
            {
                command.TransitionTime = transitionTime;
            }

            return command;
        }
    /// <summary>
    /// Send command to a group
    /// </summary>
    /// <param name="command"></param>
    /// <param name="group"></param>
    /// <returns></returns>
    public Task<HueResults> SendGroupCommandAsync(LightCommand command, string group = "0")
    {
      if (command == null)
        throw new ArgumentNullException("command");

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

      return SendGroupCommandAsync(jsonCommand, group);
    }
Example #5
0
		public ActionResult HueAdmin(AdminViewModel model)
		{
			var command = new LightCommand();
			command = command.SetColor(model.Color.Remove(0, 1));
			command.Effect = Effect.None;

			_hueClient.SendCommandAsync(command, _lightList);

			return View("HueAdmin", new AdminViewModel { Log = "Changed Color" });
		}
Example #6
0
        protected override void Execture_HomeAutomationSingleDeviceDefinition(HomeAutomationSingleDeviceContext context)
        {
            var device = context.Device as Q42HueDevice;
            var command = new LightCommand
            {
                Effect = Effect.ColorLoop,
            };

            device.SendCommand(command);
        }
Example #7
0
		public ActionResult TurnOn()
		{
			var command = new LightCommand();
			command = command.TurnOn();
			command.Effect = Effect.None;

			_hueClient.SendCommandAsync(command, _lightList);

			return View("HueAdmin", new AdminViewModel { Log = "Turned On" });
		}
		async void SetImmediateColor(){
			if (client != null) {
				var command = new LightCommand ();
				command.TurnOn ().SetColor ("c0392b");
				await client.SendCommandAsync (command);
			} else {
				var alert = new UIAlertView ("Hangon!", "First, press the button on the Hue bridge. Then tap 'Connect' in the app.", null, "OK");		
				alert.Show ();		
				Console.WriteLine ("Connect to bridge first");
			}
		}
  private void Color_Picker_SelectedColorChanged(object sender, EventArgs e)
  {
      if (_isInitialized && this.toggle_Power.IsOn)
      {
          //Queue color change command
          LightCommand cmd = new LightCommand();
          var color = this.color_Picker.SelectedColor.Color;
          cmd.SetColor(color.R, color.G, color.B);
          cmd.Brightness = color.A;
          QueueCommand(COLOR, cmd);
      }
 
  }
Example #10
0
        /// <summary>
        /// Send command to a group
        /// </summary>
        /// <param name="command"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        public Task SendGroupCommandAsync(LightCommand command, string group = "0")
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

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

            return(SendGroupCommandAsync(jsonCommand, group));
        }
Example #11
0
        /// <summary>
        /// Send a lightCommand to a list of lights
        /// </summary>
        /// <param name="command"></param>
        /// <param name="lightList">if null, send command to all lights</param>
        /// <returns></returns>
        public Task <HueResults> SendCommandAsync(LightCommand command, IEnumerable <string> lightList = null)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

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

            return(SendCommandRawAsync(jsonCommand, lightList));
        }
Example #12
0
        public ActionResult AllOn()
        {
            var command = new LightCommand();
            command = command.TurnOn();

            _hueClient.SendCommandAsync(command, _lightList);
            foreach (var light in _lightList)
            {
                light.State.On = true;
            }

            ViewBag.Msg = "Turned on Lights";

            return View("Index", _lightList);
        }
        public override LightCommand GetLightCommand(IDictionary<string, string> values, PhilipsHueDevice bulb)
        {
            var command = new LightCommand
            {
                On = true
            };

            TimeSpan transitionTime;
            if (TryGetTransitionTime(values, out transitionTime))
            {
                command.TransitionTime = transitionTime;
            }

            return command;
        }
Example #14
0
        public static LightCommand CreateCommand(int power)
        {
            power = Utilities.ValidatePower(power, MaxPower);

            var result = new LightCommand();

            var on = power > 0;

            result.On = on;

            if (on)
            {
                result.Brightness = (byte)power;
            }

            return result;
        }
Example #15
0
        /// <summary>
        /// Helper to set the color based on a HEX value
        /// </summary>
        /// <param name="lightCommand"></param>
        /// <param name="hexColor"></param>
        /// <returns></returns>
        public static LightCommand SetColor(this LightCommand lightCommand, string hexColor)
        {
            if (lightCommand == null)
            {
                throw new ArgumentNullException("lightCommand");
            }
            if (hexColor == null)
            {
                throw new ArgumentNullException("hexColor");
            }

            int red   = int.Parse(hexColor.Substring(0, 2), NumberStyles.AllowHexSpecifier);
            int green = int.Parse(hexColor.Substring(2, 2), NumberStyles.AllowHexSpecifier);
            int blue  = int.Parse(hexColor.Substring(4, 2), NumberStyles.AllowHexSpecifier);

            return(lightCommand.SetColor(red, green, blue));
        }
        public override LightCommand GetLightCommand(IDictionary<string, string> values, PhilipsHueDevice bulb)
        {
            byte brightness;
            if (!TryGetBrightness(values, out brightness))
            {
                throw new ArgumentException("Brightness");
            }

            var command = new LightCommand
            {
                Brightness = brightness,
                On = true
            };

            TimeSpan transitionTime;
            if (TryGetTransitionTime(values, out transitionTime))
            {
                command.TransitionTime = transitionTime;
            }

            return command;
        }
Example #17
0
        public static LightCommand CreateCommand(BinarySwitchPower power)
        {
            var result = new LightCommand();

            switch (power)
            {
                case BinarySwitchPower.On:
                    result.On = true;
                    result.Brightness = byte.MaxValue;
                    break;

                case BinarySwitchPower.Off:
                    result.On = false;
                    result.Brightness = byte.MinValue;
                    break;

                default:
                    throw new Exception();
            }

            return result;
        }
Example #18
0
 internal void SendCommand(LightCommand command, params Q42HueDevice[] devices)
 {
     SendCommand(command, devices.Select(x => x.Address));
 }
Example #19
0
    /// <summary>
    /// Send a lightCommand to a list of lights
    /// </summary>
    /// <param name="command"></param>
    /// <param name="lightList">if null, send command to all lights</param>
    /// <returns></returns>
    public Task SendCommandAsync(LightCommand command, IEnumerable<string> lightList = null)
    {
      if (command == null)
        throw new ArgumentNullException ("command");

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

      return SendCommandRawAsync(jsonCommand, lightList);
    }
 private void Toggle_Power_Toggled(object sender, RoutedEventArgs e)
 {
     if (_isInitialized)
     {
         //queue power command
         LightCommand cmd = new LightCommand();
         cmd.On = this.toggle_Power.IsOn;
         QueueCommand(ON_OFF, cmd);
     }
 
 }
Example #21
0
 internal void SendCommand(LightCommand command, IEnumerable<string> lightList)
 {
     var task = _client.SendCommandAsync(command, lightList);
     task.Wait();
 }
        //helper method to queue light commands for execution
        private void QueueCommand(string commandType, LightCommand cmd)
        {
            if (_commandQueue.ContainsKey(commandType))
            {
                //replace with most recent
                _commandQueue[commandType] = cmd;
            }
            else
            {
                _commandQueue.Add(commandType, cmd);
            }

        }
Example #23
0
 private void SendCommandTo(Q42.HueApi.LightCommand command, IEnumerable <string> lightList)
 {
     this.hueClient.SendCommandAsync(command, lightList);
 }
Example #24
0
        public async Task <HueResults> ModifySceneAsync(string sceneId, string lightId, LightCommand command)
        {
            CheckInitialized();

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

            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

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

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

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

            return(DeserializeDefaultHueResult(jsonResult));
        }
        private void Slider_Brightness_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            if (_isInitialized && toggle_Power.IsOn)
            {
                //queue brightness command
                LightCommand cmd = new LightCommand();
                cmd.Brightness = (byte)slider_Brightness.Value;
                QueueCommand(BRIGHTNESS, cmd);
            }

        }
Example #26
0
 public override int Run(string[] remainingArguments)
 {
     var command = new LightCommand { On = false };
     this._executor.ExecuteCommand(command);
     return 0;
 }
Example #27
0
        private async Task ChangeColor(string colorName)
        {
            var lc = new LightCommand();

            var color = _colorMap[colorName];

            lc.SetColor(color.R, color.G, color.B);
            await HueHelper.SendCommandAsync(lc);
        }
Example #28
0
		public async Task<HueResults> ModifySceneAsync(string sceneId, string lightId, LightCommand command)
    {
      CheckInitialized();

      if (sceneId == null)
        throw new ArgumentNullException("sceneId");
      if (sceneId.Trim() == String.Empty)
        throw new ArgumentException("sceneId must not be empty", "sceneId");
      if (lightId == null)
        throw new ArgumentNullException("lightId");
      if (lightId.Trim() == String.Empty)
        throw new ArgumentException("lightId must not be empty", "lightId");

      if (command == null)
        throw new ArgumentNullException("command");

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

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

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

      return DeserializeDefaultHueResult(jsonResult);
    }
Example #29
0
 protected override void ChangeColor(LightColour colour)
 {
     lock (_lockObject)
     {
         switch (colour)
         {
             case LightColour.Red:
                 CurrentColour = LightColour.Red;
                 SetColour("FF0D00");
                 break;
             case LightColour.Green:
                 CurrentColour = LightColour.Green;
                 SetColour("00FF00");
                 break;
             case LightColour.Blue:
                 CurrentColour = LightColour.Blue;
                 SetColour("0000FF");
                 break;
             case LightColour.Yellow:
                 CurrentColour = LightColour.Yellow;
                 SetColour("FFFF00");
                 break;
             case LightColour.White:
                 CurrentColour = LightColour.White;
                 SetColour("FFFFFF");
                 break;
             case LightColour.Purple:
                 CurrentColour = LightColour.Purple;
                 SetColour("8400FF");
                 break;
             case LightColour.Off:
                 CurrentColour = LightColour.Off;
                 var command = new LightCommand();
                 command.TurnOff();
                 command.Effect = Effect.None;
                 _hueClient.SendCommandAsync(command, _lights);
                 break;
         }
     }
 }
 public static Task SendCommandAsync(this IHueClient hueClient, LightCommand command, IEnumerable<Light> lights)
 {
     return hueClient.SendCommandAsync(command, lights.Select(x => x.Id));
 }
Example #31
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);
 }
Example #32
0
        public static LightCommand CreateCommand(IColor color, Light light)
        {
            var rgb = color.RedGreenBlue;

            var result = new LightCommand()
                .SetColor(new RGBColor(rgb.Red, rgb.Green, rgb.Blue), light.ModelId);

            return result;
        }
Example #33
0
        public LightsModule()
            : base("/lights/")
        {
            Get["/all/", true] = async (_, token) =>
              {
            var client = HueHelper.GetClient();

            var lights = await client.GetLightsAsync();

            var lightsData = from l in lights
                         let state = l.State
                         select new
                         {
                           id = l.Id,
                           name = l.Name,
                           state = new
                           {
                             brightness = state.Brightness,
                             @on = state.On,
                             saturation = state.Saturation,
                             hue = state.Hue,
                             hex = state.ToHex()
                           }
                         };

            var anyOn = lightsData.Any(l => l.state.on);

            var brightestLight = lightsData.Where(l => l.state.on).OrderByDescending(l => l.state.brightness).FirstOrDefault();

            var allLight = new[]
            {
              new
              {
            id = "all",
            name = "All",
            state = new
            {
              brightness = brightestLight != null ? brightestLight.state.brightness : (byte)0,
              @on = anyOn,
              saturation = brightestLight != null ? brightestLight.state.saturation : 0,
              hue = brightestLight != null ? brightestLight.state.hue : 0,
              hex = brightestLight != null ? brightestLight.state.hex : "000000"
            }
              }
            };

            var data = allLight.Union(lightsData);

            return data;
              };

              Post["/all/toggle", true] = async (_, token) =>
              {
            var client = HueHelper.GetClient();

            var lights = await client.GetLightsAsync();

            var anyOn = lights.Any(l => l.State.On);

            bool turnOff = anyOn;

            var command = new LightCommand();
            command.On = !turnOff;
            await client.SendCommandAsync(command, lights.Select(l => l.Id));

            var hub = GlobalHost.ConnectionManager.GetHubContext<LightsHub>();

            hub.Clients.All.lightsChanged();

            return new
            {
              success = true
            };
              };

              Post["/{id}/state/apply/", true] = async (p, token) =>
              {
            var data = this.Bind<StateData>();

            var client = HueHelper.GetClient();

            var id = (string)p.id;

            var command = new LightCommand();

            checked
            {
              command.Hue = data.Hue;
              command.Saturation = data.Saturation;
              command.Brightness = (byte?)data.Brightness;
              command.On = data.On;

              if (data.Hex != null)
              {
            command.SetColor(data.Hex);
              }

              if (id == "all")
              {
            await client.SendCommandAsync(command);
              }
              else
              {
            await client.SendCommandAsync(command, new[] { id });
              }
            }

            var hub = GlobalHost.ConnectionManager.GetHubContext<LightsHub>();

            hub.Clients.All.lightsChanged();

            return new
            {
              success = true
            };
              };
        }
Example #34
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);
    }
 public static Task SendCommandAsync(this IHueClient hueClient, LightCommand command, string lightId)
 {
     return hueClient.SendCommandAsync(command, new[] { lightId });
 }
Example #36
0
 public static async Task SendCommandAsync(LightCommand lightCommand)
 {
     await (await GetClient()).SendCommandAsync(lightCommand);
 }