Beispiel #1
0
        public AccessViewModel(IJobManager jobs,
                               INotificationManager notifications = null,
                               ISpeechRecognizer speech = null,
                               IGeofenceManager geofences = null,
                               IGpsManager gps = null,
                               ICentralManager bluetooth = null,
                               IBeaconManager beacons = null)
        {
            this.Append("Jobs", AccessState.Unknown, () => jobs.RequestAccess());

            if (notifications != null)
                this.Append("Notifications", AccessState.Unknown, () => notifications.RequestAccess());

            if (speech != null)
                this.Append("Speech", AccessState.Unknown, () => speech.RequestAccess().ToTask(CancellationToken.None));

            if (gps != null)
                this.Append("GPS", gps.Status, () => gps.RequestAccess(true));

            if (geofences != null)
                this.Append("Geofences", geofences.Status, () => geofences.RequestAccess());

            if (bluetooth != null)
                this.Append("BluetoothLE Central", bluetooth.Status, () => bluetooth.RequestAccess().ToTask(CancellationToken.None));

            if (beacons != null)
                this.Append("iBeacons", beacons.Status, () => beacons.RequestAccess(true));
        }
Beispiel #2
0
        public MapViewModel(IGpsManager gpsManager)
        {
            this.gpsManager = gpsManager;
            this.gpsManager
            .WhenReading()
            .SubOnMainThread(x => this.Position = x.Position)
            .DisposeWith(this.DestroyWith);

            this.Toggle = ReactiveCommand.CreateFromTask(async() =>
            {
                if (this.gpsManager.IsListening)
                {
                    await this.gpsManager.StopListener();
                }
                else
                {
                    var access = await this.gpsManager.RequestAccess(new GpsRequest());
                    if (access == AccessState.Available)
                    {
                        await this.gpsManager.StartListener(null);
                    }
                }
                this.SetText();
            });
        }
 public HomePageViewModel(INavigationService navigationService, IGpsManager gpsManager, IGpsListener gpsListener) : base(navigationService)
 {
     _gpsManager  = gpsManager;
     _gpsListener = gpsListener;
     _gpsListener.OnReadingReceived += OnReadingReceived;
     StartShinyLocation();
 }
Beispiel #4
0
 public LogsViewModel(SampleSqliteConnection conn,
                      IGpsManager manager,
                      IDialogs dialogs) : base(dialogs)
 {
     this.conn    = conn;
     this.manager = manager;
 }
Beispiel #5
0
        /// <summary>
        /// This method will start the GPS with realtime and close on disposable (or when the app backgrounds)
        /// </summary>
        /// <param name="gpsManager"></param>
        /// <returns></returns>
        public static IObservable <IGpsReading> StartAndReceive(this IGpsManager gpsManager) => Observable.Create <IGpsReading>(ob =>
        {
            var composite = new CompositeDisposable();
            var platform  = ShinyHost.Resolve <IPlatform>();
            gpsManager
            .WhenReading()
            .Subscribe(
                ob.OnNext,
                ob.OnError
                )
            .DisposedBy(composite);

            platform
            .WhenStateChanged()
            .Where(x => x == PlatformState.Background)
            .Subscribe(_ => ob.Respond(null))
            .DisposedBy(composite);

            gpsManager
            .StartListener(GpsRequest.Foreground)
            .ContinueWith(x =>
            {
                if (x.IsFaulted)
                {
                    ob.OnError(x.Exception);
                }
            });

            return(() =>
            {
                composite.Dispose();
                gpsManager.StopListener();
            });
        });
        public LocationViewModel(INavigationService navigator, IGpsManager gpsManager)
        {
            this.gpsManager = gpsManager;

            this.Cancel = navigator.GoBackCommand();

            this.PickLocation = navigator.GoBackCommand(
                false,
                p => p
                .Set("Latitude", this.Latitude)
                .Set("Longitude", this.Longitude),
                this.WhenAny(
                    x => x.Latitude,
                    x => x.Longitude,
                    (lat, lng) =>
            {
                var latv = lat.GetValue();
                if (latv != null && (latv >= 89.9 || latv <= -89.9))
                {
                    return(false);
                }

                var lngv = lng.GetValue();
                if (lngv != null && (lngv >= 179.9 || lngv <= -179.9))
                {
                    return(false);
                }

                return(true);
            }
                    )
                );
        }
Beispiel #7
0
        /// <summary>
        /// Requests a single GPS reading by starting the listener and stopping once a reading is received
        /// Requests a single GPS reading - This will start & stop the gps listener if wasn't running already
        /// </summary>
        /// <param name="gpsManager"></param>
        /// <returns></returns>
        public static IObservable <IGpsReading> GetCurrentPosition(this IGpsManager gpsManager) => Observable.FromAsync(async ct =>
        {
            var iStarted = false;
            try
            {
                await currentLocSemaphore
                .WaitAsync(ct)
                .ConfigureAwait(false);

                var task = gpsManager
                           .WhenReading()
                           .Take(1)
                           .ToTask(ct);
                if (!gpsManager.IsListening())
                {
                    iStarted = true;
                    await gpsManager
                    .StartListener(GpsRequest.Foreground)
                    .ConfigureAwait(false);
                }
                var reading = await task.ConfigureAwait(false);

                return(reading);
            }
            finally
            {
                currentLocSemaphore.Release();
                if (iStarted)
                {
                    await gpsManager.StopListener().ConfigureAwait(false);
                }
            }
        });
Beispiel #8
0
        public App()
        {
            InitializeComponent();

            MainPage   = new MainPage();
            gpsManager = Shiny.ShinyHost.Resolve <IGpsManager>();
        }
Beispiel #9
0
        public LocationUpdateService()
        {
            _gpsManager = ShinyHost.Resolve <IGpsManager>();

            MessagingCenter.Subscribe <GpsDelegate, IGpsReading>(this, Constants.Message.LOCATION_UPDATED, async(sender, reading) =>
            {
                if (IsRunning)
                {
                    try
                    {
                        var positions = await State.SetPositionAsync(new PositionUpdate()
                        {
                            Id        = State.Id,
                            Category  = State.Category,
                            Nickname  = State.Nickname,
                            Latitude  = reading.Position.Latitude,
                            Longitude = reading.Position.Longitude,
                            Altitude  = reading.Altitude,
                            Timestamp = reading.Timestamp
                        });

                        //Wakeup();
                    }
                    catch (Exception ex)
                    {
                        Log.Event(ex.Message);
                    }
                }

                State.LastKnownPosition = reading.Position;
            });
        }
Beispiel #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="gpsManager"></param>
        /// <param name="center"></param>
        /// <param name="radius"></param>
        /// <param name="cancelToken"></param>
        /// <returns>Returns null if current position could not be determined - else returns true if in region, false otherwise</returns>
        public static async Task <bool?> IsInsideRegion(this IGpsManager gpsManager, Position center, Distance radius, CancellationToken cancelToken = default)
        {
            var result = await gpsManager.GetCurrentPosition().ToTask(cancelToken);

            var inside = result.Position.GetDistanceTo(center) < radius;

            return(inside);
        }
Beispiel #11
0
        private async Task <ILoraWanGateway> CreateGateway()
        {
            try
            {
                // Create the transceiver:
                TransceiverPinSettings pinSettings = GetTransceiverPinSettings();
                ITransceiver           transceiver = await TransceiverFactory.Create(_gatewaySettings, pinSettings).ConfigureAwait(false);

                transceiver.OnMessageReceived += TransceiverOnMessageReceived;


                // Create the GPS manager (if existing):
                IPositionProvider positionProvider;
                if (UseGpsManager())
                {
                    // Create the GPS manager:
                    IGpsManager gpsManager = await GpsManagerFactory.Create(GpsManagerSettings.Default).ConfigureAwait(false);

                    // Hook up the event fired when a new position is recorded:
                    gpsManager.OnPositionData += GpsManagerPositionDataAsync;

                    // Start the GPS:
                    await gpsManager.WakeUp().ConfigureAwait(false);

                    // Make the Gateway use the GpsManager as position provider
                    // (sending the actual coordinates in its status messages):
                    positionProvider = gpsManager;
                }
                else
                {
                    // Make the Gateway use "no position" as its coordinate:
                    positionProvider = FixedPositionProvider.NoPositionProvider;

                    // ...or give it a fixed coordinate:
                    //positionProvider = new FixedPositionProvider(new SimplePosition(55.597382, 12.95889, 18.4));
                }


                // Get the gateway EUI:
                GatewayEui gatewayEui = await GetGatewayEui().ConfigureAwait(false);

                WriteLog("The gateway EUI: " + gatewayEui);


                // Create the LoRa WAN gateway handler:
                return(LoraWanGatewayFactory.Create(
                           transceiver,
                           _gatewaySettings,
                           gatewayEui,
                           positionProvider));
            }
            catch (Exception exception)
            {
                WriteLog("Failed creating the LoRaWAN gateway:\r\n" + exception.Message);
                Debugger.Break();
                return(null);
            }
        }
Beispiel #12
0
 public GpsManagerTests(ITestOutputHelper output)
 {
     ShinyHost.Init(TestStartup.CurrentPlatform, new ActionStartup
     {
         BuildServices = x => x.UseGps(),
         BuildLogging  = x => x.AddXUnit(output)
     });
     this.gps = ShinyHost.Resolve <IGpsManager>();
 }
        public AccessViewModel(IJobManager jobs,
                               INotificationManager notifications = null,
                               ISpeechRecognizer speech           = null,
                               IGeofenceManager geofences         = null,
                               IGpsManager gps           = null,
                               ICentralManager bluetooth = null,
                               IBeaconManager beacons    = null,
                               IPushManager push         = null,
                               INfcManager nfc           = null)
        {
            this.Append("Jobs", AccessState.Unknown, () => jobs.RequestAccess());

            if (notifications != null)
            {
                this.Append("Notifications", AccessState.Unknown, () => notifications.RequestAccess());
            }

            if (speech != null)
            {
                this.Append("Speech", AccessState.Unknown, () => speech.RequestAccess());
            }

            if (gps != null)
            {
                this.Append("GPS (Background)", gps.GetCurrentStatus(true), () => gps.RequestAccess(true));
            }

            if (geofences != null)
            {
                this.Append("Geofences", geofences.Status, () => geofences.RequestAccess());
            }

            if (bluetooth != null)
            {
                this.Append("BluetoothLE Central", bluetooth.Status, () => bluetooth.RequestAccess().ToTask(CancellationToken.None));
            }

            if (beacons != null)
            {
                this.Append("iBeacons (Monitoring)", beacons.GetCurrentStatus(true), () => beacons.RequestAccess(true));
            }

            if (push != null)
            {
                this.Append("Push", AccessState.Unknown, async() =>
                {
                    var status = await push.RequestAccess();
                    return(status.Status);
                });
            }

            if (nfc != null)
            {
                this.Append("NFC", AccessState.Unknown, () => nfc.RequestAccess().ToTask(CancellationToken.None));
            }
        }
Beispiel #14
0
        /// <summary>
        /// Gets the last reading (can be filtered out by maxAgeOfLastReading) otherwise request the current reading
        /// </summary>
        /// <param name="gpsManager"></param>
        /// <param name="maxAgeOfLastReading"></param>
        /// <returns></returns>
        public static IObservable <IGpsReading> GetLastReadingOrCurrentPosition(this IGpsManager gpsManager, DateTime?maxAgeOfLastReading = null) => Observable.FromAsync <IGpsReading>(async ct =>
        {
            var reading = await gpsManager.GetLastReading().ToTask(ct);
            if (reading == null || (maxAgeOfLastReading != null && reading.Timestamp < maxAgeOfLastReading.Value))
            {
                reading = await gpsManager.GetCurrentPosition().ToTask(ct);
            }

            return(reading);
        });
Beispiel #15
0
        public LogsViewModel(SampleSqliteConnection conn,
                             IGpsManager manager,
                             IDialogs dialogs) : base(dialogs)
        {
            this.conn    = conn;
            this.manager = manager;

            this.WhenAnyValue(x => x.SelectedDate)
            .Skip(1)
            .Subscribe(_ => this.Load.Execute(null));
        }
Beispiel #16
0
        public static async Task <AccessState> RequestAccessAndStart(this IGpsManager gps, GpsRequest request)
        {
            var access = await gps.RequestAccess(request.UseBackground);

            if (access == AccessState.Available)
            {
                await gps.StartListener(request);
            }

            return(access);
        }
Beispiel #17
0
        public GpsViewModel(IGpsManager manager, IUserDialogs dialogs)
        {
            this.manager    = manager;
            this.IsUpdating = this.manager.IsListening;
            this.Access     = this.manager.Status.ToString();

            this.listenerText = this
                                .WhenAnyValue(x => x.IsUpdating)
                                .Select(x => x ? "Stop Listening" : "Start Updating")
                                .ToProperty(this, x => x.ListenerText);

            this.GetCurrentPosition = ReactiveCommand.CreateFromTask(async _ =>
            {
                var reading = await this.manager.GetLastReading();
                if (reading == null)
                {
                    dialogs.Alert("Could not getting GPS coordinates");
                }
                else
                {
                    this.SetValues(reading);
                }
            });
            this.BindBusyCommand(this.GetCurrentPosition);

            this.ToggleUpdates = ReactiveCommand.CreateFromTask(async() =>
            {
                if (this.manager.IsListening)
                {
                    await this.manager.StopListener();
                    this.gpsListener?.Dispose();
                }
                else
                {
                    await this.manager.StartListener(new GpsRequest
                    {
                        UseBackground = true
                    });
                }
                this.IsUpdating = this.manager.IsListening;
            });

            this.RequestAccess = ReactiveCommand.CreateFromTask(async() =>
            {
                var access  = await this.manager.RequestAccess(true);
                this.Access = access.ToString();
            });
            this.BindBusyCommand(this.RequestAccess);
        }
Beispiel #18
0
        public void Start()
        {
            Text element = transform.Find("Text").GetComponent <Text>();

            try {
                IGpsManager manager = GpsManagerFactory.GetManager();

                element.text = string.Format(
                    "Longtitude: {0}\nLatitude: {1}",
                    manager.Longtitude,
                    manager.Latitude
                    );
            } catch (Exception exc) {
                element.text = exc.Message;
            }
        }
Beispiel #19
0
        public LocationViewModel(INavigationService navigator,
                                 IGpsManager gpsManager)
        {
            this.gpsManager = gpsManager;

            this.PickLocation = navigator.GoBackCommand(
                false,
                p => p
                .Set("Latitude", this.Latitude)
                .Set("Longitude", this.Longitude),
                this.WhenAny(
                    x => x.Latitude,
                    x => x.Longitude,
                    (lat, lng) => true
                    )
                );
        }
Beispiel #20
0
        public MainPage(IGpsManager manager, IEventAggregator eventAggregator)
        {
            InitializeComponent();

            var map = new Map
            {
                CRS            = "EPSG:3857",
                Transformation = new MinimalTransformation()
            };

            // map.Limiter.PanLimits = new BoundingBox(new Mapsui.Geometries.Point(45.26, 24.68), new Mapsui.Geometries.Point(60.56, 39.26));
            map.Layers.Add(OpenStreetMap.CreateTileLayer());

            map.Widgets.Add(new ScaleBarWidget(map)
            {
                TextAlignment = Alignment.Center, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top
            });
            map.Widgets.Add(new ZoomInOutWidget {
                MarginX = 20, MarginY = 40
            });
            mapView.Map = map;

            manager.RequestAccessAndStart(new GpsRequest());
            manager.StartListener(new GpsRequest());

            mapView.Navigator = new Navigator(mapView.Map, (IViewport)mapView.Viewport);

            eventAggregator.GetEvent <GpsDataReceivedEvent>().Subscribe(e =>
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                {
                    var coords = new Position(e.Position.Latitude, e.Position.Longitude);
                    info.Text  = $"{coords} - D:{(int)e.Heading} S:{Math.Round(e.Speed, 2)}";

                    mapView.MyLocationLayer.UpdateMyLocation(new Position(e.Position.Latitude, e.Position.Longitude));
                    mapView.MyLocationLayer.UpdateMyDirection(e.Heading, mapView.Viewport.Rotation);
                    mapView.MyLocationLayer.UpdateMySpeed(e.Speed);
                });
            });
        }
Beispiel #21
0
        private async Task InitGpsManager()
        {
            try
            {
                // Create the GPS manager
                _gpsManager = await GpsManagerFactory.Create(GpsManagerSettings.Default).ConfigureAwait(false);

                // Hook up the events
                _gpsManager.OnStandardMessage += GpsManagerStandardMessage;
                _gpsManager.OnCustomMessage   += GpsManagerCustomMessage;
                _gpsManager.OnPositionData    += GpsManagerPositionDataAsync;
                _gpsManager.OnMovementData    += GpsManagerMovementData;

                // Wake up!
                await _gpsManager.WakeUp().ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                WriteLog("The demo crashed:\r\n" + exception.Message);
                Debugger.Break();
            }
        }
Beispiel #22
0
        public GpsViewModel(IGpsManager gps)
        {
            this.Start = ReactiveCommand.CreateFromTask(
                async() =>
            {
                this.foreground = gps
                                  .WhenReading()
                                  .Subscribe(reading =>
                {
                    this.Latitude  = reading.Position.Latitude;
                    this.Longitude = reading.Position.Longitude;
                });

                await gps.StartListener(GpsRequest.Realtime(true));
            }
                );

            this.Stop = ReactiveCommand.CreateFromTask(async() =>
            {
                await gps.StopListener();
                this.foreground?.Dispose();
            });
        }
Beispiel #23
0
        public MapPage(IGpsManager manager, IEventAggregator eventAggregator)
        {
            InitializeComponent();
            mapView.Map = CreateMap();
            manager.RequestAccessAndStart(new GpsRequest()
            {
                Interval = TimeSpan.FromSeconds(5), UseBackground = true
            });

            mapView.Navigator    = new Navigator(mapView.Map, (IViewport)mapView.Viewport);
            this.eventAggregator = eventAggregator;
            eventAggregator.GetEvent <GpsDataReceivedEvent>().Subscribe(e =>
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                {
                    var coords = new Position(e.Position.Latitude, e.Position.Longitude);
                    info.Text  = $"{coords.ToString()} - D:{(int)e.Heading} S:{Math.Round(e.Speed, 2)}";

                    mapView.MyLocationLayer.UpdateMyLocation(new Position(e.Position.Latitude, e.Position.Longitude));
                    mapView.MyLocationLayer.UpdateMyDirection(e.Heading, mapView.Viewport.Rotation);
                    mapView.MyLocationLayer.UpdateMySpeed(e.Speed);
                });
            });
        }
Beispiel #24
0
        public CreateViewModel(INavigationService navigator,
                               IGeofenceManager geofenceManager,
                               IGpsManager gpsManager,
                               IUserDialogs dialogs)
        {
            this.navigator       = navigator;
            this.geofenceManager = geofenceManager;
            this.gpsManager      = gpsManager;
            this.dialogs         = dialogs;

            var hasEventType = this.WhenAny(
                x => x.NotifyOnEntry,
                x => x.NotifyOnExit,
                (entry, exit) => entry.GetValue() || exit.GetValue()
                );

            geofenceManager
            .WhenAccessStatusChanged()
            .ToPropertyEx(this, x => x.AccessStatus);

            this.SetCurrentLocation = ReactiveCommand.CreateFromTask(async ct =>
            {
                var loc              = await this.gpsManager.GetLastReading().ToTask(ct);
                this.CenterLatitude  = loc?.Position?.Latitude ?? 0;
                this.CenterLongitude = loc?.Position?.Longitude ?? 0;
            });
            this.BindBusyCommand(this.SetCurrentLocation);

            //this.RequestAccess = ReactiveCommand.CreateFromTask(
            //    async () => await geofenceManager.RequestAccess()
            //);

            this.AddCnTower = ReactiveCommand.CreateFromTask(
                _ => this.AddGeofence(
                    "CNTowerToronto",
                    43.6425662,
                    -79.3892508,
                    DEFAULT_DISTANCE_METERS
                    ),
                hasEventType
                );

            this.AddAppleHQ = ReactiveCommand.CreateFromTask(
                _ => this.AddGeofence(
                    "AppleHQ",
                    37.3320045,
                    -122.0329699,
                    DEFAULT_DISTANCE_METERS
                    ),
                hasEventType
                );

            this.CreateGeofence = ReactiveCommand.CreateFromTask(
                _ => this.AddGeofence
                (
                    this.Identifier,
                    this.CenterLatitude,
                    this.CenterLongitude,
                    this.RadiusMeters
                ),
                this.WhenAny(
                    //x => x.AccessStatus,
                    x => x.Identifier,
                    x => x.RadiusMeters,
                    x => x.CenterLatitude,
                    x => x.CenterLongitude,
                    x => x.NotifyOnEntry,
                    x => x.NotifyOnExit,
                    //(access, id, rad, lat, lng, entry, exit) =>
                    (id, rad, lat, lng, entry, exit) =>
            {
                //if (access.GetValue() != AccessState.Available)
                //    return false;

                if (id.GetValue().IsEmpty())
                {
                    return(false);
                }

                var radius = rad.GetValue();
                if (radius < 200 || radius > 5000)
                {
                    return(false);
                }

                var latv = lat.GetValue();
                if (latv >= 89.9 || latv <= -89.9)
                {
                    return(false);
                }

                var lngv = lng.GetValue();
                if (lngv >= 179.9 || lngv <= -179.9)
                {
                    return(false);
                }

                if (!entry.GetValue() && !exit.GetValue())
                {
                    return(false);
                }

                return(true);
            }
                    )
                );
        }
Beispiel #25
0
        public GpsViewModel(IGpsManager manager, IUserDialogs dialogs)
        {
            this.manager    = manager;
            this.IsUpdating = this.manager.IsListening;

            this.WhenAnyValue(x => x.UseBackground)
            .Subscribe(x => this.Access = this.manager.GetCurrentStatus(this.UseBackground).ToString());

            this.WhenAnyValue(x => x.IsUpdating)
            .Select(x => x ? "Stop Listening" : "Start Updating")
            .ToPropertyEx(this, x => x.ListenerText);

            this.GetCurrentPosition = ReactiveCommand.CreateFromTask(async _ =>
            {
                var result = await dialogs.RequestAccess(() => this.manager.RequestAccess(true));
                if (!result)
                {
                    return;
                }

                var reading = await this.manager.GetLastReading();
                if (reading == null)
                {
                    await dialogs.Alert("Could not getting GPS coordinates");
                }
                else
                {
                    this.SetValues(reading);
                }
            });
            this.BindBusyCommand(this.GetCurrentPosition);

            this.SelectPriority = ReactiveCommand.Create(() => dialogs.ActionSheet(
                                                             new ActionSheetConfig()
                                                             .SetTitle("Select Priority/Desired Accuracy")
                                                             .Add("Highest", () => this.Priority = GpsPriority.Highest)
                                                             .Add("Normal", () => this.Priority  = GpsPriority.Normal)
                                                             .Add("Low", () => this.Priority     = GpsPriority.Low)
                                                             .AddCancel()
                                                             ));

            this.ToggleUpdates = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (this.manager.IsListening)
                {
                    await this.manager.StopListener();
                    this.gpsListener?.Dispose();
                }
                else
                {
                    var result = await dialogs.RequestAccess(() => this.manager.RequestAccess(this.UseBackground));
                    if (!result)
                    {
                        await dialogs.Alert("Insufficient permissions");
                        return;
                    }

                    var request = new GpsRequest
                    {
                        UseBackground = this.UseBackground,
                        Priority      = this.Priority,
                    };
                    if (IsInterval(this.DesiredInterval))
                    {
                        request.Interval = ToInterval(this.DesiredInterval);
                    }

                    if (IsInterval(this.ThrottledInterval))
                    {
                        request.ThrottledInterval = ToInterval(this.ThrottledInterval);
                    }

                    await this.manager.StartListener(request);
                }
                this.IsUpdating = this.manager.IsListening;
            },
                this.WhenAny(
                    x => x.IsUpdating,
                    x => x.DesiredInterval,
                    x => x.ThrottledInterval,
                    (u, i, t) =>
            {
                if (u.GetValue())
                {
                    return(true);
                }

                var isdesired   = IsInterval(i.GetValue());
                var isthrottled = IsInterval(t.GetValue());

                if (isdesired && isthrottled)
                {
                    var desired  = ToInterval(i.GetValue());
                    var throttle = ToInterval(t.GetValue());
                    if (throttle.TotalSeconds >= desired.TotalSeconds)
                    {
                        return(false);
                    }
                }
                return(true);
            }
                    )
                );

            this.UseRealtime = ReactiveCommand.Create(() =>
            {
                var rt = GpsRequest.Realtime(false);
                this.ThrottledInterval = String.Empty;
                this.DesiredInterval   = rt.Interval.TotalSeconds.ToString();
                this.Priority          = rt.Priority;
            });

            this.RequestAccess = ReactiveCommand.CreateFromTask(async() =>
            {
                var access  = await this.manager.RequestAccess(this.UseBackground);
                this.Access = access.ToString();
            });
            this.BindBusyCommand(this.RequestAccess);
        }
Beispiel #26
0
        public CreateViewModel(IGeofenceManager geofenceManager,
                               IGpsManager gpsManager,
                               IUserDialogs dialogs)
        {
            this.geofenceManager = geofenceManager;
            this.gpsManager      = gpsManager;
            this.dialogs         = dialogs;

            var hasEventType = this.WhenAny(
                x => x.NotifyOnEntry,
                x => x.NotifyOnExit,
                (entry, exit) => entry.GetValue() || exit.GetValue()
                );

            this.SetCurrentLocation = ReactiveCommand.CreateFromTask(async ct =>
            {
                var loc              = await this.gpsManager.GetLastReading().ToTask(ct);
                this.CenterLatitude  = loc?.Position?.Latitude ?? 0;
                this.CenterLongitude = loc?.Position?.Longitude ?? 0;
            });
            this.BindBusyCommand(this.SetCurrentLocation);

            this.AddCnTower = ReactiveCommand.CreateFromTask(
                _ => this.AddGeofence(
                    "CNTowerToronto",
                    43.6425662,
                    -79.3892508,
                    DEFAULT_DISTANCE_METERS
                    ),
                hasEventType
                );

            this.AddAppleHQ = ReactiveCommand.CreateFromTask(
                _ => this.AddGeofence(
                    "AppleHQ",
                    37.3320045,
                    -122.0329699,
                    DEFAULT_DISTANCE_METERS
                    ),
                hasEventType
                );

            this.CreateGeofence = ReactiveCommand.CreateFromTask(
                async _ =>
            {
                await this.AddGeofence(
                    this.Identifier,
                    this.CenterLatitude,
                    this.CenterLongitude,
                    this.RadiusMeters
                    );
                this.Identifier      = String.Empty;
                this.CenterLatitude  = 0;
                this.CenterLongitude = 0;
                this.RadiusMeters    = DEFAULT_DISTANCE_METERS;
            },
                this.WhenAny(
                    x => x.Identifier,
                    x => x.RadiusMeters,
                    x => x.CenterLatitude,
                    x => x.CenterLongitude,
                    x => x.NotifyOnEntry,
                    x => x.NotifyOnExit,
                    (id, rad, lat, lng, entry, exit) =>
            {
                if (String.IsNullOrWhiteSpace(id.GetValue()))
                {
                    return(false);
                }

                var radius = rad.GetValue();
                if (radius < 200 || radius > 5000)
                {
                    return(false);
                }

                var latv = lat.GetValue();
                if (latv >= 89.9 || latv <= -89.9)
                {
                    return(false);
                }

                var lngv = lng.GetValue();
                if (lngv >= 179.9 || lngv <= -179.9)
                {
                    return(false);
                }

                if (!entry.GetValue() && !exit.GetValue())
                {
                    return(false);
                }

                return(true);
            }
                    )
                );
        }
        public GpsViewModel(IGpsManager manager, IUserDialogs dialogs)
        {
            this.manager    = manager;
            this.IsUpdating = this.manager.IsListening;

            this.WhenAnyValue(x => x.UseBackground)
            .Subscribe(x => this.Access = this.manager.GetCurrentStatus(this.UseBackground).ToString());

            this.WhenAnyValue(x => x.IsUpdating)
            .Select(x => x ? "Stop Listening" : "Start Updating")
            .ToPropertyEx(this, x => x.ListenerText);

            this.GetCurrentPosition = ReactiveCommand.CreateFromTask(async _ =>
            {
                var result = await dialogs.RequestAccess(() => this.manager.RequestAccess(true));
                if (!result)
                {
                    return;
                }

                var reading = await this.manager.GetLastReading();
                if (reading == null)
                {
                    dialogs.Alert("Could not getting GPS coordinates");
                }
                else
                {
                    this.SetValues(reading);
                }
            });
            this.BindBusyCommand(this.GetCurrentPosition);

            this.SelectPriority = ReactiveCommand.Create(() => dialogs.ActionSheet(
                                                             new ActionSheetConfig()
                                                             .SetTitle("Select Priority/Desired Accuracy")
                                                             .Add("Highest", () => this.Priority = GpsPriority.Highest)
                                                             .Add("Normal", () => this.Priority  = GpsPriority.Normal)
                                                             .Add("Low", () => this.Priority     = GpsPriority.Low)
                                                             .SetCancel()
                                                             ));

            this.ToggleUpdates = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (this.manager.IsListening)
                {
                    await this.manager.StopListener();
                    this.gpsListener?.Dispose();
                }
                else
                {
                    var result = await dialogs.RequestAccess(() => this.manager.RequestAccess(this.UseBackground));
                    if (!result)
                    {
                        dialogs.Alert("Insufficient permissions");
                        return;
                    }

                    var request = new GpsRequest
                    {
                        UseBackground = this.UseBackground,
                        Priority      = this.Priority
                    };
                    var meters = ToDeferred(this.DeferredMeters);
                    if (meters > 0)
                    {
                        request.DeferredDistance = Distance.FromMeters(meters);
                    }

                    var secs = ToDeferred(this.DeferredSeconds);
                    if (secs > 0)
                    {
                        request.DeferredTime = TimeSpan.FromSeconds(secs);
                    }

                    await this.manager.StartListener(request);
                }
                this.IsUpdating = this.manager.IsListening;
            },
                this.WhenAny(
                    x => x.IsUpdating,
                    x => x.DeferredMeters,
                    x => x.DeferredSeconds,
                    (u, m, s) =>
                    u.GetValue() ||
                    (
                        ToDeferred(m.GetValue()) >= 0 &&
                        ToDeferred(s.GetValue()) >= 0
                    )
                    )
                );

            this.RequestAccess = ReactiveCommand.CreateFromTask(async() =>
            {
                var access  = await this.manager.RequestAccess(this.UseBackground);
                this.Access = access.ToString();
            });
            this.BindBusyCommand(this.RequestAccess);
        }
Beispiel #28
0
 /// <summary>
 /// Returns true if there is a current GPS listener configuration running
 /// </summary>
 /// <param name="manager"></param>
 /// <returns></returns>
 public static bool IsListening(this IGpsManager manager) => manager.CurrentListener != null;
 public MainPageViewModel(IGpsManager gpsManager, IGpsListener gpsListener)
 {
     _gpsManager  = gpsManager;
     _gpsListener = gpsListener;
     _gpsListener.OnReadingReceived += OnReadingReceived;
 }
Beispiel #30
0
 public LocationTask()
 {
     _notificationManager = DependencyService.Get <INotificationManager>();
     _notificationManager.Initialize("foreground2", "foreground2", "this is channel", 0);
     _gpsManager = ShinyHost.Resolve <IGpsManager>();
 }