Exemple #1
0
        /// <summary>
        /// Initiates the acquisition of data from the current location provider. This method returns synchronously.
        /// </summary>
        /// <param name="suppressPermissionPrompt">Not used.</param>
        /// <param name="timeout">Time in milliseconds to wait for the location provider to start before timing out.</param>
        /// <returns>true if data acquisition is started within the time period specified by timeout; otherwise, false.</returns>
        /// <remarks>This method blocks during the time period specified by timeout.
        /// Use caution when calling TryStart from the user interface thread of your application.</remarks>
        /// <example>The following example demonstrates how to call TryStart.
        /// <code lang="cs">
        /// using System;
        /// using System.Device.Location;
        ///
        /// namespace GetLocationProperty
        /// {
        ///     class Program
        ///     {
        ///         static void Main(string[] args)
        ///         {
        ///             GetLocationProperty();
        ///         }
        ///
        ///         static void GetLocationProperty()
        ///         {
        ///             GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
        ///
        ///             // Do not suppress prompt, and wait 1000 milliseconds to start.
        ///             watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
        ///
        ///             GeoCoordinate coord = watcher.Position.Location;
        ///
        ///             if (coord.IsUnknown != true)
        ///             {
        ///                 Debug.WriteLine("Lat: {0}, Long: {1}", coord.Latitude, coord.Longitude);
        ///             }
        ///             else
        ///             {
        ///                 Debug.WriteLine("Unknown latitude and longitude.");
        ///             }
        ///         }
        ///     }
        /// }
        /// </code></example>
        public bool TryStart(bool suppressPermissionPrompt, TimeSpan timeout)
        {
            if (!active)
            {
                active = OpenDevice();

                if (!active)
                {
                    status = GeoPositionStatus.Disabled;
                    return(false);
                }

                Stopwatch st = new Stopwatch();
                st.Start();
                while (st.ElapsedMilliseconds < timeout.TotalMilliseconds)
                {
                    GetDeviceState(false);
                    if (status == GeoPositionStatus.Ready)
                    {
                        break;
                    }
                }
                st.Stop();

                // start worker thread
                System.Threading.Thread workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(Worker));
                workerThread.Name         = "InTheHand.Device.Location.GeoCoordinateWatcher_Worker";
                workerThread.IsBackground = true;
                workerThread.Start();

                return(status == GeoPositionStatus.Ready);
            }

            return(false);
        }
Exemple #2
0
        /// <summary>
        /// Stops the <see cref="GeoCoordinateWatcher"/> from providing location data and events.
        /// </summary>
        /// <remarks>After <see cref="Stop"/> is called, no further <see cref="PositionChanged"/> events occur, and the <see cref="Position"/> property will return <see cref="GeoCoordinate.Unknown"/>.
        /// When <see cref="Stop"/> is called, the <see cref="Status"/> property is set to <see cref="GeoPositionStatus.Disabled"/>.</remarks>
        public void Stop()
        {
            if (active)
            {
                this.active = false;

                System.Diagnostics.Debug.WriteLine("InTheHand.Device.Location.GeoCoordinateWatcher.Stop");

                //reset status
                this.status = GeoPositionStatus.Disabled;
                OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(GeoPositionStatus.Disabled));

                currentPosition  = GeoCoordinate.Unknown;
                currentTimeStamp = new DateTimeOffset(0, new TimeSpan(0));

                //inform worker thread to stop
                if (waitHandles[0] != null)
                {
                    waitHandles[0].Set();
                }

                //worker thread must give up the lock
                lock (this)
                {
                    if (handle != IntPtr.Zero)
                    {
                        int hresult = NativeMethods.CloseDevice(handle);
                        handle = IntPtr.Zero;
                    }
                }
            }
        }
 void UpdateStatus(GeoPositionStatus status)
 {
     if (mGPSCallback != null)
     {
         mGPSCallback(status);
     }
 }
Exemple #4
0
        private void GetDeviceState(bool raiseEvent)
        {
            // get device state
            int result = NativeMethods.GetDeviceState(ref device);

            CheckResponse(result);

            // debug
            System.Diagnostics.Debug.WriteLine(string.Format("Service state: {0}", device.dwServiceState));
            System.Diagnostics.Debug.WriteLine(string.Format("Device state: {0}", device.dwDeviceState));
            System.Diagnostics.Debug.WriteLine(string.Format("Last data received: {0}", DateTime.FromFileTimeUtc(device.ftLastDataReceived)));
            System.Diagnostics.Debug.WriteLine(string.Format("Friendly name: {0}", device.szGPSFriendlyName));
            System.Diagnostics.Debug.WriteLine(string.Format("GPS driver prefix: {0}", device.szGPSDriverPrefix));
            System.Diagnostics.Debug.WriteLine(string.Format("GPS multiplex prefix: {0}", device.szGPSMultiplexPrefix));

            status = ToGeoPositionStatus(device.dwDeviceState);

            if (raiseEvent)
            {
                try
                {
                    OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(this.Status));
                }
                catch
                {
                    System.Diagnostics.Debug.WriteLine("Exception in GetDeviceState->OnPositionStatusChanged");
                }
            }
        }
Exemple #5
0
        void geoWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            currentState = e.Status;

            switch (e.Status)
            {
            case GeoPositionStatus.Disabled:
                if (geoWatcher.Permission == GeoPositionPermission.Denied)
                {
                    string[] strings = { "ok" };
                    Guide.BeginShowMessageBox("Info", "Please turn on geo-location service in the settings tab.", strings, 0, 0, ExitGame, null);
                }
                else
                if (geoWatcher.Permission == GeoPositionPermission.Granted)
                {
                    string[] strings = { "ok" };
                    Guide.BeginShowMessageBox("Error", "Your device doesn't support geo-location service.", strings, 0, 0, ExitGame, null);
                }
                break;

            case GeoPositionStatus.Ready:
                CurrentGeoCoord = geoWatcher.Position;
                break;
            }
        }
Exemple #6
0
        /// <summary>
        /// Initiate the acquisition of data from the current location provider.
        /// This method enables <see cref="PositionChanged"/> events and allows access to the <see cref="Position"/> property.
        /// </summary>
        /// <param name="suppressPermissionPrompt">Not used.</param>
        public void Start(bool suppressPermissionPrompt)
        {
            if (active)
            {
                return;
                //already running
            }

            System.Diagnostics.Debug.WriteLine("InTheHand.Device.Location.GeoCoordinateWatcher.Start");

            active = OpenDevice();

            if (active)
            {
                //get initial device state
                GetDeviceState(false);

                //get initial position
                GetPosition(false);

                //start worker thread
                System.Threading.Thread workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(Worker));
                workerThread.Name         = "InTheHand.Device.Location.GeoCoordinateWatcher_Worker";
                workerThread.IsBackground = true;
                workerThread.Start();
            }
            else
            {
                status = GeoPositionStatus.Disabled;
            }
        }
Exemple #7
0
        // converts GPSAPI status to System.Device status
        private static GeoPositionStatus ToGeoPositionStatus(NativeMethods.SERVICE_STATE state)
        {
            GeoPositionStatus newStatus = GeoPositionStatus.NoData;

            switch (state)
            {
            case NativeMethods.SERVICE_STATE.SERVICE_STATE_UNKNOWN:
            case NativeMethods.SERVICE_STATE.SERVICE_STATE_OFF:
                newStatus = GeoPositionStatus.Disabled;
                break;

            case NativeMethods.SERVICE_STATE.SERVICE_STATE_UNLOADING:
            case NativeMethods.SERVICE_STATE.SERVICE_STATE_UNINITIALIZED:
            case NativeMethods.SERVICE_STATE.SERVICE_STATE_SHUTTING_DOWN:
                newStatus = GeoPositionStatus.NoData;
                break;

            case NativeMethods.SERVICE_STATE.SERVICE_STATE_STARTING_UP:
            case NativeMethods.SERVICE_STATE.SERVICE_STATE_ON:
                newStatus = GeoPositionStatus.Initializing;
                break;
            }

            return(newStatus);
        }
Exemple #8
0
        private void RefreshLocationStatuses()
        {
            // Handles first cases where no location is found.

            GeoPositionStatus locStatus = Model.Core.DeviceLocationStatus;

            // Location service is disabled or unavailable.
            if (locStatus == GeoPositionStatus.Disabled)
            {
                LocationWarning = "This device's location services are disabled or not working.";
            }

            // Location service is OK but no data was found.
            else if (locStatus == GeoPositionStatus.NoData)
            {
                LocationWarning = "Location services are enabled but gave no data so far.";
            }

            else if (locStatus == GeoPositionStatus.Initializing)
            {
                LocationWarning = null;
            }

            if (locStatus != GeoPositionStatus.Ready)
            {
                LocationStatus         = "Status: " + locStatus.ToString();
                LocationAccuracyStatus = null;
                return;
            }

            // Location service is OK and data should be here.
            GeoCoordinate loc = Model.Core.DeviceLocation;

            // Data is not valid.
            if (loc == null || loc.IsUnknown)
            {
                LocationWarning = "Location services are enabled but only gave invalid data so far.";
                LocationStatus  = "Status: " + locStatus.ToString();
                return;
            }

            // Data is valid.
            bool isPoorAccuracy = loc.HorizontalAccuracy >= MaxGoodLocationAccuracy;

            LocationStatus         = loc.ToZonePoint().ToString(GeoCoordinateUnit.DegreesMinutes);
            LocationAccuracyStatus = String.Format("Accuracy: {0:0.00}m ({1})",
                                                   loc.HorizontalAccuracy,
                                                   isPoorAccuracy ? "POOR" : "OK");

            // Shows a warning for low accuracy.
            if (isPoorAccuracy)
            {
                LocationWarning = "Very low accuracy. Try looking for clear sky.";
            }
            else
            {
                LocationWarning = null;
            }
        }
 private void ChangeStatusWithEvent(GeoPositionStatus status)
 {
     Status = status;
     if (StatusChanged != null)
     {
         StatusChanged(this, new GeoPositionStatusChangedEventArgs(status));
     }
 }
 private void CoordinateWatcher_OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs args)
 {
     if (this._statusChangedCallback == null)
     {
         return;
     }
     this.PositionStatus = args.Status;
     this._statusChangedCallback(this.PositionStatus);
 }
 public void Start(bool cevaParametru)
 {
     Status = GeoPositionStatus.Ready;
     ChangePosition(DateTime.Now, new GeoCoordinate(44.448074, 26.081837));
     ChangePosition(DateTime.Now, new GeoCoordinate(44.447959, 26.082315));
     ChangePosition(DateTime.Now, new GeoCoordinate(44.447924, 26.082518));
     ChangePosition(DateTime.Now, new GeoCoordinate(44.448231, 26.082679));
     ChangePosition(DateTime.Now, new GeoCoordinate(44.450681, 26.084096));
     ChangePosition(DateTime.Now, new GeoCoordinate(44.451187, 26.084364));
 }
        private void ChangeStatusWithEvent(GeoPositionStatus status, GeoCoordinate currentLocation)
        {
            Position = new GeoPosition <GeoCoordinate>(DateTimeOffset.Now, currentLocation);
            ChangeStatusWithEvent(status);

            if (PositionChanged != null)
            {
                PositionChanged(this, new GeoPositionChangedEventArgs <GeoCoordinate>(Position));
            }
        }
        public void ChangeStatus(GeoPositionStatus geoPositionStatus)
        {
            Status = geoPositionStatus;

            var handler = StatusChanged;

            if (handler != null)
            {
                handler(null, new GeoPositionStatusChangedEventArgs(geoPositionStatus));
            }
        }
        // Event handler for the GeoCoordinateWatcher.StatusChanged event.
        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            _gpsStatus = e.Status;

            switch (e.Status)
            {
            case GeoPositionStatus.Disabled:
                // The Location Service is disabled or unsupported.
                // Check to see whether the user has disabled the Location Service.
                if (watcher.Permission == GeoPositionPermission.Denied)
                {
                    // The user has disabled the Location Service on their device.
                    MessageText.Text    = "Location services disabled. To use this feature, turn on location from the phone settings menu.";
                    MapPanel.Visibility = Visibility.Collapsed;
                    AppLocationDisabledMessage.Visibility = Visibility.Collapsed;
                    MessagePanel.Visibility = Visibility.Visible;
                    MessageBox.Show("Location services disabled.");
                    watcher.Stop();
                }
                else
                {
                    // Location service is not functioning (not supported?)
                    MessageText.Text    = "Location services disabled. To use this feature, turn on location from the phone settings menu.";
                    MapPanel.Visibility = Visibility.Collapsed;
                    AppLocationDisabledMessage.Visibility = Visibility.Collapsed;
                    MessagePanel.Visibility = Visibility.Visible;
                    MessageBox.Show("Location services disabled.");
                    watcher.Stop();
                }
                break;

            case GeoPositionStatus.Initializing:
                // The Location Service is initializing.
                break;

            case GeoPositionStatus.NoData:
                // The Location Service is working, but it cannot get location data.
                MessageText.Text    = "Location cannot be aquired. Please try again.";
                MapPanel.Visibility = Visibility.Collapsed;
                AppLocationDisabledMessage.Visibility = Visibility.Collapsed;
                MessagePanel.Visibility = Visibility.Visible;
                MessageBox.Show("Location cannot be aquired.");
                watcher.Stop();
                break;

            case GeoPositionStatus.Ready:
                // The Location Service is working and is receiving location data.
                refreshData();
                break;
            }
        }
 // get the broadcast event
 private void LocationServiceStatusCallback(GeoPositionStatus status)
 {
     switch (status)
     {
         case GeoPositionStatus.Disabled:
             break;
         case GeoPositionStatus.Initializing:
             break;
         case GeoPositionStatus.NoData:
             break;
         case GeoPositionStatus.Ready:
             break;
     }
 }
Exemple #16
0
 void gps_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     gpsStatus = e.Status;
     if (gpsStatus == GeoPositionStatus.Disabled || gpsStatus == GeoPositionStatus.NoData)
     {
         try
         {
             UIWorker.addUIEvent(c_pos2, 'V', 0, 0, 0, false);
         }
         catch (Exception ex)
         {
             Logger.log("Exception in do_async_connect_cb: " + ex.ToString());
         }
     }
 }
        // get the broadcast event
        private void LocationServiceStatusCallback(GeoPositionStatus status)
        {
            switch (status)
            {
            case GeoPositionStatus.Disabled:
                break;

            case GeoPositionStatus.Initializing:
                break;

            case GeoPositionStatus.NoData:
                break;

            case GeoPositionStatus.Ready:
                break;
            }
        }
 private void HandlePositionStatus(GeoPositionStatus status)
 {
     if (status == GeoPositionStatus.Ready)
     {
         this._viewModel.StopLoading();
         VisualStateManager.GoToState((Control)this, "Disabled", false);
     }
     else
     {
         VisualStateManager.GoToState((Control)this, "Normal", false);
         if (status != GeoPositionStatus.Initializing)
         {
             return;
         }
         this._viewModel.StartLoading();
     }
 }
Exemple #19
0
        public static LocationServiceStatus ToLocationServiceStatus(this GeoPositionStatus positionStatus)
        {
            switch (positionStatus)
            {
            case GeoPositionStatus.Disabled:
                return(LocationServiceStatus.Disabled);

            case GeoPositionStatus.Ready:
                return(LocationServiceStatus.Ready);

            case GeoPositionStatus.Initializing:
                return(LocationServiceStatus.Initializing);

            case GeoPositionStatus.NoData:
                return(LocationServiceStatus.NoData);

            default:
                throw new ArgumentOutOfRangeException("positionStatus");
            }
        }
Exemple #20
0
        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void geoWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            currentState = e.Status;

            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    if (watcher.Permission == GeoPositionPermission.Denied)
                    {
                        string[] strings = { "ok" };
                        //Guide.BeginShowMessageBox("Info", "Please turn on geo-location service in the settings tab.", strings, 0, 0, ExitGame, null);
                    }
                    else
                        if (watcher.Permission == GeoPositionPermission.Granted)
                        {
                            string[] strings = { "ok" };
                            //Guide.BeginShowMessageBox("Error", "Your device doesn't support geo-location service.", strings, 0, 0, ExitGame, null);
                        }
                    break;

                case GeoPositionStatus.Ready:
                    currentLocation = watcher.Position.Location;
                    break;
            }
        }
        public void ChangeStatus(GeoPositionStatus geoPositionStatus)
        {
            Status = geoPositionStatus;

            var handler = StatusChanged;
            if (handler != null)
                handler(null, new GeoPositionStatusChangedEventArgs(geoPositionStatus));
        }
Exemple #22
0
 private void WatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     _status = e.Status;
 }
 public LocationUnavailableException(string message, GeoPositionStatus status)
     : base(message)
 {
     Status = status;
 }
Exemple #24
0
        private void GetPosition(bool raiseEvent)
        {
            bool isValid = false;

            // reset flags
            position.dwValidFields = 0;

            // get position
            int result = NativeMethods.GetPosition(handle, ref position, 2000, 0);

            // fix for WM6.1 devices which broke the version checking
            if (result == 87)
            {
                position.dwSize = NativeMethods.GPS_POSITION.GPS_POSITION_SIZE_V2;
                // now check again
                result = NativeMethods.GetPosition(handle, ref position, 2000, 0);
            }

            CheckResponse(result);

            // must be at least one valid field
            if (position.dwValidFields > 0)
            {
                // check that lat, long and time are valid
                if (position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.LATITUDE | NativeMethods.GPS_VALID.LONGITUDE | NativeMethods.GPS_VALID.UTC_TIME))
                {
                    System.Diagnostics.Debug.WriteLine(position.stUTCTime.ToDateTime(DateTimeKind.Utc).ToString() + "," + position.dblLatitude.ToString() + "," + position.dblLongitude.ToString());

                    // ignore readings where the time is said to be valid but is zero
                    if (position.stUTCTime.year != 0)
                    {
                        isValid = true;
                    }

                    // motorola sometimes returns this field as valid but with 0 - which means no satellites used to obtain a fix
                    if (/*position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.SATELLITE_COUNT) &&*/ (position.dwSatelliteCount < 3))
                    {
                        isValid = false;
                    }

                    // widely accepted that 7 is maximum for a useful position
                    if (position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.HORIZONTAL_DILUTION_OF_PRECISION) && position.flHorizontalDilutionOfPrecision > 7)
                    {
                        isValid = false;
                    }
                }
            }

            if (isValid)
            {
                // get the timestamp
                DateTimeOffset timestamp = new DateTimeOffset(position.stUTCTime.year, position.stUTCTime.month, position.stUTCTime.day, position.stUTCTime.hour, position.stUTCTime.minute, position.stUTCTime.second, new TimeSpan(0));
                currentTimeStamp = timestamp;

                // calculate the horizontal uncertainty
                double accuracy = 0.0;
                if (position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.POSITION_UNCERTAINTY_ERROR))
                {
                    // v2 method
                    double avgError = (position.PositionUncertaintyError.dwHorizontalErrorAlong + position.PositionUncertaintyError.dwHorizontalErrorPerp) / 2f;
                    // get the 1 sigma radius
                    accuracy = avgError / position.PositionUncertaintyError.dwHorizontalConfidence * 39;
                }
                else
                {
                    // legacy method
                    if (position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.HORIZONTAL_DILUTION_OF_PRECISION))
                    {
                        accuracy = (position.flHorizontalDilutionOfPrecision <= 50.0 ? position.flHorizontalDilutionOfPrecision : 50.0) * NativeMethods.DOP_TO_METRES;
                    }
                    else
                    {
                        accuracy = double.NaN;
                    }
                }

                // get the coordinates
                GeoCoordinate latLon = new GeoCoordinate(position.dblLatitude, position.dblLongitude,
                                                         position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.ALTITUDE_WRT_SEA_LEVEL) ? position.flAltitudeWRTSeaLevel : (position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.ALTITUDE_WRT_ELLIPSOID) ? position.flAltitudeWRTEllipsoid : double.NaN),
                                                         accuracy,
                                                         position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.POSITION_UNCERTAINTY_ERROR) ? position.PositionUncertaintyError.dwVerticalError : (position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.VERTICAL_DILUTION_OF_PRECISION) ? (position.flVerticalDilutionOfPrecision <= 50.0 ? position.flVerticalDilutionOfPrecision : 50.0) * NativeMethods.DOP_TO_METRES : double.NaN),
                                                         position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.SPEED) ? position.flSpeed * NativeMethods.KNOTS_TO_METRES_PER_SECOND : double.NaN,
                                                         position.dwValidFields.HasFlag(NativeMethods.GPS_VALID.HEADING) ? position.flHeading : double.NaN);

                currentPosition = latLon;

                // raise event?
                if (raiseEvent)
                {
                    if (Status != GeoPositionStatus.Ready)
                    {
                        status = GeoPositionStatus.Ready;
                        OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(GeoPositionStatus.Ready));
                    }

                    // only raise an event if movement threshold is exceeded
                    if (this.MovementThreshold == 0.0 || latLon.GetDistanceTo(currentPosition) > this.MovementThreshold)
                    {
                        OnPositionChanged(new GeoPositionChangedEventArgs <GeoCoordinate>(new GeoPosition <GeoCoordinate>(timestamp, latLon)));
                    }
                }
            }
            else
            {
                // running but no current fix
                if (raiseEvent && (Status == GeoPositionStatus.Ready))
                {
                    status = GeoPositionStatus.NoData;
                    OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(GeoPositionStatus.NoData));
                }
            }
        }
Exemple #25
0
        /// <summary>
        /// Thread pool callback used to ensure location COM API is instantiated from
        /// multi-thread apartment, and register for location events.
        /// </summary>
        /// <param name="state"></param>
        private void CreateHandler(object state)
        {
            lock (this.InternalSyncObject)
            {
                try
                {
                    m_location = new COMLocation() as ILocation;
                }
                catch (COMException)
                {
                    Utility.Trace("Failed to CoCreate ILocation COM object.");
                }

                if (null != m_location)
                {
                    Utility.Trace("Successfully created ILocation COM object");

                    //
                    // Mapping to platform accuracy
                    //
                    GeoPositionAccuracy desiredAccuracy = (GeoPositionAccuracy)state;
                    DesiredAccuracy     accuracy        = (desiredAccuracy == GeoPositionAccuracy.Default) ?
                                                          DesiredAccuracy.DefaultAccuracy : DesiredAccuracy.HighAccuracy;

                    Guid reportKey = LocationReportKey.LatLongReport;
                    m_location.SetDesiredAccuracy(ref reportKey, accuracy);

                    //
                    // Always listen for latlong reports
                    //
                    if (m_location.RegisterForReport(this, ref reportKey, 0) == 0)
                    {
                        m_latLongRegistered = true;
                    }
                    //
                    // Check the latlong status. If latlong reports are not supported, then register
                    // for civic address reports.
                    //
                    m_location.GetReportStatus(ref reportKey, ref m_latLongStatus);

                    if (ReportStatus.NotSupported == m_latLongStatus)
                    {
                        reportKey = LocationReportKey.CivicAddressReport;
                        if (m_location.RegisterForReport(this, ref reportKey, 0) == 0)
                        {
                            m_civicAddrRegistered = true;
                            m_location.GetReportStatus(ref reportKey, ref m_civicAddrStatus);
                        }
                    }
                    //
                    // set the current status to the available report type status
                    //
                    ReportStatus status = (ReportStatus.NotSupported != m_latLongStatus) ? m_latLongStatus : m_civicAddrStatus;
                    m_curStatus = m_geoStatusMap[(int)status];

                    ChangePermissionFromReportStatus(status);
                }
                else
                {
                    m_curStatus = GeoPositionStatus.Disabled;
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// This is where the application responds to new status information. In this case, it simply
        /// displays the location information.  If emulation is enabled and the status is Ready, a
        /// new thread is launched for position emulation. This mimics the behaviour of the live data,
        /// where location data doesn't arrive until the LocationService status is Ready.
        /// </summary>
        /// <param name="status"></param>
        void StatusChanged(GeoPositionStatus status)
        {
            // Display the current status
            statusTextBlock.Text = status.ToString();

            // If emulation is being used and the status is Ready, start the position emulation thread
            if (status == GeoPositionStatus.Ready && useEmulation)
            {

                positionEmulationThread = new Thread(StartPositionEmulation);
                positionEmulationThread.Start();
            }
        }
Exemple #27
0
 void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     currentGPSStatus = e.Status;
     Deployment.Current.Dispatcher.BeginInvoke(() => MyStatusChanged(e));
 }
Exemple #28
0
 internal GeoPositionStatusChangedEventArgs(GeoPositionStatus status)
 {
     Status = status;
 }
Exemple #29
0
        private void HandleLocationStatusChangedEvent(ReportStatus newStatus)
        {
            lock (this.InternalSyncObject)
            {
                //
                // If we are registered for civic address reports and a latlong provider
                // has become available, then unregister for civic address reports
                //
                if (m_civicAddrRegistered && m_latLongStatus != ReportStatus.NotSupported)
                {
                    if (m_civicAddrRegistered)
                    {
                        Guid reportType = LocationReportKey.CivicAddressReport;
                        if (m_location.UnregisterForReport(ref reportType) == 0)
                        {
                            m_civicAddrRegistered = false;
                        }
                    }
                }
            }

            GeoPositionStatus prevStatus = Status;

            //
            // Update current status
            //
            ReportStatus status = (ReportStatus.NotSupported != m_latLongStatus) ? m_latLongStatus : m_civicAddrStatus;

            m_curStatus = m_geoStatusMap[(int)status];

            ChangePermissionFromReportStatus(status);

            if (IsStarted)
            {
                //
                // If the reported status has changed, send a status change event
                //
                if (prevStatus != Status)
                {
                    OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(Status));

                    //
                    // If we have location data and have held off sending it until the
                    // status becomes ready, send the location event now
                    //
                    if (GeoPositionStatus.Ready == Status && m_eventPending)
                    {
                        m_eventPending = false;
                        OnPositionChanged(new GeoPositionChangedEventArgs <GeoCoordinate>(m_position));
                    }

                    //
                    // If switching to ready from a permission denied state, then the sensor may not
                    // send a location changed event. So start a worker thread to get it via a
                    // synchronous request for current data.
                    // (Note: Check m_curStatus rather than Status because Status won't be Ready
                    // if there is no location data.)
                    //
                    if (m_curStatus == GeoPositionStatus.Ready)
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(this.GetLocationData), null);
                    }
                }
            }
        }
Exemple #30
0
 private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     positionStatus = e.Status;
     if (positionStatus == GeoPositionStatus.Ready)
     {
         GetForecast();
         watcher.Stop();
     }
 }
Exemple #31
0
        /// <summary>
        /// InvokeStatusChanged is called when new location status is available (either live
        /// or emulated).
        /// </summary>
        /// <param name="status"></param>
        void InvokeStatusChanged(GeoPositionStatus status)
        {
            if (!IsServiceInitializatonAttempted)
            {
                switch (status)
                {
                    case GeoPositionStatus.Disabled:
                        IsServiceInitializatonAttempted = true;
                        ApplicationState = ApplicationStateType.NotReady;
                        break;
                    case GeoPositionStatus.NoData:
                    case GeoPositionStatus.Ready:
                        IsServiceInitializatonAttempted = true;
                        ApplicationState = _initialApplicationState;
                        break;
                }

                if (LocationServiceStatusChanged != null)
                    LocationServiceStatusChanged(status);
            }
        }
Exemple #32
0
 public void Stop()
 {
     Status = GeoPositionStatus.Disabled;
     timer.Stop();
 }
Exemple #33
0
 public void Start()
 {
     Status = GeoPositionStatus.Ready;
     timer.Start();
 }
 private void _geoWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     Status = e.Status;
 }
        private void ChangeStatusWithEvent(GeoPositionStatus status, GeoCoordinate currentLocation)
        {
            Position = new GeoPosition<GeoCoordinate>(DateTimeOffset.Now, currentLocation);
              ChangeStatusWithEvent(status);

              if (PositionChanged != null)
              {
            PositionChanged(this, new GeoPositionChangedEventArgs<GeoCoordinate>(Position));
              }
        }
Exemple #36
0
        private void HandleLocationChangedEvent(ILocationReport locationReport)
        {
            const double KnotsToMetersPerSec = 463.0 / 900.0;

            GeoCoordinate coordinate = GeoCoordinate.Unknown;
            CivicAddress  address    = CivicAddress.Unknown;

            DateTimeOffset timestamp = DateTimeOffset.Now;
            SYSTEMTIME     systime;

            if (0 == locationReport.GetTimestamp(out systime))
            {
                timestamp = new DateTimeOffset(systime.wYear, systime.wMonth, systime.wDay, systime.wHour,
                                               systime.wMinute, systime.wSecond, systime.wMilliseconds, TimeSpan.Zero);
            }

            //
            // If we are listening for latlong reports and this is one,
            // extract the coordinate properties
            //
            if (m_latLongStatus != ReportStatus.NotSupported)
            {
                ILatLongReport latLongReport = locationReport as ILatLongReport;
                if (latLongReport != null)
                {
                    double latitude, longitude, errorRadius, altitude, altitudeError;
                    if ((latLongReport.GetLatitude(out latitude) == 0) &&
                        (latLongReport.GetLongitude(out longitude) == 0))
                    {
                        latLongReport.GetErrorRadius(out errorRadius);
                        latLongReport.GetAltitude(out altitude);
                        latLongReport.GetAltitudeError(out altitudeError);

                        double speed  = GetDoubleProperty(locationReport, LocationPropertyKey.Speed) * KnotsToMetersPerSec;
                        double course = GetDoubleProperty(locationReport, LocationPropertyKey.Heading);

                        coordinate = new GeoCoordinate(latitude, longitude, altitude, errorRadius, altitudeError, speed, course);
                    }
                }
            }

            //
            // Now see if there is civic address data in the report. We do this for both latlong and civic address
            // reports to handle the case of one sensor providing both types of data. Only generate a report if
            // countryRegion and at least one other string is present. For Win 7 a country string is always present
            // because the native location provider API defaults to UserGeoID if no sensor provides one.
            //
            string countryRegion = GetStringProperty(locationReport, LocationPropertyKey.CountryRegion);

            if (countryRegion != String.Empty)
            {
                string address1      = GetStringProperty(locationReport, LocationPropertyKey.AddressLine1);
                string address2      = GetStringProperty(locationReport, LocationPropertyKey.AddressLine2);
                string city          = GetStringProperty(locationReport, LocationPropertyKey.City);
                string postalCode    = GetStringProperty(locationReport, LocationPropertyKey.PostalCode);
                string stateProvince = GetStringProperty(locationReport, LocationPropertyKey.StateProvince);

                if (address1 != String.Empty || address2 != String.Empty || city != String.Empty ||
                    postalCode != String.Empty || stateProvince != String.Empty)
                {
                    address = new CivicAddress(address1, address2, String.Empty, city, countryRegion, String.Empty, postalCode, stateProvince);
                }
            }

            //
            // if we have either coordinate or civic address report data, continue the processing
            //
            if (!coordinate.IsUnknown || !address.IsUnknown)
            {
                GeoPositionStatus prevStatus = Status;

                //
                // Combine with civic address if there is one available
                //
                if (!coordinate.IsUnknown && (!address.IsUnknown))
                {
                    coordinate.m_address = address;
                }
                m_position = new GeoPosition <GeoCoordinate>(timestamp, coordinate);

                if (IsStarted)
                {
                    //
                    // Send a location change event if we are reporting a ready status. Otherwise, set
                    // an event pending flag which will cause the event to be sent when the status
                    // does switch to ready.
                    //
                    if (GeoPositionStatus.Ready == Status)
                    {
                        //
                        // The reported status may have changed because of the received data. If it
                        // has then generate a status change event.
                        //
                        if (Status != prevStatus)
                        {
                            OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(m_curStatus));
                        }

                        OnPositionChanged(new GeoPositionChangedEventArgs <GeoCoordinate>(m_position));
                    }
                    else
                    {
                        m_eventPending = true;
                    }
                }
                else
                {
                    //
                    // Fire Ready event when location is available in case Start() hasn't been called
                    //
                    if (GeoPositionStatus.Ready == m_curStatus)
                    {
                        OnPositionStatusChanged(new GeoPositionStatusChangedEventArgs(m_curStatus));
                    }
                }
            }
        }
        private void OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Status = e.Status;
#if GEO_DEBUG
            Debug.WriteLine("*******");
            Debug.WriteLine("");
            Debug.WriteLine("GEO: Status is {0}", _status);
            Debug.WriteLine("");
#endif

            switch (e.Status)
            {
                case GeoPositionStatus.Initializing:
                    break;

                case GeoPositionStatus.Disabled:
                    //throw new InvalidOperationException();
                    break;

                case GeoPositionStatus.NoData:
#if DEBUG
                    if (seattle)
                    {
                        double lat = isBoka ? 47.60487905922638 : 47.60643068740198;
                        double @long = isBoka ? -122.33625054359436 : -122.3319536447525;

                        Debug.WriteLine("GEO: Using some favorite Seattle coordinates for debug-time emulator work.");
                        LastKnownLocation = new Location
                        {
                            Latitude           = lat,
                            Longitude          = @long,
                            VerticalAccuracy   = double.NaN,
                            HorizontalAccuracy = 350,
                            Altitude           = 0,
                        };
                    }
                    else
                    {
                        if (isWorldwide)
                        {
                            Debug.WriteLine("GEO: Using a worldwide coordinate for debug-time emulator work.");
                            LastKnownLocation = new Location
                            {
                                // sweden
                                //Latitude = 55.603331,
                                //Longitude = 13.001303,

                                // russia
                                //Latitude = 54.741903,
                                //Longitude = 20.532171,

                                // NYC
                                //Latitude = 40.760838,
                                //Longitude = -73.983436,

                                // Shanghai French Concession
                                //Latitude = 31.209058,
                                //Longitude = 121.470015,

                                // Winter Garden, FL
                                Latitude = 28.564889,
                                Longitude = -81.587257,

                                // London, Trafalgar Square
                                //Latitude = 51.507828,
                                //Longitude = -0.128628,

                                VerticalAccuracy = double.NaN,
                                HorizontalAccuracy = 100,
                                Altitude = 0,
                            };
                        }

                        else
                        {
                            // redmond
                            Debug.WriteLine("GEO: Using Redmond work coordinates for debug-time emulator work.");
                            LastKnownLocation = new Location
                                                    {
                                                        Latitude = 47.6372299194336,
                                                        Longitude = -122.133848190308,
                                                        VerticalAccuracy = double.NaN,
                                                        HorizontalAccuracy = 100,
                                                        Altitude = 0,
                                                    };
                        }
                    }
                    Status = GeoPositionStatus.Ready;
#endif
                    break;

                case GeoPositionStatus.Ready:
                    break;
            }

            var handler = StatusChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }
Exemple #38
0
 /// <summary>
 /// This is where the application responds to new status information.
 /// </summary>
 private void LocationServiceStatusChanged(GeoPositionStatus status)
 {
     switch (status)
     {
         case GeoPositionStatus.Disabled:
             Dispatcher.BeginInvoke(() =>
             {
                 initializingBusyMessage.Visibility = System.Windows.Visibility.Collapsed;
                 MessageBox.Show("Location services are not available. Application functionality will be limited.");
                 InitializeApplicationBar(App.ApplicationModel.ApplicationState);
                 App.ApplicationModel.LocationServiceStatusChanged -= LocationServiceStatusChanged;
             });
             break;
         case GeoPositionStatus.Initializing:
             Dispatcher.BeginInvoke(() =>
             {
                 initializingBusyMessage.Visibility = System.Windows.Visibility.Visible;
             });
             break;
         case GeoPositionStatus.NoData:
         case GeoPositionStatus.Ready:
             Dispatcher.BeginInvoke(() =>
             {
                 initializingBusyMessage.Visibility = System.Windows.Visibility.Collapsed;
                 InitializeApplicationBar(App.ApplicationModel.ApplicationState);
                 App.ApplicationModel.LocationServiceStatusChanged -= LocationServiceStatusChanged;
             });
             break;
     }
 }
Exemple #39
0
 void gps_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     gpsStatus = e.Status;
     if (gpsStatus == GeoPositionStatus.Disabled || gpsStatus == GeoPositionStatus.NoData)
     {
         try
         {
             UIWorker.addUIEvent(c_pos2, 'V', 0, 0, 0, false);
         }
         catch (Exception ex)
         {
             Logger.log("Exception in do_async_connect_cb: " + ex);
         }
     }
 }
 private void ChangeStatusWithEvent(GeoPositionStatus status)
 {
     Status = status;
       if (StatusChanged != null)
       {
     StatusChanged(this, new GeoPositionStatusChangedEventArgs(status));
       }
 }
Exemple #41
0
 private static void CheckLocationService(GeoPositionStatus status)
 {
     switch (status)
     {
         case GeoPositionStatus.Disabled:
             ProcessErrorMessage(SR.ErrorMsgTitleLocationServicesOff, SR.ErrorMsgDescLocationServicesOff);
             Messenger.Default.Send(new NotificationMessage<bool>(false, string.Empty), MessengerToken.EnableLocationButtonIndicator);
             break;
         case GeoPositionStatus.NoData:
         case GeoPositionStatus.Initializing:
             Messenger.Default.Send(new NotificationMessage<bool>(true, SR.ProgressBarAcquiringLocation), MessengerToken.MainMapProgressIndicator);
             Messenger.Default.Send(new NotificationMessage<bool>(false, string.Empty), MessengerToken.EnableLocationButtonIndicator);
             break;
         case GeoPositionStatus.Ready:
             Messenger.Default.Send(new NotificationMessage<bool>(false, SR.ProgressBarAcquiringLocation), MessengerToken.MainMapProgressIndicator);
             Messenger.Default.Send(new NotificationMessage<bool>(true, string.Empty), MessengerToken.EnableLocationButtonIndicator);
             break;
     }
 }
Exemple #42
0
 /// <summary>
 /// InvokeStatusChanged is called when new location status is available (either live
 /// or emulated). It uses BeginInvoke to call another handler on the Page's UI thread.
 /// </summary>
 /// <param name="status"></param>
 void InvokeStatusChanged(GeoPositionStatus status)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() => StatusChanged(status));
 }
 public LocationStatusEventArgs(GeoPositionStatus status)
 {
     Status = status;
 }
 internal GeoPositionStatusChangedEventArgs(GeoPositionStatus status)
 {
     Status = status;
 }
 public void ChangeStatus(GeoPositionStatus newStatus)
 {
     this.status.OnNext(newStatus);
 }
Exemple #46
0
 private void WatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     _status = e.Status;
 }
 public LocationUnavailableException(string message, GeoPositionStatus status)
     : base(message)
 {
     Status = status;
 }
Exemple #48
0
 public GeoPositionStatusChangedEventArgs(GeoPositionStatus status)
 {
     Status = status;
 }
 void UpdateStatus(GeoPositionStatus status)
 {
     if (mGPSCallback != null)
     {
         mGPSCallback(status);
     }
 }
        private void OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Status = e.Status;
#if GEO_DEBUG
            Debug.WriteLine("*******");
            Debug.WriteLine("");
            Debug.WriteLine("GEO: Status is {0}", _status);
            Debug.WriteLine("");
#endif

            switch (e.Status)
            {
            case GeoPositionStatus.Initializing:
                break;

            case GeoPositionStatus.Disabled:
                //throw new InvalidOperationException();
                break;

            case GeoPositionStatus.NoData:
#if DEBUG
                if (seattle)
                {
                    double lat   = isBoka ? 47.60487905922638 : 47.60643068740198;
                    double @long = isBoka ? -122.33625054359436 : -122.3319536447525;

                    Debug.WriteLine("GEO: Using some favorite Seattle coordinates for debug-time emulator work.");
                    LastKnownLocation = new Location
                    {
                        Latitude           = lat,
                        Longitude          = @long,
                        VerticalAccuracy   = double.NaN,
                        HorizontalAccuracy = 350,
                        Altitude           = 0,
                    };
                }
                else
                {
                    if (isWorldwide)
                    {
                        Debug.WriteLine("GEO: Using a worldwide coordinate for debug-time emulator work.");
                        LastKnownLocation = new Location
                        {
                            // sweden
                            //Latitude = 55.603331,
                            //Longitude = 13.001303,

                            // russia
                            //Latitude = 54.741903,
                            //Longitude = 20.532171,

                            // NYC
                            //Latitude = 40.760838,
                            //Longitude = -73.983436,

                            // Shanghai French Concession
                            //Latitude = 31.209058,
                            //Longitude = 121.470015,

                            // Winter Garden, FL
                            Latitude  = 28.564889,
                            Longitude = -81.587257,

                            // London, Trafalgar Square
                            //Latitude = 51.507828,
                            //Longitude = -0.128628,

                            VerticalAccuracy   = double.NaN,
                            HorizontalAccuracy = 100,
                            Altitude           = 0,
                        };
                    }

                    else
                    {
                        // redmond
                        Debug.WriteLine("GEO: Using Redmond work coordinates for debug-time emulator work.");
                        LastKnownLocation = new Location
                        {
                            Latitude           = 47.6372299194336,
                            Longitude          = -122.133848190308,
                            VerticalAccuracy   = double.NaN,
                            HorizontalAccuracy = 100,
                            Altitude           = 0,
                        };
                    }
                }
                Status = GeoPositionStatus.Ready;
#endif
                break;

            case GeoPositionStatus.Ready:
                break;
            }

            var handler = StatusChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }
Exemple #51
0
 /// <summary>
 /// Trigger Gps Status change
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void triggerGpsStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 {
     switch (e.Status)
     {
         case GeoPositionStatus.Disabled:
             this.IsGpsEnabled = false;
             this.IsGpsInitializing = false;
             this.IsGpsData = false;
             break;
         case GeoPositionStatus.Initializing:
             this.IsGpsEnabled = true;
             this.IsGpsInitializing = true;
             this.IsGpsData = false;
             break;
         case GeoPositionStatus.NoData:
             this.IsGpsEnabled = true;
             this.IsGpsInitializing = true;
             this.IsGpsData = false;
             break;
         case GeoPositionStatus.Ready:
             this.IsGpsEnabled = true;
             this.IsGpsInitializing = false;
             this.IsGpsData = true;
             break;
     }
     this.gpsStatus = e.Status;
     this.setData();
 }
 /// <summary>
 /// InvokeStatusChanged is called when new location status is available (either live
 /// or emulated). It uses BeginInvoke to call another handler on the Page's UI thread.
 /// </summary>
 /// <param name="status"></param>
 void InvokeStatusChanged(GeoPositionStatus status)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() =>
         StatusChanged(null, new GeoPositionStatusChangedEventArgs(status)));
 }
        private static BusesViewModel GetSut(
            GeoPositionStatus positionStatus = GeoPositionStatus.Disabled,
            GeoCoordinate location = null)
        {
            locationService = new LocationServiceWp7Mock();
            var jsonSerializer = new JsonContractSerializer();
            var repository = new FakeRepository(jsonSerializer);
            var vm = new BusesViewModel(locationService, repository);

            if (positionStatus == GeoPositionStatus.Ready)
            {
                locationService.ChangeStatus(positionStatus);
                locationService.ChangeLocation(location);
            }

            return vm;
        }