public async Task <ObservableCollection <DailyWeatherItem> > GetWeatherByZipCode(string zipCode)
        {
            GeocodioClient  geocodio = null;
            GeocodeResponse geocode  = null;

            using (var httpClient = new HttpClient())
            {
                geocodio = new GeocodioClient(
                    httpClient,
                    Keys.GEOCODIO_API_KEY);
                geocode = await geocodio.GetGeocodeAsync(zipCode);
            }
            if (geocode.Success)
            {
                var      latitude        = (double)geocode.Results[0].Location.Latitude;
                var      longitude       = (double)geocode.Results[0].Location.Longitude;
                Forecast allForecastData = await darkSkyService.GetWeatherDataAsync(latitude, longitude);

                SessionDailyWeatherData = GrabDailyData(allForecastData);
                return(SessionDailyWeatherData);
            }
            else
            {
                return(new ObservableCollection <DailyWeatherItem>());
            }
        }
Пример #2
0
        public ForecastResult Get(double lat, double lng)
        {
            var client          = new DarkSkyService(DARKSKY_API);
            var darkSkyForecast = client.GetWeatherDataAsync(lat, lng).Result;

            var result = new ForecastResult
            {
                CurrentSummary = darkSkyForecast.Currently.Summary,
                CurrentTemp    = darkSkyForecast.Currently.Temperature.ToString("0.0")
            };

            foreach (var dsDayForecast in darkSkyForecast.Daily.Days)
            {
                var dayForecast = new DailyForecast
                {
                    LowTemp   = dsDayForecast.LowTemperature.ToString("0.0"),
                    HiTemp    = dsDayForecast.HighTemperature.ToString("0.0"),
                    Summary   = dsDayForecast.Summary,
                    DayOfWeek = dsDayForecast.SunriseTime.ToLocalTime().DayOfWeek.ToString()
                };

                result.Future.Add(dayForecast);
            }
            return(result);
        }
Пример #3
0
        private static async Task <Forecast> GetDarkSkyForecast(double lat, double longitude)
        {
            var ds       = new DarkSkyService("");
            var forecast = await ds.GetWeatherDataAsync(lat, longitude);

            return(forecast);
        }
Пример #4
0
        public async void GetWeather()
        {
            var client = new DarkSkyService(GlobalVars.DarkSkyWeatherKey);

            // 52.499836, 6.079915 are Windesheim Coordinates
            Weather = await client.GetWeatherDataAsync(52.499836, 6.079915);
        }
Пример #5
0
        public async Task UnicodeLanguageIsSupported()
        {
            var client = new DarkSkyService(apiKey);
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.Auto, Language.Chinese);

            Assert.That(result, Is.Not.Null);
        }
Пример #6
0
        private async Task GetWeather()
        {
            var current_weather = await _weather.GetWeatherDataAsync(_settings.LOCATION_LAT, _settings.LOCATION_LNG, Unit.UK, Language.English);

            LastWeatherMinutely = current_weather.Minutely;
            OnWeatherUpdate?.Invoke(current_weather.Currently.Icon);
        }
        public async Task <Forecast> Get(double latitude, double longitude)
        {
            var      client = new DarkSkyService(Environment.GetEnvironmentVariable("ApiKey"));
            Forecast result = await client.GetWeatherDataAsync(latitude, longitude);

            JsonConvert.SerializeObject(result);
            return(result);
        }
Пример #8
0
        public async Task UnitSIWorksCorrectly()
        {
            var client = new DarkSkyService(apiKey);

            var result = await client.GetWeatherDataAsync(MumbaiLatitude, MumbaiLongitude, Unit.SI);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Currently, Is.Not.Null);
        }
Пример #9
0
        public async Task NonUSDataCanBeRetrieved()
        {
            var client = new DarkSkyService(apiKey);

            var result = await client.GetWeatherDataAsync(MumbaiLatitude, MumbaiLongitude);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Currently, Is.Not.Null);
        }
Пример #10
0
        public async Task ValidKeyRetrievesData()
        {
            var client = new DarkSkyService(apiKey);

            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Currently, Is.Not.Null);
        }
Пример #11
0
        public async Task UnitsCanBeSpecified()
        {
            var client = new DarkSkyService(apiKey);

            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.CA);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Flags.Units, Is.EqualTo(Unit.CA.ToValue()));
        }
Пример #12
0
        public async Task WorksWithPeriodDecimalSeperator()
        {
            var client = new DarkSkyService(apiKey);

            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Currently, Is.Not.Null);
        }
Пример #13
0
        public async Task ExclusionWorksCorrectly()
        {
            var client        = new DarkSkyService(apiKey);
            var exclusionList = new List <Exclude> {
                Exclude.Minutely
            };

            var result = await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude, Unit.US, exclusionList);

            Assert.That(result, Is.Not.Null);
            Assert.That(result.Currently, Is.Not.Null);
            Assert.That(result.Minutely, Is.Null);
        }
Пример #14
0
        private async Task <Forecast> FetchCurrentWeather(double lat, double lon)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                return(null);
            }

            var unit = (Unit)Settings.GetUnit();
            var lang = GetLanguage();

            var client = new DarkSkyService(_APIKey);

            return(await client.GetWeatherDataAsync(lat, lon, unit, lang));
        }
        public WeatherModel GetWeatherForecastByCoOrdinates(string latitude, string longitude)
        {
            WeatherModel weatherModel = new WeatherModel();
            var          client       = new DarkSkyService("1edbf9d2042f997e9fe200cbfb8f55ae");
            Forecast     result       = client.GetWeatherDataAsync(
                Convert.ToDouble(latitude)
                , Convert.ToDouble(longitude)
                , Unit.UK).Result;

            weatherModel.Temperature          = Math.Round(result.Currently.Temperature, 0).ToString() + "°C";
            weatherModel.WeatherConditionIcon = result.Currently.Icon.ToUpper().Replace("-", "_");
            weatherModel.WeatherCondition     = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(
                result.Currently.Icon.ToUpper().Replace("-", " ")
                );
            weatherModel.WindSpeed = result.Currently.WindSpeed.ToString();
            weatherModel.Humidity  = result.Currently.Humidity.ToString();

            return(weatherModel);
        }
Пример #16
0
        public async Task <IActionResult> Record(double?tempC, double?humidity, bool test = false)
        {
            //Don't bother if we have no temp data
            if (tempC.HasValue || humidity.HasValue)
            {
                double?outsideTemp = null;

                try
                {
                    var client   = new DarkSkyService(_darkSky.ApiKey);
                    var forecast = await client.GetWeatherDataAsync(_darkSky.Latitude, _darkSky.Longitude, Unit.CA);

                    outsideTemp = forecast.Currently.Temperature;
                }
                catch (HttpRequestException)
                {
                    //Unable to call the DarkSkyApi, just leave outsideTemp as null.
                }

                //Docker is running in a linux container on UTC time, so we need to get it in EST.
                var tzi         = TZConvert.GetTimeZoneInfo("America/New_York");
                var estDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, tzi.Id);

                Console.WriteLine(estDateTime + " - Temp: " + tempC + " C, Humidity: " + humidity + "%, Outside: " + outsideTemp + " C");

                //If we're testing, don't save to the db.
                if (!test)
                {
                    var record = new Record()
                    {
                        SensorHumidity = humidity, SensorTemp = tempC, Timestamp = estDateTime
                    };
                    if (outsideTemp.HasValue)
                    {
                        record.OutsideTemp = outsideTemp.Value;
                    }
                    _thermometerRepo.Insert(record);
                }
            }

            return(Ok());
        }
Пример #17
0
        public void EmptyKeyThrowsException()
        {
            var client = new DarkSkyService(string.Empty);

            Assert.That(async() => await client.GetWeatherDataAsync(AlcatrazLatitude, AlcatrazLongitude), Throws.InvalidOperationException);
        }
Пример #18
0
        public static NeedToSrpinkle GetForecastStatic()
        {
            NeedToSrpinkle needToSrpinkle = new NeedToSrpinkle();

            try
            {
                // Get the forecast
                var client = new DarkSkyService(_settings.ApiKey);
                var tsk    = client.GetWeatherDataAsync(_settings.Latitude, _settings.Longitude, _settings.Unit, _settings.Language);
                tsk.Wait();
                var forecast = tsk.Result;
                needToSrpinkle.Forecast = forecast;
                // Get Forcast max temperature for the next 24h and same for precipitations
                float ForecastMaxTemp                  = 0;
                float ForecastTotalPrecipitation       = 0;
                float ForecastProbabilityPrecipitation = 0;
                if (forecast.Daily.Days != null)
                {
                    if (forecast.Daily.Days.Count > 0)
                    {
                        if (forecast.Daily.Days[0].HighTemperature >= ForecastMaxTemp)
                        {
                            ForecastMaxTemp = forecast.Daily.Days[0].HighTemperature;
                        }
                        if ((forecast.Daily.Days[0].PrecipitationIntensity * 24) >= ForecastTotalPrecipitation)
                        {
                            ForecastTotalPrecipitation = forecast.Daily.Days[0].PrecipitationIntensity * 24;
                        }
                        if (forecast.Daily.Days[0].PrecipitationProbability >= ForecastProbabilityPrecipitation)
                        {
                            ForecastProbabilityPrecipitation = forecast.Daily.Days[0].PrecipitationProbability * 100;
                        }
                    }
                }
                // Get historical temperature of the day before
                tsk = client.GetTimeMachineWeatherAsync(_settings.Latitude, _settings.Longitude, DateTime.Now.AddDays(-1), _settings.Unit, _settings.Language);
                tsk.Wait();
                var history = tsk.Result;
                // find the al up precipitation and max temperature
                float HistMaxTemp            = 0;
                float HistTotalPrecipitation = 0;
                if (history.Daily.Days != null)
                {
                    if (history.Daily.Days.Count > 0)
                    {
                        if (history.Daily.Days[0].HighTemperature >= HistMaxTemp)
                        {
                            HistMaxTemp = history.Daily.Days[0].HighTemperature;
                        }
                        if (history.Daily.Days[0].PrecipitationAccumulation >= HistTotalPrecipitation)
                        {
                            HistTotalPrecipitation = history.Daily.Days[0].PrecipitationAccumulation;
                        }
                    }
                }


                needToSrpinkle.NeedTo = false;
                //Do all math with fuzzy logic
                foreach (var objective in _fuzzySprinklers)
                {
                    //Found the righ range
                    if ((ForecastMaxTemp >= objective.TempMin) && (ForecastMaxTemp < objective.TempMax))
                    {
                        // How much it rained ?
                        if (HistTotalPrecipitation >= objective.RainMax)
                        {
                            needToSrpinkle.NeedTo = false;
                        }
                        // Will it rain for sure? and will it rain enough?
                        else if ((ForecastProbabilityPrecipitation >= _settings.PrecipitationPercentForecast) && (ForecastTotalPrecipitation >= objective.RainMax))
                        {
                            needToSrpinkle.NeedTo = false;
                        }
                        else
                        {   // so we need to sprinkler. Make the math how long with the correction factor
                            // first calculate proportion of time vs the theoritical maximum
                            needToSrpinkle.PercentageCorrection = (float)(((objective.RainMax - HistTotalPrecipitation) / objective.RainMax) * objective.SprinklingMax / 100.0);
                            needToSrpinkle.NeedTo = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
            return(needToSrpinkle);
        }
Пример #19
0
        static private string GetForecast(string param)
        {
            List <Param> Params = Param.decryptParam(param);

            if (Params != null)
            {
                //Check if there is an automation setting
                if (Params.Where(m => m.Name.ToLower() == paramAutomateAll).Any())
                {
                    WunderSettings.AutomateAll = Param.CheckConvertBool(Params, paramAutomateAll);
                }
            }

            StringBuilder sb = new StringBuilder();

            try
            {
                // Get the forecast
                var client = new DarkSkyService(ForecastSettings.ApiKey);
                var tsk    = client.GetWeatherDataAsync(ForecastSettings.Latitude, ForecastSettings.Longitude, ForecastSettings.Unit, ForecastSettings.Language);
                tsk.Wait();
                var forecast = tsk.Result;
                // Get Forcast max temperature for the next 24h and same for precipitations
                float ForecastMaxTemp                  = 0;
                float ForecastTotalPrecipitation       = 0;
                float ForecastProbabilityPrecipitation = 0;
                if (forecast.Daily.Days != null)
                {
                    if (forecast.Daily.Days.Count > 0)
                    {
                        if (forecast.Daily.Days[0].HighTemperature >= ForecastMaxTemp)
                        {
                            ForecastMaxTemp = forecast.Daily.Days[0].HighTemperature;
                        }
                        if ((forecast.Daily.Days[0].PrecipitationIntensity * 24) >= ForecastTotalPrecipitation)
                        {
                            ForecastTotalPrecipitation = forecast.Daily.Days[0].PrecipitationIntensity * 24;
                        }
                        if (forecast.Daily.Days[0].PrecipitationProbability >= ForecastProbabilityPrecipitation)
                        {
                            ForecastProbabilityPrecipitation = forecast.Daily.Days[0].PrecipitationProbability * 100;
                        }
                    }
                }
                // Get historical temperature of the day before
                tsk = client.GetTimeMachineWeatherAsync(ForecastSettings.Latitude, ForecastSettings.Longitude, DateTime.Now.AddDays(-1), ForecastSettings.Unit, ForecastSettings.Language);
                tsk.Wait();
                var history = tsk.Result;
                // find the al up precipitation and max temperature
                float HistMaxTemp            = 0;
                float HistTotalPrecipitation = 0;
                if (history.Daily.Days != null)
                {
                    if (history.Daily.Days.Count > 0)
                    {
                        if (history.Daily.Days[0].HighTemperature >= HistMaxTemp)
                        {
                            HistMaxTemp = history.Daily.Days[0].HighTemperature;
                        }
                        if (history.Daily.Days[0].PrecipitationAccumulation >= HistTotalPrecipitation)
                        {
                            HistTotalPrecipitation = history.Daily.Days[0].PrecipitationAccumulation;
                        }
                    }
                }

                // Creating the header
                sb.Append(BuildHeader());
                sb.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><meta name=\"Generator\" content=\"Meteo forecast\"></head><body>");
                sb.Append("Meteo forecast for <b>" + ForecastSettings.City + "</b></br>" + forecast.Daily.Summary + "<img src=\"https://www.ellerbach.net/public/meteo/" + forecast.Daily.Icon + ".png\"><br>");

                WunderSettings.NeedToSprinkle = false;
                // Do all the math without fuzzy logic
                if (Fuzzy == null)
                {
                    // Did it rained anough?
                    if (HistTotalPrecipitation > WunderSettings.PrecipitationThresholdActuals)
                    {
                        sb.Append($"<b>No need to sprinkle</b>: yesterday rain was {HistTotalPrecipitation} mm more than the threshold {WunderSettings.PrecipitationThresholdActuals} mm.<br>");
                        WunderSettings.NeedToSprinkle = false;
                    }
                    //Is it warm enough?
                    else if (ForecastMaxTemp > WunderSettings.MinTemp)
                    {
                        WunderSettings.PercentageCorrection = (float)(((WunderSettings.PrecipitationThresholdActuals - ForecastTotalPrecipitation) / WunderSettings.PrecipitationThresholdActuals));
                        //Will it rain?
                        if (ForecastTotalPrecipitation > WunderSettings.PrecipitationThresholdForecast)
                        {
                            var introstr = $"Forecast is for rain with {ForecastTotalPrecipitation} mm, more than {WunderSettings.PrecipitationThresholdForecast} mm.<br>";
                            //Enough rain?
                            if (ForecastProbabilityPrecipitation > WunderSettings.PrecipitationPercentForecast)
                            {
                                sb.Append("<b>No need to sprinkle</b><ol>");
                                sb.Append($"<li>{introstr}</li>");
                                sb.Append($"<li>Considence index is {ForecastTotalPrecipitation} % more than the threshold {WunderSettings.PrecipitationPercentForecast} %.</ol><br>");
                                WunderSettings.NeedToSprinkle = false;
                            }
                            //Not enough rain, so need to sprinkler
                            else
                            {
                                sb.Append($"<b>I plan to sprinkle</b>:<ol>");
                                sb.Append($"<li>Confidence index is {ForecastTotalPrecipitation} % less than threshold {WunderSettings.PrecipitationPercentForecast} %</li>");
                                sb.Append($"<li>sprinkling will be adjusted by {(WunderSettings.PercentageCorrection * 100).ToString("0")} %</li></ol><br>");
                                WunderSettings.NeedToSprinkle = true;
                            }
                        }
                    }
                    //Not warm enough to srpinkler
                    else
                    {
                        sb.Append($"<b>No need to sprinkle</b>: Temperature will be {ForecastMaxTemp}°C lower than threshold {WunderSettings.MinTemp}. Please use manual program if you still want to sprinkler.");
                        WunderSettings.NeedToSprinkle = false;
                    }
                }
                //Do all math with fuzzy logic
                else
                {
                    foreach (var objective in Fuzzy)
                    {
                        //Found the righ range
                        if ((ForecastMaxTemp >= objective.TempMin) && (ForecastMaxTemp < objective.TempMax))
                        {
                            // How much it rained ?
                            if (HistTotalPrecipitation >= objective.RainMax)
                            {
                                sb.Append($"<b>No need to sprinkle</b>: It rained {HistTotalPrecipitation} mm more than the threshold {objective.RainMax} mm.<br>");
                                WunderSettings.NeedToSprinkle = false;
                            }
                            // Will it rain for sure? and will it rain enough?
                            else if ((ForecastProbabilityPrecipitation >= WunderSettings.PrecipitationPercentForecast) && (ForecastTotalPrecipitation >= objective.RainMax))
                            {
                                sb.Append($"<b>No need to sprinkle</b>:<ol><li>Confidence index is {ForecastProbabilityPrecipitation} % more than the threshold {WunderSettings.PrecipitationPercentForecast} %</li>");
                                sb.Append($"<li>With {ForecastTotalPrecipitation} mm more than the threshold {objective.RainMax} mm.</li></ol><br>");
                                WunderSettings.NeedToSprinkle = false;
                            }
                            else
                            {   // so we need to sprinkler. Make the math how long with the correction factor
                                // first calculate proportion of time vs the theoritical maximum
                                WunderSettings.PercentageCorrection = (float)(((objective.RainMax - HistTotalPrecipitation) / objective.RainMax) * objective.SprinklingMax / 100.0);
                                sb.Append($"<b>I plan to sprinkle</b>: <ol><li>Yesterday rain was {HistTotalPrecipitation} mm and {HistMaxTemp}°C</li>");
                                sb.Append($"<li>Today forecast is {ForecastTotalPrecipitation} mm at {ForecastProbabilityPrecipitation}% and max temperature {ForecastMaxTemp}°C</li>");
                                sb.Append($"<li>Percentage adjustment is {(WunderSettings.PercentageCorrection * 100).ToString("0")}%</li></ol><br>");
                                WunderSettings.NeedToSprinkle = true;
                            }
                        }
                    }
                }

                // display the forecast per day
                sb.Append("<table><tr><th>Date</th><th>Summary</th><th></th><th>Temp min</th><th>Temp max</th><th>Wind speed</th><th>Precipitation</th><tr>");
                for (int i = 0; i < forecast.Daily.Days.Count; i++)
                {
                    sb.Append("<tr><td>" + forecast.Daily.Days[i].Time.AddDays(1).ToString("yyyy-MM-dd ddd") + "</td><td>");
                    sb.Append(forecast.Daily.Days[i].Summary + "</td><td>");
                    sb.Append("<img src=\"https://www.ellerbach.net/public/meteo/" + forecast.Daily.Days[i].Icon + ".png\"></td><td>");
                    sb.Append(forecast.Daily.Days[i].LowTemperature.ToString("0.0") + "°C</td><td>");
                    sb.Append(forecast.Daily.Days[i].HighTemperature.ToString("0.0") + "°C</td><td>");
                    sb.Append((forecast.Daily.Days[i].WindSpeed * 3.6).ToString("0.0") + "km/h</td><td>");
                    sb.Append(forecast.Daily.Days[i].PrecipitationType + " " + forecast.Daily.Days[i].PrecipitationProbability * 100 + "% chance with " + (forecast.Daily.Days[i].PrecipitationIntensity * 24).ToString("0.0") + " mm</td>");
                }
                //hourly forecast
                sb.Append("</table><br />Prévisions par heure:<br />");
                sb.Append("<table><tr><th>Date</th><th>Summary</th><th></th><th>Temp</th><th>Temp app</th><th>Wind speed</th><th>Precipitation</th><tr>");
                for (int i = 0; i < forecast.Hourly.Hours.Count; i++)
                {
                    sb.Append("<tr><td>" + forecast.Hourly.Hours[i].Time.ToString("yyyy-MM-dd ddd hh:mm") + "</td><td>");
                    sb.Append(forecast.Hourly.Hours[i].Summary + "</td><td>");
                    sb.Append("<img src=\"https://www.ellerbach.net/public/meteo/" + forecast.Hourly.Hours[i].Icon + ".png\"></td><td>");
                    sb.Append(forecast.Hourly.Hours[i].Temperature.ToString("0.0") + "°C</td><td>");
                    sb.Append(forecast.Hourly.Hours[i].ApparentTemperature.ToString("0.0") + "°C</td><td>");
                    sb.Append((forecast.Hourly.Hours[i].WindSpeed * 3.6).ToString("0.0") + "km/h</td><td>");
                    sb.Append(forecast.Hourly.Hours[i].PrecipitationType + " " + forecast.Hourly.Hours[i].PrecipitationProbability * 100 + "% chance with " + (forecast.Hourly.Hours[i].PrecipitationIntensity).ToString("0.0") + " mm</td>");
                }

                //End of the page
                sb.Append("</table></body></html>");
            }
            catch (Exception ex)
            {
                sb.Append($"<p>ERROR:<br>{ex.Message}");
            }
            sb.Append("<p><a href='/typic.aspx" + Param.ParamStart + securityKey + Param.ParamSeparator + paramClk
                      + Param.ParamEqual + "1'>Create typical program</a><br>");
            sb.Append("<a href='/" + paramPageSprinkler + Param.ParamStart + securityKey + "'>Return to main page</a>");
            sb.Append("</p></BODY></HTML>");
            return(sb.ToString());
        }