/// <summary>
        /// If not currently connected to the Band, create a connection.
        /// If already connected, then do nothing.
        ///
        /// Note that we block the thread waiting for async calls to complete, to
        /// ensure all processing related to the event is completed before OnRequestReceive returns.
        /// </summary>
        private void ConnectBand()
        {
            if (this.bandClient == null)
            {
                // Note that we specify isBackground = true here to avoid conflicting with any foreground app connection to the Band
                Task <IBandInfo[]> getBands = BandClientManager.Instance.GetBandsAsync(isBackground: true);
                getBands.Wait();
                IBandInfo[] pairedBands = getBands.Result;

                if (pairedBands.Length == 0)
                {
                    LogEvent("ERROR - No paired Band");
                }

                try
                {
                    Task <IBandClient> connect = BandClientManager.Instance.ConnectAsync(pairedBands[0]);
                    connect.Wait();
                    this.bandClient = connect.Result;
                }
                catch
                {
                    LogEvent("ERROR - Unable to connect to Band");
                }
            }
        }
Esempio n. 2
0
        async Task RemoveTileAsync(IBandClient client)
        {
            var bandTiles = await client.TileManager.GetTilesAsync();

            var bandTile = bandTiles.Single(b => b.TileId == TileGuidSetting);
            await client.TileManager.RemoveTileAsync(bandTile);
        }
Esempio n. 3
0
        public IAsyncOperation<bool> Connect(string name)
        {
            return AsyncInfo.Run<bool>((token) =>

                 Task.Run<bool>(async () =>
                 {
                     var paired = await BandClientManager.Instance.GetBandsAsync();
                     var band = paired.FirstOrDefault(x => x.Name == name);
                     if (band != null)
                     {
                         StatusChanged?.Invoke(this, "connecting");
                         this.connection = await BandClientManager.Instance.ConnectAsync(band);
                         StatusChanged?.Invoke(this, "connected");
                         connection.SensorManager.Accelerometer.ReadingChanged += (s, args) =>
                         {
                             if (AccelerometerChanged != null)
                             {
                                 AccelerometerChanged(this, new SensorReading()
                                 {
                                     X = args.SensorReading.AccelerationX,
                                     Y = args.SensorReading.AccelerationY,
                                     Z = args.SensorReading.AccelerationZ,
                                     Timestamp = args.SensorReading.Timestamp
                                 });
                             }
                         };
                         await connection.SensorManager.Accelerometer.StartReadingsAsync();
                     }
                     return true;
                 }));
        }
Esempio n. 4
0
        //on navigated too start trying to find band and get data
        private async void OnNavigatedTo(object sender, NavigationEventArgs e)
        {
            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    this.textBlock.Text = "This sample app requires a Microsoft Band paired to your phone. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                    return;
                    //add logic to open and pair on pair page here
                }

                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    // Subscribe to Accelerometer data.
                    bandClient.SensorManager.Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                    // Receive Accelerometer data for a while.
                    await Task.Delay(TimeSpan.FromMinutes(1));

                    await bandClient.SensorManager.Accelerometer.StopReadingsAsync();
                }
            }
            catch (Exception ex)
            {
                this.textBlock.Text = ex.ToString();
            }
        }
Esempio n. 5
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    textBox.Text = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                    return;
                }

                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    int samplesReceived = 0; // the number of Accelerometer samples received

                    // Subscribe to Accelerometer data.
                    bandClient.SensorManager.Accelerometer.ReadingChanged += (s, args) => { samplesReceived++; };
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                    // Receive Accelerometer data for a while, then stop the subscription.
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    await bandClient.SensorManager.Accelerometer.StopReadingsAsync();

                    textBox.Text = "Done. Accelerometer samples were received.";
                }
            }
            catch (Exception ex)
            {
                //this.viewModel.StatusMessage = ex.ToString();
            }
        }
Esempio n. 6
0
        private async void connectToBand()
        {
            try
            {
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

                AddBandSensor <IBandHeartRateReading>(bandClient.SensorManager.HeartRate,
                                                      "HeartRate",
                                                      "bpm",
                                                      HeartRate_ReadingChanged);

                AddBandSensor <IBandSkinTemperatureReading>(bandClient.SensorManager.SkinTemperature,
                                                            "SkinTemperature",
                                                            "C",
                                                            SkinTemperature_ReadingChanged);
            }
            catch (BandException ex)
            {
                // handle a Band connection exception
                var dialogbox = new MessageDialog("Error while connecting Band Sensors: " + ex.Message.ToString() + "\nRetrying...");
                await dialogbox.ShowAsync();

                connectToBand();
            }
        }
        public static IBandConnectionCallback RegisterConnectionCallback(this IBandClient client, Action <ConnectionState> callback)
        {
            var instance = new BandConnectionCallback(callback);

            client.RegisterConnectionCallback(instance);
            return(instance);
        }
Esempio n. 8
0
        public static async Task InitializeAsync()
        {
            if (bandClient != null)
            {
                return;
            }

            var bands = await BandClientManager.Instance.GetBandsAsync();

            bandInfo = bands.First();

            bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);

            var  uc          = bandClient.SensorManager.HeartRate.GetCurrentUserConsent();
            bool isConsented = false;

            if (uc == UserConsent.NotSpecified)
            {
                isConsented = await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
            }

            if (isConsented || uc == UserConsent.Granted)
            {
                bandClient.SensorManager.HeartRate.ReadingChanged += (obj, ev) =>
                {
                    int heartRate = ev.SensorReading.HeartRate;
                    Debug.WriteLine($"Heart rate = {heartRate}");
                    DispatchAsync(() => Messenger.Default.Send(
                                      new BandData(ConfigurationService.UserName, DateTime.Now, heartRate)));
                };
                await bandClient.SensorManager.HeartRate.StartReadingsAsync();
            }
        }
Esempio n. 9
0
        public async Task BandInit()
        {
            try
            {
                pairedBands = await BandClientManager.Instance.GetBandsAsync();

                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]); //connect

                // Check if the current user has given consent to the collection of heart rate sensor data.
                if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() !=
                    UserConsent.Granted)
                {
                    // We don't have user consent, so let's request it.
                    await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
                }
            }
            catch (BandException e1)
            {
                DialogBox.ShowOk("Error", "Not connected to Microsoft Band. Please verfiy connection and restart app.");
            }
            catch (IndexOutOfRangeException e1)
            {
                //TODO - No Band
            }
            catch (Exception e3)
            {
                DialogBox.ShowOk("Error", "Not connected to Microsoft Band. Please verfiy connection and restart app.");
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Called when the "Remove Tile" button is pressed in the UI.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void RemoveTileButton_Click(object sender, RoutedEventArgs e)
        {
            App.Current.StatusMessage = "Removing...\n";
            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    App.Current.StatusMessage = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                    return;
                }

                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    // Unsubscribe from background tile events
                    await bandClient.UnsubscribeFromBackgroundTileEventsAsync(TileConstants.TileGuid);

                    // Remove the Tile from the Band, if present
                    await bandClient.TileManager.RemoveTileAsync(TileConstants.TileGuid);

                    App.Current.StatusMessage = "Removed Tile";
                }
            }
            catch (Exception ex)
            {
                App.Current.StatusMessage = ex.ToString();
            }
        }
        //on navigated too start trying to find band and get data
        private async void OnNavigatedTo(object sender, NavigationEventArgs e)
        {
            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    //message box here
                    return;
                    //add logic to open and pair on pair page here
                }

                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    // Subscribe to Accelerometer data.
                    bandClient.SensorManager.Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                    // Receive Accelerometer data for a while.
                    //await Task.Delay(TimeSpan.FromMinutes(1));
                    //await bandClient.SensorManager.Accelerometer.StopReadingsAsync(); use to stop getting data
                }
            }
            catch (Exception ex)
            {
                //this.textBlock.Text = ex.ToString();
            }
        }
Esempio n. 12
0
        public async void StartBandAPI()
        {
            
            try
            {
                // Get the list of Microsoft Bands paired to the device.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
                if (pairedBands.Length < 1)
                {
                    string needBand = "Need to pair Band";
                    System.Diagnostics.Debug.WriteLine(needBand);
                    return;
                }

                // Connect to Microsoft Band.
                using (bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {

                    // Subscribe to Accelerometer data.
                    bandClient.SensorManager.Accelerometer.ReadingChanged += (s, args) =>
                    {
                        accel = Accelerometer_ReadingChanged(s, args);
                    };
                    System.Diagnostics.Debug.WriteLine("Retrieving accelerometer data");
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();
                    // Keep retrieving Accelerometer data for an hour
                    await Task.Delay(TimeSpan.FromHours(1));
                    await bandClient.SensorManager.Accelerometer.StopReadingsAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
        public async void ConnectWithBand()
        {
            pairedBands = await BandClientManager.Instance.GetBandsAsync();

            try
            {
                if (pairedBands.Length > 0)
                {
                    bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);
                    bandFound_value.Text = pairedBands[0].Name;

                    // Enable buttons
                    button_getHeartRate.IsEnabled = true;
                    button_vibrate.IsEnabled = true;
                    button_getVersions.IsEnabled = true;
                }
                else
                {
                    bandFound_value.Text = "None";
                }
            }
            catch (BandException ex)
            {
                bandFound_value.Text = ex.Message;
            }

        }
        /// <summary>
        /// Connect_Click responds to the user touch event from the button on the main page. It starts the
        /// finding of paired bands and adds event handlers as needed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Connect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    this.messageBlock.Text = "This app requires Microsoft Health Band paired to your phone";
                    return;
                }

                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    IEnumerable <TimeSpan> supportedIntervals = bandClient.SensorManager.Accelerometer.SupportedReportingIntervals;

                    bandClient.SensorManager.Accelerometer.ReportingInterval = supportedIntervals.Last();
                    bandClient.SensorManager.Accelerometer.ReadingChanged   += Accelerometer_ReadingChanged;
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                    await Task.Delay(TimeSpan.FromMinutes(1));

                    await bandClient.SensorManager.Accelerometer.StopReadingsAsync();
                }
            }
            catch (Exception ex)
            {
                this.messageBlock.Text = ex.ToString();
            }
        }
Esempio n. 15
0
        private async void ConnectToBand()
        {
            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

            //connect to the Band to get a new BandClient object
            try
            {
                using (bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    // check current sensor consent
                    if (bandClient.SensorManager.Accelerometer.GetCurrentUserConsent() != UserConsent.Granted)
                    {
                        // user hasn't consented, request consent
                        await bandClient.SensorManager.Accelerometer.RequestUserConsentAsync();
                    }
                }
            }
            catch (BandException ex)
            {
                // handle Band connection exception
            }

            // start the accelerometer sensor
            try
            {
                await bandClient.SensorManager.Accelerometer.StartReadingsAsync();
            }     
            catch(BandException ex)
            {
                // handle accelerometer exception
                throw ex;
            }
        }
Esempio n. 16
0
        //Reads the fitness data from the Band
        private async void GetHeartRate()
        {
            if (_bandClient != null)
            {
                return;
            }

            var bands = await BandClientManager.Instance.GetBandsAsync();

            _bandInfo = bands.First();

            _bandClient = await BandClientManager.Instance.ConnectAsync(_bandInfo);

            var  uc          = _bandClient.SensorManager.HeartRate.GetCurrentUserConsent();
            bool isConsented = false;

            if (uc == UserConsent.NotSpecified)
            {
                isConsented = await _bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
            }

            if (isConsented || uc == UserConsent.Granted)
            {
                _bandClient.SensorManager.HeartRate.ReadingChanged += async(obj, ev) =>
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        HeartRateDisplay.Text = ev.SensorReading.HeartRate.ToString();
                    });
                };
                await _bandClient.SensorManager.HeartRate.StartReadingsAsync();

                //Here we can call the NAV Service Layer REST API to pass the heart rate data
            }
        }
        private static async Task SetBackgroundAsync(IBandClient bandClient)
        {
            var backgroundImageUri = new Uri("ms-appx:///Assets/BandBackground.png");
            var bandImage = await backgroundImageUri.GetBandImageAsync();

            await bandClient.PersonalizationManager.SetMeTileImageAsync(bandImage);
        }
Esempio n. 18
0
        async Task CheckForPinnedBandTile()
        {
            bool result = false;

            if (currentBand == null)
            {
                tilePinned = false;
            }
            else
            {
                try
                {
                    bandClient = await BandClientManager.Instance.ConnectAsync(currentBand);

                    foreach (var tile in await bandClient.TileManager.GetTilesAsync())
                    {
                        if (tile.Name == bandTile.Name)
                        {
                            result = true;
                        }
                    }
                    bandClient.Dispose();
                }
                catch (Exception ex)
                {
                    ErrorBlock.Text = ex.Message;
                }
            }
            tilePinned = result;
        }
        public async Task<IBandClient> GetBandClientAsync()
        {
            if (_bandClient != null)
            {
                // test to see if the band client is still good by looking at the version number
                try
                {
                    await _bandClient.GetFirmwareVersionAsync();
                    return _bandClient;
                }
                catch (Exception)
                {
                    _bandClient.TileManager.TileButtonPressed -= TileManagerOnTileButtonPressed;
                    _bandClient = null;
                }
            }

            // TODO: what if we get a band exception here?
            var pairedBands = await BandClientManager.Instance.GetBandsAsync();
            if (pairedBands.Length < 1)
            {
                throw new BandNotPairedException();
            }

            _bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

            _bandClient.TileManager.TileButtonPressed += TileManagerOnTileButtonPressed;

            return _bandClient;
        }
Esempio n. 20
0
        /// <summary>
        /// Gets the band version
        /// </summary>
        public async void GetBandVersion()
        {
            try
            {
                IBandInfo pairedBand = await GetPairedBand();

                if (pairedBand == null)
                {
                    // We don't have a band.
                    return;
                }

                // Try to connect to the band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBand))
                {
                    string versionString = await bandClient.GetHardwareVersionAsync();

                    int version = int.Parse(versionString);
                    BandVersion = version >= 20 ? BandVersions.V2 : BandVersions.V1;
                }
            }
            catch (Exception e)
            {
                m_baconMan.MessageMan.DebugDia("Failed to get band version.", e);
            }
        }
Esempio n. 21
0
        private async void OnLoaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (_bandClient != null)
                return;

            var bands = await BandClientManager.Instance.GetBandsAsync();
            _bandInfo = bands.First();

            _bandClient = await BandClientManager.Instance.ConnectAsync(_bandInfo);

            var uc = _bandClient.SensorManager.HeartRate.GetCurrentUserConsent();
            bool isConsented = false;
            if (uc == UserConsent.NotSpecified)
            {
                isConsented = await _bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
            }

            if (isConsented || uc == UserConsent.Granted)
            {
                _bandClient.SensorManager.HeartRate.ReadingChanged += async (obj, ev) =>
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                        {
                                            HeartRateDisplay.Text = ev.SensorReading.HeartRate.ToString();
                                        });
                };
                await _bandClient.SensorManager.HeartRate.StartReadingsAsync();
            }
        }
Esempio n. 22
0
        public static async Task Set_Image(object path)
        {
            BandClient = await Connect_Band(await Get_Band());

            if (BandClient == null)
            {
                return;
            }

            using (BandClient)
            {
                if (path is WriteableBitmap)
                {
                    WriteableBitmap wb = (WriteableBitmap)path;
                    BandImage       bi = wb.ToBandImage();
                    await BandClient.PersonalizationManager.SetMeTileImageAsync(bi);

                    //set
                }
                else if (path is string)
                {
                    WriteableBitmap writeableBitmap = await Loader.LoadImage((string)path);

                    BandImage bandImage = writeableBitmap.ToBandImage();
                    await BandClient.PersonalizationManager.SetMeTileImageAsync(bandImage);
                }
            }
        }
Esempio n. 23
0
        private void ConnectBand()
        {
            if (this.bandClient == null)
            {
                try
                {
                    // Note that we specify isBackground = true here to avoid conflicting with any foreground app connection to the Band
                    Task <IBandInfo[]> getBands = BandClientManager.Instance.GetBandsAsync(isBackground: true);
                    getBands.Wait();
                    IBandInfo[] pairedBands = getBands.Result;

                    if (pairedBands.Length == 0)
                    {
                        System.Diagnostics.Debug.WriteLine("CODECRIB - No Paired Band Found!");
                        //LogEvent("ERROR - No paired Band");
                    }


                    Task <IBandClient> connect = BandClientManager.Instance.ConnectAsync(pairedBands[0]);
                    connect.Wait();
                    this.bandClient = connect.Result;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("CODECRIB - " + ex.ToString());
                    //LogEvent("ERROR - Unable to connect to Band");
                }
            }
        }
Esempio n. 24
0
        public IAsyncOperation <bool> Connect(string name)
        {
            return(AsyncInfo.Run <bool>((token) =>

                                        Task.Run <bool>(async() =>
            {
                var paired = await BandClientManager.Instance.GetBandsAsync();
                var band = paired.FirstOrDefault(x => x.Name == name);
                if (band != null)
                {
                    StatusChanged?.Invoke(this, "connecting");
                    this.connection = await BandClientManager.Instance.ConnectAsync(band);
                    StatusChanged?.Invoke(this, "connected");
                    connection.SensorManager.Accelerometer.ReadingChanged += (s, args) =>
                    {
                        if (AccelerometerChanged != null)
                        {
                            AccelerometerChanged(this, new SensorReading()
                            {
                                X = args.SensorReading.AccelerationX,
                                Y = args.SensorReading.AccelerationY,
                                Z = args.SensorReading.AccelerationZ,
                                Timestamp = args.SensorReading.Timestamp
                            });
                        }
                    };
                    await connection.SensorManager.Accelerometer.StartReadingsAsync();
                }
                return true;
            })));
        }
Esempio n. 25
0
        public async Task <bool> StartListening()
        {
            var pairedBands = await BandClientManager.Instance.GetBandsAsync();

            if (pairedBands.Any())
            {
                var band = pairedBands.FirstOrDefault();
                if (band != null)
                {
                    bandName   = band.Name;
                    bandClient = await BandClientManager.Instance.ConnectAsync(band);

                    var consent = await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();

                    if (consent)
                    {
                        var sensor = bandClient.SensorManager.HeartRate;
                        sensor.ReadingChanged += SensorReadingChanged;
                        await sensor.StartReadingsAsync();
                    }
                    return(consent);
                }
            }
            return(false);
        }
Esempio n. 26
0
        async Task <BandTile> CreateTileAsync(IBandClient client)
        {
            BandTile bandTile = null;

            var tileSpace = await client.TileManager.GetRemainingTileCapacityAsync();

            if (tileSpace > 0)
            {
                var smallIcon = await TileImageUtility.MakeTileIconFromFileAsync(
                    new Uri("ms-appx:///Assets/bandSmall.png"), 24);

                var largeIcon = await TileImageUtility.MakeTileIconFromFileAsync(
                    new Uri("ms-appx:///Assets/bandLarge.png"), 48);

                TheTask.TileIdentifier = Guid.NewGuid();

                bandTile = new BandTile(TheTask.TileIdentifier)
                {
                    Name      = "Beacon",
                    TileIcon  = largeIcon,
                    SmallIcon = smallIcon
                };

                var added = await client.TileManager.AddTileAsync(bandTile);
            }
            return(bandTile);
        }
        private async Task <bool> Band_Connect()
        {
            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    Debug.WriteLine("Microsoft Band not found. Verify your band is paired to this device and has the latest firmware.");
                    return(false);
                }

                // Connect to Microsoft Band.
                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

                Debug.WriteLine("Band Connected.");

                // Subscribe to Accelerometer data.
                //var intervals = bandClient.SensorManager.Accelerometer.SupportedReportingIntervals;
                bandClient.SensorManager.Accelerometer.ReportingInterval = bandClient.SensorManager.Accelerometer.SupportedReportingIntervals.Last();
                bandClient.SensorManager.Accelerometer.ReadingChanged   += BandAccelerometer_ReadingChanged;
                await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                Debug.WriteLine("Accelerometer samples started.");
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
        public async void ConnectWithBand()
        {
            pairedBands = await BandClientManager.Instance.GetBandsAsync();

            try
            {
                if (pairedBands.Length > 0)
                {
                    bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

                    bandFound_value.Text = pairedBands[0].Name;

                    // Enable buttons
                    button_getHeartRate.IsEnabled = true;
                    button_vibrate.IsEnabled      = true;
                    button_getVersions.IsEnabled  = true;
                }
                else
                {
                    bandFound_value.Text = "None";
                }
            }
            catch (BandException ex)
            {
                bandFound_value.Text = ex.Message;
            }
        }
Esempio n. 29
0
        public static async Task <int> Get_BandGeneration()
        {
            int hwVersion;

            BandClient = await Connect_Band(await Get_Band());

            if (BandClient == null)
            {
                return(-1);
            }

            using (BandClient)
            {
                bool res = int.TryParse(await BandClient.GetHardwareVersionAsync(), out hwVersion);

                if (res)
                {
                    if (hwVersion <= 19)
                    {
                        return(1);
                    }
                    else if (hwVersion >= 20)
                    {
                        return(2);
                    }
                }
            }



            return(0);
        }
Esempio n. 30
0
        //////////////////////////////////////////////////////////////


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (bandClient != null)
            {
                bandClient.Dispose();
            }
            bandClient = null;
        }
 /// <summary>
 /// If currently connected to the Band, then disconnect.
 /// </summary>
 private void DisconnectBand()
 {
     if (bandClient != null)
     {
         bandClient.Dispose();
         bandClient = null;
     }
 }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            this.viewModel.StatusMessage = "Running ...";

            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
                if (pairedBands.Length < 1)
                {
                    this.viewModel.StatusMessage = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                    return;
                }

                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    // Create a Tile.
                    // WARNING! This tile guid is only an example. Please do not copy it to your test application;
                    // always create a unique guid for each application.
                    // If one application installs its tile, a second application using the same guid will fail to install
                    // its tile due to a guid conflict. In the event of such a failure, the text of the exception will not
                    // report that the tile with the same guid already exists on the band.
                    // There might be other unexpected behavior.
                    Guid myTileId = new Guid("06CF1D20-81F5-4200-AA8B-C694BAFDA0A8");
                    BandTile myTile = new BandTile(myTileId)
                    {
                        Name = "My Tile",
                        TileIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconLarge.png"),
                        SmallIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconSmall.png")
                    };

                    // Remove the Tile from the Band, if present. An application won't need to do this everytime it runs. 
                    // But in case you modify this sample code and run it again, let's make sure to start fresh.
                    await bandClient.TileManager.RemoveTileAsync(myTileId);
                    
                    // Check if there is space for your tile on the band before adding it.
                    if (await bandClient.TileManager.GetRemainingTileCapacityAsync() > 0)
                    {
                        // Create the Tile on the Band.
                        await bandClient.TileManager.AddTileAsync(myTile);

                        // Send a notification.
                        await bandClient.NotificationManager.SendMessageAsync(myTileId, "Microsoft Band", "Hello World !", DateTimeOffset.Now, MessageFlags.ShowDialog);

                        this.viewModel.StatusMessage = "Done. Check the Tile on your Band (it's the last Tile).";
                    }
                    else
                    {
                        this.viewModel.StatusMessage = "No space on the band for your tile, remove a tile and try again.";
                    }
                }
            }
            catch (Exception ex)
            {
                this.viewModel.StatusMessage = ex.ToString();
            }
        }
        private async void OnLoaded()
        {
            pairedBands = await BandClientManager.Instance.GetBandsAsync();

            bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

            bandClient.SensorManager.Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
            await bandClient.SensorManager.Accelerometer.StartReadingsAsync();
        }
Esempio n. 34
0
        private async void SetGetTheme_Click(object sender, RoutedEventArgs args)
        {
            IBandInfo[] pairedBands;
            IBandClient client = null;

            this.viewModel.StatusMessage = "Running Theme demo ...";

            // Enumerate Bands that are paired to this device.
            pairedBands = await BandClientManager.Instance.GetBandsAsync();

            if (pairedBands.Length == 0)
            {
                this.viewModel.StatusMessage = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                return;
            }

            try
            {
                // Connect to the first Band in the enumeration.
                client = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);
            }
            catch (Exception e)
            {
                this.viewModel.StatusMessage = "Failed to connect to a Band.\r\n" + e.Message;
                return;
            }

            using (client)
            {
                // Set up a custom theme.
                BandTheme theme = new BandTheme
                {
                    Base          = Colors.BurlyWood.ToBandColor(),
                    Highlight     = Colors.BlanchedAlmond.ToBandColor(),
                    Lowlight      = Colors.Azure.ToBandColor(),
                    SecondaryText = Colors.DarkGreen.ToBandColor(),
                    HighContrast  = Colors.LightGreen.ToBandColor(),
                    Muted         = Colors.Purple.ToBandColor()
                };

                // Set the theme on the band.
                await client.PersonalizationManager.SetThemeAsync(theme);

                // Get the theme from the band.
                theme = await client.PersonalizationManager.GetThemeAsync();

                // Display the theme on screen.
                ThemeColor_Base.Background          = new SolidColorBrush(theme.Base.ToColor());
                ThemeColor_Highlight.Background     = new SolidColorBrush(theme.Highlight.ToColor());
                ThemeColor_Lowlight.Background      = new SolidColorBrush(theme.Lowlight.ToColor());
                ThemeColor_SecondaryText.Background = new SolidColorBrush(theme.SecondaryText.ToColor());
                ThemeColor_HighContrast.Background  = new SolidColorBrush(theme.HighContrast.ToColor());
                ThemeColor_Muted.Background         = new SolidColorBrush(theme.Muted.ToColor());
            }

            this.viewModel.StatusMessage = "Done.";
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            this.viewModel.StatusMessage = "Running ...";

            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

                if (pairedBands.Length < 1)
                {
                    this.viewModel.StatusMessage = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                    return;
                }

                // Connect to Microsoft Band.
                using (IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    bool heartRateConsentGranted;

                    // Check whether the user has granted access to the HeartRate sensor.
                    if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() == UserConsent.Granted)
                    {
                        heartRateConsentGranted = true;
                    }
                    else
                    {
                        heartRateConsentGranted = await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
                    }

                    if (!heartRateConsentGranted)
                    {
                        this.viewModel.StatusMessage = "Access to the heart rate sensor is denied.";
                    }
                    else
                    {
                        int samplesReceived = 0; // the number of HeartRate samples received

                        // Subscribe to HeartRate data.
                        bandClient.SensorManager.HeartRate.ReadingChanged += (s, args) => { samplesReceived++; };
                        await bandClient.SensorManager.HeartRate.StartReadingsAsync();

                        // Receive HeartRate data for a while, then stop the subscription.
                        await Task.Delay(TimeSpan.FromSeconds(5));

                        await bandClient.SensorManager.HeartRate.StopReadingsAsync();

                        this.viewModel.StatusMessage = string.Format("Done. {0} HeartRate samples were received.", samplesReceived);
                    }
                }
            }
            catch (Exception ex)
            {
                this.viewModel.StatusMessage = ex.ToString();
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Making the connection with Band
        /// </summary>
        /// <returns></returns>
        private async Task ConnectToBand()
        {
            var pairedBands = await BandClientManager.Instance.GetBandsAsync();

            if (pairedBands.Any())
            {
                var band = pairedBands.First();
                bandClient = await BandClientManager.Instance.ConnectAsync(band);
            }
        }
        public void Dispose()
        {
            if (_bandClient != null)
            {
                _bandClient.Dispose();
                _bandClient = null;
            }

            _bandInfo = null;
        }
        public void Dispose()
        {
            if( _bandClient != null )
            {

                _bandClient.Dispose();
                _bandClient = null;
            }

            _bandInfo = null;
        }
Esempio n. 39
0
 public async Task<string> RetrieveInfo(IBandInfo bandInfo, IBandClient client)
 {
     Name = bandInfo.Name;
     ConnectionType = bandInfo.ConnectionType;
     Firmware = await client.GetFirmwareVersionAsync();
     Hardware = await client.GetHardwareVersionAsync();
     return string.Format(" Connected to: {0}" +
                          " \n Connection type : {1}" +
                          " \n Firmware : {2} \n Hardware : {3}",
             Name, ConnectionType, Firmware, Hardware);
 }
Esempio n. 40
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                var pairedBands = await BandClientManager.Instance.GetBandsAsync();
                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

                await this.CreateTilesAsync();
            }
            catch { }

            base.OnNavigatedTo(e);
        }
        private static async Task SetThemeAsync(IBandClient bandClient)
        {
            var bandTheme = new BandTheme()
            {
                Base = new BandColor(0x08, 0x22, 0x5B),
                Highlight = new BandColor(0x0D, 0x36, 0x7F),
                Lowlight = new BandColor(0x06, 0x1C, 0x3E),
                Muted = Colors.Gray.ToBandColor(),
                SecondaryText = Colors.Black.ToBandColor()
            };

            await bandClient.PersonalizationManager.SetThemeAsync(bandTheme);
        }
        public async Task CreateBandTileIfNotExistsAsync(IBandClient bandClient)
        {
            if (!await ExistsOnBandAsync(bandClient))
            {
                var bandTile = await CreateBandTilelAsync();
                await bandClient.TileManager.AddTileAsync(bandTile);

                var pageData = GetInitialPageData();
                if (pageData != null)
                {
                    await bandClient.TileManager.SetPagesAsync(Id, pageData); 
                }
            }
        }
Esempio n. 43
0
        public async void Connect()
        {
            if (_bandClient != null)
                return;

            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
            if (pairedBands.Length == 0)
                return;

            _bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

            _bandClient.SensorManager.Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
            await _bandClient.SensorManager.Accelerometer.StartReadingsAsync();
        }
        public DataViewModelBase(string name, IBandClient bandClient)
        {
            _bandClient = bandClient;

            _name = name;

            _startCmd = new Lazy<ICommand>(() =>
            {
                return new AsyncDelegateCommand<object>(Start, CanStart);
            });
            _stopCmd = new Lazy<ICommand>(() =>
            {
                return new AsyncDelegateCommand<object>(Stop, CanStop);
            });
        }
        public BandDataViewModel(string name, IBandClient bandClient)
        {
            _bandClient = bandClient;

            _name = name;
            _dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
            _startCmd = new Lazy<ICommand>(() =>
            {
                return new AsyncDelegateCommand<object>(Start, CanStart);
            });
            _stopCmd = new Lazy<ICommand>(() =>
            {
                return new AsyncDelegateCommand<object>(Stop, CanStop);
            });
        }
        async void doWork()
        {
            if (bandClient == null)
            {
                bool exception = false;
                try
                {
                    IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
                    if (pairedBands.Length < 1)
                    {
       
                        lblBand.Text = "Status: band out of range";
                        lblBand.Foreground = new SolidColorBrush(Colors.Red);
                        bandClient = null;
                        if (isTestMode)
                        {
                            startTestMode();
                        }
                        return;
                    }
                    lblBand.Text = "connecting";
                    lblBand.Foreground = new SolidColorBrush(Colors.White);

                    // Connect to Microsoft Band.
                    bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);
                }
                catch (Exception ex)
                {
                    exception = true;
                    lblBand.Text = "Status: out of range";
                    lblBand.Foreground = new SolidColorBrush(Colors.Red);
                    return;
                }
            }

            #region BandContact
            //bandClient.SensorManager.Contact.SupportedReportingIntervals.GetEnumerator();
            bandClient.SensorManager.Contact.ReadingChanged += Contact_ReadingChanged;

            if (bandClient.SensorManager.Contact.GetCurrentUserConsent() != UserConsent.Granted)
            {
                // user has not consented, request it
                await bandClient.SensorManager.Contact.RequestUserConsentAsync();
            }

            await bandClient.SensorManager.Contact.StartReadingsAsync();
            #endregion
        }
Esempio n. 47
0
    public void StartBandAPI()
#endif
    {
#if REAL_APP
        UnityEngine.Debug.Log("Sarting App");
        try
        {
            
            // Get the list of Microsoft Bands paired to the device.
            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
            
            if (pairedBands.Length < 1)
            {
                string needBand = "Need to pair Band";
                System.Diagnostics.Debug.WriteLine(needBand);
                UnityEngine.Debug.Log(needBand);
                return;
            }
            UnityEngine.Debug.Log("1");
            // Connect to Microsoft Band.
            await Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
            {
                using (bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
                {
                    UnityEngine.Debug.Log("2");
                    UnityEngine.Debug.Log("---Connecting to band: " + pairedBands[0].ToString());
                    // Subscribe to Accelerometer data.
                    bandClient.SensorManager.Accelerometer.ReadingChanged += (s, args) =>
                    {
                        accel = Accelerometer_ReadingChanged(s, args);
                    };
                    System.Diagnostics.Debug.WriteLine("Retrieving accelerometer data");
                    UnityEngine.Debug.Log("Retrieving accelerometer data");
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();
                    // Keep retrieving Accelerometer data for an hour
                    await Task.Delay(TimeSpan.FromHours(1));
                    await bandClient.SensorManager.Accelerometer.StopReadingsAsync();
                }
            });

        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
            UnityEngine.Debug.Log(ex.ToString());
        }
#endif
    }
 private bool TryClearExistingBand()
 {
   try
   {
     if (_bandClient != null)
     {
       _bandClient.Dispose();
       _bandClient = null;
     }
   }
   catch (Exception)
   {
     return false;
   }
   return true;
 }
Esempio n. 49
0
        private async void start_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.viewModel.StatusMessage = "Starting...";

                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

                if (pairedBands.Length < 1)
                {
                    this.viewModel.StatusMessage = "Connect your band and click the start button again.";
                    return;
                }

                bool heartRateConsentGranted;

                // Check whether the user has granted access to the HeartRate sensor.
                if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() == UserConsent.Granted)
                {
                    heartRateConsentGranted = true;
                }
                else
                {
                    heartRateConsentGranted = await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
                }

                if (!heartRateConsentGranted)
                {
                    this.viewModel.StatusMessage = "Access to the heart rate sensor is denied.";
                }
                else
                {
                    // Subscribe to HeartRate data.
                    bandClient.SensorManager.HeartRate.ReadingChanged += (s, args) => 
                    {
                        this.viewModel.StatusMessage = args.SensorReading.HeartRate.ToString();
                    };
                    await bandClient.SensorManager.HeartRate.StartReadingsAsync();
                }
            }
            catch (Exception ex)
            {
                this.viewModel.StatusMessage = ex.ToString();
            }
        }
Esempio n. 50
0
	    private async void ConnectBand()
	    {
	        var bandInitializationFailed = false;
	        var pairedBands = await BandClientManager.Instance.GetBandsAsync();
	        try
	        {
	            for (int index = 0; index < pairedBands.Length; index++)
	            {
                    if (index == 0)
                    {
                        m_Player1BandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[index]);
                        m_Player1BandClient.SensorManager.Accelerometer.ReportingInterval = TimeSpan.FromMilliseconds(16.0);
                        m_Player1Name = pairedBands[index].Name;
                        UpdatePlayer1Name();

                        m_Player1BandClient.SensorManager.Accelerometer.ReadingChanged += OnAccelerometerPlayer1OnReadingChanged;

                        await m_Player1BandClient.SensorManager.Accelerometer.StartReadingsAsync();   
                        
                    }
                    if (index == 1)
                    {
                        m_Player2BandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[index]);
                        m_Player2BandClient.SensorManager.Accelerometer.ReportingInterval = TimeSpan.FromMilliseconds(16.0);
                        m_Player2Name = pairedBands[index].Name;
                        UpdatePlayer2Name();

                        m_Player2BandClient.SensorManager.Accelerometer.ReadingChanged += OnAccelerometerPlayer2OnReadingChanged;

                        await m_Player2BandClient.SensorManager.Accelerometer.StartReadingsAsync();
                    }
	            }
	            
	        }
	        catch (Exception ex)
	        {
	            Debug.WriteLine(ex.Message);
	            bandInitializationFailed = true;
	        }

	        if (bandInitializationFailed)
	        {
                await DisconnectBands();
	        }
	    }
Esempio n. 51
0
        public async void ConnectWithBand()
        {
            pairedBands = await BandClientManager.Instance.GetBandsAsync();

            bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

            if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
            {
                await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
            }

            currentBand = new BandInformation();
            await currentBand.RetrieveInfo(pairedBands[0], bandClient);

            bandClient.SensorManager.HeartRate.ReadingChanged += HeartRateReceived;

            await bandClient.SensorManager.HeartRate.StartReadingsAsync();
        }
Esempio n. 52
0
        public async Task<IBandClient> ConnectBandAsync(IBandInfo band)
        {
            this.bandClient?.Dispose();
            this.bandClient = null;

            try
            {
                this.bandClient = await BandClientManager.Instance.ConnectAsync(band);

                Messenger.Default.Send(new BandConnectedStateChanged());
            }
            catch (BandException e)
            {
                Debug.WriteLine(e.ToString());
            }

            return this.bandClient;
        }
Esempio n. 53
0
        private async Task<bool> CreateTile(IBandClient bandClient)
        {
            try
            {
                int tileCapacity = await bandClient.TileManager.GetRemainingTileCapacityAsync();

                if (tileCapacity > 0)
                {
                    BandTile tile = new BandTile(myTileId)
                    {
                        Name = "Ahorcado",
                        TileIcon = await LoadIcon(String.Format("{0}Logo46x46{1}", path, ext)),
                        SmallIcon = await LoadIcon(String.Format("{0}Logo24x24{1}", path, ext))
                    };

                    foreach (string code in codes)
                        tile.AdditionalIcons.Add(await LoadIcon(String.Format("{0}{1}{2}", path, code, ext)));

                    if (await bandClient.TileManager.AddTileAsync(tile))
                    {
                        CreateLayout(tile);
                        await bandClient.NotificationManager.SendMessageAsync(myTileId, "Ahorcado", "Tile was just created!",
                            DateTimeOffset.Now, MessageFlags.None);

                        return true;
                    }
                    else
                    {
                        await ShowDialogAsync("Error", "Tile not created");
                        return false;
                    }
                }
                else
                {
                    await ShowDialogAsync("Error", "No space on Band for tile");
                    return false;
                }
            }
            catch (BandException ex)
            {
                ShowDialogAsync("Error", "Error creating tile. Exception found: " + ex.Message);
                return false;
            }
        }
        private async void button_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                // Get the list of Microsoft Bands paired to the phone.
                IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
                if (pairedBands.Length < 1)
                {
                    textBox.Text = "This sample app requires a Microsoft Band paired to your device. Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.";
                    return;
                }

                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);
                
                    //while (true)
                    //{
                        int samplesReceived = 0; // the number of Accelerometer samples received

                    // Subscribe to Accelerometer data.
                    //bandClient.SensorManager.Accelerometer.ReadingChanged += (s, args) => { samplesReceived++; };
                    bandClient.SensorManager.Accelerometer.ReadingChanged += async (s, args) => {
                        await textBox.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            textBox.Text = "Accelerator = " + args.SensorReading.AccelerationX;

                        });
                    };
                    await bandClient.SensorManager.Accelerometer.StartReadingsAsync();

                    //    // Receive Accelerometer data for a while, then stop the subscription.
                    //    await Task.Delay(TimeSpan.FromSeconds(5));
                    //    await bandClient.SensorManager.Accelerometer.StopReadingsAsync();
                    //    string message = "Accelerator =" + samplesReceived;
                    //    textBox.Text = message;
                    //}
                
            }
            catch (Exception ex)
            {
                textBox.Text = ex.ToString();
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            DataTransferManager.GetForCurrentView().DataRequested += OnShareDataRequested;
            bestSteps = IsolatedStorageHelper.GetObject<double>("bestSteps");

            pairedBands = await BandClientManager.Instance.GetBandsAsync();
            if (pairedBands.Length < 1)
            {
                return;
            }
            _bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);


            _bandClient.SensorManager.Pedometer.ReadingChanged += PedometerOnReadingChanged;
            await _bandClient.SensorManager.Pedometer.StartReadingsAsync();

            MessageDialog msg = new MessageDialog("Wear your Microsoft Band and walk to count your steps", "Instruction");
            await msg.ShowAsync();
        }
Esempio n. 56
0
        private async void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            var bands = await BandClientManager.Instance.GetBandsAsync();
            if (bands.Length == 0)
            {

                Speak("Warning. Patient not found.");
                return;
            }
            bandinfo = bands[0];
            client = await BandClientManager.Instance.ConnectAsync(bandinfo);
            //client.SensorManager.HeartRate.ReadingChanged += BandInitialized;
            client.SensorManager.HeartRate.ReadingChanged += HeartRate_ReadingChanged;
            client.SensorManager.SkinTemperature.ReadingChanged += SkinTemperature_ReadingChanged;
            if (client.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
                await client.SensorManager.HeartRate.RequestUserConsentAsync();
            await client.SensorManager.HeartRate.StartReadingsAsync();
            await client.SensorManager.SkinTemperature.StartReadingsAsync();
        }
 private async Task<IBandClient> GetBandClient(bool forceFreshClient = false)
 {
   if (_bandClient == null || forceFreshClient)
   {
     TryClearExistingBand();
     _bandClient = await GetNewBandClient();
   }
   try
   {
     var t = _bandClient.NotificationManager;
     Debug.WriteLine($"Notifcation manager succesfull accessed {t}");
   }
   catch (Exception)
   {
     TryClearExistingBand();
     _bandClient = await GetNewBandClient();
   }
   return _bandClient;
 }
Esempio n. 58
0
        public async void Connect()
        {
            if (_bandClient != null)
                return;

            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
            if (pairedBands.Length == 0)
            {
                return;
            }

            Debug.WriteLine("Connecting");
            _bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

            _bandClient.SensorManager.Gyroscope.ReadingChanged += Gyroscope_ReadingChanged;
            await _bandClient.SensorManager.Gyroscope.StartReadingsAsync();

            Debug.WriteLine("Connected");
        }
Esempio n. 59
0
        async public void PairBand()
        {
            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

            try
            {
                bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);

                // do work after successful connect
                try
                {
                    // do work with firmware & hardware versions
                    connecting.Text = "Connected";
                    check.Text = " ✔";

                    IsPinned();

                    var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                    if (localSettings.Values.ContainsKey("BOLGuid"))
                    {
                        tileGuid = (Guid)localSettings.Values["BOLGuid"];
                    }
                }
                catch (BandException ex)
                {
                    // handle any BandExceptions
                }
            }
            catch (BandException ex)
            {
                // handle a Band connection exception
            }

            // Subscribe to events
            bandClient.TileManager.TileOpened += EventHandler_TileOpened;
            //bandClient.TileManager.TileClosed += EventHandler_TileClosed;
            //bandClient.TileManager.TileButtonPushed += EventHandler_TileButtonPushed;  
            // Start listening for events
            await bandClient.TileManager.StartReadingsAsync();
        }
        // Connects to the band
        public async Task<bool> ConnectAsync()
        {
            if( IsConnected )
            {
                return false;
            }

            // Find all Bands
            IBandInfo[ ] allBands = await BandClientManager.Instance.GetBandsAsync();
            if( !allBands.Any() )
            {
                throw new NoBandFoundException();
            }

            // Use first Band
            _bandInfo = allBands.First();

            // Connect to first Band
            _bandClient = await BandClientManager.Instance.ConnectAsync( _bandInfo );

            // Get User Consent of current band
            UserConsent uc = _bandClient.SensorManager.HeartRate.GetCurrentUserConsent();
            bool isConsented = false;
            if( uc == UserConsent.NotSpecified )
            {
                isConsented = await _bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
            }

            // Check if really consented and check if permissions are granted
            if( isConsented || uc == UserConsent.Granted )
            {
                // provide new rate via event
                _bandClient.SensorManager.HeartRate.ReadingChanged += FireHeartRate;

                // Start reading
                return ( await _bandClient.SensorManager.HeartRate.StartReadingsAsync() );
            }

            return ( IsConnected = false );
        }