我正在尝试通过蓝牙在两部手机(例如两部 iPhone,甚至可能是跨平台)之间发送数据。
我一直在尝试使用 NuGet 的 Plugin.BluetoothLE,它最近似乎已经更新(2020 年 3 月),但是我似乎无法让任何示例代码正常工作(详情如下)。
如果有人能指出下面的问题,和/或是否有更好的方法通过蓝牙在两部手机之间发送数据,我将不胜感激。我的应用程序是时间相关的,可能没有wifi网络,所以蓝牙似乎是最好的选择......
当我在https://github.com/aritchie/bluetoothle实现演示服务器代码时,我收到以下错误:
中没有“AddService”方法
CrossBleAdapter.Current.CreateGattServer()
。
中没有“开始”方法
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, 0, x.Value.Length);
// do something value
});
await server.Start(new AdvertisementData
{
LocalName = "TestServer"
});
}
}
}