ResponseMessage CommandWeather(Update inUpd)
        {
            CurrentWeatherResponse weather = null;

            if (inUpd.Message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
            {
                if (inUpd.Message.Text == "/weather")
                {
                    return(new TextResponseMessage(inUpd.Message, $"Жду вашу локацию"));
                }
                // Пытаемся поискать по локации
                weather = GetWeatherByName(inUpd.Message.Text);
            }
            if (inUpd.Message.Type == Telegram.Bot.Types.Enums.MessageType.LocationMessage)
            {
                weather = GetWeatherByLocation(inUpd.Message.Location.Longitude, inUpd.Message.Location.Latitude);
            }

            // Подготовка результата
            userInCommandProcessing[inUpd.Message.From.Id] = CommandEnum.None;
            if (weather == null)
            {
                return(new TextResponseMessage(inUpd.Message, "Не удалось определить погоду"));
            }
            return(new TextResponseMessage(inUpd.Message, $"Погода в {weather.City.Name}: t°={weather.Temperature.Value}°C (min: {weather.Temperature.Min}°C, max: {weather.Temperature.Max}°C)" +
                                           $", w={weather.Wind.Speed.Value}м/с ({weather.Wind.Direction.Name})"));
        }
        /// <summary>
        /// Get Current Weather using a zip code
        /// </summary>
        /// <param name="zip">Zip code for current weather</param>
        /// <param name="countryCode">Optional: Country Code corresponding to zip.  US by default.</param>
        /// <param name="temperatureUnit">Temperature Unit - Imperial by default.</param>
        public async Task <CurrentWeatherResponse> GetCurrentWeatherByZip(string zip, string countryCode = "us", TemperatureUnit temperatureUnit = TemperatureUnit.Imperial)
        {
            if (string.IsNullOrEmpty(zip))
            {
                throw new ArgumentNullException(nameof(zip));
            }

            var parameters = new Dictionary <string, string>()
            {
                { "zip", $"{zip},{countryCode}" },
                { "units", temperatureUnit.ToString() }
            };

            HttpResponseMessage response;

            using (_client)
            {
                response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, BuildUri(@"https://api.openweathermap.org/data/2.5/weather", parameters)));
            }

            if (response.IsSuccessStatusCode)
            {
                return(CurrentWeatherResponse.FromJson(await response.Content.ReadAsStringAsync()));
            }

            throw new Exception(await response.Content.ReadAsStringAsync());
        }
Exemple #3
0
 public DailyForecast ParseData(CurrentWeatherResponse data)
 {
     return(new DailyForecast(data.Name, (int)data.Main.Temp,
                              (int)data.Wind.Speed, (int)data.Main.Humidity,
                              Convert.ToInt32(data.Weather.FirstOrDefault()?.Id.ToString().Substring(0, 1))
                              , UnixTimeStampToDateTime(data.Dt)));
 }
Exemple #4
0
        public async Task <WeatherLoad> Get(string city)
        {
            _Params = new Dictionary <string, string>();

            _Params.Add("q", city);
            _Params.Add("units", OW_Unit.Metric.ToString("g"));
            _Params.Add("appid", _AccessKey);

            _requestStartDateTime = DateTime.Now.ToUniversalTime();
            _requestEndDateTime   = null;
            _responseSizeBytes    = 0;

            CurrentWeatherResponse response = await this.Get();

            return(SerialiseResponse(response));

            if (response != null)
            {
                return(SerialiseResponse(response));
            }
            else
            {
                return(null);
            }
        }
Exemple #5
0
 public void Update(object data)
 {
     if (data == null)
     {
         WeatherDataUi = _weatherSubject.GetWeatherData();
         WeatherDataUi.Temperature.Value = Math.Round(WeatherDataUi.Temperature.Value - 273.15);
     }
 }
Exemple #6
0
        public static DomainWeather ToDomainWeather(CurrentWeatherResponse currentWeatherResponse)
        {
            var wind          = new Wind(currentWeatherResponse.Wind.Speed, currentWeatherResponse.Wind.Deg);
            var precipitation = new Precipitation(currentWeatherResponse.Weather[0].Description);

            return(new DomainWeather(currentWeatherResponse.Main.Humidity, currentWeatherResponse.Main.Temp,
                                     currentWeatherResponse.Name, wind, precipitation));
        }
Exemple #7
0
 public static CurrentWeatherData ResponseToCurrentWeatherData(CurrentWeatherResponse response)
 {
     return(new CurrentWeatherData()
     {
         Station = new Station()
         {
             Latitude = response.lat,
             Longitude = response.lon,
             AltitudeF = response.alt_ft,
             AltitudeM = response.alt_m
         },
         Weather = new Weather()
         {
             Icon = response.wx_icon,
             Code = response.wx_code,
             Description = response.wx_desc
         },
         CloudTotal = response.cloudtotal_pct,
         DewPoint = new Temperature()
         {
             Celcius = response.dewpoint_c,
             Fahrenheit = response.dewpoint_f
         },
         Temperature = new Temperature()
         {
             Celcius = response.temp_c,
             Fahrenheit = response.temp_f
         },
         FeelsLikeTemperature = new Temperature()
         {
             Celcius = response.feelslike_c,
             Fahrenheit = response.feelslike_f
         },
         Humidity = response.humid_pct,
         Pressure = new SeaLevelPressure()
         {
             Inches = response.slp_in,
             Millibars = response.slp_mb
         },
         Visibility = new Visibility()
         {
             Kilometers = response.vis_km,
             Miles = response.vis_mi
         },
         Wind = new Wind()
         {
             DirectionCompass = response.winddir_compass,
             DirectionDeg = response.winddir_deg,
             Speed = new Speed
             {
                 Kmh = response.windspd_kmh,
                 Kts = response.windspd_kts,
                 Mph = response.windspd_mph,
                 Ms = response.windspd_ms
             }
         }
     });
 }
Exemple #8
0
        private WeatherLoad SerialiseResponse(CurrentWeatherResponse response)
        {
            //Setup WeatherLoad header data
            WeatherLoad weatherLoad = new WeatherLoad
            {
                WeatherProviderId = enumWeatherProvider.WP_OpenWeatherMap,
                ResponseId        = response.Sys is not null ? response.Sys.Id : null,
                Message           = response.Sys is not null?response.Sys.Message.ToString() : null,
                                        LoadStartDateTime_UTC = _requestStartDateTime.Value,
                                        LoadEndDateTime_UTC   = DateTime.Now.ToUniversalTime(),
                                        LoadDurationMs        = (int)_requestEndDateTime.Value.Subtract(_requestStartDateTime.Value).TotalMilliseconds,
                                        ResponseSizeBytes     = _responseSizeBytes,
                                        RecordCount           = 1
            };

            //Setup Weather Location Data
            WeatherLocation weatherLocation = new WeatherLocation
            {
                CountryISO = response.Sys is not null ? response.Sys.Country : null,
                CityName   = response.CityName,
                CityId     = response.CityId,
                Longitude  = response.Coordinates.Longitude,
                Latitude   = response.Coordinates.Latitude
            };

            //Setup Weather Readings
            WeatherReading weatherReading = new WeatherReading
            {
                WeatherDateTime_UTC      = DateTimeOffset.FromUnixTimeSeconds(response.TimeOfDataCalculation).UtcDateTime, //convert from unix time (seconds since jan 1, 1970)
                WeatherLocation          = weatherLocation,                                                                //Add location from above
                Temperature_C            = response.Main.Temperature,
                FeelsLike_C              = response.Main is not null ? response.Main.FeelsLike : null,
                TempMin_C                = response.Main is not null ? response.Main.TempMin : null,
                TempMax_C                = response.Main is not null ? response.Main.TempMax : null,
                Description              = response.Weather[0].Description,
                Pressure_hPA             = (short)response.Main.Pressure,
                Pressure_SeaLevel_hPA    = (short)response.Main.Pressure_SeaLevel_hPA,
                Pressure_GroundLevel_hPA = (short)response.Main.Pressure_GroundLevel_hPA,
                Humidity_Pct             = (short)response.Main.Humidity,
                WindSpeed_MS             = (short)response.Wind.Speed,
                WindSpeed_Deg            = (short)response.Wind.Deg,
                WindSpeed_Gust           = (short)response.Wind.Gust,
                CloudCover_Pct           = (short)response.Clouds.All,
                Rain1h_mm                = response.Rain is not null ? response.Rain.Rain1h : null,
                Rain3h_mm                = response.Rain is not null ? response.Rain.Rain3h : null,
                Snow1h_mm                = response.Snow is not null ? response.Snow.Snow1h : null,
                Snow3h_mm                = response.Snow is not null ? response.Snow.Snow3h : null,
                WeatherIconId            = response.Weather[0].Icon
            };

            //Add the weather reading to the WeatherLoad object
            weatherLoad.WeatherReadings = new List <Model.WeatherReading>();
            weatherLoad.WeatherReadings.Add(weatherReading);

            return(weatherLoad);
        }
    }
}
Exemple #9
0
 /// <summary>
 /// Worker thread which fetches weather info from OpenWeatherMapApi
 /// </summary>
 private async void FetchOpenWeatherMap__Worker()
 {
     await Task.Run(async() =>
     {
         while (true)
         {
             WeatherData = await _weatherMapClient.CurrentWeather.GetByName(SearchCity);
             Thread.Sleep(1250);
         }
     });
 }
        private static Common.Weather.WeatherPoint ConvertToWeatherPoint(CurrentWeatherResponse source) {
            var destination = new Common.Weather.WeatherPoint();

            destination.Location = ConvertToLocation(source);
            destination.Weather = ConvertToWeatherPointData(source);
            if (source.Timestamp.HasValue) {
                destination.Timestamp = UnixToDateTime(source.Timestamp.Value);
            }
            destination.SunAltitude = null;

            return destination;
        }
 private WeatherForecastResponse ConvertToServiceModel(CurrentWeatherResponse currentWeather, WeatherForecastRequest request)
 {
     return(new WeatherForecastResponse
     {
         Location = request.Location,
         Tempreature = new Tempreature
         {
             Format = "Celsius",
             Value = currentWeather.Temperature.Value
         },
         Humidity = currentWeather.Humidity.Value
     });
 }
        public async Task <CurrentWeatherResponse> GetWeather()
        {
            if (lastMeasureTime.AddMinutes(2) > DateTime.Now)
            {
                return(currentWeather);
            }

            currentWeather = await client.CurrentWeather.GetByName(locationId, MetricSystem.Metric);

            lastMeasureTime = DateTime.Now;

            return(currentWeather);
        }
 public void TestAllProperties(CurrentWeatherResponse response)
 {
     Assert.IsNotNull(response);
     Assert.IsNotNull(response.City);
     Assert.IsNotNull(response.Clouds);
     Assert.IsNotNull(response.Humidity);
     Assert.IsNotNull(response.LastUpdate);
     Assert.IsNotNull(response.Precipitation);
     Assert.IsNotNull(response.Pressure);
     Assert.IsNotNull(response.Temperature);
     Assert.IsNotNull(response.Weather);
     Assert.IsNotNull(response.Wind);
 }
 public byte[] ToJson(CurrentWeatherResponse weather)
 {
     Celsius       = RoundMeasurement(weather.Temperature.Value, 2).ToString();
     CelsiusMin    = RoundMeasurement(weather.Temperature.Min, 2).ToString();
     CelsiusMax    = RoundMeasurement(weather.Temperature.Max, 2).ToString();
     Cloud         = RoundMeasurement(weather.Clouds.Value, 2).ToString();
     HPa           = RoundMeasurement(weather.Pressure.Value, 0).ToString();
     Humidity      = RoundMeasurement(weather.Humidity.Value, 2).ToString();
     WindSpeed     = RoundMeasurement(weather.Wind.Speed.Value, 0).ToString();
     WindDirection = RoundMeasurement(weather.Wind.Direction.Value, 0).ToString();
     Id            = ++msgCount;
     return(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(this)));
 }
        public ForecastServiceTest()
        {
            _openWeatherMapConfig = new OpenWeatherMapConfig {
                IconUrl = "fakeurl/{0}.png"
            };
            _mockMapper                = new Mock <IMapper>();
            _mockGetForecastFunc       = new Mock <Func <string, string, string, Task <WeatherForecastResponse> > >();
            _mockGetCurrentWeatherFunc = new Mock <Func <string, string, string, Task <CurrentWeatherResponse> > >();
            _mapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new WeatherForecastMappingProfile());
            }).CreateMapper();

            _mockCurrentWeatherResponse = new CurrentWeatherResponse()
            {
                DateUnixFormat = 1590144273,
                WeatherInfo    = new WeatherCondition {
                    Temperature = 69.55, Humidity = 50
                },
                WindData = new Wind {
                    Speed = 9.53
                },
                WeatherData = new WeatherResponse[] { new WeatherResponse {
                                                          Icon = "04d"
                                                      } }
            };

            _mockWeatherForecastResponse = new WeatherForecastResponse()
            {
                CityData = new City {
                    Name = "Hamburg", Country = "DE"
                },
                ForecastData = new ForecastResponse[] {
                    new ForecastResponse {
                        DateUnixFormat = 1590559200,
                        WeatherInfo    = new WeatherCondition {
                            Temperature = 69.55,
                            Humidity    = 50
                        },
                        WindData = new Wind()
                        {
                            Speed = 9.53
                        },
                        WeatherData = new WeatherResponse[] { new WeatherResponse {
                                                                  Icon = "04d"
                                                              } }
                    }
                }
            };
        }
Exemple #16
0
        /// <summary>
        /// Current weather data API response
        /// </summary>
        /// <param name="coordinates"></param>
        /// <returns></returns>
        public CurrentWeatherResponse GetCurrentWeather(Coordinates coordinates)
        {
            var oneCallResponse = GetCurrentAndForecastWeather(coordinates, new List <Exclude>()
            {
                Exclude.Alerts, Exclude.Minutely, Exclude.Hourly, Exclude.Daily
            });
            var response = new CurrentWeatherResponse
            {
                Latitude       = oneCallResponse.Latitude,
                Longitude      = oneCallResponse.Longitude,
                Timezone       = oneCallResponse.Timezone,
                TimezoneOffset = oneCallResponse.TimezoneOffset,
                CurrentWeather = oneCallResponse.CurrentWeather
            };

            return(response);
        }
Exemple #17
0
        public static async Task <double> GetCurrentTemperature(double latitude, double longitude)
        {
            OpenWeatherMapClient webClient = new OpenWeatherMapClient("e66f368a625694e6acc918fd6c845ad7");

            try
            {
                CurrentWeatherResponse response = await webClient.CurrentWeather.GetByCoordinates(new Coordinates { Latitude = latitude, Longitude = longitude },
                                                                                                  MetricSystem.Metric);

                return(response.Temperature.Value);
            }
            catch (Exception ex)
            {
                // Internet is not available
                return(double.NaN);
            }
        }
        public void ApiService_Should_Return_A_CurrentWeather_For_Beijing()
        {
            using (var scope = CoreServiceLocator.Current.GetIocContainer().BeginLifetimeScope())
            {
                //ARRANGE
                var city    = "Beijing";
                var country = "China";
                var service = scope.Resolve <IOpenWeatherMapApiService>();

                //ASSERT
                var weather = new CurrentWeatherResponse();

                weather = service.SearchCurrentWeatherByCity(city, country);

                //ACT
                Assert.IsNotNull(weather, "OpenWeather API service should return current weather for Beijing.");
                Assert.IsTrue(weather.City.Name.ToLower().Equals("beijing"), "OpenWeather API service should return Beijing's weather.");
            }
        }
Exemple #19
0
        public void WeatherSubject_Notify()
        {
            //Setup
            WeatherSubject_Attach();

            //Arrange
            CurrentWeatherResponse data = null;

            subject.SearchCity = "Eindhoven";

            //Act
            Task t = Task.Run(async() => {
                data = await weatherMapClient.CurrentWeather.GetByName("Eindhoven");
            }); Task.WaitAll(t);

            subject.WeatherData = data;

            //Assert
            Assert.AreEqual(subject.WeatherData, observer.WeatherDataUi);
        }
        public async Task <CurrentWeatherResponse> GetCurrentWeather(GetCurrentWeatherRequest request)
        {
            CurrentWeatherResponse result = null;
            string     content            = "";
            HttpClient client             = new HttpClient();

            client.BaseAddress = new Uri(baseUrl);
            WeatherDbDataContext db = new WeatherDbDataContext(connectString);

            //Create new Employee

            weather weather = db.weathers.FirstOrDefault(x => x.key == request.Key);

            if (weather != null)
            {
                return(new CurrentWeatherResponse {
                    text = weather.WeatherText, value = double.Parse(weather.celsius)
                });
            }
            else
            {
                HttpResponseMessage response = client.GetAsync(baseUrl + "currentconditions/v1/" + request.Key + "?apikey=" + apiKey).Result;
                if (response.IsSuccessStatusCode)
                {
                    content = await response.Content.ReadAsStringAsync();

                    var list = JsonConvert.DeserializeObject <List <CurrentWeather> >(content);
                    if (list.Count > 0)
                    {
                        result = new CurrentWeatherResponse {
                            text = list[0].WeatherText, value = list[0].temperature.metric.Value
                        };
                        db.weathers.InsertOnSubmit(new weather {
                            celsius = result.value.ToString(), key = request.Key, WeatherText = result.text
                        });
                        db.SubmitChanges();
                    }
                }
            }
            return(result);
        }
Exemple #21
0
 private bool CompareCurrentData(CurrentWeatherData currentWeatherData, CurrentWeatherResponse response)
 {
     return
         // station
         (currentWeatherData.Station.Latitude == response.lat &&
          currentWeatherData.Station.Longitude == response.lon &&
          currentWeatherData.Station.AltitudeF == response.alt_ft &&
          currentWeatherData.Station.AltitudeM == response.alt_m
          // weather
          && string.Equals(currentWeatherData.Weather.Description, response.wx_desc) &&
          currentWeatherData.Weather.Code == response.wx_code
          //&& string.Equals(currentWeatherData.Weather.Icon, response.wx_icon)
          // temperature
          && currentWeatherData.Temperature.Celcius == response.temp_c &&
          currentWeatherData.Temperature.Fahrenheit == response.temp_f
          // feelslike temperature
          && currentWeatherData.FeelsLikeTemperature.Celcius == response.feelslike_c &&
          currentWeatherData.FeelsLikeTemperature.Fahrenheit == response.feelslike_f
          // wind
          && currentWeatherData.Wind.Speed.Mph == response.windspd_mph &&
          currentWeatherData.Wind.Speed.Kmh == response.windspd_kmh &&
          currentWeatherData.Wind.Speed.Kts == response.windspd_kts &&
          currentWeatherData.Wind.Speed.Ms == response.windspd_ms &&
          currentWeatherData.Wind.DirectionDeg == response.winddir_deg &&
          string.Equals(currentWeatherData.Wind.DirectionCompass, response.winddir_compass)
          // humidity
          && currentWeatherData.Humidity == response.humid_pct
          // cloudtotal
          && currentWeatherData.CloudTotal == response.cloudtotal_pct
          // visibility
          && currentWeatherData.Visibility.Kilometers == response.vis_km &&
          currentWeatherData.Visibility.Miles == response.vis_mi
          // pressure
          && currentWeatherData.Pressure.Inches == response.slp_in &&
          currentWeatherData.Pressure.Millibars == response.slp_mb
          // dewpoint
          && currentWeatherData.DewPoint.Celcius == response.dewpoint_c &&
          currentWeatherData.DewPoint.Fahrenheit == response.dewpoint_f);
 }
        /// <summary>
        /// Get Current Weather using longitude and latitude
        /// </summary>
        /// <param name="longitude">Longitude</param>
        /// <param name="latitude">Latitude</param>
        /// <param name="temperatureUnit">Temperature Unit - Imperial by default.</param>
        /// <returns></returns>
        public async Task <CurrentWeatherResponse> GetCurrentWeatherByCoords(double longitude, double latitude, TemperatureUnit temperatureUnit = TemperatureUnit.Imperial)
        {
            var parameters = new Dictionary <string, string>()
            {
                { "lat", $"{latitude}" },
                { "lon", $"{longitude}" },
                { "units", temperatureUnit.ToString() }
            };

            HttpResponseMessage response;

            using (_client)
            {
                response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, BuildUri(@"https://api.openweathermap.org/data/2.5/weather", parameters)));
            }

            if (response.IsSuccessStatusCode)
            {
                return(CurrentWeatherResponse.FromJson(await response.Content.ReadAsStringAsync()));
            }

            throw new Exception(await response.Content.ReadAsStringAsync());
        }
        public CommandResult ProcessMessage(Update inUpdate)
        {
            //ResponseMessage resMes = null;
            //if (inUpdate.Type == Telegram.Bot.Types.Enums.UpdateType.EditedMessage)
            //    resMes = new QuoteTextResponseMessage(inUpdate.EditedMessage, "Не хорошо править старые сообщения");
            //else
            //{
            //    resMes = new TextResponseMessage(inUpdate.Message, $"Echo: {inUpdate.Message.Text.Substring(0, Math.Min(255, inUpdate.Message.Text?.Length ?? 0))}");
            //}
            //return new CommandResult(resMes, false);

            CurrentWeatherResponse weather = null;

            if (inUpdate.Message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
            {
                // try to get weather base on place name
                weather = GetWeatherByName(inUpdate.Message.Text);
            }
            if (inUpdate.Message.Type == Telegram.Bot.Types.Enums.MessageType.LocationMessage)
            {
                weather = GetWeatherByLocation(inUpdate.Message.Location.Longitude, inUpdate.Message.Location.Latitude);
            }

            ResponseMessage resMes = null;

            // Подготовка результата
            if (weather == null)
            {
                resMes = new TextResponseMessage(inUpdate.Message, "Не удалось определить погоду");
            }
            else
            {
                resMes = new TextResponseMessage(inUpdate.Message, weather.ConvertWeatherInText());
            }

            return(new CommandResult(resMes, true));
        }
        public async Task <DailyWeatherSummary> GetWeatherSummary(
            String cityName)
        {
            try
            {
                CurrentWeatherResponse response =
                    await _client.CurrentWeather
                    .GetByName(cityName, MetricSystem.Metric);

                return(new DailyWeatherSummary
                {
                    City = response.City.Name,
                    Description = response.Weather.Value,
                    ImagePath = BuildImagePath(response.Weather.Icon),
                    Temperature = response.Temperature.Value,
                    TemperatureFrom = response.Temperature.Min,
                    TemperatureTo = response.Temperature.Max
                });
            }
            catch (Exception)
            {
                return(null);
            }
        }
        private static Common.Weather.WeatherPointData ConvertToWeatherPointData(CurrentWeatherResponse source) {
            var destination = new Common.Weather.WeatherPointData();

            if (source.Main != null) {
                destination.Pressure = source.Main.Pressure;
                if (source.Main.Temperature.HasValue) {
                    destination.Temperature = new Temperature() { Kelvin = source.Main.Temperature.Value };
                }
                destination.Humidity = source.Main.Humidity;
                if (source.Clouds != null) {
                    destination.CloudCover = source.Clouds.CloudCover;
                }
                if (source.WeatherConditions != null && source.WeatherConditions.Count > 0) {
                    destination.Condition = ConvertToWeatherCondition(source.WeatherConditions[0].Id);
                } else {
                    destination.Condition = WeatherCondition.Unknown;
                }

                if (source.Wind != null) {
                    destination.WindDirection = source.Wind.Direction;
                    destination.WindSpeed = source.Wind.Speed;
                }

                if (source.Snow != null) {
                    destination.PrecipitationType = PrecipitationType.Snow;
                    destination.Precipitation = source.Snow.Last3Hours;
                } else if (source.Rain != null) {
                    destination.PrecipitationType = PrecipitationType.Rain;
                    destination.Precipitation = source.Rain.Last3Hours;
                }

                destination.DewPoint = null;
                destination.FeltHumidity = null;
                destination.FeltIntensity = null;
                destination.FeltTemperature = null;
                destination.FeltVisibility = null;
                destination.FeltWindIntensity = null;
                destination.Ozone = null;
                destination.Visibility = null;
                destination.WindChill = null;
            }

            return destination;
        }
        private static Common.Weather.Location ConvertToLocation(CurrentWeatherResponse source) {
            var destination = new Common.Weather.Location();

            destination.Country = source.WeatherLocation.CountryCode;
            destination.Latitude = source.Coordinates.Latitude;
            destination.Longitude = source.Coordinates.Longitude;
            destination.Locality = null;

            return destination;
        }
Exemple #27
0
 public WeatherSubject() : base()
 {
     _weatherData      = new CurrentWeatherResponse();
     _weatherMapClient = new OpenWeatherMapClient("c29ea3be75bc79b4fd54b5ea53cdd6aa");
     FetchOpenWeatherMap__Worker();
 }
 /// <summary>
 /// Simple convertation weather response to string
 /// </summary>
 /// <param name="weather"></param>
 /// <returns></returns>
 public static string ConvertWeatherInText(this CurrentWeatherResponse weather)
 {
     return($"Погода в {weather.City.Name}: t°={weather.Temperature.Value}°C (min: {weather.Temperature.Min}°C, max: {weather.Temperature.Max}°C)" +
            $", w={weather.Wind.Speed.Value}м/с ({weather.Wind.Direction.Name})");
 }
 public void TestAllProperties(CurrentWeatherResponse response)
 {
     Assert.IsNotNull(response);
     Assert.IsNotNull(response.City);
     Assert.IsNotNull(response.Clouds);
     Assert.IsNotNull(response.Humidity);
     Assert.IsNotNull(response.LastUpdate);
     Assert.IsNotNull(response.Precipitation);
     Assert.IsNotNull(response.Pressure);
     Assert.IsNotNull(response.Temperature);
     Assert.IsNotNull(response.Weather);
     Assert.IsNotNull(response.Wind);
 }
Exemple #30
0
        private async void LoadWeather()
        {
            OpenWeatherMapClient client = null;

            try
            {
                client = new OpenWeatherMapClient("c6b82ccf5c40a3479dff0d236e06bc53");

                if (client != null)
                {
                    //string m_Location = "Lahore,PK";
                    //int m_LocationID = 1172451;

                    //string m_Location = "Rawalpindi,PK";
                    //int m_LocationID = 1166993;

                    string m_Location   = "Sargodha,PK";
                    int    m_LocationID = 1166000;

                    //string m_Location = "Pattoki, PK";
                    //int m_LocationID = 1168226;

                    //string m_Location = "Islamabad, PK";
                    //int m_LocationID = 1176615;

                    //string m_Location = "Kot Momin, PK";
                    //int m_LocationID = 1182787;

                    bool m_Degree = true;


                    CurrentWeatherResponse currentWeather = null;

                    if (!m_Degree)
                    {
                        currentWeather = await client.CurrentWeather.GetByCityId(m_LocationID, MetricSystem.Imperial);
                    }
                    else
                    {
                        currentWeather = await client.CurrentWeather.GetByCityId(m_LocationID, MetricSystem.Metric);
                    }

                    //set city
                    v_City.Text = currentWeather.City.Name;
                    lstWeatherData.Clear();
                    lstWeatherData.Add(LoadWeatherData(currentWeather.Weather.Icon, currentWeather.Temperature, false, System.DateTime.Now));

                    int forecastDays = 4;

                    if (forecastDays > 1)
                    {
                        ForecastResponse forecast = null;

                        if (!m_Degree)
                        {
                            forecast = await client.Forecast.GetByCityId(m_LocationID, true, MetricSystem.Imperial, OpenWeatherMapLanguage.EN, forecastDays);
                        }
                        else
                        {
                            forecast = await client.Forecast.GetByCityId(m_LocationID, true, MetricSystem.Metric, OpenWeatherMapLanguage.EN, forecastDays);
                        }

                        foreach (ForecastTime forecastTime in forecast.Forecast)
                        {
                            if (forecastTime.Day.Date != System.DateTime.Now.Date)
                            {
                                lstWeatherData.Add(LoadWeatherData(forecastTime.Symbol.Var, forecastTime.Temperature, true, forecastTime.Day));
                            }
                        }
                    }

                    WeatherList.ItemsSource = lstWeatherData;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Weather exception " + ex.Message);
            }
        }
        public static async Task GetCurrentWeather()
        {
            ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;

            string lat       = (string)ApplicationData.Current.LocalSettings.Values["Latitude"];
            double latitude  = double.Parse(lat);
            string lon       = (string)ApplicationData.Current.LocalSettings.Values["Longitude"];
            double longitude = double.Parse(lon);
            var    client    = new OpenWeatherMapClient((string)ApplicationData.Current.LocalSettings.Values["WeatherAPI"]);
            CurrentWeatherResponse result = null;
            Task getWeather = Task.Run(async() => { result = await client.CurrentWeather.GetByCoordinates(new Coordinates {
                    Latitude = latitude, Longitude = longitude
                }).ConfigureAwait(true); });

            getWeather.Wait();
            if (result.Weather.Icon != null)
            {
                if (result.Weather.Icon.ToString() == "01d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 0;
                }
                else if (result.Weather.Icon.ToString() == "01n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 1;
                }
                else if (result.Weather.Icon.ToString() == "02d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 2;
                }
                else if (result.Weather.Icon.ToString() == "02n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 3;
                }
                else if (result.Weather.Icon.ToString() == "03d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 4;
                }
                else if (result.Weather.Icon.ToString() == "03n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 5;
                }
                else if (result.Weather.Icon.ToString() == "04d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 6;
                }
                else if (result.Weather.Icon.ToString() == "04n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 7;
                }
                else if (result.Weather.Icon.ToString() == "09d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 8;
                }
                else if (result.Weather.Icon.ToString() == "09n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 9;
                }
                else if (result.Weather.Icon.ToString() == "10d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 10;
                }
                else if (result.Weather.Icon.ToString() == "10n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 11;
                }
                else if (result.Weather.Icon.ToString() == "11d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 12;
                }
                else if (result.Weather.Icon.ToString() == "11n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 13;
                }
                else if (result.Weather.Icon.ToString() == "13d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 14;
                }
                else if (result.Weather.Icon.ToString() == "13n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 15;
                }
                else if (result.Weather.Icon.ToString() == "50d")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 16;
                }
                else if (result.Weather.Icon.ToString() == "50n")
                {
                    ApplicationData.Current.LocalSettings.Values["WeatherImageID"] = 17;
                }
            }
            else
            {
                Libraries.SendToast.SendToasts("OpenWeatherMap is not responding. API Key may not be valid.");
            }
        }
 public async Task <bool> SetCurrentWeatherAsync(CurrentWeatherResponse currentWeatherResponse)
 {
     return(await _redisDataAgent.SetStringValueAsync(CURRENT_WEATHER_KEY, JsonConvert.SerializeObject(currentWeatherResponse), TimeSpan.FromMinutes(30)));
 }
 public object GetValue(CurrentWeatherResponse weatherResponse)
 {
     return(_valueFunc.Invoke(weatherResponse));
 }