I'm trying to send data between two phones (e.g. two iPhones, or maybe even cross platform) via bluetooth.
I've been trying to use Plugin.BluetoothLE from NuGet, which appears to have been updated recently (March 2020), however I can't seem to get any of the sample code working (details below).
I'd be grateful if anyone can point out what's wrong below, and/or if there's a better way of sending data between two phones through bluetooth. My application is time dependent, and there may not be a wifi network, so bluetooth seems to be the best option...
When I implement the demo server code available at https://github.com/aritchie/bluetoothle, I get the following errors:
No 'AddService' method within
CrossBleAdapter.Current.CreateGattServer()
.
No 'Start' method within
CrossBleAdapter.Current.CreateGattServer()
.
Here's the code I'm using (which I'm calling from the form).
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"
});
}
}
}