private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Background = new SolidColorBrush(Colors.Black);

            _wakeUpDetector = new WakeUpDetector();
            _wakeUpDetector.WakeUpConfirmedEvent += WakeUpDetectorOnWakeUpConfirmedEvent;
            _wakeUpDetector.WakeUpProgressEvent  += WakeUpDetectorOnWakeUpProgressEvent;

            _musicPlayer = new MusicPlayer();

            var request = new ForecastIORequest("1151936ce22897f529d08c57a1e8bb71", 40.579219f, -111.999608f, Unit.us);

            _forecast = request.Get();

            StartClock();

            if (_wakeUpDetector.StartDetection())
            {
                Background = new SolidColorBrush(Colors.Black);

                //Begin playing alarm clock sound on loop
                _musicPlayer.InitAudioAsset("AlarmClock.wav", true);
                _musicPlayer.PlayMusic();
            }
            else //Could not load Kinect Sensor. Just skip it.
            {
                _wakeUpDetector.Dispose();
                DoWakeupRoutine();
            }
        }
示例#2
0
    public static Forecast GetForecast()
    {
        try {
            var excludeBlocks = new Exclude[]
            {
                Exclude.alerts,
                Exclude.minutely,
                Exclude.hourly,
                //Exclude.daily,
                Exclude.flags
            };

            var request  = new ForecastIORequest(ApiKey, 46.280613f, -119.340984f, DateTime.Now, Unit.us, null, excludeBlocks);
            var forecast = request.Get();
            return(new Forecast(forecast.daily.data[0].apparentTemperatureMax,
                                forecast.daily.data[0].apparentTemperatureMin,
                                forecast.currently.temperature,
                                forecast.currently.summary,
                                forecast.currently.icon));
        }
        catch (WebException ex)
        {
            return(new Forecast(0, 0, 0, "The weather man called in sick.", "broken"));
        }
    }
示例#3
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "location/{location}")] HttpRequestMessage req, string location, TraceWriter log)
        {
            log.Info("location function received request for location: " + location);
            var helptext  = "Please provide a location in the format of latitude,longitude e.g. for Melbourne Australia /api/location/-37.8136,-144.9631";
            var errortext = "Internal error please contact admin";

            var darkskysecret = Environment.GetEnvironmentVariable("DarkSkyApiSecret", EnvironmentVariableTarget.Process);

            if (string.IsNullOrWhiteSpace(darkskysecret))
            {
                log.Error("Couldn't read darksky api key");
                return(req.CreateResponse(HttpStatusCode.InternalServerError, errortext));
            }

            if (location.Equals("{location}") || string.IsNullOrWhiteSpace(location))
            {
                log.Verbose("Location parameter was missing");
                return(req.CreateResponse(HttpStatusCode.OK, helptext));
            }

            var request            = new ForecastIORequest(darkskysecret, Parselatitude(location), Parselongitude(location), Unit.si);
            var forecastIoResponse = request.Get();

            string[] noumbrellaicons;
            string   icon;
            var      response = MakeUmbrellaResponse(forecastIoResponse, out noumbrellaicons, out icon);

            return(req.CreateResponse(HttpStatusCode.OK, response));
        }
示例#4
0
        private static void ForecastTest(double latitude, double longitude)
        {
            var request  = new ForecastIORequest("301feb278328af0b36ee03aa2f184c58", (float)latitude, (float)longitude, Unit.si);
            var response = request.Get();

            Console.WriteLine(response.currently.temperature);
        }
        public ActualWeatherEntry GetActualWeatherEntryApi(float Lat, float Long, DateTime day)
        {
            var excludeBlocks = new Exclude[]
            {
                Exclude.alerts,
                Exclude.currently
            };

            var request    = new ForecastIORequest("4ad8e97b2cd0133665a1e30b43fa7973", Lat, Long, day, Unit.us);
            var response   = request.Get().daily;
            var returnObj  = new ActualWeatherEntry();
            var dayWeather = response.data.First();

            returnObj.ActualHi     = dayWeather.temperatureMax;
            returnObj.ActualLow    = dayWeather.temperatureMin;
            returnObj.ActualPrecip = dayWeather.precipType != null;
            if (dayWeather.precipType != null)
            {
                returnObj.ActualPrecipType = dayWeather.precipType;
            }
            if (returnObj.ActualPrecipType != null && returnObj.ActualPrecipType == "snow")
            {
                returnObj.ActualPrecipAmount = dayWeather.precipAccumulation;
            }
            return(returnObj);
        }
        public IWeatherData GetWeatherData(IToponymData toponym)
        {
            var request  = new ForecastIORequest(_apiKey, (float)toponym.Latitude, (float)toponym.Longitude, Unit.si);
            var response = request.Get();

            return(new ForecastWeatherData(response));
        }
        public List <Weather> GetWeather(DateRange dateRange, Location location)
        {
            var result = new List <Weather>();
            var day    = dateRange.From;

            while (day <= dateRange.To)
            {
                var request  = new ForecastIORequest(ApiKey, (float)location.Latitude, (float)location.Longitude, day.Date, Unit.si);
                var response = request.Get();
                if (response.daily.data.Count > 0)
                {
                    var dailyForecast = response.daily.data[0];
                    var temp          = (dailyForecast.apparentTemperatureMax + dailyForecast.apparentTemperatureMin) / 2;
                    var cloudCover    = (int)(dailyForecast.cloudCover * 100);
                    var precip        = Precipitation.None;
                    if (dailyForecast.precipIntensity > 50)
                    {
                        precip = temp > 0 ? Precipitation.Rain : Precipitation.Snow;
                    }
                    var w = new Weather {
                        Date = day.Date, Temperature = temp, Cloudness = cloudCover, Precipitation = precip
                    };
                    result.Add(w);
                }
                day = day.AddDays(1);
            }

            return(result);
        }
示例#8
0
        public async void TestAsync()
        {
            var request  = new ForecastIORequest(key, 43.4499376f, -79.7880999f, Unit.si);
            var response = await request.GetAsync();

            Console.WriteLine(string.Format("Async Response: {0}", response.currently.apparentTemperature));
        }
示例#9
0
        public string returnXMLData2(List <LocationVars> list, Unit un)
        {
            //get request
            List <ForecastIOResponse> responces = new List <ForecastIOResponse>();

            foreach (var item in list)
            {
                var request = new ForecastIORequest("d9b0a7d6636dad5856be677f4c19e4f2", (float)item.Point.Latitude, (float)item.Point.Longitude, DateTime.Now, un);
                //response that contains all the current values
                responces.Add(request.Get());
            }
            ForecastIOResponse[] arr = responces.ToArray();
            var converted            = new XElement("Weatherforecast", from a in list
                                                    select new XElement("Location",
                                                                        new XAttribute("Name", a.LocationName),
                                                                        new XAttribute("Latitude", (float)a.Point.Latitude),
                                                                        new XAttribute("Longitude", (float)a.Point.Longitude),
                                                                        new XElement("Weather", new XElement("Temperature", arr[list.IndexOf(a)].currently.temperature + Location.unitvalue(un)),
                                                                                     new XElement("Humidity", arr[list.IndexOf(a)].currently.humidity),
                                                                                     new XElement("Visibility", arr[list.IndexOf(a)].currently.visibility),
                                                                                     new XElement("summary", arr[list.IndexOf(a)].currently.summary)

                                                                                     )));

            Console.WriteLine(converted);
            return(converted.ToString());
        }
        public async Task <WeatherData> GetWeather()
        {
            var settings = Properties.Settings.Default;
            var units    = settings.Celsius ? Unit.ca : Unit.us;
            var forecast = new ForecastIORequest(settings.ApiKey, settings.Latitude, settings.Longitude, units);
            var weather  = await forecast.Get();

            if (weather == null || weather.currently == null || weather.daily == null)
            {
                return(null);
            }
            var weatherData = new WeatherData
            {
                Location             = settings.LocationName,
                Celsius              = settings.Celsius,
                Icon                 = IconToMateocon(weather.currently.icon),
                CurrentTemperature   = Temperature(weather.currently.temperature),
                FeelsLikeTemperature = Temperature(weather.currently.apparentTemperature),
                Summary              = weather.currently.summary ?? "N/A",
                LongSummary          = weather.daily.summary ?? "N/A",
                Wind                 = WindSummary(weather.currently.windSpeed, weather.currently.windBearing, settings.Celsius),
                Humidity             = Probability(weather.currently.humidity),
                Time                 = weather.currently.time.ToDateTime().ToLocalTime().ToShortTimeString(),
                PoweredBy            = "Powered by Forecast",
                Link                 = "http://forecast.io",
                Alert                = (weather.alerts != null && weather.alerts.Count > 0) ? weather.alerts[0].title : string.Empty,
                AlertLink            = (weather.alerts != null && weather.alerts.Count > 0) ? weather.alerts[0].uri : string.Empty,
                Forecasts            = new ObservableCollection <WeatherForecast>(GetForecasts(weather.daily.data))
            };

            weatherData.Forecasts[0].Day = "Today";
            return(weatherData);
        }
示例#11
0
        static int Main(string[] args)
        {
            string             forecastIOKey    = args[0];
            string             iftttKey         = args[1];
            var                forecastRequest  = new ForecastIORequest(forecastIOKey, 47.754433f, -122.214010f, Unit.si);
            ForecastIOResponse forecastResponse = forecastRequest.Get();
            double             totalRainfall    = forecastResponse.daily.data.Where(x => x.precipType != null && x.precipType.Equals("rain")).Sum(x => x.precipIntensity);

            using (var client = new HttpClient())
            {
                string totalRainfallFormatted = totalRainfall.ToString("0.##");

                var content = new StringContent($"{{\"value1\":{totalRainfallFormatted}}}", Encoding.UTF8, "application/json");

                HttpResponseMessage result =
                    client.PostAsync($"https://maker.ifttt.com/trigger/weeklyforecast_rain_inches/with/key/{iftttKey}", content).Result;

                if (result.IsSuccessStatusCode)
                {
                    return(0);
                }

                return((int)result.StatusCode);
            }
        }
 public virtual async Task <ForecastIOResponse> GetForecastResponse(float latitude, float longitude)
 {
     return(await Task <ForecastIOResponse> .Run(() =>
     {
         var request = new ForecastIORequest(this._apiKey, latitude, longitude, DateTime.Now, Unit.us);
         return request.Get();
     }));
 }
        public IHttpActionResult Get(string zipCode, int?years = 10)
        {
            // Now we can make our first API call to map the zip code
            //  to the geo coordinates we need
            //
            var zipCodeResponse = RequestGeoFromZipcode(zipCode);

            // Let's make sure the zip code was mapped properly before proceeding
            //
            if (zipCodeResponse == null)
            {
                return(BadRequest("The zip code could not be mapped to a latitude and longitude"));
            }

            var zipcodeWeather = new ZipcodeWeather
            {
                City      = zipCodeResponse.City,
                State     = zipCodeResponse.State,
                Latitude  = zipCodeResponse.Latitude,
                Longitude = zipCodeResponse.Longitude
            };

            // Grab the current date so we can create offsets from it
            //
            var startDate = DateTime.Now;

            // Now loop according to 'years' and use the index each time to make a request back
            //  in time
            //
            foreach (var offset in Enumerable.Range(0, (int)years))
            {
                // Calculate the date for this iteration
                //
                var pastDate = startDate.AddYears(-offset);

                // Make the actual forecast.io call
                //
                var request  = new ForecastIORequest(ConfigurationManager.AppSettings["forecast-io-key"], zipCodeResponse.Latitude, zipCodeResponse.Longitude, pastDate, Unit.us);
                var response = request.Get();

                // Create the temp object we need to return and add it to the list
                //
                zipcodeWeather.HistoricalTemperatures.Add(new HistoricalTemperature
                {
                    Date = pastDate,
                    High = response.daily.data[0].temperatureMax,
                    Low  = response.daily.data[0].temperatureMin
                });
            }

            // Use the WebAPI base method to return a 200-response with the list as
            //  the payload
            //
            return(Ok(zipcodeWeather));
        }
示例#14
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            hourlyString = "";

            var request = new ForecastIORequest("bd996ecbf406f3ab16eae62ced5e3ed3", latitude, longitude, Unit.auto);

            wData    = request.Get();
            response = "It took " + request.ApiResponseTime + " for a response and has been called " + request.ApiCallsMade + " times today.";
        }
示例#15
0
        public string printLocationInfoOnline(LocationVars location) //prints all actual values if the user is online
        {
            //get request
            var request = new ForecastIORequest("d9b0a7d6636dad5856be677f4c19e4f2", Convert.ToSingle(location.Point.Latitude), Convert.ToSingle(location.Point.Longitude), DateTime.Now, Unit);
            //response that contains all the current values
            var response = request.Get();

            String s = "----  " + location.LocationName + "-Forecast  ----- \r\n" +
                       " Current temperature: " + response.currently.temperature + unitvalue(Unit) + "\r\n Precipitation: " + response.currently.precipIntensity +
                       "\r\n Humidity: " + response.currently.humidity + "\r\n Visibility: " + response.currently.visibility +
                       "\r\n summary: " + response.currently.summary;

            Console.WriteLine(s);
            return(s);
        }
示例#16
0
        public string Get(Double latitude, Double longitude)
        {
            TelemetryClient telemetry = new TelemetryClient();

            string returnVal = "";

            if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180)
            {
                telemetry.TrackTrace("Failed geo location validation");
                return(""); // not a very friendly error, #TODO make errors nicer
            }

            try
            {
                // to help with testing, we're going to make it possible to override
                // the incoming lat/lon with one of our choosing.
                if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["latitude"]))
                {
                    latitude = Double.Parse(ConfigurationManager.AppSettings["latitude"]);
                }
                if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["longitude"]))
                {
                    longitude = Double.Parse(ConfigurationManager.AppSettings["longitude"]);
                }

                // make the call to our weather provider
                string apiKey   = ConfigurationManager.AppSettings["ForecastIO.apikey"];
                var    request  = new ForecastIORequest(apiKey, (float)latitude, (float)longitude, Unit.us);
                var    response = request.Get();

                // the api response is HUGE, we're only interested in
                // the "minutely" data. The forecast.io api doco
                // says this data may not always be returned :( I have not addressed that case yet
                returnVal = convertToBinnedData(response.minutely.data);
            }
            catch (Exception ex)
            {
                telemetry.TrackTrace("Exception during forecast.io call: " + ex.Message);
                return(""); // lazy with problems again :(
            }

            telemetry.TrackTrace("value returned to caller: " + returnVal);
            return(returnVal);
        }
示例#17
0
        public JsonResult getWeather(decimal latitude, decimal longitude, string dateCaught, string timeCaught)
        {
            //  https://developer.forecast.io/docs/v2  <-- Weather API Documentation

            DateTime imageDateTime = new DateTime();

            try
            {
                //convert date and time strings
                imageDateTime = Convert.ToDateTime(dateCaught + ' ' + timeCaught);
            }
            catch (Exception ex)
            {
                ErrorLoggingClass errorLog = new ErrorLoggingClass();
                errorLog.logError(ex.Message, ex.Source, ex.StackTrace, "Enter Fish", "FishController", "getWeather", User.Identity.Name, "dateCaught:" + dateCaught + ", timeCaught:" + timeCaught);
                return(Json(false));
            }

            float lat = (float)latitude;
            float lng = (float)longitude;

            ForecastIORequest request = new ForecastIORequest(_forecastIO_API_Key, lat, lng, imageDateTime, Unit.us, null);
            var response = request.Get();

            FishModels.FishWeather fw = new FishModels.FishWeather();
            fw.current = response.currently;
            fw.daily   = response.daily;
            fw.hourly  = response.hourly;

            //save response to session
            Session["FishWeather"] = fw;

            var result = new {
                temp      = fw.current.temperature,
                feelsLike = fw.current.apparentTemperature,
                icon      = fw.current.icon,
                summary   = fw.current.summary,
                windSpd   = fw.current.windSpeed,
                windDir   = convertBearingToDirection(fw.current.windBearing),
            };

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
示例#18
0
        public async Task <WeatherInfoResponse> GetAsyn(float latF, float longF)
        {
            string             apiKey = "28896f6afb4e54d741e4d57dbe5d2749";
            List <WeatherInfo> pastWeekWeatherInfo = new List <WeatherInfo>();

            try
            {
                for (int i = -7; i <= -1; i++)  //for the past 7 days
                {
                    var date     = DateTime.Today.AddDays(i);
                    var request  = new ForecastIORequest(apiKey, latF, longF, date, Unit.us);
                    var response = await request.GetAsync();

                    var weatherInfoDate = UnixTimeStampToDateTime(response.daily.data[0].time);
                    pastWeekWeatherInfo.Add(new WeatherInfo
                    {
                        Date    = weatherInfoDate.ToShortDateString(),
                        Summary = response.daily.data[0].summary,
                        DailyHighTemperature = response.daily.data[0].apparentTemperatureMax,
                        DailyLowTemperature  = response.daily.data[0].apparentTemperatureMin
                    });
                }

                WeatherInfoResponse wiResponse = new WeatherInfoResponse
                {
                    status  = "OK",
                    results = pastWeekWeatherInfo
                };

                return(wiResponse);
            }
            catch (Exception ex)
            {
                WeatherInfoResponse wiResponse = new WeatherInfoResponse
                {
                    status       = "Error",
                    errorMessage = ex.ToString()
                };

                return(wiResponse);
            }
        }
示例#19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Locations))
            {
                if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
                {
                    HttpContext.Current.Cache.Remove("ForecastCache");
                }
                else
                {
                    var responses = new List <Utility.ForecastMyProperty>();

                    if (HttpContext.Current.Cache["ForecastCache"] != null)
                    {
                        responses = (List <Utility.ForecastMyProperty>)HttpContext.Current.Cache["ForecastCache"];
                    }
                    else
                    {
                        var settings = this.GetLocationsLatitude(this.Locations);

                        foreach (var setting in settings.Keys)
                        {
                            var value    = settings[setting];
                            var request  = new ForecastIORequest(APIKey, value.Lat, value.Long, value.DisplayName, Unit.si);
                            var response = request.Get();
                            responses.Add(new Utility.ForecastMyProperty()
                            {
                                timezone    = value.DisplayName,
                                temperature = Convert.ToInt32(response.currently.temperature),
                                icon        = response.currently.icon
                            });
                        }

                        HttpContext.Current.Cache.Add("ForecastCache", responses, null, DateTime.Now.AddSeconds(Convert.ToDouble(this.CacheLifetime)), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                    }

                    rptForecast.DataSource = responses;
                    rptForecast.DataBind();
                }
            }
        }
示例#20
0
        public IEnumerable <FCEventModel> DailyForecast()
        {
            var list     = new List <FCEventModel>();
            var request  = new ForecastIORequest(ForecastKey, (float)40.083451, (float)-83.104796, Unit.us);
            var response = request.Get();

            foreach (var day in response.daily.data)
            {
                var newEvent = new FCEventModel()
                {
                    title     = String.Format("{0} - {1}", Math.Round(day.temperatureMax, 0), day.icon),
                    allDay    = true,
                    start     = new DateTime(1970, 1, 1).AddSeconds(day.time).ToString("yyyy-MM-dd"),
                    app       = "Weather",
                    rendering = "background"
                };
                list.Add(newEvent);
            }

            return(list);
        }
示例#21
0
        public string returnXMLData(LocationVars loc, Unit un)
        {
            //get request
            var request = new ForecastIORequest("d9b0a7d6636dad5856be677f4c19e4f2", (float)loc.Point.Latitude, (float)loc.Point.Longitude, DateTime.Now, un);
            //response that contains all the current values
            var response = request.Get();

            Console.WriteLine("loc LAT:" + (float)loc.Point.Latitude + "  Long:" + (float)loc.Point.Longitude);
            var converted = new XElement("Weatherforecast", new XElement("Location",
                                                                         new XAttribute("Name", loc.LocationName),
                                                                         new XAttribute("Latitude", (float)loc.Point.Latitude),
                                                                         new XAttribute("Longitude", (float)loc.Point.Longitude),
                                                                         new XElement("Weather", new XElement("Temperature", response.currently.temperature + Location.unitvalue(un)),
                                                                                      new XElement("Precipitation", response.currently.precipIntensity),
                                                                                      new XElement("Humidity", response.currently.humidity),
                                                                                      new XElement("Visibility", response.currently.visibility),
                                                                                      new XElement("summary", response.currently.summary)
                                                                                      )));

            Console.WriteLine(converted);
            return(converted.ToString());
        }
        public async Task <ForecastDto> GetForecast(double longitude, double latitude)
        {
            var request  = new ForecastIORequest(_settings.ApiKey, (float)latitude, (float)longitude, Unit.si);
            var response = await request.GetAsync();

            if (response?.currently != null)
            {
                return(new ForecastDto
                {
                    StatusCode = 200,
                    Humidity = response.currently.humidity,
                    Wind = response.currently.windSpeed,
                    Timezone = response.timezone,
                    Time = response.currently.time,
                    Summary = response.currently.summary,
                    Temperature = response.currently.temperature
                });
            }

            return(new ForecastDto {
                StatusCode = 404
            });
        }
示例#23
0
        public IEnumerable <FCEventModel> HourlyForecast()
        {
            var list     = new List <FCEventModel>();
            var request  = new ForecastIORequest(ForecastKey, (float)40.083451, (float)-83.104796, Unit.us);
            var response = request.Get();

            foreach (var hour in response.hourly.data)
            {
                var wTime    = new DateTime(1970, 1, 1).AddSeconds(hour.time);
                var newEvent = new FCEventModel()
                {
                    title     = String.Format("{0} - {1}", Math.Round(hour.temperature, 0), hour.icon),
                    allDay    = false,
                    start     = wTime.ToString("yyyy-MM-dd HH:mm"),
                    end       = wTime.AddMinutes(30).ToString("yyyy-MM-dd HH:mm"),
                    app       = "Weather",
                    rendering = "background"
                };
                list.Add(newEvent);
            }

            return(list);
        }
示例#24
0
        private async Task GetWeatherInfo(ForecastDevice device, CancellationToken cancellationToken)
        {
            var latitude  = (float)device.Latitude;
            var longitude = (float)device.Longitude;
            ForecastIOResponse response;

            try
            {
                var request = new ForecastIORequest(_apiKey, latitude, longitude, Unit.si);
                response = _policy.Execute(() => request.Get());
            }
            catch (WebException)
            {
                return;
            }
            catch (Exception e)
            {
                _log.Error(e.Message, e);
                return;
            }

            UpdateVariables(device.Id, string.Empty, response.currently);

            for (var hour = 0; hour < response.hourly.data.Count; hour++)
            {
                var data = response.hourly.data[hour];
                UpdateVariables(device.Id, $"H+{hour}_", data);
            }

            for (var day = 0; day < response.daily.data.Count; day++)
            {
                var data = response.daily.data[day];
                UpdateVariables(device.Id, $"D+{day}_", data);
            }

            await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).ContinueWith(_ => { });
        }
示例#25
0
        public static ForecastIOResponse SyncGet()
        {
            var request = new ForecastIORequest(key, 43.4499376f, -79.7880999f, Unit.si);

            return(request.Get());
        }
示例#26
0
        public static async Task <ForecastIOResponse> AsyncGet()
        {
            var request = new ForecastIORequest(key, 43.4499376f, -79.7880999f, Unit.si);

            return(await request.GetAsync());
        }
示例#27
0
        private void BrokerOnCommandReceived(object sender, CommandReceivedEventArgs e)
        {
            var task = Task.Run(async() =>
            {
                string inputLocation = null;
                bool noSave          = false;
                // parse out commandline
                if (e.Command.Arguments.Count > 0)
                {
                    inputLocation = string.Join(" ", e.Command.Arguments.Where(x => x != "nosave"));
                }
                if (e.Command.Arguments.Count > 1)
                {
                    noSave = e.Command.Arguments.Any(x => x == "nosave");
                }

                string userAddress            = null;
                Tuple <float, float> location = null;
                bool isMetric = false;

                if (string.IsNullOrEmpty(inputLocation))
                {
                    using (var ctx = new UserContext("weather"))
                    {
                        // TODO: Don't break in PMs on discord
                        WeatherUser user =
                            ctx.Users.FirstOrDefault(
                                x => x.Server == e.Server.Name && x.Client == ((IClient)sender).Name &&
                                x.Username == e.User.Name);

                        userAddress = user?.Address;
                        if (user != null)
                        {
                            location = new Tuple <float, float>(user.Latitude, user.Longitude);
                            isMetric = user.IsMetric;
                        }
                    }
                    if (userAddress == null)
                    {
                        e.ReplyTarget.Send("gotta give me a zipcode or something");
                        return;
                    }
                }

                if (userAddress == null)
                {
                    IEnumerable <GoogleAddress> addresses = await _geocode.GeocodeAsync(inputLocation);

                    if (addresses != null)
                    {
                        var address = addresses.FirstOrDefault(x => !x.IsPartialMatch);
                        userAddress = address?.FormattedAddress;
                        if (userAddress != null)
                        {
                            isMetric = address[GoogleAddressType.Country].ShortName != "US";
                            location = new Tuple <float, float>((float)address.Coordinates.Latitude,
                                                                (float)address.Coordinates.Longitude);
                            if (!noSave)
                            {
                                using (var ctx = new UserContext("weather"))
                                {
                                    WeatherUser user =
                                        ctx.Users.FirstOrDefault(
                                            x =>
                                            x.Server == e.Server.Name && x.Client == ((IClient)sender).Name &&
                                            x.Username == e.User.Name) ?? new WeatherUser();
                                    user.Server    = e.Server.Name;
                                    user.Client    = ((IClient)sender).Name;
                                    user.Username  = e.User.Name;
                                    user.Address   = userAddress;
                                    user.Latitude  = location.Item1;
                                    user.Longitude = location.Item2;
                                    user.IsMetric  = isMetric;
                                    ctx.Users.AddOrUpdate(user);
                                    await ctx.SaveChangesAsync();
                                }
                            }
                        }
                        else
                        {
                            e.ReplyTarget.Send($"where in the bloody hell is {inputLocation}?");
                            return;
                        }
                    }
                }

                var unit    = isMetric ? Unit.si : Unit.us;
                var weather = new ForecastIORequest(_forecastIoApiKey, location.Item1, location.Item2, unit).Get();

                string summary =
                    $"{userAddress} | {weather.currently.summary} | {weather.currently.temperature}{(unit == Unit.us ? "F" : "C")} | Humidity: {weather.currently.humidity*100}%";

                if (weather.minutely != null)
                {
                    summary += "\n" + weather.minutely;
                }

                var info             = new WeatherRendererInfo();
                info.Unit            = unit;
                info.Address         = userAddress;
                info.WeatherResponse = weather;
                var stream           = CreateWeatherImage(info);
                e.ReplyTarget.Send(summary,
                                   new ImageAttachment
                {
                    DataStream = stream,
                    Name       = $"{e.User.Name} Weather {DateTime.Now}.png"
                });
            });

            try
            {
                task.Wait();
            }
            catch (AggregateException ex)
            {
                throw ex.InnerExceptions.Last();
            }
        }
示例#28
0
        public static ForecastIOResponse SyncGetLL(double lat, double lon)
        {
            var request = new ForecastIORequest(key, (float)lat, (float)lon, Unit.si);

            return(request.Get());
        }