Xamarin Plugin.BLE why data read doesn't change? - c#

I'm stuck with this task about reading some data from my BLE Device.
I have a HM-19 DSD Tech Bluetooth LE module on my target machine, and I want communicate with it with my smartphone.
I'm using Xamarin with Plugin.BLE to try to achieve this.
There is my BluetoothPage.xaml.cs code
public partial class BluetoothPage : ContentPage
{
IAdapter adapter;
ObservableCollection<IDevice> devicesList;
ListView pageList;
public BluetoothPage()
{
adapter = CrossBluetoothLE.Current.Adapter;
deviceList = new ObservableCollection<IDevice>();
pageList = new ListView();
pageList.ItemSource = deviceList;
pageList.ItemSelected += ActionConnect;
pageStackLayout.Children.Add(pageList); // Layout component declared on BluetoothPage.xaml
}
private void ButtonScan(object sender, EventArgs e)
{
try
{
devicesList.Clear();
adapter.DeviceDiscovered += (s, a) =>
{
devicesList.Add(a.Device);
};
if(!adapter.isScanning)
{
await adapter.StartScanningForDevicesAsync();
}
}
catch(Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
private async void ActionConnect(object sender, SelectedItemChangedEventArgs se)
{
if(se != null)
{
try
{
if(adapter.IsScanning)
{
await adapter.StopScanningForDevicesAsync();
}
await adapter.ConnectToDeviceAsync((IDevice)pageList.SelectedItem);
IDevice device = adapter.ConnectedDevices[0];
// now get the service and characteristics of connected device
var services = await device.GetServicesAsync();
IService service = services[0];
var characteristics = await service.GetCharacteristicsAsync();
ICharacteristic characteristic = characteristics[0];
// now we can write and hopefully read values
byte[] data = { Coderequest.InitRequest, Coderequest.Info }; // My message to sendo to the machine to trigger his functions and his response
byte[] response = { 0 };
await characteristic.WriteAsync(data); // Send the data
response = await characteristic.ReadAsync() // Theorically we reading the response from the machine by BLE
}
catch(Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
}
}
When I launch my app:
I trigger the scan button and it works very fine
then I tap on the BLE device that I want, it connect perfectly
with a debugger on the target machine I can see that the data was really sent by app via BLE
But I didn't get the response expected, I'm reading always the same bytes (that are maybe default values) that aren't the bytes I expected.
The strange thing is that if I use the DSD Tech Demo App for the HM-19 module and execute same instructions (connect, send and read) it works! I send the data that trigger a response by machine and the demo app show the expect right bytes I sent from the machine.
So...how I can read that data? On the developer site the docs barely guide you on scan and connect, but on the write/read lacks of info. It is very disappointing and this plugin is the best on the Nuget repos.
Can anyone help me, where I'm doing bad?
This is a link for the plugin, maybe I missed something https://github.com/xabre/xamarin-bluetooth-le

After various try I got the solution:
To read effectively the data from the BLE module, is necessary to use the ValueUpdateHandler.
Then I changed my code in this way:
public partial class BluetoothPage : ContentPage
{
IAdapter adapter;
ObservableCollection<IDevice> devicesList;
ListView pageList;
List<byte> buffer = new List<byte>();
public BluetoothPage()
{
adapter = CrossBluetoothLE.Current.Adapter;
deviceList = new ObservableCollection<IDevice>();
pageList = new ListView();
pageList.ItemSource = deviceList;
pageList.ItemSelected += ActionConnect;
pageStackLayout.Children.Add(pageList); // Layout component declared on BluetoothPage.xaml
}
private void UpdatingValue(object sender, CharacteristicUpdateEventArgs args)
{
buffer.AddRange(args.Characteristic.Value);
}
private void ButtonScan(object sender, EventArgs e)
{
try
{
devicesList.Clear();
adapter.DeviceDiscovered += (s, a) =>
{
devicesList.Add(a.Device);
};
if(!adapter.isScanning)
{
await adapter.StartScanningForDevicesAsync();
}
}
catch(Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
private async void ActionConnect(object sender, SelectedItemChangedEventArgs se)
{
if(se != null)
{
try
{
if(adapter.IsScanning)
{
await adapter.StopScanningForDevicesAsync();
}
await adapter.ConnectToDeviceAsync((IDevice)pageList.SelectedItem);
IDevice device = adapter.ConnectedDevices[0];
// now get the service and characteristics of connected device
IService service = device.GetServiceAsync(Guid.Parse("0000ffe0-1000-8000-00805f9b34fb"));
ICharacteristic characteristic = service.GetCharacteristicAsync(Guid.Parse("0000ffe1-1000-8000-00805f9b34fb"));
// we attach the UpdateVale event to the characteristic
// and we start the service
characteristic.ValueUpdated += UpdatingValue;
await characteristic.StartUpdatesAsync();
// now we can write and hopefully read values
byte[] data = { Coderequest.InitRequest, Coderequest.Info }; // My message to sendo to the machine to trigger his functions and his response
await characteristic.WriteAsync(data); // Send the data
}
catch(Exception ex)
{
Console.WriteLine("ERROR: " + ex.Message);
}
}
}
}
So first I create a byte buffer to store the data: List<byte> buffer = new List<byte>().
I create a method for the event to catch the value readed and fill the buffer
private void UpdatingValue(object sender, CharacteristicUpdateEventArgs args)
{
buffer.AddRange(args.Characteristic.Value);
}
Finally I attach the method to the characteristic's EventHandler and start the service
characteristic.ValueUpdated += UpdatingValue;
await characteristic.StartUpdatesAsync();
Now every time the module send data to my app, the UpdateEvent triggers and fill the buffer, then print the buffer or show in some views to see the result.

BLE communication can be a pain particularly with Xamarin.
In any case asynchronous calls from your application may return before data has actually been sent to your end device.
This is due to several factors:
Operating system BLE driver behaviour - Any call that you make in your application code is handled by the operating system drivers. These may return before any data is actually handled by the BLE hardware.
BLE transport layer delays - BLE transmission of data is not instant. The data connection between two devices actually occurs within discrete time slots, between which the BLE transceiver is turned off to save power.
End device response time.
Most implementations of two way communication between devices using BLE use a minimum of two characteristics, one for data being sent and the other for data being received by a device e.g. device 1 receives data on the characteristic that device 2 sends on and vice versa. ​This avoids the possibility of any collision of data being sent by both parties.
You could try placing a delay in your code prior to polling for characteristic data and see if that helps, but its not an optimal solution.
I see that you are using your characteristic "anonymously", rather than using its uuid to select it. If the Bluetooth service supports more than one characteristic then you will need to use the uuid to ensure that you are using the correct one. The list of characteristics, much like the list of services and devices may not be returned in the same order whenever you request them.
You have the option of polling characteristics by reading them on a timed basis or setting up handlers for characteristic notification/indication events if the characteristic supports it and your BLE device uses that mechanism to show that data is ready.

The program is not working well, so I looked it up and found something similar,
What is missing is not finding the Bluetooth device.
I'm sorry, but if you can share, please send the entire program by e-mail.
thank you
kdg000#empas.com
AndroidManifest.xml
MainPage.xaml
<Button Text="Search" Clicked="searchDevice"/>
<ListView x:Name="DevicesList"
CachingStrategy="RecycleElement"
ItemSelected="DevicesList_OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding name}"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MainPage.xaml.cs
namespace employeeID
{
public partial class MainPage : ContentPage
{
IAdapter adapter;
IBluetoothLE ble;
ObservableCollection devicelist;
IDevice device;
public MainPage()
{
InitializeComponent();
ble = CrossBluetoothLE.Current;
adapter = CrossBluetoothLE.Current.Adapter;
devicelist = new ObservableCollection<IDevice>();
DevicesList.ItemsSource = devicelist;
}
private async void searchDevice(object sender, EventArgs e)
{
if (ble.State == BluetoothState.Off)
{
await DisplayAlert("Message", "Bluetooth is not available.", "OK");
}
else
{
try
{
devicelist.Clear();
adapter.ScanTimeout = 10000;
adapter.ScanMode = ScanMode.Balanced;
adapter.DeviceDiscovered += (s, a) =>
{
//devicelist.Add(new ScanResultViewModel() { Device = a.Device, IsConnect = "Status: " + a.Device.State.ToString(), Uuid = "UUID:" + a.Device.Id.ToString() });
devicelist.Add(a.Device);
};
//We have to test if the device is scanning
if (!ble.Adapter.IsScanning)
{
await adapter.StartScanningForDevicesAsync();
}
}
catch (Exception ex)
{
await DisplayAlert("Notice", ex.Message.ToString(), "Error !");
}
}
}
private async void DevicesList_OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
device = DevicesList.SelectedItem as IDevice;
var result = await DisplayAlert("Message", "Do you want to connect to this device?", "Connect", "Cancel");
if (!result)
return;
//Stop Scanner
await adapter.StopScanningForDevicesAsync();
try
{
await adapter.ConnectToDeviceAsync(device);
await DisplayAlert("Message", "Connect Status:" + device.State, "OK");
}
catch (DeviceConnectionException ex)
{
await DisplayAlert("Error", ex.Message, "OK");
}
}
}
}

Related

Cannot read Application Properties from EventHub

I managed to get connection with Azure IoTHub to send and receive device2Cloud Messages. I send the message with Microsoft.Azure.Devices.Client DeviceClient & consume the messages with Azure.Messaging.EventHubs.Consumer;
This is my code for sending the telemetry data
public async Task<IoTClientStatistics> SendDeviceToCloudMessageAsync(string messageContents)
{
if (_deviceClient == null || IsInitialized == false)
throw new InvalidAsynchronousStateException("You must call Initialize() before sending a message");
// IoT Hub message is a specific object that takes a byte array.
// You can then do many things...
Message message = new Message(Encoding.UTF8.GetBytes(messageContents));
// ...For example: add a custom application property to the message.
// An IoT hub can filter on these properties without access to the message body.
// Here we add the current runtime platform (Android, iOS, ...)
//message.Properties.Add("platform", Device.RuntimePlatform);
message.Properties.Add("name", "DeviceSample");
try
{
// Sending the event. If the event fails to be sent (no network, etc...)
// an exception will be raised.
await _deviceClient.SendEventAsync(message);
Console.WriteLine("Sent!");
// Updating statistics
_statistics.MessagesSent += 1;
_statistics.LastMessageSent = messageContents;
}
catch (Exception e)
{
_statistics.LastMessageSent = "Error: " + e;
_statistics.SendFailures += 1;
}
return _statistics;
}
This is my code for receiving the telemetry data
public async void ReceiveDeviceToCloudMessageAsync()
{
try
{
using CancellationTokenSource cancellationSource = new CancellationTokenSource();
cancellationSource.CancelAfter(TimeSpan.FromSeconds(45));
int eventsRead = 0;
int maximumEvents = 2;
var readEvents = _eventHubConsumerClient.ReadEventsAsync(cancellationSource.Token);
await foreach (PartitionEvent partitionEvent in readEvents)
{
string readFromPartition = partitionEvent.Partition.PartitionId;
byte[] eventBodyBytes = partitionEvent.Data.EventBody.ToArray();
yellowMessage($"\nMessage received on partition {partitionEvent.Partition.PartitionId}:");
string data = Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray());
greenMessage($"\tMessage body: {data}");
_statistics.MessagesReceived++;
_statistics.LastMessageReceived = data;
yellowMessage("\tApplication properties (set by device):");
foreach (KeyValuePair<string, object> prop in partitionEvent.Data.Properties)
{
PrintProperties(prop);
}
yellowMessage("\tSystem properties (set by IoT Hub):");
foreach (KeyValuePair<string, object> prop in partitionEvent.Data.SystemProperties)
{
PrintProperties(prop);
}
eventsRead++;
if (eventsRead >= maximumEvents)
{
break;
}
}
}
catch (TaskCanceledException e)
{
redMessage(e.ToString());
}
}
Problem is all the application properties I received at the partitionEvent DO NOT contain the application properties I added for the sent messages.
There is 1 possibility which still do not make sense to me, first my IoT device is configured to ignore message Application Properties. But I tested on another client app and the application properties were there normally (Using a Console App to send & a console app to receive with the same Key configuration)
Still struggle to understand why this is happening,
Is there any one expert on this topic ?

UWP C# UART RS485 DetachBuffer

I have previously posted regarding the issue but haven't really found the problem.
Recently, I found this post regarding detachbuffer and wonder if this could be the reason i encounter the problem.
I have my UART for RS485 using a FTDI USB to 485 cable connected to Raspberry Pi on Windows IoT Core.
I set a dispatchertimer at every 1second to transmit polling to respective field devices.
I am able to tx and rx the 485 data with no problem.
However, after the polling loop to about 20 times it just crash and exited the debug mode.
I used try & catch to trap the exception but could not get it. However, i manage to read the error message at the debug output pane - The program [0xBB0] PwD.exe' has exited with code -1073741811 (0xc000000d).
I wonder if i repeatedly transmit polling, dataWriteObject.DetachBuffer(); would cause the problem?
Thanks.
snippets of my code are as follow;
private void PollTimer_Tick(object sender, object e)
{
if (pollCounter <= maxDevice)
{
var a = pollCounter | 0x80;
pollCounter++;
TxAdr = Convert.ToByte(a);
TxCmd = TxPoll;
TxPollCard();
}
else pollCounter = 0;
}
private async void TxPollCard()
{
if (serialPort != null)
{
List<byte> data = new List<byte>();
data.Add(TxHeader);
data.Add(TxAdr);
data.Add(TxCmd);
TxChkSum = 0;
foreach (byte a in data)
{
TxChkSum += a;
}
TxChkSum = (byte)(TxChkSum - 0x80);
data.Add(TxChkSum);
try
{
// Create the DataWriter object and attach to OutputStream
dataWriteObject = new DataWriter(serialPort.OutputStream);
dataWriteObject.WriteBytes(data.ToArray());
Task<UInt32> storeAsyncTask;
// Launch an async task to complete the write operation
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
UInt32 bytesWritten = await storeAsyncTask;
dataWriteObject.DetachBuffer();
}
catch (Exception ex)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainStatusDisplay.Text = ex.Message;
});
}
}
else
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainStatusDisplay.Text = "No UART port found";
});
}
}
Update:
Additional test i did which i disconnect the devices & keep transmitting without expecting response, it didn't crash.
On the other hand, i stop transmit and only listen to the 485 bus, it didn't crash either.

Xabre BLE Android respectively slow at scanning and connecting

I have an application in which I use the Xabre library to connect to a BLE device.
On Android (I have tested on a Galaxy A40 and a Galaxy S7), I experience that the application utilize alot of time to respectively scan and connect.
I have changed the latency of my ScanMode to ScanMode.LowLatency - Which increased the scan-time a small bit. (though still unacceptable)
Additionally, when the device connects to a Device, it spends a lot of time and reconnects several times before connecting. (Yes, the device is within proximity, and other apps like LightBlue connects without any problems)
During connection I have set my ConnectParameters to ConnectParameters(true, true);.
I have not tested on iOS yet with this project, but have previously used Xabre for iOS where I didn't experience similar behavior.
The following code that I'm working with is:
public async void Connect(IDevice unit)
{
await adapter.StopScanningForDevicesAsync();
try
{
var parameters = new ConnectParameters(true, true);
await adapter.ConnectToDeviceAsync(unit, parameters);
//Add device
Bluetooth.Device = unit;
Console.Write(unit.Id);
//Add service and characteristics to Device object
Bluetooth.Service = await Bluetooth.Device.GetServiceAsync(Guid.Parse(Service_UUID));
Bluetooth.Characteristic = await Bluetooth.Service.GetCharacteristicAsync(Guid.Parse(Characteristic_UUID));
Characteristic_ValueUpdated();
}
catch (DeviceConnectionException e)
{
Console.WriteLine("Error: " + e);
Connect(unit);
}
}
public async void Disconnect()
{
try
{
await Characteristic.StopUpdatesAsync();
await adapter.DisconnectDeviceAsync(Device);
}
catch
{
}
}
public async void Scan()
{
adapter.ScanMode = ScanMode.LowLatency;
adapter.DeviceDiscovered += (s, a) =>
{
if (a.Device.Name == "Device_name")
{
Connect(a.Device);
}
};
await adapter.StartScanningForDevicesAsync();
}
On Galaxy S7 things generally run abit faster, but I still experience several reconnects.

HoloLens unable to send or receive data via BT and TCP

I am working on HoloLens (Unity-UWP) and trying to make a connection with PC (UWP) or Android phone work (Xamarin). So far I tried client and host with both Bluetooth and TCP (even two versions with different libraries) on Android and UWP. I kept the code entirely separated from user interface, so that it is easier to use, to understand and modular. An Action<string> is used to output results (error logs and sent messages).
Everything that is not on the HoloLens works fine (even though it's exactly the same code). It worked from PC (UWP) to Android with client and host switched. But it doesn't even work between HoloLens and PC (UWP). The behavior ranged from crashes (mostly for Bluetooth) to instant disconnection. The last tests resulted in disconnection once bytes are about to be received. It could even read the first 4 bytes (uint for the length of the following UTF-8 message), but then it was disconnected. The other devices seemed to work fine.
What I know: Capabilities are set, the code works, the issue is likely something that is common for everything that has to do with networking and HoloLens.
So the question is, is Unity or HoloLens incompatible with something I am using? What I used which is worth mentioning: StreamSocket, BinaryWriter, BinaryReader, Task (async, await). Or is HoloLens actively blocking communication with applications on other devices? I know it can connect to devices with Bluetooth and that it can connect via TCP, and it looks like people succeed to get it to work. Are there known issues? Or is there something with Unity that causes this - a bad setting maybe? Do I have to use async methods or only sync? Are there incompatibility issues with Tasks/Threads and Unity? Is this possibly the issue (inability to consent to permissions)?
Another thing to note is that I cannot ping HoloLens via its IP by using the cmd, even though the IP is correct.
I'd appreciate any advice, answer or guess. I can provide more information if requested (see also the comments below). I would suggest to focus on the TCP connection as it seemed to be working better and appears to be more "basic." Here is the code:
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Windows.Networking;
using Windows.Networking.Sockets;
#region Common
public abstract class TcpCore
{
protected StreamSocket Socket;
protected BinaryWriter BWriter;
protected BinaryReader BReader;
protected Task ReadingTask;
public bool DetailedInfos { get; set; } = false;
public bool Listening { get; protected set; }
public ActionSingle<string> MessageOutput { get; protected set; } = new ActionSingle<string> (); // Used for message and debug output. They wrap an Action and allow safer use.
public ActionSingle<string> LogOutput { get; protected set; } = new ActionSingle<string> ();
protected const string USED_PORT = "1337";
protected readonly Encoding USED_ENCODING = Encoding.UTF8;
public abstract void Disconnect ();
protected void StartCommunication ()
{
Stream streamOut = Socket.OutputStream.AsStreamForWrite ();
Stream streamIn = Socket.InputStream.AsStreamForRead ();
BWriter = new BinaryWriter (streamOut); //{ AutoFlush = true };
BReader = new BinaryReader (streamIn);
LogOutput.Trigger ("Connection established.");
ReadingTask = new Task (() => StartReading ());
ReadingTask.Start ();
}
public void SendMessage (string message)
{
// There's no need to send a zero length message.
if (string.IsNullOrEmpty (message)) return;
// Make sure that the connection is still up and there is a message to send.
if (Socket == null || BWriter == null) { LogOutput.Trigger ("Cannot send message: No clients connected."); return; }
uint length = (uint) message.Length;
byte[] countBuffer = BitConverter.GetBytes (length);
byte[] buffer = USED_ENCODING.GetBytes (message);
if (DetailedInfos) LogOutput.Trigger ("Sending: " + message);
BWriter.Write (countBuffer);
BWriter.Write (buffer);
BWriter.Flush ();
}
protected void StartReading ()
{
if (DetailedInfos) LogOutput.Trigger ("Starting to listen for input.");
Listening = true;
while (Listening)
{
try
{
if (DetailedInfos) LogOutput.Trigger ("Starting a listen iteration.");
// Based on the protocol we've defined, the first uint is the size of the message. [UInt (4)] + [Message (1*n)] - The UInt describes the length of the message (=n).
uint length = BReader.ReadUInt32 ();
if (DetailedInfos) LogOutput.Trigger ("ReadLength: " + length.ToString ());
MessageOutput.Trigger ("A");
byte[] messageBuffer = BReader.ReadBytes ((int) length);
MessageOutput.Trigger ("B");
string message = USED_ENCODING.GetString (messageBuffer);
MessageOutput.Trigger ("Received Message: " + message);
}
catch (Exception e)
{
// If this is an unknown status it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus (e.HResult) == SocketErrorStatus.Unknown)
{
// Seems to occur on disconnects. Let's not throw().
Listening = false;
Disconnect ();
LogOutput.Trigger ("Unknown error occurred: " + e.Message);
break;
}
else
{
Listening = false;
Disconnect ();
break;
}
}
}
LogOutput.Trigger ("Stopped to listen for input.");
}
}
#endregion
#region Client
public class GTcpClient : TcpCore
{
public async void Connect (string target, string port = USED_PORT) // Target is IP address.
{
try
{
Socket = new StreamSocket ();
HostName serverHost = new HostName (target);
await Socket.ConnectAsync (serverHost, port);
LogOutput.Trigger ("Connection successful to: " + target + ":" + port);
StartCommunication ();
}
catch (Exception e)
{
LogOutput.Trigger ("Connection error: " + e.Message);
}
}
public override void Disconnect ()
{
Listening = false;
if (BWriter != null) { BWriter.Dispose (); BWriter.Dispose (); BWriter = null; }
if (BReader != null) { BReader.Dispose (); BReader.Dispose (); BReader = null; }
if (Socket != null) { Socket.Dispose (); Socket = null; }
if (ReadingTask != null) { ReadingTask = null; }
}
}
#endregion
#region Server
public class GTcpServer : TcpCore
{
private StreamSocketListener socketListener;
public bool AutoResponse { get; set; } = false;
public async void StartServer ()
{
try
{
//Create a StreamSocketListener to start listening for TCP connections.
socketListener = new StreamSocketListener ();
//Hook up an event handler to call when connections are received.
socketListener.ConnectionReceived += ConnectionReceived;
//Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
await socketListener.BindServiceNameAsync (USED_PORT);
}
catch (Exception e)
{
LogOutput.Trigger ("Connection error: " + e.Message);
}
}
private void ConnectionReceived (StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args)
{
try
{
listener.Dispose ();
Socket = args.Socket;
if (DetailedInfos) LogOutput.Trigger ("Connection received from: " + Socket.Information.RemoteAddress + ":" + Socket.Information.RemotePort);
StartCommunication ();
}
catch (Exception e)
{
LogOutput.Trigger ("Connection Received error: " + e.Message);
}
}
public override void Disconnect ()
{
Listening = false;
if (socketListener != null) { socketListener.Dispose (); socketListener = null; }
if (BWriter != null) { BWriter.Dispose (); BWriter.Dispose (); BWriter = null; }
if (BReader != null) { BReader.Dispose (); BReader.Dispose (); BReader = null; }
if (Socket != null) { Socket.Dispose (); Socket = null; }
if (ReadingTask != null) { ReadingTask = null; }
}
}
#endregion
Coincidentially, I just implemented a BT connection between HoloLens and an UWP app. I followed the sample at https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BluetoothRfcommChat.
As capabilities, I set "Bluetooth" (of course), "Internet (Client & Server)" and "Private Networks (Client & Server)". The steps on the server side then are:
Create an RfcommServiceProvider for your own or an existing (eg OBEX object push) service ID.
Create a StreamSocketListener and wire its ConnectionReceived Event.
Bind the service Name on the listener: listener.BindServiceNameAsync(provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
If you have a custom service ID, set its name along with other attributes you may want to configure. See the sample linked above for this. I think, this is mostly optional.
Start advertising the BT service: provider.StartAdvertising(listener, true);
Once a client connects, there is a StreamSocket in the StreamSocketListenerConnectionReceivedEventArgs that you can use to create a DataReader and DataWriter on like on any other stream. If you only want to allow one client, you can also stop advertising now.
On the client side, you would:
Show the DevicePicker and let the user select the peer device. Do not forget setting a filter like picker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); You can also allow unpaired devices, but you need to call PairAsync before you can continue in step 2. Also, I think there is no way to circumvent the user consent dialogue in this case, so I would recommend pairing before. To be honest, I did not check whether the unpaired stuff works on HoloLens.
You get a DeviceInformation instance from the picker, which you can use to obtain a BT device like await BluetoothDevice.FromIdAsync(info.Id);
Get the services from the device like device.GetRfcommServicesAsync(BluetoothCacheMode.Uncached); and select the one you are interested in. Note that I found that the built-in filtering did not behave as expected, so I just enumerated the result and compared the UUIDs manually. I believe that the UWP implementation performs a case-sensitive string comparison at some point, which might lead to the requested service not showing up although it is there.
Once you found your service, which I will call s from now on, create a StreamSocket and connect using socket.ConnectAsync(s.ConnectionHostName, s.ConnectionServiceName, SocketProtectionLevel.PlainSocket);
Again, you can not create the stream readers and writers like on the server side.
The answer is Threading.
For whoever may have similar issues, I found the solution. It was due to Unity itself, not HoloLens specifically. My issue was that I wrote my code separately in an own class instead of commingle it with UI code, which would have made it 1. unreadable and 2. not modular to use. So I tried a better coding approach (in my opinion). Everybody could download it and easily integrate it and have basic code for text messaging. While this was no issue for Xamarin and UWP, it was an issue for Unity itself (and there the Unity-UWP solution as well).
The receiving end of Bluetooth and TCP seemed to create an own thread (maybe even something else, but I didn't do it actively), which was unable to write on the main thread in Unity, which solely handles GameObjects (like the output log). Thus I got weird log outputs when I tested it on HoloLens.
I created a new TCP code which works for Unity but not the Unity-UWP solution, using TcpClient/TcpListener, in order to try another version with TCP connection. Luckily when I ran that in the editor it finally pointed on the issue itself: The main thread could not be accessed, which would have written into the UI - the text box for the log output. In order to solve that, I just had to use Unity's Update() method in order to set the text to the output. The variables themselves still could be accessed, but not the GameObjects.

Why is BluetoothLEDevice.GattServices Empty

I am trying to communicate with a peripheral device without pairing it to Windows and I am using BluetoothLEAdvertisementWatcher to scan for devices in range. This is my WatcherOnReceived method:
async private void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
BluetoothLEDevice device = null;
BluetoothDevice basicDevice = null;
GattDeviceService services = null;
if (args.Advertisement.LocalName != "Nexus 6")
return;
_watcher.Stop();
device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
device.GattServicesChanged += Device_GattServicesChanged;
//basicDevice = await BluetoothDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
//services = await GattDeviceService.FromIdAsync(device.DeviceId);
lock (m_syncObj)
{
Debug.WriteLine("");
Debug.WriteLine("----------- DEVICE --------------");
Debug.WriteLine(args.ToString());
Debug.WriteLine(args.Advertisement.DataSections.Count);
foreach (var item in args.Advertisement.DataSections)
{
var data = new byte[item.Data.Length];
using (var reader = DataReader.FromBuffer(item.Data))
{
reader.ReadBytes(data);
}
Debug.WriteLine("Manufacturer data: " + BitConverter.ToString(data));
//Debug.WriteLine("Data : " + item.Data.ToString());
//Debug.WriteLine("Data capacity: " + item.Data.Capacity);
Debug.WriteLine("Data Type: " + item.DataType);
}
foreach (var md in args.Advertisement.ManufacturerData)
{
var data = new byte[md.Data.Length];
using (var reader = DataReader.FromBuffer(md.Data))
{
reader.ReadBytes(data);
}
Debug.WriteLine("Manufacturer data: " + BitConverter.ToString(data));
}
foreach (Guid id in args.Advertisement.ServiceUuids)
{
Debug.WriteLine("UUIDs: " + id.ToString() + " Count: " + args.Advertisement.ServiceUuids.Count);
//services = device.GetGattService(id);
}
Debug.WriteLine("Receive event...");
Debug.WriteLine("BluetoothAddress: " + args.BluetoothAddress.ToString("X"));
Debug.WriteLine("Advertisement.LocalName: " + args.Advertisement.LocalName);
Debug.WriteLine("AdvertisementType: " + args.AdvertisementType);
Debug.WriteLine("RawSignalStrengthInDBm: " + args.RawSignalStrengthInDBm);
if (device != null)
{
Debug.WriteLine("Bluetooth Device: " + device.Name);
Debug.WriteLine("Bluetooth Device conn status: " + device.ConnectionStatus);
Debug.WriteLine("Bluetooth DeviceId: " + device.DeviceId);
Debug.WriteLine("Bluetooth GettServices Count: " + device.GattServices.Count);
}
}
}
When a device is received I successfully create the BluetoothLEDevice from the args.BlutoothAddress but the device.GattServices are always empty and thus I can not use them to communicate with the device. Is the problem in the device or in the Windows API and what else can I try?
UPDATE 04/17 - CREATORS UPDATE
Microsoft have just updated their Bluetooth APIs. We now have unpaired BLE device communication!
They have very little documentation up at the moment but here is the much simplified new structure:
BleWatcher = new BluetoothLEAdvertisementWatcher
{
ScanningMode = BluetoothLEScanningMode.Active
};
BleWatcher.Start();
BleWatcher.Received += async (w, btAdv) => {
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
Debug.WriteLine($"BLEWATCHER Found: {device.name}");
// SERVICES!!
var gatt = await device.GetGattServicesAsync();
Debug.WriteLine($"{device.Name} Services: {gatt.Services.Count}, {gatt.Status}, {gatt.ProtocolError}");
// CHARACTERISTICS!!
var characs = await gatt.Services.Single(s => s.Uuid == SAMPLESERVICEUUID).GetCharacteristicsAsync();
var charac = characs.Single(c => c.Uuid == SAMPLECHARACUUID);
await charac.WriteValueAsync(SOMEDATA);
};
Much better now. As I said there is next to no documentation at the moment, I have a weird issue where my ValueChanged callback stops being called after 30 seconds or so, though that seems to be a separate scoping issue.
UPDATE 2 - SOME WEIRDNESS
After some more playing around with the new creators update there are a few more things to consider when building BLE apps.
You no longer need to run the Bluetooth stuff on the UI thread. There doesn't seem to be any permissions windows for BLE without pairing so no longer necessary to run on UI thread.
You may find that your application stops receiving updates from the device after a period of time. This is a scoping issue where objects are being disposed of that shouldn't. In the code above if you were listening to ValueChanged on the charac you may hit this issue. This is because the GattCharacteristic is disposed of before it should be, set the characteristic as a global rather than relying on it being copied in.
Disconnecting seems to be a bit broken. Quitting an app does not terminate connections. As such make sure you use the App.xml.cs OnSuspended callback to terminate your connections. Otherwise you get in a bit of a weird state where Windows seems to maintain (and keep reading!!) the BLE connection.
Well it has its quirks but it works!
This is still an issue with Windows Universal apps, the initial issue is that a device must be paired (not bonded) for GattServices to be discovered. However they also need to be discovered using Windows Devices rather than the BLE API. Microsoft are aware and are working on a new BLE API which does not require pairing but frankly their BLE support is pretty useless until this is ready.
Try pairing the device manually in Control Panel then list the services again. For some reason in Windows Universal Apps you can only list the Gatt Services for paired devices despite one of the advantages of BLE being that you do not need to pair with the device before using its services.
You can pair the device programmatically however depending on the platform the application is being run on this requires UI prompts. Therefore interrogating BLE services in the background is in-feasible. This needs to be fixed as it really stunts BLE support in UWP.
Its weird but works!
OLD ANSWER
Here is some sample code with a working BLE device connection:
private void StartWatcher()
{
ConnectedDevices = new List<string>();
Watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active };
Watcher.Received += DeviceFound;
DeviceWatcher = DeviceInformation.CreateWatcher();
DeviceWatcher.Added += DeviceAdded;
DeviceWatcher.Updated += DeviceUpdated;
StartScanning();
}
private void StartScanning()
{
Watcher.Start();
DeviceWatcher.Start();
}
private async void DeviceFound(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs btAdv)
{
if (!ConnectedDevices.Contains(btAdv.Advertisement.LocalName) && _devices.Contains(btAdv.Advertisement.LocalName))
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
{
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
if (device.GattServices.Any())
{
ConnectedDevices.Add(device.Name);
device.ConnectionStatusChanged += (sender, args) =>
{
ConnectedDevices.Remove(sender.Name);
};
SetupWaxStream(device);
} else if (device.DeviceInformation.Pairing.CanPair && !device.DeviceInformation.Pairing.IsPaired)
{
await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);
}
});
}
}
private async void DeviceAdded(DeviceWatcher watcher, DeviceInformation device)
{
if (_devices.Contains(device.Name))
{
try
{
var service = await GattDeviceService.FromIdAsync(device.Id);
var characteristics = service.GetAllCharacteristics();
}
catch
{
Debug.WriteLine("Failed to open service.");
}
}
}
private async void DeviceUpdated(DeviceWatcher watcher, DeviceInformationUpdate update)
{
var device = await DeviceInformation.CreateFromIdAsync(update.Id);
if (_devices.Contains(device.Name))
{
try
{
var service = await GattDeviceService.FromIdAsync(device.Id);
var characteristics = service.GetAllCharacteristics();
}
catch
{
Debug.WriteLine("Failed to open service.");
}
}
}

Categories

Resources