Skip to content

Commit

Permalink
Base fixes to allow BT Smart to work.
Browse files Browse the repository at this point in the history
  • Loading branch information
uwburn committed Jun 24, 2017
1 parent 3c4fca0 commit 6091ccc
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 54 deletions.
Binary file modified Cardia.v12.suo
Binary file not shown.
25 changes: 24 additions & 1 deletion Cardia/PresentationModel/Cardia.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Devices.Enumeration.Pnp;
using System.Threading;

namespace MGT.Cardia
{
Expand Down Expand Up @@ -130,7 +131,29 @@ private void InitializeBtDevices()
var task = DeviceInformation.FindAllAsync(
GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate),
new string[] { "System.Devices.ContainerId" });
BtSmartDevices = task.GetResults();

try
{
while(true)
{
Thread.Sleep(100);

var status = task.Status;

if (status == Windows.Foundation.AsyncStatus.Canceled || task.Status == Windows.Foundation.AsyncStatus.Error)
return;

if (status == Windows.Foundation.AsyncStatus.Completed)
{
BtSmartDevices = task.GetResults();
return;
}
}
}
finally
{
task.Close();
}
}

private void InitializeDevices()
Expand Down
1 change: 1 addition & 0 deletions Cardia/View/BtHrpFrm.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions Cardia/View/BtHrpFrm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.IO.Ports;
using MGT.Utilities.EventHandlers;
using Windows.Devices.Enumeration;
using System.Diagnostics;

namespace MGT.Cardia
{
Expand All @@ -33,10 +34,7 @@ public BtHrpFrm(Cardia cardia)
cardia.PacketProcessed += cardia_OnPacketProcessed;
btHrp.DeviceChanged += btHrp_DeviceChanged;

foreach (DeviceInformation device in devices)
{
cbDevices.Items.Add(device.Name);
}
cbDevices.DataSource = new BindingSource(devices, null);

if (devices.Count > 0)
{
Expand Down
102 changes: 53 additions & 49 deletions HRM/HRP/BtHrp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
Expand Down Expand Up @@ -36,7 +37,7 @@ public override string Name

private static TimeSpan START_TIMEOUT = new TimeSpan(0, 0, 10);
private static TimeSpan RUN_TIMEOUT = new TimeSpan(0, 0, 30);
private Timer timeoutTimer = new Timer(1000);
private System.Timers.Timer timeoutTimer = new System.Timers.Timer(1000);
private DateTime lastReceivedDate;

public BtHrp()
Expand Down Expand Up @@ -113,7 +114,10 @@ public DeviceInformation Device

deviceContainerId = "{" + device.Properties["System.Devices.ContainerId"] + "}";

if (backup.Equals(value))
if (backup == null && value == null)
return;

if ((backup == null && value != null) || !backup.Equals(value))
if (DeviceChanged != null)
DeviceChanged(this, value);
}
Expand All @@ -134,12 +138,12 @@ public override async void Start()
service = await GattDeviceService.FromIdAsync(device.Id);
if (service != null)
{
await ConfigureServiceForNotificationsAsync();
ConfigureServiceForNotificationsAsync();
}
else
{
FireTimeout("Bluetooth HRP device initialization failed");
throw new Exception("Bluetooth HRP device initialization failed");
//throw new Exception("Bluetooth HRP device initialization failed");
}
}
catch
Expand All @@ -149,49 +153,54 @@ public override async void Start()
Running = true;
}

private async Task ConfigureServiceForNotificationsAsync()
private void ConfigureServiceForNotificationsAsync()
{
try
new Thread(async () =>
{
// Obtain the characteristic for which notifications are to be received
characteristic = service.GetCharacteristics(CHARACTERISTIC_UUID)[CHARACTERISTIC_INDEX];

// While encryption is not required by all devices, if encryption is supported by the device,
// it can be enabled by setting the ProtectionLevel property of the Characteristic object.
// All subsequent operations on the characteristic will work over an encrypted link.
characteristic.ProtectionLevel = GattProtectionLevel.EncryptionRequired;

// Register the event handler for receiving notifications
characteristic.ValueChanged += Characteristic_ValueChanged;

// In order to avoid unnecessary communication with the device, determine if the device is already
// correctly configured to send notifications.
// By default ReadClientCharacteristicConfigurationDescriptorAsync will attempt to get the current
// value from the system cache and communication with the device is not typically required.
var currentDescriptorValue = await characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();

if ((currentDescriptorValue.Status != GattCommunicationStatus.Success) ||
(currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != CHARACTERISTIC_NOTIFICATION_TYPE))
Thread.CurrentThread.IsBackground = true;
try
{
// Set the Client Characteristic Configuration Descriptor to enable the device to send notifications
// when the Characteristic value changes
GattCommunicationStatus status =
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
CHARACTERISTIC_NOTIFICATION_TYPE);

if (status == GattCommunicationStatus.Unreachable)
// Obtain the characteristic for which notifications are to be received
characteristic = service.GetCharacteristics(CHARACTERISTIC_UUID)[CHARACTERISTIC_INDEX];
// While encryption is not required by all devices, if encryption is supported by the device,
// it can be enabled by setting the ProtectionLevel property of the Characteristic object.
// All subsequent operations on the characteristic will work over an encrypted link.
characteristic.ProtectionLevel = GattProtectionLevel.EncryptionRequired;
// Register the event handler for receiving notifications
Thread.Sleep(1000);
characteristic.ValueChanged += Characteristic_ValueChanged;
// In order to avoid unnecessary communication with the device, determine if the device is already
// correctly configured to send notifications.
// By default ReadClientCharacteristicConfigurationDescriptorAsync will attempt to get the current
// value from the system cache and communication with the device is not typically required.
var currentDescriptorValue = await characteristic.ReadClientCharacteristicConfigurationDescriptorAsync();
if ((currentDescriptorValue.Status != GattCommunicationStatus.Success) ||
(currentDescriptorValue.ClientCharacteristicConfigurationDescriptor != CHARACTERISTIC_NOTIFICATION_TYPE))
{
// Register a PnpObjectWatcher to detect when a connection to the device is established,
// such that the application can retry device configuration.
StartDeviceConnectionWatcher();
// Set the Client Characteristic Configuration Descriptor to enable the device to send notifications
// when the Characteristic value changes
GattCommunicationStatus status =
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
CHARACTERISTIC_NOTIFICATION_TYPE);
if (status == GattCommunicationStatus.Unreachable)
{
// Register a PnpObjectWatcher to detect when a connection to the device is established,
// such that the application can retry device configuration.
StartDeviceConnectionWatcher();
}
}
}
}
catch (Exception e)
{
FireTimeout("Bluetooth HRP device initialization failed");
throw new Exception("Bluetooth HRP device initialization failed");
}
catch (Exception e)
{
FireTimeout("Bluetooth HRP device initialization failed");
//throw new Exception("Bluetooth HRP device initialization failed");
}
}).Start();
}

private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
Expand Down Expand Up @@ -243,6 +252,8 @@ private void ProcessData(byte[] data, DateTimeOffset timestamp)

secondLastPacket = lastPacket;
lastPacket = btHrpPacket;

ProcessPackets();
}

private void ProcessPackets()
Expand Down Expand Up @@ -357,6 +368,7 @@ public override async void Stop()

if (characteristic != null)
{
characteristic.ValueChanged -= Characteristic_ValueChanged;
characteristic = null;
}

Expand Down Expand Up @@ -410,13 +422,5 @@ public override void Dispose()
watcher = null;
}
}

// Move this in the config form
public async void ListHRPDevices()
{
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(
GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.HeartRate),
new string[] { "System.Devices.ContainerId" });
}
}
}

0 comments on commit 6091ccc

Please sign in to comment.