0
我有一個與GATT心率監視器進行通信的應用程序。有時,傳感器失敗,我想重新初始化連接。如果舊連接失敗但是不起作用(請參見How to delete object?),我想將該連接包裝在類中並聲明新對象。然後我嘗試實施IDisposable,但我不知道如何。我也考慮過使用CancelationToken,但也不知道如何。這裏是代碼:如何發佈藍牙GATT連接
public class MainPage : Page
{
ConnectingObject conn;
MainPage()
{
this.InitializeComponent();
conn = new ConnectingObject();
}
public void cancelConnection()
{
conn.Dispose();
}
}
public class ConnectingObject : IDisposable
{
bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~HRGATTConnect()
{
Dispose(false);
}
async void Initialize()
{
try
{
var heartrateServices = await Windows.Devices.Enumeration
.DeviceInformation.FindAllAsync(GattDeviceService
.GetDeviceSelectorFromUuid(
GattServiceUuids.HeartRate),
null);
GattDeviceService firstHeartRateMonitorService = await
GattDeviceService.FromIdAsync(heartrateServices[0].Id);
//Debug.WriteLine("serviceName: " + heartrateServices[0].Name);
GattCharacteristic hrMonitorCharacteristics =
firstHeartRateMonitorService.GetCharacteristics(
GattCharacteristicUuids.HeartRateMeasurement)[0];
hrMonitorCharacteristics.ValueChanged += hrMeasurementChanged;
await hrMonitorCharacteristics
.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
}
catch (Exception e)
{
}
}
void hrMeasurementChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
{
try
{
byte[] hrData = new byte[eventArgs.CharacteristicValue.Length];
Windows.Storage.Streams.DataReader.FromBuffer(
eventArgs.CharacteristicValue).ReadBytes(hrData);
data_processing(hrData);
}
}
catch (Exception e)
{
}
}
謝謝。