示例#1
0
        /// <summary>
        /// gets the IP of the local bridge, currently one bridge is supported
        /// </summary>
        /// <returns></returns>
        public static string getIP()
        {
            try
            {
                var getBridge = new HttpsClient();
                getBridge.KeepAlive        = false;
                getBridge.Accept           = "application/json";
                getBridge.HostVerification = false;
                getBridge.PeerVerification = false;
                HttpsClientRequest bridgeRequest = new HttpsClientRequest();
                bridgeRequest.Url.Parse("https://www.meethue.com/api/nupnp");
                HttpsClientResponse lResponse = getBridge.Dispatch(bridgeRequest);
                String jsontext = lResponse.ContentString;

                /*
                 * [{"id":"001788fffe2ad33b","internalipaddress":"172.22.131.242"}]
                 */
                JArray BridgeArray = JArray.Parse(jsontext);
                BridgeIp = (String)BridgeArray[0].SelectToken("internalipaddress");
                //BridgeApi = "U8FEH-CRuHFGxXe59pitg6UeyqGKWnMsqHef8oMt";
                CrestronConsole.PrintLine("Get IP of Bridge complete...");
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Exception is {0}", e);
            }
            return(BridgeIp);
        }
示例#2
0
        private HttpsResult SendRequest(string url, RequestType requestType, IEnumerable <KeyValuePair <string, string> > additionalHeaders, string value)
        {
            using (_requestLock.AquireLock())
            {
                HttpsClientRequest httpRequest = CreateDefaultClientRequest(url, requestType);

                if (additionalHeaders != null)
                {
                    foreach (var item in additionalHeaders)
                    {
                        httpRequest.Header.AddHeader(new HttpsHeader(item.Key, item.Value));
                    }
                }

                if (!string.IsNullOrEmpty(value))
                {
                    httpRequest.ContentString = value;
                }

                try
                {
                    HttpsClientResponse httpResponse = _httpsClient.Value.Dispatch(httpRequest);
                    return(new HttpsResult(httpResponse.Code, httpResponse.ResponseUrl, httpResponse.ContentString));
                }
                catch (HttpsException ex)
                {
                    Debug.LogException(GetType(), ex);
                }

                return(null);
            }
        }
示例#3
0
        //Todo:Check if we can pass the returned object type and deserialze.
        private static HttpsClientResponse StaticDeviceRequest(string uri, RequestType requestType, string data, string contentType, string accessKey)
        {
            HttpsClient client = new HttpsClient();

            client.HostVerification = false;
            client.PeerVerification = false;

            HttpsClientRequest aRequest = new HttpsClientRequest();

            aRequest.Url.Parse(uri);
            aRequest.Encoding           = Encoding.UTF8;
            aRequest.RequestType        = requestType;
            aRequest.Header.ContentType = contentType;

            //Content cannot be null
            aRequest.ContentString = (data != null) ? data : "";

            if (accessKey != null)
            {
                aRequest.Header.SetHeaderValue("Authorization", accessKey);
            }

            HttpsClientResponse res = client.Dispatch(aRequest);

            if (res.Code == 401)
            {
                throw new DeviceNotAuthorizedException("Device not authorized");
            }

            return(res);
        }
示例#4
0
        private static void GetToken()
        {
            try
            {
                if (Username.Length > 0 && Password.Length > 0)
                {
                    using (HttpsClient client = new HttpsClient())
                    {
                        client.TimeoutEnabled    = true;
                        client.Timeout           = 10;
                        client.HostVerification  = false;
                        client.PeerVerification  = false;
                        client.AllowAutoRedirect = false;
                        client.IncludeHeaders    = false;

                        HttpsClientRequest request = new HttpsClientRequest();

                        request.Url.Parse("https://wap.tplinkcloud.com");
                        request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                        request.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));

                        request.ContentString = "{\"method\":\"login\",\"params\":{\"appType\":\"Crestron\",\"cloudUserName\":\"" + Username + "\",\"cloudPassword\":\"" + Password + "\",\"terminalUUID\":\"3df98660-6155-4a7d-bc70-8622d41c767e\"}}";

                        HttpsClientResponse response = client.Dispatch(request);

                        if (response.ContentString != null)
                        {
                            if (response.ContentString.Length > 0)
                            {
                                JObject body = JObject.Parse(response.ContentString);

                                if (body["result"] != null)
                                {
                                    if (body["result"]["token"] != null)
                                    {
                                        Token = body["result"]["token"].ToString().Replace("\"", string.Empty);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new ArgumentException("Username and Password cannot be emtpy");
                }
            }
            catch (SocketException se)
            {
                ErrorLog.Exception("SocketException occured in System.GetToken - ", se);
            }
            catch (HttpsException he)
            {
                ErrorLog.Exception("HttpsException occured in System.GetToken - ", he);
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Exception occured in System.GetToken - ", e);
            }
        }
示例#5
0
        internal static string HttpsJsonRequest(string uri, Crestron.SimplSharp.Net.Https.RequestType requestType, string key, string msg, string contentType)
        {
            HttpsClient client = new HttpsClient();

            client.HostVerification = false;
            client.PeerVerification = false;

            try
            {
                HttpsClientRequest aRequest = new HttpsClientRequest();
                //HttpsClientRequest aRequest = new HttpsClientRequest();

                string aUrl = uri;
                aRequest.Url.Parse(aUrl);
                aRequest.Encoding           = Encoding.UTF8;
                aRequest.RequestType        = requestType;
                aRequest.Header.ContentType = contentType;
                aRequest.ContentString      = msg;
                aRequest.Header.SetHeaderValue("Authorization", key);

                HttpsClientResponse myResponse = client.Dispatch(aRequest);

                return(myResponse.ContentString);
            }

            catch (Exception ex)
            {
                LogException(@"SyncProMethods \ GenericHttpsRequest", ex);
                return(null);
            }
        }
示例#6
0
        /// <summary>
        /// Registers the device with the server.
        /// </summary>
        /// <param name="mac">Device's Mac address</param>
        /// <param name="sn">Device's Serial Number</param>
        /// <param name="model">Device's Model. Note that the model must be first created in the partner.syncpro.io portal</param>
        /// <param name="fwVersion">Device's FW version</param>
        /// <param name="partnerId">PartnerID - claim your at [email protected]</param>
        /// <returns>
        /// Returns the devices uuid and accessKey, which should be saved locally and used for every future API call.
        /// If fails, returns null.
        /// </returns>
        public static RegisterDeviceResponse RegisterDevice(string partnerId, string mac, string sn, string model, string fwVersion)
        {
            //First, assemble device registration data
            RegistrationData deviceRegData = new RegistrationData(mac, sn, model, fwVersion, partnerId);

            //Send registration request with device registration data as string
            HttpsClientResponse res = WebMethods.RegisterDevice(deviceRegData);

            if (res.Code == 422)
            {
                //Device is already registers
                throw new DeviceAlreadyRegisteredException("Error 422: Device is already registered");
            }
            if (res.Code == 404)
            {
                //Could not find supported device
                throw new DeviceModelNotFoundException("Error 404: Could not find supported device");
            }

            if (res.Code != 201)
            {
                Logging.Notice(@"SyncProApi \ RegisterDevice", res.Code.ToString() + ":" + res.ContentString);
                //Todo: Throw exception - Device already registered.
                return(null);
            }
            return(JsonConvert.DeserializeObject <RegisterDeviceResponse>(res.ContentString));
        }
示例#7
0
        internal CodecResponse(CodecRequest request, HttpsClientResponse response)
        {
            _request  = request;
            _response = response;

            if (_response.ContentLength == 0)
            {
                return;
            }

            try
            {
#if DEBUG
                Debug.WriteNormal(Debug.AnsiBlue + _xml + Debug.AnsiReset);
#endif
                if (response.Code == 200)
                {
                    var reader = new XmlReader(response.ContentString);
                    _xml = XDocument.Load(reader);
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error parsing xml document from codec");
            }
        }
示例#8
0
        //Use authorization code to retrieve a refresh token and a session token
        private void GetTokenAndRefreshToken()
        {
            try
            {
                using (HttpsClient client = new HttpsClient())
                {
                    client.TimeoutEnabled    = true;
                    client.Timeout           = 10;
                    client.HostVerification  = false;
                    client.PeerVerification  = false;
                    client.AllowAutoRedirect = false;
                    client.IncludeHeaders    = false;

                    HttpsClientRequest request = new HttpsClientRequest();

                    request.Url.Parse("https://www.googleapis.com/oauth2/v4/token?client_id=" + ClientID + "&code=" + AuthCode + "&grant_type=authorization_code&redirect_uri=https://www.google.com&client_secret=" + ClientSecret);
                    request.RequestType = RequestType.Post;

                    HttpsClientResponse response = client.Dispatch(request);

                    if (response.ContentString != null)
                    {
                        if (response.ContentString.Length > 0)
                        {
                            JObject body = JObject.Parse(response.ContentString);

                            if (body["expires_in"] != null)
                            {
                                var seconds      = Convert.ToInt16(body["expires_in"].ToString().Replace("\"", string.Empty)) - 10;
                                var milliseconds = seconds * 1000;

                                refreshTimer = new CTimer(UseRefreshToken, milliseconds);
                            }
                            if (body["access_token"] != null)
                            {
                                Token = body["access_token"].ToString().Replace("\"", string.Empty);
                            }
                            if (body["token_type"] != null)
                            {
                                TokenType = body["token_type"].ToString().Replace("\"", string.Empty);
                            }
                            if (body["refresh_token"] != null)
                            {
                                refreshToken = body["refresh_token"].ToString().Replace("\"", string.Empty);

                                using (StreamWriter writer = new StreamWriter(File.Create(refreshTokenFilePath + refreshTokenFileName)))
                                {
                                    writer.WriteLine(refreshToken);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Exception ocurred in GetTokenAndRefreshToken", e);
            }
        }
示例#9
0
		public string Request(string url, string cmd)
		{
			_request.Url.Parse(url);
			if (cmd != null)
				_request.ContentString = cmd;
			_response = _client.Dispatch(_request);
			String jsontext = _response.ContentString;
			return jsontext;
		}
 //Handle client responses
 public void OnHttpsClientResponseCallback(HttpsClientResponse response, HTTPS_CALLBACK_ERROR error)
 {
     if (debug > 0)
     {
         CrestronConsole.PrintLine("\nhttps OnHTTPClientResponseCallback: " + response.ContentString);
         if (error > 0)
         {
             CrestronConsole.PrintLine("http error:\n" + error);
         }
     }
 }
示例#11
0
        /// <summary>
        /// Sends telemetry to the server. The obj must follow the guidelines as described in the API documentaion.
        /// </summary>
        /// <param name="deviceUuid">Device's unique ID</param>
        /// <param name="deviceAccessKey">Device's Access Key</param>
        /// <param name="obj">Telemetry object. Must follow API guidelines</param>
        /// <returns>Telemetry response per the API documentation or null in case of an error</returns>
        public TelemetryResponse SendTelemetry(Object obj)
        {
            HttpsClientResponse res = _webMethods.JsonPost("telemetry", obj);

            if (res.Code != 201 && res.Code != 200)
            {
                Logging.Notice(@"SyncProApi \ SendTelemetry", res.Code.ToString() + ":" + res.ContentString);
                return(null);
            }
            return(JsonConvert.DeserializeObject <TelemetryResponse>(res.ContentString));
        }
示例#12
0
        /// <summary>
        /// Adds more data to a current dump
        /// </summary>
        /// <param name="deviceUuid">Device's unique ID</param>
        /// <param name="deviceAccessKey">Device's Access Key</param>
        /// <param name="dump">Dump's content</param>
        /// <param name="dumpId">Dump's ID to append data to</param>
        /// <returns>the dump new total length or null in case of an error</returns>
        public SendDumpResponse UpdateDump(string dump, string dumpId)
        {
            HttpsClientResponse res = _webMethods.TextPost("dumps/" + dumpId, dump);

            if (res.Code != 200)
            {
                Logging.Notice(@"SyncProApi \ UpdateDump", res.Code.ToString() + ":" + res.ContentString);
                return(null);
            }
            return(JsonConvert.DeserializeObject <SendDumpResponse>(res.ContentString));
        }
示例#13
0
        /// <summary>
        /// Update server on command processing. Must be sent after getting a command.
        /// </summary>
        /// <param name="deviceUuid">Device's unique ID</param>
        /// <param name="deviceAccessKey">Device's Access Key</param>
        /// <returns>HTTP return code or null in case of an exception</returns>
        public int?UpdateCommand(SharedObjects.UpdateCommandRequets cmdStatus)
        {
            HttpsClientResponse res = _webMethods.JsonPost("command", cmdStatus);

            if (res.Code != 200)
            {
                Logging.Notice(@"SyncProApi \ UpdateCommand", res.Code.ToString() + ":" + res.ContentString);
                return(null);
            }
            return(200);
        }
示例#14
0
        /// <summary>
        /// Get awaiting commands on the server.
        /// </summary>
        /// <param name="deviceUuid">Device's unique ID</param>
        /// <param name="deviceAccessKey">Device's Access Key</param>
        /// <returns>Waiting command and its parameters, or null in case of an error</returns>
        public GetCommandResponse GetCommand()
        {
            HttpsClientResponse res = _webMethods.JsonGet("command");

            if (res.Code != 200)
            {
                Logging.Notice(@"SyncProApi \ GetCommand", res.Code.ToString() + ":" + res.ContentString);
                return(null);
            }
            return(JsonConvert.DeserializeObject <GetCommandResponse>(res.ContentString));
        }
示例#15
0
        /// <summary>
        /// This methods get the device's configurations from the cloud, or null in case of an error.
        /// </summary>
        /// <param name="deviceUuid">Device's unique ID</param>
        /// <param name="deviceAccessKey">Device's Access Key</param>
        /// <returns>a String representing the device's configurations</returns>
        public String GetDeviceConfig()
        {
            HttpsClientResponse res = _webMethods.JsonGet("config");

            if (res.Code != 200)
            {
                Logging.Notice(@"SyncProApi \ GetDeviceConfig", res.Code.ToString() + ":" + res.ContentString);
                return(null);
            }
            return(res.ContentString);
        }
示例#16
0
 private int ProwlDispatch(ProwlRequest request)
 {
     try
     {
         HttpsClientResponse response = Dispatch(request);
         return(response.Code);
     }
     catch (HttpsException)
     {
         return(0);
     }
 }
示例#17
0
 private int ProwlDispatch(ProwlRequest request)
 {
     try
     {
         HttpsClientResponse response = Dispatch(request);
         return(response.Code);
     }
     catch (HttpsException e)
     {
         ErrorLog.Exception("Got exception dispatching Prowl request", e);
         return(0);
     }
 }
        //Get all devices
        public void GetDevices()
        {
            try
            {
                using (HttpsClient client = new HttpsClient())
                {
                    client.TimeoutEnabled    = true;
                    client.Timeout           = 10;
                    client.HostVerification  = false;
                    client.PeerVerification  = false;
                    client.AllowAutoRedirect = false;
                    client.IncludeHeaders    = false;

                    HttpsClientRequest request = new HttpsClientRequest();

                    request.Url.Parse("https://smartdevicemanagement.googleapis.com/v1/enterprises/" + ProjectID + "/devices");
                    request.RequestType        = RequestType.Get;
                    request.Header.ContentType = "application/json";
                    request.Header.AddHeader(new HttpsHeader("Authorization", string.Format("{0} {1}", TokenType, Token)));

                    HttpsClientResponse response = client.Dispatch(request);

                    //  CrestronConsole.PrintLine("Get Devices ************ " + response.ContentString);

                    if (response.ContentString != null)
                    {
                        if (response.ContentString.Length > 0)
                        {
                            JObject body = JObject.Parse(response.ContentString);

                            if (body["error"] != null)
                            {
                                onErrorMessage(body["error"]["message"].ToString().Replace("\"", string.Empty));
                            }

                            foreach (var dev in body["devices"])
                            {
                                if (devices.ContainsKey(dev["traits"]["sdm.devices.traits.Info"]["customName"].ToString().Replace("\"", string.Empty)))
                                {
                                    devices[dev["traits"]["sdm.devices.traits.Info"]["customName"].ToString().Replace("\"", string.Empty)].ParseData(dev);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Exception ocurred in GetDevices", e);
            }
        }
        /// <summary>
        /// Attempt to refresh the access token, return a boolean indicating success (true)/failure (false), and
        /// include the response code and body from the Authorization Server in the event of failure
        /// </summary>
        /// <param name="errMsg"></param>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        bool RefreshAccessToken(out string errMsg, out int statusCode)
        {
            using (var client = new HttpsClient())
            {
                CrestronConsole.PrintLine("Attempting to refresh Access Token...");
                HttpsClientRequest req = new HttpsClientRequest();
                req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                req.Url         = new UrlParser(TokenEndpoint);
                HttpsHeaders headers = new HttpsHeaders();
                // Auth0's token endpoint expects all the necessary information to be
                // placed in the entity-body of the request
                headers.SetHeaderValue("Content-Type", "application/x-www-form-urlencoded");
                req.ContentString = BuildQueryString(
                    new NameValueCollection
                {
                    { "grant_type", "refresh_token" },
                    { "client_id", ClientID },
                    { "client_secret", ClientSecret },
                    { "refresh_token", RefreshToken }
                });

                // Always set the Content-Length of your POST request to indicate the length of the body,
                // or else the Content-Length will be set to 0 by default!
                headers.SetHeaderValue("Content-Length", req.ContentString.Length.ToString());
                req.Header = headers;

                // Send the POST request to the token endpoint and wait for a response...
                HttpsClientResponse tokenResponse = client.Dispatch(req);
                if (tokenResponse.Code >= 200 && tokenResponse.Code < 300)
                {
                    // Parse JSON response and securely store the token
                    JObject resBody = JsonConvert.DeserializeObject <JObject>(tokenResponse.ContentString);
                    accessToken = (string)resBody["access_token"];
                    CrestronConsole.PrintLine("Received a new \"{0}\" Access Token. It expires in {1} hours",
                                              (string)resBody["token_type"],
                                              (int)resBody["expires_in"] / 60.0 / 60.0);
                    // Client is now authorized to access the protected resource again
                    hasAccessToken = true;
                    errMsg         = "";
                    statusCode     = tokenResponse.Code;
                    return(true);
                }
                else
                {
                    CrestronConsole.PrintLine("Refresh Failed");
                    errMsg     = tokenResponse.ContentString;
                    statusCode = tokenResponse.Code;
                    return(false);
                }
            }
        }
示例#20
0
        //Get device info
        public void GetDevice()
        {
            // CrestronConsole.PrintLine("Device ID is: " + DeviceID);

            if (DeviceID.Length > 0)
            {
                try
                {
                    using (HttpsClient client = new HttpsClient())
                    {
                        client.TimeoutEnabled    = true;
                        client.Timeout           = 10;
                        client.HostVerification  = false;
                        client.PeerVerification  = false;
                        client.AllowAutoRedirect = false;
                        client.IncludeHeaders    = false;

                        HttpsClientRequest request = new HttpsClientRequest();

                        request.Url.Parse("https://smartdevicemanagement.googleapis.com/v1/" + DeviceID);
                        request.RequestType        = RequestType.Get;
                        request.Header.ContentType = "application/json";
                        request.Header.AddHeader(new HttpsHeader("Authorization", string.Format("{0} {1}", GoogleNestCloud.TokenType, GoogleNestCloud.Token)));

                        HttpsClientResponse response = client.Dispatch(request);

                        // CrestronConsole.PrintLine("GET DEVICE INFO****************** " + response.ContentString);

                        if (response.ContentString != null)
                        {
                            if (response.ContentString.Length > 0)
                            {
                                JToken body = JToken.Parse(response.ContentString);
                                ParseData(body);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    ErrorLog.Exception("Exception ocurred in GetDevice", e);
                }
            }
            else
            {
                if (onErrorMsg != null)
                {
                    onErrorMsg("Device not found, ensure the Label field is set in the app");
                }
            }
        }
示例#21
0
        protected virtual string GetApiResponse()
        {
            Client = HttpsClientFactory.NewClient();
            int    responseCode;
            string responseString;

            try
            {
                if (Request == null)
                {
                    Request = GetClientRequest();
                }
            }
            catch (Exception ex)
            {
                CrestronConsole.PrintLine("SimplTeslaMaster.Results.BaseResult.GetApiResponse()::Failed to get client request " + ex.ToString());
            }

            Request.Url.Parse(ApiUrl);

            Client.Url = Request.Url;

            try
            {
                Request.FinalizeHeader();
            }
            catch (Exception ex)
            {
                CrestronConsole.PrintLine("SimplTeslaMaster.Results.BaseResult.GetApiResponse()::Failed to finalize header " + ex.ToString());
            }


            Response = Client.Dispatch(Request);

            responseCode   = Response.Code;
            responseString = Response.ContentString;

            if (responseCode != 200)
            {
                CrestronConsole.PrintLine("SimplTeslaMaster.Results.BaseResult.GetApiResponse()::Request was not successful!");
                CrestronConsole.PrintLine("SimplTeslaMaster.Results.BaseResult>GetApiResponse()::Response code: " + responseCode.ToString());
                CrestronConsole.PrintLine("SimplTeslaMaster.Results.BaseResult>GetApiResponse()::Response content: " + responseString);
            }

            Request = null;
            Client.Dispose();
            Client = null;

            return(Response.ContentString);
        }
        private HttpsResult SendRequest(string url, RequestType requestType, IEnumerable <KeyValuePair <string, string> > additionalHeaders, string content)
        {
            var obj    = _httpsClientPool.GetFromPool();
            var client = obj.Value;

            try
            {
                Debug.WriteInfo("Making API GET request to endpoint: {0}", url);

                if (client.ProcessBusy)
                {
                    client.Abort();
                }

                var httpsRequest = new HttpsClientRequest {
                    RequestType = requestType,
                    Encoding    = Encoding.UTF8,
                    KeepAlive   = false,
                };

                if (requestType != RequestType.Get && !string.IsNullOrEmpty(content))
                {
                    httpsRequest.ContentSource = ContentSource.ContentString;
                    httpsRequest.ContentString = content;
                }

                if (additionalHeaders != null)
                {
                    foreach (var item in additionalHeaders)
                    {
                        httpsRequest.Header.AddHeader(new HttpsHeader(item.Key, item.Value));
                    }
                }

                httpsRequest.Url.Parse(url);

                HttpsClientResponse httpResponse = client.Dispatch(httpsRequest);
                return(new HttpsResult(httpResponse.Code, httpResponse.ResponseUrl, httpResponse.ContentString));
            }
            catch (Exception ex)
            {
                Debug.WriteException(ex);
            }
            finally
            {
                _httpsClientPool.AddToPool(obj);
            }

            return(null);
        }
示例#23
0
        //Use refresh token to request a session token
        private void UseRefreshToken(object o)
        {
            try
            {
                using (HttpsClient client = new HttpsClient())
                {
                    client.TimeoutEnabled    = true;
                    client.Timeout           = 10;
                    client.HostVerification  = false;
                    client.PeerVerification  = false;
                    client.AllowAutoRedirect = false;

                    HttpsClientRequest request = new HttpsClientRequest();

                    request.Url.Parse("https://www.googleapis.com/oauth2/v4/token?client_id=" + ClientID + "&refresh_token=" + refreshToken + "&grant_type=refresh_token&redirect_uri=https://www.google.com&client_secret=" + ClientSecret);
                    request.RequestType = RequestType.Post;

                    HttpsClientResponse response = client.Dispatch(request);

                    if (response.ContentString != null)
                    {
                        if (response.ContentString.Length > 0)
                        {
                            JObject body = JObject.Parse(response.ContentString);

                            if (body["expires_in"] != null)
                            {
                                var seconds      = Convert.ToInt16(body["expires_in"].ToString().Replace("\"", string.Empty)) - 10;
                                var milliseconds = seconds * 1000;

                                refreshTimer = new CTimer(UseRefreshToken, milliseconds);
                            }
                            if (body["access_token"] != null)
                            {
                                Token = body["access_token"].ToString().Replace("\"", string.Empty);
                            }
                            if (body["token_type"] != null)
                            {
                                TokenType = body["token_type"].ToString().Replace("\"", string.Empty);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DebugLogic.Log(">>> ERROR: Exception ocurred in UseRefreshToken" + e, DebugLogic.ErrorLevel.Error, true);
            }
        }
示例#24
0
        /*This Method will set the LIGHT at _id to any level between 0-65535 in 100 miliseconds
         * _id can be found in the _Devices print out. These IDs can be parsed out with this Library but
         * an example is not provided*/
        public void LightsExample(ushort _id, ushort level)
        {
            string _Post = "{\"lights\": [ { \"" + _id + "\": 01 , \"level\": " + level +
                           ", \"time\": 100}]}";

            CrestronConsole.PrintLine(_Post);
            MyHttpsClientRequest LightRequest = new MyHttpsClientRequest(URL, Path, AuthHeader, sAuthKey);

            LightRequest.RequestType   = RequestType.Post;
            LightRequest.ContentString = _Post;
            try
            {
                HttpsClientResponse PostResponse = MyClient.Dispatch(LightRequest);
            }
            catch (HttpsException e)
            {
                CrestronConsole.PrintLine("Post error: {0}\n", e.Message);
            }
        }
示例#25
0
        /// <summary>
        /// Retrieves a token from Tesla's authorization API
        /// </summary>
        public static Token GetToken()
        {
            HttpsClient         client;
            HttpsClientRequest  request;
            HttpsClientResponse response = null;
            Token result = null;

            // Create a new web client
            client = HttpsClientFactory.NewClient();

            // Create the reqeuest object
            request = GetRequest();

            // Set the URL to communicate with
            client.Url = request.Url;

            // Finalize the HTTP request header that was geerated in GetRequest()
            request.FinalizeHeader();


            try
            {
                // Send the request to Tesla's server
                response = client.Dispatch(request);

                // Covert Tesla's respose to a Token object by deserializing the JSON response
                result = (Token)JsonConvert.DeserializeObject(response.ContentString, typeof(Token));
            }
            catch (Exception ex)
            {
                // If there's a error, make note of it in the Crestron console.  This will appear both in the Toolbox's log, and in the SSH/Command line if logged in
                CrestronConsole.PrintLine("SimplTeslaCar.Tokens.TokenGenerator.GetToken()::Error in Tesla API (TokenGenerator.GetToken): Unable to get response. " + ex.ToString());
                ErrorLog.Exception("SimplTeslaCar.Tokens.TokenGenerator.GetToken()::Error in Tesla API (TokenGenerator.GetToken): Unable to get response.", ex);
            }

            // Clear the objects that were used from memory
            request = null;
            client.Dispose();
            client = null;

            return(result);
        }
示例#26
0
        //Post HTTPS command
        internal string PostCommand(string body)
        {
            try
            {
                if (DeviceID.Length > 0)
                {
                    using (HttpsClient client = new HttpsClient())
                    {
                        client.TimeoutEnabled    = true;
                        client.Timeout           = 10;
                        client.HostVerification  = false;
                        client.PeerVerification  = false;
                        client.AllowAutoRedirect = false;
                        client.IncludeHeaders    = false;

                        HttpsClientRequest request = new HttpsClientRequest();

                        request.Url.Parse("https://smartdevicemanagement.googleapis.com/v1/" + DeviceID + ":executeCommand");
                        request.RequestType        = RequestType.Post;
                        request.Header.ContentType = "application/json";
                        request.Header.AddHeader(new HttpsHeader("Authorization", string.Format("{0} {1}", GoogleNestCloud.TokenType, GoogleNestCloud.Token)));

                        request.ContentString = body;

                        HttpsClientResponse response = client.Dispatch(request);

                        return(response.ContentString);
                    }
                }
                else
                {
                    return(string.Empty);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Exception ocurred in PostCommand", e);
                return(string.Empty);
            }
        }
示例#27
0
        /// <summary>
        /// Sets the device's configuration to the server.
        /// </summary>
        /// <param name="deviceUuid">Device's unique ID</param>
        /// <param name="deviceAccessKey">Device's Access Key</param>
        /// <param name="obj">The device's configuration object. Must follow the device's schema</param>
        /// <returns>Server's configuration version on success or null on failure</returns>
        public int?SetDeviceConfig(DeviceConfig obj)
        {
            HttpsClientResponse res = _webMethods.JsonPost("config", obj);

            if (res.Code == 422)
            {
                //Reported config version is older than the one on the server
                throw new ConfigVersionIsOlderThanServersVersion("Error 422: Reported configuration is older than server's version");
            }

            if (res.Code == 401)
            {
                throw new DeviceNotAuthorizedException("ErrorLog 401: Device is not authorized");
            }

            if (res.Code != 200)
            {
                Logging.Notice(@"SyncProApi \ SetDeviceConfig", res.Code.ToString() + ":" + res.ContentString);
                return(null);
            }
            return((JsonConvert.DeserializeObject <SetConfigResponse>(res.ContentString)).version);
        }
示例#28
0
        /// <summary>
        /// Requests an authorization token from the Tesla servers
        /// </summary>
        public static Token GetToken()
        {
            HttpsClient         client;
            HttpsClientRequest  request;
            HttpsClientResponse response = null;
            Token result = null;

            client = HttpsClientFactory.NewClient();

            // Create the Client request
            request = GetRequest();

            // Set the client's endpoint and finalize the HTTP header
            client.Url = request.Url;
            request.FinalizeHeader();

            try
            {
                // Send the request to Tesla's server, and get the response back
                response = client.Dispatch(request);

                // Convert the JSON to a token object
                result = (Token)JsonConvert.DeserializeObject(response.ContentString, typeof(Token));
            }
            catch (Exception ex)
            {
                CrestronConsole.PrintLine("SimplTeslaMaster.Tokens.TokenGenerator.GetToken()::Error in Tesla API (TokenGenerator.GetToken): Unable to get response. " + ex.ToString());
                ErrorLog.Exception("Error in Tesla API (TokenGenerator.GetToken): Unable to get response.", ex);
            }

            // Clean up
            request = null;
            client.Dispose();
            client = null;

            return(result);
        }
示例#29
0
        /// <summary>
        /// Sends the web request to the API
        /// </summary>
        /// <returns>The API's response</returns>
        protected virtual string GetApiResponse()
        {
            int    responseCode;
            string responseString;

            Client = HttpsClientFactory.NewClient();

            if (Request == null)
            {
                Request = GetClientRequest();
            }

            Request.Url.Parse(ApiUrl);
            Client.Url = Request.Url;

            Request.FinalizeHeader();
            Response = Client.Dispatch(Request);

            // Retrieving the response code serves 2 purposes:
            //      1) It ensures that the thread has waited for the Dispatch request to have completed before proceeding, preventing null results; and
            //      2) It allows verification of success (200)
            responseCode   = Response.Code;
            responseString = Response.ContentString;

            if (responseCode != 200)
            {
                CrestronConsole.PrintLine("SimplTeslaCar.Results.BaseResult.GetApiResponse()::Request was not successful!");
                CrestronConsole.PrintLine("SimplTeslaCar.Results.BaseResult>GetApiResponse()::Response code: " + responseCode.ToString());
                CrestronConsole.PrintLine("SimplTeslaCar.Results.BaseResult>GetApiResponse()::Response content: " + responseString);
            }

            Request = null;
            Client.Dispose();
            Client = null;

            return(Response.ContentString);
        }
示例#30
0
        public static ushort GetSystem()
        {
            try
            {
                if (Username.Length > 0 && Password.Length > 0)
                {
                    GetToken();

                    if (Token != null)
                    {
                        if (Token.Length > 0)
                        {
                            using (HttpsClient client = new HttpsClient())
                            {
                                client.TimeoutEnabled    = true;
                                client.Timeout           = 10;
                                client.HostVerification  = false;
                                client.PeerVerification  = false;
                                client.AllowAutoRedirect = false;
                                client.IncludeHeaders    = false;

                                HttpsClientRequest request = new HttpsClientRequest();

                                request.Url.Parse(string.Format("https://wap.tplinkcloud.com?token={0}", Token));
                                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                                request.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));

                                request.ContentString = "{\"method\":\"getDeviceList\"}";

                                HttpsClientResponse response = client.Dispatch(request);

                                if (response.ContentString != null)
                                {
                                    if (response.ContentString.Length > 0)
                                    {
                                        JObject body = JObject.Parse(response.ContentString);

                                        if (body["result"] != null)
                                        {
                                            if (body["result"]["deviceList"] != null)
                                            {
                                                Devices = JsonConvert.DeserializeObject <List <KasaDeviceInfo> >(body["result"]["deviceList"].ToString());

                                                foreach (var device in Devices)
                                                {
                                                    if (SubscribedDevices.ContainsKey(device.alias))
                                                    {
                                                        SubscribedDevices[device.alias].Fire(new KasaDeviceEventArgs(eKasaDeviceEventId.GetNow, 1));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (Devices.Count > 0)
                    {
                        return(1);
                    }
                    else
                    {
                        return(0);
                    }
                }

                else
                {
                    throw new ArgumentException("Username and Password cannot be emtpy");
                }
            }
            catch (SocketException se)
            {
                ErrorLog.Exception("SocketException occured in System.GetSystem - ", se);
                return(0);
            }
            catch (HttpsException he)
            {
                ErrorLog.Exception("HttpsException occured in System.GetSystem - ", he);
                return(0);
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Exception occured in System.GetSystem - ", e);
                return(0);
            }
        }