예제 #1
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                Geoposition newGeoPos = null;

                try
                {
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        geoStatus = await Geolocator.RequestAccessAsync();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                    }
                    finally
                    {
                        if (geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10));
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "WeatherNow: GetWeather error");
                            }
                        }
                        else if (geoStatus == GeolocationAccessStatus.Denied)
                        {
                            // Disable gps feature
                            Settings.FollowGPS = false;
                        }
                    }

                    if (!Settings.FollowGPS)
                    {
                        return(false);
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        geoPos != null && ConversionMethods.CalculateGeopositionDistance(geoPos, newGeoPos) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    });

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    location        = lastGPSLocData;
                    geoPos          = newGeoPos;
                    locationChanged = true;
                }
            }

            return(locationChanged);
        }
예제 #2
0
        private async Task LoadWeatherData()
        {
            /*
             * If unable to retrieve saved data, data is old, or units don't match
             * Refresh weather data
             */

            Logger.WriteLine(LoggerLevel.Debug, "{0}: Loading weather data for {1}", TAG, location?.ToString());

            bool gotData = await LoadSavedWeatherData();

            if (!gotData)
            {
                Logger.WriteLine(LoggerLevel.Debug, "{0}: Saved weather data invalid for {1}", TAG, location?.ToString());
                Logger.WriteLine(LoggerLevel.Debug, "{0}: Retrieving data from weather provider", TAG);

                try
                {
                    if ((weather != null && weather.source != Settings.API) ||
                        (weather == null && location != null && location.source != Settings.API))
                    {
                        // Update location query and source for new API
                        string oldKey = location.query;

                        if (weather != null)
                        {
                            location.query = await wm.UpdateLocationQuery(weather);
                        }
                        else
                        {
                            location.query = await wm.UpdateLocationQuery(location);
                        }

                        location.source = Settings.API;

                        // Update database as well
#if !__ANDROID_WEAR__
                        if (location.locationType == LocationType.GPS)
                        {
                            Settings.SaveLastGPSLocData(location);
#if __ANDROID__
                            WearableDataListenerService.EnqueueWork(App.Context,
                                                                    new Android.Content.Intent(App.Context, typeof(WearableDataListenerService))
                                                                    .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));
#endif
                        }
                        else
                        {
                            await Settings.UpdateLocationWithKey(location, oldKey);
                        }
#else
                        Settings.SaveHomeData(location);
#endif

#if WINDOWS_UWP
                        // Update tile id for location
                        if (SecondaryTileUtils.Exists(oldKey))
                        {
                            await SecondaryTileUtils.UpdateTileId(oldKey, location.query);
                        }
#elif __ANDROID__ && !__ANDROID_WEAR__
                        if (WidgetUtils.Exists(oldKey))
                        {
                            WidgetUtils.UpdateWidgetIds(oldKey, location);
                        }
#endif
                    }

                    await GetWeatherData();
                }
                catch (WeatherException wEx)
                {
                    errorCallback?.OnWeatherError(wEx);
                }
            }
        }
예제 #3
0
        private async void FollowGPS_Toggled(object sender, RoutedEventArgs e)
        {
            ToggleSwitch sw = sender as ToggleSwitch;

            if (sw.IsOn)
            {
                var geoStatus = GeolocationAccessStatus.Unspecified;

                try
                {
                    // Catch error in case dialog is dismissed
                    geoStatus = await Geolocator.RequestAccessAsync();
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Error, ex, "SettingsPage: error getting location permission");
                }

                // Setup error just in case
                MessageDialog error = null;

                switch (geoStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    // Reset home location data
                    //Settings.SaveLastGPSLocData(new WeatherData.LocationData());
                    break;

                case GeolocationAccessStatus.Denied:
                    error = new MessageDialog(App.ResLoader.GetString("Msg_LocDeniedSettings"), App.ResLoader.GetString("Label_ErrLocationDenied"));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Settings"), async(command) =>
                    {
                        await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                    }, 0));
                    error.Commands.Add(new UICommand(App.ResLoader.GetString("Label_Cancel"), null, 1));
                    error.DefaultCommandIndex = 0;
                    error.CancelCommandIndex  = 1;
                    await error.ShowAsync();

                    sw.IsOn = false;
                    break;

                case GeolocationAccessStatus.Unspecified:
                    error = new MessageDialog(App.ResLoader.GetString("Error_Location"), App.ResLoader.GetString("Label_ErrorLocation"));
                    await error.ShowAsync();

                    sw.IsOn = false;
                    break;

                default:
                    break;
                }
            }

            // Update ids when switching GPS feature
            if (sw.IsOn)
            {
                var prevLoc = (await Settings.GetFavorites()).FirstOrDefault();
                if (prevLoc?.query != null && SecondaryTileUtils.Exists(prevLoc.query))
                {
                    var gpsLoc = await Settings.GetLastGPSLocData();

                    if (gpsLoc?.query == null)
                    {
                        Settings.SaveLastGPSLocData(prevLoc);
                    }
                    else
                    {
                        await SecondaryTileUtils.UpdateTileId(prevLoc.query, gpsLoc.query);
                    }
                }
            }
            else
            {
                var prevLoc = await Settings.GetLastGPSLocData();

                if (prevLoc?.query != null && SecondaryTileUtils.Exists(prevLoc.query))
                {
                    var favLoc = (await Settings.GetFavorites()).FirstOrDefault();
                    if (favLoc?.query != null)
                    {
                        await SecondaryTileUtils.UpdateTileId(prevLoc.query, favLoc.query);
                    }
                }
            }

            Settings.FollowGPS = sw.IsOn;
            RequestAppTrigger  = true;
        }
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS)
            {
                Geoposition newGeoPos = null;
                Geolocator  geolocal  = new Geolocator()
                {
                    DesiredAccuracyInMeters = 5000, ReportInterval = 900000, MovementThreshold = 1600
                };

                try
                {
                    cts.Token.ThrowIfCancellationRequested();
                    newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token);
                }
                catch (OperationCanceledException)
                {
                    return(locationChanged);
                }
                catch (Exception)
                {
                    var geoStatus = GeolocationAccessStatus.Unspecified;

                    try
                    {
                        cts.Token.ThrowIfCancellationRequested();
                        geoStatus = await Geolocator.RequestAccessAsync().AsTask(cts.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        return(locationChanged);
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine(LoggerLevel.Error, ex, "{0}: error requesting location permission", taskName);
                    }
                    finally
                    {
                        if (!cts.IsCancellationRequested && geoStatus == GeolocationAccessStatus.Allowed)
                        {
                            try
                            {
                                newGeoPos = await geolocal.GetGeopositionAsync(TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(10)).AsTask(cts.Token);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteLine(LoggerLevel.Error, ex, "{0}: GetWeather error", taskName);
                            }
                        }
                    }
                }

                // Access to location granted
                if (newGeoPos != null)
                {
                    var lastGPSLocData = await Settings.GetLastGPSLocData();

                    if (cts.IsCancellationRequested)
                    {
                        return(locationChanged);
                    }

                    // Check previous location difference
                    if (lastGPSLocData.query != null &&
                        Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                      newGeoPos.Coordinate.Point.Position.Latitude, newGeoPos.Coordinate.Point.Position.Longitude)) < geolocal.MovementThreshold)
                    {
                        return(false);
                    }

                    LocationQueryViewModel view = null;

                    await Task.Run(async() =>
                    {
                        view = await wm.GetLocation(newGeoPos);

                        if (String.IsNullOrEmpty(view.LocationQuery))
                        {
                            view = new LocationQueryViewModel();
                        }
                    }, cts.Token);

                    if (String.IsNullOrWhiteSpace(view.LocationQuery))
                    {
                        // Stop since there is no valid query
                        return(false);
                    }

                    if (cts.IsCancellationRequested)
                    {
                        return(locationChanged);
                    }

                    // Save oldkey
                    string oldkey = lastGPSLocData.query;

                    // Save location as last known
                    lastGPSLocData.SetData(view, newGeoPos);
                    Settings.SaveLastGPSLocData(lastGPSLocData);

                    // Update tile id for location
                    if (oldkey != null && SecondaryTileUtils.Exists(oldkey))
                    {
                        await SecondaryTileUtils.UpdateTileId(oldkey, lastGPSLocData.query);
                    }

                    locationChanged = true;
                }
            }

            return(locationChanged);
        }