I am trying to connect two devices using Plugin.BLE and send data from one device to another.
showDevices.xaml.cs
using Android.Bluetooth;
using Newtonsoft.Json;
using Plugin.BLE.Abstractions.Contracts;
using Plugin.BLE.Abstractions.Extensions;
using Plugin.BLE.Android;
using SampleData.Services;
using System.Text;
namespace SampleData;
public partial class ShowDevices : ContentPage
{
private List<string> _devices;
private IReadOnlyList<IDevice> _systemDevices;
private IAdapter _adapter;
public ShowDevices(List<string> devices, IReadOnlyList<IDevice> systemDevices, IAdapter adapter)
{
InitializeComponent();
this._devices = devices;
this._systemDevices = systemDevices;
this._adapter = adapter;
lst.ItemsSource = _devices;
}
private async void TextCell_Tapped(object sender, EventArgs e)
{
var device = _systemDevices.First();
var guid = device.Id;
try
{
_adapter.ConnectToKnownDeviceAsync(guid);
// await DisplayAlert("Response", $"{guid}", "Ok");
await DisplayAlert("Connected Established !!!", $"{device.Name}", "Ok");
}
catch(Exception ex)
{
await DisplayAlert("Exception", $"{ex.Message}", "Ok");
}
}
private async void SendData()
{
var Device = _systemDevices.FirstOrDefault();
if (Device != null)
{
var guid = Device.Id;
try
{
await DisplayAlert("Response", "Sending the data, please wait!", "Ok");
var services = await Device.GetServicesAsync();
var message = await APIService.GetData();
var convertedMsg = JsonConvert.SerializeObject(message);
foreach (var service in services)
{
var char_guid = Guid.Parse("0x2B2E");
var characteristic = await service.GetCharacteristicAsync(char_guid);
await DisplayAlert("char", $"{characteristic}", "Ok");
if (characteristic != null)
{
byte[] msg = Encoding.UTF8.GetBytes(convertedMsg);
await characteristic.WriteAsync(msg);
await DisplayAlert("Sent!!!", "Message sent successfully", "Ok");
}
else
{
await DisplayAlert("Characteristic not found!", "Couldn't find the specified characteristic", "Ok");
}
}
}
catch (Exception ex)
{
await DisplayAlert("Exception", $"{ex.Message}", "Ok");
}
}
else
{
await DisplayAlert("Error", "No device connected", "Ok");
}
}
private void sendBtn_Clicked(object sender, EventArgs e)
{
SendData();
}
}
The device is getting identified properly it is also returning appropriate id, but nothing was being sent, so added a breakpoint and found that the services are return null , in the following line.
var services = await Device.GetServicesAsync();
I am unable to figure out this issue.
Help appreciated!