Exemplo n.º 1
0
        internal override void CheckAndEnableSensors()
        {
            base.CheckAndEnableSensors();

            if (Accelerometer.ShouldBeEnabled)
            {
                motionManager.StartAccelerometerUpdates();
            }

            if ((Compass.ShouldBeEnabled || Orientation.ShouldBeEnabled) && !locationManagerActivated)
            {
                locationManagerActivated = true;
                locationManager.StartUpdatingHeading();
            }

            if (Gyroscope.ShouldBeEnabled)
            {
                motionManager.StartGyroUpdates();
            }

            if ((UserAcceleration.ShouldBeEnabled || Gravity.ShouldBeEnabled || Orientation.ShouldBeEnabled) && !motionManager.DeviceMotionActive)
            {
                motionManager.StartDeviceMotionUpdates();
            }
        }
Exemplo n.º 2
0
        private void payAction()
        {
            isInitialXPosition = true;
            motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
            {
                if (isInitialXPosition)
                {
                    isInitialXPosition = false;
                    initialXPosition   = (float)data.Acceleration.X;
                }
                float difference = Math.Abs((float)data.Acceleration.X - initialXPosition);
                //Console.WriteLine("Difference from initial X position = " + difference);
                if ((float)data.Acceleration.X > 0.8 || (float)data.Acceleration.X < -0.8)
                {
                    Console.WriteLine("Bumped");
                    stopMonitoring();
                    //Create Alert
                    var okAlertController = UIAlertController.Create("Payment", "Payment Found", UIAlertControllerStyle.Alert);

                    //Add Action
                    okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

                    // Present Alert
                    PresentViewController(okAlertController, true, null);
                }
                this.lblX.Text = data.Acceleration.X.ToString("0.00000000");
                this.lblY.Text = data.Acceleration.Y.ToString("0.00000000");
                this.lblZ.Text = data.Acceleration.Z.ToString("0.00000000");
            });
        }
Exemplo n.º 3
0
        protected override void StartSensingCore()
        {
            // iOS 8 has additional permissions requirements
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                _locationManager.RequestAlwaysAuthorization();                  // works in background
                //locMgr.RequestWhenInUseAuthorization (); // only in foreground
            }

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                _locationManager.AllowsBackgroundLocationUpdates = true;
            }

            _locationManager.StartUpdatingLocation();

            _sensorManager.AccelerometerUpdateInterval = 1.0 / SensorPack.AccelerometerDesiredHz;
            _sensorManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) => {
                if (error == null)
                {
                    ReportNewAcceleration(data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z);
                }
                else
                {
                    //TODO: catch error
                }
            });
        }
Exemplo n.º 4
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Viewのサイズを取得
            layoutW = View.Bounds.Width;
            layoutH = View.Bounds.Height;

            // Viewサイズを元にLabelサイズを指定
            textW = layoutW / 2;
            textH = layoutH / 6;

            System.Diagnostics.Debug.WriteLine("Width: {0}, Height: {1}", layoutW, layoutH);

            // Label作成&配置
            var sensorText = new UILabel(new CGRect(layoutW / 2 - textW / 2, layoutH / 2 - textH / 2, textW, textH));

            sensorText.BackgroundColor = UIColor.FromRGB(192, 192, 192);
            sensorText.Lines           = 0;
            sensorText.TextAlignment   = UITextAlignment.Center;
            sensorText.LineBreakMode   = UILineBreakMode.TailTruncation;
            View.AddSubview(sensorText);

            // Frameを取得して変数に
            var textLoc = sensorText.Frame;

            motionManager = new CMMotionManager();

            if (motionManager.AccelerometerAvailable)
            {
                // Accelerometer Update間隔
                motionManager.AccelerometerUpdateInterval = 0.015;
                // UpdateがQueueに入る度に処理を行う(多分)
                motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    sensorText.Text = string.Format("X = {0:N4}\nY = {1:N4}", data.Acceleration.X, data.Acceleration.Y);
                    // 現在の位置を取得
                    nowX = sensorText.Frame.X;
                    nowY = sensorText.Frame.Y;

                    System.Diagnostics.Debug.WriteLine("nowX: {0}, nowY: {1}", nowX, nowY);

                    // Viewをはみ出さないようにAccelerometerの値によってLabelを移動
                    if (nowX + (nfloat)data.Acceleration.X * 10 > 0 && nowX + (nfloat)data.Acceleration.X * 10 < layoutW - textW)
                    {
                        textLoc.X = nowX + (nfloat)data.Acceleration.X * 10;
                    }

                    if (nowY - (nfloat)data.Acceleration.Y * 10 > 0 && nowY - (nfloat)data.Acceleration.Y * 10 < layoutH - textH)
                    {
                        textLoc.Y = nowY - (nfloat)data.Acceleration.Y * 10;
                    }

                    sensorText.Frame = textLoc;
                });
            }
        }
Exemplo n.º 5
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.


            layoutW = View.Bounds.Width;
            layoutH = View.Bounds.Height;


            textW = layoutW / 2;
            textH = layoutH / 6;

            System.Diagnostics.Debug.WriteLine("Width: {0}, Height: {1}", layoutW, layoutH);


            var sensorText = new UILabel(new CGRect(layoutW / 2 - textW / 2, layoutH / 2 - textH / 2, textW, textH));

            sensorText.BackgroundColor = UIColor.FromRGB(192, 192, 192);
            sensorText.Lines           = 0;
            sensorText.TextAlignment   = UITextAlignment.Center;
            sensorText.LineBreakMode   = UILineBreakMode.TailTruncation;
            View.AddSubview(sensorText);


            var textLoc = sensorText.Frame;

            motionManager = new CMMotionManager();

            if (motionManager.AccelerometerAvailable)
            {
                motionManager.AccelerometerUpdateInterval = 0.015;

                motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    sensorText.Text = string.Format("X = {0:N4}\nY = {1:N4}", data.Acceleration.X, data.Acceleration.Y);

                    nowX = sensorText.Frame.X;
                    nowY = sensorText.Frame.Y;

                    Console.WriteLine("nowX: {0}, nowY: {1}", nowX, nowY);


                    if (nowX + (nfloat)data.Acceleration.X * 10 > 0 && nowX + (nfloat)data.Acceleration.X * 10 < layoutW - textW)
                    {
                        textLoc.X = nowX + (nfloat)data.Acceleration.X * 10;
                    }

                    if (nowY - (nfloat)data.Acceleration.Y * 10 > 0 && nowY - (nfloat)data.Acceleration.Y * 10 < layoutH - textH)
                    {
                        textLoc.Y = nowY - (nfloat)data.Acceleration.Y * 10;
                    }

                    sensorText.Frame = textLoc;
                });
            }
        }
        public void StartReading(int reportInterval = -1)
        {
            if (reportInterval >= 0)
            {
                _motionManager.AccelerometerUpdateInterval = reportInterval;
            }

            _motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, OnAccelerometerChanged);
        }
Exemplo n.º 7
0
 private void ScreenReturnToMenu()
 {
     _motionManager = new CMMotionManager();
     _motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) => {
         if (data.Acceleration.Z > 0.890)
         {
             PushMainMenuWhenRotating();
         }
     });
 }
Exemplo n.º 8
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad();
     motionManager = new CMMotionManager();
     motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
     {
         this.lblX.Text = data.Acceleration.X.ToString("0.00000000");
         this.lblY.Text = data.Acceleration.Y.ToString("0.00000000");
         this.lblZ.Text = data.Acceleration.Z.ToString("0.00000000");
     });
 }
Exemplo n.º 9
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad ();
     motionManager = new CMMotionManager ();
     motionManager.StartAccelerometerUpdates (NSOperationQueue.CurrentQueue, (data, error) =>
     {
         this.lblX.Text = data.Acceleration.X.ToString ("0.00000000");
         this.lblY.Text = data.Acceleration.Y.ToString ("0.00000000");
         this.lblZ.Text = data.Acceleration.Z.ToString ("0.00000000");
     });
 }
        /// <summary>
        /// Start the specified sensorType and interval.
        /// </summary>
        /// <param name="sensorType">Sensor type.</param>
        /// <param name="interval">Interval.</param>
        public void Start(MotionSensorType sensorType, MotionSensorDelay interval)
        {
            switch (sensorType)
            {
            case MotionSensorType.Accelerometer:
                if (motionManager.AccelerometerAvailable)
                {
                    motionManager.AccelerometerUpdateInterval = (double)interval / ms;
                    motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, OnAccelerometerChanged);
                }
                else
                {
                    Debug.WriteLine("Accelerometer not available");
                }
                break;

            case MotionSensorType.Gyroscope:
                if (motionManager.GyroAvailable)
                {
                    motionManager.GyroUpdateInterval = (double)interval / ms;
                    motionManager.StartGyroUpdates(NSOperationQueue.CurrentQueue, OnGyroscopeChanged);
                }
                else
                {
                    Debug.WriteLine("Gyroscope not available");
                }
                break;

            case MotionSensorType.Magnetometer:
                if (motionManager.MagnetometerAvailable)
                {
                    motionManager.MagnetometerUpdateInterval = (double)interval / ms;
                    motionManager.StartMagnetometerUpdates(NSOperationQueue.CurrentQueue, OnMagnometerChanged);
                }
                else
                {
                    Debug.WriteLine("Magnetometer not available");
                }
                break;

            case MotionSensorType.Compass:
                if (CLLocationManager.HeadingAvailable)
                {
                    locationManager.StartUpdatingHeading();
                    locationManager.UpdatedHeading += OnHeadingChanged;
                }
                else
                {
                    Debug.WriteLine("Compass not available");
                }
                break;
            }
            sensorStatus[sensorType] = true;
        }
Exemplo n.º 11
0
        protected override void StartListening()
        {
            base.StartListening();

            _motionManager.StartAccelerometerUpdates(new NSOperationQueue(), async(data, error) =>
            {
                if (!Stabilizing)
                {
                    await StoreDatumAsync(new AccelerometerDatum(DateTimeOffset.UtcNow, data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
                }
            });
        }
Exemplo n.º 12
0
        protected override void StartListening()
        {
            base.StartListening();

            _motionManager?.StartAccelerometerUpdates(new NSOperationQueue(), (data, error) =>
            {
                if (!Stabilizing && data != null && error == null)
                {
                    StoreDatum(new AccelerometerDatum(DateTimeOffset.UtcNow, data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
                }
            });
        }
Exemplo n.º 13
0
        private void SetupAccelerometer()
        {
            motionManager = new CMMotionManager();

            if (GCController.Controllers != null && GCController.Controllers.Length == 0 && motionManager.AccelerometerAvailable)
            {
                motionManager.AccelerometerUpdateInterval = 1.0 / 60.0;
                motionManager.StartAccelerometerUpdates(NSOperationQueue.MainQueue, (data, error) => {
                    AccelerometerDidChange(data.Acceleration);
                });
            }
        }
Exemplo n.º 14
0
        protected override async Task StartListeningAsync()
        {
            await base.StartListeningAsync();

            _motionManager?.StartAccelerometerUpdates(new NSOperationQueue(), async(data, error) =>
            {
                if (data != null && error == null)
                {
                    await StoreDatumAsync(new AccelerometerDatum(DateTimeOffset.UtcNow, data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
                }
            });
        }
Exemplo n.º 15
0
 public override void Start()
 {
     if (started == false)
     {
         motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, AccelerometerHandler);
         started = true;
         state   = SensorState.Ready;
     }
     else
     {
         throw new AccelerometerFailedException("Failed to start accelerometer data acquisition. Data acquisition already started.", -1);
     }
 }
        private void SetupAccelerometerReading()
        {
            // Movement of Pacman
            _lastUpdateTime = DateTime.Now;
            _currentPoint   = new PointF(0, 144);
            _motionManager  = new CMMotionManager();
            _motionManager.AccelerometerUpdateInterval = UPDATE_INTERVAL;

            _motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) => {
                _acceleration = data.Acceleration;
                InvokeOnMainThread(UpdatePacman);
            });
        }
Exemplo n.º 17
0
        protected override void StartSensor() {
            _sensorManager.AccelerometerUpdateInterval = 1.0 / SensorPack.AccelerometerDesiredHz;
            _sensorManager.StartAccelerometerUpdates (NSOperationQueue.CurrentQueue, (data, error) => {
                if (error == null) {
                    double accX = data.Acceleration.X;
                    double accY = data.Acceleration.Y;
                    double accZ = data.Acceleration.Z;

                    ReportAcceleration(accX, accY, accZ);
                }

                // TODO: catch error
            });
        }
Exemplo n.º 18
0
 public void StartListening()
 {
     _manager = new CMMotionManager();
     _manager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
     {
         AccelerometerEvent e = new AccelerometerEvent
         {
             XAcc = (float)data.Acceleration.X,
             YAcc = (float)data.Acceleration.Y,
             ZAcc = -(float)data.Acceleration.Z,
         };
         AccelerationChanged?.Invoke(this, e);
     });
 }
Exemplo n.º 19
0
        protected override void StartListening()
        {
            base.StartListening();

            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                _motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    if (!Stabilizing)
                    {
                        StoreDatum(new AccelerometerDatum(DateTimeOffset.UtcNow, data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
                    }
                });
            });
        }
        public void StartReading(int reportInterval = -1)
        {
            if (reportInterval >= 0)
            {
                _motionManager.AccelerometerUpdateInterval = reportInterval;
            }

            try
            {
                _motionManager.StartAccelerometerUpdates(NSOperationQueue.MainQueue, OnAccelerometerChanged);
            }
            catch (Exception ex)
            {
                OnReadingError?.Invoke(this, new DeviceSensorReadingErrorEventArgs("Accelerometer - Not called from the UIThread"));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Start the specified sensor type reading.
        /// </summary>
        /// <param name="sensorType">Sensor type</param>
        public override void Start(SensorType sensorType)
        {
            switch (sensorType)
            {
            case SensorType.Accelerometer:
                AccelerometerActive = true;
                motionManager.AccelerometerUpdateInterval = 0.05;
                motionManager.StartAccelerometerUpdates(NSOperationQueue.MainQueue, (data, error) =>
                {
                    EmitAccelerometer(new MotionVector(data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z));
                });
                break;

            case SensorType.Gyroscope:
                GyroActive = true;
                motionManager.GyroUpdateInterval = 0.05;
                motionManager.StartGyroUpdates(NSOperationQueue.MainQueue, (data, error) =>
                {
                    EmitGyroscope(new MotionVector(data.RotationRate.x, data.RotationRate.y, data.RotationRate.z));
                });
                break;

            case SensorType.DeviceMotion:
                DeviceMotionActive = true;
                motionManager.DeviceMotionUpdateInterval = 0.05d;
                motionManager.StartDeviceMotionUpdates(NSOperationQueue.MainQueue, (motion, error) =>
                {
                    EmitDeviceMotion(new MotionVector(motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw));
                });
                break;

            case SensorType.Compass:
                CompassActive = true;
                locationManager.UpdatedHeading += (sender, eventArgs) =>
                {
                    // TODO: Fix.
                    EmitCompass(eventArgs.NewHeading.TrueHeading);
                };
                locationManager.StartUpdatingHeading();
                break;

            case SensorType.LightLevel:
                LightLevelActive = false;
                break;
            }
        }
        public void Start()
        {
            // 加速度センサ
            if (motionManager.AccelerometerAvailable)
            {
                motionManager.AccelerometerUpdateInterval = 0.1;
                motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    // 加速度センサの取得間隔を取得(sec)
                    // CMAccelerometerData.Timestamp : デバイスが起動してからの秒単位の時間
                    double nowAccelTimeStamp = data.Timestamp;
                    double accelInterval     = (prevAccelTimeStamp != 0) ? (nowAccelTimeStamp - prevAccelTimeStamp) : 0;
                    prevAccelTimeStamp       = nowAccelTimeStamp;

                    AccelerationReceived(this, new SensorEventArgs
                    {
                        X        = data.Acceleration.X,
                        Y        = data.Acceleration.Y,
                        Z        = data.Acceleration.Z,
                        Interval = accelInterval
                    });
                });
            }

            // ジャイロスコープ
            if (motionManager.GyroAvailable)
            {
                motionManager.GyroUpdateInterval = 0.1;
                motionManager.StartGyroUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    // ジャイロの取得間隔を取得(sec)
                    // CMGyroData.Timestamp : デバイスが起動してからの秒単位の時間
                    double nowGyroTimeStamp = data.Timestamp;
                    double gyroInterval     = (prevGyroTimeStamp != 0) ? (nowGyroTimeStamp - prevGyroTimeStamp) : 0;
                    prevGyroTimeStamp       = nowGyroTimeStamp;

                    AngularVelocityReceived(this, new SensorEventArgs
                    {
                        X        = data.RotationRate.x,
                        Y        = data.RotationRate.y,
                        Z        = data.RotationRate.z,
                        Interval = gyroInterval
                    });
                });
            }
        }
Exemplo n.º 23
0
        public void GetSpeed()
        {
            motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
            {
                double x = data.Acceleration.X;
                double y = data.Acceleration.Y;
                double z = data.Acceleration.Z;

                DateTime curTime = System.DateTime.Now;

                if (hasUpdated == false)
                {
                    hasUpdated = true;
                    lastUpdate = curTime;

                    last_x = x;
                    last_y = y;
                    last_z = z;
                }
                else
                {
                    if ((curTime - lastUpdate).TotalMilliseconds > ShakeDetectionTimeLapse)
                    {
                        double diffTime = (double)(curTime - lastUpdate).TotalMilliseconds;
                        lastUpdate      = curTime;

                        double total    = x + y + z - last_x - last_y - last_z;
                        double getSpeed = (Math.Abs(total) / diffTime * 10000) * 4;

                        if (getSpeed > ShakeThreshold)
                        {
                            args.speed = getSpeed;
                            speedObtained(this, args);

                            System.Diagnostics.Debug.WriteLine("[GetShakeSpeed.iOS] Speed : " + getSpeed);
                        }

                        last_x = x;
                        last_y = y;
                        last_z = z;
                    }
                }
            });
        }
Exemplo n.º 24
0
        protected override bool StartService()
        {
            if (_motionManager == null || !IsAvailable() || (_orientationUpdateThread != null && _orientationUpdateThread.IsAlive))
            {
                return(false);
            }

            _motionManager.StartAccelerometerUpdates();

            _isOrientationUpdateThreadActive = true;

            _orientationUpdateThread = new Thread(OrientationUpdateThread)
            {
                Priority = ThreadPriority.BelowNormal
            };

            _orientationUpdateThread.Start();

            return(true);
        }
Exemplo n.º 25
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            motionManager = new CMMotionManager();

            StartButton.TouchUpInside += (sender, e) =>
            {
                motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    this.xLabel.Text = data.Acceleration.X.ToString("0.0000");
                    this.yLabel.Text = data.Acceleration.Y.ToString("0.0000");
                    this.zLabel.Text = data.Acceleration.Z.ToString("0.0000");
                });
            };

            StopButton.TouchUpInside += (sender, e) =>
            {
                motionManager.StopAccelerometerUpdates();
            };
        }
Exemplo n.º 26
0
        public void StartSensorUpdates()
        {
            // Raw accelerometer
            if (_motionManager.AccelerometerAvailable)
            {
                _motionManager.StartAccelerometerUpdates(_queue, HandleCMAccelerometerHandler);
            }

            if (_motionManager.GyroAvailable)
            {
                _motionManager.StartGyroUpdates(_queue, HandleCMGyroHandler);
            }

            if (_motionManager.MagnetometerAvailable)
            {
                _motionManager.StartMagnetometerUpdates(_queue, HandleCMMagnetometerHandler);
            }

            if (_motionManager.DeviceMotionAvailable)
            {
                _motionManager.StartDeviceMotionUpdates(_queue, HandleCMDeviceMotionHandler);
                _pedometer.StartPedometerUpdates(NSDate.Now, HandleCMPedometer);
            }

            //start updating headings
            _locationManager.StartUpdatingHeading();

            //// service for measurements once per minute
            UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;

            Timer timer = new Timer(60000);

            timer.AutoReset = true;
            timer.Elapsed  += SensorMeasurementSessionTimerElapsed;
            timer.Start();


            IsListening = true;
        }
Exemplo n.º 27
0
        private void preparePhysics()
        {
            spiderView.Center            = new CGPoint(Center.X, -height - spiderImage.Size.Height);
            spiderView.Layer.AnchorPoint = new CGPoint(0.5, 0);

            spiderAnimator = new UIDynamicAnimator(this);

            var spider = new UIDynamicItemBehavior(spiderView);

            spider.Action     = () => SetNeedsDisplay();
            spider.Resistance = spiderResistance;
            spiderAnimator.AddBehavior(spider);

            links = createRope();

            gravity = new UIGravityBehavior(links);
            spiderAnimator.AddBehavior(gravity);

            motionManager?.Dispose();
            motionManager = new CMMotionManager();
            motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, processAccelerometerData);
        }
Exemplo n.º 28
0
        public void Start()
        {
            if (motionManager.AccelerometerAvailable)
            {
                motionManager.AccelerometerUpdateInterval = 0.005;
                motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    // センサの取得間隔を取得(sec)
                    // CMAccelerometerData.Timestamp : デバイスが起動してからの秒単位の時間
                    double nowTimeStamp = data.Timestamp;
                    double interval     = (prevTimeStamp != 0) ? (nowTimeStamp - prevTimeStamp) : 0;
                    prevTimeStamp       = nowTimeStamp;

                    AccelerationReceived(this, new AccelerometerEventArgs {
                        X        = data.Acceleration.X,
                        Y        = data.Acceleration.Y,
                        Z        = data.Acceleration.Z,
                        Interval = interval
                    });
                });
            }
        }
Exemplo n.º 29
0
        private void preparePhysics()
        {
            spiderRadius = Math.Sqrt(Math.Pow(spiderImage.Size.Width / 2, 2) + Math.Pow(spiderImage.Size.Height / 2, 2));
            double height = (UIScreen.MainScreen.ApplicationFrame.Size.Width / 2) - 1.5 * spiderRadius;

            spiderAnimator = new UIDynamicAnimator(this);

            var spider = new UIDynamicItemBehavior(spiderView);

            spider.Action         = () => SetNeedsDisplay();
            spider.Resistance     = spiderResistance;
            spider.AllowsRotation = true;
            spiderAnimator.AddBehavior(spider);

            links = createRope(height);

            gravity = new UIGravityBehavior(links);
            spiderAnimator.AddBehavior(gravity);

            motionManager?.Dispose();
            motionManager = new CMMotionManager();
            motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, processAccelerometerData);
        }
Exemplo n.º 30
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Viewのサイズを取得
            layoutW = View.Bounds.Width;
            layoutH = View.Bounds.Height;

            // Viewサイズを元にLabelサイズを指定
            textW = layoutW / 2;
            textH = layoutH / 6;

            System.Diagnostics.Debug.WriteLine("Width: {0}, Height: {1}", layoutW, layoutH);

            // Label作成&配置
            var sensorText = new UILabel(new CGRect(layoutW / 2 - textW / 2, layoutH / 2 - textH / 2, textW, textH));
            sensorText.BackgroundColor = UIColor.FromRGB(192, 192, 192);
            sensorText.Lines = 0;
            sensorText.TextAlignment = UITextAlignment.Center;
            sensorText.LineBreakMode = UILineBreakMode.TailTruncation;
            View.AddSubview(sensorText);

            // Frameを取得して変数に
            var textLoc = sensorText.Frame;

            motionManager = new CMMotionManager();

            if (motionManager.AccelerometerAvailable)
            {
                // Accelerometer Update間隔
                motionManager.AccelerometerUpdateInterval = 0.015;
                // UpdateがQueueに入る度に処理を行う(多分)
                motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
                {
                    sensorText.Text = string.Format("X = {0:N4}\nY = {1:N4}", data.Acceleration.X, data.Acceleration.Y);
                    // 現在の位置を取得
                    nowX = sensorText.Frame.X;
                    nowY = sensorText.Frame.Y;

                    System.Diagnostics.Debug.WriteLine("nowX: {0}, nowY: {1}", nowX, nowY);

                    // Viewをはみ出さないようにAccelerometerの値によってLabelを移動
                    if (nowX + (nfloat)data.Acceleration.X * 10 > 0 && nowX + (nfloat)data.Acceleration.X * 10 < layoutW - textW)
                        textLoc.X = nowX + (nfloat)data.Acceleration.X * 10;

                    if (nowY - (nfloat)data.Acceleration.Y * 10 > 0 && nowY - (nfloat)data.Acceleration.Y * 10 < layoutH - textH)
                        textLoc.Y = nowY - (nfloat)data.Acceleration.Y * 10;

                    sensorText.Frame = textLoc;
                });
            }
        }
Exemplo n.º 31
0
 partial void UIButton21_TouchUpInside(UIButton sender)
 {
     starttime = DateTime.Now;
     builder.Append("{\"Type\":\"Training Data\",")
     .Append(" \"StartTime\": \"" + starttime.ToString() + "\",")
     .Append("\"Record\":[");
     StartButton.Enabled = false;
     StopButton.Enabled  = true;
     motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
     {
         double dataX   = data.Acceleration.X * 10;
         double dataY   = data.Acceleration.Y * 10;
         double dataZ   = data.Acceleration.Z * 10;
         this.lblX.Text = dataX.ToString("0.00000000");
         this.lblY.Text = dataY.ToString("0.00000000");
         this.lblZ.Text = dataZ.ToString("0.00000000");
         int i;
         reading[1] = -dataX;
         reading[2] = -dataX;
         reading[3] = -dataX;
         reading[0] = reading[1] * reading[1] + reading[2] * reading[2] + reading[3] * reading[3];
         if (count == -1)
         {
             for (i = 0; i < 4; i++)
             {
                 max[i] = reading[i];
                 min[i] = reading[i];
             }
             count++;
         }
         if (count == 90)
         {
             //calculate resultant acceleration
             max[0] = Math.Sqrt(max[0]);
             min[0] = Math.Sqrt(min[0]);
             avg[0] = sum[0] / 90;
             avg[0] = Math.Sqrt(avg[0]);
             for (i = 1; i < 4; i++)
             {
                 avg[i] = sum[i] / 90;
             }
             //write json
             builder.Append("{\"max_resultant\":" + max[0].ToString() + ",")
             .Append("\"min_resultant\":" + min[0].ToString() + ",")
             .Append("\"avg_resultant\":" + avg[0].ToString() + ",")
             .Append("\"max_x\":" + max[1].ToString() + ",")
             .Append("\"min_x\":" + min[1].ToString() + ",")
             .Append("\"avg_x\":" + avg[1].ToString() + ",")
             .Append("\"max_y\":" + max[2].ToString() + ",")
             .Append("\"min_y\":" + min[2].ToString() + ",")
             .Append("\"avg_y\":" + avg[2].ToString() + ",")
             .Append("\"max_z\":" + max[3].ToString() + ",")
             .Append("\"min_z\":" + min[3].ToString() + ",")
             .Append("\"avg_z\":" + avg[3].ToString() + "},");
             //renew max min sum
             for (i = 0; i < 4; i++)
             {
                 max[i] = reading[i];
                 min[i] = reading[i];
                 sum[i] = 0.0;
             }
             count = 0;
         }
         for (i = 0; i < 4; i++)
         {
             if (max[i] < reading[i])
             {
                 max[i] = reading[i];
             }
             if (min[i] > reading[i])
             {
                 min[i] = reading[i];
             }
             sum[i] += reading[i];
         }
         count++;
     });
 }
Exemplo n.º 32
0
		private void SetupAccelerometer ()
		{
			motionManager = new CMMotionManager ();

			if (GCController.Controllers != null && GCController.Controllers.Length == 0 && motionManager.AccelerometerAvailable) {
				motionManager.AccelerometerUpdateInterval = 1.0 / 60.0;
				motionManager.StartAccelerometerUpdates (NSOperationQueue.MainQueue, (data, error) => {
					AccelerometerDidChange (data.Acceleration);
				});
			}
		}
Exemplo n.º 33
0
        public void StartUpdatesWithMotionDataType(MotionDataType type, int sliderValue)
        {
            double updateInterval = 0.00;
            double delta          = 0.005;

            switch (graphDataSource)
            {
            case MotionDataType.AccelerometerData:
                updateInterval = GraphViewController.accelerometrMin + delta * sliderValue;
                if (mManager.AccelerometerAvailable)
                {
                    mManager.AccelerometerUpdateInterval = updateInterval;
                    mManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) => {
                        if (primaryGraph == null)
                        {
                            return;
                        }

                        primaryGraph.AddX(data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z);
                        SetLabelValueX(data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z);
                    });
                }
                primaryGraphLabel.Text = "AccelerometerData.Acceleration";
                break;

            case MotionDataType.GyroData:
                updateInterval = gyroMin + delta * sliderValue;
                if (mManager.GyroAvailable)
                {
                    mManager.GyroUpdateInterval = updateInterval;
                    mManager.StartGyroUpdates(NSOperationQueue.CurrentQueue, (gyroData, error) => {
                        if (primaryGraph == null)
                        {
                            return;
                        }

                        primaryGraph.AddX(gyroData.RotationRate.x, gyroData.RotationRate.y, gyroData.RotationRate.z);
                        SetLabelValueX(gyroData.RotationRate.x, gyroData.RotationRate.y, gyroData.RotationRate.z);
                    });
                }
                primaryGraphLabel.Text = "GyroData.RotationRate";
                break;

            case MotionDataType.DeviceMotion:
                updateInterval = deviceMotionMin + delta * sliderValue;
                if (mManager.DeviceMotionAvailable)
                {
                    mManager.DeviceMotionUpdateInterval = updateInterval;
                    mManager.StartDeviceMotionUpdates(NSOperationQueue.CurrentQueue, (motion, error) => {
                        graphs [(int)DeviceMotionGraphType.Attitude].AddX(motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw);
                        graphs [(int)DeviceMotionGraphType.RotationRate].AddX(motion.RotationRate.x, motion.RotationRate.y, motion.RotationRate.z);
                        graphs [(int)DeviceMotionGraphType.Gravity].AddX(motion.Gravity.X, motion.Gravity.Y, motion.Gravity.Z);
                        graphs [(int)DeviceMotionGraphType.UserAcceleration].AddX(motion.UserAcceleration.X, motion.UserAcceleration.Y, motion.UserAcceleration.Z);

                        switch ((DeviceMotionGraphType)SegmentedControl.SelectedSegment)
                        {
                        case DeviceMotionGraphType.Attitude:
                            SetLabelValueRoll(motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw);
                            break;

                        case DeviceMotionGraphType.RotationRate:
                            SetLabelValueX(motion.RotationRate.x, motion.RotationRate.y, motion.RotationRate.z);
                            break;

                        case DeviceMotionGraphType.Gravity:
                            SetLabelValueX(motion.Gravity.X, motion.Gravity.Y, motion.Gravity.Z);
                            break;

                        case DeviceMotionGraphType.UserAcceleration:
                            SetLabelValueX(motion.UserAcceleration.X, motion.UserAcceleration.Y, motion.UserAcceleration.Z);
                            break;
                        }
                    });
                }
                primaryGraphLabel.Text = graphTitles [SegmentedControl.SelectedSegment];
                break;
            }
            UpdateIntervalLabel.Text = updateInterval.ToString();
        }
Exemplo n.º 34
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // For accelerometer readings
            motionManager = new CMMotionManager();
            motionManager.AccelerometerUpdateInterval = 0.01; // 100Hz

            //To handle long presses and bring up path start/end menu
            var longPressManager = new UILongPressGestureRecognizer();

            //Graph loading code
			//Graph loading code
			var assembly = Assembly.GetExecutingAssembly();
			var asset = assembly.GetManifestResourceStream("Navigator.iOS.Resources.dcsfloorWideDoors.xml");

			pf = new Pathfinding.Pathfinding(new Dictionary<int, Stream>()
				{
					{0,assembly.GetManifestResourceStream("Navigator.iOS.Resources.dcsfloorWideDoors.xml")},
					{1,assembly.GetManifestResourceStream("Navigator.iOS.Resources.dcsFloor1.xml")}
				},assembly.GetManifestResourceStream("Navigator.iOS.Resources.Rooms.xml") );
			pf.CurrentFloor = 0;

			while (true)
			{
				if (pf.Ready)            

					break;
				Thread.Sleep(500);
			}
				
			//set up the search bar and prediction box
			var searchController = new CustomSearchController(this, SearchBar, SearchPredictionTable, pf.Rooms);
		
            floorPlanGraph = Graph.Load(asset);

            wallCollImg = UIImage.FromBundle("Images/dcsfloorWideDoors.png");

            col = new Collision(floorPlanGraph, new StepDetector());

            ((Collision)col).WallCol = new WallCollision ((x,y) => GetPixelColor(new PointF(x, y), wallCollImg));
            wallColTest = new WallCollision ((x,y) => GetPixelColor(new PointF(x, y), wallCollImg));

            pathView = new PathView (wallColTest);

            col.SetLocation(707.0f, 677.0f);
            col.PassHeading(90);
            col.PositionChanged += HandleStepsTaken;

			//Container for floorplan and any overlaid images
            var container = new UIView();

			//Will contain floorplan images
            floorplanImageView = new UIImageView();

			//Load floorplan images
            floorplanImageNoGrid = UIImage.FromBundle("Images/FinalDcsFloor1.png");
            floorplanImageWithGrid = UIImage.FromBundle("Images/dcsFloorWideDoorsGrid.png");

			//Initiate the location arrow
            locationArrow = new LocationArrowImageView();
            locationArrow.ScaleFactor = floorplanView.ZoomScale;
            pathView.ScaleFactor = floorplanView.ZoomScale;
            setStartPoint(690.0f, 840.0f);

			//Set sizes for floorplan view and path view
            floorplanView.ContentSize = floorplanImageNoGrid.Size;
            pathView.Frame = new CGRect(new CGPoint(0, 0), floorplanImageNoGrid.Size);

			//Add subviews to the container (including pathview and floorplanview)
            container.AddSubview(floorplanImageView);
            container.AddSubview(locationArrow);
            floorplanImageView.AddSubview(pathView);
            changeFloorPlanImage(floorplanImageView, floorplanImageNoGrid);
            container.SizeToFit();

			//Adjust scrolling and zooming properties for the floorplanView
            floorplanView.MaximumZoomScale = 1f;
            floorplanView.MinimumZoomScale = .25f;
            floorplanView.AddSubview(container);
            floorplanView.ViewForZoomingInScrollView += (UIScrollView sv) => { return floorplanImageView; };

			//Variables needed to convert device acceleration to world z direction acceleration
			double accelX = 0, accelY = 0, accelZ = 0;

			//Scale location arrow and paths when zooming the floorplan
            floorplanView.DidZoom += (sender, e) =>
            {
                locationArrow.ScaleFactor = floorplanView.ZoomScale;
                pathView.ScaleFactor = floorplanView.ZoomScale;
            };

			//Pass acceleremoter values to the collision class
            motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue,
                (data, error) =>
                {
					accelX = data.Acceleration.X*9.8;
					accelY = data.Acceleration.Y*9.8;
					accelZ = Math.Sqrt(Math.Pow(accelX, 2) + Math.Pow(accelY, 2) + Math.Pow(data.Acceleration.Z*9.8, 2));

                    col.PassSensorReadings(CollisionSensorType.Accelometer, accelX,
                        accelY, accelZ);
                    //displayAccelVal((float)accelZ);
                });

			/*
			motionManager.StartDeviceMotionUpdates(NSOperationQueue.CurrentQueue, (data, error) =>
				{ 
					//data.Attitude.MultiplyByInverseOfAttitude(data.Attitude);
					var test = data.UserAcceleration.X;
					var accelRelZ = data.Attitude.RotationMatrix.m31 * accelX + data.Attitude.RotationMatrix.m32 * accelY + data.Attitude.RotationMatrix.m33 * accelZ;
					debugLabel.Text = "" + Math.Round(test, 2);//Math.Round(accelRelZ, 2);
				}
			);
			*/

			//LongPressManager will cause the path input menu to appear after a stationary long press
            longPressManager.AllowableMovement = 0;
            longPressManager.AddTarget(() => handleLongPress(longPressManager, floorPlanGraph));
            floorplanView.AddGestureRecognizer(longPressManager);

			//the location manager handles the phone heading
            locationManager = new CLLocationManager();
            locationManager.DesiredAccuracy = CLLocation.AccuracyBest;
            locationManager.HeadingFilter = 1;
            locationManager.UpdatedHeading += HandleUpdatedHeading;
            locationManager.StartUpdatingHeading();

			//Button currently used for testing purposes only

			//Another testing button
            simulationButton.TouchUpInside += delegate { col.StepTaken(false); };

            returnButton.TouchUpInside += delegate{ returnToMenu(); };

        }