Example #1
0
        /// <summary>
        /// Try to connect with the pen.
        /// </summary>
        /// <param name="macAddress">Mac address of the pen to connect</param>
        /// <returns>True or false if the connection is successful</returns>
        public async Task <bool> Connect(string macAddress)
        {
            try
            {
                await semaphreSlime.WaitAsync();

                PenInformation penInfo = GetPenInformationByAddress(macAddress);

                if (penInfo == null || penInfo.Protocol == Protocols.NONE)
                {
                    return(false);
                }

                if (penInfo.Protocol == Protocols.V2)
                {
                    return(await Connect(penInfo));
                }

                return(false);
            }
            catch
            {
                return(false);
            }
            finally
            {
                semaphreSlime.Release();
            }
        }
Example #2
0
        private async void btnDeletePaired_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            PenInformation selected = lvDevices.SelectedItem as PenInformation;
            await _client.UnPairing(selected);

            lvDevices.Items.Remove(lvDevices.SelectedItem);
        }
Example #3
0
        private async void btnConnect_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            Button btnConnect = (sender as Button);

            btnConnect.IsEnabled = false;

            PenInformation selected = lvDevices.SelectedItem as PenInformation;

            if (selected == null)
            {
                await ShowMessage("Select your device");
            }
            else
            {
                try
                {
                    bool result = await _client.Connect(selected);

                    if (!result)
                    {
                        await ShowMessage("Connection is failure");
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("conection exception : " + ex.Message);
                    Debug.WriteLine("conection exception : " + ex.StackTrace);
                }
            }

            btnConnect.IsEnabled = true;
        }
Example #4
0
        private void lvDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PenInformation selected = lvDevices.SelectedItem as PenInformation;

            if (selected == null)
            {
                return;
            }

            CurrentMacAddress = selected.MacAddress;
        }
Example #5
0
 private async void MClient_onUpdatePenController(BluetoothPenClient sender, PenUpdateInformation args)
 {
     await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
     {
         var item = lvDevices.Items.Where(p => (p as PenInformation)?.Id == args.Id);
         if (item != null)
         {
             PenInformation penInformation = item as PenInformation;
             if (penInformation != null)
             {
                 penInformation.Update(args);
             }
         }
     });
 }
Example #6
0
        /// <summary>
        /// Try to connect with the pen.
        /// </summary>
        /// <param name="penInformation">PenInformation instance that holds the pen's information</param>
        /// <returns>True or false if the connection is successful</returns>
        public async Task <bool> Connect(PenInformation penInformation)
        {
            try
            {
                if (penInformation.Protocol != Protocols.V2)
                {
                    throw new NotSupportedException("Not supported protocol version");
                }

                await semaphreSlime.WaitAsync();

                Debug.WriteLine("");

                bluetoothLEDevice = await BluetoothLEDevice.FromIdAsync(penInformation.Id);

                var status = await bluetoothLEDevice.RequestAccessAsync();

                Debug.WriteLine("RequestAccessAsync result is " + status.ToString());

                if (status != Windows.Devices.Enumeration.DeviceAccessStatus.Allowed)
                {
                    throw new Exception();
                }

                GattDeviceServicesResult result = await bluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                if (result.Status != GattCommunicationStatus.Success || await Bind(result.Services) == false)
                {
                    Debug.WriteLine("GetGattServicesAsync status is " + result.Status.ToString());
                    throw new Exception();
                }

                bluetoothLEDevice.ConnectionStatusChanged += BluetoothLEDevice_ConnectionStatusChanged;

                return(true);
            }
            catch
            {
                DisposeBluetoothResource();
                return(false);
            }
            finally
            {
                semaphreSlime.Release();
            }
        }
Example #7
0
        private async void BluetoothLEAdvertisementWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            try
            {
                if (args.AdvertisementType == BluetoothLEAdvertisementType.ConnectableUndirected)
                {
                    int protocol = Protocols.NONE;
                    if (args.Advertisement.ServiceUuids.Contains(BluetoothLePenClient.OldServiceUuidV2))
                    {
                        protocol = Protocols.V2;
                    }
                    else if (args.Advertisement.ServiceUuids.Contains(BluetoothLePenClient.ServiceUuidV2))
                    {
                        protocol = Protocols.V2;
                    }
                    else if (args.Advertisement.ServiceUuids.Contains(BluetoothPenClient.ServiceUuidV1))
                    {
                        protocol = Protocols.V1;
                    }

                    // mac address를 안쓰고 virtual mac address를 쓴이유는 advertisement는 굉장히 많이 들어오는 값이기 떄문에 좀더 빠르게 검색하기 위해
                    //if (penList.Exists(x => x.virtualMacAddress == args.BluetoothAddress))
                    //	return;

                    var penInformation = penList.Where(x => x.VirtualMacAddress == args.BluetoothAddress).FirstOrDefault();
                    if (penInformation == null)
                    {
                        BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                        string mac = string.Empty;
                        foreach (var data in args.Advertisement.DataSections)
                        {
                            if (data.DataType == 0xFF)
                            {
                                mac = BufferToMacAddress(data.Data);
                                break;
                            }
                        }

                        if (ValidateMacAddress(mac))
                        {
                            lock (deviceLock)
                            {
                                if (penList.Where(x => x.VirtualMacAddress == args.BluetoothAddress).Count() <= 0)
                                {
                                    penInformation = PenInformation.Create(bleDevice.DeviceInformation, bleDevice.Name, args.BluetoothAddress, mac, args.RawSignalStrengthInDBm, protocol, true);
                                    penList.Add(penInformation);
                                    onAddPenController(this, penInformation);
                                }
                            }
                        }
                    }
                    else
                    {
                        BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                        var update = PenUpdateInformation.Create(bleDevice?.DeviceId, true);
                        update.Rssi = args.RawSignalStrengthInDBm;

                        onUpdatePenController?.Invoke(this, update);
                    }
                }
                else if (args.AdvertisementType == BluetoothLEAdvertisementType.ScanResponse)
                {
                    // ScanResponse에 name이 추가정보로 오는데 DeviceInformaion을 가져오면 Name을 알 수 있기 때문에 추가로 받아 처리할 필요는 아직까진 없다.
                    var penInformation = penList.Where(x => x.VirtualMacAddress == args.BluetoothAddress).FirstOrDefault();
                    if (penInformation == null)
                    {
                        return;
                    }

                    BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                    var update = PenUpdateInformation.Create(bleDevice?.DeviceId, true);
                    update.Rssi = args.RawSignalStrengthInDBm;
                    if (!string.IsNullOrEmpty(bleDevice.Name))
                    {
                        update.ModelName = bleDevice.Name;
                    }
                    else
                    {
                        foreach (var data in args.Advertisement.DataSections)
                        {
                            if (data.DataType == 0x09)
                            {
                                var b = new byte[data.Data.Length];
                                using (var reader = DataReader.FromBuffer(data.Data))
                                {
                                    reader.ReadBytes(b);
                                }
                                update.ModelName = Encoding.UTF8.GetString(b);
                                break;
                            }
                        }
                    }

                    onUpdatePenController?.Invoke(this, update);
                }
            }
            catch { }
        }
Example #8
0
        /// <summary>
        /// Get the information of the pen to the pen's mac address.
        /// </summary>
        /// <param name="macAddress">Mac address of the pen to get the information.</param>
        /// <returns>PenInformation instance that holds the pen's information</returns>
        public PenInformation GetPenInformationByAddress(string macAddress)
        {
            try
            {
                PenInformation penInfo = null;

                var bleAdWatcher = CreateLEAdvertisementWatcher();

                bleAdWatcher.Received += async(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) =>
                {
                    try
                    {
                        if (args.AdvertisementType == BluetoothLEAdvertisementType.ConnectableUndirected)
                        {
                            int protocol = Protocols.NONE;
                            if (args.Advertisement.ServiceUuids.Contains(BluetoothLePenClient.OldServiceUuidV2))
                            {
                                protocol = Protocols.V2;
                            }
                            else if (args.Advertisement.ServiceUuids.Contains(BluetoothLePenClient.ServiceUuidV2))
                            {
                                protocol = Protocols.V2;
                            }
                            else if (args.Advertisement.ServiceUuids.Contains(BluetoothPenClient.ServiceUuidV1))
                            {
                                protocol = Protocols.V1;
                            }

                            if (penInfo != null || protocol == Protocols.NONE)
                            {
                                return;
                            }

                            BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                            string mac = string.Empty;

                            foreach (var data in args.Advertisement.DataSections)
                            {
                                if (data.DataType == 0xFF)
                                {
                                    mac = BufferToMacAddress(data.Data);
                                    break;
                                }
                            }

                            if (mac.ToLower() == macAddress.ToLower())
                            {
                                penInfo = PenInformation.Create(bleDevice.DeviceInformation, bleDevice.Name, args.BluetoothAddress, mac, args.RawSignalStrengthInDBm, protocol, true);

                                bleAdWatcher?.Stop();
                                bleAdWatcher = null;
                            }
                        }
                    }
                    catch
                    {
                    }
                };

                bleAdWatcher.Stopped += (BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementWatcherStoppedEventArgs args) =>
                {
                    bleAdWatcher?.Stop();
                    bleAdWatcher = null;

                    autoResetEvent.Set();
                };

                bleAdWatcher.Start();

                ThreadPoolTimer.CreateTimer((ThreadPoolTimer timer) => {
                    bleAdWatcher?.Stop();
                    bleAdWatcher = null;
                }, TimeSpan.FromSeconds(5));

                autoResetEvent.WaitOne();

                if (penInfo == null || penInfo.Protocol == Protocols.NONE)
                {
                    return(null);
                }

                return(penInfo);
            }
            catch
            {
                return(null);
            }
        }
Example #9
0
 private async void MClient_onAddPenController(BluetoothPenClient sender, PenInformation args)
 {
     await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => lvDevices.Items.Add(args));
 }