public void setSwitchState(string command, string deviceID, string category)
        {
            HttpsClient client = new HttpsClient();
            //client.Verbose = true;
            client.PeerVerification = false;
            client.HostVerification = false;
            //Testing
            //client.AllowAutoRedirect = true;

            HttpsClientRequest request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "";
            url = SmartThingsReceiver.InstallationURL + "/" + category + "/" + deviceID + "/" + command + "?access_token=" + SmartThingsReceiver.AccessToken;
            request.KeepAlive = true;

            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            if (response.Code >= 200 && response.Code < 300)
            {
                //ErrorLog.Notice("Wink https response code: " + response.Code);
                //ErrorLog.Notice(response.ContentString.ToString() + "\n");                
            }
            else
            {
                // A reponse code outside this range means the server threw an error.
                ErrorLog.Notice("HTTPS response code: " + response.Code);
            }
        }
        /// <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);
                }
            }
        }
        /// <summary>
        /// Connect to pushbullet and make a send request
        /// </summary>
        private string PushBulletHttpRequest(string requestUrl, string accessToken, RequestType HttpRequestType, string pushBulletObject)
        {
            HttpsClient client = new HttpsClient();

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

            HttpsClientRequest  httpRequest = new HttpsClientRequest();
            HttpsClientResponse response;

            try
            {
                httpRequest.KeepAlive = true;
                httpRequest.Url.Parse(requestUrl);
                httpRequest.RequestType = HttpRequestType;
                httpRequest.Header.SetHeaderValue("Content-Type", "application/json");
                httpRequest.Header.SetHeaderValue("Access-Token", accessToken);
                httpRequest.ContentString = pushBulletObject;

                response = client.Dispatch(httpRequest);

                if (response.Code >= 200 && response.Code < 300)
                {
                    // sucess
                    return(response.ContentString);
                }
                else if (response.Code == 401 | response.Code == 403)
                {
                    ErrorLog.Error("PushBullet Invalid Access Token");
                    OnDoorLockMessageReceived("PushBullet Invalid Access Token");
                    return("Error");
                }
                else
                {
                    // error responce
                    ErrorLog.Error(response.ContentString.ToString());
                    return("Error");
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("PushBulletHttpRequest Error: " + e.Message);
                return("Error");
            }
            finally
            {
                client.Dispose();
            }
        }
示例#4
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;
                    client.IncludeHeaders    = 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)
            {
                ErrorLog.Exception("Exception ocurred in UseRefreshToken", e);
            }
        }
示例#5
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);

                    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>
        /// After save operation on JSON master happens, send it to server
        /// </summary>
        /// <param name="json"></param>
        void SaveCallback(string json)
        {
            CurrentPreset.Data = json;

            if (!UrlBase.StartsWith("https"))
            {
                return;
            }
            var req = new HttpsClientRequest();

            req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
            req.Url         = new UrlParser(string.Format("{0}/api/presets/addorchange", UrlBase));
            req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
            req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
            req.ContentString = JsonConvert.SerializeObject(CurrentPreset);

            var client = new HttpsClient();

            client.HostVerification = false;
            client.PeerVerification = false;
            try
            {
                var resp = client.Dispatch(req);

                // 201=created
                // 204=empty content
                if (resp.Code == 201)
                {
                    CrestronConsole.PrintLine("Preset added");
                }
                else if (resp.Code == 204)
                {
                    CrestronConsole.PrintLine("Preset updated");
                }
                else if (resp.Code == 209)
                {
                    CrestronConsole.PrintLine("Preset already exists. Cannot save as new.");
                }
                else
                {
                    CrestronConsole.PrintLine("Preset save failed: {0}\r", resp.Code, resp.ContentString);
                }
            }
            catch (HttpException e)
            {
                CrestronConsole.PrintLine("Preset save exception {0}", e.Response.Code);
            }
        }
        //Get device info
        public void GetDevice()
        {
            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);
                        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);

                        if (response.ContentString != null)
                        {
                            if (response.ContentString.Length > 0)
                            {
                                JToken body = JToken.Parse(response.ContentString);
                                ParseData(body);
                            }
                        }
                    }
                }
                else
                {
                    if (onErrorMsg != null)
                    {
                        onErrorMsg("Device not found, ensure the Label field is set in the app");
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Exception ocurred in GetDevice", e);
            }
        }
        private object CodecPollingProcess(object userSpecific)
        {
            while (!_programStopping)
            {
                foreach (var valuePair in _codecAddresses)
                {
                    var roomId  = valuePair.Key;
                    var address = valuePair.Value;

                    try
                    {
                        var uri = new UriBuilder("https", address, 443, "status.xml").Uri;
                        Debug.WriteInfo("Polling Codec", "Room {0}: {1}", roomId, uri.ToString());
                        var request = new HttpsClientRequest {
                            Url = new UrlParser(uri.ToString())
                        };
                        var username = ConfigManager.Config.CodecUsername;
                        var password = ConfigManager.Config.CodecPassword;
                        var auth     = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
                        request.Header.AddHeader(new HttpsHeader("Authorization", "Basic " + auth));
                        var response = Client.Dispatch(request);
                        var reader   = new XmlReader(response.ContentString);
                        var doc      = XDocument.Load(reader);
                        var status   = doc.Element("Status");
                        Debug.WriteSuccess("Codec Online", status.Element("UserInterface").Element("ContactInfo").Element("Name").Value);
                        Debug.WriteSuccess("Mute", status.Element("Audio").Element("Microphones").Element("Mute").Value);
                        Debug.WriteSuccess("In Call", status.Elements("Call").Any().ToString());
                        Debug.WriteSuccess("Uptime", TimeSpan.FromSeconds(int.Parse(status.Element("SystemUnit").Element("Uptime").Value)).ToPrettyFormat());
                        Debug.WriteSuccess("Standby", "Status = {0}", status.Element("Standby").Element("State").Value != "Standby");
                        CrestronConsole.PrintLine("");
                    }
                    catch (Exception e)
                    {
                        CloudLog.Error("Error polling codec at {0}, {1}", address, e.Message);
                    }
                }

                Thread.Sleep(30000);
                CrestronEnvironment.AllowOtherAppsToRun();
            }

            CloudLog.Notice("Leaving thread: {0}", Thread.CurrentThread.Name);

            return(null);
        }
        /// <summary>
        /// Create a Device
        /// </summary>
        public void MyDevice(string devicestring)
        {
            HttpsClient client = new HttpsClient();

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

            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "https://api.pushbullet.com/v2/devices";

            try
            {
                request.KeepAlive = true;
                request.Url.Parse(url);
                client.UserName     = DeviceToken;
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                request.Header.SetHeaderValue("Content-Type", "application/json");
                request.Header.SetHeaderValue("Authorization", "Bearer " + DeviceToken);
                request.ContentString = devicestring;
                response = client.Dispatch(request);

                if (response.Code >= 200 && response.Code < 300)
                {
                    // A response code between 200 and 300 means it was successful.
                    //CrestronConsole.Print(response.ContentString.ToString());
                    string   s     = response.ContentString.ToString();
                    string[] words = s.Split(',');
                    foreach (string word in words)
                    {
                        //CrestronConsole.PrintLine(word + "\n");
                    }
                }
                else
                {
                    // A reponse code outside this range means the server threw an error.
                    CrestronConsole.Print("Pushbullet https response code: " + response.Code);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("Exception in Pushbullet: " + e.ToString());
            }
        }
示例#10
0
        public void BellPush()
        {
            CrestronConsole.PrintLine("button push received");

            PushInfo pushinfo = new PushInfo
            {
                type  = "note",
                title = "Doorbell",
                body  = "reply unlock or ignore"
            };

            HttpsClient hsc = new HttpsClient();

            hsc.PeerVerification = false;
            hsc.HostVerification = false;
            HttpsClientRequest  hscr = new HttpsClientRequest();
            HttpsClientResponse hscrs;

            hsc.KeepAlive = true;
            hscr.Url.Parse("https://api.pushbullet.com/v2/pushes");
            //hscr.Header.AddHeader(new HttpsHeader("Access-Token", token));
            hscr.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
            hscr.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
            hscr.Header.AddHeader(new HttpsHeader("Authorization", "Bearer " + token));
            hscr.ContentString = JsonConvert.SerializeObject(pushinfo);
            try
            {
                hscrs = hsc.Dispatch(hscr);
                if (hscrs.Code >= 200 && hscrs.Code < 300)
                {
                    // success
                    CrestronConsole.PrintLine("Dispatch worked.");
                    //checkPushes();
                }
                else
                {
                    CrestronConsole.PrintLine("Dispatch server error:" + hscrs.Code);
                }
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Connection error:" + e.ToString());
            }
        }
示例#11
0
        public void setLightBulbState(string access_code, string deviceID, string state)
        {
            HttpsClient client = new HttpsClient();

            client.Verbose          = false;
            client.PeerVerification = false;
            client.HostVerification = false;
            //Testing
            //client.AllowAutoRedirect = true;

            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "https://winkapi.quirky.com/light_bulbs/" + deviceID;//SMS/Messages.json

            //String url = "https://private-714ad-wink.apiary-mock.com/light_bulbs/" + deviceID;
            request.KeepAlive = true;



            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Put;
            request.Header.SetHeaderValue("Content-Type", "application/json");
            request.Header.SetHeaderValue("Authorization", "Bearer " + access_code);
            request.Header.SetHeaderValue("Expect", "");
            //string command = "{\n    \"name\":\"My Device\",\n}";
            string command = "{\n    \"desired_state\": {\n        \"powered\":" + state + "\n    }\n}";

            request.ContentString = command;
            request.Header.SetHeaderValue("Content-Length", command.Length.ToString());
            request.Header.SetHeaderValue("transfer-encoding", "");

            response = client.Dispatch(request);
            if (response.Code >= 200 && response.Code < 300)
            {
                //ErrorLog.Notice("Wink https response code: " + response.Code);
                //ErrorLog.Notice(response.ContentString.ToString() + "\n");
            }
            else
            {
                // A reponse code outside this range means the server threw an error.
                ErrorLog.Notice("Wink https response code: " + response.Code);
            }
        }
        public ushort dismissPush(string PushIden)
        {
            if (Access_Code != "")
            {
                string      commandstring = "";
                HttpsClient client        = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose          = false;

                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/pushes/" + PushIden;

                request.KeepAlive = true;
                request.Url.Parse(url);
                request.Header.SetHeaderValue("Content-Type", "application/json");
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);

                Dismiss dismiss = new Dismiss
                {
                    dismissed = true
                };
                commandstring         = JsonConvert.SerializeObject(dismiss, Formatting.Indented);
                request.ContentString = commandstring;
                response = client.Dispatch(request);

                if (response.Code >= 200 && response.Code < 300)
                {
                    return(1);
                }
                else
                {
                    ErrorLog.Notice("Error Dismissing - " + response.Code.ToString() + "\n");
                    return(0);
                }
            }
            else
            {
                return(0);
            }
        }
        public void GetUserForPasscode(string passcode)
        {
            // Bullshit duplicate code here... These two cases should be the same
            // except for https/http and the certificate ignores
            if (!UrlBase.StartsWith("https"))
            {
                return;
            }
            var req = new HttpsClientRequest();

            req.Url         = new UrlParser(UrlBase + "/api/users/dopin");
            req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
            req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
            req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
            var jo = new JObject();

            jo.Add("pin", passcode);
            req.ContentString = jo.ToString();

            var client = new HttpsClient();

            client.HostVerification = false;
            client.PeerVerification = false;
            var resp    = client.Dispatch(req);
            var handler = UserReceived;

            if (resp.Code == 200)
            {
                //CrestronConsole.PrintLine("Received: {0}", resp.ContentString);
                var user = JsonConvert.DeserializeObject <User>(resp.ContentString);
                CurrentUser = user;
                if (handler != null)
                {
                    UserReceived(this, new UserReceivedEventArgs(user, true));
                }
            }
            else
            if (handler != null)
            {
                UserReceived(this, new UserReceivedEventArgs(null, false));
            }
        }
        public void getStatus(string deviceID, string category)
        {
            HttpsClient client = new HttpsClient();
            client.AllowAutoRedirect = true;
            client.PeerVerification = false;
            client.HostVerification = false;
            client.KeepAlive = true;
            HttpsClientRequest request = new HttpsClientRequest();
            HttpsClientResponse response;

            //Get Switches
            string url = SmartThingsReceiver.InstallationURL + "/"+category+"/"+deviceID+"?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            //ErrorLog.Notice("Response = {0}", response.ContentString);
            string pattern = "value\":\"(.*?)\"";
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
                SignalChangeEvents.SerialValueChange(deviceID, m.Groups[1].ToString());
        }
示例#15
0
        public static void deletePush()
        {
            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose          = false;

                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/pushes";

                request.KeepAlive = true;
                request.Url.Parse(url);
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Delete;
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                response = client.Dispatch(request);
                client.Abort();
            }
        }
示例#16
0
        //SendPush method that send a push message to the PushBullet Server
        public void SendPush(string message)
        {
            HttpsClient client = new HttpsClient();

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

            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "https://api.pushbullet.com/v2/pushes";

            request.KeepAlive = true;
            request.Url.Parse(url);
            client.UserName     = User_Token;
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
            request.Header.SetHeaderValue("Content-Type", "application/json");
            request.Header.SetHeaderValue("Authorization", "Bearer " + User_Token);
            request.ContentString = message;
            response = client.Dispatch(request);
        }
示例#17
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);
            }
        }
        public ushort deletePush(string PushIden)
        {
            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose          = false;
                client.UserName         = Access_Code;


                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                //String url = "https://api.pushbullet.com/v2/pushes/" + PushIden;
                String url = "https://api-pushbullet-com-fqp420kzi8tw.runscope.net/v2/pushes/" + PushIden;

                //request.KeepAlive = true;
                request.Url.Parse(url);
                request.Header.SetHeaderValue("Content-Type", "application/json");
                //request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Delete;
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);

                response = client.Dispatch(request);
                string s = response.ContentString.ToString();
                if (response.Code >= 200 && response.Code < 300)
                {
                    //ErrorLog.Notice("Deleted\n");
                    return(1);
                }
                else
                {
                    ErrorLog.Notice("Error Deleting - " + response.Code.ToString() + "\n");
                    return(0);
                }
            }
            else
            {
                return(0);
            }
        }
        /// <summary>
        /// This is what actually send the push
        /// </summary>
        /// <param name="commandstring"></param>
        public void Send(string commandstring)
        {
            HttpsClient client = new HttpsClient();

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

            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "https://api.pushbullet.com/v2/pushes";

            try
            {
                request.KeepAlive = true;
                request.Url.Parse(url);
                client.UserName     = Access_Code;
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                request.Header.SetHeaderValue("Content-Type", "application/json");
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                request.ContentString = commandstring;
                response = client.Dispatch(request);

                if (response.Code >= 200 && response.Code < 300)
                {
                    // A response code between 200 and 300 means it was successful.
                    //ErrorLog.Notice(response.ContentString.ToString());
                }
                else
                {
                    // A reponse code outside this range means the server threw an error.
                    ErrorLog.Notice("Pushbullet https response code: " + response.Code);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("Exception in Pushbullet: " + e.ToString());
            }
        }
        /// <summary>
        /// This Method Will Retrieve all pushes since x.
        /// </summary>
        /// <returns></returns>
        public ushort getUserInfo()
        {
            string commandstring = "";

            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose          = false;

                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/users/me";

                try
                {
                    myCC.Enter(); // Will not finish, until you have the Critical Section
                    request.KeepAlive = true;
                    request.Url.Parse(url);
                    request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
                    request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                    request.ContentString = commandstring;

                    // Dispatch will actually make the request with the server
                    response = client.Dispatch(request);
                    client.Abort();
                    if (response.Code >= 200 && response.Code < 300)
                    {
                        string s = response.ContentString.ToString();
                        //ErrorLog.Notice(s + "\n");
                        string[] words = s.Split(',');
                        string   senderEmail;
                        foreach (string word in words)
                        {
                            if (word.Contains("\"email\""))
                            {
                                senderEmail = word.Substring(11, word.Length - 12);
                                setSenderEmail(senderEmail);
                            }
                        }

                        //ErrorLog.Notice(response.ContentString.ToString());
                        // A response code between 200 and 300 means it was successful.
                        return(1);
                    }
                    else
                    {
                        ErrorLog.Notice("Response Code = " + response.Code.ToString() + "\n");
                        // A reponse code outside this range means the server threw an error.
                        return(0);
                    }
                }
                catch (Exception e)
                {
                    ErrorLog.Error("Exception in Pushbullet - GetInfo: " + e.ToString());
                    return(0);
                }
                finally
                {
                    myCC.Leave();
                }
            }
            else
            {
                return(0);
            }
        }
        /// <summary>
        /// This Method Will Retrieve all pushes since x.
        /// </summary>
        /// <returns></returns>
        public ushort getPush()
        {
            string commandstring = "";

            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose          = false;

                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/pushes";

                try
                {
                    myCC.Enter(); // Will not finish, until you have the Critical Section
                    request.KeepAlive = true;
                    request.Url.Parse(url);
                    request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
                    request.Header.SetHeaderValue("Content-Type", "application/json");
                    request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                    request.ContentString = commandstring;


                    // Dispatch will actually make the request with the server
                    response = client.Dispatch(request);
                    client.Abort();
                    if (response.Code >= 200 && response.Code < 300)
                    {
                        string s = response.ContentString.ToString();
                        //ErrorLog.Notice(s + "\n");
                        string[] words       = s.Split(',');
                        string   PushIden    = "";
                        string   PushTitle   = "";
                        string   PushMessage = "";
                        bool     PushUnread  = true;
                        bool     SentMessage = false;
                        foreach (string word in words)
                        {
                            //ErrorLog.Notice(word + "\n");
                            if (word.Contains("\"iden\""))
                            {
                                PushIden = word.Substring(8, word.Length - 9);
                            }
                            if (word.Contains("title"))
                            {
                                PushTitle = word.Substring(9, word.Length - 10);
                                if (PushTitle.Contains("\""))
                                {
                                    PushTitle.Substring(0, PushTitle.Length - 1);
                                }
                            }
                            if (word.Contains("body"))
                            {
                                if (word.Contains("}"))
                                {
                                    PushMessage = word.Substring(8, word.Length - 10);
                                }
                                else
                                {
                                    PushMessage = word.Substring(8, word.Length - 9);
                                    if (PushMessage.Contains("\""))
                                    {
                                        PushMessage.Substring(0, PushMessage.Length - 1);
                                    }
                                }
                            }
                            if (word.Contains("dismissed"))
                            {
                                if (word.Contains("true"))
                                {
                                    PushUnread = false;
                                    continue;
                                }
                            }
                            if (word.Contains("sender_email") && word.Contains(Sender_Email))
                            {
                                SentMessage = true;
                            }
                            if (word.Contains("}"))
                            {
                                //TODO Trigger Event To Output String to S+
                                if (PushTitle != "" || PushMessage != "")
                                {
                                    if (PushUnread == true)
                                    {
                                        if (SentMessage != true)
                                        {
                                            PushReceived("CMD=" + PushTitle + "." + PushMessage + ";");
                                        }
                                        ushort result = dismissPush(PushIden);
                                    }
                                }
                                PushIden    = "";
                                PushTitle   = "";
                                PushMessage = "";
                                PushUnread  = false;
                            }
                        }
                        //ErrorLog.Notice(response.ContentString.ToString());
                        // A response code between 200 and 300 means it was successful.
                        return(1);
                    }
                    else
                    {
                        ErrorLog.Notice("Response Code = " + response.Code.ToString() + "\n");
                        // A reponse code outside this range means the server threw an error.
                        return(0);
                    }
                }
                catch (Exception e)
                {
                    ErrorLog.Error("Exception in Pushbullet - GetInfo: " + e.ToString());
                    return(0);
                }
                finally
                {
                    myCC.Leave();
                }
            }
            else
            {
                return(0);
            }
        }
示例#22
0
        /// <summary>
        /// This Method Will Retrieve all pushes since x.
        /// </summary>
        /// <returns></returns>
        public ushort getUserInfo()
        {
            string commandstring = "";
            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose = false;

                HttpsClientRequest request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/users/me";

                try
                {
                    myCC.Enter(); // Will not finish, until you have the Critical Section
                    request.KeepAlive = true;
                    request.Url.Parse(url);
                    request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
                    request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                    request.ContentString = commandstring;

                    // Dispatch will actually make the request with the server
                    response = client.Dispatch(request);
                    client.Abort();
                    if (response.Code >= 200 && response.Code < 300)
                    {
                        string s = response.ContentString.ToString();
                        //ErrorLog.Notice(s + "\n");
                        string[] words = s.Split(',');
                        string senderEmail;
                        foreach (string word in words)
                        {
                            if (word.Contains("\"email\""))
                            {
                                senderEmail = word.Substring(11, word.Length - 12);
                                setSenderEmail(senderEmail);
                            }
                        }
                        
                        //ErrorLog.Notice(response.ContentString.ToString());
                        // A response code between 200 and 300 means it was successful.
                        return 1;
                    }
                    else
                    {
                        ErrorLog.Notice("Response Code = " + response.Code.ToString() + "\n");
                        // A reponse code outside this range means the server threw an error.
                        return 0;
                    }
                }
                catch (Exception e)
                {
                    ErrorLog.Error("Exception in Pushbullet - GetInfo: " + e.ToString());
                    return 0;
                }
                finally
                {
                    myCC.Leave();
                }
            }
            else
            {
                return 0;
            }
        }
示例#23
0
        public ushort GetDevices(string access_code)
        {
            if (access_code == null)
            {
                // can't send without these fields being set.
                return(0);
            }
            else
            {
                HttpsClient client = new HttpsClient();
                //client.UserName = AccountSID;
                //client.Password = AuthToken;
                client.Verbose = false;

                /*
                 * The PeerVerification option determines whether our HTTPS class verifies the authenticity of
                 * the peer's certificate.
                 *
                 * WARNING: disabling verification of the certificate allows bad guys to man-in-the-middle the
                 * communication without you knowing it. Disabling verification makes the communication insecure.
                 * Just having encryption on a transfer is not enough as you cannot be sure that you are
                 * communicating with the correct end-point.
                 */
                client.PeerVerification = false;

                /*
                 * The HostVerification option determines whether our HTTPS verifies that the server cert is for
                 * the server it is known as.
                 */
                client.HostVerification = false;

                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://winkapi.quirky.com/users/me/wink_devices";//SMS/Messages.json

                try
                {
                    request.KeepAlive = true;
                    request.Url.Parse(url);
                    request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
                    request.Header.SetHeaderValue("Content-Type", "application/json");
                    request.Header.SetHeaderValue("Authorization", "Bearer " + access_code);
                    request.ContentString = "";


                    // Dispatch will actually make the request with the server
                    response = client.Dispatch(request);

                    if (response.Code >= 200 && response.Code < 300)
                    {
                        // A response code between 200 and 300 means it was successful.
                        //ErrorLog.Notice(response.ContentString.ToString());
                        string[] subStrings = response.ContentString.ToString().Split(',');

                        foreach (string str in subStrings)
                        {
                            ErrorLog.Notice(str);
                        }

                        return(1);
                    }
                    else
                    {
                        // A reponse code outside this range means the server threw an error.
                        ErrorLog.Notice("Wink https response code: " + response.Code);
                        return(0);
                    }
                }
                catch (Exception e)
                {
                    ErrorLog.Error("Exception in Wink: " + e.ToString());
                    return(0);
                }
            }
        }
        /// <summary>
        /// List Devices
        /// </summary>
        public void MyDevice()
        {
            HttpsClient client = new HttpsClient();

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

            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url            = "https://api.pushbullet.com/v2/devices";
            string MyDeviceName   = "";
            bool   MyDeviceActive = false;

            //CrestronConsole.PrintLine("MyDevice\n");

            try
            {
                request.KeepAlive = true;
                request.Url.Parse(url);
                client.UserName     = DeviceToken;
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
                request.Header.SetHeaderValue("Content-Type", "application/json");
                request.Header.SetHeaderValue("Authorization", "Bearer " + DeviceToken);
                //request.ContentString = devicestring;
                response = client.Dispatch(request);
                client.Abort();

                if (response.Code >= 200 && response.Code < 300)
                {
                    // A response code between 200 and 300 means it was successful.
                    string   s            = response.ContentString.ToString();
                    bool     MyDeviceFind = false;
                    string[] words        = s.Split(',');
                    foreach (string word in words)
                    {
                        //CrestronConsole.PrintLine("Device : "+word + "\n");
                        if (word.Contains("{\"active\":true"))
                        {
                            //CrestronConsole.PrintLine("Device is active\n");
                            MyDeviceActive = true;
                        }


                        if (word.Contains("\"nickname\"") && MyDeviceActive == true)
                        {
                            MyDeviceName = word.Substring(12, word.Length - 13);
                            //CrestronConsole.PrintLine(MyDeviceName + " = " + DeviceName + " \n");

                            if (MyDeviceName == DeviceName)
                            {
                                MyDeviceFind = true;
                                //CrestronConsole.PrintLine(MyDeviceName + " Finded\n");
                                break;
                            }
                        }
                        //CrestronConsole.PrintLine(word + "\n");
                    }
                    if (MyDeviceFind == false)
                    {
                        CreateDevice();
                    }
                }
                else
                {
                    // A reponse code outside this range means the server threw an error.
                    CrestronConsole.Print("Pushbullet https response code: " + response.Code);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("Exception in Pushbullet: " + e.ToString());
            }
        }
示例#25
0
        public string Authenticate(string client_id, string client_secret, string username, string password)
        {
            if (username != "" && password != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose          = false;

                HttpsClientRequest  request = new HttpsClientRequest();
                HttpsClientResponse response;
                //String url = "https://private-714ad-wink.apiary-mock.com/oauth2/token";
                String url = "https://winkapi.quirky.com/oauth2/token";

                try
                {
                    request.KeepAlive = true;
                    request.Url.Parse(url);
                    request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                    request.Header.SetHeaderValue("Content-Type", "application/json");
                    request.ContentString = "";
                    request.ContentString = str2JSON("?client_id=" + client_id + "&" + "client_secret=" + client_secret + "&" + "username="******"&" + "password="******"&" + "grant_type=" + "password");

                    // Dispatch will actually make the request with the server
                    response = client.Dispatch(request);

                    if (response.Code >= 200 && response.Code < 300)
                    {
                        // A response code between 200 and 300 means it was successful.
                        //ErrorLog.Notice(response.ContentString.ToString());

                        string[] subStrings = response.ContentString.ToString().Split(',');

                        foreach (string str in subStrings)
                        {
                            if (str.Contains("access_token"))
                            {
                                string result = str.Substring(25, str.Length - 26);
                                return(result);
                            }
                            else
                            {
                                ErrorLog.Notice("Not Found\n");
                            }
                        }
                    }
                    else
                    {
                        // A reponse code outside this range means the server threw an error.
                        ErrorLog.Notice("Wink https response code: " + response.Code);
                        return("");
                    }
                }
                catch (Exception e)
                {
                    ErrorLog.Error("Exception in Wink: " + e.ToString());
                    return("");
                }
                return("");
            }
            return("");
        }
示例#26
0
        public string getLightBulbState(string access_code, string deviceID)
        {
            HttpsClient client = new HttpsClient();

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

            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "https://winkapi.quirky.com/light_bulbs/" + deviceID;//SMS/Messages.json

            request.KeepAlive = true;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            request.Header.SetHeaderValue("Content-Type", "application/json");
            request.Header.SetHeaderValue("Authorization", "Bearer " + access_code);
            request.ContentString = "";
            response = client.Dispatch(request);
            ushort lr = 0;

            if (response.Code >= 200 && response.Code < 300)
            {
                //ErrorLog.Notice(response.ContentString.ToString());
                string[] subStrings = response.ContentString.ToString().Split(',');

                foreach (string str in subStrings)
                {
                    if (str.Contains("last_reading"))
                    {
                        lr = 1;
                    }
                    if (lr == 1)
                    {
                        if (str.Contains("{"))
                        {
                            string result = str.Substring(26, str.Length - 26);
                            //ErrorLog.Notice(result);
                            if (result == "false")
                            {
                                return("off");
                            }
                            else if (result == "true")
                            {
                                return("on");
                            }
                        }
                    }
                    if (str.Contains("connection"))
                    {
                        lr = 0;
                    }
                }
            }
            else
            {
                // A reponse code outside this range means the server threw an error.
                ErrorLog.Notice("Wink https response code: " + response.Code);
            }
            return("");
        }
示例#27
0
        public ushort deletePush(string PushIden)
        {
            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose = false;
                client.UserName = Access_Code;
                

                HttpsClientRequest request = new HttpsClientRequest();
                HttpsClientResponse response;
                //String url = "https://api.pushbullet.com/v2/pushes/" + PushIden;
                String url = "https://api-pushbullet-com-fqp420kzi8tw.runscope.net/v2/pushes/" + PushIden;

                //request.KeepAlive = true;
                request.Url.Parse(url);
                request.Header.SetHeaderValue("Content-Type", "application/json");
                //request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Delete;
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);

                response = client.Dispatch(request);
                string s = response.ContentString.ToString();
                if (response.Code >= 200 && response.Code < 300)
                {
                    //ErrorLog.Notice("Deleted\n");
                    return 1;
                }
                else
                {
                    ErrorLog.Notice("Error Deleting - " + response.Code.ToString() + "\n");
                    return 0;
                }
            }
            else

                return 0;
        }
        /// <summary>
        /// This Method Will Retrieve all pushes since x.
        /// </summary>
        /// <returns></returns>
        public static ushort getPush()
        {            
            string commandstring = "";
            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose = false;

                HttpsClientRequest request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/pushes";

                try
                {
                    myCC.Enter(); // Will not finish, until you have the Critical Section
                    request.KeepAlive = true;
                    request.Url.Parse(url);
                    request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
                    request.Header.SetHeaderValue("Content-Type", "application/json");
                    request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                    request.ContentString = commandstring;


                    // Dispatch will actually make the request with the server
                    response = client.Dispatch(request);

                    if (response.Code >= 200 && response.Code < 300)
                    {
                        client.Abort();
                        string s = response.ContentString.ToString();
                        string[] words = s.Split(',');
                        string PushIden = "";
                        string PushTitle = "";
                        string PushMessage = "";
                        foreach (string word in words)
                        {
                            //ErrorLog.Notice(word + "\n");
                            if (word.Contains("iden"))
                            {
                                PushIden = word.Substring(8, word.Length - 9);
                            }
                            if (word.Contains("title"))
                            {
                                PushTitle = word.Substring(9, word.Length - 10);
                            }
                            if (word.Contains("message"))
                            {
                                PushMessage = word.Substring(11, word.Length - 12);
                            }
                            if (word.Contains("dismissed"))
                            {
                                //TODO Trigger Event To Output String to S+

                                PushReceived("CMD=" + PushTitle + "." + PushMessage + ";");
                                //ErrorLog.Notice("TX = " + PushTitle + "." + PushMessage + ";");
                                //TODO Delete Push.IDEN
                                PushIden = "";
                                PushTitle = "";
                                PushMessage = "";

                            }
                        }
                        //ErrorLog.Notice(response.ContentString.ToString());
                        // A response code between 200 and 300 means it was successful.
                        return 1;
                    }
                    else
                    {
                        client.Abort();
                        ErrorLog.Notice("Response Code = " + response.Code.ToString() + "\n");
                        // A reponse code outside this range means the server threw an error.
                        return 0;
                    }
                }
                catch (Exception e)
                {
                    client.Abort();
                    ErrorLog.Error("Exception in Pushbullet - GetInfo: " + e.ToString());
                    return 0;
                }
                finally
                {
                    myCC.Leave();
                }
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// This is what actually send the push
        /// </summary>
        /// <param name="commandstring"></param>
        public static void Send(string commandstring)
        {
            HttpsClient client = new HttpsClient();
            client.PeerVerification = false;
            client.HostVerification = false;
            client.Verbose = false;

            HttpsClientRequest request = new HttpsClientRequest();
            HttpsClientResponse response;
            String url = "https://api.pushbullet.com/v2/pushes";

            try
            {
                request.KeepAlive = true;
                request.Url.Parse(url);
                client.UserName = Access_Code;
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                request.Header.SetHeaderValue("Content-Type", "application/json");
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                request.ContentString = commandstring;
                response = client.Dispatch(request);

                if (response.Code >= 200 && response.Code < 300)
                {
                    // A response code between 200 and 300 means it was successful.
                    ErrorLog.Notice(response.ContentString.ToString());
                }
                else
                {
                    // A reponse code outside this range means the server threw an error.
                    ErrorLog.Notice("Pushbullet https response code: " + response.Code);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("Exception in Pushbullet: " + e.ToString());
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="roomTypeId"></param>
        /// <param name="presetNumber"></param>
        public void GetPresetForThisUser(int roomTypeId, int presetNumber)
        {
            if (CurrentUser == null)
            {
                CrestronConsole.PrintLine("GetPresetForThisUser no user loaded");
                return;
            }

            var msg = new UserAndRoomMessage
            {
                UserId       = CurrentUser.Id,
                RoomTypeId   = roomTypeId,
                PresetNumber = presetNumber
            };

            var handler = PresetReceived;

            try
            {
                if (!UrlBase.StartsWith("https"))
                {
                    return;
                }
                var req = new HttpsClientRequest();
                req.Url         = new UrlParser(UrlBase + "/api/presets/userandroom");
                req.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                req.Header.AddHeader(new HttpsHeader("Content-Type", "application/json"));
                req.Header.AddHeader(new HttpsHeader("Accept", "application/json"));
                req.ContentString = JsonConvert.SerializeObject(msg);

                var client = new HttpsClient();
                client.HostVerification = false;
                client.PeerVerification = false;

                // ask for the preset
                var resp = client.Dispatch(req);
                if (resp.Code == 200) // got it
                {
                    //Debug.Console(1, this, "Received: {0}", resp.ContentString);
                    var preset = JsonConvert.DeserializeObject <Preset>(resp.ContentString);
                    CurrentPreset = preset;

                    //if there's no preset data, load the template
                    if (preset.Data == null || preset.Data.Trim() == string.Empty || JObject.Parse(preset.Data).Count == 0)
                    {
                        //Debug.Console(1, this, "Loaded preset has no data. Loading default template.");
                        LoadDefaultPresetData();
                        return;
                    }

                    J2SMaster.LoadWithJson(preset.Data);
                    if (handler != null)
                    {
                        PresetReceived(this, new PresetReceivedEventArgs(preset, true));
                    }
                }
                else // no existing preset
                {
                    CurrentPreset = new Preset();
                    LoadDefaultPresetData();
                    if (handler != null)
                    {
                        PresetReceived(this, new PresetReceivedEventArgs(null, false));
                    }
                }
            }
            catch (HttpException e)
            {
                var resp = e.Response;
                Debug.Console(1, this, "No preset received (code {0}). Loading default template", resp.Code);
                LoadDefaultPresetData();
                if (handler != null)
                {
                    PresetReceived(this, new PresetReceivedEventArgs(null, false));
                }
            }
        }
        public static string GetClientIdentfier(string token, string adr)
        {
            try
            {
                var identifier = string.Empty;

                using (HttpsClient clientsServer = new HttpsClient())
                {
                    IPHostEntry entry;

                    if ((entry = Dns.GetHostEntry("plex.tv")) != null)
                    {
                        HttpsClientRequest  clientServerRequest = new HttpsClientRequest();
                        HttpsClientResponse clientServerResponse;

                        clientsServer.TimeoutEnabled       = true;
                        clientsServer.Timeout              = 25;
                        clientsServer.AuthenticationMethod = Crestron.SimplSharp.Net.AuthMethod.BASIC;
                        clientsServer.PeerVerification     = false;

                        clientServerRequest.Url.Parse("https://plex.tv/devices.xml");
                        clientServerRequest.Header.AddHeader(new HttpsHeader("X-Plex-Client-Identifier", "Crestron"));
                        clientServerRequest.Header.AddHeader(new HttpsHeader("X-Plex-Token", token));
                        clientServerRequest.RequestType = RequestType.Get;

                        clientServerResponse = clientsServer.Dispatch(clientServerRequest);

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(clientServerResponse.ContentString);

                        XmlNodeList deviceList = doc.SelectNodes("MediaContainer/Device");

                        foreach (XmlNode item in deviceList)
                        {
                            XmlNodeList connections;

                            if ((connections = item.SelectNodes("Connection")) != null)
                            {
                                foreach (XmlNode connection in connections)
                                {
                                    if (connection.Attributes["uri"].Value.Contains(adr))
                                    {
                                        identifier = item.Attributes["clientIdentifier"].Value;
                                        break;
                                    }
                                }

                                if (identifier != string.Empty)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }

                return(identifier);
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Unable to resolve address"))
                {
                }
                else
                {
                    ErrorLog.Error("Error authorizing Plex: {0}", e);
                }
                return("");
            }
        }
示例#32
0
        public void AuthenticateStep2()
        {
            HttpsClient client = new HttpsClient();

            //client.Verbose = true;
            //Testing
            client.AllowAutoRedirect = true;
            client.PeerVerification  = false;
            client.HostVerification  = false;
            client.KeepAlive         = true;
            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;

            //Get AccessToken
            String url = "https://graph.api.smartthings.com/oauth/token?grant_type=authorization_code&client_id=" + ClientID + "&client_secret=" + ClientSecret + "&redirect_uri=http://" + IP + ":" + Port.ToString() + "&scope=app&code=" + AuthCode;

            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            try
            {
                response = client.Dispatch(request);
                //ErrorLog.Notice("Response = {0}\n", response.ContentString);
                string pattern = ".*?\"([a-z0-9-]+)\"";
                var    r       = new Regex(pattern, RegexOptions.IgnoreCase);
                if (response.ContentString != null)
                {
                    var match = r.Match(response.ContentString);
                    if (match.Success)
                    {
                        SmartThingsReceiver.AccessToken = match.Groups[1].Value;
                        //ErrorLog.Notice("AccessToken = {0}\n", SmartThingsReceiver.AccessToken);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("**Failed To Retrieve External Complete Authentication**\n");
                ErrorLog.Error("URL = {0}\n", url);
                response = null;
                return;
            }

            //Get Installation ID and URL

            url = "https://graph.api.smartthings.com/api/smartapps/endpoints/" + SmartThingsReceiver.ClientID + "?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            try
            {
                response = client.Dispatch(request);
                //ErrorLog.Notice("Response = {0}\n", response.ContentString);
                string pattern = ".*?\"url\":\"(.*?)\"}";
                var    r       = new Regex(pattern, RegexOptions.IgnoreCase);
                if (response.ContentString != null)
                {
                    var match = r.Match(response.ContentString);
                    if (match.Success)
                    {
                        SmartThingsReceiver.InstallationURL = "https://graph.api.smartthings.com" + match.Groups[1].Value;
                        //ErrorLog.Notice("InstallationURL = {0}\n", SmartThingsReceiver.InstallationURL);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("**Failed To Retrieve External Complete Authentication**\n");
                ErrorLog.Error("URL = {0}\n", url);
                response = null;
                return;
            }

            //Write Authentication Credentials to a File
            SmartThingsReceiver.WriteFile();
            SmartThingsReceiver.Authorized = 1;
        }
        public static void deletePush()
        {
            if (Access_Code != "")
            {
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose = false;

                HttpsClientRequest request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/pushes";

                request.KeepAlive = true;
                request.Url.Parse(url);
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Delete;
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);
                response = client.Dispatch(request);
                client.Abort();
            }
        }
        public void DeviceList()
        {
            HttpsClient client = new HttpsClient();
            //client.Verbose = true;
            //Testing
            client.AllowAutoRedirect = true;
            client.PeerVerification = false;
            client.HostVerification = false;
            client.KeepAlive = true;
            HttpsClientRequest request = new HttpsClientRequest();
            HttpsClientResponse response;

            //Get Switches
            string url = SmartThingsReceiver.InstallationURL + "/switches/?access_token=" + SmartThingsReceiver.AccessToken;            
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            string pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**Switches**");         
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
                ErrorLog.Notice("'{0}' found with ID {1}.",m.Groups[2], m.Groups[1]);
            ErrorLog.Notice("\n");

            //Get Dimmers
            url = SmartThingsReceiver.InstallationURL + "/dimmers/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**Dimmers**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            ErrorLog.Notice("\n");

            //Get Presence
            url = SmartThingsReceiver.InstallationURL + "/presence/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**Presence**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            ErrorLog.Notice("\n");

            //Get thermostats
            url = SmartThingsReceiver.InstallationURL + "/thermostats/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**thermostats**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            ErrorLog.Notice("\n");

            //Get Locks
            url = SmartThingsReceiver.InstallationURL + "/locks/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response = client.Dispatch(request);
            pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**locks**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            ErrorLog.Notice("\n");

        }
        //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);


                    // CrestronConsole.PrintLine("GetTokenAndRefreshToken : " + response.ContentString);



                    if (response.ContentString != null)
                    {
                        if (response.ContentString.Length > 0)
                        {
                            char[]  charsToTrim = { '"' };
                            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);
            }
        }
示例#36
0
        public ushort dismissPush(string PushIden)
        {
            if (Access_Code != "")
            {
                string commandstring = "";
                HttpsClient client = new HttpsClient();
                client.PeerVerification = false;
                client.HostVerification = false;
                client.Verbose = false;

                HttpsClientRequest request = new HttpsClientRequest();
                HttpsClientResponse response;
                String url = "https://api.pushbullet.com/v2/pushes/" + PushIden;

                request.KeepAlive = true;
                request.Url.Parse(url);
                request.Header.SetHeaderValue("Content-Type", "application/json");
                request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Post;
                request.Header.SetHeaderValue("Authorization", "Bearer " + Access_Code);

                Dismiss dismiss = new Dismiss
                {
                    dismissed = true
                };
                commandstring = JsonConvert.SerializeObject(dismiss, Formatting.Indented);
                request.ContentString = commandstring;
                response = client.Dispatch(request);
                
                if (response.Code >= 200 && response.Code < 300)
                {
                    return 1;
                }
                else
                {
                    ErrorLog.Notice("Error Dismissing - " + response.Code.ToString() + "\n");
                    return 0;
                }
            }
            else

                return 0;
        }
示例#37
0
        public void DeviceList()
        {
            HttpsClient client = new HttpsClient();

            //client.Verbose = true;
            //Testing
            client.AllowAutoRedirect = true;
            client.PeerVerification  = false;
            client.HostVerification  = false;
            client.KeepAlive         = true;
            HttpsClientRequest  request = new HttpsClientRequest();
            HttpsClientResponse response;

            //Get Switches
            string url = SmartThingsReceiver.InstallationURL + "/switches/?access_token=" + SmartThingsReceiver.AccessToken;

            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response            = client.Dispatch(request);
            string pattern = "id\":\"(.*?)\".*?label\":\"(.*?)\"";

            ErrorLog.Notice("**Switches**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
            {
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            }
            ErrorLog.Notice("\n");

            //Get Dimmers
            url = SmartThingsReceiver.InstallationURL + "/dimmers/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response            = client.Dispatch(request);
            pattern             = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**Dimmers**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
            {
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            }
            ErrorLog.Notice("\n");

            //Get Presence
            url = SmartThingsReceiver.InstallationURL + "/presence/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response            = client.Dispatch(request);
            pattern             = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**Presence**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
            {
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            }
            ErrorLog.Notice("\n");

            //Get thermostats
            url = SmartThingsReceiver.InstallationURL + "/thermostats/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response            = client.Dispatch(request);
            pattern             = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**thermostats**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
            {
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            }
            ErrorLog.Notice("\n");

            //Get Locks
            url = SmartThingsReceiver.InstallationURL + "/locks/?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            response            = client.Dispatch(request);
            pattern             = "id\":\"(.*?)\".*?label\":\"(.*?)\"";
            ErrorLog.Notice("**locks**");
            foreach (Match m in Regex.Matches(response.ContentString, pattern, RegexOptions.IgnoreCase))
            {
                ErrorLog.Notice("'{0}' found with ID {1}.", m.Groups[2], m.Groups[1]);
            }
            ErrorLog.Notice("\n");
        }
示例#38
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);
            }
        }
示例#39
0
        //Use authorization code to retrieve a refresh token and a session token
        private void GetTokenAndRefreshToken()
        {
            try
            {
                using (var client = new HttpsClient())
                {
                    client.TimeoutEnabled    = true;
                    client.Timeout           = 10;
                    client.HostVerification  = false;
                    client.PeerVerification  = false;
                    client.AllowAutoRedirect = false;

                    var request = new HttpsClientRequest();

                    var url = "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.Url.Parse(url);

                    DebugLogic.Log(">>> LOGGING: GetTokenAndRefreshToken: URL: " + url, DebugLogic.ErrorLevel.Notice, true);

                    request.RequestType = RequestType.Post;
                    request.Header.SetHeaderValue("Content-Type", "application/json; charset=utf-8");

                    var response = client.Dispatch(request);

                    if (response.ContentString == null)
                    {
                        return;
                    }

                    if (response.ContentString.Length <= 0)
                    {
                        return;
                    }

                    DebugLogic.Log(">>> LOGGING: GetTokenAndRefreshToken: Response Content String - Not Parsed: " + response.ContentString, DebugLogic.ErrorLevel.Notice, true);

                    var body = JObject.Parse(response.ContentString);
                    DebugLogic.Log(">>> LOGGING: GetTokenAndRefreshToken: Parsed String: " + body.ToString(), DebugLogic.ErrorLevel.Notice, true);

                    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)
                    {
                        return;
                    }

                    refreshToken = body["refresh_token"].ToString().Replace("\"", string.Empty);

                    using (var writer = new StreamWriter(File.Create(refreshTokenFilePath + refreshTokenFileName)))
                    {
                        writer.WriteLine(refreshToken);
                    }
                }
            }
            catch (Exception e)
            {
                DebugLogic.Log(">>> ERROR: Exception ocurred in GetTokenAndRefreshToken" + e, DebugLogic.ErrorLevel.Error, true);
            }
        }
        public void AuthenticateStep2()
        {
            HttpsClient client = new HttpsClient();
            //client.Verbose = true;
            //Testing
            client.AllowAutoRedirect = true;
            client.PeerVerification = false;
            client.HostVerification = false;
            client.KeepAlive = true;
            HttpsClientRequest request = new HttpsClientRequest();
            HttpsClientResponse response;

            //Get AccessToken
            String url = "https://graph.api.smartthings.com/oauth/token?grant_type=authorization_code&client_id=" + ClientID + "&client_secret=" + ClientSecret + "&redirect_uri=http://" + IP + ":" + Port.ToString() + "&scope=app&code=" + AuthCode;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            try
            {
                response = client.Dispatch(request);
                //ErrorLog.Notice("Response = {0}\n", response.ContentString);
                string pattern = ".*?\"([a-z0-9-]+)\"";
                var r = new Regex(pattern, RegexOptions.IgnoreCase);
                if (response.ContentString != null)
                {
                    var match = r.Match(response.ContentString);
                    if (match.Success)
                    {
                        SmartThingsReceiver.AccessToken = match.Groups[1].Value;
                        //ErrorLog.Notice("AccessToken = {0}\n", SmartThingsReceiver.AccessToken);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("**Failed To Retrieve External Complete Authentication**\n");
                ErrorLog.Error("URL = {0}\n", url);
                response = null;
                return;
            }

            //Get Installation ID and URL

            url = "https://graph.api.smartthings.com/api/smartapps/endpoints/" + SmartThingsReceiver.ClientID + "?access_token=" + SmartThingsReceiver.AccessToken;
            request.Url.Parse(url);
            request.RequestType = Crestron.SimplSharp.Net.Https.RequestType.Get;
            try
            {
                response = client.Dispatch(request);
                //ErrorLog.Notice("Response = {0}\n", response.ContentString);
                string pattern = ".*?url\":\"(.*?)\"}";
                var r = new Regex(pattern, RegexOptions.IgnoreCase);
                if (response.ContentString != null)
                {
                    var match = r.Match(response.ContentString);
                    if (match.Success)
                    {
                        SmartThingsReceiver.InstallationURL = "https://graph.api.smartthings.com" + match.Groups[1].Value;
                        //ErrorLog.Notice("InstallationURL = {0}\n", SmartThingsReceiver.InstallationURL);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLog.Error("**Failed To Retrieve External Complete Authentication**\n");
                ErrorLog.Error("URL = {0}\n", url);
                response = null;
                return;
            }

            //Write Authentication Credentials to a File
            SmartThingsReceiver.WriteFile();
            SmartThingsReceiver.Authorized = 1;
        }