public bool SaveOauthInfoAsync(OauthInfo info)
        {
            OathoQuery = new OathoQuery();
            try

            {
                var NotTel = OathoQuery.GetOathinfoNotTel(info.Telephone);

                foreach (var s in NotTel)
                {
                    OathoQuery.SetOathNotDefault(s);
                }
                OathoQuery.SaveOath0Info(info);
                //var ee= OathoQuery.IsExitItems();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }


            // throw new NotImplementedException();
        }
        public async Task <OauthInfo> RefreshAcessTokenAsync(OauthInfo Old)
        {
            //
            //403    refresh token 不存在(已经使用或者过期)
            //401 网络错误

            OauthInfos = new OauthInfo();
            var uri = new Uri(string.Format(Constants.RfreshTokenUrl));

            var para = string.Format("grant_type={0}&refresh_token={1}", Constants.GrantTypeRfreshToken, Old.RefreshToken);

            var content = new StringContent(para, Encoding.UTF8, "application/x-www-form-urlencoded");
            HttpResponseMessage response = null;

            try
            {
                response = await client.PostAsync(uri, content);

                var content22 = await response.Content.ReadAsStringAsync();

                //response.

                //从重定向网址上得到的报文;


                var AcessTokenInfo = JsonConvert.DeserializeObject <AcessTokenInfo>(content22);

                // var AcessTokenInfo = JsonConvert.DeserializeObject<AcessTokenInfo>(content22);


                if (AcessTokenInfo.access_token != null)
                {
                    OauthInfos.Telephone    = Old.Telephone;
                    OauthInfos.UserId       = Old.UserId;
                    OauthInfos.AcessToken   = AcessTokenInfo.access_token;
                    OauthInfos.RefreshToken = AcessTokenInfo.refresh_token;
                    OauthInfos.IsDefault    = true;
                }
                else
                {
                    // refresh token 不存在(已经使用或者过期)
                    OauthInfos.Telephone = "403";
                    return(OauthInfos);
                }



                //throw new NotImplementedException();
            }

            catch (Exception ex)
            {
                //401 网络错误
                Debug.WriteLine(@"				ERROR {0}", ex.Message);
                OauthInfos.Telephone = "401";
                return(OauthInfos);
            }

            return(OauthInfos);
        }
Exemple #3
0
        /// <summary>
        /// 获取第三方的用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public OauthInfo GetUser()
        {
            //string accessToken = GetAccessToken();

            List <UrlParameter> parameters = new List <UrlParameter>();
            UrlParameter        param      = new UrlParameter("access_token", access_token);

            parameters.Add(param);
            param = new UrlParameter("oauth_consumer_key", client_id);
            parameters.Add(param);
            param = new UrlParameter("openid", openID);
            parameters.Add(param);
            param = new UrlParameter("format", "json");
            parameters.Add(param);
            string  jsonData = OAuthRequest.Request(user_url, parameters, "GET");
            JObject json     = JObject.Parse(jsonData);

            OauthInfo oi = new OauthInfo();

            oi.NickName  = (string)json["nickname"];
            oi.Avatar    = (string)json["figureurl_2"];
            oi.AuthCode  = openID;
            oi.ChatBack  = code;
            oi.LoginType = LoginType.QQ;
            return(oi);
        }
Exemple #4
0
        //public int DeletOathinfo(string Tel)
        //{
        //    lock (locker)
        //    {

        //    }
        //}



        public int SaveOath0Info(OauthInfo OauthInfo)
        {
            //新插入返回1;
            //更新返回0;
            lock (locker)
            {
                int m = 0;
                //database.Insert(OauthInfo);
                var info = from s in database.Table <OauthInfo>()
                           where s.Telephone.StartsWith(OauthInfo.Telephone)
                           select s;


                foreach (var s in info)
                {
                    m = s.UserId;
                }
                OauthInfo.UserId = m;

                if (info.Count() == 0)
                {
                    database.Insert(OauthInfo);
                    return(1);
                }
                else
                {
                    database.Update(OauthInfo);
                    return(0);
                }
            }
        }
Exemple #5
0
        public async Task <IActionResult> CreateSmartApp(OauthInfo authInfo)
        {
            if (ModelState.IsValid == false)
            {
                return(View(authInfo));
            }

            var conn = new SmartThingsConnection();

            if (await conn.Login(authInfo.STUserId, authInfo.STPassword) == false)
            {
                ModelState.AddModelError("STPassword", "Could not connect to smart things using the supplied credentials");
                return(View("Index", authInfo));
            }

            var cs = new DeviceTypeRepository(conn, "j64 Alarm", $"{myEnv.WebRootPath}/../SmartThingApps/j64AlarmDevice.groovy");
            var ss = new DeviceTypeRepository(conn, "j64 Contact Zone", $"{myEnv.WebRootPath}/../SmartThingApps/j64ContactZoneDevice.groovy");
            var mz = new DeviceTypeRepository(conn, "j64 Motion Zone", $"{myEnv.WebRootPath}/../SmartThingApps/j64MotionZoneDevice.groovy");
            var pd = new DeviceTypeRepository(conn, "j64 Partition", $"{myEnv.WebRootPath}/../SmartThingApps/j64PartitionDevice.groovy");

            var jal = new SmartAppRepository(conn, "j64 Alarm", $"{myEnv.WebRootPath}/../SmartThingApps/j64AlarmSmartApp.groovy");

            // Save the client/secret keys
            var oauth = OauthRepository.Get();

            oauth.clientKey = jal.clientKey;
            oauth.secretKey = jal.secretKey;
            OauthRepository.Save(oauth);

            return(View("Index", oauth));
        }
Exemple #6
0
        /// <summary>
        /// status information to the smart things zone
        /// </summary>
        /// <param name="zoneInfo"></param>
        public static void UpdateZone(ZoneInfo zoneInfo)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();

                string url = authInfo.endpoints[0].uri + $"/UpdateZone";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();
                parms.Add(new KeyValuePair <string, string>("Id", zoneInfo.Id.ToString()));
                parms.Add(new KeyValuePair <string, string>("Status", zoneInfo.Status));
                parms.Add(new KeyValuePair <string, string>("Name", zoneInfo.Name));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error updating smart things zone {zoneInfo.Id} with status {zoneInfo.Status}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error updating smart things zone {zoneInfo.Id} with status {zoneInfo.Status}.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
        /// <summary>
        /// Install or Update Devices in the SmartThings App
        /// </summary>
        public static void InstallDevices(string hostString)
        {
            try
            {
                string[] h         = hostString.Split(':');
                string   j64Server = h[0];
                int      j64Port   = 80;
                if (h.Length > 1)
                {
                    j64Port = Convert.ToInt32(h[1]);
                }

                var hostName = System.Net.Dns.GetHostEntryAsync(System.Net.Dns.GetHostName());
                hostName.Wait();
                foreach (var i in hostName.Result.AddressList)
                {
                    if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        j64Server = i.ToString();
                        break;
                    }
                }

                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError("OAuth endpoints have not been created. Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/installDevices";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();
                parms.Add(new KeyValuePair <string, string>("j64Server", j64Server));
                parms.Add(new KeyValuePair <string, string>("j64Port", j64Port.ToString()));
                parms.Add(new KeyValuePair <string, string>("j64UserName", "admin"));
                parms.Add(new KeyValuePair <string, string>("j64Password", "Admin_01"));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error installing smart things devices.  StatusCode was {response.Result.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error installing smart things devices.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
        public static OauthInfo Save(OauthInfo oai)
        {
            using (StreamWriter file = System.IO.File.CreateText(RepositoryFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                serializer.Serialize(file, oai);
            }

            return(oai);
        }
Exemple #9
0
        /// <summary>
        /// Install or Update Devices in the SmartThings App
        /// </summary>
        public static void PrepTheInstall(j64HarmonyGateway j64Config)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();
                if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    return;
                }

                // create a new identifier for this app!
                j64Config.j64AppId = Guid.NewGuid().ToString();

                string url = authInfo.endpoints[0].uri + $"/prepInstall";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();
                parms.Add(new KeyValuePair <string, string>("j64AppId", j64Config.j64AppId));
                parms.Add(new KeyValuePair <string, string>("j64UserName", "admin"));
                parms.Add(new KeyValuePair <string, string>("j64Password", "Admin_01"));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.IsSuccessStatusCode)
                {
                    // Get the address of the local smart things hub
                    var     result = response.Result.Content.ReadAsStringAsync().Result;
                    JObject ipInfo = JObject.Parse(result);

                    j64Config.STHubAddress = (string)ipInfo["hubIP"];
                    j64Config.STHubPort    = Convert.ToInt32((string)ipInfo["hubPort"]);

                    if (j64Config.STHubAddress == "null")
                    {
                        j64Config.STHubAddress = null;
                        j64Config.STHubPort    = 0;
                    }
                    j64HarmonyGatewayRepository.Save(j64Config);
                }
            }
            catch (Exception)
            {
            }
        }
        public ActionResult BeginAuth([Bind("clientKey", "secretKey")] OauthInfo authInfo)
        {
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");

            // Reset the token info
            authInfo.accessToken      = null;
            authInfo.tokenType        = null;
            authInfo.expiresInSeconds = 0;

            OauthRepository.Save(authInfo);

            string Url = $"https://graph.api.smartthings.com/oauth/authorize?response_type=code&scope=app&redirect_uri={authorizedUrl}&client_id={authInfo.clientKey}";

            return(Redirect(Url));
        }
        private SmartThingsService GetSmartThingsService()
        {
            OauthInfo authInfo = OauthRepository.Get();

            if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
            {
                throw new Exception("OAuth endpoints have not been created. Cannot update smart things at this time");
            }
            string url   = authInfo.endpoints[0].uri;
            string token = authInfo.accessToken;

            SmartThingsService service = new SmartThingsService(token, url);

            return(service);
        }
Exemple #12
0
        public async Task <IActionResult> Devices()
        {
            OauthInfo authInfo = OauthRepository.Get();

            if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
            {
                throw new Exception("OAuth endpoints have not been created. Cannot update smart things at this time");
            }
            string url   = authInfo.endpoints[0].uri;
            string token = authInfo.accessToken;

            SmartThingsService service = new SmartThingsService(token, url);
            var devices = await service.ListDevices();

            return(View(devices));
        }
Exemple #13
0
        public int SetOathNotDefault(OauthInfo OauthInfo)
        {
            lock (locker)
            {
                OauthInfo.IsDefault = false;

                try
                {
                    database.Update(OauthInfo);
                    return(1);
                }
                catch (Exception ex)
                {
                    return(0);
                }
            }
        }
Exemple #14
0
        public static OauthInfo Get()
        {
            OauthInfo oai = null;

            if (File.Exists(RepositoryFile) == false)
            {
                return(new OauthInfo());
            }

            // Read the settings now
            using (StreamReader file = System.IO.File.OpenText(RepositoryFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                oai = (OauthInfo)serializer.Deserialize(file, typeof(OauthInfo));
            }

            return(oai);
        }
Exemple #15
0
        /// <summary>
        /// Install or Update Devices in the SmartThings App
        /// </summary>
        public static void InstallDevices(string hostString)
        {
            try
            {
                var alarm = AlarmSystemRepository.Get();
                if (string.IsNullOrEmpty(alarm.j64Server) || string.IsNullOrEmpty(alarm.j64Port))
                {
                    Determinej64ServerAddress(hostString);
                }

                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError("OAuth endpoints have not been created. Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/installDevices";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();
                parms.Add(new KeyValuePair <string, string>("j64Server", alarm.j64Server));
                parms.Add(new KeyValuePair <string, string>("j64Port", alarm.j64Port));
                parms.Add(new KeyValuePair <string, string>("j64UserName", "admin"));
                parms.Add(new KeyValuePair <string, string>("j64Password", "Admin_01"));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error installing smart things devices.  StatusCode was {response.Result.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error installing smart things devices.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Exemple #16
0
        /// <summary>
        /// status information to the smart things zone
        /// </summary>
        /// <param name="zoneInfo"></param>
        public static void UpdatePartition(PartitionInfo partitionInfo)
        {
            try
            {
                OauthInfo authInfo = OauthRepository.Get();

                if (authInfo == null || authInfo.endpoints == null || authInfo.endpoints.Count == 0)
                {
                    MyLogger.LogError($"OAuth endpoints have not been created.  Cannot update smart things at this time");
                    return;
                }
                string url = authInfo.endpoints[0].uri + $"/UpdatePartition";

                var client = new System.Net.Http.HttpClient();

                System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
                msg.Headers.Add("Authorization", $"Bearer {authInfo.accessToken}");

                List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();
                parms.Add(new KeyValuePair <string, string>("Id", partitionInfo.Id.ToString()));
                parms.Add(new KeyValuePair <string, string>("Name", partitionInfo.Name));
                parms.Add(new KeyValuePair <string, string>("ReadyToArm", partitionInfo.ReadyToArm.ToString()));
                parms.Add(new KeyValuePair <string, string>("IsArmed", partitionInfo.IsArmed.ToString()));
                parms.Add(new KeyValuePair <string, string>("ArmingMode", partitionInfo.ArmingMode));
                parms.Add(new KeyValuePair <string, string>("AlarmOn", partitionInfo.AlarmOn.ToString()));
                parms.Add(new KeyValuePair <string, string>("SHMIntegrationEnabled", partitionInfo.SHMIntegrationEnabled.ToString()));
                msg.Content = new System.Net.Http.FormUrlEncodedContent(parms);
                var response = client.SendAsync(msg);
                response.Wait();

                if (response.Result.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}");
                }
            }
            catch (Exception ex)
            {
                MyLogger.LogError($"Error updating smart things partition {partitionInfo.Id} with status {partitionInfo.ArmingMode}.  Exception was {MyLogger.ExMsg(ex)}");
            }
        }
Exemple #17
0
        /// <summary>
        /// 获取第三方的用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public OauthInfo GetUser()
        {
            //string accessToken = GetAccessToken();

            List <UrlParameter> parameters = new List <UrlParameter>();
            UrlParameter        param      = new UrlParameter("access_token", access_token);

            parameters.Add(param);
            param = new UrlParameter("uid", WechatAuthCode);
            parameters.Add(param);
            string  jsonData = OAuthRequest.Request(user_url, parameters, "GET");
            JObject json     = JObject.Parse(jsonData);

            OauthInfo oi = new OauthInfo();

            oi.NickName  = (string)json["screen_name"];
            oi.Avatar    = (string)json["avatar_large"];
            oi.AuthCode  = WechatAuthCode;
            oi.ChatBack  = code;
            oi.LoginType = LoginType.Sina微博;
            return(oi);
        }
Exemple #18
0
        /// <summary>
        /// 获取第三方的用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public OauthInfo GetUser()
        {
            //string accessToken = GetAccessToken();

            List <UrlParameter> parameters = new List <UrlParameter>();
            UrlParameter        param      = new UrlParameter("access_token", access_token);

            parameters.Add(param);
            param = new UrlParameter("openid", openid);
            parameters.Add(param);
            string  jsonData = OAuthRequest.Request(user_url, parameters, "GET");
            JObject json     = JObject.Parse(jsonData);

            OauthInfo oi = new OauthInfo();

            oi.NickName  = (string)json["nickname"];
            oi.Avatar    = (string)json["headimgurl"];
            oi.AuthCode  = openid;
            oi.ChatBack  = code;
            oi.LoginType = LoginType.微信;
            return(oi);
        }
        public IActionResult Authorized(string code)
        {
            OauthInfo oai = OauthRepository.Get();

            if (code == null)
            {
                return(View(oai));
            }

            oai.authCode = code;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            var url = "https://graph.api.smartthings.com/oauth/token";

            List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();

            parms.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
            parms.Add(new KeyValuePair <string, string>("code", oai.authCode));
            parms.Add(new KeyValuePair <string, string>("client_id", oai.clientKey));
            parms.Add(new KeyValuePair <string, string>("client_secret", oai.secretKey));
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");

            parms.Add(new KeyValuePair <string, string>("redirect_uri", authorizedUrl));

            var content  = new System.Net.Http.FormUrlEncodedContent(parms);
            var response = client.PostAsync(url, content);

            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get Auth Code Error: " + response.Result.StatusCode.ToString());
                return(View(oai));
            }

            // Save the interim result
            var val = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Result.Content.ReadAsStringAsync().Result);

            oai.accessToken      = val["access_token"];
            oai.expiresInSeconds = Convert.ToInt32(val["expires_in"]);
            oai.tokenType        = val["token_type"];
            OauthRepository.Save(oai);

            // Get the endpoint info
            client = new System.Net.Http.HttpClient();
            url    = "https://graph.api.smartthings.com/api/smartapps/endpoints";

            System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            msg.Headers.Add("Authorization", $"Bearer {oai.accessToken}");

            response = client.SendAsync(msg);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get EndPoints Error: " + response.Result.StatusCode.ToString());
                return(View(oai));
            }

            string jsonString = response.Result.Content.ReadAsStringAsync().Result;

            oai.endpoints = JsonConvert.DeserializeObject <List <OauthEndpoint> >(jsonString);

            OauthRepository.Save(oai);

            // Prepare the smart app to be called from the local traffic
            SmartThingsRepository.PrepTheInstall(j64Config);

            // Send all of the default devices to the smart app
            SmartThingsRepository.InstallDevices(j64Config, Request.Host.Value);

            // all done!
            return(View(oai));
        }
Exemple #20
0
        //400 账号、密码错误
        //401网络连接错误等
        //402authorization 超时
        public async Task <OauthInfo> GetAcessTokenAsync(string Telephone, string Password)
        {
            OauthInfos = new OauthInfo();
            //string Client_credentialsUrl = "http://123.206.29.130/oauth2/token.php";

            var uri = new Uri(string.Format(Constants.AuthorizationCodeUrl + "?response_type=" + Constants.ResponseType + "&client_id=" + Constants.ClientId + "&state=" + Constants.State + "&redirect_uri=" + Constants.RedirectUrl));


            //string  Telephone1="13240811453";
            //string  Password1="a2678015";
            string Autho = "授权";


            string para = string.Format("telephone={0}&password={1}&authorized={2}", Telephone, Password, Autho);

            // var content = new StringContent(para, Encoding.UTF8, "application/json");
            var content = new StringContent(para, Encoding.UTF8, "application/x-www-form-urlencoded");
            // var content = new StringContent(para, Encoding.UTF8, "multipart/form-data");
            HttpResponseMessage response = null;

            try
            {
                response = await client.PostAsync(uri, content);

                var content11 = await response.Content.ReadAsStringAsync();

                //response.

                //从重定向网址上得到的报文;
                var Authorizationcode = JsonConvert.DeserializeObject <AuthorizationJson>(content11);
                if (Authorizationcode.code == "200")
                {//正确获得Authozrizationcode
                    var uri2 = new Uri(string.Format(Constants.AcessTokenUrl));

                    var para2 = string.Format("grant_type={0}&code={1}&redirect_uri={2}", Constants.GrantTypeAuthorizationCode, Authorizationcode.authorizationcode, Constants.RedirectUrl);

                    var content2 = new StringContent(para2, Encoding.UTF8, "application/x-www-form-urlencoded");
                    HttpResponseMessage response2 = null;
                    try
                    {
                        response2 = await client.PostAsync(uri2, content2);

                        var content22 = await response2.Content.ReadAsStringAsync();

                        //response.

                        //从重定向网址上得到的报文;
                        try
                        {
                            var AcessTokenInfo = JsonConvert.DeserializeObject <AcessTokenInfo>(content22);
                            OauthInfos.Telephone    = Telephone;
                            OauthInfos.AcessToken   = AcessTokenInfo.access_token;
                            OauthInfos.RefreshToken = AcessTokenInfo.refresh_token;
                            OauthInfos.IsDefault    = true;
                            //  return OauthInfos;
                        }
                        catch (Exception ex)
                        {
                            //402 authorization 超时
                            Debug.WriteLine(@"				ERROR {0}", ex.Message);
                            var AcessErrorInfo = JsonConvert.DeserializeObject <AcessErrorInfo>(content22);
                            OauthInfos.Telephone = "402";
                            return(OauthInfos);
                        }
                    }
                    catch (Exception ex)
                    {
                        //网络连接错误等
                        Debug.WriteLine(@"				ERROR {0}", ex.Message);
                        OauthInfos.Telephone = "401";
                        return(OauthInfos);
                    }
                }
                else if (Authorizationcode.code == "201")
                {
                    //账号、密码错误
                    Debug.WriteLine(@"				ERROR {0}", Authorizationcode.error);
                    OauthInfos.Telephone = "400";
                    return(OauthInfos);
                }
            }
            catch (Exception ex)
            {
                //网络连接错误等
                Debug.WriteLine(@"				ERROR {0}", ex.Message);
                OauthInfos.Telephone = "401";
                return(OauthInfos);
            }



            return(OauthInfos);
            // throw new NotImplementedException();
        }
Exemple #21
0
        /// <summary>
        /// Install or Update Devices in the SmartThings App
        /// </summary>
        public static void InstallDevices(j64HarmonyGateway j64Config, string host)
        {
            OauthInfo authInfo = OauthRepository.Get();

            // We can't sync if the IP has not yet been set
            if (String.IsNullOrEmpty(j64Config.STHubAddress) || j64Config.STHubAddress.Contains("TBD"))
            {
                return;
            }

            // Set the IP address of this server if it has not been set yet
            if (String.IsNullOrEmpty(j64Config.j64Address) || j64Config.j64Address.Contains("TBD"))
            {
                SmartThingsRepository.Determinej64Address(host, j64Config);
            }

            var url    = $"http://{j64Config.STHubAddress}:{j64Config.STHubPort}";
            var client = new System.Net.Http.HttpClient();

            System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);

            List <j64Device> l = new List <j64Device>();

            l.Add(new j64Device()
            {
                Name = j64Config.SoundDeviceName, DeviceValue = null, DeviceType = j64DeviceType.Volume
            });
            l.Add(new j64Device()
            {
                Name = j64Config.ChannelSurfDeviceName, DeviceValue = null, DeviceType = j64DeviceType.Surfing
            });
            l.Add(new j64Device()
            {
                Name = j64Config.VcrPauseDeviceName, DeviceValue = "pause", DeviceType = j64DeviceType.VCR
            });

            foreach (var fc in j64Config.FavoriteChannels)
            {
                l.Add(new j64Device()
                {
                    Name = fc.Name, DeviceValue = fc.Channel.ToString(), DeviceType = j64DeviceType.Channel
                });
            }
            l.Add(new j64Device()
            {
                Name = j64Config.LastChannelDeviceName, DeviceValue = "previous", DeviceType = j64DeviceType.Channel
            });

            foreach (var cc in j64Config.CustomCommands)
            {
                l.Add(new j64Device()
                {
                    Name = cc.CommandName, DeviceValue = cc.CommandName, DeviceType = j64DeviceType.CustomCommand
                });
            }

            var request = new MyRequest <List <j64Device> >()
            {
                j64Ip    = j64Config.j64Address,
                j64Port  = j64Config.j64Port,
                j64AppId = j64Config.j64AppId,
                Route    = "/installAllDevices",
                Payload  = l
            };

            string json = JsonConvert.SerializeObject(request, Formatting.None);

            msg.Content = new System.Net.Http.StringContent(json);
            msg.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            try
            {
                var response = client.SendAsync(msg);

                response.Wait();

                if (response.Result.IsSuccessStatusCode)
                {
                    var result = response.Result.Content.ReadAsStringAsync();
                }
            }
            catch (Exception)
            {
                // TODO: display an appropriate error message!
            }
        }