Example #1
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.ObexObjectPush);

            DevicePicker picker = new DevicePicker();

            picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33);
            picker.Appearance.ForegroundColor = Colors.White;
            picker.Appearance.AccentColor     = Colors.Goldenrod;

            // add our query string
            picker.Filter.SupportedDeviceSelectors.Add(aqs);

            // prompt user to select a single device
            DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect(200, 20, 50, 50));

            if (dev != null)
            {
                // if a device is selected create a BluetoothDevice instance to get more information
                RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(dev.Id);

                if (service != null)
                {
                    foreach (KeyValuePair <uint, IBuffer> attrib in await service.GetSdpRawAttributesAsync())
                    {
                        SdpDataElement de = SdpDataElement.FromByteArray(attrib.Value.ToArray());
                        System.Diagnostics.Debug.WriteLine(attrib.Key.ToString("X") + " " + de.ToString());
                    }
                    // set data-binding so that device properties are displayed
                    DeviceInformationPanel.DataContext = service;
                }
            }
        }
Example #2
0
        public async Task EnumerateDevices()
        {
            try
            {
                var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

                //var retList = new List<DeviceInformation>();
                listDevices.Clear();
                listNames.Clear();
                foreach (var serviceInfo in serviceInfoCollection)
                {
                    listNames.Add(serviceInfo.Name);
                    listDevices.Add(serviceInfo);
                }
                //return retList;
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == 0x8007048F)
                {
                    if (BluetoothNotSupported != null)
                    {
                        BluetoothNotSupported(this, new EventArgs());
                    }
                }
            }
        }
Example #3
0
        public async void Initialize()
        {
            // Enumerate devices with the object push service
            var services =
                await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(
                    RfcommDeviceService.GetDeviceSelector(
                        RfcommServiceId.ObexObjectPush));

            if (services.Count > 0)
            {
                // Initialize the target Bluetooth BR device
                var service = await RfcommDeviceService.FromIdAsync(services[0].Id);

                // Check that the service meets this App's minimum requirement
                if (SupportsProtection(service) && IsCompatibleVersion(service))
                {
                    _service = service;

                    // Create a socket and connect to the target
                    _socket = new StreamSocket();
                    await _socket.ConnectAsync(
                        _service.ConnectionHostName,
                        _service.ConnectionServiceName,
                        SocketProtectionLevel
                        .BluetoothEncryptionAllowNullAuthentication);

                    // The socket is connected. At this point the App can wait for
                    // the user to take some action, e.g. click a button to send a
                    // file to the device, which could invoke the Picker and then
                    // send the picked file. The transfer itself would use the
                    // Sockets API and not the Rfcomm API, and so is omitted here for
                    // brevity.
                }
            }
        }
Example #4
0
        public async void Connect(string deviceName)
        {
            try
            {
                var devices =
                    await DeviceInformation.FindAllAsync(
                        RfcommDeviceService.GetDeviceSelector(
                            RfcommServiceId.SerialPort));

                foreach (var dev in devices)
                {
                    Debug.Print("{0} {1}\n", dev.Name, dev.Kind.ToString());
                }

                var device = devices.Single(x => x.Name == deviceName);

                _service = await RfcommDeviceService.FromIdAsync(
                    device.Id);

                _socket = new StreamSocket();

                await _socket.ConnectAsync(
                    _service.ConnectionHostName,
                    _service.ConnectionServiceName,
                    SocketProtectionLevel.
                    BluetoothEncryptionAllowNullAuthentication);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Example #5
0
        private async void Connect_Click(object sender, RoutedEventArgs e)
        {
            string aqs = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(App.ChatServiceID));

            DevicePicker picker = new DevicePicker();

            picker.Appearance.BackgroundColor = Color.FromArgb(0xff, 0, 0x33, 0x33);
            picker.Appearance.ForegroundColor = Colors.White;
            picker.Appearance.AccentColor     = Colors.Goldenrod;

            // add our query string
            picker.Filter.SupportedDeviceSelectors.Add(aqs);

            // prompt user to select a single device
            DeviceInformation dev = await picker.PickSingleDeviceAsync(new Rect());

            if (dev != null)
            {
                remoteService = await RfcommDeviceService.FromIdAsync(dev.Id);

                if (remoteService != null)
                {
                    InputText.IsEnabled = true;
                }
            }
        }
        public override async Task <Connections> GetConnections()
        {
            if (this.isPrePairedDevice)
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = string.Empty;
            }

            try
            {
                var devices = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
                var peers   = await DeviceInformation.FindAllAsync(devices);

                var connections = new Connections();
                foreach (var peer in peers)
                {
                    connections.Add(new Connection(peer.Name, peer));
                }

                return(connections);
            }
            catch (Exception e)
            {
                Debug.WriteLine("GetConnections: pairing failed: " + e);
                return(null);
            }
        }
Example #7
0
        public async Task <DeviceInformationCollection> FindPairedDevicesAsync()
        {
            var aqsDevices = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(aqsDevices);

            return(devices);
        }
        //-----------------private functions----------------------------//

        private async void loadBluetoothPeers()
        {
            _rfcommDevices = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid)));

            if (_rfcommDevices.Count > 0)
            {
                List <string> peerNames = new List <string>();
                foreach (var chatServiceInfo in _rfcommDevices)
                {
                    peerNames.Add(chatServiceInfo.Name);
                }

                _selectBluetoothPeerBox.ItemsSource = peerNames;

                if (ApplicationData.Current.LocalSettings.Values.ContainsKey("obd"))
                {
                    String obdPeerId = ApplicationData.Current.LocalSettings.Values["obd"].ToString();
                    int    i         = 0;
                    foreach (var chatServiceInfo in _rfcommDevices)
                    {
                        if (chatServiceInfo.Id == obdPeerId)
                        {
                            _selectBluetoothPeerBox.SelectedIndex = i;
                        }
                        i++;
                    }
                }

                _connectButton.IsEnabled = true;
            }
        }
Example #9
0
        private async void btnListPrinters_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;

            // Disable the button while we do async operations so the user can't Run twice.
            button.IsEnabled = false;

            // Clear any previous messages
            NotifyUser("", NotifyType.StatusMessage);

            // Find all paired instances of the Rfcomm service and display them in a list
            dataServiceDeviceCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            if (dataServiceDeviceCollection.Count > 0)
            {
                DeviceList.Items.Clear();
                foreach (var dataServiceDevice in dataServiceDeviceCollection)
                {
                    DeviceList.Items.Add(dataServiceDevice.Name);
                }
                DeviceList.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            else
            {
                NotifyUser(
                    "No SPP services were found. Please pair with a device that is advertising the SPP service.",
                    NotifyType.ErrorMessage);
            }
            button.IsEnabled = true;
        }
        /// <summary>
        /// When the user presses the run button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list.
        /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired.
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        public async void Run()
        {
            // Find all paired instances of the Rfcomm chat service and display them in a list
            RfcommServiceId serid  = RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid);
            string          stsel  = RfcommDeviceService.GetDeviceSelector(serid);
            string          stsel1 = "System.Devices.InterfaceClassGuid:=\"{B142FC3E-FA4E-460B-8ABC-072B628B3C70}\" AND System.DeviceInterface.Bluetooth.ServiceGuid:=\"{34B1CF4D-1069-4AD6-89B6-E161D79BE4D8}\"";
            string          stsel2 = "System.Devices.InterfaceClassGuid:=\"{B142FC3E-FA4E-460B-8ABC-072B628B3C70}\"";
            string          stsel3 = "";

            chatServiceDeviceCollection = await DeviceInformation.FindAllAsync(stsel);

            int i = 0;

            if (chatServiceDeviceCollection.Count > 0)
            {
                //DeviceList.Items.Clear();
                foreach (var chatServiceDevice in chatServiceDeviceCollection)
                {
                    //if (chatServiceDevice.Name == "BAKULEV-X240")
                    {
                        //DeviceList.Items.Add(chatServiceDevice.Name + " " + chatServiceDevice.Id);
                        i++;
                    }
                }
                //DeviceList.Visibility = Windows.UI.Xaml.Visibility.Visible;
                SelectDevice(0); //bakulev
            }
            else
            {
                //rootPage.NotifyUser(
                //    "No chat services were found. Please pair with a device that is advertising the chat service.",
                //    NotifyType.ErrorMessage);
            }
        }
Example #11
0
        public async Task <string> Connect()
        {
            try
            {
                var devices =
                    await DeviceInformation.FindAllAsync(
                        RfcommDeviceService.GetDeviceSelector(
                            RfcommServiceId.SerialPort));

                var device = devices.Single(x => x.Name == connectionName);
                service = await RfcommDeviceService.FromIdAsync(device.Id);

                socket = new StreamSocket();
                await socket.ConnectAsync(
                    service.ConnectionHostName,
                    service.ConnectionServiceName);

                dataReader = new DataReader(socket.InputStream);
                dataWriter = new DataWriter(socket.OutputStream);
                return("connected");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                socket.Dispose();
                socket = null;
                service.Dispose();
                service = null;
                return("error occured");
            }
        }
Example #12
0
        private async void LoadBluetoothGPS()
        {
            //Ensure the bluetooth capability is enabled by opening package.appxmanifest in a text editor,
            // and add the following to the <Capabilities> section:
            //    <m2:DeviceCapability Name="bluetooth.rfcomm">
            //      <m2:Device Id="any">
            //        <m2:Function Type="name:serialPort" />
            //      </m2:Device>
            //    </m2:DeviceCapability>

            //Get list of devices
            string serialDeviceType = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
            var    devices          = await DeviceInformation.FindAllAsync(serialDeviceType);

            string GpsDeviceName = "HOLUX GPSlim236";             //Change name to your device or build UI for user to select from list of 'devices'
            //Select device by name
            var bluetoothDevice = devices.Where(t => t.Name == GpsDeviceName).FirstOrDefault();
            //Get service
            RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(bluetoothDevice.Id);

            if (rfcommService != null)
            {
                var device = new NmeaParser.BluetoothDevice(rfcommService);
                device.MessageReceived += device_MessageReceived;
                await device.OpenAsync();
            }
        }
        private async void RunButton_Click(object sender, RoutedEventArgs e)
        {
            // Clear any previous messages
            MainPage.Current.NotifyUser("", NotifyType.StatusMessage);

            // Find all paired instances of the Rfcomm chat service
            chatServiceInfoCollection = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid)));

            if (chatServiceInfoCollection.Count > 0)
            {
                List <string> items = new List <string>();
                foreach (var chatServiceInfo in chatServiceInfoCollection)
                {
                    items.Add(chatServiceInfo.Name);
                }
                cvs.Source = items;
                ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            else
            {
                MainPage.Current.NotifyUser(
                    "No chat services were found. Please pair with a device that is advertising the chat service.",
                    NotifyType.ErrorMessage);
            }
        }
Example #14
0
        private async Task SetupConnections()
        {
            string device1 = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);

            deviceCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(device1);
            await AddCommandLog(string.Format("Connecting to : {0}", device1));
            await AddCommandLog(string.Format("Devices found : {0}", deviceCollection.Count));

            selectedDevice = deviceCollection[0];
            deviceService  = await RfcommDeviceService.FromIdAsync(selectedDevice.Id);

            if (deviceService != null)
            {
                await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName);
                await LogStatus("Connection Established!");
                await SendInitializationCommands();
                await SetupOptions(true);
                await LogStatus("Ready for command");
            }
            else
            {
                await SetupOptions(false);

                throw new Exception("Didn't find the specified bluetooth device");
            }
        }
Example #15
0
        public async void Connect()
        {
            try
            {
                var devices = await DeviceInformation.FindAllAsync(
                    RfcommDeviceService.GetDeviceSelector(
                        RfcommServiceId.SerialPort));

                var device = devices.Single(x => x.Name == "HMSoft");

                _service = await RfcommDeviceService.FromIdAsync(
                    device.Id);

                _socket = new StreamSocket();

                await _socket.ConnectAsync(
                    _service.ConnectionHostName,
                    _service.ConnectionServiceName,
                    SocketProtectionLevel.
                    BluetoothEncryptionAllowNullAuthentication);
            }
            catch (Exception ex)
            {
                //tbError.Text = ex.Message;
            }
        }
        private async Task ConnectAsyncInternal()
        {
            _tokenSource = new CancellationTokenSource();

            string selector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            DeviceInformation device = (from d in devices where d.Name == _deviceName select d).FirstOrDefault();

            if (device == null)
            {
                throw new Exception("LEGO EV3 brick named '" + _deviceName + "' not found.");
            }

            RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(device.Id);

            if (service == null)
            {
                throw new Exception("Unable to connect to LEGO EV3 brick...is the manifest set properly?");
            }

            _socket = new StreamSocket();
            await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName,
                                       SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            _reader           = new DataReader(_socket.InputStream);
            _reader.ByteOrder = ByteOrder.LittleEndian;

            await ThreadPool.RunAsync(PollInput);
        }
Example #17
0
        /// <summary>
        /// When the user presses the "Start" button, check to see if any of the currently paired devices support the Rfcomm chat service and display them in a list.
        /// Note that in this case, the other device must be running the Rfcomm Chat Server before being paired.
        /// </summary>
        /// <param name="sender">Instance that triggered the event.</param>
        /// <param name="e">Event data describing the conditions that led to the event.</param>
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {
            StartButton.IsEnabled = false;

            // Find all paired instances of the Rfcomm chat service and display them in a list
            chatServiceDeviceCollection = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid)));

            if (chatServiceDeviceCollection.Count > 0)
            {
                DeviceList.Items.Clear();
                foreach (var chatServiceDevice in chatServiceDeviceCollection)
                {
                    DeviceList.Items.Add(chatServiceDevice.Name);
                }
                NotifyUser("Select a device.", NotifyType.StatusMessage);
            }
            else
            {
                NotifyUser(
                    "No chat services were found. Please pair with a device that is advertising the chat service.",
                    NotifyType.ErrorMessage);
            }
            StartButton.IsEnabled = true;
        }
Example #18
0
        // Rescan
        private async void Rescan()
        {
            try
            {
                // v1
                // var selector = SerialDevice.GetDeviceSelector();
                // var devices = await DeviceInformation.FindAllAsync(selector);
                // v2
                var selector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
                var devices  = await DeviceInformation.FindAllAsync(selector, null);

                // process
                for (int i = 0; i < devices.Count; i++)
                {
                    _devices.Add(devices[i]);
                }
                DeviceListSource.Source      = _devices;
                ConnectButton.IsEnabled      = true;
                ConnectDevices.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog(ex.Message, "Error");
                await dialog.ShowAsync();
            }
        }
Example #19
0
        /// <summary>
        /// Opens a bluetooth connnection to a MindWave Mobile headset.
        /// Please specify a Bluetooth name (Usually "MindWave Mobile") in the first parameter.
        /// </summary>
        public async void ConnectBluetooth(String BTname)
        {
            if (!connected)
            {
                RaiseConnecting();
                try
                {
                    connected = true;
                    var BluetoothZarizeni = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

                    var MindWaveHeadset = BluetoothZarizeni.SingleOrDefault(d => d.Name == BTname);
                    var serviceRfcomm   = await RfcommDeviceService.FromIdAsync(MindWaveHeadset.Id);

                    socket = new StreamSocket();
                    await socket.ConnectAsync(serviceRfcomm.ConnectionHostName, serviceRfcomm.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                    reader = new DataReader(socket.InputStream);
                    RaiseConnected();

                    ParseHeadsetPackets();
                }
                catch
                {
                    RaiseNoHeadset();
                    connected = false;
                    this.Dispose();
                }
            }
            else
            {
                throw new AlreadyConnected();
            }
        }
Example #20
0
        private async Task RegisterBand()
        {
            bool backgroundRegistered = false;

            var bandInfo = (await BandClientManager.Instance.GetBandsAsync()).FirstOrDefault();

            var consentGranted = await GetConsentForHeartRate(bandInfo);

            if (consentGranted.HasValue && consentGranted.Value)
            {
                // The Guid used for the RfcommServiceId is from the Package.appxmanifest.
                var device =
                    (await
                     DeviceInformation.FindAllAsync(
                         RfcommDeviceService.GetDeviceSelector(
                             RfcommServiceId.FromUuid(new Guid("A502CA9A-2BA5-413C-A4E0-13804E47B38F")))))
                    .FirstOrDefault(x => x.Name == bandInfo.Name);

                backgroundRegistered = device != null &&
                                       await
                                       BackgroundTaskProvider.RegisterBandDataTask(
                    typeof(BandDataTask).FullName,
                    device.Id);
            }

            if (backgroundRegistered)
            {
                var success =
                    new MessageDialog(
                        "The BandDataTask has been registered successfully and the app can be closed.",
                        "Background task registered");

                success.Commands.Add(new UICommand("Ok", command => { this.IsBandRegistered = true; }));

                await success.ShowAsync();
            }
            else
            {
                MessageDialog error;

                if (consentGranted.HasValue && !consentGranted.Value)
                {
                    error =
                        new MessageDialog(
                            "The BandDataTask was not registered as you have rejected consent to access the heart rate sensor. Please try again.",
                            "Background task not registered");
                }
                else
                {
                    error =
                        new MessageDialog(
                            "The BandDataTask was not registered successfully. Check your Microsoft Band is connected and try again.",
                            "Background task not registered");
                }

                error.Commands.Add(new UICommand("Ok", command => { }));

                await error.ShowAsync();
            }
        }
        public static async Task <StreamSocketConnection> ConnectAsync(Guid serviceUuid, IObjectSerializer serializer)
        {
            // Find all paired instances of the Rfcomm service
            var serviceId      = RfcommServiceId.FromUuid(serviceUuid);
            var deviceSelector = RfcommDeviceService.GetDeviceSelector(serviceId);
            var devices        = await DeviceInformation.FindAllAsync(deviceSelector);

            if (devices.Count > 0)
            {
                var device = devices.First(); // TODO

                var deviceService = await RfcommDeviceService.FromIdAsync(device.Id);

                if (deviceService == null)
                {
                    // Access to the device is denied because the application was not granted access
                    return(null);
                }

                var attributes = await deviceService.GetSdpRawAttributesAsync();

                IBuffer serviceNameAttributeBuffer;

                if (!attributes.TryGetValue(SdpServiceNameAttributeId, out serviceNameAttributeBuffer))
                {
                    // The service is not advertising the Service Name attribute (attribute id = 0x100).
                    // Please verify that you are running a BluetoothConnectionListener.
                    return(null);
                }

                using (var attributeReader = DataReader.FromBuffer(serviceNameAttributeBuffer))
                {
                    var attributeType = attributeReader.ReadByte();

                    if (attributeType != SdpServiceNameAttributeType)
                    {
                        // The service is using an unexpected format for the Service Name attribute.
                        // Please verify that you are running a BluetoothConnectionListener.
                        return(null);
                    }

                    var serviceNameLength = attributeReader.ReadByte();

                    // The Service Name attribute requires UTF-8 encoding.
                    attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8;
                    var serviceName = attributeReader.ReadString(serviceNameLength);

                    var socket = new StreamSocket();
                    await socket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName);

                    var connection = await StreamSocketConnection.ConnectAsync(socket, serializer);

                    return(connection);
                }
            }

            // No devices found
            return(null);
        }
Example #22
0
 public static IAsyncOperation <DeviceInformationCollection> getDeviceInfo(Guid guid)
 {
     return(AsyncInfo.Run((token) => {
         return Task.Run(async() => {
             var dev = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(guid));
             return await DeviceInformation.FindAllAsync(dev);
         });
     }));
 }
Example #23
0
        private async void BluetoothConnectionDialog_Loaded(object sender, RoutedEventArgs e)
        {
            var loc_deviceInformationList = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            foreach (var item in loc_deviceInformationList)
            {
                deviceInformationList.Add(item);
            }
        }
        public async Task Find()
        {
            var deviceSelectors = await DeviceInformation.FindAllAsync(
                RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            foreach (var selector in deviceSelectors)
            {
                this.device = await RfcommDeviceService.FromIdAsync(selector.Id);
            }
        }
        public async Task LookForBluetoothDevices()
        {
            Devices.Clear();
            var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            foreach (var serviceInfo in serviceInfoCollection)
            {
                Devices.Add(serviceInfo);
            }
        }
Example #26
0
 public async Task ScanForDevices()
 {
     try
     {
         DeviceCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
     }
     catch (Exception exception)
     {
     }
 }
Example #27
0
        public static IAsyncOperation <TetheringState> SendBluetooth(DeviceInformation dev, TetheringState state)
        {
            return(AsyncInfo.Run(async(cancel) =>
            {
                for (var tryout = 10; tryout > 0; tryout--)
                {
                    try
                    {
                        var selector = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(ServiceUuid));
                        var devices = await DeviceInformation.FindAllAsync(selector);
                        var service = devices.SingleOrDefault(d => d.Id.StartsWith(dev.Id, StringComparison.OrdinalIgnoreCase));
                        if (service == null)
                        {
                            throw new Exception("Tethermote Service not found");
                        }

                        using (var socket = await ConnectDevice(service))
                        {
                            using (var outstream = socket.OutputStream)
                            {
                                await outstream.WriteAsync(new byte[] { (byte)state }.AsBuffer());
                            }
                            using (var instream = socket.InputStream)
                            {
                                var buf = new Windows.Storage.Streams.Buffer(1);
                                var red = (await instream.ReadAsync(buf, 1, Windows.Storage.Streams.InputStreamOptions.Partial)).Length;

                                if (red == 1)
                                {
                                    return (TetheringState)buf.ToArray()[0];
                                }
                                Debug.WriteLine("No data");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                        try
                        {
                            await PingDevice(dev.Id);
                        }
                        catch (Exception e2)
                        {
                            Debug.WriteLine(e2);
                        }
                        if (tryout != 1)
                        {
                            await Task.Delay(100);
                        }
                    }
                }
                return TetheringState.Error;
            }));
        }
Example #28
0
        async void btList()
        {
            btListbox.Items.Clear();

            var devices = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            foreach (var device in devices)
            {
                btListbox.Items.Add(device);
            }
        }
Example #29
0
        public async Task LookForDevices()
        {
            State = ConnectionState.Enumerating;
            Devices.Clear();
            var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));

            foreach (var serviceInfo in serviceInfoCollection)
            {
                Devices.Add(serviceInfo);
            }
            State = ConnectionState.Enumerated;
        }
Example #30
0
        private async void InitializeRfcommServer()
        {
            try
            {
                listBoxDevices.Text = string.Empty;
                string device1 = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
                deviceCollection = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(device1);

                selectedDevice = deviceCollection[0];
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                    foreach (var item in deviceCollection)
                    {
                        listBoxDevices.Text += "\n========================";
                        listBoxDevices.Text += "\nDevice";
                        listBoxDevices.Text += string.Format("\nName: {0}\nId: {1}", item.Name, item.Id);
                        listBoxDevices.Text += "\n========================";
                        listBoxDevices.Text += "\nProperties";
                        listBoxDevices.Text += "\n========================";
                        foreach (var prop in item.Properties)
                        {
                            listBoxDevices.Text += string.Format("\nName: {0} - \tValue: {1}", prop.Key, prop.Value);
                        }
                        listBoxDevices.Text += "\n========================";
                    }
                });

                deviceService = await RfcommDeviceService.FromIdAsync(selectedDevice.Id);

                if (deviceService != null)
                {
                    //connect the socket
                    try
                    {
                        await streamSocket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName);
                    }
                    catch (Exception ex)
                    {
                        errorStatus.Visibility = Visibility.Visible;
                        errorStatus.Text       = "Cannot connect bluetooth device:" + ex.Message;
                    }
                }
                else
                {
                    errorStatus.Visibility = Visibility.Visible;
                    errorStatus.Text       = "Didn't find the specified bluetooth device";
                }
            }
            catch (Exception exception)
            {
                errorStatus.Visibility = Visibility.Visible;
                errorStatus.Text       = exception.Message;
            }
        }