Example #1
0
        async Task <PermissionStatus> RequestSensorsPermission()
        {
            if (CMMotionActivityManager.IsActivityAvailable)
            {
                return(PermissionStatus.Granted);
            }

            if (activityManager == null)
            {
                activityManager = new CMMotionActivityManager();
            }

            try
            {
                var results = await activityManager.QueryActivityAsync(NSDate.DistantPast, NSDate.DistantFuture, NSOperationQueue.MainQueue).ConfigureAwait(false);

                if (results != null)
                {
                    return(PermissionStatus.Granted);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to query activity manager: " + ex.Message);
                return(PermissionStatus.Denied);
            }

            return(PermissionStatus.Unknown);
        }
Example #2
0
        internal static async Task <PermissionStatus> RequestSensorsPermission()
        {
            if (SensorsPermissionStatus != PermissionStatus.Unknown)
            {
                return(SensorsPermissionStatus);
            }

#if __IOS__
            var activityManager = new CMMotionActivityManager();

            try
            {
                var results = await activityManager.QueryActivityAsync(NSDate.DistantPast, NSDate.DistantFuture, NSOperationQueue.MainQueue);

                if (results != null)
                {
                    return(PermissionStatus.Granted);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to query activity manager: " + ex.Message);
                return(PermissionStatus.Denied);
            }
#endif

            return(PermissionStatus.Unknown);
        }
Example #3
0
        async Task queryHistoricalDataAsync(NSDate startDate, NSDate endDate)
        {
            try {
                var activities = await motionActivityMgr.QueryActivityAsync(startDate, endDate, NSOperationQueue.MainQueue);

                await additionalProcessingOnAsync(activities);

                var pedometerData = await pedometer.QueryPedometerDataAsync(startDate, endDate);

                StepCounts = pedometerData.NumberOfSteps.Int32Value;
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Example #4
0
        //private void MergeWalkingDataPoints(ref List<WalkingDataPointModel> dataPoints)
        //{
        //    dataPoints.Sort((dp1, dp2) => dp1.Start.CompareTo(dp2.Start));
        //    for(int i = dataPoints.Count - 2; i >= 0; --i)
        //    {
        //        var current = dataPoints[i];
        //        var next = dataPoints[i + 1];

        //        if (next.Start >= DateTime.Today)
        //        {
        //            const double MERGE_THRESHOLD_SECONDS = 1;

        //            if (next.WasBrisk == current.WasBrisk)
        //            {
        //                if (Math.Abs((next.Start - current.Stop).TotalSeconds) <= MERGE_THRESHOLD_SECONDS)
        //                {
        //                    current.Stop = next.Stop;
        //                    dataPoints.Remove(next);
        //                }
        //            }
        //        }
        //    }
        //}

        private async Task <bool?> QueryActivityPeriodAsync(DateTime from, DateTime to)
        {
            try
            {
                bool wasWalkingOrRunning = false;
                var  rawDataPoints       = await activityManager.QueryActivityAsync(from.ToNSDate(), to.ToNSDate(), NSOperationQueue.MainQueue);

                foreach (var dp in rawDataPoints)
                {
                    if (dp.Walking || dp.Running)
                    {
                        wasWalkingOrRunning = true;
                    }
                }
                return(wasWalkingOrRunning);
            }catch (Exception e)
            {
#if DEBUG
                Debug.WriteLine("Failed to query activity datapoint {0}-{1}: {2}", from.ToLongTimeString(), to.ToLongTimeString(), e.Message);
#endif
            }

            return(null);
        }
Example #5
0
        protected override async Task <List <Datum> > PollAsync(CancellationToken cancellationToken)
        {
            List <Datum> data = new List <Datum>();

            // if this is the first poll (no existing query start time), set the query start time to the current time. we
            // used to set this to the maximally previous time per ios documentation (7 days), but this (1) causes issues
            // when triggering surveys on the basis of these activities (there might be hundreds of activities within the
            // past 7 days), and it also runs counter to the user's expectations that data will only be collected from the
            // time at which they have enrolled in the study and not from times prior.
            if (_queryStartTime == null)
            {
                _queryStartTime = DateTimeOffset.UtcNow;
            }

            await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() =>
            {
                try
                {
                    CMMotionActivityManager activityManager = new CMMotionActivityManager();

                    CMMotionActivity[] activities = await activityManager.QueryActivityAsync(_queryStartTime.Value.UtcDateTime.ToNSDate(), NSDate.Now, NSOperationQueue.CurrentQueue);

                    // process each activity, keeping track of most recent
                    NSDate mostRecentActivityStartTime = null;
                    foreach (CMMotionActivity activity in activities)
                    {
                        DateTimeOffset timestamp = new DateTimeOffset(activity.StartDate.ToDateTime(), TimeSpan.Zero);

                        #region get confidence
                        ActivityConfidence confidence = ActivityConfidence.NotAvailable;

                        if (activity.Confidence == CMMotionActivityConfidence.Low)
                        {
                            confidence = ActivityConfidence.Low;
                        }
                        else if (activity.Confidence == CMMotionActivityConfidence.Medium)
                        {
                            confidence = ActivityConfidence.Medium;
                        }
                        else if (activity.Confidence == CMMotionActivityConfidence.High)
                        {
                            confidence = ActivityConfidence.High;
                        }
                        else
                        {
                            SensusException.Report("Unrecognized confidence:  " + activity.Confidence);
                        }
                        #endregion

                        #region get activities
                        Action <Activities> AddActivityDatum = activityType =>
                        {
                            ActivityDatum activityDatum = new ActivityDatum(timestamp, activityType, ActivityPhase.Starting, ActivityState.Active, confidence);
                            data.Add(activityDatum);
                        };

                        if (activity.Stationary)
                        {
                            AddActivityDatum(Activities.Still);
                        }

                        if (activity.Walking)
                        {
                            AddActivityDatum(Activities.Walking);
                        }

                        if (activity.Running)
                        {
                            AddActivityDatum(Activities.Running);
                        }

                        if (activity.Automotive)
                        {
                            AddActivityDatum(Activities.InVehicle);
                        }

                        if (activity.Cycling)
                        {
                            AddActivityDatum(Activities.OnBicycle);
                        }

                        if (activity.Unknown)
                        {
                            AddActivityDatum(Activities.Unknown);
                        }
                        #endregion

                        if (mostRecentActivityStartTime == null)
                        {
                            mostRecentActivityStartTime = activity.StartDate;
                        }
                        else
                        {
                            mostRecentActivityStartTime = mostRecentActivityStartTime.LaterDate(activity.StartDate);
                        }
                    }

                    // set the next query start time one second after the most recent activity's start time
                    if (mostRecentActivityStartTime != null)
                    {
                        _queryStartTime = new DateTime(mostRecentActivityStartTime.ToDateTime().Ticks, DateTimeKind.Utc).AddSeconds(1);
                    }
                }
                catch (Exception ex)
                {
                    SensusServiceHelper.Get().Logger.Log("Exception while querying activities:  " + ex, LoggingLevel.Normal, GetType());
                }
            });

            // let the system know that we polled but didn't get any data
            if (data.Count == 0)
            {
                data.Add(null);
            }

            return(data);
        }