Windows Phone 8 and Bluetooth

Okey dokey, Doesn’t all GHI email go to the Gusbot? :wink:

Hi,

I found Shows | Microsoft Learn in this post Bluetooth uses as clientmode.

client = bluetooth.ClientMode;

Are we able to send data from Bluetooth to phone using client mode?

Yes, two-way communication between the Gadgeteer board and a Windows Phone 88 device does work.

Hi anotherlab,

it seems my connection from phone8 to FeZSpider Bluetooth module did not work.

Exception throws at following line

await s.ConnectAsync(hostName, “1”);

I replace with this doesn’t work either. But I still problem with getting service name.

await s.ConnectAsync(hostName, “{21EC2020-3AEA-1069-A2DD-08002B30309D}”);

I appreciate your advice.

Thank

Hi aswin,

Without any other information, it’s hard to see where the problem is. I can throw out a bunch of things that come to mind. Some of which may be obvious, but you want to cover all the bases.

What do you mean by “service name”?
[em]Is that different than the HostName property being returned from the PeerInformation class?[/em]

What is the exception being thrown?
[em]If we know the error is, that helps track down the problem[/em]

Which phone do you have?
[em]I used a HTC 8X, but other Windows Phone 8 devices should work the same way[/em]

Does the phone have Bluetooth turned on?
[em]It’s an obvious question, always check the low hanging fruit[/em]

Have you already paired the FEZ Spider to the phone?
[em]You need to have already paired the Bluetooth device to the phone before you can get the host[/em]

How did you get the hostName variable set?
[em]Did you use the PeerFinder API to enumerate the list of paired devices?[/em]

Are any Bluetooth events being seen on the FEZ side?
[em]You probably are not getting this fair since the error occurs when you try to connect.[/em]

-Chris

Hi Chris,

My apology for not giving full details.

Once I debug I saw hostname as “(00:18:A1:12:0D:09)” which is the mac address of Bluetooth module.

The exception thrown was “The requested address is not valid in its context. (Exception from HRESULT: 0x80072741)”

I am using Nokia 920

I have checked my Bluetooth is on.

I believed I got host name as I mentioned - “(00:18:A1:12:0D:09)”

I used following fragment of code


// Constructor
        public MainPage()
        {
            InitializeComponent();     
            this.Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
           AppToDevice();          
        }
        
        
        private async void AppToDevice()
        {
            HostName hname = await GetHostName();
            bool ok = await ConnectToDevice(hname);            
        }

        private async Task<HostName> GetHostName()
        {          
                HostName hostname = await QueryForHost();         
                return hostname;
        }

        private async Task<HostName> QueryForHost()
        {
            // Tell PeerFinder to only enumerate paired devices
            // See http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207007(v=vs.105).aspx#BKMK_Codeexamples
            PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";
           // PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{00001101-0000-1000-8000-00805f9b34fb}";
            IReadOnlyList<PeerInformation> devices = null;

            try
            {
                // Get a list of matching devices
                devices = await PeerFinder.FindAllPeersAsync();
            }
            catch { }

            // If we can't find any devices, goto to the phone's Bluetooth settings
            if (devices == null || devices.Count == 0)
            {
                MessageBox.Show("No bluetooth devices");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));
                return null;
            }

            // Find the first device that identifies as the Pano Head, otherwise go to the Bluetooth settings
            PeerInformation peerInfo = devices.FirstOrDefault(c => c.DisplayName.Contains("Fez"));
            if (peerInfo == null)
            {
                MessageBox.Show("No pairing");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));
                return null;
            }      
            return peerInfo.HostName;
        }

        private async Task<bool> ConnectToDevice(HostName hostName)
        {
            // Attempt to create a new connection
            StreamSocket s = new StreamSocket();
            try
            {
                // Try to connect to the device on the first port
              //  String guid = Guid.NewGuid().ToString();
                await s.ConnectAsync(hostName, "1");           //exception thrown at this point   
                //WaitForData(s);
                MessageBox.Show("Is connected");
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }   

            return true;
        }

Now I received new error message.

"A socket operation was attempted to an unreachable network. (Exception from HRESULT: 0x80072743)"
at following line.

await s.ConnectAsync(hostName, “1”);

Do you ID_CAP_NETWORKING is enabled in your WMAppManifest.xml? If that’s not set, the call to connect will throw an access violation. For my app, I had ID_CAP_NETWORKING and ID_CAP_PROXIMITY set.

Hi,

I managed to connect Bluetooth from my phone.
Now I am troubled with data receiving at phone 8 from Bluetooth.

if use following code in timer to send data to phone.

int distance = 10;

 if (bluetooth.IsConnected == true)
                {
                     Debug.Print("sending  " + distance);
                    client.Send("" + distance.ToString());
                }

In my phone 8 app I use following code to retrieve the data. But I always receive and display 7,8 or 9. I appreciate your advice.

   private async void WaitForData(StreamSocket socket)
        {
            try
            {
                DataReader dr = new DataReader(socket.InputStream) { InputStreamOptions = InputStreamOptions.Partial };
                uint numStrBytes = await dr.LoadAsync(512);
                dr.ReadString(numStrBytes);

                if (numStrBytes == 0)
                {
                    MessageBox.Show(string.Format("Error", socket.Information.RemoteHostName.DisplayName));
                    return;
                }
                else
                {
                   distanceTxtBlock.Text = numStrBytes.ToString(); //i displayed in textbox
                }

                WaitForData(socket);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Just out of curiosity, what did you have to change to get the phone to connect to the FEZ? That would be helpful if someone else has the same problem.

For getting data back to the phone, you are going to get the data in chunks and reassemble it. Your WaitForData method is going to push the incoming data into a buffer and then you’ll have to periodically check the buffer and look for the data. If you are expecting 12 bytes, you may only get 7 bytes in the first call to Waitdata, and then 5 bytes the next time.

It will be much easier if you define your own protocol, so you can define a starting and ending byte of sequence.

In fact, i did not change at the coding part.
However, someone needs to watch the behaviour of bluetooth pairing process.
Once i start up the device with correct client pairing code, nokia phone prompt to enter the pin code.
Sometimes it may prompt two times

  1. nokia built-in bluetooth connection
  2. your phone application (with bluetooth connection)
    That is the exact moment you need to pair device with phone. It seems small factors but it took me rounds of discussion.

Thank…

aswin can u share ur code that u use for connecting gadgeteer with wp8 i just need to do the same please share if u can … thank you…

The code is not much difference. However for some reason, once you start FezSpider with bluetooth your phone need to be in Bluetooth setting page. It will popup to request the pairing code in your phone. If you successfully enter pairing code, you could exchange the data.


private async void AppToDevice()
        {
            HostName hname = await GetHostName();
            bool ok = await ConnectToDevice(hname);
        }

        private async Task<HostName> GetHostName()
        {
            HostName hostname = await QueryForHost();
            return hostname;
        }

        private async Task<HostName> QueryForHost()
        {
            PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";
            IReadOnlyList<PeerInformation> devices = null;

            try
            {
                // Get a list of matching devices
                devices = await PeerFinder.FindAllPeersAsync();
            }
            catch { }

            // If we can't find any devices, goto to the phone's Bluetooth settings
            if (devices == null || devices.Count == 0)
            {
                MessageBox.Show("No bluetooth devices");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));
                return null;
            }

            // Find the first device that identifies as the Pano Head, otherwise go to the Bluetooth settings
            PeerInformation peerInfo = devices.FirstOrDefault(c => c.DisplayName.Contains("Fez"));
            if (peerInfo == null)
            {
                MessageBox.Show("No pairing");
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));
                return null;
            }
            return peerInfo.HostName;
        }

private async Task<bool> ConnectToDevice(HostName hostName)
        {

            // Attempt to create a new connection
            StreamSocket s = new StreamSocket();
            try
            {
                // Try to connect to the device on the first port
                await s.ConnectAsync(hostName, "1");
                MessageBox.Show("Is connected");
                while (true)
                {
                    Debug.WriteLine("Detecting...");
                    string data = await WaitForData(s); //data processing based on your data format
                   }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return true;
        }

@ aswin -
Hi Aswin,
I’m facing the same problem while reading data from Bluetooth device, so could you guide me to find the solution .

Thanks in advance,
muppudathi

My android phone can’t find the GHI’s BT module also.

@ Muppudathi -
Hi, I think it’s better if you open a new thread. What is the exact problem? Which NETMF and GHI SDK Version? Which driver for the BT-module are you using. Which code do you use on your Windows 8 phone. Unfortunately a do not own a Win 8 phone, I could only give same advice concerning bt-connection to a Windows PC.

@ Muppudath,

You need to provide specific details of the problem.

Which NETMF, which GHI SDK, which Phone?

Does the phone see the BT module or is the problem just with the app?

If you are using Windows Phone, make sure that you have added ID_CAP_PROXIMITY and ID_CAP_NETWORKING capabilities to the app manifest for your app.