none
[WPSL](Dis)Connecting bluetooth devices with Windows.Devices.Bluetooth.Rfcomm RRS feed

  • Question

  • After migrating my app to WinPhone8.1(SilverLight) I use RFCOMM connection, but it works unstable.

    The first time I try to connect to the devices everything will go fine and the connection will open. When I subsequently close the connection and re-connect the device, the trouble starts.  During the re-connect the connection will never open and the debugger will throw a System.Exception (Message: No more data is available).

    Also, when the connection fails the Windows 8.1 devices will keep trying to (unsuccessfully) connect to the Bluetooth Devices by themselves, even when my own application is terminated. Sometimes the Windows 8.1 device will also show the Bluetooth device as connected, while the device visually shows that it's not connected anymore. The only way to reconnect the Bluetooth device is to unpair it and shutdown/restart Bluetooth on the Windows device. Whenever I try to make a new call to DeviceInformation after a failed connect it will refuse to return the device that I earlier tried to connect. (Message: The service cannot be found in the specified name space.)

    I don't have this problem with WinPhone8.

    I already have got SilverLight capabilities ID_CAP_NETWORK, ID_CAP_PROXIMITY

    I set .... in Package.appmainfest

    <m2:DeviceCapability Name="bluetooth.rfcomm">
      <m2:Device Id="any">
        <m2:Function Type="name:serialPort" />
        <m2:Function Type="name:obexObjectPush" />
        <m2:Function Type="name:obexFileTransfer" />        
      </m2:Device> 

    Search for  "SerialPort" devices 

    var devicesInfoCollection = await DeviceInformation.FindAllAsync(
     RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
    sensorCollection.Clear();
    foreach (DeviceInformation dInfo in devicesInfoCollection)
    {
      sensorCollection.Add(dInfo);
    }

    Connection  

    RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(selectedDeviceInfo.Id);
    socket = new StreamSocket();
    await socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, 
      SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

    Disconnection

    if (dataWriter != null)
    {
       dataWriter.DetachStream();
       dataWriter.Dispose();
       dataWriter = null;
    }                   
    if (socket != null)
    {
       socket.Dispose();
       socket = null;
    }

    http://stackoverflow.com/questions/27122484/rfcomm-connection-works-unstable#comment42753894_27124946

    http://stackoverflow.com/questions/26970395/disconnecting-bluetooth-devices-with-windows-devices-bluetooth-rfcomm-wp8-1


    Tuesday, November 25, 2014 1:07 PM

All replies

  • After the initial disconnect, does devicewatcher find the device?

    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, November 25, 2014 8:43 PM
    Moderator
  • After my device stop connecting, I get this Exception:"The service cannot be found in the specified name space". This code returns me an empty list:

    var devicesInfoCollection = await DeviceInformation.FindAllAsync(

    RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

    sensorCollection.Clear();

    foreach (DeviceInformation dInfo in devicesInfoCollection)

    {  sensorCollection.Add(dInfo);}

    And DeviceWatcher can  see my device

    void watcher_EnumerationCompleted(DeviceWatcher sender,object args){               
    List<DeviceInformation> devColl = 
         AllDevicesInfo.Where(d => d.Name == "my_device").ToList();}

    this code returns List with 3 Items:

    1)
    Id = "\\\\?\\BTHENUM#{00001101-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d#6&268da77&0&00126F330002_C00000000#{b142fc3e-fa4e-460b-8abc-072b628b3c70}"
    IsDefault = false;
    IsEnable = false;
    2)
    Id = "\\\\?\\BTHENUM#{00001101-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d#6&268da77&0&00126F330002_C00000000#{00001101-0000-1000-8000-00805f9b34fb}"
    IsDefault = false;
    IsEnable = false;
    3)
    Id = "\\\\?\\B11:19 26.11.2014+THENUM#Dev_00126F330002#6&23f92770&0&BluetoothDevice_00126F330002#{00f40965-e89d-4487-9890-87c3abb211f4}"
    IsDefault = false;
    IsEnable = true;

    Wednesday, November 26, 2014 8:38 AM
  • Another question I've paired my laptop with lumia by Bluetooth. 

    void watcher_EnumerationCompleted (DeviceWatcher sender, object args)        { List<DeviceInformation> expColl = AllDevicesInfo.Where(d => d.Name.Contains("ACER")).ToList();

    }

    DeviceWatcher returns me 3 Items:

    1)

    "\\\\?\\BTHENUM#Dev_00242CF19A04#6&23f92770&0&BluetoothDevice_00242CF19A04#{00f40965-e89d-4487-9890-87c3abb211f4}"

    2)

    "\\\\?\\BTHENUM#{00001000-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d#6&23f92770&0&00242CF19A04_C00000000#{00001000-0000-1000-8000-00805f9b34fb}"

    3)

    "\\\\?\\BTHENUM#{00001115-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d#6&23f92770&0&00242CF19A04_C00000000#{00001115-0000-1000-8000-00805f9b34fb}"

    there are no id that contains {00001105-0000-1000-8000-00805f9b34fb} - ObexObjectPush.

    but with the same lumia and the same laptop on Windows Phone 8 this code works well

    await socket.ConnectAsync(_selectedDevice.HostName, "{00001105-0000-1000-8000-00805f9b34fb}");

    and files transfer successfully

    Wednesday, November 26, 2014 9:20 AM
  • the exception ""The system cannot find the file specified. (Exception from HRESULT: 0x80070002)"" I wrote before is thrown at this line:

    RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id);

    Wednesday, November 26, 2014 9:38 AM
  • Can you provide a full app for me to test? I'll try it out here.

    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.

    Wednesday, November 26, 2014 4:48 PM
    Moderator
  • Thanks for your help! How can I send it to you?
    Wednesday, November 26, 2014 8:02 PM
  • Upload to OneDrive and share a link here.

    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.

    Thursday, November 27, 2014 5:54 PM
    Moderator
  • Thursday, November 27, 2014 10:19 PM
  • Hey GloomyOwl - I'm working on this now.  This got delayed due to the Thanksgiving holiday.

    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.

    Wednesday, December 3, 2014 2:16 PM
    Moderator
  • Hello, Matt. My account on StackOverflow isn't gl77. My name is Nick and thread is

    http://stackoverflow.com/questions/27122484/rfcomm-connection-works-unstable/

    but that's ok, thanks for your help

    Thursday, December 4, 2014 2:36 PM
  • Hello, Matt, do you have any news about this question?
    Tuesday, December 16, 2014 3:02 PM
  • Hi - I am working on this issue but don't have any update.

    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.

    Monday, December 22, 2014 6:37 PM
    Moderator
  • I see the same bahavior in a project controlling Gadgeteer Devices by Windows Phone via bluetooth

    https://www.ghielectronics.com/community/codeshare/entry/1004

    Is there any news, when the issue is going to be fixed or a solution how to circumvent?

    Saturday, February 7, 2015 5:36 PM
  • Hello Matt, sorry for bothering you: Is there any update on this issue?

    It's preventing some apps to be released :S

    Thursday, February 26, 2015 9:05 AM
  • Unfortunately, no. We've tested some potential fixes, but nothing is working at the moment. It's a very high priority issue for us and there are likely multiple individual problems here that we need to identify.

    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.

    Thursday, February 26, 2015 1:08 PM
    Moderator
  • Glad to know that you are working on this, fingers crossed!
    Thursday, February 26, 2015 5:40 PM
  • Windows Phone GDR2 fixes most of the problems in Bluetooth. I hope you can get this update.

    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.

    Monday, March 16, 2015 1:51 PM
    Moderator
  • Thanks a lot. It's a very good news!
    Monday, March 16, 2015 1:53 PM
  • Matt, excuse me, but I've installed Windows Phone 10 TP and still have the problem. Were the fixes icluded in the Win10TP?
    Monday, April 13, 2015 9:34 PM
  • Good day everybody, I was wondering has there been any resolution to this issue. I have the exact same problem as GloomyOwl. This is really frustrating as it was working fine with Windows Phone 8.0.

    I would appreciate any feedback on how to go about getting this working again.

    Friday, June 19, 2015 3:26 PM
  • It's supposed to be in there.

    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.

    Monday, June 22, 2015 6:58 PM
    Moderator
  • I test my app with the last Windows 10 Mobile TP (10136) and still I get the same problem.
    Sorry, Matt, but it doesn't work correctly. Actually it could works few times
    (if I reboot my device and restart my app they could connect/disconnect few times if I do 5 seconds pauses between connections and disconnections), but after that problems begin.

    Bluetooth icon doesn't disappear from status bar and
    I get these errors:

    "Only one usage of each socket address(protocol/network address/port) is normally permitted"

    "No more data is available"

    "A connection attempt failed because the connected party did not properly respond after a period of time, or
    established connection failed because connected host has failed to respond."

    or usually nothing happens and I just break connection process after 20 sec.

    My bluetooth module model is BTM-160 and  I use code that I've sent to you earlier.

    Wednesday, June 24, 2015 3:29 PM
  • Hi Matt,

    I'm using a Nokia Lumia 1020 (Nokia 909) phone running Windows Phone 8.1 OS, the  Bluetooth transceiver model is a JY-MCU. Unfortunately I'm not in a position to upgrade to anything else in the near future. Is there anything that I can get/download to be able correct this issue for my configuration?

    Any advice/suggestions would be helpful.

    Friday, June 26, 2015 11:40 PM
  • Got a software update for my Lumia 920 (Germany) to Core Build ID 3051.50009.1451.10458, Application Version 3.14.7.4.

    Still the same Problem.

    Saturday, July 11, 2015 11:15 PM
  • Hi Matt,

    It's articles like this

    http://www.businessinsider.com/apple-92-percent-profits-entire-smartphone-industry-q1-samsung-2015-7

    that frustrate me that Microsoft support is not trying to help the developers that are trying to develop applications for the Microsoft mobile platforms.

    Bluetooth and IoT are the next leading technologies that I believe are the way Mobile computing is going and if Microsoft doesn't support the developers of Microsoft software for mobile, then it is only obvious that these developers are going to look for other platforms to take their skills to.

    I would really appreciate some kind of feedback on what is been done about this issue.

    Wednesday, July 15, 2015 4:36 PM
  • Has there been any progress on this issue?  With Windows Phone 8.1, after the first connect and disconnect cycle, the device no longer appears as available as a serial port.  

    Prior to the first connect, we query like so

    DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommSerialPortId))

    The device is listed and if we inspect the DeviceInformation we see this:

    Socket CHS 7x [0FB741]
    \\?\BTHENUM#{00001101-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d#6&2914267d&0&00C01B0FB741_C00000000#{b142fc3e-fa4e-460b-8abc-072b628b3c70}
    Enabled? True
    System.ItemNameDisplay->Socket CHS 7x [0FB741]
    System.Devices.DeviceInstanceId->BTHENUM\{00001101-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d\6&2914267d&0&00C01B0FB741_C00000000
    System.Devices.Icon->
    {51236583-0C4A-4FE8-B81F-166AEC13F510} 123->
    System.Devices.InterfaceEnabled->True
    System.Devices.IsDefault->False
    System.Devices.PhysicalDeviceLocation->

    But then, if we disconnect and try to reconnect, no serial ports are available.  If we query the raw device list, we can still find the device, but it is not enabled and we cannot connect:

    bleDevices = await DeviceInformation.FindAllAsync();

    var socketScanners = bleDevices.Where(n => n.Name.IndexOf("Socket") > -1)


    Socket CHS 7x [0FB741]
    \\?\BTHENUM#{00001101-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d#6&2914267d&0&00C01B0FB741_C00000000#{b142fc3e-fa4e-460b-8abc-072b628b3c70}
    Enabled? False
    System.ItemNameDisplay->Socket CHS 7x [0FB741]
    System.Devices.DeviceInstanceId->BTHENUM\{00001101-0000-1000-8000-00805f9b34fb}_LOCALMFG&001d\6&2914267d&0&00C01B0FB741_C00000000
    System.Devices.Icon->
    {51236583-0C4A-4FE8-B81F-166AEC13F510} 123->
    System.Devices.InterfaceEnabled->False
    System.Devices.IsDefault->False
    System.Devices.PhysicalDeviceLocation->

    If we then unpair the device via Bluetooth settings and re-pair we can again connect in the app.  

    It seems the socket is "locked' even after we dispose it.  

    We have tried many variations of closing the socket, stream and reader, but this is our current approach:

            private void close(IDisposable o)
            {
                if (o == null) return;
                try
                {
                    o.Dispose();
                }
                catch (Exception)
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                        throw;
                }
                o = null;
            }
            public async Task Close()
            {
                LastError = null;
                if (listenerCancellation != null)
                {
                    bool listenerWasRunning = listenerRunning;
                    listenerCancellation.Cancel();
                    if (listenerWasRunning)
                        while (listenerRunning)
                            await Task.Yield();
                    listenerWasRunning = false;
                }
                if (reader != null)
                    try { reader.DetachStream(); }
                    catch ( Exception) {  }
                close(reader);
                close(input);
                close(socket);
            }

    Tuesday, October 20, 2015 9:36 PM
  • Unfortunately, there is still no information on how to solve this problem. So, I still can not update my project to win8.1
    Wednesday, October 21, 2015 8:59 AM
  • I finally solved this for my situation in Windows Phone Silverlight 8.1.  The entire problem seemed to be how I was listening to the socket.  I was doing a new DataReader(socket.InputStream).  Big mistake.  Even with reader.DetachStream and reader.Dispose on close, it was still locking the port.

    What worked was following this example to read from the socket directly:

    http://32feet.codeplex.com/SourceControl/latest#InTheHand.Devices.Bluetooth/InTheHand.Devices.Bluetooth/BluetoothChat.BackgroundTask/BluetoothChatBackgroundTask.cs

    When doing it that way, all I have to do is socket.Dispose() and the port is closed the way it's supposed to be.  Then I can reconnect (socket.ConnectAsync) and disconnect (socket.Dispose) as often as I want and the port remains accessible.  

    I took one more precaution, which was to allow cancellation of the read:

    IBuffer b; b = await socket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial) .AsTask(listenerCancellation.Token);


    As per my code in the above comment, I cancel the listener, wait for that to complete, and then dispose the socket.

    public async Task Close() { if (listenerCancellation != null) { bool listenerWasRunning = listenerRunning; listenerCancellation.Cancel(); if (listenerWasRunning) while (listenerRunning) await Task.Yield(); listenerWasRunning = false; } close(socket); IsConnected = false; } private void close(IDisposable o) { if (o == null) return; try { o.Dispose(); } catch (Exception) { if (System.Diagnostics.Debugger.IsAttached) throw; } o = null; }

    So, if you can find a way to not use DataReader or DataWriter in your implementation, try that.  

    ....

    Though as I continue working with it, no, this does not solve the problem.  Particularly for uncontrolled disconnects, like if the device goes to sleep.  Even if I perform the Close process in the Application_Deactivated event, eventually the device will no longer be available as a serial port.  

    • Edited by rmdnetsol Wednesday, October 21, 2015 2:12 PM Was wrong
    Wednesday, October 21, 2015 12:20 PM
  • rmdnetsol , I removed DataReader, DataWriter and use socket.InputStream.ReadAsync, socket.OutputStream.WriteAsync instead. In my situation it doesn't help, unfortunately, problem is still exist.
    Friday, October 23, 2015 7:00 AM
  • Hi, I can report a positive result for a special Bluetooth Module. With the HM-13 Dual Mode Module (JNHuaMao Technology Company) available as Seeed BLE (Dual mode) Bee reconnecting works perfect on a Lumia 920 with WP 8.1. 
    • Edited by SchmiRo Tuesday, November 17, 2015 12:07 AM
    Tuesday, November 17, 2015 12:05 AM
  • Hi, GloomyOwl!

    Have you found any solution for this problem? I'm facing exactly the same issue with my WP8.1 app and I cannot find any solution in my searches. 

    I'm asking you that because my next move will be to migrate to WP8.0. It will be a very hard work, but I have no choice once I need BT working perfectly on my project.

    Regards,

    Saturday, March 19, 2016 1:26 PM
  • Hi, Cassio Basile!

    I've tried different ways, but the problem wasn't solved. All deal in Bluetooth module in my device.

    As a result I have two versions: my device version 1 + WP8.0 app and my device version 2 (with (different) new Bluetooth module) + WP8.1 app.

    With another Bluetooth module in device WP8.1 application works normally.

    Wish you luck!


    • Edited by GloomyOwl Saturday, March 19, 2016 2:02 PM
    Saturday, March 19, 2016 2:02 PM
  • Has there been any progress on this? I have an bluetooth app that works great on phone 8.0 but is unstable on 8.1.
    Thursday, February 2, 2017 10:28 PM