예제 #1
0
        public CurrentConditions GetCurrentConditions(string zipCode)
        {
            WeatherUndergroundClient  wuClient = new WeatherUndergroundClient();
            CurrentConditionsResponse response = wuClient.GetCurrentConditions(zipCode);

            return(this.MapCurrentConditionsResponse(response));
        }
예제 #2
0
        /// <summary>
        /// Action that calls the Weather Underground library directly
        /// </summary>
        /// <param name="zipCode"></param>
        /// <returns></returns>
        public ActionResult Index(String zipCode = null)
        {
            if (String.IsNullOrWhiteSpace(zipCode))
            {
                zipCode = "53211";
            }


            WeatherUndergroundClient  weatherClient     = new WeatherUndergroundClient();
            CurrentConditionsResponse currentConditions = weatherClient.GetCurrentConditions(zipCode);

            HomeIndexModel model = new HomeIndexModel()
            {
                WeatherData = currentConditions
            };

            return(View(model));
        }
    private CurrentWeather MapCurrentConditionsResponse(CurrentConditionsResponse apiResponse)
    {
        if (apiResponse == null)
        {
            return new CurrentWeather()
                   {
                       ErrorMessage = "Null received from Open Weather Map API",
                       Success      = false
                   }
        }
        ;

        var currentConditions = new CurrentWeather()
        {
            Success      = true,
            ErrorMessage = String.Empty,
            Location     = new CurrentWeather.LocationData()
            {
                Name      = apiResponse.Name,
                Latitude  = apiResponse.Coordintates.Latitude,
                Longitude = apiResponse.Coordintates.Longitude
            },
            ObservationTime    = DateTimeOffset.FromUnixTimeSeconds(apiResponse.ObservationTime + apiResponse.TimezoneOffset).DateTime,
            ObservationTimeUtc = DateTimeOffset.FromUnixTimeSeconds(apiResponse.ObservationTime).DateTime,
            CurrentConditions  = new CurrentWeather.WeatherData()
            {
                Conditions            = apiResponse.ObservedConditions.FirstOrDefault()?.Conditions,
                ConditionsDescription = apiResponse.ObservedConditions.FirstOrDefault()?.ConditionsDetail,
                Visibility            = apiResponse.Visibility / 1609.0, // Visibility always comes back in meters, even when imperial requested
                CloudCover            = apiResponse.Clouds.CloudCover,
                Temperature           = apiResponse.ObservationData.Temperature,
                Humidity             = apiResponse.ObservationData.Humidity,
                Pressure             = apiResponse.ObservationData.Pressure * 0.0295301, // Pressure always comes back in millibars, even when imperial requested
                WindSpeed            = apiResponse.WindData.Speed,
                WindDirection        = CompassDirection.GetDirection(apiResponse.WindData.Degrees),
                WindDirectionDegrees = apiResponse.WindData.Degrees,
                RainfallOneHour      = apiResponse.Rain?.RainfallOneHour ?? 0.0
            },
            FetchTime = DateTime.Now
        };

        return(currentConditions);
    }
        public async Task <CurrentConditionsResponse> GetCurrentConditions(string locationKey)
        {
            CurrentConditionsResponse currentConditionsResponse = null;

            try
            {
                var        url    = "http://dataservice.accuweather.com/currentconditions/v1/" + locationKey + "/?apikey=" + apiKeyToken;
                HttpClient client = new HttpClient();
                string     json   = await client.GetStringAsync(url);

                currentConditionsResponse = (Newtonsoft.Json.JsonConvert.DeserializeObject <CurrentConditionsResponse[]>(json)).FirstOrDefault();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(currentConditionsResponse);
        }
예제 #5
0
        /// <summary>
        /// A simple mapper method that maps the response we get from WeatherUnderground to our standard response object
        /// for current conditions
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        internal CurrentConditions MapCurrentConditionsResponse(CurrentConditionsResponse response)
        {
            CurrentConditions currentConditions = new CurrentConditions();

            // I took the name and location from the display location.  You could choose to map it from the measurement location
            currentConditions.Source          = "Weather Underground";
            currentConditions.LocationName    = response.current_observation.display_location.full;
            currentConditions.Latitide        = Convert.ToDouble(response.current_observation.display_location.latitude);
            currentConditions.Longitude       = Convert.ToDouble(response.current_observation.display_location.longitude);
            currentConditions.ObservationTime = DateTime.Parse(response.current_observation.local_time_rfc822);

            currentConditions.ConditionsDescription = response.current_observation.weather;
            currentConditions.Temperature           = response.current_observation.temp_f;
            currentConditions.Humidity  = Convert.ToDouble(response.current_observation.relative_humidity.Replace('%', ' '));
            currentConditions.Dewpoint  = response.current_observation.dewpoint_f;
            currentConditions.Windchill = this.ConvertWindchillString(response.current_observation.windchill_f);

            currentConditions.WindSpeed            = response.current_observation.wind_mph;
            currentConditions.WindDirectionDegrees = response.current_observation.wind_degrees;
            currentConditions.WindDirection        = response.current_observation.wind_dir;

            return(currentConditions);
        }
        /// <summary>
        /// Gets the current weather conditions for a given latitude and longitude
        /// </summary>
        /// <param name="lat">Latitude</param>
        /// <param name="lng">Longitude</param>
        /// <returns>A CurrentConditionsResponse containing current weather data conditions.</returns>
        public async Task <CurrentConditionsResponse> GetCurrentConditionsAsync(decimal lat, decimal lng)
        {
            CurrentConditionsResponse response = null;

            //Get the current list of stations for the given latitude and longitude.
            var redirectResponseText = await webClient.GetAsync($"https://api.weather.gov/points/{ lat.ToString("0.####") },{ lng.ToString("0.####") }");

            //Parse the json response
            dynamic json = JObject.Parse(redirectResponseText);

            //Get the URL of the observation stations from the response
            var observationStationsUrl = (string)json.properties.observationStations;

            //Load the observation stations URL from the API
            var observationResponseText = await webClient.GetAsync(observationStationsUrl);

            //Parse the json response
            dynamic json2 = JObject.Parse(observationResponseText);

            //The station list is a property in the response called "features"
            var stations = json2.features;

            //Ensure we have a list of stations
            if (stations != null && stations.Count > 0)
            {
                //Loop over the list of stations
                for (int i = 0; i < stations.Count; i++)
                {
                    var s = stations[i];

                    if (s != null)
                    {
                        //We have a station. Instantiate a WeatherStation object and fill some properties.
                        var station = new WeatherStation()
                        {
                            Name = s.properties.name,
                            StationIdentifier = s.properties.stationIdentifier,
                            ElevationInMeters = 0,
                            Latitude          = 0,
                            Longitude         = 0
                        };

                        if (s.properties.elevation.value != null)
                        {
                            station.ElevationInMeters = s.properties.elevation.value;
                        }

                        if (s.geometry.coordinates[0] != null)
                        {
                            station.Longitude = s.geometry.coordinates[0];
                        }

                        if (s.geometry.coordinates[1] != null)
                        {
                            station.Latitude = s.geometry.coordinates[1];
                        }

                        //Attempt to get the current conditions for the station provided.
                        response = await GetCurrentConditionsForStationAsync(station);
                    }

                    //If we have current conditions, return it. Otherwise, continue through loop.
                    if (response != null)
                    {
                        break;
                    }
                }
            }

            return(response);
        }
        async Task <CurrentConditionsResponse> GetCurrentConditionsForStationAsync(WeatherStation station)
        {
            if (station != null)
            {
                //Get the current observations for the provided weather station
                var observationsText = await webClient.GetAsync($"https://api.weather.gov/stations/{ station.StationIdentifier }/observations/latest");

                //Parse the json response
                dynamic json = JObject.Parse(observationsText);

                //Get the list of properties which contain the current condition values
                dynamic properties = json.properties;

                //Instantiate a CurrentConditionsResponse and fill with the properties
                var response = new CurrentConditionsResponse
                {
                    WeatherStation             = station,
                    TextDescription            = properties.textDescription,
                    ObservationDate            = properties.timestamp,
                    TemperatureCelsius         = TryConvertToDecimal(properties.temperature.value),
                    DewPointCelsius            = TryConvertToDecimal(properties.dewpoint.value),
                    WindDirection              = TryConvertToDecimal(properties.windDirection.value),
                    WindSpeedKilometersPerHour = TryConvertToDecimal(properties.windSpeed.value),
                    WindGustKilometersPerHour  = TryConvertToDecimal(properties.windGust.value),
                    BarometricPressure         = TryConvertToDecimal(properties.barometricPressure.value),
                    SeaLevelPressure           = TryConvertToDecimal(properties.seaLevelPressure.value),
                    VisibilityMeters           = TryConvertToDecimal(properties.visibility.value),
                    RelativeHumidityPercent    = TryConvertToDecimal(properties.relativeHumidity.value),
                    WindChillCelsius           = TryConvertToDecimal(properties.windChill.value),
                    HeatIndexCelsius           = TryConvertToDecimal(properties.heatIndex.value)
                };

                //Convert celsius to fahrenheit

                if (response.TemperatureCelsius.HasValue)
                {
                    response.TemperatureFahrenheit = Utilities.ConvertCelsiusToFahrenheit(response.TemperatureCelsius.Value);
                }

                if (response.DewPointCelsius.HasValue)
                {
                    response.DewPointFahrenheit = Utilities.ConvertCelsiusToFahrenheit(response.DewPointCelsius.Value);
                }

                if (response.WindChillCelsius.HasValue)
                {
                    response.WindChillFahrenheit = Utilities.ConvertCelsiusToFahrenheit(response.WindChillCelsius.Value);
                }

                if (response.HeatIndexCelsius.HasValue)
                {
                    response.HeatIndexFahrenheit = Utilities.ConvertCelsiusToFahrenheit(response.HeatIndexCelsius.Value);
                }

                if (response.WindSpeedKilometersPerHour.HasValue)
                {
                    response.WindSpeedMilesPerHour = Utilities.ConvertKilometersPerHourToMilesPerHour(response.WindSpeedKilometersPerHour.Value);
                }

                if (response.WindGustKilometersPerHour.HasValue)
                {
                    response.WindGustMilesPerHour = Utilities.ConvertKilometersPerHourToMilesPerHour(response.WindGustKilometersPerHour.Value);
                }

                response.RawData = observationsText;

                response.Station = station;

                return(response);
            }

            return(null);
        }