locked
GATT bluetooth 4.0 Win8.1 Visual Studio 2013 C# - question RRS feed

  • Question

  • I'm following an example code from msdn:

    GATT Scenario: Retrieve Bluetooth LE Data

    and I 'm gettin the error:

    An exception of type 'System.Exception' occurred in a6822_v2.exe but was not handled in user code

    Additional information: the applications called an interface not packed (marshall) through another module. (Exception of HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

    my code is and it breaks the error message above on line below: "   TextBlock11.Text = lightData.ToString();

    using a6822_v2.Common;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.Devices.Bluetooth;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Devices.Enumeration;
    using Windows.Devices.Enumeration.Pnp;


    // The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

    namespace a6822_v2
    {
        /// <summary>
        /// A basic page that provides characteristics common to most applications.
        /// </summary>
        ///


     
        public sealed partial class MainPage : Page
        {

            private NavigationHelper navigationHelper;
            private ObservableDictionary defaultViewModel = new ObservableDictionary();

            /// <summary>
            /// This can be changed to a strongly typed view model.
            /// </summary>
            public ObservableDictionary DefaultViewModel
            {
                get { return this.defaultViewModel; }
            }

            /// <summary>
            /// NavigationHelper is used on each page to aid in navigation and
            /// process lifetime management
            /// </summary>
            public NavigationHelper NavigationHelper
            {
                get { return this.navigationHelper; }
            }


            public MainPage()
            {
                this.InitializeComponent();
                this.navigationHelper = new NavigationHelper(this);
                this.navigationHelper.LoadState += navigationHelper_LoadState;
                this.navigationHelper.SaveState += navigationHelper_SaveState;
                this.Initialize();
                  

            }

           
            async public void Initialize()
            {
                Guid formatCharacteristicUuid = new Guid("{cccc0000-0000-0000-0000-111100001111}");
                Guid tr = new Guid("{aaaa0000-0000-0000-0000-111100001111}");
               
                var a6822Services = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(tr), null);

                GattDeviceService a6822Service = await GattDeviceService.FromIdAsync(a6822Services[0].Id);
                
                TextBlock1.Text = "service nome:" + a6822Services[0].Name;
                TextBlock2.Text = "service id:" + a6822Services[0].Properties;
                TextBlock3.Text = "service enable:" + a6822Services[0].IsEnabled;

                GattCharacteristic formatCharacteristic = a6822Service.GetCharacteristics(formatCharacteristicUuid)[0];
                Windows.Devices.Bluetooth.GenericAttributeProfile.GattReadResult a = await formatCharacteristic.ReadValueAsync();

                TextBlock4.Text = "proriedades da caracteritica:" + formatCharacteristic.CharacteristicProperties;
                TextBlock5.Text = "valor caracteristica read_value_async :" + a.Value.ToString();
                TextBlock6.Text = "valor client characteristic Configuration Descriptor :" + a.Value;
                TextBlock7.Text = "handle :" + formatCharacteristic.AttributeHandle+1;

                 GattCommunicationStatus xxxx = await formatCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                TextBlock10.Text = xxxx.ToString();

                formatCharacteristic.ValueChanged += formatCharacteristic_ValueChanged;
                
            }

            void formatCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
            {
                byte[] lightData = new byte[args.CharacteristicValue.Length];
                Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(lightData);
                TextBlock11.Text = lightData.ToString();
            }
                  
            private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
            {
            }
                    
            private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
            {
            }

            #region NavigationHelper registration

            /// The methods provided in this section are simply used to allow
            /// NavigationHelper to respond to the page's navigation methods.
            ///
            /// Page specific logic should be placed in event handlers for the  
            /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
            /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
            /// The navigation parameter is available in the LoadState method
            /// in addition to page state preserved during an earlier session.

            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                navigationHelper.OnNavigatedTo(e);
            }

            protected override void OnNavigatedFrom(NavigationEventArgs e)
            {
                navigationHelper.OnNavigatedFrom(e);
            }

            #endregion
        }
    }

    Tuesday, December 31, 2013 3:06 AM

Answers

  • This is some code that I use:

    await ElementForPropertyChange.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    {
     // The Barometer has to read in calibration data.
     Retval += await ConfigureSensorAsync(2);
     await ReadConfigurationAsync();
    });

    where ElementForPropertyChange is a UI element.  This is from my code that works with the TI SensorTag Bluetooth 4.0 BLE (GATT) device.

    • Marked as answer by Anne Jing Tuesday, January 7, 2014 6:41 AM
    Friday, January 3, 2014 7:32 PM
  • Thank you all,

    After 200hours the programme is working.

    The solution i found was as follows:

    1.)declaring a class:

     public static class AppState
            {
                public static Windows.UI.Core.CoreDispatcher Dispatcher;
            }

    2.) adding the following line to the App.Xaml.cs, inside function OnLaunched:

     MainPage.AppState.Dispatcher = Window.Current.CoreWindow.Dispatcher;

    3.) changing the code above as follows:

        void formatCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
            {
                byte[] lightData = new byte[args.CharacteristicValue.Length];
                Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(lightData);

    AppState.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                     {
                        TextBlock11.Text = lightData.ToString();
                      
                     });            
            }

    • Marked as answer by EloiCarvalho Tuesday, January 7, 2014 9:51 PM
    Tuesday, January 7, 2014 9:50 PM

All replies

  • You should try calling that line of code via the Dispatcher.  It appears that you're running on a background thread and accessing a UI element, which will cause this problem.  You can search this forum for many examples of using the Dispatcher.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Tuesday, December 31, 2013 2:24 PM
    Moderator
  • I Matt, thank for your reply

    I saw some examples but, i can´t acess for example :  Dispatcher.BeginInvoke

    BeginInvoke does not show on the drop list Dispacther, it seems the BeginInvoke as reference Windowsbase.dll but it's absolete as far i can read, because i can add namespace using.system.threading

    I'm using Visual Studio 2013 and C# and i just want to see the content of the variable LightData on the PC, showing on the TextBlock.

    Can you please give an example?

    Thanks

    Thursday, January 2, 2014 4:59 PM
  • sorry, i can't add namespace using.system.threading
    Thursday, January 2, 2014 5:00 PM
  • This is some code that I use:

    await ElementForPropertyChange.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
    {
     // The Barometer has to read in calibration data.
     Retval += await ConfigureSensorAsync(2);
     await ReadConfigurationAsync();
    });

    where ElementForPropertyChange is a UI element.  This is from my code that works with the TI SensorTag Bluetooth 4.0 BLE (GATT) device.

    • Marked as answer by Anne Jing Tuesday, January 7, 2014 6:41 AM
    Friday, January 3, 2014 7:32 PM
  • Thank you all,

    After 200hours the programme is working.

    The solution i found was as follows:

    1.)declaring a class:

     public static class AppState
            {
                public static Windows.UI.Core.CoreDispatcher Dispatcher;
            }

    2.) adding the following line to the App.Xaml.cs, inside function OnLaunched:

     MainPage.AppState.Dispatcher = Window.Current.CoreWindow.Dispatcher;

    3.) changing the code above as follows:

        void formatCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
            {
                byte[] lightData = new byte[args.CharacteristicValue.Length];
                Windows.Storage.Streams.DataReader.FromBuffer(args.CharacteristicValue).ReadBytes(lightData);

    AppState.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                     {
                        TextBlock11.Text = lightData.ToString();
                      
                     });            
            }

    • Marked as answer by EloiCarvalho Tuesday, January 7, 2014 9:51 PM
    Tuesday, January 7, 2014 9:50 PM