/// <summary> /// Initializes the sensor /// </summary> /// <exception cref="NotSupportedException">The device does not support the sensor</exception> /// <exception cref="UnauthorizedAccessException">The user does not grant your app access to sensors</exception> public PedometerService() { try { // A NotSupportedException will be thrown if the sensor is not available on the device _sensor = new Pedometer(); // Add an event handler to the sensor _sensor.DataUpdated += OnSensorDataUpdated; // TODO: Declare how the sensor behaves when the screen turns off or the device goes into power save mode // For details see https://docs.tizen.org/application/dotnet/guides/location-sensors/device-sensors // _sensor.PausePolicy = SensorPausePolicy.None; // TODO: Set the update interval in milliseconds // _sensor.Interval = 1000; } catch (NotSupportedException) { // TODO: The device does not support the sensor, handle exception as appropriate to your scenario } catch (UnauthorizedAccessException) { // TODO: The user does not grant your app access to sensors, handle exception as appropriate to your scenario } }
/// <summary> /// Invoked when 'Register Task' button is clicked. Attempts to find a default /// Pedometer and registers a background task with a step goal of 50 steps. /// Adds a /// </summary> private async void ScenarioRegisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { sensor = await Pedometer.GetDefaultAsync(); if (sensor != null) { var status = await BackgroundExecutionManager.RequestAccessAsync(); if ((BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity == status) || (BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity == status)) { RegisterBackgroundTask(); } else { rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("No pedometer sensors found", NotifyType.ErrorMessage); } } catch (UnauthorizedAccessException) { rootPage.NotifyUser("User has denied access to Pedometer history", NotifyType.ErrorMessage); } }
/// <summary> /// Invoked when 'Register Task' button is clicked. Attempts to find a default /// Pedometer and registers a background task with a step goal of 50 steps. /// Adds a /// </summary> private async void ScenarioRegisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { sensor = await Pedometer.GetDefaultAsync(); if (sensor != null) { var status = await BackgroundExecutionManager.RequestAccessAsync(); if ((BackgroundAccessStatus.AlwaysAllowed == status) || (BackgroundAccessStatus.AllowedSubjectToSystemPolicy == status)) { RegisterBackgroundTask(); } else { rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("No pedometer sensors found", NotifyType.ErrorMessage); } } catch (UnauthorizedAccessException) { rootPage.NotifyUser("User has denied access to Pedometer history", NotifyType.ErrorMessage); } }
/// <summary> /// Returns steps for given day at given resolution /// </summary> /// <param name="day">Day to fetch data for</param> /// <param name="resolution">Resolution in minutes. Minimum resolution is five minutes.</param> /// <returns>List of steps counts for the given day at given resolution.</returns> public async Task <List <KeyValuePair <TimeSpan, uint> > > GetStepsCountsForDay(DateTime day, uint resolution) { List <KeyValuePair <TimeSpan, uint> > steps = new List <KeyValuePair <TimeSpan, uint> >(); uint numIntervals = (((24 * 60) / resolution) + 1); if (day.Date.Equals(DateTime.Today)) { numIntervals = (uint)((DateTime.Now - DateTime.Today).TotalMinutes / resolution) + 1; } uint totalSteps = 0; for (uint i = 0; i < numIntervals; i++) { TimeSpan ts = TimeSpan.FromMinutes(i * resolution); DateTime startTime = day.Date + ts; if (startTime < DateTime.Now) { // Get history from startTime to the resolution duration var readings = await Pedometer.GetSystemHistoryAsync(startTime, TimeSpan.FromMinutes(resolution)); // Compute the deltas var stepsDelta = StepCountData.FromPedometerReadings(readings); // Add to the total count totalSteps += stepsDelta.TotalCount; steps.Add(new KeyValuePair <TimeSpan, uint>(ts, totalSteps)); } else { break; } } return(steps); }
/// <summary> /// Gets sensor information. /// </summary> /// <returns>Sensor information.</returns> public SensorInfo GetSensorInfo() { SensorInfo info = new SensorInfo(); info.Type = SensorTypes.PedometerType; try { sensor = new Pedometer { Interval = 100, PausePolicy = SensorPausePolicy.None }; info.Name = sensor.Name; info.Vendor = sensor.Vendor; info.MinRange = sensor.MinValue; info.MaxRange = sensor.MaxValue; info.Resolution = sensor.Resolution; info.MinInterval = sensor.MinInterval; } catch (Exception e) { global::Tizen.Log.Info(Log.LogTag, e.Message); info.Status = "Permission Denied"; } return(info); }
/// <summary> /// 'Register ReadingChanged' button click handler. Registers to the ' /// ReadingChanged' event of the default pedometer opened earlier. /// </summary> /// <param name="sender">unused</param> /// <param name="e">unused</param> async private void RegisterButton_Click(object sender, RoutedEventArgs e) { // Get the default sensor if (!registeredForEvents) { RegisterButton.IsEnabled = false; try { pedometer = await Pedometer.GetDefaultAsync(); if (pedometer == null) { rootPage.NotifyUser("No pedometer available", NotifyType.ErrorMessage); } RegisterButton.Content = "UnRegister ReadingChanged"; RegisterButton.IsEnabled = true; rootPage.NotifyUser("Registered for step count changes", NotifyType.StatusMessage); } catch (System.UnauthorizedAccessException) { rootPage.NotifyUser("Access to the default pedometer is denied", NotifyType.ErrorMessage); } pedometer.ReadingChanged += Pedometer_ReadingChanged; registeredForEvents = true; } else { pedometer.ReadingChanged -= Pedometer_ReadingChanged; pedometer = null; RegisterButton.Content = "Register ReadingChanged"; registeredForEvents = false; rootPage.NotifyUser("Pedometer available - Not registered for events", NotifyType.StatusMessage); } }
/// <summary> /// 步数变化 /// </summary> private void Pedometer_ReadingChanged(Pedometer sender, PedometerReadingChangedEventArgs args) { PedometerReading reding = args.Reading; if (reding.StepKind == PedometerStepKind.Running) { if (rs == reding.CumulativeSteps) { return; } rs = reding.CumulativeSteps; } else { if (ws == reding.CumulativeSteps) { return; } ws = reding.CumulativeSteps; } double h = Math.Round(nowH, 1); double p = pressure.GetCurrentReading().StationPressureInHectopascals; int s = args.Reading.CumulativeSteps; long time = TimeUtil.getNowStamp(); dm.insertHeight(time, h, p, ws, rs); }
public Database() { DropTables(); // Drop table to ensure that the table is fresh CheckDbExist("1"); GetAugmonInfo(); // retrieve default augmon data GetPedometerInfo(); // retrieve default pedometer data Augmon tempmon = new Augmon(); /*** Tested Dummy Data ***/ tempmon.ID = 1; tempmon.Total_xp = 50; tempmon.Lvl = 2; tempmon.Attack = 35; tempmon.Defense = 26; tempmon.Happiness = 99; StoreAugmonInfo(tempmon); Pedometer pp = new Pedometer(); /*** Tested Dummy Data ***/ pp.ID = 1; pp.Total_step = 500; pp.Daily_step = 60; StorePedometerInfo(pp); GetAugmonInfo(); // retrieve updated augmon data GetPedometerInfo(); // retrieve updated pedometer data }
// Use this for initialization void Start() { Database db = new Database(); DAO dao = new DAO(); Debug.Log("Login With Email:\t\t" + dao.LoginWithEmail("*****@*****.**", "aaa")); Debug.Log("Register with Email:\t\t" + dao.Register("*****@*****.**", "zzz")); Debug.Log("Register with Facebook:\t\t" + dao.RegisterWithFacebook("32151fads12321")); Debug.Log("Login with Facebook:\t\t" + dao.LoginWithFacebook("32151fads12321")); Augmon augmon = new Augmon(); augmon.ID = 2; augmon.Total_xp = 292929; augmon.Attack = 25; augmon.Defense = 40; augmon.Happiness = 88; Debug.Log("Update Augmon Info:\t\t" + dao.UpdateAugmon(augmon)); Pedometer p = new Pedometer(); p.ID = 2; p.Total_step = 10231; p.Daily_step = 2131; Debug.Log("Update Pedometer Info:\t\t" + dao.UpdatePedometer(p)); Debug.Log("Get Augmon Info:\t\t" + dao.GetAugmonInfo(2)); Debug.Log("Get Pedometer Info:\t\t" + dao.GetPedometerInfo(2)); Debug.Log("Get User Info:\t\t" + dao.GetUserInfo(2)); }
/// <summary> /// Returns step count for given day /// </summary> /// <returns>Step count for given day</returns> public async Task <StepCountData> GetTotalStepCountAsync(DateTime day) { // Get history from 1 day var readings = await Pedometer.GetSystemHistoryAsync(day.Date, TimeSpan.FromDays(1)); return(StepCountData.FromPedometerReadings(readings)); }
public void StartSensors() { m_logger.Debug("StartSensors"); Pedometer.Start(); Compass.Start(); }
public WizardBotThread(Client Client) { this.Client = Client; Target = new Targeting(this); PathFinder = new SonarV2(Client); WalkingPath = new Pedometer(Client, PathFinder); }
// Start is called before the first frame update public void Start() { pedometer = new Pedometer(OnStep); OnStep(0, 0); print_shoes_count(); print_gold_count(); }
private void Start() { // Create a new pedometer pedometer = new Pedometer(OnStep); // Reset UI OnStep(0, 0); }
// Use this for initialization void Awake() { DAO database = new DAO(); Pedometer ped = database.GetPedometerInfo(FacebookManager.Instance().user_ID); pedometersteps = ped.Total_step; isClosed = true; }
private void Start() { // Create a new pedometer // Reset UI mileStep.text = milestone.ToString(); pedometer = new Pedometer(OnStep); OnStep(0, 0); }
private void Start() { Debug.Log("Started"); // Create a new pedometer pedometer = new Pedometer(OnStep); // Reset UI OnStep(0, 0); }
private void Start() { // Create a new pedometer // Reset UI HPBar.maxValue = HP = PlayerPrefs.GetInt("m_current_hp"); pedometer = new Pedometer(OnStep); OnStep(0, 0); }
private void Start() { sceneM = SceneManager.GetActiveScene(); // Create a new pedometer pedometer = new Pedometer(OnStep); // Reset UI OnStep(0, 0); }
public List <DeviceInfo> CreateList() { List <DeviceInfo> selectors = new List <DeviceInfo>(); // Pre-canned device class selectors selectors.Add(new DeviceInfo() { DisplayName = "All Device Interfaces (default)", DeviceClassSelector = DeviceClass.All, Selection = null }); selectors.Add(new DeviceInfo() { DisplayName = "Audio Capture", DeviceClassSelector = DeviceClass.AudioCapture, Selection = null }); selectors.Add(new DeviceInfo() { DisplayName = "Audio Render", DeviceClassSelector = DeviceClass.AudioRender, Selection = null }); selectors.Add(new DeviceInfo() { DisplayName = "Image Scanner", DeviceClassSelector = DeviceClass.ImageScanner, Selection = null }); selectors.Add(new DeviceInfo() { DisplayName = "Location", DeviceClassSelector = DeviceClass.Location, Selection = null }); selectors.Add(new DeviceInfo() { DisplayName = "Portable Storage", DeviceClassSelector = DeviceClass.PortableStorageDevice, Selection = null }); selectors.Add(new DeviceInfo() { DisplayName = "Video Capture", DeviceClassSelector = DeviceClass.VideoCapture, Selection = null }); // A few examples of selectors built dynamically by windows runtime apis. selectors.Add(new DeviceInfo() { DisplayName = "Human Interface (HID)", Selection = HidDevice.GetDeviceSelector(0, 0) }); selectors.Add(new DeviceInfo() { DisplayName = "Activity Sensor", Selection = ActivitySensor.GetDeviceSelector() }); selectors.Add(new DeviceInfo() { DisplayName = "Pedometer", Selection = Pedometer.GetDeviceSelector() }); selectors.Add(new DeviceInfo() { DisplayName = "Proximity", Selection = ProximityDevice.GetDeviceSelector() }); selectors.Add(new DeviceInfo() { DisplayName = "Proximity Sensor", Selection = ProximitySensor.GetDeviceSelector() }); return(selectors); }
/// <summary> /// Gets number of steps for current day /// </summary> /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns> private async Task <bool> GetStepsAsync() { // First try the pedometer try { var readings = await Pedometer.GetSystemHistoryAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date); _steps = StepCountData.FromPedometerReadings(readings); return(true); } catch (Exception) { // Continue to the fallback } // Fall back to using Lumia Sensor Core. IStepCounter stepCounter = null; try { //var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues; if (DeviceTypeHelper.GetDeviceFormFactorType() == DeviceFormFactorType.Phone) { stepCounter = await StepCounter.GetDefaultAsync(); StepCount count = await stepCounter.GetStepCountForRangeAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date); _steps = StepCountData.FromLumiaStepCount(count); } else { var obj = await SenseRecording.LoadFromFileAsync("Simulations\\short recording.txt"); if (!await CallSensorCoreApiAsync(async() => { stepCounter = await StepCounterSimulator.GetDefaultAsync(obj, DateTime.Now - TimeSpan.FromHours(12)); StepCount count = await stepCounter.GetStepCountForRangeAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date); _steps = StepCountData.FromLumiaStepCount(count); })) { return(false); } } } catch (Exception e) { _lastError = SenseHelper.GetSenseError(e.HResult); return(false); } finally { if (stepCounter != null && typeof(StepCounter) == stepCounter.GetType()) { ((StepCounter)stepCounter).Dispose(); } } return(true); }
private void Start() { // Create a new pedometer pedometer = new Pedometer(OnStep); player = FindObjectOfType <PlayerInfo>(); savedSteps = player.steps; OnStep(0, 0); }
/// <summary> /// Invoked when 'GetCurrentButton' is clicked. /// 'ReadingChanged' will not be fired when there is no activity on the pedometer /// and hence can't be reliably used to get the current step count. This handler makes /// use of pedometer history on the system to get the current step count of the parameter /// </summary> async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { DateTime dt = DateTime.FromFileTimeUtc(0); int totalStepCount = 0; int lastTotalCount = 0; rootPage.NotifyUser("Retrieving history to get current step counts", NotifyType.StatusMessage); // Disable the button while we get the history GetCurrentButton.IsEnabled = false; DateTimeOffset fromBeginning = new DateTimeOffset(dt); IReadOnlyList <PedometerReading> historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning); // History always returns chronological list of step counts for all PedometerStepKinds // And each record represents cumulative step counts for that step kind. // So we will use the last set of records - that gives us the cumulative step count for // each kind and ignore rest of the records PedometerStepKind stepKind = PedometerStepKind.Unknown; DateTimeOffset lastReadingTimestamp; bool resetTotal = false; foreach (PedometerReading reading in historyReadings) { if (stepKind == PedometerStepKind.Running) { // reset the total after reading the 'PedometerStepKind.Running' count resetTotal = true; } totalStepCount += reading.CumulativeSteps; if (resetTotal) { lastReadingTimestamp = reading.Timestamp; lastTotalCount = totalStepCount; stepKind = PedometerStepKind.Unknown; totalStepCount = 0; resetTotal = false; } else { stepKind++; } } ScenarioOutput_TotalStepCount.Text = lastTotalCount.ToString(); DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime"); ScenarioOutput_Timestamp.Text = timestampFormatter.Format(lastReadingTimestamp); rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage); GetCurrentButton.IsEnabled = true; }
public PedometerDeviceSensor() { try { _pedometer = new Pedometer(); } catch (NotSupportedException) { } }
/// <summary> /// Invoked when the underlying Pedometer sees a change in the step count for a step kind /// </summary> /// <param name="sender">unused</param> /// <param name="args">Pedometer reading that is being notified</param> async private void Pedometer_ReadingChanged(Pedometer sender, PedometerReadingChangedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { PedometerReading reading = args.Reading; int newCount = 0; // update step counts based on the step kind switch (reading.StepKind) { case PedometerStepKind.Unknown: if (reading.CumulativeSteps < unknownStepCount) { unknownStepCount = 0; } newCount = reading.CumulativeSteps - unknownStepCount; unknownStepCount = reading.CumulativeSteps; ScenarioOutput_UnknownCount.Text = unknownStepCount.ToString(); ScenarioOutput_UnknownDuration.Text = reading.CumulativeStepsDuration.TotalMilliseconds.ToString(); break; case PedometerStepKind.Walking: if (reading.CumulativeSteps < walkingStepCount) { walkingStepCount = 0; } newCount = reading.CumulativeSteps - walkingStepCount; walkingStepCount = reading.CumulativeSteps; ScenarioOutput_WalkingCount.Text = walkingStepCount.ToString(); ScenarioOutput_WalkingDuration.Text = reading.CumulativeStepsDuration.TotalMilliseconds.ToString(); break; case PedometerStepKind.Running: if (reading.CumulativeSteps < runningStepCount) { runningStepCount = 0; } newCount = reading.CumulativeSteps - runningStepCount; runningStepCount = reading.CumulativeSteps; ScenarioOutput_RunningCount.Text = runningStepCount.ToString(); ScenarioOutput_RunningDuration.Text = reading.CumulativeStepsDuration.TotalMilliseconds.ToString(); break; default: break; } totalCumulativeSteps += newCount; ScenarioOutput_TotalStepCount.Text = totalCumulativeSteps.ToString(); DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime"); ScenarioOutput_Timestamp.Text = timestampFormatter.Format(reading.Timestamp); }); }
public async void StartReading(int reportInterval = -1) { _pedometer = await Pedometer.GetDefaultAsync(); if (reportInterval >= 0) { _pedometer.ReportInterval = (uint)reportInterval; } _pedometer.ReadingChanged += PedometerReadingChanged; }
private void Update() { // Release the pedometer pedometer.Dispose(); pedometer = null; for (int i = 0; i < options.Length; i++) { if (i == index) { part.sprite = options[i]; } } }
/// <summary> /// Invoked when 'GetCurrentButton' is clicked. /// 'ReadingChanged' will not be fired when there is no activity on the pedometer /// and hence can't be reliably used to get the current step count. This handler makes /// use of 'GetCurrentReadings' API to determine the current step count /// </summary> async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // Determine if we can access pedometers var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId); if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed) { // Determine if a pedometer is present // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync var sensor = await Pedometer.GetDefaultAsync(); if (sensor != null) { DateTime dt = DateTime.FromFileTimeUtc(0); int totalStepCount = 0; // Get the current readings to find the current step counters var currentReadings = sensor.GetCurrentReadings(); bool updateTimestamp = true; foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind))) { PedometerReading reading; if (currentReadings.TryGetValue(kind, out reading)) { totalStepCount += reading.CumulativeSteps; } if (updateTimestamp) { DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime"); ScenarioOutput_Timestamp.Text = timestampFormatter.Format(reading.Timestamp); updateTimestamp = false; } } ScenarioOutput_TotalStepCount.Text = totalStepCount.ToString(); rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage); // Re-enable button GetCurrentButton.IsEnabled = true; } else { rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage); } }
/// <summary> /// Releases all resources used by the current instance /// </summary> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _sensor.DataUpdated -= OnSensorDataUpdated; _sensor.Dispose(); } _sensor = null; _disposed = true; } }
/******************************************************************************************************************************/ /*** Update All function : Pedometer ***/ /******************************************************************************************************************************/ public void StorePedometerInfo(Pedometer pedometer) { OpenConnection(); Debug.Log("StorePedometerInfo being called"); dbcmd = dbcon.CreateCommand(); dbcmd.CommandType = CommandType.Text; string sql = "UPDATE pedometer SET total_steps = " + pedometer.Total_step + ", daily_steps = " + pedometer.Daily_step + " WHERE id = " + pedometer.ID; dbcmd.CommandText = sql; dbcmd.ExecuteNonQuery(); Debug.Log("all columns on pedometer table updated"); CloseConnection(); }
/// <summary> /// The entry point of a background task. /// </summary> /// <param name="taskInstance">The current background task instance.</param> public void Run(IBackgroundTaskInstance taskInstance) { // Associate a cancellation handler with the background task. // Even though this task isn't performing much work, it can still be cancelled. taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // Read the pedometer reports from the trigger SensorDataThresholdTriggerDetails triggerDetails = taskInstance.TriggerDetails as SensorDataThresholdTriggerDetails; // Ensure that this trigger is of Pedometer type if (SensorType.Pedometer == triggerDetails.SensorType) { var nThFromLast = 1; var reports = Pedometer.GetReadingsFromTriggerDetails(triggerDetails); var settings = ApplicationData.Current.LocalSettings; var lastReading = reports[reports.Count - nThFromLast]; var knownTimestamp = lastReading.Timestamp; settings.Values["ReportCount"] = reports.Count.ToString(); settings.Values["LastTimestamp"] = lastReading.Timestamp; // insert this step kind count settings.Values[lastReading.StepKind.ToString()] = lastReading.CumulativeSteps.ToString(); // All reports that have the same timestamp correspond to step counts // of different step kinds supported by the sensor - Parse each one of // them and save in the application data while (nThFromLast < reports.Count) { // get the next reading from the last nThFromLast++; lastReading = reports[reports.Count - nThFromLast]; if (knownTimestamp.UtcTicks == lastReading.Timestamp.UtcTicks) { // captured at the same time indicates that this step-kind data belongs to the same sample // insert this step kind count settings.Values[lastReading.StepKind.ToString()] = lastReading.CumulativeSteps.ToString(); } else { break; } } settings.Values["TaskStatus"] = "Completed at " + DateTime.Now.ToString("u"); } // No deferral is held on taskInstance because we are returning immediately. }
public PedometerEvents(Pedometer This) { this.This = This; }