使用蓝牙在两部手机之间发送数据我正在尝试使用Aritchie的Plugin.BluetoothLE插件

问题描述

我正在尝试通过蓝牙在两部手机(例如两部iPhone,甚至跨平台)之间发送数据。

我一直在尝试使用NuGet的plugin.bluetoothle,它似乎最近已更新(2020年3月),但是我似乎无法使任何示例代码正常工作(详细信息如下)。

如果有人能指出下面的问题,和/或如果有更好的方法通过蓝牙在两部手机之间发送数据,我将不胜感激。我的应用程序是时间相关的,并且可能没有wifi网络,因此蓝牙似乎是最好的选择...

实施https://github.com/aritchie/bluetoothle处的演示服务器代码时,出现以下错误

CrossBleAdapter.Current.CreateGattServer()中没有'AddService'方法

CrossBleAdapter.Current.CreateGattServer()中没有'开始'方法

这是我正在使用的代码(从表单中调用)。

using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Text;
using plugin.bluetoothle;
using plugin.bluetoothle.Server;

namespace BluetoothTest.Models
{
    public class BluetoothServer
    {

        public BluetoothServer()
        {

        }

        public void StartAdvertising()
        {
            //Guid[] guidArray = new Guid[1];
            List<Guid> guidArray;
            guidArray = new List<Guid>();
            guidArray.Add(Guid.NewGuid());

            CrossBleAdapter.Current.Advertiser.Start(new AdvertisementData
            {
                LocalName = "TestServer",ServiceUuids = guidArray
            });
        }

        public void StopAdvertising()
        {

        }

        public async void SetUpServer()
        {
            var server = CrossBleAdapter.Current.CreateGattServer();
            var service = server.AddService(Guid.NewGuid(),true);

            var characteristic = service.AddCharacteristic(
                Guid.NewGuid(),CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.Writenoresponse,GattPermissions.Read | GattPermissions.Write
            );

            var notifyCharacteristic = service.AddCharacteristic
            (
                Guid.NewGuid(),CharacteristicProperties.Indicate | CharacteristicProperties.Notify,GattPermissions.Read | GattPermissions.Write
            );

            Idisposable notifybroadcast = null;
            notifyCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                var @event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";

                if (notifybroadcast == null)
                {
                    this.notifybroadcast = Observable
                        .Interval(TimeSpan.FromSeconds(1))
                        .Where(x => notifyCharacteristic.SubscribedDevices.Count > 0)
                        .Subscribe(_ =>
                        {
                            Debug.WriteLine("Sending broadcast");
                            var dt = DateTime.Now.ToString("g");
                            var bytes = Encoding.UTF8.GetBytes(dt);
                            notifyCharacteristic.broadcast(bytes);
                        });
                }
            });

            characteristic.WhenReadReceived().Subscribe(x =>
            {
                var write = "HELLO";

                // you must set a reply value
                x.Value = Encoding.UTF8.GetBytes(write);

                x.Status = GattStatus.Success; // you can optionally set a status,but it defaults to Success
            });
            characteristic.WhenWriteReceived().Subscribe(x =>
            {
                var write = Encoding.UTF8.GetString(x.Value,x.Value.Length);
                // do something value
            });

            await server.Start(new AdvertisementData
            {
                LocalName = "TestServer"
            });
        }
    }
}

解决方法

确保在info.plist中设置了正确的密钥。有关更多详细信息,请参见this link

存在一个问题,就是在尝试创建Gatt Server时基础CBPeripheralManager仍处于未知状态。要解决此问题,您必须绕过CrossBleAdapter并自己处理顶级对象的创建。与给定的示例相比,API也有一些细微的变化,这使得它不那么容易上手。

代码

可以在此处找到完整的工作示例:https://github.com/jameswestgate/BleRedux

定义一个接口,然后可以在每个平台上实现

public interface IBleServer
{
    void Initialise();

    event EventHandler<Plugin.BluetoothLE.AdapterStatus> StatusChanged;

    IGattService CreateService(Guid uuid,bool primary);
    void AddService(IGattService service);
    void StartAdvertiser(AdvertisementData advertisingData);
    void StopAdvertiser();
}

实现界面,创建自己的CBPeripheralManager并公开 基础StatusChanged事件。在iOS上,您还需要创建一个广告商。

public class BleServer: IBleServer
{
    private CBPeripheralManager _manager;
    private GattServer _server;
    private Advertiser _advertiser;

    public event EventHandler<Plugin.BluetoothLE.AdapterStatus> StatusChanged;

    public void Initialise()
    {
        _manager = new CBPeripheralManager();

        _manager.StateUpdated += (object sender,EventArgs e) =>
        {
            var result = Plugin.BluetoothLE.AdapterStatus.Unknown;

            Enum.TryParse(_manager.State.ToString(),true,out result);

            StatusChanged?.Invoke(this,result);
        };
    }

    public IGattService CreateService(Guid uuid,bool primary)
    {
        if (_server == null) _server = new GattServer(_manager);

        return new GattService(_manager,_server,uuid,primary);
    }

    public void AddService(IGattService service)
    {
        _server.AddService(service);
    }

    public void StartAdvertiser(Plugin.BluetoothLE.Server.AdvertisementData advertisingData)
    {
        //advertisingData.ManufacturerData = new ManufacturerData();
        if (_advertiser != null) StopAdvertiser();

        _advertiser = new Advertiser(_manager);

        _advertiser.Start(advertisingData);
    }

    public void StopAdvertiser()
    {
        if (_advertiser == null) return;
        _advertiser.Stop();
    }
} 

在您的共享项目中,创建该类的实例,并按照原始示例添加服务和特征:

public partial class MainPage : ContentPage
{
    IBleServer _server;
    IDisposable notifyBroadcast = null;
    Plugin.BluetoothLE.Server.IGattService _service;

    public MainPage()
    {
        InitializeComponent();
    }

    void Button_Clicked(System.Object sender,System.EventArgs e)
    {
        if (_server == null)
        {
            Console.WriteLine("CREATING SERVER");
            _server = DependencyService.Get<IBleServer>();
            _server.Initialise();

            _server.StatusChanged += Peripheral_StatusChanged;
        }
    }

    private void Peripheral_StatusChanged(object sender,AdapterStatus status)
    {
        try
        {
            Console.WriteLine($"GOT STATUS CHANGED: {status}");

            if (status != AdapterStatus.PoweredOn) return;
            if (_service != null) return;

            Console.WriteLine($"CREATING SERVICE");
            _service = _server.CreateService(new Guid(BluetoothConstants.kFidoServiceUUID),true);

            Console.WriteLine($"ADDING CHARACTERISTICS");
            var characteristic = _service.AddCharacteristic(
                Guid.NewGuid(),CharacteristicProperties.Read | CharacteristicProperties.Write | CharacteristicProperties.WriteNoResponse,GattPermissions.Read | GattPermissions.Write
            );

            var notifyCharacteristic = _service.AddCharacteristic
            (
                Guid.NewGuid(),CharacteristicProperties.Indicate | CharacteristicProperties.Notify,GattPermissions.Read | GattPermissions.Write
            );

            Console.WriteLine($"SUBSCRIBING TO DEVICE SUBS");

            notifyCharacteristic.WhenDeviceSubscriptionChanged().Subscribe(e =>
            {
                var @event = e.IsSubscribed ? "Subscribed" : "Unsubcribed";

                if (notifyBroadcast == null)
                {
                    this.notifyBroadcast = Observable
                        .Interval(TimeSpan.FromSeconds(1))
                        .Where(x => notifyCharacteristic.SubscribedDevices.Count > 0)
                        .Subscribe(_ =>
                        {
                            Console.WriteLine("Sending Broadcast");
                            var dt = DateTime.Now.ToString("g");
                            var bytes = Encoding.UTF8.GetBytes(dt);
                            notifyCharacteristic.Broadcast(bytes);
                        });
                }
            });

            Console.WriteLine($"SUBSCRIBING TO READ");
            characteristic.WhenReadReceived().Subscribe(x =>
            {
                Console.WriteLine($"READ RECEIVED");
                var write = "HELLO";

                // you must set a reply value
                x.Value = Encoding.UTF8.GetBytes(write);
                x.Status = GattStatus.Success; // you can optionally set a status,but it defaults to Success
            });

            Console.WriteLine($"SUBSCRIBING TO WRITE");
            characteristic.WhenWriteReceived().Subscribe(x =>
            {
                var write = Encoding.UTF8.GetString(x.Value,x.Value.Length);
                // do something value
                Console.WriteLine($"WRITE RECEIVED: {write}");
            });

            //Also start advertiser (on ios)
            var advertisingData = new AdvertisementData
            {
                LocalName = "FIDO Test Server",ServiceUuids = new List<Guid> { new Guid(BluetoothConstants.kFidoServiceUUID) } //new Guid(DeviceInformationService),};

            //Now add the service
            Console.WriteLine($"ADDING SERVICE");
            _server.AddService(_service);

            Console.WriteLine($"STARTING ADVERTISER");
            _server.StartAdvertiser(advertisingData);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"EXCEPTION: {ex}");
        }
    }
}

使用诸如 nFR Connect 之类的工具,您现在应该能够连接到服务器并查询特征。写入时可能需要将数据编码为utf-8(参见图片)

nRF write example