Esempio n. 1
0
        /// <summary>
        /// Set the light state of a scene.
        /// </summary>
        /// <param name="sceneid">Id of the scene.</param>
        /// <param name="lightid">Id of the light.</param>
        /// <param name="state">State of the light.</param>
        /// <returns>BrideHttpResult</returns>
        public bool SetSceneLightState(string sceneid, string lightid, IBaseProperties state)
        {
            string     url = BridgeUrl + $"/scenes/{sceneid}/lightstates/{lightid}";
            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, Serializer.ModifyJsonObject(state));

                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Set Virtual scene state : {sceneid}, {lightid}, {state.ToString()}"
                });
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 2
0
        private static void _bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            string    mac = e.Argument.ToString();
            IPAddress ip  = IPAddress.Parse(GetLocalIPAddress());

            byte[] ipArray   = ip.GetAddressBytes();
            byte   currentip = ipArray[3];

            e.Result = null;

            for (byte x = 2; x <= 254; x++)
            {
                if (_bgw.CancellationPending)
                {
                    log.Info("Bridge lookup cancelled.");
                    e.Cancel = true;
                    break;
                }


                if (x == currentip)
                {
                    continue;
                }
                ipArray[3] = x;
                _bgw.ReportProgress(0, new ProgressReport(new IPAddress(ipArray), x));

                HueHttpClient.Timeout = 50;
                if (_bgw.CancellationPending)
                {
                    break;
                }

                HttpResult comres = HueHttpClient.SendRequest(new Uri($@"http://{new IPAddress(ipArray)}/api/config"), WebRequestType.Get);
                Philips_Hue.BridgeObject.BridgeObjects.BridgeSettings desc = new Philips_Hue.BridgeObject.BridgeObjects.BridgeSettings();

                if (comres.Success)
                {
                    desc = Serializer.DeserializeToObject <Philips_Hue.BridgeObject.BridgeObjects.BridgeSettings>(comres.Data); // try to deserialize the received message.
                    if (desc == null)
                    {
                        continue;               // if the deserialisation didn't work it means this is not a bridge continue with next ip.
                    }
                    if (desc.mac == mac)
                    {
                        e.Result = new IPAddress(ipArray);
                        break;
                    }
                }

                if (e.Result != null)
                {
                    _bgw.ReportProgress(0, new ProgressReport(new IPAddress(ipArray), 254));
                    break;
                }
            }

            // Restore the timeout to the original value
            HueHttpClient.Timeout = WinHueSettings.settings.Timeout;
        }
Esempio n. 3
0
        /// <summary>
        /// Remove the specified object from the bridge.
        /// </summary>
        /// <typeparam name="T">HueObject (Light,Group,Sensor,Rule,Schedule,Scene)</typeparam>
        /// <param name="obj">Object to modify</param>
        /// <returns>HueObject (Light,Group,Sensor,Rule,Schedule,Scene)</returns>
        public bool RemoveObject(string Id, HueObjectType type)
        {
            string typename = type.ToString();
            string url      = BridgeUrl + $@"/{typename}/{Id}";

            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Delete);
                if (comres.Success)
                {
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Deleted Virtual object : {Id},{type.ToString()}"
                });
                return(LastCommandMessages.Success);
            }

            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 4
0
        /// <summary>
        /// Rename a specified object on the bridge.
        /// </summary>
        /// <typeparam name="T">HueObject (Light,Group,Sensor,Rule,Schedule,Scene)</typeparam>
        /// <param name="id">ID of the specified object to rename.</param>
        /// <param name="newname">New name of the object.</param>
        /// <returns>BridgeHttpResult</returns>
        public bool RenameObject(IHueObject hueobj)
        {
            string typename = hueobj.GetType().Name.ToLower() + "s";
            string url      = BridgeUrl + $@"/{typename}/{hueobj.Id}";

            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, $@"{{""name"":""{hueobj.name}""}}");
                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Rename object : {hueobj.ToString()}"
                });
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 5
0
        /// <summary>
        /// Modify the specified object in the bridge.
        /// </summary>
        /// <typeparam name="T">HueObject (Light,Group,Sensor,Rule,Schedule,Scene)</typeparam>
        /// <param name="modifiedobject">The new modified object.</param>
        /// <param name="id">Id of the object.</param>
        /// <returns>BridgeHttpResult</returns>
        public bool ModifyObject(IHueObject modifiedobject)
        {
            string     typename = modifiedobject.GetType().Name.ToLower() + "s";
            IHueObject clone    = (IHueObject)modifiedobject.Clone();
            string     url      = BridgeUrl + $@"/{typename}/{modifiedobject.Id}";

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

            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, Serializer.ModifyJsonObject(clone));
                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Modified Virtual object : {modifiedobject.ToString()}"
                });
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 6
0
        /// <summary>
        /// Change the sensor's state.
        /// </summary>
        /// <param name="id">id of the sensor</param>
        /// <param name="newstate">New state of the sensor</param>
        /// <returns>BridgeHttpResult</returns>
        public bool ChangeSensorState(string id, object newstate)
        {
            string     url = BridgeUrl + $@"/sensors/{id}/state";
            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, Serializer.ModifyJsonObject(newstate));
                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Modified Virtual sensor state : {id},{newstate.ToString()}"
                });
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 7
0
        /// <summary>
        /// Activate a scene.
        /// </summary>
        /// <param name="id">Id of the scene.</param>
        /// <returns>BridgeHttpResult</returns>
        public bool ActivateScene(string id)
        {
            string     url = BridgeUrl + "/groups/0/action";
            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, "{\"scene\":\"" + id + "\"}");
                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Set Virtual scene : {id}"
                });
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 8
0
        /// <summary>
        /// Set Entertrainment Group light location
        /// </summary>
        /// <param name="id">ID of the group</param>
        /// <param name="loc">Location information</param>
        /// <returns></returns>
        public bool SetEntertrainementLightLocation(string id, Location loc)
        {
            string     url = BridgeUrl + $@"/groups/{id}";
            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, Serializer.SerializeJsonObject(loc));
                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = $"Update Light location for group : {id}"
                });
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 9
0
        public bool RemoveUser(string username)
        {
            string     url    = BridgeUrl + "/config/whitelist/" + username;
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Delete);

            if (comres.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 10
0
        /// <summary>
        /// Allows the user to set some configuration values.
        /// </summary>
        /// <param name="settings">Settings of the bridge.</param>
        /// <return>The new settings of the bridge.</return>
        public bool SetBridgeSettings(BridgeSettings settings)
        {
            string     url    = BridgeUrl + "/config";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, Serializer.ModifyJsonObject(settings));

            if (comres.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 11
0
        /// <summary>
        /// Set notify to false once the update has been done.
        /// </summary>
        /// <returns>True or false if the operation was successful or not</returns>
        public bool SetNotify()
        {
            HttpResult comres = HueHttpClient.SendRequest(new Uri(BridgeUrl + "/config"), WebRequestType.Put, "{\"swupdate\": {\"notify\":false}}");

            if (comres.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, BridgeUrl + "/config", WebExceptionStatus.NameResolutionFailure));

            return(false);
        }
Esempio n. 12
0
        /// <summary>
        /// Get Bridge capabilities
        /// </summary>
        /// <returns></returns>
        public Capabilities GetBridgeCapabilities()
        {
            string     url    = BridgeUrl + "/capabilities";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                Capabilities cap = Serializer.DeserializeToObject <Capabilities>(comres.Data);
                return(cap);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 13
0
        /// <summary>
        /// Try to contact the specified bridge to get the basic config.
        /// </summary>
        /// <param name="BridgeIP">IP Address of the bridge.</param>
        /// <returns>The basic configuration of the bridge.</returns>
        public BasicConfig GetBridgeBasicConfig()
        {
            string     url    = BridgeUrl + "/config";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                BasicConfig config = Serializer.DeserializeToObject <BasicConfig>(comres.Data);
                return(config);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 14
0
        /// <summary>
        /// Send a raw json command to the bridge without altering the bridge lastmessages
        /// </summary>
        /// <param name="url">url to send the command to.</param>
        /// <param name="data">raw json data string</param>
        /// <param name="type">type of command.</param>
        /// <returns>json test resulting of the command.</returns>
        public string SendRawCommand(string url, string data, WebRequestType type)
        {
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), type, data);

            if (comres.Success)
            {
                if (type != WebRequestType.Get)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                }
                return(comres.Data);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 15
0
        /// <summary>
        /// Set the state of a light or group on the bridge.
        /// </summary>
        /// <typeparam name="T">Any class the derives from CommonProperties</typeparam>
        /// <param name="state">New state of the object.</param>
        /// <param name="id">ID of the specified object.</param>
        /// <returns>BridgeHttpResult</returns>
        public bool SetState(IBaseProperties state, string id)
        {
            string typename = null;
            string type     = null;

            if (state is State)
            {
                typename = "lights";
                type     = "state";
            }
            if (state is Action)
            {
                typename = "groups";
                type     = "action";
            }
            if (typename == null)
            {
                return(false);
            }
            string url = BridgeUrl + $@"/{typename}/{id}/{type}";

            HttpResult comres;

            if (!Virtual)
            {
                comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Put, Serializer.ModifyJsonObject(state));
                if (comres.Success)
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                    return(LastCommandMessages.Success);
                }
            }
            else
            {
                LastCommandMessages.AddMessage(new Success()
                {
                    Address = url, value = state.ToString()
                });
                return(LastCommandMessages.Success);
            }


            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 16
0
        /// <summary>
        /// Get the list of users.
        /// </summary>
        /// <returns>The List of user or null on error.</returns>
        public Dictionary <string, Whitelist> GetUserList()
        {
            string     url    = BridgeUrl + "/config";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                BridgeSettings brs = Serializer.DeserializeToObject <BridgeSettings>(comres.Data);
                if (brs != null)
                {
                    return(brs.whitelist);
                }
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(null);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 17
0
        /// <summary>
        /// Update the bridge firmware.
        /// </summary>
        /// <returns>True or False command sent succesfully.</returns>
        public bool UpdateBridge()
        {
            Version api   = Version.Parse(ApiVersion);
            Version limit = Version.Parse("1.20.0");

            string updatestring = "";

            updatestring = api > limit ? "{\"swupdate2\": {\"install\": true}}" : "{\"swupdate\":{\"updatestate\":3}}";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(BridgeUrl + "/config"), WebRequestType.Put, updatestring);

            if (comres.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, BridgeUrl + "/config", WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 18
0
        /// <summary>
        ///  Get all the timezones that are supported by the bridge.
        /// </summary>
        /// <returns>a list of all the timezones supported by the bridge.</returns>
        public List <string> GetTimeZones()
        {
            string     url    = BridgeUrl + "/info/timezones";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                List <string> timezones = Serializer.DeserializeToObject <List <string> >(comres.Data);
                if (timezones != null)
                {
                    return(timezones);
                }
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(null);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 19
0
        /// <summary>
        /// Check if there is an update available on the bridge . (Does not force the bridge to check for an update)
        /// </summary>
        /// <returns>Software Update or null.</returns>
        public bool CheckUpdateAvailable()
        {
            HttpResult comres = HueHttpClient.SendRequest(new Uri(BridgeUrl + "/config"), WebRequestType.Get);

            if (comres.Success)
            {
                BridgeSettings brs = Serializer.DeserializeToObject <BridgeSettings>(comres.Data);
                if (brs != null)
                {
                    return(brs.swupdate.updatestate == 2);
                }
                else
                {
                    LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(HueHttpClient.LastJson));
                }
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, BridgeUrl + "/config", WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 20
0
        /// <summary>
        /// Force the bridge to check online for an update.
        /// </summary>
        /// <returns>True or false if the operation is successful (does not return if there is an update)</returns>
        public bool CheckOnlineForUpdate()
        {
            Version api   = Version.Parse(ApiVersion);
            Version limit = Version.Parse("1.20.0");
            string  swu   = "swupdate";

            if (api > limit)
            {
                swu = swu + "2";
            }
            HttpResult comres = HueHttpClient.SendRequest(new Uri(BridgeUrl + "/config"), WebRequestType.Put, "{\"" + swu + "\": {\"checkforupdate\":true}}");

            if (comres.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, BridgeUrl + "/config", WebExceptionStatus.NameResolutionFailure));
            return(false);
        }
Esempio n. 21
0
        /// <summary>
        /// Get the specified object freom the bridge.
        /// </summary>
        /// <typeparam name="T">Type of object to deserialize to</typeparam>
        /// <param name="id">Id of the object to get</param>
        /// <returns>BridgeCommResult</returns>
        public T GetObject <T>(string id) where T : IHueObject
        {
            string typename = typeof(T).Name.ToLower() + "s";

            if (typename == string.Empty || typename == "s")
            {
                return(default(T));
            }
            string     url    = BridgeUrl + $"/{typename}/{id}";
            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                T data = Serializer.DeserializeToObject <T>(comres.Data);
                if (data != null)
                {
                    data.Id = id;
                    return(data);
                }

                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(default);
Esempio n. 22
0
        public List <IHueObject> GetAllObjects(bool showhidden = false, bool getgroupzero = false)
        {
            List <IHueObject> huelist = new List <IHueObject>();
            string            url     = BridgeUrl + $"/";
            HttpResult        comres  = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                DataStore data = Serializer.DeserializeToObject <DataStore>(comres.Data);
                if (data != null)
                {
                    List <IHueObject> listdata = data.ToList();
                    if (!showhidden)
                    {
                        RemoveHiddenObjects(ref listdata, WinHueSettings.bridges.BridgeInfo[Mac].hiddenobjects);
                    }

                    if (getgroupzero)
                    {
                        listdata.Add(GetObject <Group>("0"));
                    }

                    if (!WinHueSettings.settings.ShowHiddenScenes)
                    {
                        listdata.RemoveAll(x => x.GetType() == typeof(Scene) && x.name.StartsWith("HIDDEN"));
                    }

                    return(listdata.ToList());
                }

                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(null);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));

            return(huelist);
        }
Esempio n. 23
0
        /// <summary>
        /// Creates a new user / Register a new user. The link button on the bridge must be pressed and this command executed within 30 seconds.
        /// </summary>
        /// <returns>Contains a list with a single item that details whether the user was added successfully along with the username parameter. Note: If the requested username already exists then the response will report a success.</returns>
        /// <param name="deviceType">Description of the type of device associated with this username. This field must contain the name of your app.</param>
        /// <return>The new API Key.</return>
        public string CreateUser(string deviceType, bool?generatesteamkey = null)
        {
            string url     = "http://" + _ipAddress + "/api";
            User   newuser = new User()
            {
                devicetype = deviceType, generateclientkey = generatesteamkey
            };
            Version current = new Version(ApiVersion);

            if (current < Version.Parse("1.22"))
            {
                newuser.generateclientkey = null;
            }

            HttpResult comres = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Post, Serializer.CreateJsonObject(newuser));

            if (comres.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success ? LastCommandMessages.LastSuccess.value : null);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 24
0
        /// <summary>
        /// Get a list of specified objects from the bridge.
        /// </summary>
        /// <typeparam name="T">HueObject (Light,Group,Sensor,Rule,Schedule,Scene)</typeparam>
        /// <returns>BridgeCommResult</returns>
        public List <T> GetListObjects <T>(bool showhidden = false) where T : IHueObject
        {
            string     typename = typeof(T).Name.ToLower() + "s";
            string     url      = BridgeUrl + $"/{typename}";
            HttpResult comres   = HueHttpClient.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Success)
            {
                Dictionary <string, T> data = Serializer.DeserializeToObject <Dictionary <string, T> >(comres.Data);
                if (data != null)
                {
                    List <T> listdata = data.Select(x => { x.Value.Id = x.Key; return(x.Value); }).ToList();
                    if (!showhidden)
                    {
                        RemoveHiddenObjects(ref listdata, WinHueSettings.bridges.BridgeInfo[Mac].hiddenobjects);
                    }
                    return(listdata);
                }
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(null);
            }
            BridgeNotResponding?.Invoke(this, new BridgeNotRespondingEventArgs(this, url, WebExceptionStatus.NameResolutionFailure));
            return(null);
        }
Esempio n. 25
0
        private static void _detectionBgw_DoWork(object sender, DoWorkEventArgs e)
        {
            log.Info("Starting bridge detection...");


            Dictionary <string, BasicConfig> newdetectedBridge = new Dictionary <string, BasicConfig>();

            // Detect using UPNP

            try
            {
                ServiceController sc = new ServiceController("SSDPSRV");

                if (sc.Status == ServiceControllerStatus.Running)
                {
                    log.Info("Starting UPNP detection of bridges...");
                    try
                    {
                        List <ManagedUPnP.Device> upnpDevices =
                            Discovery.FindDevices(null, 3000, int.MaxValue, out bool finished).ToList();

                        foreach (ManagedUPnP.Device dev in upnpDevices)
                        {
                            if (!dev.ModelName.Contains("Philips hue bridge"))
                            {
                                continue;
                            }
                            Bridge bridge = new Bridge()
                            {
                                IpAddress = IPAddress.Parse(dev.RootHostName)
                            };
                            BasicConfig bresult = bridge.GetBridgeBasicConfig();
                            if (bresult != null)
                            {
                                log.Info($"Bridge found : {bridge.Name} at {bridge.IpAddress} ");
                                newdetectedBridge.Add(dev.RootHostName, bresult);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    log.Info("Ending UPNP detection of bridges...");
                }
            }
            catch (Exception ex)
            {
                log.Error($"UPNP detection error : {ex.Message}");
            }

            // If not bridge are found via upnp try the portal.
            log.Info("Starting bridge portal detection...");
            if (newdetectedBridge.Count == 0)
            {
                // Detect using Portal
                HttpResult comres = HueHttpClient.SendRequest(new Uri("https://discovery.meethue.com"), WebRequestType.Get);
                if (comres.Success)
                {
                    List <HueDevice> portalDevices = Serializer.DeserializeToObject <List <HueDevice> >(comres.Data);
                    foreach (HueDevice dev in portalDevices)
                    {
                        if (newdetectedBridge.ContainsKey(dev.internalipaddress))
                        {
                            continue;
                        }
                        Bridge bridge = new Bridge()
                        {
                            IpAddress = IPAddress.Parse(dev.internalipaddress)
                        };
                        BasicConfig bresult = bridge.GetBridgeBasicConfig();
                        if (bresult != null)
                        {
                            log.Info($"Bridge found : {bridge.Name} at {bridge.IpAddress} ");
                            newdetectedBridge.Add(dev.internalipaddress, bresult);
                        }
                    }
                }
                else
                {
                    log.Info($"Dns resolution failure. (AKA unable to connect to the bridge");
                    OnPortalDetectionTimedOut?.Invoke(null, new DetectionErrorEventArgs(comres.Data));
                    OnBridgeDetectionFailed?.Invoke(null, new DetectionErrorEventArgs(comres.Data));
                }
            }
            log.Info("Ending bridge portal detection...");

            Dictionary <string, Bridge> bridges = newdetectedBridge.Select(kvp => new Bridge
            {
                IpAddress  = IPAddress.Parse(kvp.Key),
                Mac        = kvp.Value.mac,
                ApiVersion = kvp.Value.apiversion,
                SwVersion  = kvp.Value.swversion,
                Name       = kvp.Value.name ?? ""
            }).ToDictionary(p => p.Mac, p => p);

            // Process all bridges to get needed settings.
            e.Result = bridges;
            log.Info("Ending bridge detection.");
        }
Esempio n. 26
0
        public void GetBadTest()
        {
            HttpResult res = HueHttpClient.SendRequest(new Uri(badbaseUri + "lights"), WebRequestType.Get);

            Assert.IsFalse(res.Success);
        }