Bluetooth Windows

Bluetooth Virtual Sniffer for Windows

I only just found out about this but Microsoft released a packet sniffer for Bluetooth on Windows 10 back in February. This is incredibly useful for debugging and is something I’ve been craving for some time. Previously I’ve been able to analyse packets from Android using Wireshark and now we can view activity between Windows and another device.

I’m desperately hoping this provide some clues to the constant “Unreachable” errors when trying to communicate with an iPhone which Windows Settings acknowledges is currently connected…

You can download the Bluetooth Test Platform here.

Windows 10

New Windows Phone App

Okay, now I’ve drawn you in with a click-bait headline I need to clarify a little! For some time now Windows 10 has had a tightly integrated app called Your Phone which allows you to interact with your phone from the desktop. However, it doesn’t cater for the 50-odd percent of users who have fruit based phones. I’ve been working on closing this gap by creating an app for Windows which is now available in the Microsoft Store called Thy Phone.

The name came about because thy is an archaic version of your and the name also happens to rhyme with a popular phone type.

It uses functionality available in Windows 10 2004 and above to setup a phone device to use Windows as a handsfree device. This allows you to conduct calls through your PC microphone and speakers (or headset) and see call progress and incoming call alerts on your desktop. It also allows you to activate the Bluetooth Audio support so that you can play music, podcasts etc from your phone through your PC.

Finally when using an iPhone it supports toast notifications and mirrors those notifications directly in the Windows notification center. Notifications which uses actions can also be triggered directly from the desktop Toast.

I’ll be adding more functionality over time including Messaging support. I completed a proof of concept but I’m working on a new version of InTheHand.Net.Obex to make it easier to do this. That will also open up other functionality such as file transfers. Because these features all use standard Bluetooth profiles the app is not limited to just iPhones, you can even pair and use your Windows Phone or Nokia 3310 – whatever floats your boat!

English badge
Bluetooth Windows

What’s in a BluetoothLEDevice.Name

I’ve noticed an odd behaviour when creating a BluetoothLEDevice from a found device id. I’m not doing anything special, just retrieving paired devices and then trying to access the relevant BluetoothLEDevice. In common with all Windows device searches (whether by Picker or programmatically with DeviceInformation.FindAllAsync) you receive a DeviceInformation which contains the name and unique id (an opaque device path).

If you search for paired BluetoothLEDevices the returned DeviceInformations contain the valid name and id of the device. When you use BluetoothLEDevice.FromIdAsync() you get back a working BluetoothLEDevice instance but the Name is of the form “Bluetooth nn:nn:nn:nn:nn:nn” which is slightly less than useless. It turns out that Windows isn’t suffering from Amnesia and the actual display name of the device is accessible from BluetoothLEDevice.DeviceInformation.Name. I was scratching my head for a while over the logic of this but at least now I’ve been able to put in a workaround in InTheHand.BluetoothLE 4.0.18. The BluetoothDevice.Name now shows the same name as Windows shows in the UI and so it behaves the same as the other platform implementations!

Bluetooth Xamarin

Wrapping up 2020

I haven’t posted as much as I would have liked this year, because “reasons” but I thought I would put together a short post to wrap up some of the things that have been going on behind the scenes.


Back in January I announced a re-write of 32feet.NET. The library for Bluetooth Classic has been reworked for the NuGet/.NET Standard age. The intention was removing legacy code and take advantage of newer language features to make it easier to support more platforms and concentrate on getting the core functionality across as many .NET platforms as possible. It’ll also make it easier to support .NET 5/6 ahead. I’ve invested a lot of time into the macOS IOBluetooth and IOBluetoothUI bindings too and will be integrating macOS into the 32feet library in 2021.

I started to work on integrating some code I had written for iOS using the External Accessory API. This allows access to a subset of Bluetooth devices if they implement Apple’s proprietary MFi standard. This will allow devices such as mobile printers to be used with shared code across multiple platforms.

I would like to start work on Linux support (via BlueZ) too which will be another major platform ticked off.

This year I also revived original parts of 32feet.NET in separate packages so IrDA and Object Exchange functionality are available separately. IrDA is end-of-life so I won’t be investing in this area but I wanted to ensure it was made available for desktop Windows in a modern package if required. OBEX has the basic ObexWebRequest with a few minor improvements but it’s something I intend to revisit with a more powerful API soon.

Bluetooth Low Energy

Alongside the Bluetooth Classic updates I also created a new library for Bluetooth Low Energy. This currently supports Windows 10 (.NET Framework, .NET Core and UWP), Android, iOS, tvOS, watchOS, macOS. It would be nice to add Linux and possibly Tizen to this list!

The API follows the existing WebBluetooth standard closely with some additional features relevant to apps. For example not only can you display a picker to the user to choose a device but you can also programmatically discover to generate your own UI. There are some platform specific additions too such as the ability to request a particular physical layer (PHY) which facilitates longer range communication (Currently Android only). Work has also gone into round-tripping support for service UUIDs – the ability to specify by name or short and long UUIDs.


The Xamarin Forms MediaElement now has a new home in the Xamarin Community Toolkit. It’s already received a number of fixes and improvements. In October I added support for databinding to the Position property. Rather than having to write your own timer and query the position you can just bind your UI to the property which gets regularly updated as the media plays.

Happy New Year

I hope you have a happy holiday season and wish you the best for 2021.

Bluetooth Windows

Bluetooth Virtual COM Ports

I was thinking about a comment on a Gist I wrote some time ago and thought I’d written a blog post on the topic, but when I couldn’t find any sign of it I decided to start from scratch as I’d have probably needed to update it anyway.
The Bluetooth stack in Windows has supported virtual COM ports since the beginning (Windows XP SP2 if you can remember that far back!). It’s important to understand the difference between these and any Serial Port Bluetooth device. The Virtual COM port functionality exists purely for interop with older software – you can make a Bluetooth device appear to the system as a wired Serial device and open a COM port and talk to the device as if it was plugged into your PC.
If you’re writing modern software which talks to devices then you would use a Bluetooth API – either 32feet.NET or the platform specific Bluetooth API directly. If not you can create a virtual COM port. Throughout Windows 10’s lifetime the Bluetooth options have been slowly moving to the modern Settings experience but the old Control Panel still exists and is used for some additional functionality – Virtual Serial ports are still in there.
The port can be either incoming – you have a listening service which other devices can connect to; or outgoing where you connect to a specific remote device. From Settings > Devices select “More Bluetooth options” from the righthand menu.

2020-11-22 (1)

From the resulting “classic” control panel applet select the “COM ports” tab to see configured ports or to set one up.


When I reworked the 32feet.NET library I decided not to include the COM port functionality as it’s only relevant to Windows and is for legacy code only. However I put together the required code to enumerate all the Bluetooth virtual COM ports on the system in a Gist which you can find here:-

I’ve just updated it as I noticed an issue with the null termination of the port names so it is now correctly trimmed. The class is very simple to use – the following will write out all the configured ports to the debug console:-

foreach (var p in BluetoothDiagnostics.BluetoothComPort.FindAll()) 
   System.Diagnostics.Debug.WriteLine($"{p.PortName} {p.DeviceId} {p.BluetoothAddress:X6}"); 

This will match the contents of the Control Panel shown above.

Bluetooth Xamarin

Asyncify a method and event response

It’s common to come across a pattern where you call a synchronous method to kick off an activity then await an event which gives you the result (or an error). In the process of building 32feet‘s Bluetooth LE library this became a familiar sight both for Android and iOS APIs.

The goal was to create a single async method which starts the process and completes when the response (good or bad) is received. The API model for the resulting cross-platform API is based on Web Bluetooth but with some extensions. The Web Bluetooth API is JavaScript based and each operation returns a promise – the .NET approach is to use a Task which you can await or ContinueWith.

In an early implementation I had used a WaitHandle and had a thread blocking on this but this is not a clean async approach. I needed a solution which would handle the method and event handler and use a standard Task. Luckily there is the TaskCompletionSource type which can facilitate this. It wraps a Task and allows you to set a result (or exception) which we’ll be setting inside the event handler. Therefore each resulting method follows basically the pattern below:-

TaskCompletionSource<IReadOnlyList<GattDescriptor>> tcs = new TaskCompletionSource<IReadOnlyList<GattDescriptor>>();
CBPeripheral peripheral = Service.Device;

void handler(object sender, CBCharacteristicEventArgs args)
   peripheral.DiscoveredDescriptor -= handler;

   if (args.Error != null)
      tcs.SetException(new Exception(args.Error.ToString()));

   List<GattDescriptor> descriptors = new List<GattDescriptor>();

   foreach (CBDescriptor cbdescriptor in _characteristic.Descriptors)
      descriptors.Add(new GattDescriptor(this, cbdescriptor));


peripheral.DiscoveredDescriptor += handler;

return tcs.Task;
  • Create a TaskCompletionSource with the required return type
  • Get the native object we’ll be starting the operation on
  • Create a handler for the event. Inside the handler we
    • Remove the event handler
    • Check the response – set either positive or negative result to TaskCompletionSource.
  • Add the event handler
  • Call the method to start the process
  • Return the TaskCompletionSource Task

I hope this provides a handy pattern to follow if you’re trying to use similar APIs, if not I’m sure it will at least jog my memory. I’ll post again soon about the full Bluetooth library in more depth.

Bluetooth Xamarin

Changes coming in Xamarin Android BluetoothSocket

While debugging an app I came across this new message in the Output window:-

"Not wrapping exception of type Java.IO.IOException from method `Read`. This will change in a future release."

When working with an RFComm service on Android you use a BluetoothSocket which in turn owns two Streams – one for Input and one for Output. Currently when there is a failure such as a broken connection the Read or Write operation will throw a Java.IO.IOException even though these streams are exposed as regular .NET Streams. It looks like Microsoft plan to change this behaviour and I presume this will be to wrap the exception in the equivalent System.IO.IOException. This makes a lot of sense and will improve consistency with other .NET flavours but it is something you need to be aware of as it will require code changes in your exception handling.

Desktop Code Windows Xamarin

WPF Activity in Xamarin Forms

I’ve recently been working on extending an existing product written in Xamarin Forms to Windows desktop and this has meant learning a lot more about the WPF implementation. Originally Xamarin Forms was created for mobile platforms such as Android and iOS (and Windows Phone – more on that later) but has since expanded to desktop platforms such as macOS, GTK and WPF on Windows (UWP originally straddled mobile and desktop). WPF is a more recent addition to Xamarin Forms and so understandably the implementation is less mature. It does follow the native look and feel closely but I soon found quite a jarring omission.

Our app uses the ActivityIndicator to represent indeterminate activity. On Android et al. this displays a rotating circular spinner but on WPF it was using an indeterminate progress bar squashed into a rectangular space which looked odd. This is understandable as there is no native control in WPF. I then had a flash of deja vu when thinking about something I wrote some time ago for Windows Phone!

Windows Phone 8.1 introduced the WinRT application model (from Windows 8) alongside the existing Silverlight approach but there were some complications and some types of apps could only be written in Silverlight. I created a library called Charming which added some of the Windows 8 style APIs to the Silverlight app model. This was later expanded and became Pontoon. One of the APIs was a Silverlight ProgressRing control which looked just like the Windows 8 equivalent. The progress ring still regularly appears in the Windows shell and is implemented in UWP. Since Silverlight is a subset of WPF it was straightforward to port it into the Xamarin Forms WPF platform library and modify the renderer for ActivityIndicator. Voila! A nice native looking ActivityIndicator for Windows desktop apps. This has now been merged into the Xamarin Forms code and should appear in a preview release soon alongside the MediaElement that also got merged recently. Until it hits a stable release you can add it via InTheHand.Forms too.

Bluetooth Windows Xamarin

New Year, New 32feet.NET Library

I’ve been working away on the Bluetooth code for some time. I’d been meaning to modernise the code and build with .NET Standard and NuGet in mind and ideally support more platforms. However the project has stopped and started a few times and gone down a few dead ends.

I had planned to rework the library into a full implementation of the UWP API set for Windows.Devices.Bluetooth covering Bluetooth Classic and Bluetooth LE but while I got quite far and had a set of working code for Windows, Android and iOS I decided that that wasn’t the right approach. Some aspects are clearly tied to underlying Windows concepts – the whole device finding/picking process uses magic strings and is not intuitive from a purely Bluetooth perspective. Also there was no real need to integrate both Bluetooth Classic and Bluetooth LE into a single library because there was very little shareable code and these could be maintained separately.

Instead I decided to go with a much simpler option. Build a new library around fundamentally the same API which the library has used for 16 years with a few necessary tweaks, cutting out a few of the more complex features and making it easy to do the most common tasks with Bluetooth Classic. The Bluetooth LE functionality will be revisited in 2020 with a more logical cross-platform API and packaged in a separate NuGet package (but still part of the 32feet.NET project).

What has changed

The library has been renamed InTheHand.Net.Bluetooth to make clear it is a different package and also to make clear the focus as I’ll no longer be including the IrDA functionality. It includes .NET Standard, Classic .NET Desktop, Android and iOS versions. As you can imagine there will be no new version for .NET Compact Framework. The iOS version is not yet complete but will have some limitations as imposed by the platform. I’ll discuss the details further in a separate blog post because it does some fun things over Apple’s quirky API and should make cross-platform Bluetooth Classic a lot easier for iOS.

In due course it will be joined by UWP, Linux and macOS implementations. Linux will require reworking for BlueZ 5 and macOS will be built on top of the IOBluetooth and IOBluetoothUI framework wrappers which are slowly taking shape. Potentially there may be other platforms too, such as Tizen, and hopefully we can grow the community around the project to target other platforms.

There is no BluetoothListener support in this release but it will be included in future builds (except on iOS). 95% of 32feet.NET users are using BluetoothClient to connect out to other devices so this wasn’t a top priority for this release.

The SelectBluetoothDeviceDialog which was heavily tied to WinForms has been replaced with the BluetoothDevicePicker. This offers a similar level of functionality but in a way which feels comfortable from any UI stack and supports async/await.

DiscoverDevices again is vastly simplified to remove concepts which only make sense in the Win32 implementation. Instead this method is used to discover “live” devices in the vicinity. It is accompanied by the new property PairedDevices which offers a more efficient way of retrieving paired devices without doing a live discovery.

When I started working on a modified version of the library for Unity development there was an odd problem. The Sockets stack in the Mono runtime doesn’t correctly support Bluetooth sockets and so the workaround was to P/Invoke the native Sockets APIs directly. In order to simplify the code the Win32 version uses a single implementation which calls the relevant Win32 APIs rather than using System.Net.Sockets. The library defines its own version of NetworkStream to be able to provide a familiar API which also not being tied to .NET Sockets. This makes it easier to support other platforms such as Android where the underlying implementation is completely different but can be wrapped inside a familiar .NET Stream. All of this means that the desktop .NET version of the library will work for the Windows target of a Unity project.

Where is it going?

The aim with this new version is to have a modern code base able to run on the current spectrum of .NET platforms – From IoT devices, to mobile phones to desktop PCs. Alongside the current Bluetooth Classic library and the Bluetooth LE library I’m also planning for other technologies to join the 32feet.NET project all aimed at handling short range device to device communications.

View the project on GitHub

See the latest InTheHand.Net.Bluetooth NuGet package


MediaElement Enhancements

In the process of digging into a native exception when disposing the MediaElementRenderer on iOS I came across the closest thing I would get to the source of the problem.

Do not subclass AVPlayerViewController

Because the resulting stacktrace contains redacted elements there was no hope of fixing the issue, so in the end I decided to rewrite the renderer again using the original (non-FastRenderer) approach. The control now behaves correctly and can be created/disposed repeatedly without causing any unexpected problems. I can’t say you can notice any performance hit in not using a fast renderer for this. Though this may be more of a problem if you’re trying to use multiple instances of the control or have some frequently changing screen layout.

I was also able to fix a small issue on Android where depending on the aspect ratio of the video and the size allocated to the control the content may appear left-aligned rather than centered. The result is the latest version of the package on NuGet. At some point I may need to roll these changes into the Xamarin Forms Pull-Request although this seems to have lost all traction after 18-months and is now the second oldest open pull request in the Xamarin Forms project. For the foreseeable future it looks like I’ll be maintaining the standalone control.