public GenericWeather AsGenericWeather()
        {
            GenericWeather weather = new GenericWeather()
            {
                CurrentObservation = new GenericCurrentObservation()
                {
                    Icon = GetIconFromInternationalWeather(CurrentWeather.Wx_code),
                    TemperatureCelsius    = CurrentWeather.Temp_c,
                    TemperatureFahrenheit = CurrentWeather.Temp_f,
                    WeatherDescription    = CurrentWeather.Wx_desc,
                    AdditionalInfo        = string.Format(Common.GetLocalizedText("HumidityText"), CurrentWeather.Humid_pct.ToString())
                },
                Forecast = new GenericForecast()
            };

            List <GenericForecastDay> forecastDays = new List <GenericForecastDay>();

            // weatherunlocked.com gives a 7-day forecast, starting with yesterday's weather - we want the forecast starting tomorrow
            foreach (var day in ForecastWeather.Days)
            {
                if (DateTime.TryParseExact(day.Date, DateFormats, CultureInfo.CurrentUICulture, DateTimeStyles.None, out DateTime result) &&
                    result > DateTime.Now)
                {
                    forecastDays.Add(GetGenericForecastDay(day));
                }
            }
            weather.Forecast.Days = forecastDays.ToArray();
            return(weather);
        }
Ejemplo n.º 2
0
        private async Task <bool> SetUpForecastAsync(SimpleLocation location, bool showLoading = true)
        {
            if (showLoading)
            {
                ShowLoadingPanel(Common.GetLocalizedText("LoadingWeatherInfoText"));
            }

            try
            {
                CurrentLocation = location.Name;

                // Set the map center
                MapCenter = new Geopoint(location.Position);

                // Add pin
                MapLayers.Clear();
                AddPinToMap(new SimpleLocation(Common.GetLocalizedText("WeatherMapPinLabel"), location.Position.Latitude, location.Position.Longitude));

                // Retrieve weather information about location
                var weather = await WeatherProvider.Instance.GetGenericWeatherAsync(location.Position.Latitude, location.Position.Longitude);

                // Update the UI if weather is available
                if (weather != null)
                {
                    // Only set weather if it's not null
                    _weather = weather;

                    // Update weather-related UI
                    RefreshWeatherUI(_weather);

                    // Try to get sensor data
                    try
                    {
                        SensorTemperatureAndHumidity = await GetSensorTemperatureAndHumidityString();
                    }
                    catch (Exception ex)
                    {
                        LogService.WriteException(ex);
                    }

                    // Show proper weather panel
                    WeatherErrorPageVisibility = false;
                    WeatherControlVisibility   = true;
                    return(true);
                }
                else
                {
                    // Something went wrong so show the error panel
                    WeatherErrorPageVisibility = true;
                    WeatherControlVisibility   = false;
                }
            }
            finally
            {
                HideLoadingPanel();
            }
            return(false);
        }
Ejemplo n.º 3
0
        public GenericWeather AsGenericWeather()
        {
            var genericWeather = new GenericWeather
            {
                Source             = Name,
                CurrentObservation = GetGenericCurrentObservation(),
                Forecast           = GetGenericForecast()
            };

            return(genericWeather);
        }
Ejemplo n.º 4
0
        public GenericWeather AsGenericWeather()
        {
            var weather = new GenericWeather
            {
                CurrentObservation = new GenericCurrentObservation(),
                Forecast           = new GenericForecast()
            };

            var forecastObjects = ParseForecastDayObjects();
            var currentForecast = forecastObjects.FirstOrDefault(x => x.StartValidTime.Date == DateTime.Now.Date && DateTime.Now >= x.StartValidTime);

            if (currentForecast != null)
            {
                weather.CurrentObservation.Icon = GetIconFromUSWeather(currentForecast.IconLink);
                weather.CurrentObservation.TemperatureFahrenheit = (float)currentForecast.Temperature;
                weather.CurrentObservation.TemperatureCelsius    = WeatherHelper.GetCelsius((int)weather.CurrentObservation.TemperatureFahrenheit);
                weather.CurrentObservation.WeatherDescription    = currentForecast.Weather;
            }

            // forecast.weather.gov gives 15 weather reports, including 2 for each day (one during the day, and one at night),
            // possibly starting with either "This Afternoon" or "Tonight" depending on the time of day.
            // Only grab the first forecast for each date, up to the number of days we specify
            var forecastDays = new List <GenericForecastDay>();
            int numDays      = 5;

            foreach (var forecastObject in forecastObjects)
            {
                if (forecastDays.Count == numDays)
                {
                    break;
                }

                var date = forecastObject.StartValidTime.Date;
                // If we haven't already gotten a forecast for the day and it isn't today, add it to the list
                if (forecastDays.FirstOrDefault(x => x.DayOfWeek == date.ToString("dddd")) == null && date != DateTime.Now.Date)
                {
                    forecastDays.Add(GetGenericForecastDay(
                                         date.ToString("dddd"),
                                         ((int)forecastObject.Temperature).ToString(),
                                         forecastObject.IconLink,
                                         forecastObject.Weather));
                }
            }

            weather.Forecast.Days = forecastDays.ToArray();

            return(weather);
        }
Ejemplo n.º 5
0
        private void DisplayWeather(GenericWeather weather)
        {
            CurrentTemperature = $"{((Settings.IsFahrenheit) ? Math.Round(weather.CurrentObservation.Temperature) : Math.Round(WeatherHelper.GetCelsius(weather.CurrentObservation.Temperature)))}{TempUnit}";

            if (!Settings.IsFahrenheit)
            {
                foreach (var day in weather.Forecast.Days)
                {
                    day.TemperatureHigh = Math.Round(WeatherHelper.GetCelsius(day.TemperatureHigh));
                    day.TemperatureLow  = Math.Round(WeatherHelper.GetCelsius(day.TemperatureLow));
                }
            }

            ForecastCollection = weather.Forecast.Days;

            AttributionText = weather.Source;
        }
Ejemplo n.º 6
0
        public string GetCurrentTemperatureString(GenericWeather weather)
        {
            string result = string.Empty;

            if (FahrenheitEnabled)
            {
                result += (int)Math.Round(weather.CurrentObservation.TemperatureFahrenheit, 0) + "°F";
            }
            if (FahrenheitEnabled && CelsiusEnabled)
            {
                result += " / ";
            }
            if (CelsiusEnabled)
            {
                result += (int)Math.Round(weather.CurrentObservation.TemperatureCelsius, 0) + "°C";
            }
            return(result);
        }
Ejemplo n.º 7
0
        private void RefreshWeatherUI(GenericWeather weather)
        {
            WeatherProviderString = weather.Source ?? Common.GetLocalizedText("NotAvailable");

            CurrentTemperature    = GetCurrentTemperatureString(weather);
            CurrentAdditionalInfo = weather.CurrentObservation.AdditionalInfo;
            CurrentWeatherIcon    = weather.CurrentObservation.Icon;
            CurrentWeather        = weather.CurrentObservation.WeatherDescription;

            Forecast.Clear();
            for (int i = 0; i < 5 && i < _weather.Forecast.Days.Length; ++i)
            {
                Forecast.Add(new ForecastDay
                {
                    Day   = _weather.Forecast.Days[i].DayOfWeek,
                    TempF = _weather.Forecast.Days[i].TemperatureFahrenheit,
                    TempC = _weather.Forecast.Days[i].TemperatureCelsius,
                    Icon  = _weather.Forecast.Days[i].WeatherIcon,
                    Desc  = _weather.Forecast.Days[i].WeatherDescription,
                });
            }
        }
Ejemplo n.º 8
0
        public async Task <bool> RefreshWeatherAsync()
        {
            try
            {
                var location = await LocationUtil.GetLocationAsync(Settings);

                // Couldn't get user's location
                if (location.Name == Common.GetLocalizedText("WeatherMapPinUnknownLabel"))
                {
                    ErrorTitle    = Common.GetLocalizedText("LocationErrorTitle");
                    ErrorSubtitle = Common.GetLocalizedText("LocationErrorSubtitle");
                    return(false);
                }

                var weather = await WeatherProvider.Instance.GetGenericWeatherAsync(
                    location.Position.Latitude,
                    location.Position.Longitude
                    );

                // Couldn't get weather
                if (weather == null)
                {
                    ErrorTitle    = Common.GetLocalizedText("GenericErrorTitle");
                    ErrorSubtitle = Common.GetLocalizedText("WeatherErrorSubtitle");
                    return(false);
                }

                DisplayWeather(weather);

                _currentWeather = weather;

                return(true);
            }
            catch (Exception ex)
            {
                LogService.WriteException(ex);
                return(false);
            }
        }
        /// <summary>
        /// Returns GenericWeather, populated by weatherunlocked.com
        /// </summary>
        public async Task <GenericWeather> GetGenericWeatherAsync(double lat, double lon)
        {
            // Get the Timestamp of when the next refresh will be allowed and calculate the difference between that and now
            DateTime timeToRefresh = _lastRefreshedTime.Add(_refreshCooldown);

            // Return the cached weather data if the the refresh is still cooling down
            if (_cachedWeather != null && DateTime.Now.CompareTo(timeToRefresh) < 0)
            {
                return(_cachedWeather);
            }

            try
            {
                InternationalForecastWeather jsonForecastData;
                InternationalCurrentWeather  jsonCurrentData;

                // If the user provided a WeatherToken.config file, then read the keys from that. Otherwise, read it from Keys.cs
                WeatherAPIInfo weatherInfo = await WeatherHelper.ReadWeatherAPIInfo();

                using (var cancel = new CancellationTokenSource(20000))
                    using (var client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Add("User-Agent", "SmartDisplay");
                        string data       = string.Empty;
                        Uri    currentUri = new Uri("http://api.weatherunlocked.com/api/current/" +
                                                    Convert.ToString(lat, CultureInfo.InvariantCulture) + "," + Convert.ToString(lon, CultureInfo.InvariantCulture) +
                                                    "?lang=" + GetLanguage() +
                                                    "&app_id=" + weatherInfo.AppId +
                                                    "&app_key=" + weatherInfo.AppKey);
                        var response = await client.GetAsync(currentUri).AsTask(cancel.Token);

                        if (response.IsSuccessStatusCode)
                        {
                            data = await client.GetStringAsync(currentUri);

                            jsonCurrentData = Newtonsoft.Json.JsonConvert.DeserializeObject <InternationalCurrentWeather>(data);

                            if (data.Contains("error"))
                            {
                                throw new Exception("Location not found");
                            }
                        }
                        else
                        {
                            return(null);
                        }

                        Uri forecastUri = new Uri("http://api.weatherunlocked.com/api/forecast/" +
                                                  Convert.ToString(lat, CultureInfo.InvariantCulture) + "," + Convert.ToString(lon, CultureInfo.InvariantCulture) +
                                                  "?lang=" + GetLanguage() +
                                                  "&app_id=" + weatherInfo.AppId +
                                                  "&app_key=" + weatherInfo.AppKey);

                        response = await client.GetAsync(forecastUri).AsTask(cancel.Token);

                        data = string.Empty;
                        if (response.IsSuccessStatusCode)
                        {
                            data = await client.GetStringAsync(forecastUri);

                            jsonForecastData = Newtonsoft.Json.JsonConvert.DeserializeObject <InternationalForecastWeather>(data);

                            if (data.Contains("error"))
                            {
                                throw new Exception("Location not found");
                            }
                        }
                        else
                        {
                            return(null);
                        }
                    }

                var result = new InternationalWeather(jsonCurrentData, jsonForecastData).AsGenericWeather();
                result.Source = Name;

                // Update cached weather object and refresh timestamp
                _cachedWeather     = result;
                _lastRefreshedTime = DateTime.Now;

                return(result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(null);
            }
        }