예제 #1
0
    static void Send_Notification_Response(object[] data, Action <object[]> concluding_method)
    {
        Response_Status status = Http_Client.Parse_Status(data[0]);

        if (status < Response_Status.Network_Error)
        {
            SimpleJSON.JSONNode raw = SimpleJSON.JSON.Parse((string)data[2]);

            if (status == Response_Status.Ok)
            {
                if (raw["failure"].Value == "0")
                {
                    Debug.Log("Success on sending notification.");
                    concluding_method?.Invoke(new object[] { status, raw["success"].Value, "0" });
                }
                else
                {
                    Debug.LogWarning("Correct HTTP response but sending failures exists! (" + raw["success"].Value + " success, " + raw["failure"].Value + " failures)");
                    concluding_method?.Invoke(new object[] { status, raw["success"].Value, raw["failure"].Value });
                }
            }
            else
            {
                concluding_method?.Invoke(new object[] { status, raw["error"].Value, "-1" });
            }
        }
    }
예제 #2
0
    // ______________________________________
    //
    // 6. NOTIFICATION SENDING.
    // ______________________________________
    //


    public static void Send_Notification(FCM_Params param)
    {
        if (param.Notification_Key == "")
        {
            Get_Notification_Key("user_id" + param.User_Id.ToString(), (object[] data_get) =>
            {
                Response_Status status_get = Http_Client.Parse_Status(data_get[0]);

                if (status_get == Response_Status.Ok)
                {
                    param.Notification_Key = (string)data_get[1];
                    Send_Notification(param);
                }
                else
                {
                    Debug.LogWarning("Could not send notification due to error on getting the notification_key!");
                    param.Concluding_Method?.Invoke(new object[] { Response_Status.HTTP_Error, "notification_key not found", "-1" });
                }
            });
            return;
        }

        string content =
            "{" +
            s + "to" + s + ":" + s + param.Notification_Key + s + "," +
            s + "data" + s +
            ":{";

        if (param.Data_Pairs != null)
        {
            foreach (KeyValuePair <string, string> data in param.Data_Pairs)
            {
                content += s + data.Key + s + ":" + s + data.Value + s + ",";
            }
        }

        if (content[content.Length - 1] == ',')
        {
            content = content.Substring(0, content.Length - 1);
        }

        content +=
            "}" +
            s + "notification" + s + ": " +
            "{" +
            s + "title" + s + ": " + s + param.Title + s + "," +
            s + "body" + s + ": " + s + param.Body + s + "," +
            s + "priority" + s + ": " + param.Priority +
            "}" +
            "}";

        Http_Client.Send_HTTP_Request(
            "https://fcm.googleapis.com/fcm/send",
            Http_Client.Request_Type.POST,
            default_header,
            Send_Notification_Response,
            param.Concluding_Method,
            content
            );
    }
예제 #3
0
    static void Get_Notification_Key_Response(object[] data, Action <object[]> concluding_method)
    {
        Response_Status status = Http_Client.Parse_Status(data[0]);

        if (status < Response_Status.Network_Error)
        {
            SimpleJSON.JSONNode raw = SimpleJSON.JSON.Parse((string)data[2]);

            if (status == Response_Status.Ok)
            {
                if (raw["notification_key"] != null)
                {
                    Debug.Log("Notification key is " + raw["notification_key"].Value);
                    concluding_method?.Invoke(new object[] { status, raw["notification_key"].Value });
                }
                else
                {
                    Debug.LogError("Correct HTTP response but notification key is null!");
                }
            }
            else
            {
                concluding_method?.Invoke(new object[] { status, raw["error"].Value });
            }
        }
    }
예제 #4
0
        //private async Task<string> CheckNetwork(string uri)
        //{
        //    Domoticz_Times result = null;
        //    string baseUrl = string.Empty;
        //    try
        //    {
        //        baseUrl = uri;
        //        _baseUrl = uri;
        //        uri = $"{baseUrl}{Constants.GetSunRiseSunSet}";
        //        result = await GetSunRiseSunSet(uri);
        //        if (result?.status == Response_Status.OK.ToString())
        //        {
        //            //_baseUrl = baseUrl;
        //            SetCaptions(result);
        //        }
        //        else
        //        {
        //            baseUrl = string.Empty;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.WriteLine(string.Format("Error Message: {0}", ex.Message));
        //        Debug.WriteLine(string.Format("Error Inner: {0}", ex.InnerException));
        //    }

        //    return baseUrl;
        //}

        //private void SetCaptions(Domoticz_Times result)
        //{
        //    if (result.Sunrise != _sunriseText)
        //    {
        //        _sunriseText = $"Sunrise: {result.Sunrise}";
        //    }
        //    if (result.Sunset != _sunsetText)
        //    {
        //        _sunsetText = $"Sunset: {result.Sunset}";
        //    }
        //    TimeSpan now = DateTime.Now.TimeOfDay;
        //    int indexPeriod = now.ToString().LastIndexOf('.');
        //    string updateInfo = now.ToString().Remove(indexPeriod);
        //    if (_statusUpdated.CompareTo($"{updateInfo}") != 0)
        //    {
        //        //string up = String.Format("{0:d/M/yyyy HH:mm:ss}", now);
        //        _statusUpdated = $"Updated: {updateInfo}";
        //    }
        //}

        //private async Task<bool> CheckNetworkConnectionsAsync()
        //{
        //    string result = null;
        //    try
        //    {
        //        // First check local network
        //        CheckingLanNetwork = true;
        //        CheckingWanNetwork = true;
        //        result = await CheckNetwork(GetLocalServerUri(true));
        //        if (result != null && result != string.Empty)
        //        {
        //            CheckingLanNetwork = false;
        //            SetLanAvailable(true);
        //            _baseUrl = GetLocalServerUri(false);
        //        }
        //        else
        //        {
        //            SetLanAvailable(false);
        //        }
        //        CheckingLanNetwork = false;

        //        result = await CheckNetwork(GetWanServerUri(true));
        //        if (result != null && result != string.Empty)
        //        {
        //            CheckingWanNetwork = false;
        //            SetWanAvailable(true);
        //            _baseUrl = GetWanServerUri(false);
        //        }
        //        else
        //        {
        //            SetWanAvailable(false);
        //        }
        //        CheckingWanNetwork = false;
        //    }
        //    catch (Exception)
        //    {

        //        return false;
        //    }
        //    return true;

        //    #region MyRegion
        //    //// failing calls
        //    //var reachable1 = await CrossConnectivity.Current.IsReachable("192.168.1.9:82", 2000);
        //    //var reachable1b = await CrossConnectivity.Current.IsReachable("192.168.1.9", 2000);
        //    //var reachable2 = await CrossConnectivity.Current.IsReachable("http://192.168.1.9:82", 2000);
        //    //var reachable3 = await CrossConnectivity.Current.IsRemoteReachable("http://192.168.1.9:82", 2000);

        //    //IEnumerable<ConnectionType> y = CrossConnectivity.Current.ConnectionTypes;
        //    //IEnumerable<UInt64> z = CrossConnectivity.Current.Bandwidths;

        //    //string localServer = CrossSettings.Current.GetValueOrDefault("Address", "");
        //    //string remoteServer = CrossSettings.Current.GetValueOrDefault("WanAddress", "");

        //    //bool available1 = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
        //    //bool available2 = CrossConnectivity.Current.IsConnected;

        //    //var remoteAvailable = await CrossConnectivity.Current.IsRemoteReachable($"http://{remoteServer}");
        //    //var localAvailable = await CrossConnectivity.Current.IsReachable(localServer, 3000);

        //    //if (!available1 && !available2)
        //    //{
        //    //    //UseLanAddress = false;
        //    //    //UseWanAddress = false;
        //    //    await App.Current.MainPage.DisplayAlert("Network Unavailable", "Please set the correct address and retry.", "OK");
        //    //    await _navigationService.NavigateAsync("SettingsPage");
        //    //}
        //    //else if (remoteAvailable)
        //    //{
        //    //    //UseLanAddress = false;
        //    //    //UseWanAddress = true;
        //    //}
        //    //else if (localAvailable && available1 && available2)
        //    //{
        //    //    IsSwitchBusy = false;
        //    //    IsSceneBusy = false;
        //    //    //UseLanAddress = true;
        //    //    //UseWanAddress = false;
        //    //}
        //    //else
        //    //{
        //    //    IsSwitchBusy = false;
        //    //    IsSceneBusy = false;
        //    //    //UseWanAddress = true;
        //    //    await App.Current.MainPage.DisplayAlert("Servers not found", "Please set the correct address and retry.", "OK");
        //    //    await _navigationService.NavigateAsync("SettingsPage");
        //    //}
        //    #endregion
        //}



        private async void BackgroundTasks()
        {
            while (true)
            {
                // Establish if Network is available
                bool networkSeen = await CheckNetworkConnections();

                if (!networkSeen)
                {
                    await App.Current.MainPage.DisplayAlert("Network Unavailable", "Please enable the network and retry.", "OK");

                    //    await _navigationService.NavigateAsync("SettingsPage");
                }

                // Establish connection with Domoticz
                string          primaryUri            = $"{Preferences.Get ( "Protocol", "Http://" )}{Preferences.Get ( "Address", "192.168.1.53" )}:{Preferences.Get ( "Port", "8080" )}/json.htm?username=brad=&password=elky454=&{SunRiseSunSet}";
                Response_Status primaryDomoticzIsSeen = await CheckNetworkForDomoticz(primaryUri);

                string          secondaryUri            = $"{Preferences.Get ( "Protocol", "Http://" )}{Preferences.Get ( "SecondaryAddress", "192.168.1.53" )}:{Preferences.Get ( "SecondaryPort", "8080" )}/json.htm?username=brad=&password=elky454=&{SunRiseSunSet}";
                Response_Status secondaryDomoticzIsSeen = await CheckNetworkForDomoticz(secondaryUri);


                await Task.Delay(5000);
            }
        }
예제 #5
0
    void Handle_Response(UnityWebRequest www, Action <object[], Action <object[]> > processing_method, Action <object[]> concluding_method)
    {
        StringBuilder   header = new StringBuilder();
        Response_Status status = Response_Status.Ok;

        foreach (KeyValuePair <string, string> dict in www.GetResponseHeaders())
        {
            header.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n");
        }

        if (www.isNetworkError)
        {
            status = Response_Status.Network_Error;

            if (www.error == "Cannot resolve destination host")
            {
                Message.ShowMessage("No estás conectad@ a internet.");
            }
            else
            {
                Message.ShowMessage(www.error);
            }

            Debug.LogError("HTTP Response: " + www.error + "\nHeader:\n" + header.ToString() + "\nContent:\n" + www.downloadHandler.text + "\nConcluding Method: " + processing_method.Method.Name);
        }
        else if (www.isHttpError)
        {
            status = Response_Status.HTTP_Error;
            Debug.LogWarning("HTTP Response: " + www.error + "\nHeader:\n" + header.ToString() + "\nContent:\n" + www.downloadHandler.text + "\nConcluding Method: " + processing_method.Method.Name);
        }
        else
        {
            Debug.Log("HTTP Response:\nHeader:\n" + header.ToString() + "\nContent:\n" + www.downloadHandler.text + "\nConcluding method: " + processing_method.Method.Name);
        }

        processing_method(
            new object[]
        {
            status,
            header.ToString(),
            www.downloadHandler.text
        },
            concluding_method
            );
    }
예제 #6
0
        private async Task <Response_Status> CheckNetworkForDomoticz(string uri)
        {
            Domoticz_Times  result  = null;
            Response_Status success = Response_Status.ERR;

            try
            {
                // You must set the Uri to the base HtpClient or the request fails
                _baseUrl = uri;
                result   = await GetSunRiseSunSet(uri);

                if (result?.status == Response_Status.OK.ToString( ))
                {
                    success = Response_Status.OK;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Error Message: {0}", ex.Message));
                Debug.WriteLine(string.Format("Error Inner: {0}", ex.InnerException));
            }

            return(success);
        }