В настоящее время я разрабатываю функциональность для существующего приложения UWP, чтобы проверить возможности устройства Bluetooth на устройстве.При этом я в настоящее время сталкиваюсь с двумя проблемами, одна из которых является основной: я создаю возможности Bluetooth на основе перечисления устройств и примера сопряжения из образцов Windows Universal. Ссылка здесь .Я могу успешно найти и перечислить BT-устройства и даже соединиться с ними, но странным образом я не могу отключить устройство.Код, который я сделал, находится здесь, я добавил целый класс, чтобы вы могли полностью протестировать его, если это необходимо:
class UWP_Bluetooth
{
DeviceWatcher deviceWatcher;
public StringBuilder btNetworkInfo = new StringBuilder();
//EventHandler<BluetoothWin32AuthenticationEventArgs> authHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(handleAuthRequests);
//BluetoothWin32Authentication authenticator = new BluetoothWin32Authentication(authHandler);
public ObservableCollection<RfcommChatDeviceDisplay> ResultCollection
{
get;
private set;
}
public void SearchForBTNetworks()
{
ResultCollection = new ObservableCollection<RfcommChatDeviceDisplay>();
string[] requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")",
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
//deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>((watcher, deviceInfo) =>
{
//Debug.WriteLine("Something added");
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
// Make sure device name isn't blank
if (deviceInfo.Name != "")
{
//Debug.WriteLine(deviceInfo.Name);
//Debug.WriteLine(deviceInfo.Id);
ResultCollection.Add(new RfcommChatDeviceDisplay(deviceInfo));
//rootPage.NotifyUser(
//String.Format("{0} devices found.", ResultCollection.Count),
//NotifyType.StatusMessage);
}
});
deviceWatcher.Updated += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) =>
{
//Debug.WriteLine("Something updated");
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
if (rfcommInfoDisp.Id == deviceInfoUpdate.Id)
{
rfcommInfoDisp.Update(deviceInfoUpdate);
break;
}
}
});
deviceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) =>
{
//Debug.WriteLine("Something removed");
// Find the corresponding DeviceInformation in the collection and remove it
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
if (rfcommInfoDisp.Id == deviceInfoUpdate.Id)
{
//Debug.WriteLine(rfcommInfoDisp.Name + " Removed");
ResultCollection.Remove(rfcommInfoDisp);
break;
}
}
});
deviceWatcher.Start();
Debug.WriteLine("Started searching BT devices");
//base.OnNavigatedTo(e);
}
public void StopSearchingBTNetworks()
{
if (deviceWatcher.Status == DeviceWatcherStatus.Started)
{
deviceWatcher.Stop();
Debug.WriteLine("Stopped searching BT devices");
}
}
public string DisplayBTDevices()
{
btNetworkInfo.AppendLine("ID,Name,Type,Pairing");
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
btNetworkInfo.Append($"{rfcommInfoDisp.Id}\t");
btNetworkInfo.Append($"{rfcommInfoDisp.Name}\t");
btNetworkInfo.Append($"{rfcommInfoDisp.GetType()}\t");
btNetworkInfo.Append($"{rfcommInfoDisp.DeviceInformation.Pairing.IsPaired}\t");
Debug.WriteLine(rfcommInfoDisp.Name);
Debug.WriteLine(rfcommInfoDisp.Id);
btNetworkInfo.AppendLine();
//Debug.WriteLine("\n");
}
return btNetworkInfo.ToString();
}
public async Task<int> PairWithSelectedAsync(string SSIDToPairWith)
{
int returnvalue = 5;
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
if (rfcommInfoDisp.Name == SSIDToPairWith)
{
returnvalue = 3;
Debug.WriteLine("Found device to connect to");
Debug.WriteLine(rfcommInfoDisp.Name);
Debug.WriteLine(rfcommInfoDisp.Id);
if (rfcommInfoDisp.DeviceInformation.Pairing.CanPair == true)
{
//rfcommInfoDisp.DeviceInformation.Properties.
DevicePairingResult pairingResult = await rfcommInfoDisp.DeviceInformation.Pairing.PairAsync();
if (pairingResult.Status == 0)
{
Debug.WriteLine("Connected with bluetooth device");
returnvalue = 0;
}
else
{
returnvalue = (int)pairingResult.Status;
}
}
}
}
if (returnvalue == 5)
Debug.WriteLine("Didn't find device");
return returnvalue;
}
public async Task<int> UnpairWithSelectedAsync(string SSIDToUnpairWith)
{
int returnvalue = 0;
foreach (RfcommChatDeviceDisplay rfcommInfoDisp in ResultCollection)
{
if (rfcommInfoDisp.Name == SSIDToUnpairWith)
{
Debug.WriteLine("Found device to unconnect from");
//Debug.WriteLine(rfcommInfoDisp.Name);
//Debug.WriteLine(rfcommInfoDisp.Id);
Debug.WriteLine(rfcommInfoDisp.DeviceInformation.Pairing.IsPaired);
//rfcommInfoDisp.DeviceInformation.Properties.
DeviceUnpairingResult pairingResult = await rfcommInfoDisp.DeviceInformation.Pairing.UnpairAsync();
Debug.WriteLine("Unpairing result: " +pairingResult.Status);
if (pairingResult.Status == 0 )
{
Debug.WriteLine("Successfully unpaired with bluetooth device");
returnvalue = 0;
}
else
{
returnvalue = (int)pairingResult.Status;
}
//Debug.WriteLine("\n");
}
}
return returnvalue;
}
}
public class RfcommChatDeviceDisplay : INotifyPropertyChanged
{
private DeviceInformation deviceInfo;
public RfcommChatDeviceDisplay(DeviceInformation deviceInfoIn)
{
deviceInfo = deviceInfoIn;
//UpdateGlyphBitmapImage();
}
public DeviceInformation DeviceInformation
{
get
{
return deviceInfo;
}
private set
{
deviceInfo = value;
}
}
public string Id
{
get
{
return deviceInfo.Id;
}
}
public string Name
{
get
{
return deviceInfo.Name;
}
}
public BitmapImage GlyphBitmapImage
{
get;
private set;
}
public void Update(DeviceInformationUpdate deviceInfoUpdate)
{
deviceInfo.Update(deviceInfoUpdate);
//UpdateGlyphBitmapImage();
}
/*
private async void UpdateGlyphBitmapImage()
{
DeviceThumbnail deviceThumbnail = await deviceInfo.GetGlyphThumbnailAsync();
BitmapImage glyphBitmapImage = new BitmapImage();
await glyphBitmapImage.SetSourceAsync(deviceThumbnail);
GlyphBitmapImage = glyphBitmapImage;
OnPropertyChanged("GlyphBitmapImage");
}
*/
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
В настоящее время основной проблемой является отсутствие возможности отключиться от устройства, уже связанного с устройством.Бонус: если кто-либо из вас знает, как удалить подсказку или всплывающее окно, которое появляется, если я пытаюсь выполнить сопряжение с устройством Bluetooth (само устройство имеет нулевую безопасность, не требующую ввода PIN-кода или подсказки), что также очень поможет.