コード例 #1
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();
            }
        }
コード例 #2
0
        ///SingleBinding.ReloadMainPage

        public async Task Load_BandData()
        {
            IBandInfo Band_Found = await BandHandler.Get_Band();

            if (Band_Found == null)
            {
                Disable_BandFeatures();
                return;
            }



            #region Setup BandData

            if (App._CustomBandThemes == null || App._CustomBandThemes.Count == 0)
            {
                OneMomentDetails.Text  = Localization.Get_Text(Localization.Tag.Band_, "GetDetails1");
                App.OverlayApp.Overlay = true;


                #region Gets and sets the meTile
                App._MeImageTile = await Core.BandHandler.Get_Image(); /// Gets the band metile form the band

                BandPreview.SetImage(App._MeImageTile);                /// Sets the image of the previewControl
                PreviewImage.Source = App._MeImageTile;                /// Sets the image of the tapp to change control
                #endregion
                #region Gets and sets the Theme
                BandTheme tempBandTheme = await Core.BandHandler.Get_Theme(); /// Gets the current theme on the band

                BandPreview.SetTheme(tempBandTheme);                          /// Sets the preview theme as the current
                App._CurrentBandTheme  = tempBandTheme;                       /// Sets the retrieved teme as the current
                App._SelectedBandTheme = 0;                                   /// Sets the selected as 0 since the control now contains a theme. If this is not set the applicaiton will not work correctly. Possible issue of .20 -> .25 issue. Caused rewrite of this task
                App._CustomBandThemes  = await ReturnProfiles();              /// Gets the custom profiles created by user from storage.

                #endregion

                App.BandGeneration = await BandHandler.Get_BandGeneration(); /// Gets the current band generation possible values -1, 1, 2

                App.OverlayApp.Overlay = false;
            }
            else
            {
                App._CurrentBandTheme = App._CustomBandThemes[App._SelectedBandTheme].Theme;
                BandPreview.SetImage(App._MeImageTile);
                BandPreview.SetTheme(App._CurrentBandTheme);

                PreviewImage.Source = App._MeImageTile;

                Profile_Selector.SelectedIndex = App._SelectedBandTheme;

                App.ViewModel.Items.ElementAt(App._SelectedBandTheme).LineNine = "#" + await Parse._ColorToHEX(App._CurrentBandTheme.Base.ToColor());

                App.ViewModel.Items.ElementAt(App._SelectedBandTheme).LineTen = "#" + await Parse._ColorToHEX(App._CurrentBandTheme.HighContrast.ToColor());
            }

            FillBase.Fill         = new SolidColorBrush(App._CurrentBandTheme.Base.ToColor());
            FillHighContrast.Fill = new SolidColorBrush(App._CurrentBandTheme.HighContrast.ToColor());

            #endregion
        }
コード例 #3
0
        protected async override Task<object> Start(object arg)
        {
            var band = arg as Band;
            _bandInfo = band.Info;
            _bandClient = band.Client;

            var consent = _bandClient.SensorManager.Distance.GetCurrentUserConsent();
            switch (consent)
            {
                case UserConsent.NotSpecified:
                    await _bandClient.SensorManager.Distance.RequestUserConsentAsync();
                    break;
                case UserConsent.Declined:
                    return false;
            }

            IsBusy = true;
            ((AsyncDelegateCommand<object>)(StartCmd)).RaiseCanExecuteChanged();

            //App.Events.Publish(new BusyProcessing { IsBusy = true, BusyText = "Starting..." });

            try
            {
                _bandClient.SensorManager.Distance.ReadingChanged += Distance_ReadingChanged;
                // If the user consent was granted
                _started = await _bandClient.SensorManager.Distance.StartReadingsAsync();
            }
            finally
            {
                //App.Events.Publish(new BusyProcessing { IsBusy = false, BusyText = "" });
                IsBusy = false;
                ((AsyncDelegateCommand<object>)(StopCmd)).RaiseCanExecuteChanged();
            }
            return _started;
        }
コード例 #4
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();
            }
        }
コード例 #5
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
            }
        }
コード例 #6
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);
            }
        }
コード例 #7
0
 public BandViewModel(IBandInfo info)
 {
     _info       = info;
     _connectCmd = new Lazy <IAsyncCommand>(() =>
     {
         return(new AsyncDelegateCommand <object>(Connect, CanConnect));
     });
 }
コード例 #8
0
        public BandViewModel(IBandInfo info)
        {
            _info = info;
            _connectCmd = new Lazy<IAsyncCommand>(() =>
            {
                return new AsyncDelegateCommand<object>(Connect, CanConnect);
            });

        }
コード例 #9
0
        public void Dispose()
        {
            if (_bandClient != null)
            {
                _bandClient.Dispose();
                _bandClient = null;
            }

            _bandInfo = null;
        }
コード例 #10
0
        /// <summary>
        /// Called when we should update the inbox and send any notifications.
        /// </summary>
        /// <param name="newNotifications"></param>
        /// <param name="currentMessages"></param>
        public async Task UpdateInboxMessages(List <Tuple <string, string, string> > newNotifications, List <Message> currentMessages)
        {
            // Make sure we are enabled and in a good state
            if (ShowInboxOnBand && await EnsureBandTileState())
            {
                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))
                    {
                        foreach (Tuple <string, string, string> newNote in newNotifications)
                        {
                            string title = newNote.Item1;
                            string body  = newNote.Item2;

                            // If the body is empty move the title to the body so it wraps
                            if (String.IsNullOrWhiteSpace(body))
                            {
                                body  = title;
                                title = "";
                            }

                            // If we have a title clip it to only two words. The title can't be very long and
                            // looks odd if it is clipped on the band.
                            int firstSpace = String.IsNullOrWhiteSpace(title) ? -1 : title.IndexOf(' ');
                            if (firstSpace != -1)
                            {
                                int secondSpace = title.IndexOf(' ', firstSpace + 1);
                                if (secondSpace != -1)
                                {
                                    title = title.Substring(0, secondSpace);
                                }
                            }

                            // Send the message.
                            await bandClient.NotificationManager.SendMessageAsync(c_bandTileGuid, title, body, DateTimeOffset.Now, Microsoft.Band.Notifications.MessageFlags.ShowDialog);
                        }
                    }
                }
                catch (Exception e)
                {
                    m_baconMan.MessageMan.DebugDia("failed to update band message", e);
                    m_baconMan.TelemetryMan.ReportUnExpectedEvent(this, "FailedToUpdateBandMessages", e);
                }
            }
        }
コード例 #11
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);
 }
コード例 #12
0
        public void Dispose()
        {
            if( _bandClient != null )
            {

                _bandClient.Dispose();
                _bandClient = null;
            }

            _bandInfo = null;
        }
コード例 #13
0
        /// <summary>
        /// Band デバイスに接続する
        /// </summary>
        /// <param name="device">Band デバイス情報</param>
        /// <returns>Band 接続サービス</returns>
        public async Task <IBandClient> ConnectAsync(IBandInfo bandInfo)
        {
            var client = Native.BandClientManager.Instance.AttachedClients.FirstOrDefault(c => c.Name.Equals(bandInfo.Name));

            if (client != null && !client.IsDeviceConnected)
            {
                await Native.BandClientManagerExtensions.ConnectTaskAsync(Native.BandClientManager.Instance, client);
            }

            return(new NativeBandClient(client));
        }
コード例 #14
0
ファイル: MainPage.xaml.cs プロジェクト: vaclavpetr/Blog
        public async Task <string> RetrieveInfo(IBandInfo bandInfo, IBandClient client)
        {
            Name           = bandInfo.Name;
            ConnectionType = bandInfo.ConnectionType;
            Firmware       = await client.GetFirmwareVersionAsync();

            Hardware = await client.GetHardwareVersionAsync();

            return(Format(" Connected to: {0}" +
                          " \n Connection type : {1}" +
                          " \n Firmware : {2} \n Hardware : {3}",
                          Name, ConnectionType, Firmware, Hardware));
        }
コード例 #15
0
        private async Task <CargoClient> GetUSBBand()
        {
            var devices = await GetConnectedUSBDevicesAsync();

            if (devices != null && devices.Length > 0)
            {
                _deviceInfo = devices[0];

                return((await BandAdminClientManager.Instance.ConnectAsync(_deviceInfo)) as CargoClient);
            }

            return(null);
        }
コード例 #16
0
 public static async Task <IBandClient> Connect_Band(IBandInfo Band)
 {
     try
     {
         return(await BandClientManager.Instance.ConnectAsync(Band));
     }
     catch (Exception ex)
     {
         MessageDialog msg = new MessageDialog(Localization.Get_Text(Localization.Tag.MessageDialog_, "BandConnectErrorContent"), Localization.Get_Text(Localization.Tag.MessageDialog_, "BandConnectErrorTitle"));
         await msg.ShowAsync();
     }
     return(null);
 }
コード例 #17
0
ファイル: BandManager.cs プロジェクト: AndreLucas13/WbaBand
        public void Dispose()
        {
            foreach (var disposableStream in this.disposableStreams)
            {
                disposableStream.Dispose();
            }

            this.selectedBand = null;
            this.bandClient?.Dispose();
            this.bandClient = null;
            //this.sensorClient?.Dispose();
            //this.sensorClient = null;
        }
コード例 #18
0
        public async Task <IBandClient> ConnectBandAsync(IBandInfo band)
        {
            var bandClient = await BandClientManager.Instance.ConnectAsync(band);

            // Note. The following code is a workaround for a bug in the Band SDK;
            // see the following link
            // http://stackoverflow.com/questions/30611731/microsoft-band-sdk-sensors-windows-sample-exception
            Type.GetType("Microsoft.Band.BandClient, Microsoft.Band")
            .GetRuntimeFields()
            .First(field => field.Name == "currentAppId")
            .SetValue(bandClient, Guid.NewGuid());

            return(bandClient);
        }
コード例 #19
0
        public async Task<IBandClient> ConnectBandAsync(IBandInfo band)
        {
            var bandClient = await BandClientManager.Instance.ConnectAsync(band);

            // Note. The following code is a workaround for a bug in the Band SDK;
            // see the following link 
            // http://stackoverflow.com/questions/30611731/microsoft-band-sdk-sensors-windows-sample-exception
            Type.GetType("Microsoft.Band.BandClient, Microsoft.Band")
                        .GetRuntimeFields()
                        .First(field => field.Name == "currentAppId")
                        .SetValue(bandClient, Guid.NewGuid());

            return bandClient;
        }
コード例 #20
0
        public async Task <IBandClient> ConnectToFirstBand()
        {
            // Get a list of the available bands in the form of IBandInfo[] then take the first one from the list.
            // We could also present the list to the user to choose a band.
            IBandInfo[] bands = await bandClientManager.GetBandsAsync();

            if (bands == null || bands.Length == 0)
            {
                return(null);
            }

            IBandInfo band = bands[0];

            return(await bandClientManager.ConnectAsync(band));
        }
コード例 #21
0
        private static async Task <bool?> GetConsentForHeartRate(IBandInfo bandInfo)
        {
            bool consentGranted;

            IBandClient bandClient = null;

            bool isRunning = false;

            if (bandInfo != null)
            {
                using (new DisposableAction(() => isRunning = true, () => isRunning = false))
                {
                    try
                    {
                        bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);
                    }
                    catch (Exception)
                    {
                        // Handle exception
                    }

                    if (bandClient != null)
                    {
                        if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
                        {
                            consentGranted = await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
                        }
                        else
                        {
                            consentGranted = true;
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else
            {
                return(null);
            }

            bandClient.Dispose();

            return(consentGranted);
        }
コード例 #22
0
        /// <summary>
        /// Band デバイスに接続する
        /// </summary>
        /// <param name="device">Band デバイス情報</param>
        /// <returns>Band 接続サービス</returns>
        public async Task <IBandClient> ConnectAsync(IBandInfo bandInfo)
        {
            var info = bandInfo as NativeBandInfo;

            if (info == null)
            {
                throw new InvalidOperationException("Parameter 'device' is not BandDevice type.");
            }
            var client = Native.BandClientManager.Instance.Create(Application.Context, info.DeviceInfo);

            if (client != null && !client.IsConnected)
            {
                var result = await Native.BandClientExtensions.ConnectTaskAsync(client);
            }

            return(new NativeBandClient(client));
        }
コード例 #23
0
        private async Task SetupBand()
        {
            try
            {
                // Loads in any previously saved health data
                this.RecordedData = await LoadRecordedData();
            }
            catch (Exception)
            {
                this.RecordedData = new List <BandData>();
            }

            // Gets the first available Band from the device
            this.bandInfo = (await BandClientManager.Instance.GetBandsAsync()).FirstOrDefault();

            if (this.bandInfo == null)
            {
                throw new InvalidOperationException("No Microsoft Band available to connect to.");
            }

            var isConnecting = false;

            using (new DisposableAction(() => isConnecting = true, () => isConnecting = false))
            {
                // Attempts to connect to the Band
                this.bandClient = await BandClientManager.Instance.ConnectAsync(this.bandInfo);

                if (this.bandClient == null)
                {
                    throw new InvalidOperationException("Could not connect to the Microsoft Band available.");
                }

                // This sample uses the Heart Rate sensor so the user must have granted access prior to the BG task running
                if (this.bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
                {
                    throw new InvalidOperationException(
                              "User has not granted access to the Microsoft Band heart rate sensor.");
                }

                this.ResetReceivedFlags();

                this.bandData = new BandData();

                await this.SetupSensors();
            }
        }
コード例 #24
0
        public IAsyncOperation <IBandClient> ConnectAsync(IBandInfo bandInfo)
        {
            var myBandInfo = bandInfo as BandInfo;

            if (myBandInfo == null)
            {
                throw new ArgumentException("Unrecognized IBandInfo implementation.");
            }

            return
                (Band
                 .BandClientManager
                 .Instance
                 .ConnectAsync(myBandInfo.ProxiedBandInfo)
                 .ContinueWith <IBandClient>(task => new BandClient(task.Result))
                 .AsAsyncOperation());
        }
コード例 #25
0
        async Task CheckForBand()
        {
            ErrorBlock.Text = "Loading...";
            if (currentBand != null)
            {
                return;
            }
            MessageBlock.Text   = "Looking for a Microsoft Band...";
            PinButton.IsEnabled = false;
            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

            if (pairedBands.Length < 1)
            {
                MessageBlock.Text = "I can't find a Microsoft Band.";
            }
            else
            {
                currentBand = pairedBands[0];
                try
                {
                    bandClient = await BandClientManager.Instance.ConnectAsync(currentBand);

                    MessageBlock.Text   = "Connected to " + currentBand.Name + ".";
                    PinButton.IsEnabled = true;
                }
                catch (Exception ex)
                {
                    currentBand       = null;
                    MessageBlock.Text = ex.Message;
                }
            }
            if (bandClient != null)
            {
                bandClient.Dispose();
                bandClient = null;
            }
            if (!tilePinned)
            {
                ErrorBlock.Text = "You need to pin the Walk Reminder tile before you can change the settings.";
            }
            if (currentBand == null)
            {
                ErrorBlock.Text = "You need to connect a Microsoft Band before you can change the settings. Make sure that your Band is paired, and all software is up to date.";
            }
            UpdateUI();
        }
コード例 #26
0
ファイル: BandService.cs プロジェクト: Blisse/Bandit
        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;
        }
コード例 #27
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);
        }
コード例 #28
0
ファイル: BandManager.cs プロジェクト: AndreLucas13/WbaBand
        private async Task InitAsync()
        {
            try
            {
                this.selectedBand = await this.FindDevicesAsync();

                if (this.selectedBand == null)
                {
                    return;
                }

                this.bandClient = await this.ConnectAsync();

                if (this.bandClient == null)
                {
                    return;
                }

                //await this.LoadBandRegistrySensor();
                //if (this.bandRegistrySensor == null)
                //{
                //    return;
                //}

                //RemoveTile();

                bandVersion = await this.bandClient.GetHardwareVersionAsync();

                AddingTile();

                this.StartStreams();

                StartConnectionChecker();
            }
            catch (Exception x)
            {
                Debug.WriteLine(x.Message);
                await c.saveStringToLocalFile("DebugLogs.txt", "TimeStamp: " + BandController.CurrentDate() + " Debug: " + "Connecting to the Band - " + x.Message);
            }
            finally
            {
                this.initializingTask = null;
            }
        }
コード例 #29
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();
        }
コード例 #30
0
        private async Task SetupBandAsync()
        {
            // Use the fake band client manager
            IBandClientManager clientManager = GetBandClientManager();

            // --------------------------------------------------
            // set up Band SDK code to start reading HR values..
            var bands = await clientManager.GetBandsAsync();

            _bandInfo = bands.First();

            _bandClient = await clientManager.ConnectAsync(_bandInfo);

            await SetupSensorReadingAsync(_bandClient.SensorManager.HeartRate, async (obj, ev) =>
            {
                _hrArgs.Args = ev.SensorReading;
                var payload  = JsonConvert.SerializeObject(_hrArgs);
                using (var releaser = await _lockObj.LockAsync())
                {
                    await _socketWriter.WriteAsync(payload);
                }
            });

            await SetupSensorReadingAsync(_bandClient.SensorManager.Gyroscope, async (obj, ev) =>
            {
                _gyroArgs.Args = ev.SensorReading;
                var payload    = JsonConvert.SerializeObject(_gyroArgs);
                using (var releaser = await _lockObj.LockAsync())
                {
                    await _socketWriter.WriteAsync(payload);
                }
            });

            await SetupSensorReadingAsync(_bandClient.SensorManager.Accelerometer, async (obj, ev) =>
            {
                _accArgs.Args = ev.SensorReading;
                var payload   = JsonConvert.SerializeObject(_accArgs);
                using (var releaser = await _lockObj.LockAsync())
                {
                    await _socketWriter.WriteAsync(payload);
                }
            });
        }
コード例 #31
0
        // 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);
        }
コード例 #32
0
        public static async Task <CargoClient> CreateAsync(IBandInfo deviceInfo)
        {
            if (deviceInfo.ConnectionType != BandConnectionType.Bluetooth)
            {
                throw new ArgumentException("Only use BlutoothClient to instantiate Bluetooth devices");
            }

            // since constructors can't be async (and we can't use the builtin CreateAsync since it will
            // choke on Bluetooth) wrap the creation in a Task
            return(await Task.Run <CargoClient>(() =>
            {
                var client = new CargoClient(new BluetoothDeviceTransport((BluetoothDeviceInfo)deviceInfo), null, null, null, null);

                // if we don't set this most actions will fail. I assume this causes weirdness if the Band is not in
                // App mode (perhaps during initial setup?), but in reality we always seem to be in App mode
                // REMOVED FROM LATEST DLL: client.deviceTransportApp = RunningAppType.App;

                return client;
            }));
        }
コード例 #33
0
        /// <summary>
        ///   Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">
        ///   Event data that describes how this page was reached.
        ///   This parameter is typically used to configure the page.
        /// </param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode != NavigationMode.New)
            {
                return;
            }
            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();

            IBandInfo band = pairedBands.FirstOrDefault();

            if (band == null)
            {
                TextBlock.Text = NotPairedMessage;
                return;
            }
            TextBlock.Text = PairedMessage;

            StopButton.IsEnabled = false;
            _bandClient          = await BandClientManager.Instance.ConnectAsync(band);
        }
コード例 #34
0
ファイル: BluetoothClient.cs プロジェクト: misspierc/unBand
        public static async Task<CargoClient> CreateAsync(IBandInfo deviceInfo)
        {
            if (deviceInfo.ConnectionType != BandConnectionType.Bluetooth)
            {
                throw new ArgumentException("Only use BlutoothClient to instantiate Bluetooth devices");
            }

            // since constructors can't be async (and we can't use the builtin CreateAsync since it will
            // choke on Bluetooth) wrap the creation in a Task
            return await Task.Run<CargoClient>(() =>
            {
                var client = new CargoClient(new BluetoothDeviceTransport((BluetoothDeviceInfo)deviceInfo), null, null, null, null);

                // if we don't set this most actions will fail. I assume this causes weirdness if the Band is not in
                // App mode (perhaps during initial setup?), but in reality we always seem to be in App mode
                // REMOVED FROM LATEST DLL: client.deviceTransportApp = RunningAppType.App;

                return client;
            });
        }
コード例 #35
0
        // 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 );
        }
コード例 #36
0
        /// <summary>
        /// Initialize the connection to the band. Default will be the first one in the paired Band
        /// </summary>
        /// <returns> True indicate success , False indicate failure</returns>
        public async Task <bool> InitializeBandConnection()
        {
            //check if we already have a connection to a band or not.
            if (currentBandInfo == null)
            {
                //Get a list of paired band
                var pairedBands = await BandClientManager.Instance.GetBandsAsync();


                if (pairedBands.Count() < 1)
                {
                    //something is wrong.
                    return(false);
                }

                //Get the band info
                currentBandInfo = pairedBands[0];
            }


            try
            {
                //Try to establish connection to the band
                currentBandClient = await BandClientManager.Instance.ConnectAsync(currentBandInfo);

                if (currentBandClient == null)
                {
                    return(false);
                }

                return(true);
            }

            catch (BandException ex)
            {
                //something went wrong.
                return(false);
            }
        }
コード例 #37
0
        protected async override Task <object> Start(object arg)
        {
            var band = arg as Band;

            _bandInfo   = band.Info;
            _bandClient = band.Client;

            var consent = _bandClient.SensorManager.Distance.GetCurrentUserConsent();

            switch (consent)
            {
            case UserConsent.NotSpecified:
                await _bandClient.SensorManager.Distance.RequestUserConsentAsync();

                break;

            case UserConsent.Declined:
                return(false);
            }

            IsBusy = true;
            ((AsyncDelegateCommand <object>)(StartCmd)).RaiseCanExecuteChanged();

            //App.Events.Publish(new BusyProcessing { IsBusy = true, BusyText = "Starting..." });

            try
            {
                _bandClient.SensorManager.Distance.ReadingChanged += Distance_ReadingChanged;
                // If the user consent was granted
                _started = await _bandClient.SensorManager.Distance.StartReadingsAsync();
            }
            finally
            {
                //App.Events.Publish(new BusyProcessing { IsBusy = false, BusyText = "" });
                IsBusy = false;
                ((AsyncDelegateCommand <object>)(StopCmd)).RaiseCanExecuteChanged();
            }
            return(_started);
        }
コード例 #38
0
        public FakeBandClient(IBandInfo bandInfo)
        {
            this.bandInfo = bandInfo;
            _bandVersion = ((FakeBandInfo)bandInfo).Version;
            _container = new Lazy<FakeTileContainer>(() => new FakeTileContainer());
            _sensorManager = new Lazy<IBandSensorManager>(() => new FakeBandSensorManager(BandTypeConstants));
            _notificationManager = new Lazy<IBandNotificationManager>(() => new FakeBandNotificationManager(this, Container));
            _personalizationManager = new Lazy<IBandPersonalizationManager>(() => new FakeBandPersonalizationManager());
            _tileManager = new Lazy<IBandTileManager>(() =>
            {
                IBandConstants consts = null;
                if (_bandVersion == BandVersion.BandOne)
                {
                    consts = new FakeBandOneConstants();
                }
                else
                {
                    consts = new FakeBandTwoConstants();
                }

                return new FakeBandTileManager(consts, this, Container);
            });
        }
コード例 #39
0
        public FakeBandClient(IBandInfo bandInfo)
        {
            this.bandInfo           = bandInfo;
            _bandVersion            = ((FakeBandInfo)bandInfo).Version;
            _container              = new Lazy <FakeTileContainer>(() => new FakeTileContainer());
            _sensorManager          = new Lazy <IBandSensorManager>(() => new FakeBandSensorManager(BandTypeConstants));
            _notificationManager    = new Lazy <IBandNotificationManager>(() => new FakeBandNotificationManager(this, Container));
            _personalizationManager = new Lazy <IBandPersonalizationManager>(() => new FakeBandPersonalizationManager());
            _tileManager            = new Lazy <IBandTileManager>(() =>
            {
                IBandConstants consts = null;
                if (_bandVersion == BandVersion.BandOne)
                {
                    consts = new FakeBandOneConstants();
                }
                else
                {
                    consts = new FakeBandTwoConstants();
                }

                return(new FakeBandTileManager(consts, this, Container));
            });
        }
コード例 #40
0
        public async Task TestGetBandLiveInfo()
        {
            //check if we already have a connection to a band or not.
            if (currentBandInfo == null)
            {
                //Get a list of paired band
                var pairedBands = await BandClientManager.Instance.GetBandsAsync();


                if (pairedBands.Count() < 1)
                {
                    //something is wrong.
                    BandLiveInfo = "Can't find your band info. Did you pair it?";
                    return;
                }

                //Get the band info
                currentBandInfo = pairedBands[0];
            }


            try
            {
                //Try to establish connection to the band
                currentBandClient = await BandClientManager.Instance.ConnectAsync(currentBandInfo);

                BandLiveInfo = "Band Firmware Version: " + (await currentBandClient.GetFirmwareVersionAsync()) + "  Hardware Version: " + (await currentBandClient.GetHardwareVersionAsync());

                return;
            }

            catch (BandException ex)
            {
                //something went wrong.
                BandLiveInfo = "Can't find your band. Please keep that in range";
            }
        }
コード例 #41
0
        private async void SettingUp()
        {
            resultText.Text = "Retrieving information";
            band            = await GetConnectedBand();

            if (band != null)
            {
                string[] bandInformation = await GetBandInformation();

                BandTile[] bandTiles = await GetBandTiles();

                try
                {
                    resultText.Text = "Retrieving capacity";
                    int capacity = await TileCapacity();

                    if (capacity > 0)
                    {
                        canSetTile      = true;
                        resultText.Text = "Ok";

                        AddTileButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        canSetTile               = true;
                        resultText.Text          = "You haven't more spaces... but this app delete the Tile :P";
                        AddTileButton.Visibility = Visibility.Visible;
                    }
                }
                catch (Exception ex)
                {
                    canSetTile      = false;
                    resultText.Text = ex.Message;
                }
            }
        }
コード例 #42
0
 public async Task<IBandClient> ConnectAsync(IBandInfo bandInfo)
 {
     await Task.Delay(300);
     return new FakeBandClient(bandInfo);
 }
コード例 #43
0
        private async void SettingUp()
        {
            resultText.Text = "Retrieving information";
            band = await GetConnectedBand();
            if (band != null)
            {
                string[] bandInformation = await GetBandInformation();
                BandTile[] bandTiles = await GetBandTiles();
                
                try
                {
                    resultText.Text = "Retrieving capacity";
                    int capacity = await TileCapacity();
                    if (capacity > 0)
                    {
                        canSetTile = true;
                        resultText.Text = "Ok";

                        AddTileButton.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        canSetTile = true;
                        resultText.Text = "You haven't more spaces... but this app delete the Tile :P";
                        AddTileButton.Visibility = Visibility.Visible;
                    }
                }
                catch (Exception ex)
                {
                    canSetTile = false;
                    resultText.Text = ex.Message;
                }

            }
        }        
コード例 #44
0
        private static async Task<bool?> GetConsentForHeartRate(IBandInfo bandInfo)
        {
            bool consentGranted;

            IBandClient bandClient = null;

            bool isRunning = false;

            if (bandInfo != null)
            {
                using (new DisposableAction(() => isRunning = true, () => isRunning = false))
                {
                    try
                    {
                        bandClient = await BandClientManager.Instance.ConnectAsync(bandInfo);
                    }
                    catch (Exception)
                    {
                        // Handle exception
                    }

                    if (bandClient != null)
                    {
                        if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
                        {
                            consentGranted = await bandClient.SensorManager.HeartRate.RequestUserConsentAsync();
                        }
                        else
                        {
                            consentGranted = true;
                        }
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            else
            {
                return null;
            }

            bandClient.Dispose();

            return consentGranted;
        }
コード例 #45
0
 /// <summary>
 /// Destructor to remove the references to the connected Band to free it.
 /// author: Raphael Zenhäusern
 /// </summary>
 public void Destruct()
 {
     _bandClient = null;
     _selectedBand = null;
 }
コード例 #46
0
        private async Task SetupBand()
        {
            try
            {
                // Loads in any previously saved health data
                this.RecordedData = await LoadRecordedData();
            }
            catch (Exception)
            {
                this.RecordedData = new List<BandData>();
            }

            // Gets the first available Band from the device
            this.bandInfo = (await BandClientManager.Instance.GetBandsAsync()).FirstOrDefault();

            if (this.bandInfo == null)
            {
                throw new InvalidOperationException("No Microsoft Band available to connect to.");
            }

            var isConnecting = false;

            using (new DisposableAction(() => isConnecting = true, () => isConnecting = false))
            {
                // Attempts to connect to the Band
                this.bandClient = await BandClientManager.Instance.ConnectAsync(this.bandInfo);

                if (this.bandClient == null)
                {
                    throw new InvalidOperationException("Could not connect to the Microsoft Band available.");
                }

                // This sample uses the Heart Rate sensor so the user must have granted access prior to the BG task running
                if (this.bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
                {
                    throw new InvalidOperationException(
                        "User has not granted access to the Microsoft Band heart rate sensor.");
                }

                this.ResetReceivedFlags();

                this.bandData = new BandData();

                await this.SetupSensors();
            }
        }
コード例 #47
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            btnClickMe.Content = "Start Collection";
            btnClickMe.IsEnabled = false;
            tbStatus.Text = "Getting band info";
            IBandInfo[] bands = await BandClientManager.Instance.GetBandsAsync();
            if (bands.Length == 0)
            {
                await UpdateStatusAsync("no bands found");
                return;
            }

            _bandInfo = bands.First();
            await RunOnUiThread(() =>
            {
                tbStatus.Text = $"Using Band {_bandInfo.Name}";
                btnClickMe.IsEnabled = true;
            });

            await LoadFilesAsync();
        }
コード例 #48
0
ファイル: BandManager.cs プロジェクト: jehy/unBand
        private async Task<ICargoClient> GetUSBBand()
        {
            var devices = await GetConnectedUSBDevicesAsync();

            if (devices != null && devices.Length > 0)
            {
                _deviceInfo = devices[0];

                return (await BandAdminClientManager.Instance.ConnectAsync(_deviceInfo)) as ICargoClient;
            }

            return null;
        }
コード例 #49
0
        public async Task InitBand()
        {
            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();

                        /*
                            Enter band threshold code here.
                        */
                    });
                };
                await _bandClient.SensorManager.HeartRate.StartReadingsAsync();
            }
        }
コード例 #50
0
 /// <summary>
 /// Utility to reflect the connected band in the interface.
 /// author: Raphael Zenhäusern
 /// </summary>
 /// <param name="bandInfo"></param>
 private void DisplayBandConnected(IBandInfo bandInfo)
 {
     BandConnectionInfotext.Text = "Verbunden mit " + bandInfo.Name;
     DisplayBandSearchingIndicator(false);
     BandConnectionInfotext.Visibility = Visibility.Visible;
 }
コード例 #51
0
 public async Task<IBandClient> ConnectBandAsync(IBandInfo band)
 {
     await Task.Delay(1000);
     return new FakeBandClient();
 }