コード例 #1
0
        /// <summary>
        /// Connect the controller to the light bridge.
        /// </summary>
        internal async Task <bool> Connect()
        {
            // Connect to the Philips Hue bridge.  If we ever change lights the Hue stuff can be abstracted out.
            if (Simulator != null)
            {
                Simulator.Log("Connection");
                return(true);
            }
            IBridgeLocator locator = new HttpBridgeLocator();
            IEnumerable <LocatedBridge> bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            if (bridges == null || bridges.Count() == 0)
            {
                ConnectionFailed?.Invoke(this, new EventArgs());
                return(false);
            }
            bridge = bridges.ElementAt(0);
            client = new LocalHueClient(bridge.IpAddress);
            // var appKey = await client.RegisterAsync("light-control", "fela");
            client?.Initialize(apiKey);
            bool connected = await client?.CheckConnection();

            if (client != null && connected)
            {
                Connected?.Invoke(this, new EventArgs());
            }
            else
            {
                ConnectionFailed?.Invoke(this, new EventArgs());
            }
            return(connected);
        }
コード例 #2
0
ファイル: Util.cs プロジェクト: andriks2/Andriks.HueApiDemo
        /// <summary>
        /// Check if a certain 'user' is already a registered user of the bridge.
        /// </summary>
        /// <param name="bridge">The bridge for which to check.</param>
        /// <param name="appKey">The appkey for the user.</param>
        /// <returns></returns>
        public async static Task <bool> ClientAlreadyRegistered(LocatedBridge bridge,
                                                                string appKey)
        {
            ILocalHueClient client = null;

            try
            {
                // see if initialized
                if ((bridge == null) || String.IsNullOrEmpty(appKey))
                {
                    return(false);
                }
                client = new LocalHueClient(bridge.IpAddress);
                client.Initialize(appKey);
                // Only initializing is not enough to check the appKey, so check:
                bool isConnected = await client.CheckConnection();

                return(isConnected);
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Something went while connecting. The error was '{0}'.",
                                              ex.Message),
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return(false);
            }
        }
コード例 #3
0
        /// <summary>
        /// If the app key is already know to the bridge, only initialize the client.
        /// Otherwise register the client and initialize.
        /// </summary>
        private async void buttonRegister_Click(object sender, EventArgs e)
        {
            foreach (var b in checkedListBoxBridges.CheckedItems)
            {
                LocatedBridge bridge = (LocatedBridge)b;
                // Check if already registered:
                bool ok = await Util.ClientAlreadyRegistered(bridge, appKey);

                ILocalHueClient client = new LocalHueClient(bridge.IpAddress);
                if (ok)
                {
                    client.Initialize(appKey);
                }
                else
                {
                    string computerName = System.Environment.MachineName;
                    // Make sure the user has pressed the button on the bridge before calling RegisterAsync
                    // It will throw an LinkButtonNotPressedException if the user did not press the button
                    appKey = await client.RegisterAsync("Q42", computerName);

                    client.Initialize(appKey);
                    saveAppKey(appKey);
                }
            }
        }
コード例 #4
0
        ILocalHueClient Initialize(LocatedBridge bridge)
        {
            var client = new LocalHueClient(bridge.IpAddress);

            client.Initialize(_key);
            return(client);
        }
コード例 #5
0
        private void btn_Ok_Click(object sender, EventArgs e)
        {
            if (m_Bridges.Count > 0 && dgv_Bridges.SelectedRows.Count > 0)
            {
                m_SelectedBridge = m_Bridges[dgv_Bridges.SelectedRows[0].Index];
            }

            DialogResult = DialogResult.OK;
        }
コード例 #6
0
        public SelectBridgeForm(LocatedBridge[] bridges)
        {
            InitializeComponent();

            m_Bridges = new BindingList <LocatedBridge>();
            foreach (var bridge in bridges)
            {
                m_Bridges.Add(bridge);
            }
            dgv_Bridges.DataSource = bridges;

            m_SelectedBridge = null;
        }
コード例 #7
0
        /// <summary>
        /// When the OK button is pressed, try to connect a bridge. If there is a checked
        /// item in the listbox, use that. Otherwise use the first item.
        /// </summary>
        private async void buttonOK_Click(object sender, EventArgs e)
        {
            try
            {
                LocatedBridge bridge = null;

                if (checkedListBoxBridges.CheckedItems.Count > 0)
                {
                    bridge = checkedListBoxBridges.CheckedItems[0] as LocatedBridge;
                }
                else if (checkedListBoxBridges.Items.Count > 0)
                {
                    bridge = checkedListBoxBridges.Items[0] as LocatedBridge;
                }

                if (bridge != null)
                {
                    client = new LocalHueClient(bridge.IpAddress);
                    client.Initialize(appKey);
                    if (!await client.CheckConnection())
                    {
                        MessageBox.Show("Could not connect client. This might be caused by an invalid application key.\n\n" +
                                        "Other parts of the application will not work.",
                                        "Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        client = null;
                    }
                    this.Close();
                }
                else
                {
                    if (MessageBox.Show("No client connected. Other parts of the application will not work. Continue?",
                                        "Warning",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Something went wrong while connecting. The error was '{0}'.",
                                              ex.Message),
                                "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
コード例 #8
0
        public async Task Initialize()
        {
            IBridgeLocator locator   = new HttpBridgeLocator();
            var            bridgeIPs = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            bridge = bridgeIPs.FirstOrDefault();

            // if there's one or more that comes back, register this app
            if (Connected)
            {
                client = new LocalHueClient(bridge.IpAddress);
                appKey = await client.RegisterAsync(APP_NAME, DEVICE_NAME);

                client.Initialize(appKey);
            }
        }
コード例 #9
0
        private IEnumerator searchForBridge()
        {
            SearchingGameObject.SetActive(true);
            RetryGameObject.SetActive(false);

            Debug.Log("Searching for bridge...");

            yield return(new WaitForSeconds(PrefindSeconds));

            ServicePointManager.ServerCertificateValidationCallback +=
                (sender, cert, chain, sslPolicyErrors) => true;

            LocatedBridge bridge = null;

            try
            {
                IBridgeLocator locator = new HttpBridgeLocator();
                var            bridges = locator.LocateBridgesAsync(TimeSpan.FromSeconds(TimeoutSeconds)).Result;
                bridge = bridges.FirstOrDefault();
            }
            catch
            {
                // Swallow exception
            }

            Debug.Log(bridge == null ? "No bridge found" : $"Bridge found: {bridge.IpAddress}");

            if (bridge != null)
            {
                // Bridge found, move to app registration
                if (!string.IsNullOrEmpty(bridge.IpAddress))
                {
                    // Set IP in application state
                    ApplicationState.Instance.HueBridgeIp = bridge.IpAddress;

                    // Move to app registration screen
                    ExecuteEvents.ExecuteHierarchy <ISwitchScreenHandler>(gameObject, null,
                                                                          (x, y) => x.SwitchScreen(ScreenType.AppRegistration));
                }
            }
            else
            {
                // Show retry UI
                SearchingGameObject.SetActive(false);
                RetryGameObject.SetActive(true);
            }
        }
コード例 #10
0
        public async Task <bool> ConnectToBridge(string ip = null, bool loadKey = true)
        {
            IBridgeLocator locator = new HttpBridgeLocator();
            IEnumerable <LocatedBridge> bridges = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

            LocatedBridge bridge = null;

            if (ip == null)
            {
                bridge = bridges.FirstOrDefault();
            }
            else
            {
                bridge = bridges.FirstOrDefault(b => b.IpAddress == ip);
            }

            if (bridge == null)
            {
                throw new ArgumentException("Hue Bridge not found");
            }

            var configuration = new HueKey(bridge.IpAddress);

            if (loadKey)
            {
                _key = configuration.LoadKey();
            }

            if (_key == null)
            {
                _key = await Register(bridge);

                if (_key == null)
                {
                    return(false);
                }

                if (!configuration.SaveKey(_key))
                {
                    return(false);
                }
            }

            _client = Initialize(bridge);
            return(true);
        }
コード例 #11
0
        public HueStateMachine(IBox gameBox,
                               LocatedBridge bridge,
                               ILightableButton button,
                               List <ILightableButton> playerTwoButtons,
                               CancellationToken cancellationToken)
        {
            this.gameBox           = gameBox;
            this.bridge            = bridge;
            this.button            = button;
            this.playerTwoButtons  = playerTwoButtons;
            this.cancellationToken = cancellationToken;

            this.stateMachine = new StateMachine <HueBridgeState, HueBridgeEvent>();

            this.stateMachine.In(HueBridgeState.Initialized)
            .On(HueBridgeEvent.Located)
            .Goto(HueBridgeState.Located);

            this.stateMachine.In(HueBridgeState.Located)
            .ExecuteOnEntry(this.Located)
            .On(HueBridgeEvent.Connected)
            .Goto(HueBridgeState.Connected)
            .On(HueBridgeEvent.Register)
            .Goto(HueBridgeState.Register);

            this.stateMachine.In(HueBridgeState.Register)
            .ExecuteOnEntry(this.Register)
            .On(HueBridgeEvent.Connected)
            .Goto(HueBridgeState.Connected);

            this.stateMachine.In(HueBridgeState.Connected)
            .ExecuteOnEntry(this.Connected)
            .On(HueBridgeEvent.Select)
            .Goto(HueBridgeState.Selected);

            this.stateMachine.In(HueBridgeState.Selected)
            .ExecuteOnEntry(this.Selected)
            .On(HueBridgeEvent.Unselect)
            .Goto(HueBridgeState.Connected)
            .Execute(this.Unselect);

            this.stateMachine.TransitionExceptionThrown += this.StateMachineOnTransitionExceptionThrown;

            this.stateMachine.Initialize(HueBridgeState.Initialized);
        }
コード例 #12
0
 public BridgeData(LocatedBridge b)
 {
     if (b == null)
     {
         throw new ArgumentException("Invalid located bridge.");
     }
     IpAddress     = b.IpAddress;
     Id            = b.BridgeId;
     Brightness    = 100;
     Name          = Id;
     User          = "";
     Key           = "";
     SelectedGroup = "-1";
     Groups        = new List <Group>();
     Lights        = new List <LightData>();
     GroupName     = "";
     GroupNumber   = -1;
 }
コード例 #13
0
        async Task <string> Register(LocatedBridge bridge)
        {
            if (WaitForUserInput == null)
            {
                throw new InvalidOperationException("You must set WaitForUserInput");
            }

            WaitForUserInput("Press the button on your bridge then press ENTER");
            try
            {
                ILocalHueClient client = new LocalHueClient(bridge.IpAddress);
                return(await client.RegisterAsync("Alteridem.Hue.CLI", Environment.MachineName));
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }
コード例 #14
0
ファイル: BridgeSelector.xaml.cs プロジェクト: joao7yt/CSHUE
        private void ButtonOk_OnClick(object sender, RoutedEventArgs e)
        {
            foreach (var c in ViewModel.List)
            {
                if (!c.IsChecked)
                {
                    continue;
                }

                SelectedBridge = new LocatedBridge
                {
                    IpAddress = c.Ip,
                    BridgeId  = c.Id
                };
                break;
            }

            DialogResult = true;
            Close();
        }
コード例 #15
0
        public async Task InitializeAsync()
        {
            List <LocatedBridge> bridges = await HueBridgeDiscovery.FastDiscoveryAsync(TimeSpan.FromSeconds(5));

            LocatedBridge locatedBridge = bridges.First();

            if (string.IsNullOrEmpty(_appKey))
            {
                throw new NotImplementedException("Registering application is not yet implemented");
            }

            LocalHueClient hueClient = new LocalHueClient(locatedBridge.IpAddress, _appKey);

            if (!await hueClient.CheckConnection())
            {
                throw new Exception("Could not establish connection to bridge");
            }

            _hueClient = hueClient;
        }
コード例 #16
0
 public FrmHandshake(LocatedBridge bridge)
 {
     InitializeComponent();
     this._bridge         = bridge;
     this.ptbBanner.Image = Properties.Resources.mode_hue;
 }
コード例 #17
0
        /// <summary>
        /// Listen to any response on a socket and check if responding IP is a Hue Bridge
        /// </summary>
        /// <param name="socket">The socket to listen to</param>
        /// <param name="discoveredBridges">The dictionary to fill with located bridges</param>
        private void ListenSocketAndCheckEveryEndpoint(Socket socket, ConcurrentDictionary <string, LocatedBridge> discoveredBridges)
        {
            try
            {
                var ipSeen        = new List <string>();
                var socketAddress = ((IPEndPoint?)socket.LocalEndPoint)?.Address;

                while (true)
                {
                    var      responseRawBuffer = new byte[8000];
                    EndPoint responseEndPoint  = new IPEndPoint(IPAddress.Any, 0);

                    // Blocking call until something is received
                    socket.ReceiveFrom(responseRawBuffer, ref responseEndPoint);

                    // We received a response
                    try
                    {
                        // Get IP address
                        IPAddress responseIpAddress = ((IPEndPoint)responseEndPoint).Address;

                        if (!(socketAddress?.Equals(responseIpAddress) ?? false) && !ipSeen.Contains(responseIpAddress.ToString()))
                        {
                            // Try decode response as UTF8
                            var responseBody = Encoding.UTF8.GetString(responseRawBuffer);

                            if (!string.IsNullOrWhiteSpace(responseBody))
                            {
                                // Spin up a new thread to handle this specific response so we can continue waiting for response
                                new Thread(() =>
                                {
                                    try
                                    {
                                        // Check if it's a Hue Bridge
                                        string serialNumber = CheckHueDescriptor(responseIpAddress, TimeSpan.FromMilliseconds(1000)).Result;

                                        if (!string.IsNullOrWhiteSpace(serialNumber))
                                        {
                                            var locatedBridge = new LocatedBridge()
                                            {
                                                IpAddress = responseIpAddress.ToString(),
                                                BridgeId  = serialNumber,
                                            };
                                            if (discoveredBridges.TryAdd(responseIpAddress.ToString(), locatedBridge))
                                            {
                                                OnBridgeFound(locatedBridge);
                                            }
                                        }
                                        else
                                        {
                                            // Not a valid S/N
                                        }
                                    }
                                    catch
                                    {
                                        // Something went wrong, ignore...
                                    }
                                }).Start();

                                // Add this ip to local list, so we won't start other thread for it
                                ipSeen.Add(responseIpAddress.ToString());
                            }
                            else
                            {
                                // Not a valid response
                            }
                        }
                        else
                        {
                            // IP already seen
                        }
                    }
                    catch
                    {
                        // Something went wrong when parsing the response. Ignore it.
                    }
                }
            }
            catch
            {
                // Socket connection closed, this will terminate the thread
            }
        }
コード例 #18
0
 public HueEndpoint(LocatedBridge endpoint)
 {
     Endpoint = endpoint ?? throw new System.ArgumentNullException(nameof(endpoint));
     Client   = new LocalHueClient(Endpoint.IpAddress);
 }
コード例 #19
0
 public PhilipsHueBridge(LocatedBridge newBridge)
 {
     BridgeId  = newBridge.BridgeId;
     IpAddress = newBridge.IpAddress;
 }
コード例 #20
0
 public BridgeItem(LocatedBridge bridge)
 {
     this.bridge      = bridge;
     this.displayName = bridge.BridgeId;
 }
コード例 #21
0
 public void SetBridge(LocatedBridge bridge)
 {
     _useBridge = bridge;
 }
コード例 #22
0
ファイル: BridgeInfo.cs プロジェクト: rmmlr/Hue2Json
 public BridgeInfo(LocatedBridge locatedBridge)
 {
     IpAddress = locatedBridge.IpAddress;
     BridgeId  = locatedBridge.BridgeId;
 }
コード例 #23
0
ファイル: BridgeLocator.cs プロジェクト: pil4283/Q42.HueApi
 /// <summary>
 /// Calls the event that a bridge is found
 /// </summary>
 /// <param name="locatedBridge">The bridge that was found</param>
 protected void OnBridgeFound(LocatedBridge locatedBridge)
 {
     BridgeFound(this, locatedBridge);
 }
コード例 #24
0
        /// <summary>
        /// Locate bridges
        /// </summary>
        /// <param name="cancellationToken">Token to cancel the search</param>
        /// <returns>List of bridge IPs found</returns>
        public override async Task <IEnumerable <LocatedBridge> > LocateBridgesAsync(CancellationToken cancellationToken)
        {
            var discoveredBridges = new ConcurrentDictionary <string, LocatedBridge>();

            // Get all IPv4 private unicast addresses from all network interfaces that are up
            List <IPAddress> networkIps = NetworkInterfaceExtensions.GetAllUpNetworkInterfacesFirstPrivateIPv4()
                                          // For each interface, get all IP from this network
                                          .SelectMany(info => info.Address.GetAllIPv4FromNetwork(info.IPv4Mask))
                                          // Eventually filter common ones
                                          .Distinct()
                                          .ToList();

            if (networkIps.Count > 0)
            {
                // Run in another thread so we won't block the UI
                await Task.Run(() =>
                {
                    try
                    {
                        // We'll use the Parallel.ForEach methods so the work will be distributed on all core
                        ParallelOptions parallelOptions = new ParallelOptions
                        {
                            CancellationToken      = cancellationToken,
                            MaxDegreeOfParallelism = Environment.ProcessorCount,
                        };

                        Parallel.ForEach(networkIps, parallelOptions, (ip) =>
                        {
                            // Check if an IP is a Hue Bridge by checking its descriptor
                            // Note that the timeout here is important:
                            // - if small, can speedup significantly the searching, but may miss an answer if the Hue Bridge took too much time to answer
                            // - if big, will be sure to check thoroughly each IP, but the search can be slower
                            string serialNumber = CheckHueDescriptor(ip, TimeSpan.FromMilliseconds(1000), cancellationToken).Result;

                            if (!string.IsNullOrEmpty(serialNumber))
                            {
                                var locatedBridge = new LocatedBridge()
                                {
                                    IpAddress = ip.ToString(),
                                    BridgeId  = serialNumber,
                                };
                                if (discoveredBridges.TryAdd(ip.ToString(), locatedBridge))
                                {
                                    OnBridgeFound(locatedBridge);
                                }
                            }
                            else
                            {
                                // Not a hue bridge
                            }
                        });
                    }
                    catch (OperationCanceledException)
                    {
                        // Cancellation requested
                    }
                });
            }
            else
            {
                // No IP found
            }

            return(discoveredBridges.Select(x => x.Value).ToList());
        }
コード例 #25
0
        static async Task IndexHueBridges(TwinCollection desiredProperties) {
            // Only proceed if the module twin contains a hueBridges key
            // TODO: exception handling in case of malformed JSON?
            if (desiredProperties.Contains("hueBridges")) {

                // Reset previous lists of sensors and lights
                hueSensors.Clear();
                hueLights.Clear();

                // Naive lookup through https://discovery.meethue.com
                IBridgeLocator locator = new HttpBridgeLocator();
                IEnumerable<LocatedBridge> locatedLocalBridges  = await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5));

                // Iterate over the bridge IDs and corresponding app key credentials provided in the module twin
                JArray moduleTwinBridges = desiredProperties["hueBridges"];
                foreach (JObject bridge in moduleTwinBridges.Children()) {
                    string moduleTwinBridgeId = bridge.GetValue("id").ToString();
                    string moduleTwinAppKey = bridge.GetValue("appKey").ToString();

                    // If a locally found bridge corresponds with a set of such credentials from the module twin, index it for sensors and lights
                    IEnumerable<LocatedBridge> locatedBridgesInModuleTwinProperties = locatedLocalBridges.Where(locatedBridge => locatedBridge.BridgeId == moduleTwinBridgeId);
                    if (locatedBridgesInModuleTwinProperties.Count() == 1) {
                        LocatedBridge bridgeToIndex = locatedBridgesInModuleTwinProperties.First();
                        Console.WriteLine($"Will index Hue bridge with ID = {moduleTwinBridgeId} at IP {bridgeToIndex.IpAddress}, using App Key = {moduleTwinAppKey}");

                        LocalHueClient client = new LocalHueClient(bridgeToIndex.IpAddress, moduleTwinAppKey);

                        try {
                            // Index sensors
                            IReadOnlyCollection<Sensor> sensors = await client.GetSensorsAsync();
                            foreach(Sensor sensor in sensors) {
                                if (Enum.IsDefined(typeof(SensorType), sensor.Type)) {
                                    HueDeviceDescription sensorDescription = new HueDeviceDescription() {
                                        id = sensor.Id,
                                        uniqueId = sensor.UniqueId,
                                    };
                                    hueSensors.Add(sensorDescription, new HueClientDescription(){client = client, ip = bridgeToIndex.IpAddress});
                                    Console.WriteLine($"Found sensor: {sensor.Name} ({sensor.UniqueId})");
                                }
                            }
                        
                            // Index lights
                            IEnumerable<Light> lights = await client.GetLightsAsync();
                            foreach(Light light in lights) {
                                hueLights.Add(light.Name);
                                Console.WriteLine($"Found light: {light.Name} ({light.UniqueId})");
                            }
                        }
                        catch (Exception ex) 
                        {
                            Console.Error.WriteLine(ex.Message);
                            Console.Error.WriteLine(ex.StackTrace);
                        }
                    }
                }

                // Report back the results of the indexing; the unique ID:s of each detected Hue device
                TwinCollection reportedProperties = new TwinCollection
                {
                    ["Sensors"] = hueSensors.Keys.Select(sensorDescription => sensorDescription.uniqueId),
                    ["Lights"] = hueLights
                };
                await ioTHubModuleClient.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false);
            }
        }