private async void TimerElapsed(object sender, ElapsedEventArgs e) { var protocolId = _deviceInformation.Properties["System.Devices.Aep.ProtocolId"] as Guid?; if (protocolId.HasValue) { if (protocolId.Value == Guid.Parse("{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}")) { using (var device = await BluetoothDevice.FromIdAsync(_deviceInformation.Id)) { await device.GetRfcommServicesAsync(BluetoothCacheMode.Uncached); } } // API is unreliable/broken, cutting Bluetooth LE support //else //{ // using (var device = await BluetoothLEDevice.FromIdAsync(_deviceInformation.Id)) // { // // Do something to force a connection // } //} OnPropertyChanged("SignalStrength"); OnPropertyChanged("IsPresent"); OnPropertyChanged("LastUpdated"); } _signalStrengthTimer.Start(); }
//https://stackoverflow.com/questions/45191412/deviceinformation-pairasync-not-working-in-wpf private async Task DoUnPairing(BTDeviceInfo info) { try { using (BluetoothDevice device = await BluetoothDevice.FromIdAsync(info.Address)) { this.log.Info("DoUnPairing", () => string.Format("'{0}'", info.Name)); DeviceUnpairingResult result = await device.DeviceInformation.Pairing.UnpairAsync(); this.log.Info("DoUnPairing", () => string.Format("'{0}' Unpair status {1}", info.Name, result.Status.ToString())); this.BT_UnPairStatus?.Invoke(this, new BTUnPairOperationStatus() { Name = info.Name, UnpairStatus = result.Status.ConvertStatus(), IsSuccessful = result.Status.IsSuccessful(), }); } } catch (Exception e) { WrapErr.SafeAction(() => { this.BT_UnPairStatus?.Invoke(this, new BTUnPairOperationStatus() { Name = info.Name, UnpairStatus = BT_UnpairingStatus.Failed, IsSuccessful = false, }); }); } }
private async Task Connect(DeviceInformation deviceInformation) { // Perform device access checks before trying to get the device. // First, we check if consent has been explicitly denied by the user. var accessStatus = DeviceAccessInformation.CreateFromId(deviceInformation.Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { throw new UnauthorizedAccessException("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"); } var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInformation.Id); // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call) var rfcommServices = await bluetoothDevice.GetRfcommServicesAsync(); RfcommDeviceService bluetoothService = null; foreach (var service in rfcommServices.Services) { System.Diagnostics.Debug.WriteLine("Service {0}: {1}", service.ConnectionHostName, service.ConnectionServiceName); if (service.ServiceId.Uuid == RfcommServiceId.SerialPort.Uuid) { bluetoothService = service; break; } } if (bluetoothService != null) { bluetoothDevice.ConnectionStatusChanged += BluetoothDevice_ConnectionStatusChanged; var device = new UwpRfcommDevice(deviceInformation, bluetoothService); connectedDevices.Add(device.deviceInfo.Id, device); DeviceConnected?.Invoke(device); } }
private async void ButtonConnect_Click(object sender, RoutedEventArgs e) { try { BluetoothLEDevice bluetoothLeDevice; bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BluetoothLE#BluetoothLEdc:85:de:1f:8d:db-75:74:d3:9d:aa:73"); bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BluetoothLE#BluetoothLEdc:85:de:1f:8d:db-70:a9:b9:1c:80:94"); bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BluetoothLE#BluetoothLEdc:85:de:1f:8d:db-6b:6e:7a:3a:c1:da"); bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BluetoothLE#BluetoothLEdc:85:de:1f:8d:db-6a:ac:e9:a9:d5:fa"); bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BluetoothLE#BluetoothLEdc:85:de:1f:8d:db-57:59:da:9d:0e:39"); bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BluetoothLE#BluetoothLEdc:85:de:1f:8d:db-48:fd:28:27:e8:9e"); BluetoothDevice bluetoothDevice; bluetoothDevice = await BluetoothDevice.FromIdAsync("Bluetooth#Bluetoothdc:85:de:1f:8d:db-3c:f7:a4:87:75:aa"); //bluetoothDevice = await BluetoothDevice. } catch (Exception ex) { #if DEBUG Debug.WriteLine($"BluetoothDevice.FromIdAsync, error:{ex}"); #endif } }
public async static Task Main(string[] args) { select: Console.Clear(); var deviceId = await SelectDevice(); if (string.IsNullOrEmpty(deviceId)) { goto select; } else if (deviceId == "q") { return; } DrawLine(); BluetoothDevice BTDevice = await BluetoothDevice.FromIdAsync(deviceId); PbapClientSession = new BluetoothPbapClientSession(BTDevice); try { await PbapClientSession.Connect(); } catch (BluetoothObexSessionException ex) { Console.WriteLine(ex.Message); goto restart; } DrawLine(); try { await PbapClientSession.ObexClient.PullPhoneBook("telecom/cch.vcf"); } catch (ObexRequestException ex) { Console.WriteLine(ex.Message); goto restart; } restart: Console.WriteLine("Enter q to exit or other keys to try again..."); var c = Console.ReadKey(); if (PbapClientSession != null) { PbapClientSession.Dispose(); } if (c.KeyChar.Equals('q')) { return; } else { goto select; } }
/// <summary> /// 这个函数以后还是想办法废掉的好 /// 测试一下FromIdAsync到底是真的老老实实做的还是直接从本地的 /// </summary> /// <returns></returns> public async Task RfcommConnectAsync() { Win10RfcommDevice = await BluetoothDevice.FromIdAsync(Win10DeviceInformaion.Id); System.Diagnostics.Debug.WriteLine("Rfcomm Connected:" + Win10RfcommDevice.Name); Guid RfcommChatServiceUuid = Guid.Parse("34B1CF4D-1069-4AD6-89B6-E161D79BE4D8"); }
private async void Connect_Click(object sender, RoutedEventArgs e) { bluetoothList.Items.Clear(); foreach (var info in await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector())) { bluetoothList.Items.Add(await BluetoothDevice.FromIdAsync(info.Id)); } }
/// <summary>Discover devices</summary> /// <param name="paired">If discovery limited to paired or non paired devices</param> private async void DoDiscovery(bool paired) { try { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync( BluetoothDevice.GetDeviceSelectorFromPairingState(paired)); foreach (DeviceInformation info in devices) { try { this.log.Info("DoDiscovery", () => string.Format("Found device {0}", info.Name)); BTDeviceInfo deviceInfo = new BTDeviceInfo() { Name = info.Name, Connected = false, Address = info.Id, }; using (BluetoothDevice device = await BluetoothDevice.FromIdAsync(info.Id)) { deviceInfo.Connected = device.ConnectionStatus == BluetoothConnectionStatus.Connected; deviceInfo.CanPair = this.GetBoolProperty(device.DeviceInformation.Properties, KEY_CAN_PAIR, false); deviceInfo.IsPaired = this.GetBoolProperty(device.DeviceInformation.Properties, KEY_IS_PAIRED, false); // Container Id also //device.DeviceAccessInformation.CurrentStatus == DeviceAccessStatus. // Allowed, denied by user, by system, unspecified //device.DeviceInformation.EnclosureLocation.; // Dock, lid, panel, etc //device.DeviceInformation.IsDefault; //device.DeviceInformation.IsEnabled; //device.DeviceInformation.Kind == //AssociationEndpoint, Device, etc //device.DeviceInformation.Properties if (device.ClassOfDevice != null) { deviceInfo.DeviceClassInt = (uint)device.ClassOfDevice.MajorClass; deviceInfo.DeviceClassName = string.Format("{0}:{1}", device.ClassOfDevice.MajorClass.ToString(), device.ClassOfDevice.MinorClass.ToString()); //device.ClassOfDevice.ServiceCapabilities == BluetoothServiceCapabilities.ObjectTransferService, etc } // Serial port service name // Bluetooth#Bluetooth10:08:b1:8a:b0:02-20:16:04:07:61:01#RFCOMM:00000000:{00001101-0000-1000-8000-00805f9b34fb} // TODO - determine if all the info in device is disposed by the device.Dispose } // end of using (device) this.DeviceDiscovered?.Invoke(this, deviceInfo); } catch (Exception ex2) { this.log.Exception(9999, "", ex2); } } this.DiscoveryComplete?.Invoke(this, true); } catch (Exception e) { this.log.Exception(9999, "", e); this.DiscoveryComplete?.Invoke(this, false); } }
public async void Connect() { // Repair the device if needed if (!devInfo.Pairing.IsPaired) { Debug.WriteLine("Pairing..."); DeviceInformationCustomPairing customPairing = devInfo.Pairing.Custom; customPairing.PairingRequested += PairingRequested; DevicePairingResult result = await customPairing.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None); customPairing.PairingRequested -= PairingRequested; Debug.WriteLine("Pair status: " + result.Status); } else { Debug.WriteLine("Already Paired"); } // Get the actual device try { device = await BluetoothDevice.FromIdAsync(devInfo.Id); device.ConnectionStatusChanged += ConnectionStatusChanged; } catch (Exception ex) { Debug.WriteLine("Bluetooth Not Available"); return; } //try { var services = await device.GetRfcommServicesAsync(); if (services.Services.Count > 0) { var service = services.Services[0]; stream = new StreamSocket(); //try { await stream.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName); //} catch (Exception ex) { //Debug.WriteLine("Could not connect to device"); //} Debug.WriteLine("Stream Connected"); rx = new DataReader(stream.InputStream); rx.InputStreamOptions = InputStreamOptions.Partial; tx = new DataWriter(stream.OutputStream); OnConnected(); } /*} catch (Exception ex) { * Debug.WriteLine("Failed to get services"); * return; * }*/ }
/// <summary> /// This is a async task to connect to device and create _socket, _dataReader and _dataWriter object. /// </summary> /// <param name="BtdeviceId"></param> /// <returns> boolean</returns> public async Task <Boolean> ConnectAsyncFromId(string BtdeviceId) { deviceId = BtdeviceId; StopDeviceWatcher(); bluetoothDevice = await BluetoothDevice.FromIdAsync(BtdeviceId); if (bluetoothDevice != null) { if (deviceConnectedCallback != null) { deviceConnectedCallback(this, deviceInformation); } if (appSuspendEventHandler == null || appResumeEventHandler == null) { RegisterForAppEvents(); } if (deviceAccessEventHandler == null) { RegisterForDeviceAccessStatusChange(); } var _rfcomService = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.SerialPort, BluetoothCacheMode.Uncached); if (_rfcomService.Services.Count <= 0) { rootPage.StatusBar("Serial service not found on " + bluetoothDevice.Name, BarStatus.Error); return(false); } var serialService = _rfcomService.Services[0]; lock (this) { _socket = new StreamSocket(); } // for marking this as crtical section. try { // socket initializesd await _socket.ConnectAsync(serialService.ConnectionHostName, serialService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); rootPage.StatusBar("connection to device done sucessfully", BarStatus.Sucess); // reader and writer assingment. _serialWriter = new DataWriter(_socket.OutputStream); _serialReader = new DataReader(_socket.InputStream); } catch (Exception e) { rootPage.StatusBar(e.ToString(), BarStatus.Error); } } return(bluetoothDevice != null); }
public RoboBluetoothWatcher() { string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; _watcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")", requestedProperties, DeviceInformationKind.AssociationEndpoint); _watcher.Added += async(sender, args) => { var info = await BluetoothDevice.FromIdAsync(args.Id); RoboBluetoothDevice device; lock (_threadLock) { device = new RoboBluetoothDevice(info.Name, info.BluetoothAddress, args.Id); _discoverDevices[info.BluetoothAddress] = device; } NewDeviceDiscovered(device); }; _watcher.Updated += async(sender, args) => { var info = await BluetoothDevice.FromIdAsync(args.Id); RoboBluetoothDevice device; var nameChanged = !string.IsNullOrEmpty(info.Name) && _discoverDevices[info.BluetoothAddress].Name != info.Name; lock (_threadLock) { device = new RoboBluetoothDevice(info.Name, info.BluetoothAddress, args.Id); _discoverDevices[info.BluetoothAddress] = device; } DeviceDiscovered(device); if (nameChanged) { DeviceNameChanged(device); } }; _watcher.Removed += async(sender, args) => { var info = await BluetoothDevice.FromIdAsync(args.Id); RoboBluetoothDevice device; lock (_threadLock) { device = new RoboBluetoothDevice(info.Name, info.BluetoothAddress, args.Id); _discoverDevices.Remove(info.BluetoothAddress); } DeviceTimeout(device); }; _watcher.Stopped += (sender, args) => { StoppedListening(); }; }
private async Task LoadDeviceList() { deviceList.Items.Clear(); var list = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); foreach (var info in list) { var device = await BluetoothDevice.FromIdAsync(info.Id); var item = new ComboboxItem <string>(device.Name, info.Id); deviceList.Items.Add(item); } }
IReadOnlyCollection <BluetoothDeviceInfo> DoDiscoverDevices(int maxDevices) { List <BluetoothDeviceInfo> results = new List <BluetoothDeviceInfo>(); var devices = DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(false)).GetResults(); foreach (var device in devices) { var bluetoothDevice = BluetoothDevice.FromIdAsync(device.Id).GetResults(); results.Add(bluetoothDevice); } return(results.AsReadOnly()); }
private async void ConnectButton_Click(object sender, RoutedEventArgs e) { AvatarDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as AvatarDeviceDisplay; var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInfoDisp.Id);; var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync( RfcommServiceId.FromUuid(avatarServiceUUID), BluetoothCacheMode.Uncached); if (rfcommServices.Services.Count > 0) { chatService = rfcommServices.Services[0]; } else { Status.Text = "Could not discover the avatar service on the remote device"; return; } deviceWatcher.Stop(); lock (this) { chatSocket = new StreamSocket(); } try { await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); EnableActivityDetectionAsync(); } catch (Exception ex) { switch ((uint)ex.HResult) { case (0x80070490): // ERROR_ELEMENT_NOT_FOUND Status.Text = "Please verify that you are running the Avatar server."; RunButton.IsEnabled = true; break; default: throw; } } }
public static async Task <BluetoothDevice> GetFirstPairedDeviceAvailable() { var serialDeviceCollection = await FindPairedDevices(); var serialDeviceInformation = serialDeviceCollection.FirstOrDefault(); if (serialDeviceInformation != null) { return(await BluetoothDevice.FromIdAsync(serialDeviceInformation.Id)); } else { return(null); } }
private async void Button_Click_GetRfcommServices(object sender, RoutedEventArgs e) { BluetoothDevice bt = await BluetoothDevice.FromIdAsync(ViewModel.SelectedDevice.Id); RfcommDeviceServicesResult result = await bt.GetRfcommServicesAsync(); foreach (var b in bt.SdpRecords) { Debug.WriteLine(Encoding.UTF8.GetString(b.ToArray())); } foreach (var service in result.Services) { Debug.WriteLine(service.ServiceId.AsString() + " " + service.ConnectionHostName + " " + service.ConnectionServiceName); } }
public async Task InitBluetoothClient() { var informations = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector()); foreach (var info in informations) { Console.WriteLine(info.Name); } if (informations.Count == 0) { Console.WriteLine("デバイスが見つかりません"); return; } var bluetoothDevice = await BluetoothDevice.FromIdAsync(informations[0].Id); var rfcommServices = await bluetoothDevice.GetRfcommServicesAsync(); if (rfcommServices.Services.Count == 0) { Console.WriteLine("サービスがみつかりません"); return; } var _service = rfcommServices.Services[0]; var services = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush)); if (services.Count != 0) { Console.WriteLine(services[0].Id); _service = await RfcommDeviceService.FromIdAsync(services[0].Id); } else { Console.WriteLine("サービスが見つかりませんでした"); return; } var _socket = new StreamSocket(); await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); StartStream(_socket); }
private static IAsyncAction PingDevice(string id) { return(AsyncInfo.Run(async(cancel) => { var bl = await BluetoothDevice.FromIdAsync(id); var service = (await bl.GetRfcommServicesAsync()).Services.FirstOrDefault(); if (service == null) { return; } using (var socket = new StreamSocket()) { await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionWithAuthentication); } })); }
private async Task <BluetoothDeviceInfo> DoPickSingleDeviceAsync() { Rect bounds = Rect.Empty; var deviceInfo = await picker.PickSingleDeviceAsync(bounds); if (deviceInfo == null) { return(null); } var device = await BluetoothDevice.FromIdAsync(deviceInfo.Id); var access = await device.RequestAccessAsync(); return(new BluetoothDeviceInfo(device)); }
IEnumerable <BluetoothDeviceInfo> GetPairedDevices() { var t = DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); t.AsTask().ConfigureAwait(false); t.AsTask().Wait(); var devices = t.GetResults(); foreach (var device in devices) { var td = BluetoothDevice.FromIdAsync(device.Id).AsTask(); td.Wait(); var bluetoothDevice = td.Result; yield return(bluetoothDevice); } yield break; }
public async Task <bool> TryAndConnectToDevice() { #if WINDOWS_UWP try { m_btDevice = await BluetoothDevice.FromIdAsync(DeviceId); } catch (Exception ex) { Debug.Write(ex); } return(m_btDevice != null); #else await Task.CompletedTask; return(false); #endif }
private async Task GetDevice() { if (device != null) { return; } device = await BluetoothDevice.FromIdAsync(LightID); if (device != null) { return; } await GetAllDevices(); device = await BluetoothDevice.FromIdAsync(LightID); }
async Task <BluetoothDevice> IBluetoothService.FromIdAsync(string id) { var device = await BluetoothDevice.FromIdAsync(id); if (device != null) { var result = await device.GetRfcommServicesAsync(); foreach (var service in result.Services) { var attributes = await service.GetSdpRawAttributesAsync(); foreach (var attr in attributes) { } } } return(device); }
public override async void Connect() { var accessStatus = DeviceAccessInformation.CreateFromId(Id).CurrentStatus; if (accessStatus == DeviceAccessStatus.DeniedByUser) { _logger.NotifyUserError("BT Channel", "This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices"); return; } try { var bluetoothDevice = await BluetoothDevice.FromIdAsync(Id); if (bluetoothDevice == null) { _logger.NotifyUserError("BT Channel", "Bluetooth Device returned null. Access Status = " + accessStatus.ToString()); return; } var services = await bluetoothDevice.GetRfcommServicesAsync(); if (!services.Services.Any()) { _logger.NotifyUserError("BT Channel", "Could not discover any remote devices."); return; } _deviceService = services.Services.FirstOrDefault(); if (await ConnectAsync()) { InvokeConnected(); } } catch (Exception ex) { _logger.NotifyUserError("BT Channel", ex.Message); return; } }
public async void Connect(string devid) { this.Logger.Info("入力デバイスへの接続開始:" + devid); this.StartingSendTaskFlag = true; this.StartingReceiveTaskFlag = true; this.SelectedDeviceInfo = (from i in KnownDeviceList where i.Id == devid select i).First(); try { SelectedDevice = await BluetoothDevice.FromIdAsync(this.SelectedDeviceInfo.Id); var rfcommsrv = await SelectedDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceUuid), BluetoothCacheMode.Uncached); RfcommService = rfcommsrv.Services[0]; var attributes = await RfcommService.GetSdpRawAttributesAsync(); var attributereader = DataReader.FromBuffer(attributes[0x100]); var attributetype = attributereader.ReadByte(); var servicenamelength = attributereader.ReadByte(); attributereader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16BE; Socket = new StreamSocket(); await Socket.ConnectAsync(RfcommService.ConnectionHostName, RfcommService.ConnectionServiceName); SocketWriter = new DataWriter(Socket.OutputStream); SocketReader = new DataReader(Socket.InputStream); this.RunningFlag = true; this.SendTask = Task.Run(() => { this.RunSend(); }); this.ReceiveTask = Task.Run(() => { this.RunReceive(); }); this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Connect)); } catch (Exception ex) { this.Logger.Error(ex, "入力デバイスへの接続失敗"); this.RunningFlag = false; this.StartingSendTaskFlag = false; this.StartingReceiveTaskFlag = false; this.ConnectStatusChanged?.Invoke(this, new AsyncCompletedEventArgs(null, false, BluetoothApplicationConnectStatus.Error)); } }
public async void Setup() { foreach (var i in json.Devices) { if (i.DeviceType == "Bluetooth") { BluetoothDevice bd; if (i.DeviceAddress.StartsWith("Bluetooth")) { bd = await BluetoothDevice.FromIdAsync(i.DeviceAddress); } else { bd = await BluetoothDevice.FromBluetoothAddressAsync(ulong.Parse(i.DeviceAddress)); } bd.ConnectionStatusChanged += Bd_ConnectionStatusChanged; } } }
private async void AddPairedBtDevice(DeviceInformation deviceInformation) { DeviceInformation found = GetPairedBtDevice(deviceInformation); if (found != null) { return; } lock (PairedDeviceList) { PairedDeviceList.Add(deviceInformation); } Earbuds earbuds = GetNaerByEarbirds(deviceInformation.Id); if (earbuds != null) { earbuds.EnableGattConnection(); } else { var BtDevice = await BluetoothDevice.FromIdAsync(deviceInformation.Id); if (BtDevice != null) { if (BtDevice.ConnectionStatus == BluetoothConnectionStatus.Connected) { string bleDeviceID = BluetoothDevices.ConvertDeviceIdType(deviceInformation.Id, AddressType.BLE); AddNearByEarbuds(bleDeviceID); Log.D($"\tAlready Connected Device Found: Add it to NearByEarbuds List"); AddNearByBtDevice(bleDeviceID, deviceInformation.Name); } BtDevice.Dispose(); } } return; }
/// <summary> /// Get list of all available paired Bands. /// </summary> /// <returns>Task<List<Band>></returns> public async Task <List <BandInterface> > GetPairedBands() { string selector; RfcommServiceId cargo; DeviceInformationCollection devices; List <BandInterface> bands = new List <BandInterface>(); // Get devices cargo = RfcommServiceId.FromUuid(Guid.Parse(Services.CARGO)); selector = RfcommDeviceService.GetDeviceSelector(cargo); devices = await DeviceInformation.FindAllAsync(selector); // Create Band instances foreach (DeviceInformation device in devices) { BluetoothDevice bt; bt = await BluetoothDevice.FromIdAsync(device.Id); bands.Add(new Band <BandSocketUWP>(bt.HostName.ToString(), bt.Name)); } return(bands); }
public async Task ConnectDeviceAsync(string deviceId) { var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceId); var device = _discoverDevices[bluetoothDevice.BluetoothAddress]; var rfcommDeviceServicesResult = await bluetoothDevice.GetRfcommServicesAsync(BluetoothCacheMode.Uncached); _socket = new StreamSocket(); if (rfcommDeviceServicesResult.Services.Count > 0) { _connectService = rfcommDeviceServicesResult.Services.First(); await _socket.ConnectAsync(_connectService.ConnectionHostName, _connectService.ConnectionServiceName); _writer = new DataWriter(_socket.OutputStream); _reader = new DataReader(_socket.InputStream); _reader.UnicodeEncoding = UnicodeEncoding.Utf8; _reader.ByteOrder = ByteOrder.LittleEndian; ReceiveStringLoop(); DeviceConnected(device); } }
public async void Startup() { //todo: replace with confi setting builders: port type and ID data Logger.DebugWrite("Trying to connect..."); var devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort)); var device = devices[0].Id; var btd = await BluetoothDevice.FromIdAsync(device); await btd.RequestAccessAsync(); var btp = new ObdBluetoothPort("Port"); var provider = new ObdDevice(btp); await provider.Connect(); var debug = new DebugSubscriber(); var iot = new IotSubscriber("<YOUR IOT HUB NAME>", "<YOUR DEVICE>", "<YOUR DEVICE KEY>"); provider.Subscribe(debug); provider.Subscribe(iot); provider.Startup(); }