Ejemplo n.º 1
0
        public static async Task StopStream(StreamingHueClient client, BridgeData b)
        {
            var id = b.SelectedGroup;

            Console.WriteLine($@"Hue: Stopping stream.");
            await client.LocalHueClient.SetStreamingAsync(id, false).ConfigureAwait(true);
        }
        private async Task <EntertainmentLayer> GetOrCreateEntertainmentLayerAsync()
        {
            if (entertainmentLayer != null)
            {
                return(entertainmentLayer);
            }

            var group = (await deviceInfo.Client.GetEntertainmentGroups()).FirstOrDefault();

            if (group == null)
            {
                ErrorMessage = "No default entertainment group";
                return(null);
            }

            Debug.WriteLine($"Group: {group.Name}");

            var streamClient = new StreamingHueClient(deviceInfo.Address, localSettings.AppKey, localSettings.StreamingKey);
            var stream       = new StreamingGroup(group.Lights);

            await streamClient.Connect(group.Id);

            streamClient.AutoUpdate(stream, globalEffectsCancelSource.Token);

            return(entertainmentLayer = stream.GetNewLayer(isBaseLayer: true));
        }
Ejemplo n.º 3
0
        public async Task ConnectToBridge()
        {
            if (_config.Model.hueSettings.hueType == HueType.Basic)
            {
                _client = new LocalHueClient(_config.Model.hueSettings.ip);
                _client.Initialize(_config.Model.hueSettings.appKey);
                IsConnectedToBridge = true;
                if (!string.IsNullOrWhiteSpace(_config.Model.hueSettings.roomId))
                {
                    var Groups = await _client.GetGroupsAsync();

                    if (Groups != null && Groups.Count != 0)
                    {
                        UseRoom = Groups.FirstOrDefault(x => x.Id == _config.Model.hueSettings.roomId);
                    }
                }
            }
            else if (_config.Model.hueSettings.hueType == HueType.Entertainment)
            {
                _streamClient       = new StreamingHueClient(_config.Model.hueSettings.ip, _config.Model.hueSettings.appKey, _config.Model.hueSettings.entertainmentKey);
                IsConnectedToBridge = true;
                if (!string.IsNullOrWhiteSpace(_config.Model.hueSettings.roomId))
                {
                    var Groups = await _streamClient.LocalHueClient.GetEntertainmentGroups();

                    if (Groups != null && Groups.Count != 0)
                    {
                        UseRoom = Groups.FirstOrDefault(x => x.Id == _config.Model.hueSettings.roomId);
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public bool Initialize(RGBDeviceType loadFilter = RGBDeviceType.All, bool exclusiveAccessIfPossible = false, bool throwExceptions = false)
        {
            IsInitialized = false;

            try
            {
                UpdateTrigger.Stop();

                IList <IRGBDevice> devices = new List <IRGBDevice>();
                UpdateTrigger.ClientGroups = new Dictionary <StreamingHueClient, StreamingGroup>();

                foreach (HueClientDefinition clientDefinition in ClientDefinitions)
                {
                    // Create a temporary for this definition
                    ILocalHueClient client = new LocalHueClient(clientDefinition.Ip);
                    client.Initialize(clientDefinition.AppKey);

                    // Get the entertainment groups, no point continuing without any entertainment groups
                    IReadOnlyList <Group> entertainmentGroups = client.GetEntertainmentGroups().GetAwaiter().GetResult();
                    if (!entertainmentGroups.Any())
                    {
                        continue;
                    }

                    // Get all lights once, all devices can use this list to identify themselves
                    List <Light> lights = client.GetLightsAsync().GetAwaiter().GetResult().ToList();

                    foreach (Group entertainmentGroup in entertainmentGroups.OrderBy(g => int.Parse(g.Id)))
                    {
                        StreamingHueClient streamingClient = new StreamingHueClient(clientDefinition.Ip, clientDefinition.AppKey, clientDefinition.ClientKey);
                        StreamingGroup     streamingGroup  = new StreamingGroup(entertainmentGroup.Locations);
                        streamingClient.Connect(entertainmentGroup.Id).GetAwaiter().GetResult();

                        UpdateTrigger.ClientGroups.Add(streamingClient, streamingGroup);
                        foreach (string lightId in entertainmentGroup.Lights.OrderBy(int.Parse))
                        {
                            HueDeviceInfo deviceInfo = new HueDeviceInfo(entertainmentGroup, lightId, lights);
                            HueDevice     device     = new HueDevice(deviceInfo);
                            device.Initialize(new HueUpdateQueue(UpdateTrigger, lightId, streamingGroup));
                            devices.Add(device);
                        }
                    }
                }

                UpdateTrigger.Start();
                Devices       = new ReadOnlyCollection <IRGBDevice>(devices);
                IsInitialized = true;
            }
            catch
            {
                if (throwExceptions)
                {
                    throw;
                }
                return(false);
            }

            return(true);
        }
Ejemplo n.º 5
0
 private void SetClient()
 {
     if (Bd?.User == null || Bd?.Key == null || _client != null)
     {
         return;
     }
     _client = new StreamingHueClient(Bd.IpAddress, Bd.User, Bd.Key);
 }
Ejemplo n.º 6
0
        public HueLightClient(
            StreamingHueClient hueClient,
            StreamingGroup streamingGroup)
        {
            this.hueClient      = hueClient;
            this.streamingGroup = streamingGroup;
            hueLayer            = streamingGroup.GetNewLayer(true);

            Lights = hueLayer.Select(l => new Position((float)l.LightLocation.X, (float)l.LightLocation.Y)).ToArray();
        }
Ejemplo n.º 7
0
        public static async Task StopStream(StreamingHueClient client, BridgeData b)
        {
            if (client == null || b == null)
            {
                throw new ArgumentException("Invalid argument.");
            }

            var id = b.SelectedGroup;
            await client.LocalHueClient.SetStreamingAsync(id, false).ConfigureAwait(true);
        }
        public void InitializeClient()
        {
            // Initialize streaming client
            Client = new StreamingHueClient(HueBridgeIp, Profile.HueKey, Profile.HueStreamingKey);

            // Get the entertainment group
            var all = Client.LocalHueClient.GetBridgeAsync().Result;

            AvailableEntertainmentGroups = all.Groups.Where(x => x.Type == GroupType.Entertainment).ToList();
        }
Ejemplo n.º 9
0
 public static async Task Disconnect(StreamingHueClient client)
 {
     if (LightInfo.client != null)
     {
         client.Close();
         LightInfo.disconnect();
         origLeft  = new Color(1, 0, 0);
         origRight = new Color(0, 0, 1);
         Debug.Log("Disconnected");
     }
 }
Ejemplo n.º 10
0
        public static async Task <StreamingGroup> SetupAndReturnGroup()
        {
            //string ip = "192.168.0.4";
            //string key = "8JwWAj5J1tSsKLxyUOdAkWmcCQFcNc51AKRhxdH9";
            //string entertainmentKey = "AFFD322C34C993C19503D369481869FD";
            //var useSimulator = false;


            //string ip = "10.42.39.194";
            //string key = "tocjq6GmPJ8KX5DyLDKXQreZE6txQVQ5oBqbYDFn";
            //string entertainmentKey = "DB088F63639524B5A8CDC8AEEAC9C322";
            //var useSimulator = false;

            string ip  = "127.0.0.1";
            string key = "aSimulatedUser";
            string entertainmentKey = "01234567890123456789012345678901";
            var    useSimulator     = true;


            //Initialize streaming client
            StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey);

            //Get the entertainment group
            var all = await client.LocalHueClient.GetEntertainmentGroups();

            var group = all.FirstOrDefault();

            if (group == null)
            {
                throw new Exception("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample");
            }
            else
            {
                Console.WriteLine($"Using Entertainment Group {group.Id}");
            }

            //Create a streaming group
            var stream = new StreamingGroup(group.Locations);

            stream.IsForSimulator = useSimulator;


            //Connect to the streaming group
            await client.Connect(group.Id, simulator : useSimulator);

            //Start auto updating this entertainment group
            client.AutoUpdate(stream, new System.Threading.CancellationToken(), 50);

            //Optional: Check if streaming is currently active
            var bridgeInfo = await client.LocalHueClient.GetBridgeAsync();

            Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active");
            return(stream);
        }
Ejemplo n.º 11
0
 public HueBridge(BridgeData data)
 {
     bd         = data ?? throw new ArgumentNullException(nameof(data));
     BridgeIp   = bd.Ip;
     BridgeKey  = bd.Key;
     BridgeUser = bd.User;
     client     = StreamingSetup.GetClient(bd);
     disposed   = false;
     streaming  = false;
     entLayer   = null;
     Console.WriteLine(@"Hue: Loading bridge: " + BridgeIp);
 }
Ejemplo n.º 12
0
        public static async Task <StreamingGroup> SetupAndReturnGroup()
        {
            //string ip = "192.168.0.4";
            //string key = "8JwWAj5J1tSsKLxyUOdAkWmcCQFcNc51AKRhxdH9";
            //string entertainmentKey = "AFFD322C34C993C19503D369481869FD";
            //var useSimulator = false;

            //string ip = "10.70.16.38";
            //string key = "dpzXfw8NvafvCCvtLkQLUET-6Kc4jT4RovPg59Rx";
            //string entertainmentKey = "260FE0B7251DF783CFB9FBAB1D1E8B0C";
            //var useSimulator = false;

            string ip  = "127.0.0.1";
            string key = "aSimulatedUser";
            string entertainmentKey = "01234567890123456789012345678901";
            var    useSimulator     = true;


            //Initialize streaming client
            StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey);

            //Get the entertainment group
            var all = await client.LocalHueClient.GetEntertainmentGroups();

            var group = all.FirstOrDefault();

            if (group == null)
            {
                throw new HueException("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample");
            }
            else
            {
                Console.WriteLine($"Using Entertainment Group {group.Id}");
            }

            //Create a streaming group
            var stream = new StreamingGroup(group.Locations);

            stream.IsForSimulator = useSimulator;


            //Connect to the streaming group
            await client.Connect(group.Id, simulator : useSimulator);

            //Start auto updating this entertainment group
            client.AutoUpdate(stream, new System.Threading.CancellationToken(), 50, onlySendDirtyStates: false);

            //Optional: Check if streaming is currently active
            var bridgeInfo = await client.LocalHueClient.GetBridgeAsync();

            Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active");
            return(stream);
        }
Ejemplo n.º 13
0
        public static StreamingHueClient GetClient(BridgeData b)
        {
            var hueIp   = b.Ip;
            var hueUser = b.User;
            var hueKey  = b.Key;

            Console.WriteLine(@"Hue: Creating client...");
            //Initialize streaming client
            var client = new StreamingHueClient(hueIp, hueUser, hueKey);

            return(client);
        }
Ejemplo n.º 14
0
        public async Task RegisterBridgeEntertainment(string name)
        {
            _client = new LocalHueClient(_useBridge.IpAddress);
            var registerResult = await _client.RegisterAsync(_appName, name, true);

            _streamClient                              = new StreamingHueClient(registerResult.Ip, registerResult.Username, registerResult.StreamingClientKey);
            IsConnectedToBridge                        = true;
            _config.Model.hueSettings.ip               = _useBridge.IpAddress;
            _config.Model.hueSettings.appKey           = registerResult.Username;
            _config.Model.hueSettings.entertainmentKey = registerResult.StreamingClientKey;
            _config.SaveConfig();
            await ConnectToBridge();
        }
Ejemplo n.º 15
0
        public static async Task <StreamingGroup> SetupAndReturnGroup()
        {
            string ip  = "192.168.0.4";
            string key = "im5PBqU--4CJq2N2t8xMVNvZ2qxOtgzLcfVTkwzP";
            string entertainmentKey = "32C1FEB5439F313891C44369FF71388C";
            var    useSimulator     = false;

            //string ip = "127.0.0.1";
            //string key = "aSimulatedUser";
            //string entertainmentKey = "01234567890123456789012345678901";
            //var useSimulator = true;


            //Initialize streaming client
            StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey);

            //Get the entertainment group
            var all = await client.LocalHueApi.GetEntertainmentConfigurations();

            var group = all.Data.FirstOrDefault();

            if (group == null)
            {
                throw new HueEntertainmentException("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample");
            }
            else
            {
                Console.WriteLine($"Using Entertainment Group {group.Id}");
            }

            //Create a streaming group
            var stream = new StreamingGroup(group.Channels);

            stream.IsForSimulator = useSimulator;


            //Connect to the streaming group
            await client.Connect(group.Id, simulator : useSimulator);

            //Start auto updating this entertainment group
            client.AutoUpdate(stream, new CancellationToken(), 50, onlySendDirtyStates: false);

            //Optional: Check if streaming is currently active
            var entArea = await client.LocalHueApi.GetEntertainmentConfiguration(group.Id);

            Console.WriteLine(entArea.Data.First().Status == HueApi.Models.EntertainmentConfigurationStatus.active ? "Streaming is active" : "Streaming is not active");
            return(stream);
        }
Ejemplo n.º 16
0
        public static async Task <StreamingGroup> SetupAndReturnGroup()
        {
            string ip  = ApplicationManager.Instance.Settings.HueBridgeIP;
            string key = ApplicationManager.Instance.Settings.HueKey;
            string entertainmentKey = ApplicationManager.Instance.Settings.HueEntertainmentKey;
            bool   useSimulator     = ApplicationManager.Instance.Settings.HueUseSimulator;

            StreamingGroup = null;
            Layers         = null;

            StreamingHueClient = new StreamingHueClient(ip, key, entertainmentKey);

            var allEntertainmentGroups = await StreamingHueClient.LocalHueClient.GetEntertainmentGroups();

            var entertainmentGroup = allEntertainmentGroups.FirstOrDefault();

            if (entertainmentGroup == null)
            {
                throw new Exception("No Entertainment Group found.");
            }

            var stream = new StreamingGroup(entertainmentGroup.Locations);

            stream.IsForSimulator = useSimulator;

            await StreamingHueClient.Connect(entertainmentGroup.Id, simulator : useSimulator);

            StreamingHueClient.AutoUpdate(stream, 50);

            StreamingGroup = stream;
            var baseLayer   = stream.GetNewLayer(isBaseLayer: true);
            var effectLayer = stream.GetNewLayer(isBaseLayer: false);

            Layers = new List <EntertainmentLayer>()
            {
                baseLayer, effectLayer
            };

            baseLayer.AutoCalculateEffectUpdate();
            effectLayer.AutoCalculateEffectUpdate();

            return(stream);
        }
Ejemplo n.º 17
0
        private static async Task <string> GetEntertainmentGroupName(StreamingHueClient client)
        {
            var entertainmentGroups = await client.LocalHueClient.GetEntertainmentGroups();

            if (entertainmentGroups.Count == 0)
            {
                Console.Error.WriteLine("No entertainment groups found. Please set them up through the Hue app");
                Exit(1);
            }

            if (entertainmentGroups.Count == 1)
            {
                return(entertainmentGroups.First().Name);
            }

            var names = entertainmentGroups.Select(e => e.Name);

            throw new InvalidOperationException(
                      "Please select entertainment group name with the -e option");
        }
Ejemplo n.º 18
0
        private async Task <HueLightClient> Connect(StreamingHueClient hueClient, string entertainmentGroupName)
        {
            var entertainmentGroups = await hueClient.LocalHueClient.GetEntertainmentGroups();

            var entertainmentGroup = entertainmentGroups.FirstOrDefault(g => g.Name == entertainmentGroupName);

            if (entertainmentGroup == null)
            {
                throw new ArgumentException($"Cannot find entertainment group {entertainmentGroupName}");
            }

            var streamingGroup = new StreamingGroup(entertainmentGroup.Locations);

            Console.WriteLine("Attempting to connect to entertainment group");
            await hueClient.Connect(entertainmentGroup.Id).ConfigureAwait(false);

            Console.WriteLine("Connected");

            return(new HueLightClient(hueClient, streamingGroup));
        }
Ejemplo n.º 19
0
        public static async Task connect(CancellationToken token, string ip = null)
        {
            if (ip == null)
            {
                ip = await FindBridge();
            }
            token.ThrowIfCancellationRequested();
            var appKey    = Settings.ChromaConfig.Instance.HueAppKey;
            var clientKey = Settings.ChromaConfig.Instance.HueClientKey;

            Debug.Log("Connecting to bridge...");
            var client = new StreamingHueClient(ip, appKey, clientKey);

            token.ThrowIfCancellationRequested();
            Debug.Log("Connected! Getting entertainment group...");
            var group = (await client.LocalHueClient.GetEntertainmentGroups()).FirstOrDefault();

            if (group == null)
            {
                Debug.Log("Group is missing!");
                return;
            }
            token.ThrowIfCancellationRequested();
            var entGroup = new StreamingGroup(group.Locations);

            Debug.Log("Found group! Connecting to lightbulbs...");
            await client.Connect(group.Id);

            token.ThrowIfCancellationRequested();
            Debug.Log("Connected to bulbs! Syncing...");
            _ = client.AutoUpdate(entGroup, token);
            var entLayer = entGroup.GetNewLayer(true);

            LightInfo.setInfo(client, entLayer, token);
            await Task.Delay(TimeSpan.FromMilliseconds(50), token);

            if (Settings.ChromaConfig.Instance.LowLight == true)
            {
                entLayer.SetState(token, new RGBColor(255, 255, 255), 0.5);
            }
        }
Ejemplo n.º 20
0
        public async Task OnStopReading()
        {
            if (_config.Model.hueSettings.hueType == HueType.Basic)
            {
                if (_config.Model.hueSettings.shutLightOffOnStop)
                {
                    var command = new LightCommand
                    {
                        On             = false,
                        TransitionTime = _frameTimeSpan
                    };
                    command.TurnOff();
                    await _client.SendCommandAsync(command, UseRoom.Lights);
                }
            }
            else if (_config.Model.hueSettings.hueType == HueType.Entertainment)
            {
                if (_config.Model.hueSettings.shutLightOffOnStop && _streamBaseLayer != null)
                {
                    foreach (var light in _streamBaseLayer)
                    {
                        light.SetState(_cancelToken, brightness: 0.0, timeSpan: _frameTimeSpan);
                    }
                }

                if (_streamGroup != null)
                {
                    _streamClient?.ManualUpdate(_streamGroup);
                }

                _cancelSource?.Cancel();
                _cancelSource?.Dispose();
                _streamGroup     = null;
                _streamBaseLayer = null;
                //Closing disposes the client so we need to reconnect if we want to reuse it.
                _streamClient?.Close();
                _streamClient = null;
                await ConnectToBridge();
            }
        }
Ejemplo n.º 21
0
        public async Task Start()
        {
            /*IBridgeLocator locator = new HttpBridgeLocator();
             * var locateBridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));
             * IEnumerable<LocatedBridge> bridgeIPs = locateBridges;
             *
             * if (bridgeIPs.Count() == 0)
             * {
             *  throw new Exception("No bridges found.");
             * }*/

            string ip               = "192.168.50.3";
            string appName          = "LightingLink";
            string deviceName       = "WarMachine";
            string key              = "8pJuacIOcvBN9XA34hZWLSWTI0CQ9JYoif7SyEn9";
            string entertainmentKey = "87E3D4B1CC91E68B44F4393951F838DA";

            //--------Get a new key---------
            //ILocalHueClient baseClient = new LocalHueClient(ip);
            //var appKey = await baseClient.RegisterAsync(appName, deviceName);

            //--------Get a new key and entertainment key---------
            //var entKey = await LocalHueClient.RegisterAsync(ip, appName, deviceName, true);

            //Initialize Streaming Client
            StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey);

            //var localClient = client.LocalHueClient;
            //await localClient.SendCommandAsync(new LightCommand().SetColor(new RGBColor(255, 255, 255)), new List<string> { "1" });

            //Get the Entertainment Groups
            var all = await client.LocalHueClient.GetBridgeAsync();

            var group = all.Groups.Where(x => x.Type == Q42.HueApi.Models.Groups.GroupType.Entertainment).FirstOrDefault();

            if (group == null)
            {
                throw new Exception("No Entertainment Group found.");
            }
            else
            {
                Console.WriteLine($"Using Entertainment Group {group.Id}");
            }

            //Create a streaming group
            entGroup = new StreamingGroup(group.Locations);

            //Connect to the streaming group
            await client.Connect(group.Id);

            //Start auto updating this entertainment group
            client.AutoUpdate(entGroup, 50);

            //Optional: calculated effects that are placed in the room
            client.AutoCalculateEffectUpdate(entGroup);

            //Optional: Check if streaming is currently active
            var bridgeInfo = await client.LocalHueClient.GetBridgeAsync();

            Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active");

            //Order lights based on position in the room
            var orderedLeft      = entGroup.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X);
            var orderedRight     = entGroup.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X);
            var allLightsOrdered = orderedLeft.Concat(orderedRight.Reverse()).ToArray();

            var allLightsReverse = allLightsOrdered.ToList();

            allLightsReverse.Reverse();
        }
Ejemplo n.º 22
0
 public static void disconnect()
 {
     client = null;
     layer  = null;
 }
Ejemplo n.º 23
0
 public static void setInfo(StreamingHueClient input, EntertainmentLayer input1, CancellationToken input2)
 {
     client = input;
     layer  = input1;
     token  = input2;
 }
Ejemplo n.º 24
0
        public async void Init(Label labelHint)
        {
            client = new StreamingHueClient(ip, key, entertainmentKey);

            //Get the entertainment group
            IReadOnlyList <Group> all = null;

            try
            {
                all = await client.LocalHueClient.GetEntertainmentGroups();
            }
            catch (Exception e)
            {
                labelHint.Text = "Hue init exception: " + e.Message;
                return;
            }
            var group = all.FirstOrDefault();

            if (group == null)
            {
                //throw new Exception("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample");
                labelHint.Text = "No Entertainment Group found";
                return;
            }
            else
            {
                labelHint.Text = $"Using Entertainment Group {group.Id}";
                Console.WriteLine($"Using Entertainment Group {group.Id}");
            }

            //Create a streaming group
            entGroup = new StreamingGroup(group.Locations);

            //Connect to the streaming group
            await client.Connect(group.Id);

            //Start auto updating this entertainment group
            client.AutoUpdate(entGroup, 50);

            //Optional: calculated effects that are placed in the room
            client.AutoCalculateEffectUpdate(entGroup);

            //Optional: Check if streaming is currently active
            var bridgeInfo = await client.LocalHueClient.GetBridgeAsync();

            Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active");
            labelHint.Text = bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active";

            //Order lights based on position in the room
            var orderedLeft      = entGroup.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X);
            var orderedRight     = entGroup.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X);
            var allLightsOrdered = orderedLeft.Concat(orderedRight.Reverse()).ToArray();

            var allLightsReverse = allLightsOrdered.ToList();

            allLightsReverse.Reverse();

            Random rnd = new Random();

            hue = rnd.Next(0, 65535);

            entGroup.SetState(HueToRGB(hue, 1, 1), 1, TimeSpan.FromMilliseconds(0));

            isInit = true;
        }
Ejemplo n.º 25
0
        public static async Task Setup(CancellationToken token)
        {
            var bridges = await HueBridgeDiscovery.FastDiscoveryWithNetworkScanFallbackAsync(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30));

            var bridge = bridges.FirstOrDefault();

            RegisterEntertainmentResult registeredInfos;

            // Is the Hue credentials present ?
            if (!File.Exists(credentialPath))
            {
                Console.WriteLine("No credentials found please press the bridge button");

                // Wait for the user to press the link button
                await Task.Delay(TimeSpan.FromSeconds(30));

                var client = new LocalHueClient(bridge.IpAddress);
                registeredInfos = await client.RegisterAsync("ScreenHueSync", Environment.MachineName, true);

                hueCredential = new HueCredential()
                {
                    Username = registeredInfos.Username,
                    Key      = registeredInfos.StreamingClientKey
                };
                File.WriteAllText(credentialPath, Newtonsoft.Json.JsonConvert.SerializeObject(hueCredential));
                Console.WriteLine("Registration success credentials are :");
                Console.WriteLine("Username : "******"Key : " + registeredInfos.StreamingClientKey);
            }
            else
            {
                hueCredential = Newtonsoft.Json.JsonConvert.DeserializeObject <HueCredential>(File.ReadAllText(credentialPath));
            }

            registeredInfos = new RegisterEntertainmentResult()
            {
                Username           = hueCredential.Username,
                StreamingClientKey = hueCredential.Key
            };

            Console.WriteLine("Get client");
            Client = new StreamingHueClient(bridge.IpAddress, registeredInfos.Username, registeredInfos.StreamingClientKey);

            //Get the entertainment group
            Console.WriteLine("Get entertainment group");
            var all = await Client.LocalHueClient.GetEntertainmentGroups();

            var group = all.Last();

            //Create a streaming group
            Console.WriteLine("Get streaming group");
            StreamingGroup = new StreamingGroup(group.Locations);

            //Connect to the streaming group
            Console.WriteLine("Connect to group");
            await Client.Connect(group.Id);

            Console.WriteLine("Done !");
            BaseLayer = StreamingGroup.GetNewLayer(true);
            Ready     = true;

            //Start auto updating this entertainment group
            _ = Client.AutoUpdate(StreamingGroup, token, 50);
        }
Ejemplo n.º 26
0
        public async Task Start()
        {
            //string ip = "192.168.0.4";
            //string key = "8JwWAj5J1tSsKLxyUOdAkWmcCQFcNc51AKRhxdH9";
            //string entertainmentKey = "AFFD322C34C993C19503D369481869FD";
            //var useSimulator = false;


            //string ip = "10.42.39.194";
            //string key = "tocjq6GmPJ8KX5DyLDKXQreZE6txQVQ5oBqbYDFn";
            //string entertainmentKey = "DB088F63639524B5A8CDC8AEEAC9C322";
            //var useSimulator = false;

            string ip  = "127.0.0.1";
            string key = "aSimulatedUser";
            string entertainmentKey = "01234567890123456789012345678901";
            var    useSimulator     = true;


            //Initialize streaming client
            StreamingHueClient client = new StreamingHueClient(ip, key, entertainmentKey);

            //Get the entertainment group
            var all = await client.LocalHueClient.GetEntertainmentGroups();

            var group = all.FirstOrDefault();

            if (group == null)
            {
                throw new Exception("No Entertainment Group found. Create one using the Q42.HueApi.UniversalWindows.Sample");
            }
            else
            {
                Console.WriteLine($"Using Entertainment Group {group.Id}");
            }

            //Create a streaming group
            var entGroup = new StreamingGroup(group.Locations);

            entGroup.IsForSimulator = useSimulator;

            //Connect to the streaming group
            await client.Connect(group.Id, simulator : useSimulator);

            //Start auto updating this entertainment group
            client.AutoUpdate(entGroup, 50);

            //Optional: calculated effects that are placed in the room
            client.AutoCalculateEffectUpdate(entGroup);

            //Optional: Check if streaming is currently active
            var bridgeInfo = await client.LocalHueClient.GetBridgeAsync();

            Console.WriteLine(bridgeInfo.IsStreamingActive ? "Streaming is active" : "Streaming is not active");

            //Order lights based on position in the room
            var orderedLeft      = entGroup.GetLeft().OrderByDescending(x => x.LightLocation.Y).ThenBy(x => x.LightLocation.X);
            var orderedRight     = entGroup.GetRight().OrderByDescending(x => x.LightLocation.Y).ThenByDescending(x => x.LightLocation.X);
            var allLightsOrdered = orderedLeft.Concat(orderedRight.Reverse()).ToArray();

            var allLightsReverse = allLightsOrdered.ToList();

            allLightsReverse.Reverse();


            CancellationTokenSource cst = new CancellationTokenSource();

            Console.WriteLine("Random color on all lights");
            entGroup.SetRandomColor(IteratorEffectMode.All, TimeSpan.FromMilliseconds(250), cancellationToken: cst.Token);
            cst = WaitCancelAndNext(cst);

            Console.WriteLine("Different random colors on all lights");
            entGroup.SetRandomColor(IteratorEffectMode.AllIndividual, TimeSpan.FromMilliseconds(250), cancellationToken: cst.Token);
            cst = WaitCancelAndNext(cst);

            Console.WriteLine("Knight rider (works best with 6+ lights)");
            allLightsOrdered.KnightRider(cancellationToken: cst.Token);
            cst = WaitCancelAndNext(cst);

            Ref <TimeSpan?> waitTime = TimeSpan.FromMilliseconds(750);

            Console.WriteLine("Flash lights (750ms), press enter to decrease by 200 ms");
            allLightsOrdered.FlashQuick(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Cycle, waitTime: waitTime, cancellationToken: cst.Token);
            Console.ReadLine();

            waitTime.Value -= TimeSpan.FromMilliseconds(200);
            Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})");
            Console.ReadLine();

            waitTime.Value -= TimeSpan.FromMilliseconds(200);
            Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})");
            Console.ReadLine();

            waitTime.Value -= TimeSpan.FromMilliseconds(200);
            Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})");
            Console.ReadLine();

            waitTime.Value -= TimeSpan.FromMilliseconds(100);
            Console.WriteLine($"Flash ({waitTime.Value.Value.TotalMilliseconds})");
            cst = WaitCancelAndNext(cst);

            Console.WriteLine("Flash on random lights");
            allLightsOrdered.FlashQuick(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.Random, waitTime: waitTime, cancellationToken: cst.Token);
            cst = WaitCancelAndNext(cst);

            Console.WriteLine("Flash on ALL lights");
            waitTime.Value = TimeSpan.FromMilliseconds(150);
            allLightsOrdered.Flash(new Q42.HueApi.ColorConverters.RGBColor("FFFFFF"), IteratorEffectMode.All, waitTime: waitTime, cancellationToken: cst.Token);
            cst = WaitCancelAndNext(cst);

            Console.WriteLine("Flash effect with transition times");
            entGroup.GetLeft().Flash(new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.All, waitTime: TimeSpan.FromSeconds(1), transitionTimeOn: TimeSpan.FromMilliseconds(1000), transitionTimeOff: TimeSpan.FromMilliseconds(1000), cancellationToken: cst.Token);
            await Task.Delay(2000);

            entGroup.GetRight().Flash(new Q42.HueApi.ColorConverters.RGBColor("FF0000"), IteratorEffectMode.All, waitTime: TimeSpan.FromSeconds(1), transitionTimeOn: TimeSpan.FromMilliseconds(1000), transitionTimeOff: TimeSpan.FromMilliseconds(1000), cancellationToken: cst.Token);
            cst = WaitCancelAndNext(cst);

            //Console.WriteLine("Or build your own effects");
            //Task.Run(async () =>
            //{
            //  while (true && !cst.Token.IsCancellationRequested)
            //  {
            //    entGroup.SetState(new RGBColor("0000FF"), 1, TimeSpan.FromSeconds(4), cancellationToken: cst.Token);
            //    await Task.Delay(TimeSpan.FromSeconds(5));
            //    entGroup.SetState(new RGBColor("FF0000"), 0.6, TimeSpan.FromSeconds(4), cancellationToken: cst.Token);
            //    await Task.Delay(TimeSpan.FromSeconds(5));
            //  }
            //}, cst.Token);
            //cst = WaitCancelAndNext(cst);

            Console.WriteLine("A red light that is moving in horizontal direction and is placed on an XY grid, matching your entertainment setup");
            var redLightEffect = new RedLightEffect();

            redLightEffect.Radius = 0.3;
            redLightEffect.Y      = -0.8;
            redLightEffect.X      = -0.8;
            entGroup.PlaceEffect(redLightEffect);
            redLightEffect.Start();

            Task.Run(async() =>
            {
                double step = 0.2;
                while (true)
                {
                    redLightEffect.Y += step;
                    await Task.Delay(100);
                    if (redLightEffect.Y >= 2)
                    {
                        step = -0.1;
                    }
                    if (redLightEffect.Y <= -2)
                    {
                        step = +0.1;
                    }
                }
            }, cst.Token);


            cst = WaitCancelAndNext(cst);
            redLightEffect.Stop();


            Console.WriteLine("Thank you for using Q42.Hue.Streaming. This library was developed during Christmas 2017.");
            await allLightsOrdered.Christmas(cancellationToken : cst.Token);

            cst = WaitCancelAndNext(cst);

            Console.WriteLine("Press Enter to Exit");
            Console.ReadLine();
        }
Ejemplo n.º 27
0
        public static async Task <StreamingGroup> SetupAndReturnGroup(StreamingHueClient client, BridgeData b,
                                                                      CancellationToken ct)
        {
            if (client == null || b == null)
            {
                throw new ArgumentException("Invalid argument.");
            }

            try {
                var groupId = b.SelectedGroup;
                if (groupId == null && b.Groups != null && b.Groups.Count > 0)
                {
                    groupId = b.Groups[0].Id;
                }

                if (groupId == null)
                {
                    return(null);
                }
                //Get the entertainment group
                var group = client.LocalHueClient.GetGroupAsync(groupId).Result;
                if (group == null)
                {
                    var groups = b.Groups;
                    if (groups.Count > 0)
                    {
                        groupId = groups[0].Id;
                        group   = client.LocalHueClient.GetGroupAsync(groupId).Result;
                        if (group != null)
                        {
                            LogUtil.Write(@$ "Selected first group: {groupId}");
                        }
                        else
                        {
                            LogUtil.Write(@"Unable to load group, can't connect for streaming.");
                            return(null);
                        }
                    }
                }

                //Create a streaming group
                if (group != null)
                {
                    var lights       = group.Lights;
                    var mappedLights = new List <string>();
                    foreach (var light in lights)
                    {
                        foreach (var ml in b.Lights)
                        {
                            if (ml.Id == light && ml.TargetSector != -1)
                            {
                                mappedLights.Add(light);
                            }
                        }
                    }

                    var stream = new StreamingGroup(mappedLights);
                    //Connect to the streaming group
                    try {
                        await client.Connect(group.Id);
                    } catch (SocketException e) {
                        LogUtil.Write(@"Exception: " + e.Message);
                    } catch (InvalidOperationException f) {
                        LogUtil.Write("Exception: " + f.Message);
                    } catch (Exception) {
                        LogUtil.Write("Random exception caught.");
                    }

                    //Start auto updating this entertainment group
#pragma warning disable 4014
                    client.AutoUpdate(stream, ct);
#pragma warning restore 4014

                    return(stream);
                }
            } catch (SocketException e) {
                LogUtil.Write("Socket exception occurred, can't return group right now: " + e.Message);
            }

            return(null);
        }
Ejemplo n.º 28
0
        public void Push(ControlDevice controlDevice)
        {
            if (isWriting)
            {
                return;
            }


            isWriting = true;
            try
            {
                PhillipsHueControlDevice pcd = (PhillipsHueControlDevice)controlDevice;

                var entLayer = pcd.StreamingGroup.GetNewLayer(isBaseLayer: true);
                int ct       = 0;


                foreach (EntertainmentLight entertainmentLight in entLayer)
                {
                    var led = pcd.LEDs[ct];
                    Q42.HueApi.ColorConverters.RGBColor thisCol = new Q42.HueApi.ColorConverters.RGBColor
                    {
                        R = led.Color.Red / 255f,
                        G = led.Color.Green / 255f,
                        B = led.Color.Blue / 255f,
                    };

                    entertainmentLight.SetState(CancellationToken.None, thisCol, 1.0, TimeSpan.FromMilliseconds(0));
                    ct++;
                }

                if (!pcd.HasConnected && !isConnecting)
                {
                    isConnecting = true;
                    try
                    {
                        Debug.WriteLine("Connecting");
                        if (StreamingClient == null)
                        {
                            StreamingClient = new StreamingHueClient(config.IPAddress, config.UserName, config.Key);
                        }

                        StreamingClient.Connect(pcd.AllGroupId, false).Wait();
                        pcd.HasConnected = true;
                        Debug.WriteLine("Connected");
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                    isConnecting = false;
                }

                StreamingClient.ManualUpdate(pcd.StreamingGroup, true);
            }
            catch
            {
            }

            lastRefresh = DateTime.Now;
            isWriting   = false;
        }
Ejemplo n.º 29
0
        public async Task Run(CancellationToken token, string ip = null)
        {
            try
            {
                if (ip == null)
                {
                    ip = await FindBridge();
                }
                token.ThrowIfCancellationRequested();
                var appKey    = prefs.GetString("HueSaber", "appKey");
                var clientKey = prefs.GetString("HueSaber", "clientKey");
                log.Info("Connecting to bridge...");
                var client = new StreamingHueClient(ip, appKey, clientKey);
                token.ThrowIfCancellationRequested();
                log.Info("Connected! Getting entertainment group...");
                var group = (await client.LocalHueClient.GetEntertainmentGroups()).ElementAtOrDefault(prefs.GetInt("HueSaber", "overrideRoom", 0));
                if (group == null)
                {
                    log.Error("Group is missing!");
                    return;
                }
                token.ThrowIfCancellationRequested();
                var entGroup = new StreamingGroup(group.Locations);
                log.Info("Found group! Connecting to lightbulbs...");
                await client.Connect(group.Id);

                token.ThrowIfCancellationRequested();
                log.Info("Connected to bulbs! Tracking background color...");
                _ = client.AutoUpdate(entGroup, token);
                var layer = entGroup.GetNewLayer(true);
                while (!token.IsCancellationRequested)
                {
                    //log.Info($"Color is {currentColor}");
                    var color = (Color)currentColor;
                    var miss  = DateTimeOffset.UtcNow - (DateTimeOffset)missTime;
                    var cut   = DateTimeOffset.UtcNow - (DateTimeOffset)cutTime;

                    var rgbColor = new RGBColor(color.r, color.g, color.b);
                    var hsbColor = rgbColor.GetHSB();
                    if (hsbColor.Saturation > 35)
                    {
                        hsbColor.Saturation = 200;
                    }

                    var brightness = 0.7;
                    if (miss < TimeSpan.FromMilliseconds(100))
                    {
                        brightness = 0.5;
                    }
                    else if (cut < TimeSpan.FromMilliseconds(100))
                    {
                        brightness = 1;
                    }

                    layer.SetState(token, hsbColor.GetRGB(), brightness, TimeSpan.FromMilliseconds(50));
                    await Task.Delay(TimeSpan.FromMilliseconds(1000.0 / 30.0), token);
                }
            } catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
Ejemplo n.º 30
0
        public async Task Setup()
        {
            int fd = 0;

            if (controlDevices != null)
            {
                fd = controlDevices.Count;
            }

            if (!string.IsNullOrWhiteSpace(config.IPAddress))
            {
                isConnecting = true;
                LocalHueClient localClient = new LocalHueClient(config.IPAddress);


                Console.WriteLine("Registering");
                if (string.IsNullOrWhiteSpace(config.UserName) || string.IsNullOrWhiteSpace(config.Key))
                {
                    registeredEntertainmentResult = await localClient.RegisterAsync("SLHueDriver", "SimpleLed", true);

                    config.UserName    = registeredEntertainmentResult.Username;
                    config.Key         = registeredEntertainmentResult.StreamingClientKey;
                    config.DataIsDirty = true;
                }

                Console.WriteLine("Registered");


                StreamingClient = new StreamingHueClient(config.IPAddress, config.UserName, config.Key);
                allGroups       = await StreamingClient.LocalHueClient.GetEntertainmentGroups();

                controlDevices = new List <ControlDevice>();
                Debug.WriteLine("Setting up devices");
                foreach (Group allGroup in allGroups)
                {
                    Debug.WriteLine("Working on " + allGroup.Name);

                    var dev = (new PhillipsHueControlDevice
                    {
                        DeviceType = DeviceTypes.Bulb,
                        Driver = this,
                        LEDs = new ControlDevice.LedUnit[allGroup.Lights.Count],
                        Name = allGroup.Name,
                        StreamingGroup = new StreamingGroup(allGroup.Locations),
                        AllGroupId = allGroup.Id
                    });

                    Debug.WriteLine("connecting...");

                    CancellationToken derp = new CancellationToken();

                    for (int i = 0; i < dev.LEDs.Length; i++)
                    {
                        dev.LEDs[i] = new ControlDevice.LedUnit
                        {
                            LEDName = "Bulb " + allGroup.Lights[i],
                            Data    = new ControlDevice.LEDData()
                            {
                                LEDNumber = int.Parse(allGroup.Lights[i])
                            },
                            Color = new LEDColor(0, 0, 0)
                        };
                    }

                    Debug.WriteLine("adding device");

                    controlDevices.Add(dev);
                }

                isReady      = true;
                isConnecting = false;

                if (fd != controlDevices.Count)
                {
                    config.DataIsDirty = true;
                    FireDeviceRescanRequired();
                }

                Debug.WriteLine("All done");
            }
        }