Search code examples
androidunity-game-enginebluetoothbluetooth-lowenergyhololens

How to send BLE advertisements from Android to Unity on HoloLens v2


I have already successfully used BLE advertising to broadcast information from one android device and receive it on another. Now I want the observer to be a Unity-app running on the HoloLens v2. The HoloLens does not need to connect to the android-device as I am aware that this does not seem to be supported. I am looking for a broadcaster -> observer solution.

As mentioned, I already have the broadcaster written and it works fine with android -> android. Now I have implemented my observer in Unity, largely inspired by this article, and it looks like this:

#if ENABLE_WINMD_SUPPORT
using System;
using Windows.Devices.Bluetooth.Advertisement;
#endif

public class DemoManager : MonoBehaviour
{

    [SerializeField] private StatusDisplay statusDisplay;


    private void Awake()
    {
#if ENABLE_WINMD_SUPPORT
        StartWatcher();
#else
        statusDisplay.Display("UWP APIs are not supported on this platform!");
#endif
    }

#if ENABLE_WINMD_SUPPORT
    private void StartWatcher()
    {
        void OnAdvertisementReceived(object sender, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            statusDisplay.Display("Advertisement received!");
        }

        try {
            BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
            watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(GetManufacturerData());
            watcher.Received += OnAdvertisementReceived;
            watcher.Start();
            
            statusDisplay.Display("Watcher started!");
        } catch (Exception e){
            statusDisplay.Display($"Watcher could not start! Error: {e.Message}");
        }
    }

    private BluetoothLEManufacturerData GetManufacturerData()
    {
        var manufacturerData = new BluetoothLEManufacturerData();
        manufacturerData.CompanyId = 1234;

        return manufacturerData;
    }
#endif

}

The StatusDisplay script is used for displaying text in a thread-safe way. The company-id 1234 is also used by the broadcaster.

My app has bluetooth capabilities (enabled both in the Unity-editor and in the built solution)

All looks very promising, but sadly the advertisement never seems to be received, or at the very least I am getting no corresponding status message.

Does anybody have any ide what might be wrong? Does anyone have any experience with this problem?


Solution

  • The problem was not with the Unity-side. My advertisement was malformed. I tested my advertisements with a observer that I also wrote myself on Android. So I accounted for the incorrect formatting there, but of course, the C# Advertisement-watcher did not.