protected async void btnPredictDelays_Click(object sender, EventArgs e)
        {
            var departureDate = DateTime.Parse(txtDepartureDate.Text);

            departureDate = departureDate.AddHours(double.Parse(txtDepartureHour.Text));

            var selectedAirport = aiports.FirstOrDefault(a => a.AirportCode == ddlOriginAirportCode.SelectedItem.Value);

            if (selectedAirport != null)
            {
                var query = new DepartureQuery()
                {
                    DepartureDate      = departureDate,
                    DepartureDayOfWeek = ((int)departureDate.DayOfWeek) + 1, //Monday = 1
                    Carrier            = txtCarrier.Text,
                    OriginAirportCode  = selectedAirport.AirportCode,
                    OriginAirportLat   = selectedAirport.Latitude,
                    OriginAirportLong  = selectedAirport.Longitude,
                    DestAirportCode    = ddlDestAirportCode.SelectedItem.Text
                };

                await GetWeatherForecast(query);

                if (forecast == null)
                {
                    throw new Exception("Forecast request did not succeed. Check Settings for weatherApiKey.");
                }

                PredictDelays(query, forecast).Wait();
            }

            UpdateStatusDisplay(prediction, forecast);
        }
Exemple #2
0
        private async Task GetWeatherForecast(DepartureQuery departureQuery)
        {
            var departureDate = departureQuery.DepartureDate;

            forecast = null;

            try
            {
                var weatherPrediction = await openWeatherClient.GetWeatherForecast5d3hAsync(
                    (float)departureQuery.OriginAirportLong,
                    (float)departureQuery.OriginAirportLat);

                if (weatherPrediction != null && weatherPrediction.List.Any())
                {
                    // Extract the dates from the prediction, then find the closest matching date and time based on the departure date.
                    var dates       = weatherPrediction.List.Select(x => x.DateTimeUtc).ToList();
                    var nearestDiff = dates.Min(date => Math.Abs((date - departureDate).Ticks));
                    var nearestDate = dates.First(date => Math.Abs((date - departureDate).Ticks) == nearestDiff);
                    forecast = (from f in weatherPrediction.List
                                where f.DateTimeUtc == nearestDate
                                select new ForecastResult()
                    {
                        WindSpeed = f.Wind?.SpeedKmph ?? 0,
                        Precipitation = f.Rain?.OneHourMm ?? 0,
                        Pressure = f.Main?.PressurehPa ?? 0,
                        ForecastIconUrl = GetImagePathFromIcon(f.Weather[0].Icon),
                        Condition = f.Weather[0].Description
                    }).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Failed retrieving weather forecast: " + ex.ToString());
            }
        }
        private async Task GetWeatherForecast(DepartureQuery departureQuery)
        {
            var departureDate = departureQuery.DepartureDate;

            forecast = null;

            try
            {
                var weatherPrediction = await darkSky.GetForecast(departureQuery.OriginAirportLat,
                                                                  departureQuery.OriginAirportLong, new DarkSkyService.OptionalParameters
                {
                    ExtendHourly        = true,
                    DataBlocksToExclude = new List <ExclusionBlock> {
                        ExclusionBlock.Flags,
                        ExclusionBlock.Alerts, ExclusionBlock.Minutely
                    }
                });

                if (weatherPrediction.Response.Hourly.Data != null && weatherPrediction.Response.Hourly.Data.Count > 0)
                {
                    var timeZone           = DateTimeZoneProviders.Tzdb[weatherPrediction.Response.TimeZone];
                    var zonedDepartureDate = LocalDateTime.FromDateTime(departureDate)
                                             .InZoneLeniently(timeZone);

                    forecast = (from f in weatherPrediction.Response.Hourly.Data
                                where f.DateTime == zonedDepartureDate.ToDateTimeOffset()
                                select new ForecastResult()
                    {
                        WindSpeed = f.WindSpeed ?? 0,
                        Precipitation = f.PrecipIntensity ?? 0,
                        Pressure = f.Pressure ?? 0,
                        ForecastIconUrl = GetImagePathFromIcon(f.Icon),
                        Condition = f.Summary
                    }).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Failed retrieving weather forecast: " + ex.ToString());
            }
        }
        private async Task PredictDelays(DepartureQuery query, ForecastResult forecast)
        {
            if (string.IsNullOrEmpty(mlUrl))
            {
                return;
            }

            var departureDate = DateTime.Parse(txtDepartureDate.Text);

            prediction = new DelayPrediction();

            try
            {
                using (var client = new HttpClient())
                {
                    var predictionRequest = new PredictionRequest
                    {
                        OriginAirportCode = query.OriginAirportCode,
                        Month             = query.DepartureDate.Month,
                        DayofMonth        = query.DepartureDate.Day,
                        CRSDepHour        = query.DepartureDate.Hour,
                        DayOfWeek         = query.DepartureDayOfWeek,
                        Carrier           = query.Carrier,
                        DestAirportCode   = query.DestAirportCode,
                        WindSpeed         = forecast.WindSpeed,
                        SeaLevelPressure  = forecast.Pressure,
                        HourlyPrecip      = forecast.Precipitation
                    };

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", mlApiKey);
                    client.BaseAddress = new Uri(mlUrl);
                    var response = await client.PostAsJsonAsync("", predictionRequest).ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();

                        var token        = JToken.Parse(result);
                        var parsedResult = JsonConvert.DeserializeObject <PredictionResult>((string)token);

                        if (parsedResult.prediction == 1)
                        {
                            this.prediction.ExpectDelays = true;
                            this.prediction.Confidence   = parsedResult.probability;
                        }
                        else if (parsedResult.prediction == 0)
                        {
                            this.prediction.ExpectDelays = false;
                            this.prediction.Confidence   = parsedResult.probability;
                        }
                        else
                        {
                            this.prediction = null;
                        }
                    }
                    else
                    {
                        prediction = null;

                        Trace.Write($"The request failed with status code: {response.StatusCode}");

                        // Print the headers - they include the request ID and the timestamp, which are useful for debugging the failure
                        Trace.Write(response.Headers.ToString());

                        var responseContent = await response.Content.ReadAsStringAsync();

                        Trace.Write(responseContent);
                    }
                }
            }
            catch (Exception ex)
            {
                prediction = null;
                System.Diagnostics.Trace.TraceError("Failed retrieving delay prediction: " + ex.ToString());
                throw;
            }
        }