Beispiel #1
0
        /// <summary>
        /// Get All objects from the bridge
        /// </summary>
        /// <param name="showmyhidden">Show users hidden objects</param>
        /// <param name="getgroupzero">Show group zero</param>
        /// <returns></returns>
        public async Task <List <IHueObject> > GetAllObjectsAsync(bool showmyhidden = false, bool getgroupzero = false)
        {
            List <IHueObject> huelist = new List <IHueObject>();
            string            url     = BridgeUrl + $"/";
            CommResult        comres  = await Comm.SendRequestAsyncTask(new Uri(url), WebRequestType.Get);

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

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

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

                    return(listdata);
                }

                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(null);
            }
            ProcessCommandFailure(url, comres.Status);

            return(huelist);
        }
Beispiel #2
0
        public async Task <bool> FindNewLightsAsync(string serialslist = null)
        {
            LightSearchSerial lsl = new LightSearchSerial();

            if (serialslist != null)
            {
                string[] serials = serialslist.Split(',');

                foreach (string s in serials)
                {
                    lsl.deviceid.Add(s);
                }
            }

            CommResult comres = await Comm.SendRequestAsyncTask(new Uri(BridgeUrl + $"/lights"), WebRequestType.Post, lsl.deviceid.Count == 0? "" : Serializer.SerializeJsonObject(lsl));

            if (comres.Status == WebExceptionStatus.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(true);
            }
            ProcessCommandFailure(BridgeUrl + $"/lights", comres.Status);
            return(false);
        }
Beispiel #3
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 IHueObject GetObject(string id, Type objecttype)
        {
            string typename = objecttype.GetHueType();

            if (typename == null)
            {
                return(null);
            }
            string     url    = BridgeUrl + $"/{typename}/{id}";
            CommResult comres = Comm.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Status == WebExceptionStatus.Success)
            {
                IHueObject data = (IHueObject)Serializer.DeserializeToObject(comres.Data, objecttype);
                if (data != null)
                {
                    return(data);
                }
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(null);
            }
            ProcessCommandFailure(url, comres.Status);
            return(null);
        }
Beispiel #4
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).GetHueType();

            if (typename == null)
            {
                return(default(T));
            }
            string     url    = BridgeUrl + $"/{typename}/{id}";
            CommResult comres = Comm.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Status == WebExceptionStatus.Success)
            {
                T data = Serializer.DeserializeToObject <T>(comres.Data);
                if (data != null)
                {
                    return(data);
                }
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(default(T));
            }
            ProcessCommandFailure(url, comres.Status);
            return(default(T));
        }
Beispiel #5
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;
            }

            CommResult comres = Comm.SendRequest(new Uri(url), WebRequestType.Post, Serializer.SerializeToJson(newuser));

            if (comres.Status == WebExceptionStatus.Success)
            {
                LastCommandMessages.AddMessage(Serializer.DeserializeToObject <List <IMessage> >(comres.Data));
                return(LastCommandMessages.Success ? LastCommandMessages.LastSuccess.value : null);
            }
            ProcessCommandFailure(url, comres.Status);
            return(null);
        }
Beispiel #6
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}";
            CommResult comres   = Comm.SendRequest(new Uri(url), WebRequestType.Get);

            if (comres.Status == WebExceptionStatus.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);
            }
            ProcessCommandFailure(url, comres.Status);
            return(null);
        }
Beispiel #7
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
                CommResult comres = Comm.SendRequest(new Uri("http://www.meethue.com/api/nupnp"), WebRequestType.Get);

                switch (comres.Status)
                {
                case WebExceptionStatus.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);
                        }
                    }
                    break;

                case WebExceptionStatus.Timeout:
                    log.Info($"Timeout while detecting bridge via portal");
                    OnPortalDetectionTimedOut?.Invoke(null, new DetectionErrorEventArgs(comres.Data));
                    OnBridgeDetectionFailed?.Invoke(null, new DetectionErrorEventArgs(comres.Data));
                    break;

                default:
                    log.Info($"Unknown error while detecting bridge via portal");
                    OnPortalDetectionError?.Invoke(null, new DetectionErrorEventArgs(comres.Data));
                    OnBridgeDetectionFailed?.Invoke(null, new DetectionErrorEventArgs(comres.Data));
                    break;
                }
            }
            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.");
        }
Beispiel #8
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));

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

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

                switch (comres.Status)
                {
                case WebExceptionStatus.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;
                    }

                    break;

                case WebExceptionStatus.Timeout:
                    // IP DOES NOT RESPOND
                    break;

                default:

                    break;
                }

                if (e.Result != null)
                {
                    _bgw.ReportProgress(0, new ProgressReport(new IPAddress(ipArray), 254));
                    break;
                }
            }
        }
Beispiel #9
0
        private void btn_login_Click(object sender, EventArgs e)
        {
            this.btn_login.Enabled = false;
            this.Cursor            = Cursors.WaitCursor;
            if (this.ddl_websites.SelectedIndex < 0)
            {
                MessageBox.Show("请选择平台!");
                return;
            }
            if (Program.allGc == null)
            {
                Program.allGc = Program.gc.CopyTo <GlobalClass>();
            }
            // GlobalClass.resetTypeDataPoints();//必须重新设置,每个平台投注品种不一样
            Program.gc.ClientUserName = this.txt_user.Text.Trim();
            Program.gc.ClientPassword = this.txt_password.Text.Trim();
            Program.gc.ForWeb         = this.ddl_websites.SelectedValue.ToString();
            GlobalClass.SetConfig();
            GlobalClass sgc = new GlobalClass(this.ddl_websites.SelectedValue.ToString());

            if (sgc.loadSucc)
            {
                Program.gc = sgc;

                //Program.gc.ForWeb = this.ddl_websites.SelectedValue.ToString();
                //return;
            }
            CommunicateToServer cts = new CommunicateToServer();
            CommResult          cr  = cts.Login(GlobalClass.strLoginUrlModel, this.txt_user.Text, this.txt_password.Text);

            if (cr == null)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show("无法返回对象!");
                this.btn_login.Enabled = true;
                return;
            }
            if (cr.Succ == false)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(cr.Message);
                this.btn_login.Enabled = true;
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            this.Hide();
            UserInfoClass ret = cr.Result[0] as UserInfoClass;

            Program.UserId             = ret.BaseInfo.UserId;
            Program.gc.ClientUserName  = ret.BaseInfo.UserCode;
            Program.gc.ClientPassword  = ret.BaseInfo.Password;
            Program.gc.Odds            = ret.BaseInfo.Odds;
            Program.gc.WXLogNoticeUser = ret.BaseInfo.WXToUser;

            Program.gc.ClientAliasName = string.IsNullOrEmpty(ret.BaseInfo.AliasName)?ret.BaseInfo.UserCode:ret.BaseInfo.AliasName;
            XmlDocument xmldoc = new XmlDocument();

            try
            {
                string strXml = HttpUtility.UrlDecode(ret.BaseInfo.AssetConfig, Encoding.UTF8);
                xmldoc.LoadXml(strXml);
                XmlNodeList items = xmldoc.SelectNodes("config[@type='AssetUnits']/item");
                Dictionary <string, AssetInfoConfig> assetconfig = new Dictionary <string, AssetInfoConfig>();
                if (items.Count > 0)
                {
                    for (int i = 0; i < items.Count; i++)
                    {
                        string key = items[i].SelectSingleNode("@key").Value;
                        //int val = int.Parse(items[i].SelectSingleNode("@value").Value);
                        //if (!assetconfig.ContainsKey(key))
                        //    assetconfig.Add(key, val);
                        AssetInfoConfig aic = new AssetInfoConfig(GlobalClass.readXmlItems(items[i].OuterXml));
                        if (!assetconfig.ContainsKey(key))
                        {
                            assetconfig.Add(key, aic);
                        }
                    }
                }
                Program.gc.AssetUnits = assetconfig;
            }
            catch (Exception ce)
            {
                //return;
            }
            if (Program.gc.SvrConfigUrl != null)//获取服务器默认配置
            {
                string strConfig = AccessWebServerClass.GetData(string.Format(Program.gc.SvrConfigUrl, Program.gc.InstHost), Encoding.UTF8);
                if (strConfig != null && strConfig.Trim().Length > 0)
                {
                    SvrConfigClass scc = new SvrConfigClass().getObjectByJsonString(strConfig);
                    if (scc.DefaultExchangeHost != null)
                    {
                        Program.gc.LoginDefaultHost = scc.DefaultExchangeHost;
                    }
                    if (scc.WXSvrHost != null)
                    {
                        Program.gc.WXSVRHost = scc.WXSvrHost;
                    }
                    if (scc.DefaultNavHost != null)
                    {
                        Program.gc.NavHost = scc.DefaultNavHost;
                    }
                }
            }
            try
            {
                //Program.gc.LoginDefaultHost = WebRuleBuilder.Create(Program.gc).GetChanle(Program.gc.WebNavUrl, Program.gc.LoginDefaultHost); ;
                GlobalClass.SetConfig(Program.gc.ForWeb);
                this.Hide();
                this.Cursor = Cursors.Default;
                //必须重新指定登录用户
                Program.wxl = new WolfInv.com.LogLib.WXLogClass(Program.gc.ClientAliasName, Program.gc.WXLogNoticeUser, Program.gc.WXLogUrl);
                MainWindow mw = new MainWindow();
                //testWeb mw = new testWeb();
                DialogResult res = mw.ShowDialog();

                //////while ( res == DialogResult.OK)//如果frm退出是因为要求重启
                //////{
                //////    if (mw.ForceReboot)
                //////    {
                //////        mw.ForceReboot = false;
                //////        Program.Reboot = false;
                //////        mw = new MainWindow();
                //////        res = mw.ShowDialog();
                //////    }
                //////    //GC.SuppressFinalize(frm);
                //////}
                Application.Exit();
            }
            catch (Exception ce1)
            {
                MessageBox.Show(string.Format("{0}:{1}", ce1.Message, ce1.StackTrace));
            }
        }
Beispiel #10
0
        private void timer_RequestInst_Tick(object sender, ElapsedEventArgs e)
        {
            DateTime            CurrTime = DateTime.Now;
            CommunicateToServer wc       = new CommunicateToServer();
            CommResult          cr       = wc.getRequestInsts(GlobalClass.strRequestInstsURL);

            if (!cr.Succ)
            {
                this.statusStrip1.Items[0].Text = cr.Message;
                return;
            }
            if (cr.Cnt != 1)
            {
                this.statusStrip1.Items[0].Text = "无指令!";
                return;
            }
            RequestClass ic = cr.Result[0] as RequestClass;

            if (ic == null)
            {
                this.statusStrip1.Items[0].Text = "指令内容错误!";
                return;
            }
            Int64 CurrExpectNo = Int64.Parse(ic.Expect);

            this.statusStrip1.Items[1].Text = DateTime.Now.ToLongTimeString();
            if (CurrExpectNo > this.NewExpect)
            {
                LastInstsTime = DateTime.Now;
                int CurrMin = DateTime.Now.Minute % 5;

                ////if (CurrMin % 5 < 2)
                ////{
                ////    this.timer_RequestInst.Interval = (2-CurrMin)*60000;//加分钟以后见
                ////}
                ////else
                ////{
                ////    this.timer_RequestInst.Interval = (5-CurrMin)*6000;//5分钟以后见
                ////}
                this.timer_RequestInst.Interval = (CurrMin % 5 < 3 ? 3 : 8 - CurrMin) * 60000 - 1000;//5分钟以后见,减掉1秒不断收敛时间,防止延迟接收
                //ToAdd:填充各内容
                this.txt_ExpectNo.Text = ic.Expect;
                this.txt_OpenTime.Text = ic.LastTime;
                this.txt_Insts.Text    = ic.getUserInsts(Program.gc);
                this.NewExpect         = CurrExpectNo;
                if (WebBrowserLoad)
                {
                    this.btn_Send_Click(null, null);
                }
            }
            else
            {
                if (CurrTime.Hour < 9)//如果在9点前
                {
                    //下一个时间点是9:08
                    DateTime TargetTime = DateTime.Today.AddHours(9).AddMinutes(8);
                    this.timer_RequestInst.Interval = TargetTime.Subtract(CurrTime).TotalMilliseconds;
                }
                else
                {
                    if (CurrTime.Subtract(LastInstsTime).Minutes > 7)//如果离上期时间超过7分钟,说明数据未接收到,那不要再频繁以10秒访问服务器
                    {
                        this.timer_RequestInst.Interval = 60 * 1000;
                    }
                    else //一般未接收到,10秒以后再试
                    {
                        this.timer_RequestInst.Interval = 10000;
                    }
                }
            }
            this.statusStrip1.Items[0].Text = string.Format("{0}秒后见", this.timer_RequestInst.Interval / 1000);
            //////ViewDataList = er.ReadNewestData(DateTime.Now.AddDays(-1));
            //////int CurrExpectNo = int.Parse(ViewDataList.LastData.Expect);
            //////if (CurrExpectNo > this.NewestExpectNo)
            //////{
            //////    this.timer_For_NewestData.Interval = 290000;//5分钟以后见
            //////    RefreshGrid();
            //////    RefreshNewestData();
            //////    this.NewestExpectNo = CurrExpectNo;
            //////}
            //////else
            //////{
            //////    this.timer_For_NewestData.Interval = 10000;//10秒后见
            //////}
        }
Beispiel #11
0
 public UnkownError(CommResult comres)
 {
     status      = comres.status;
     description = comres.data;
 }