Start() public méthode

public Start ( ) : void
Résultat void
        private void start_Click(object sender, EventArgs e)
        {
            if (!timer.IsEnabled)
            {
                string runningMessage = "Reading: ";
                if (Accelerometer.IsSupported)
                {
                    accelSensor.Start();
                    runningMessage += "Accelerometer ";
                }

                if (Compass.IsSupported)
                {
                    compassSensor.Start();
                    runningMessage += "Compass ";
                }

                if (Gyroscope.IsSupported)
                {
                    gyroSensor.Start();
                    runningMessage += "Gyroscope ";
                }

                timer.Start();
                messageBlock.Text = runningMessage;
            }
        }
 protected override void OnAppearing()
 {
     if (!Compass.IsMonitoring)
     {
         Compass.Start(SensorSpeed.UI, true);
     }
 }
        protected async override void OnAppearing()
        {
            base.OnAppearing();

            // Check if the application has permission to use location
            var hasLocationPermission = await Permissions.RequestAsync <Permissions.LocationWhenInUse>();

            if (hasLocationPermission != PermissionStatus.Granted) // No permission to use location
            {
                await DisplayAlert(AppResources.error, AppResources.errorCompassNoPermission, AppResources.ok);
            }
            else
            {
                // Get the set endpoint coordinates
                endLocation.Latitude  = Preferences.Get("targetLatitude", 0f);
                endLocation.Longitude = Preferences.Get("targetLongitude", 0f);

                // Start the compass
                try
                {
                    if (!Compass.IsMonitoring)
                    {
                        Compass.Start(SensorSpeed.UI, applyLowPassFilter: true);
                    }
                }
                catch (FeatureNotSupportedException) // Device doesn't support compass
                {
                    await DisplayAlert(AppResources.error, AppResources.errorCompassNoSupport, AppResources.ok);
                }
                catch // Some other exception while starting compass
                {
                    await DisplayAlert(AppResources.error, AppResources.errorDefault, AppResources.ok);
                }

                // Constantly get the users location, until leaving the page
                getLocation = true;
                while (getLocation)
                {
                    try
                    {
                        var request = new GeolocationRequest(GeolocationAccuracy.Best);
                        startLocation = await Geolocation.GetLocationAsync(request);

                        errorLabel.IsVisible = false;
                        locationFound        = true;
                    }
                    catch (FeatureNotEnabledException) // GPS is not enabled
                    {
                        await DisplayAlert(AppResources.error, AppResources.errorCompassLocationOff, AppResources.ok);

                        break;
                    }
                    catch // Some other exception while getting GPS-location
                    {
                        errorLabel.IsVisible = true;
                        locationFound        = false;
                    }
                }
            }
        }
Exemple #4
0
        public void Start()
        {
            if (_compass != null)
            {
                return;
            }

            if (Compass.IsSupported == false)
            {
                return;
            }

            _compass = new Compass
            {
                TimeBetweenUpdates = TimeBetweenUpdates
            };

            // The sensor may not support the requested time between updates.
            // The TimeBetweenUpdates property reflects the actual rate.

            TimeBetweenUpdates = _compass.TimeBetweenUpdates;

            _compass.CurrentValueChanged += CompassCurrentValueChanged;
            _compass.Calibrate           += CompassCalibrate;
            _compass.Start();
        }
        private void InitializeCompass()
        {
            if (!Compass.IsSupported)
            {
                // The device on which the application is running does not support
                // the compass sensor. Alert the user and hide the
                // application bar.
                //statusTextBlock.Text = "device does not support compass";

                MessageBox.Show("Device not supported compass sensors. Heading map will be turned off");
                HeadingPath.Visibility = Visibility.Collapsed;
            }
            else
            {
                // Initialize the timer and add Tick event handler, but don't start it yet.
                timer          = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMilliseconds(30);
                timer.Tick    += new EventHandler(timer_Tick);

                //Start the compass
                if (compass != null && compass.IsDataValid)
                {
                    // Stop data acquisition from the compass.
                    compass.Stop();
                    timer.Stop();
                    //statusTextBlock.Text = "compass stopped.";
                }
                else
                {
                    if (compass == null)
                    {
                        // Instantiate the compass.
                        compass = new Compass();

                        // Specify the desired time between updates. The sensor accepts
                        // intervals in multiples of 20 ms.
                        compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);

                        // The sensor may not support the requested time between updates.
                        // The TimeBetweenUpdates property reflects the actual rate.
                        //timeBetweenUpdatesTextBlock.Text = compass.TimeBetweenUpdates.TotalMilliseconds + " ms";


                        compass.CurrentValueChanged += compass_CurrentValueChanged;
                        compass.Calibrate           += compass_Calibrate;

                        try
                        {
                            //statusTextBlock.Text = "starting compass.";
                            compass.Start();
                            timer.Start();
                        }
                        catch (InvalidOperationException)
                        {
                            //statusTextBlock.Text = "unable to start compass.";
                        }
                    }
                }
            }
        }
Exemple #6
0
        public MainPage()
        {
            InitializeComponent();
            BatteryLifeInSeconds = 18000;
            LastCharge           = 1F;
            ElapsedTime          = 0;
            isEyeball            = false;

            Battery.BatteryInfoChanged += Battery_BatteryInfoChanged;

            //https://www.youtube.com/watch?v=eDx8tbUrkP0
            Device.StartTimer(TimeSpan.FromSeconds(1), () => {
                Device.BeginInvokeOnMainThread(() =>
                                               DisplayCountdown()
                                               );

                return(true);
            });

            Magnetometer.Start(SensorSpeed.UI);
            Magnetometer.ReadingChanged += Magnetometer_ReadingChanged;

            Compass.Start(SensorSpeed.UI);
            Compass.ReadingChanged += Compass_ReadingChanged;
        }
        private bool TimerStarted()
        {
            Device.BeginInvokeOnMainThread(async() =>
            {
                Compass.Start(SensorSpeed.UI, applyLowPassFilter: true);
                Compass.ReadingChanged += Compass_ReadingChanged;
                map.Pins.Clear();
                map.Polylines.Clear();
                var contents = await mapPageViewModel.LoadVehicles();
                if (contents != null)
                {
                    foreach (var item in contents)
                    {
                        Pin VehiclePins = new Pin()
                        {
                            Label = "Cars",
                            Type  = PinType.Place,

                            Icon = (Device.RuntimePlatform == Device.Android) ? BitmapDescriptorFactory.FromBundle("CarPins.png") : BitmapDescriptorFactory.FromView(new Image()
                            {
                                Source = "CarPins.png", WidthRequest = 30, HeightRequest = 30
                            }),
                            Position = new Position(Convert.ToDouble(item.Latitude), Convert.ToDouble(item.Longitude)),
                            Rotation = ToRotationPoints(headernorthvalue)
                        };
                        map.Pins.Add(VehiclePins);
                    }
                }
            }

                                           );
            Compass.Stop();
            return(true);
        }
Exemple #8
0
        private void StartListeningCompass()
        {
            try
            {
                if (Compass.IsMonitoring)
                {
                    Compass.Stop();
                }
                else
                {
                    Compass.Start(_speed);
                }
            }
            catch (FeatureNotSupportedException)
            {
                // Feature not supported on device
            }
            catch (Exception)
            {
                // Some other exception has occured
            }


            //if (!CrossCompass.Current.IsSupported)
            //    return;

            //CrossCompass.Current.CompassChanged += Current_CompassChanged;
            //CrossCompass.Current.Start();
        }
 private void LoadComp(Object sender, RoutedEventArgs e)
 {
     Comp = new Compass();
     Comp.TimeBetweenUpdates   = TimeSpan.FromMilliseconds(5);
     Comp.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <CompassReading> >(CompHandler);
     Comp.Start();
 }
 public void ToggleCompass()
 {
     try
     {
         if (Compass.IsMonitoring)
         {
             Compass.Stop();
         }
         else
         {
             Compass.Start(speed);
         }
     }
     catch (FeatureNotSupportedException fnsEx)
     {
         // Feature not supported on device
         Console.WriteLine(fnsEx);
         exception.Text = "Feature not supported on device";
     }
     catch (Exception ex)
     {
         // Other error has occurred.
         Console.WriteLine(ex);
         exception.Text = "Other error has occurred";
     }
 }
 private void Button_Clicked(object sender, EventArgs e)
 {
     if (!Compass.IsMonitoring)
     {
         Compass.Start(SensorSpeed.UI, applyLowPassFilter: true);
     }
 }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            _engine = new Engine();
            _engine.ghostCreated += new Engine.GhostCreated(ghostCreated);
            _engine.worldObjectCreated += new Engine.WorldObjectCreated(worldObjectCreated);
            _engine.worldObjectRemoved += new Engine.WorldObjectRemoved(worldObjectRemoved);
            _engine.ghostsMoved += new Engine.GhostsMoved(ghostsMoved);
            _engine.gameStarted += new Engine.GameStarted(gameStarted);
            _engine.gameOver += new Engine.GameOver(gameOver);
            //_engine.Player.Position = new GeoCoordinate(0, 0);

            _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            _watcher.MovementThreshold = 0;
            _watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            _watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);

            if (Compass.IsSupported)
            {
                _compass = new Compass();
                _compass.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<CompassReading>>(compassChanged);
                _compass.Start();
            }

            gpsHideAnimation.Completed += new EventHandler(gpsHideAnimation_Completed);

            rect.Visibility = Visibility.Collapsed;
        }
 public void ToggleMetrics(bool isToogled)
 {
     try
     {
         if (isToogled)
         {
             Accelerometer.Start(speed);
             //Barometer.Start(speed);
             Compass.Start(speed);
             Gyroscope.Start(speed);
             Magnetometer.Start(speed);
             OrientationSensor.Start(speed);
         }
         else
         {
             Accelerometer.Stop();
             //Barometer.Stop();
             Compass.Stop();
             Gyroscope.Stop();
             Magnetometer.Stop();
             OrientationSensor.Stop();
         }
     }
     catch (FeatureNotSupportedException)
     {
         ShowNotSupportedError();
     }
     catch (Exception ex)
     {
         ShowError(ex.Message);
     }
 }
Exemple #14
0
        public void Start()
        {
            createGCWInstance();

            if (wtc != null)
            {
                wtc.MovementThreshold = GpsMovementThreshold;
                wtc.Start();
            }

            createCompassInstance();
            if (cmp != null)
            {
                cmp.TimeBetweenUpdates = TimeSpan.FromMilliseconds(UpdateCompassTimeSpan);

                try
                {
                    cmp.Start();
                }
                catch (InvalidOperationException)
                {
                    //Do something
                }
            }
            Location = new GeoCoordinate();
        }
Exemple #15
0
        public MapPage(Action <IMapControl> setup, Func <MapView, MapClickedEventArgs, bool> c = null)
        {
            InitializeComponent();

            mapView.RotationLock          = false;
            mapView.UnSnapRotationDegrees = 30;
            mapView.ReSnapRotationDegrees = 5;

            mapView.PinClicked += OnPinClicked;
            mapView.MapClicked += OnMapClicked;

            Compass.ReadingChanged += Compass_ReadingChanged;

            mapView.MyLocationLayer.UpdateMyLocation(new UI.Forms.Position());

            mapView.Info += MapView_Info;
            mapView.Renderer.WidgetRenders[typeof(CustomWidget.CustomWidget)] = new CustomWidgetSkiaRenderer();

            Task.Run(() => StartGPS());

            try
            {
                if (!Compass.IsMonitoring)
                {
                    Compass.Start(SensorSpeed.Default);
                }
            }
            catch (Exception) { }

            setup(mapView);

            Clicker = c;
        }
Exemple #16
0
 public void ControlSunscribe(bool flag)
 {
     try
     {
         if (Compass.IsMonitoring && !flag)
         {
             Compass.Stop();
             CompassWatch.Reset();
         }
         else if (!Compass.IsMonitoring && flag)
         {
             CompassWatch.Start();
             Compass.Start(Config.sensorSpeed);
         }
         else
         {
             //Dont think anything is needed here
         }
     }
     catch (FeatureNotEnabledException ex)
     {
     }
     catch (Exception ex)
     {
     }
 }
Exemple #17
0
 private void Map_MyLocationButtonClicked(object sender, MyLocationButtonClickedEventArgs e)
 {
     if (!Compass.IsMonitoring)
     {
         Compass.Start(SensorSpeed.UI);
     }
 }
        public void ExecuteToggleDarkNavCommand()
        {
            //Make Dark nav visible/invible
            DarkNavEnabled = !DarkNavEnabled;

            //Start compass, because compass is only visible in DarkMode
            try
            {
                if (DarkNavEnabled)
                {
                    Compass.ReadingChanged += Compass_ReadingChanged;
                    Compass.Start(SensorSpeed.Fastest);
                }
                else
                {
                    Compass.ReadingChanged -= Compass_ReadingChanged;
                    Compass.Stop();
                }
            }
            catch (Exception ex)
            {
                HeadingMagneticNorth = 30;
                Crashes.TrackError(ex);
            }
        }
        public MainPage()
        {
            this.DataContext = this;
            InitializeComponent();

            this.WarningBlock1.Visibility = System.Windows.Visibility.Collapsed;
            this.WarningBlock2.Visibility = System.Windows.Visibility.Collapsed;
            this.WarningBlock3.Visibility = System.Windows.Visibility.Collapsed;
            this.WarningBlock4.Visibility = System.Windows.Visibility.Collapsed;

            m_fValue1 = 0.01f;
            m_fValue2 = 0.03f;
            m_fValue3 = 0.05f;
            m_fValue4 = 0.06f;
            m_fValue5 = 0.08f;
            m_fValue6 = 0.1f;
            m_fValue7 = 0.2f;
            m_fValue8 = 0.3f;
            m_fValue9 = 0.4f;
            m_fValue10 = 0.5f;

            // time interval
            m_fInterval = 120;

            if (Compass.IsSupported)
            {
                m_oCompass = new Compass();
                m_oCompass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(m_fInterval);
                m_oCompass.CurrentValueChanged += m_oCompass_CurrentValueChanged;
                m_oCompass.Start();
            }
        }
        private void startCompass()
        {
            if (compass != null && compass.IsDataValid)
            {
                compass.Stop();
                timer.Stop();
                accelerometer.Stop();
            }
            else
            {
                if (compass == null)
                {
                    compass = new Compass();
                    compass.TimeBetweenUpdates   = TimeSpan.FromMilliseconds(20);
                    compass.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <CompassReading> >(compass_CurrentValueChanged);
                    compass.Calibrate           += new EventHandler <CalibrationEventArgs>(compass_Calibrate);
                }
            }

            try
            {
                compass.Start();
                timer.Start();
                accelerometer = new Accelerometer();
                // Start accelerometer for detecting compass axis
                accelerometer = new Accelerometer();
                accelerometer.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <AccelerometerReading> >(accelerometer_CurrentValueChanged);
                accelerometer.Start();
                heading = 0.0;
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show("Error with sensor data");
            }
        }
Exemple #21
0
        public async Task Stop_Monitor(SensorSpeed sensorSpeed)
        {
            // TODO: the test runner app (UI version) should do this, until then...
            if (!HardwareSupport.HasCompass)
            {
                return;
            }

            var tcs = new TaskCompletionSource <CompassData>();

            Compass.ReadingChanged += Compass_ReadingChanged;
            void Compass_ReadingChanged(object sender, CompassChangedEventArgs e)
            {
                tcs.TrySetResult(e.Reading);
            }

            Compass.Start(sensorSpeed);

            var d = await tcs.Task;

            Compass.Stop();
            Compass.ReadingChanged -= Compass_ReadingChanged;

            Assert.False(Compass.IsMonitoring);
        }
        public CompassPage()
        {
            CompassViewModel viewModel;

            InitializeComponent();
            BindingContext          = viewModel = new CompassViewModel();
            Compass.ReadingChanged += Compass_ReadingChanged;
            try
            {
                if (!Compass.IsMonitoring)
                {
                    Compass.Start(viewModel.Speed);
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Feature not supported on device
                //UserDialogs.Instance.Alert(AppResources.CihazDesteklemiyor, AppResources.CihazDesteklemiyor);
                Debug.WriteLine($"**** {this.GetType().Name}.{nameof(Compass_ReadingChanged)}: {fnsEx.Message}");
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.Alert(ex.Message);
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #23
0
 protected override void OnAppearing()
 {
     Accelerometer.Start(SensorSpeed.UI);
     Gyroscope.Start(SensorSpeed.UI);
     Magnetometer.Start(SensorSpeed.UI);
     Compass.Start(SensorSpeed.UI);
     base.OnAppearing();
 }
Exemple #24
0
 private void Click_CompassOnOff(object sender, EventArgs e)
 {
     if (compas_running == true)
     {
         if (camera_running == true)
         {
             try
             {
                 Camera_Source.CaptureImageAvailable += new System.EventHandler <ContentReadyEventArgs>(Camera_Image_Available);
                 Camera_Source.FlashMode              = FlashMode.Off;
                 Camera_Source.CaptureImage();
             }
             catch (InvalidOperationException)
             {
                 MessageBox.Show(" La caméra n'a pas eu le temps de s'initialiser.");
             }
         }
         Boussolle_Get_Timer.Stop();
         Accelerometre_Get_Timer.Stop();
         etat_TextBlock.Text = " Pause";
         compas_running      = false;
     }
     else
     {
         if (Boussolle_Get_Timer == null)
         {
             Boussolle_Get_Timer = new Compass();
             Boussolle_Get_Timer.TimeBetweenUpdates   = TimeSpan.FromMilliseconds(timer_get);
             Boussolle_Get_Timer.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <CompassReading> >(Boussolle_ValueChanged);
             Boussolle_Get_Timer.Calibrate           += new EventHandler <CalibrationEventArgs>(Calibration_Start);
         }
         try
         {
             etat_TextBlock.Text = " Démarrage...";
             Boussolle_Get_Timer.Start();
             Accelerometre_Get_Timer = new Accelerometer();
             Accelerometre_Get_Timer.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <AccelerometerReading> >(Orientation_ValueChanged);
             Accelerometre_Get_Timer.Start();
             Accelerometre_Get_Timer = new Accelerometer();
             Accelerometre_Get_Timer.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <AccelerometerReading> >(Orientation_ValueChanged);
             Accelerometre_Get_Timer.Start();
             compas_running = true;
             //MessageBox.Show("Reel : " + Boussolle_Get_Timer.TimeBetweenUpdates.TotalMilliseconds + "ms \nPrevu : " + timer_get + "ms \nDisplay : " + timer_display + "ms"); //timer affichage
             if (camera_running == false && camera_ison == true)
             {
                 Camera_Ellipse.Fill = Camera_Brush;
                 Camera_Source       = new PhotoCamera(CameraType.Primary);
                 Camera_Brush.SetSource(Camera_Source);
                 camera_running        = true;
                 Image_Ellipse.Opacity = 0;
             }
         }
         catch (InvalidOperationException)
         {
             etat_TextBlock.Text = " Erreur.";
         }
     }
 }
Exemple #25
0
        public void Monitor_Null_Handler()
        {
            if (DeviceInfo.DeviceType == DeviceType.Virtual && DeviceInfo.Platform == DeviceInfo.Platforms.iOS)
            {
                return;
            }

            Assert.Throws <ArgumentNullException>(() => Compass.Start(SensorSpeed.Normal, null));
        }
Exemple #26
0
        protected async override void OnAppearing()
        {
            base.OnAppearing();

            // Move stsuff to OnStart in app instead of appearing of this page
            if (initialised)
            {
                return;
            }

            var hasPermission = await Utils.CheckPermissions(Permission.Location);

            Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
            wifiIp   = DependencyService.Get <IWifiIp>();
            deviceId = wifiIp.GetDeviceId();

            Device.BeginInvokeOnMainThread(() =>
            {
                TxtDeviceId.Text = deviceId;
            });

            if (!hasPermission)
            {
                Application.Current?.MainPage?.DisplayAlert("Permissions", "please restart app", "Ok");
                return;
            }

            // start compass
            Compass.Start(SensorSpeed.Normal);
            Compass.ReadingChanged += Compass_ReadingChanged;

            TxtName.Text         = Settings.StewardName;
            TxtName.TextChanged += TxtName_TextChanged;
            name = Settings.StewardName;

            TxtBroker.Text = broker;

            // start position
            var locator = CrossGeolocator.Current;

            locator.DesiredAccuracy  = 1;
            locator.PositionChanged += Locator_PositionChanged;
            await locator.StartListeningAsync(new TimeSpan(1), 1, true);

            StartPublishing();

            if (Connectivity.NetworkAccess == NetworkAccess.Internet)
            {
                TxtHasInternetConnection.Text = "true";
            }
            else
            {
                TxtHasInternetConnection.Text = "false";
            }

            initialised = true;
        }
 private void InitializeCompass()
 {
     if (CompassIsSupported)
     {
         _compass = new Compass();
         _compass.CurrentValueChanged += CompassOnCurrentValueChanged;
         _compass.Start();
     }
 }
Exemple #28
0
 public MainPage()
 {
     InitializeComponent();
     Compass.ReadingChanged += Compass_ReadingChanged;
     if (!Compass.IsMonitoring)
     {
         Compass.Start(speed);
     }
 }
Exemple #29
0
        public MainPage()
        {
            InitializeComponent();

            //値を取得したときのイベントハンドラをセット
            Compass.ReadingChanged += Compass_ReadingChanged;

            //コンパス値の取得開始
            Compass.Start(SensorSpeed.UI);
        }
        protected Task <bool> StartCompassAsync()
        {
            if (!Compass.IsMonitoring)
            {
                Compass.ReadingChanged += CompassOnReadingChanged;
                Compass.Start(SensorSpeed.UI);
            }

            return(Task.FromResult(true));
        }
Exemple #31
0
 private void OnIsCompassEnabledChanged(bool value)
 {
     if (value)
     {
         _Compass.Start();
     }
     else
     {
         _Compass.Stop();
     }
 }
Exemple #32
0
        public MainPage()
        {
            InitializeComponent();

            if (Compass.IsSupported)
            {
                compass = new Compass();
                compass.TimeBetweenUpdates   = TimeSpan.FromMilliseconds(1);
                compass.CurrentValueChanged += new EventHandler <SensorReadingEventArgs <CompassReading> >(compass_CurrentValueChanged);
                compass.Start();
            }
        }
        public CompassSamplePage()
        {
            InitializeComponent();

            // not all the devices support compass

            if(Compass.IsSupported)
            {
                _c = new Compass();
                _c.CurrentValueChanged += CompassCurrentValueChanged;
                _c.Start();
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (!Compass.IsSupported)
            {
                MessageBox.Show("Dein Gerät unterstützt keinen Kompass :(");
                return;
            }
            
            compass = new Compass();
            compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(500);
            compass.CurrentValueChanged += compass_CurrentValueChanged;
            compass.Calibrate += compass_Calibrate;
            compass.Start();
        }
Exemple #35
0
        public string ReturnHeading()
        {
            if (!Compass.IsSupported)
              {
            throw new Exception("Could not load Compass");
              }
              if (_compass == null)
              {
            _compass = new Compass();
            _compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(100);
            _compass.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<CompassReading>>(_compass_CurrentValueChanged);
            try
            {
              _compass.Start();
            }
            catch (InvalidOperationException e)
            {
              if (_compass != null)
              {
            _compass.Dispose();
            _compass = null;
              }

              throw new Exception("Could not initiate compass readings", e);
            }
              }

              string trueHeading = null;
              if (_compass != null)
              {
            // block on the search until the async result return
            lock (_locker)
            {
              while (_trueHeading == null)
              {
            Monitor.Pulse(_locker);
              }

              trueHeading = _trueHeading;
              _trueHeading = null;
            }
              }
              return trueHeading;
        }
 private void Btn_Brujula_Click(object sender, RoutedEventArgs e)
 {
     if(Compass.IsSupported) {
         if (!vBrujula)
         {
             objBrujula = new Compass();
             objBrujula.TimeBetweenUpdates = TimeSpan.FromMilliseconds(100);
             objBrujula.CurrentValueChanged += objBrujula_CurrentValueChanged;
             objBrujula.Start();
             Btn_Brujula.Content = "Apagar Brújula";
         }
         else {
             vBrujula = false;
             Btn_Brujula.Content = "Iniciar Brújula";
             objBrujula.Stop();
         }
     } else {
         MessageBox.Show("El dispositivo no tiene brújula","Brújula", MessageBoxButton.OK);
     }
 }
        public DistanceViewModel(GeoCoordinate target)
        {
            this.target = target;
            lastKnownPosition = target;
            Distance = -1;
            DistanceUnit = "???";
            Degree = 0;
            //start GPS
            _watcher = new GeoCoordinateWatcher() { MovementThreshold = 10};
            c = new Compass();
            _watcher.StatusChanged += delegate(Object sender, GeoPositionStatusChangedEventArgs a)
            {
                if (a.Status == GeoPositionStatus.Ready)
                    CalcDistance();
            };
            
            c.CurrentValueChanged +=delegate(object sender, SensorReadingEventArgs<CompassReading> e) {
                CalcCourse();
            };

            c.Start();
            _watcher.Start();
        }
        public void GoLive()
        {
            if (Compass.IsSupported)
            {
                compass = new Compass();
                compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(10);
                compass.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<CompassReading>>(compass_CurrentValueChanged);
                compass.Start();
            }
            else
            {
                noDir.Text = "compass not supported by your device!";
            }

            if (appSettings.Contains("allowGps") && appSettings["allowGps"] as Boolean? == true)
            {
                _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default) { MovementThreshold = 500 };
                _watcher.PositionChanged += delegate(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
                {
                    Dispatcher.BeginInvoke(() => RecalcPosition());
                };
                _watcher.Start(false);
            }
        }
Exemple #39
0
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.ProgressTextBlock.Text = "Loading...";

            var model = ((App)App.Current).Model as StarViewModel;
            if (model != null)
            {
                this.Model = model;
            }
            else
            {
                this.Model = new StarViewModel();
                ((App)App.Current).Model = this.Model;
            }

            this.InitializeScene();

            var panel = this.arPanel;
            //For motion to be supported, device needs at least a compass and
            //an accelerometer. A gyro as well makes the experience much better though
            if (Microsoft.Devices.Sensors.Motion.IsSupported)
            {
                //Warn user that without gyro, the experience isn't as good as it can get
                if (!Microsoft.Devices.Sensors.Gyroscope.IsSupported)
                {
                    LayoutRoot.Children.Add(new TextBlock()
                    {
                        Text = "No gyro detected. Experience may be degraded",
                        TextWrapping = System.Windows.TextWrapping.Wrap,
                        VerticalAlignment = System.Windows.VerticalAlignment.Bottom
                    });
                }
                //Start the AR PAnel
                panel.Start();
            }
            else //Bummer!
            {
                panel.Visibility = System.Windows.Visibility.Collapsed;
                MessageBox.Show("Sorry - Motion sensor is not supported on this device");
            }

            if (Compass.IsSupported)
            {
                // If compass sensor is supported create new compass object and attach event handlers
                Compass myCompass = new Compass();
                myCompass.TimeBetweenUpdates = System.TimeSpan.FromMilliseconds(100); // This defines how often heading is updated
                //myCompass.Calibrate += new System.EventHandler<CalibrationEventArgs>((s, e) =>
                //{
                //    // This will show the calibration screen
                //    //this.IsCalibrationNeeded = true;
                //});
                myCompass.CurrentValueChanged += new System.EventHandler<SensorReadingEventArgs<CompassReading>>((s, args) =>
                {
                    // This will update the current heading value. We have to put it in correct direction
                    Deployment.Current.Dispatcher.BeginInvoke(() => { this.CurrentHeading = args.SensorReading.TrueHeading; this.UpdateTooltip(); });
                    UpdateNavigationArrow();

                });

                // Start receiving data from compass sensor
                myCompass.Start();
            }
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maSensorStart = delegate(int _sensor, int _interval)
            {
                _interval = GetSensorIntervalDefaults(_interval);

                TimeSpan time = TimeSpan.FromMilliseconds((double)_interval);

                if (_sensor == MoSync.Constants.SENSOR_TYPE_ACCELEROMETER &&
                        Accelerometer.IsSupported)
                {
                    mAccelerometer = new Accelerometer();
                    mAccelerometer.TimeBetweenUpdates = time;
                    mAccelerometer.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<AccelerometerReading> args)
                        {
                            Vector3 acc = args.SensorReading.Acceleration;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_ACCELEROMETER, acc);
                        };

                    mAccelerometer.Start();
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_GYROSCOPE &&
                        Gyroscope.IsSupported)
                {
                    mGyroscope = new Gyroscope();
                    mGyroscope.TimeBetweenUpdates = time;
                    mGyroscope.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<GyroscopeReading> args)
                        {
                            Vector3 rot = args.SensorReading.RotationRate;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_GYROSCOPE, rot);
                        };

                    mGyroscope.Start();
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD &&
                        Compass.IsSupported)
                {
                    mCompass = new Compass();
                    mCompass.TimeBetweenUpdates = time;
                    mCompass.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<CompassReading> args)
                        {
                            Vector3 rot = args.SensorReading.MagnetometerReading;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD, rot);
                        };

                    mCompass.Start();
                }
            #if false
            else if (_sensor == MoSync.Constants.SENSOR_TYPE_ORIENTATION &&
                    Motion.IsSupported)
                {
                    mMotion = new Motion();
                    mMotion.TimeBetweenUpdates = new TimeSpan(intervalIn100Nanoseconds);
                    mMotion.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<MotionReading> args)
                        {
                        };
                }
            #endif
                else
                    return MoSync.Constants.SENSOR_ERROR_NOT_AVAILABLE;

                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maSensorStop = delegate(int _sensor)
            {
                switch (_sensor)
                {
                    case MoSync.Constants.SENSOR_TYPE_ACCELEROMETER:
                        if (mAccelerometer != null)
                        {
                            mAccelerometer.Stop();
                            mAccelerometer = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_GYROSCOPE:
                        if (mGyroscope != null)
                        {
                            mGyroscope.Stop();
                            mGyroscope = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD:
                        if (mCompass != null)
                        {
                            mCompass.Stop();
                            mCompass = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_ORIENTATION:
                        if (mMotion != null)
                        {
                            mMotion.Stop();
                            mMotion = null;
                        }
                        break;
                }
                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maLocationStart = delegate()
            {
                if (mGeoWatcher == null)
                {
                    mGeoWatcher = new GeoCoordinateWatcher();
                    //mGeoWatcher.MovementThreshold = 20;

                    mGeoWatcher.StatusChanged += delegate(object sender,
                        GeoPositionStatusChangedEventArgs args)
                    {
                        int maState;
                        switch (args.Status)
                        {
                            case GeoPositionStatus.Disabled:
                                maState = MoSync.Constants.MA_LPS_OUT_OF_SERVICE;
                                break;
                            case GeoPositionStatus.NoData:
                            case GeoPositionStatus.Initializing:
                                maState = MoSync.Constants.MA_LPS_TEMPORARILY_UNAVAILABLE;
                                break;
                            case GeoPositionStatus.Ready:
                                maState = MoSync.Constants.MA_LPS_AVAILABLE;
                                break;
                            default:
                                throw new Exception("invalid GeoPositionStatus");
                        }
                        Memory evt = new Memory(2 * 4);
                        evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_LOCATION_PROVIDER);
                        evt.WriteInt32(MoSync.Struct.MAEvent.state, maState);
                        runtime.PostEvent(new Event(evt));
                    };

                    mGeoWatcher.PositionChanged += delegate(object sender,
                        GeoPositionChangedEventArgs<GeoCoordinate> args)
                    {
                        int maValidity = args.Position.Location.IsUnknown ?
                            MoSync.Constants.MA_LOC_INVALID : MoSync.Constants.MA_LOC_QUALIFIED;
                        Memory evt = new Memory(4 + 4 * 8 + 4);
                        GeoCoordinate l = args.Position.Location;
                        evt.WriteInt32(MoSync.Struct.MALocation.state, maValidity);
                        evt.WriteDouble(MoSync.Struct.MALocation.lat, l.Latitude);
                        evt.WriteDouble(MoSync.Struct.MALocation.lon, l.Longitude);
                        evt.WriteDouble(MoSync.Struct.MALocation.horzAcc, l.HorizontalAccuracy);
                        evt.WriteDouble(MoSync.Struct.MALocation.vertAcc, l.VerticalAccuracy);
                        evt.WriteFloat(MoSync.Struct.MALocation.alt, (float)l.Altitude);
                        runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_LOCATION, evt);
                    };

                    mGeoWatcher.Start();
                }

                return 0;
            };

            ioctls.maLocationStop = delegate()
            {
                if (mGeoWatcher != null)
                {
                    mGeoWatcher.Stop();
                    mGeoWatcher = null;
                }

                return 0;
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maSensorStart = delegate(int _sensor, int _interval)
            {
                _interval = GetSensorIntervalDefaults(_interval);

                TimeSpan time = TimeSpan.FromMilliseconds((double)_interval);

                if (_sensor == MoSync.Constants.SENSOR_TYPE_ACCELEROMETER &&
                    Accelerometer.IsSupported)
                {
                    mAccelerometer = new Accelerometer();
                    mAccelerometer.TimeBetweenUpdates = time;
                    mAccelerometer.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<AccelerometerReading> args)
                        {
                            Vector3 acc = args.SensorReading.Acceleration;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_ACCELEROMETER, acc);
                        };

                    mAccelerometer.Start();
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_GYROSCOPE &&
                    Gyroscope.IsSupported)
                {
                    mGyroscope = new Gyroscope();
                    mGyroscope.TimeBetweenUpdates = time;
                    mGyroscope.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<GyroscopeReading> args)
                        {
                            Vector3 rot = args.SensorReading.RotationRate;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_GYROSCOPE, rot);
                        };

                    mGyroscope.Start();
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD &&
                    Compass.IsSupported)
                {
                    mCompass = new Compass();
                    mCompass.TimeBetweenUpdates = time;
                    mCompass.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<CompassReading> args)
                        {
                            Vector3 rot = args.SensorReading.MagnetometerReading;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD, rot);
                        };

                    mCompass.Start();
                }
            #if false
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_ORIENTATION &&
                    Motion.IsSupported)
                {
                    mMotion = new Motion();
                    mMotion.TimeBetweenUpdates = new TimeSpan(intervalIn100Nanoseconds);
                    mMotion.CurrentValueChanged +=
                               delegate(object sender, SensorReadingEventArgs<MotionReading> args)
                               {
                               };
                }
            #endif
                else
                    return MoSync.Constants.SENSOR_ERROR_NOT_AVAILABLE;

                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maSensorStop = delegate(int _sensor)
            {
                switch (_sensor)
                {
                    case MoSync.Constants.SENSOR_TYPE_ACCELEROMETER:
                        if (mAccelerometer != null)
                        {
                            mAccelerometer.Stop();
                            mAccelerometer = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_GYROSCOPE:
                        if (mGyroscope != null)
                        {
                            mGyroscope.Stop();
                            mGyroscope = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD:
                        if (mCompass != null)
                        {
                            mCompass.Stop();
                            mCompass = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_ORIENTATION:
                        if (mMotion != null)
                        {
                            mMotion.Stop();
                            mMotion = null;
                        }
                        break;
                }
                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maLocationStart = delegate()
            {
                if (mGeoWatcher == null)
                {
                    mGeoWatcher = new GeoCoordinateWatcher();
                    mGeoWatcher.MovementThreshold = 20;

                    mGeoWatcher.StatusChanged += delegate(object sender,
                        GeoPositionStatusChangedEventArgs args)
                    {

                    };

                    mGeoWatcher.PositionChanged += delegate(object sender,
                        GeoPositionChangedEventArgs<GeoCoordinate> args)
                    {

                    };

                    mGeoWatcher.Start();
                }

                return 0;
            };

            ioctls.maLocationStop = delegate()
            {
                if (mGeoWatcher != null)
                {
                    mGeoWatcher.Stop();
                    mGeoWatcher = null;
                }

                return 0;
            };
        }
Exemple #42
0
 void CompassStart()
 {
     if (!Compass.IsSupported) {
         Deployment.Current.Dispatcher.BeginInvoke(() => {
             this.webBrowser1.InvokeScript("eval", "compass.onCompassFail('Compass not available.')");
         });
         return;
     }
     if (_compass == null) {
         _compass = new Compass();
         _compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(100);
         _compass.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<CompassReading>>(_compass_CurrentValueChanged);
         try {
             _compass.Start();
         }
         catch (InvalidOperationException) {
             this.webBrowser1.InvokeScript("eval", "compass.onCompassFail('Could not start the compass.')");
         }
     }
 }
Exemple #43
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            graphicsDevice = SharedGraphicsDeviceManager.Current.GraphicsDevice;
            graphicsDevice.SetSharingMode(true);

            // Create a new RenderTarget2D to handle screen captures.
            target2D = new RenderTarget2D(graphicsDevice, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, false, SurfaceFormat.Alpha8, DepthFormat.Depth24);

            // Motion
            if (Motion.IsSupported)
            {
                motion = new Motion();
                motion.Start();
                useMotion = true;
            }

            if (Compass.IsSupported)
            {
                // Instantiate the compass.
                compass = new Compass();

                // Specify the desired time between updates. The sensor accepts
                // intervals in multiples of 20 ms.
                compass.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
                compass.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<CompassReading>>(compass_CurrentValueChanged);
                compass.Start();
            }

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            Matrix projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4, graphicsDevice.Viewport.AspectRatio, 1.0f, 10000.0f);
            meshes = new List<TexturedMeshObject>();

            center = new Vector3(0, earthdOffset, 0);

            AddPlanetoidMesh(ref projection, center, "Earth");
            AddPlanetoidMesh(ref projection, new Vector3(2038.0f, earthdOffset, 0), "Moon");
            AddPlanetoidMesh(ref projection, new Vector3(203.8f, earthdOffset, 0), "Moon");

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }
Exemple #44
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Extract target coordinates
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            settings.TryGetValue("longitude", out targetLongitude);
            settings.TryGetValue("latitude", out targetLatitude);
            settings.TryGetValue("useGeoLocation", out useGeoLocation);
            settings.TryGetValue("PlaceMarks", out PlaceMarks);

            if (PlaceMarks == null)
            {
                PlaceMarks = new ObservableCollection<Placemark>();
            }
            if (PlaceMarks.Count < 4)
            {
                PlaceMarks.Add(new Placemark() { Title = "Дом", Persist = true });
                PlaceMarks.Add(new Placemark() { Title = "Гостиница", Persist = true });
                PlaceMarks.Add(new Placemark() { Title = "Рыбное место", Persist = true });
                PlaceMarks.Add(new Placemark() { Title = "Грибное место", Persist = true });
                PlaceMarks.Add(new Placemark() { Title = "Выход", Persist = true });
            }

            if (useGeoLocation == false)
            {

                MessageBoxResult mb = MessageBox.Show("Для работы программы необходим доступ к GPS вашего устройства. Мы не храним, не отправляем и не передаем координаты третьим лицам. Нажмите ОК для продолжения", "Предупреждение", MessageBoxButton.OKCancel);

                if (mb == MessageBoxResult.OK)
                {
                    useGeoLocation = true;
                }
                else
                {
                    useGeoLocation = false;
                }
                settings["useGeoLocation"] = useGeoLocation;
                settings.Save();
            }

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            // Positioning stuff
            geoWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            geoWatcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            geoWatcher.Start();

            //if (Microsoft.Devices.Environment.DeviceType != Microsoft.Devices.DeviceType.Emulator)
            //{
            if (!Compass.IsSupported)
            {
                // The device on which the application is running does not support
                // the compass sensor. Alert the user and hide the
                // application bar.
                MessageBox.Show("Устройство не поддерживает компасс.");

            }
            else
            {
                // Compass stuff
                compass = new Compass() { TimeBetweenUpdates = TimeSpan.FromMilliseconds(30) };
                compass.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<CompassReading>>(compass_CurrentValueChanged);
                compass.Calibrate += new EventHandler<CalibrationEventArgs>(compass_Calibrate);
                compass.Start();
            }
            //}

            // Sound stuff

            ambienceSound = new MediaElement();
            ambienceSound.AutoPlay = false;
            ambienceSound.Source = new Uri("Sounds/pointed.mp3", UriKind.Relative);
            ambienceSound.Volume = 1f;
            ambienceSound.MediaEnded += new RoutedEventHandler(ambienceSound_MediaEnded);
            LayoutRoot.Children.Add(ambienceSound);
            ambienceSound.Visibility = Visibility.Collapsed;

            // Graphical Timer stuff
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

            FirstListBox.DataContext = PlaceMarks;
        }