Пример #1
0
        public async Task Register()
        {
            if (!string.IsNullOrWhiteSpace(config.IPAddress))
            {
                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");
            }
        }
Пример #2
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);
        }
Пример #3
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");
            }
        }
Пример #4
0
        /// <summary>
        /// Register your <paramref name="applicationName"/> and <paramref name="deviceName"/> at the Hue Bridge.
        /// </summary>
        /// <param name="ip">ip address of bridge</param>
        /// <param name="applicationName">The name of your app.</param>
        /// <param name="deviceName">The name of the device.</param>
        /// <param name="generateClientKey">Set to true if you want a client key to use the streaming api</param>
        /// <returns>Secret key for the app to communicate with the bridge.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="applicationName"/> or <paramref name="deviceName"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException"><paramref name="applicationName"/> or <paramref name="deviceName"/> aren't long enough, are empty or contains spaces.</exception>
        private async Task <RegisterEntertainmentResult?> RegisterAsync(string ip, string applicationName, string deviceName, bool generateClientKey)
        {
            if (applicationName == null)
            {
                throw new ArgumentNullException(nameof(applicationName));
            }
            if (applicationName.Trim() == String.Empty)
            {
                throw new ArgumentException("applicationName must not be empty", nameof(applicationName));
            }
            if (applicationName.Length > 20)
            {
                throw new ArgumentException("applicationName max is 20 characters.", nameof(applicationName));
            }
            if (applicationName.Contains(" "))
            {
                throw new ArgumentException("Cannot contain spaces.", nameof(applicationName));
            }

            if (deviceName == null)
            {
                throw new ArgumentNullException(nameof(deviceName));
            }
            if (deviceName.Length < 0 || deviceName.Trim() == String.Empty)
            {
                throw new ArgumentException("deviceName must be at least 0 characters.", nameof(deviceName));
            }
            if (deviceName.Length > 19)
            {
                throw new ArgumentException("deviceName max is 19 characters.", nameof(deviceName));
            }
            if (deviceName.Contains(" "))
            {
                throw new ArgumentException("Cannot contain spaces.", nameof(deviceName));
            }

            string fullName = string.Format("{0}#{1}", applicationName, deviceName);

            JObject obj = new JObject();

            obj["devicetype"] = fullName;

            if (generateClientKey)
            {
                obj["generateclientkey"] = true;
            }

            HttpClient client   = new HttpClient();//await GetHttpClient().ConfigureAwait(false));
            var        response = await client.PostAsync(new Uri($"{Scheme}://{ip}/api"), new JsonContent(obj.ToString())).ConfigureAwait(false);

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

            JObject?result;

            try
            {
                JArray jresponse = JArray.Parse(stringResponse);
                result = (JObject?)jresponse.First;
            }
            catch
            {
                //Not an expected response. Return response as exception
                throw new HueException(stringResponse);
            }

            if (result != null)
            {
                JToken?error;
                if (result.TryGetValue("error", out error))
                {
                    if (error["type"]?.Value <int>() == 101) // link button not pressed
                    {
                        throw new LinkButtonNotPressedException("Link button not pressed");
                    }
                    else
                    {
                        throw new HueException(error["description"]?.Value <string>());
                    }
                }

                var username           = result["success"]?["username"]?.Value <string>();
                var streamingClientKey = result["success"]?["clientkey"]?.Value <string>();

                if (username != null)
                {
                    Console.WriteLine("Returning valid log in");
                    Console.WriteLine(ip);
                    Console.WriteLine(username);
                    Console.WriteLine(streamingClientKey);
                    var berp = new RegisterEntertainmentResult
                    {
                        Ip                 = ip,
                        Username           = username,
                        StreamingClientKey = streamingClientKey
                    };

                    return(berp);
                }
            }


            return(null);
        }
Пример #5
0
        public async void AuthorizeHue(string id)
        {
            LogUtil.Write("AuthHue called, for real.");
            BridgeData bd;

            if (!string.IsNullOrEmpty(id))
            {
                await Clients.All.SendAsync("hueAuth", "start");

                bd = DataUtil.GetCollectionItem <BridgeData>("bridges", id);
                LogUtil.Write("BD: " + JsonConvert.SerializeObject(bd));
                if (bd == null)
                {
                    LogUtil.Write("Null bridge retrieved.");
                    await Clients.All.SendAsync("hueAuth", "stop");

                    return;
                }

                if (bd.Key != null && bd.User != null)
                {
                    LogUtil.Write("Bridge is already authorized.");
                    await Clients.All.SendAsync("hueAuth", "authorized");

                    await Clients.All.SendAsync("olo", DataUtil.GetStoreSerialized());

                    return;
                }
            }
            else
            {
                LogUtil.Write("Null value.", "WARN");
                await Clients.All.SendAsync("hueAuth", "stop");

                return;
            }

            LogUtil.Write("Trying to retrieve appkey...");
            var count = 0;

            while (count < 30)
            {
                count++;
                try {
                    RegisterEntertainmentResult appKey = HueDiscovery.CheckAuth(bd.IpAddress).Result;
                    LogUtil.Write("Appkey retrieved! " + JsonConvert.SerializeObject(appKey));
                    if (!string.IsNullOrEmpty(appKey.StreamingClientKey))
                    {
                        bd.Key  = appKey.StreamingClientKey;
                        bd.User = appKey.Username;
                        // Need to grab light group stuff here
                        var nhb = new HueBridge(bd);
                        nhb.RefreshData();
                        bd = nhb.Bd;
                        nhb.Dispose();
                        DataUtil.InsertCollection <BridgeData>("bridges", bd);
                        await Clients.All.SendAsync("hueAuth", "authorized");

                        await Clients.All.SendAsync("olo", DataUtil.GetStoreSerialized());

                        return;
                    }
                } catch (NullReferenceException e) {
                    LogUtil.Write("NULL EXCEPTION: " + e.Message, "WARN");
                }
                await Clients.All.SendAsync("hueAuth", count);

                Thread.Sleep(1000);
            }
            LogUtil.Write("We should be authorized, returning.");
        }