예제 #1
0
        public override IObservable <IScanResult> Scan(ScanConfig config)
        {
            if (this.IsScanning)
            {
                throw new ArgumentException("There is already an active scan");
            }

            return(Observable.Create <IScanResult>(ob =>
            {
                this.IsScanning = true;
                this.context.Clear();

                var sub = this
                          .WhenRadioReady()
                          .Where(rdo => rdo != null)
                          .Select(_ => this.CreateScanner(config))
                          .Switch()
                          .Subscribe(
                    async args =>     // CAREFUL
                {
                    var device = this.context.GetPeripheral(args.BluetoothAddress);
                    if (device == null)
                    {
                        var btDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
                        if (btDevice != null)
                        {
                            device = this.context.AddOrGetPeripheral(btDevice);
                        }
                    }
                    if (device != null)
                    {
                        var adData = new AdvertisementData(args);
                        var scanResult = new ScanResult(device, args.RawSignalStrengthInDBm, adData);
                        ob.OnNext(scanResult);
                    }
                },
                    ob.OnError
                    );

                var stopSub = this.scanSubject.Subscribe(_ =>
                {
                    this.IsScanning = false;
                    sub?.Dispose();
                    ob.OnCompleted();
                });

                return () =>
                {
                    this.IsScanning = false;
                    sub?.Dispose();
                    stopSub?.Dispose();
                };
            }));
        }
        static async Task <bool> Pair(AnkiBLE.anki_vehicle vehicle)
        {
            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(vehicle.mac_address);

            DeviceInformationCustomPairing customPairing = device.DeviceInformation.Pairing.Custom;

            customPairing.PairingRequested += PairingRequestedHandler;
            DevicePairingResult result = await customPairing.PairAsync(DevicePairingKinds.ConfirmOnly, DevicePairingProtectionLevel.None);

            customPairing.PairingRequested -= PairingRequestedHandler;
            return(result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired);
        }
예제 #3
0
        private async Task <BluetoothLEDevice> ConnectToDevice(BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);

            if (device == null)
            {
                Exception e = new Exception("Connecting to bluetooth device failed");
                throw e;
            }

            return(device);
        }
        /// <summary>
        /// Handler for devices found when duplicates are allowed
        /// </summary>
        /// <param name="watcher">The bluetooth advertisement watcher currently being used</param>
        /// <param name="btAdv">The advertisement recieved by the watcher</param>
        private async void DeviceFoundAsyncDuplicate(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs btAdv)
        {
            BluetoothLEDevice currDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);

            if (currDevice != null)
            {
                var device = new Device(this, currDevice, btAdv.RawSignalStrengthInDBm, btAdv.BluetoothAddress.ToString(), ParseAdvertisementData(btAdv.Advertisement));
                Trace.Message("DiscoveredPeripheral: {0} Id: {1}", device.Name, device.Id);
                this.HandleDiscoveredDevice(device);
            }
            return;
        }
예제 #5
0
            public async Task <IGattClient> ConnectToGattServerAsync()
            {
                BluetoothLEDevice uwpLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(Address);

                if (uwpLeDevice == null)
                {
                    return(null);
                }
                GattClient gattClient = new GattClient(this, uwpLeDevice);

                return(gattClient);
            }
예제 #6
0
        private async void BleWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            if (!string.IsNullOrEmpty(args.Advertisement.LocalName) && args.Advertisement.LocalName == "Flower care")
            {
                var device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                if (!bluetoothLEDevices.Any(x => x.DeviceId == device.DeviceId))
                {
                    bluetoothLEDevices.Add(device);
                }
            }
        }
예제 #7
0
        /// <summary>
        /// connects to the BLE device and extracts more information for the
        /// <see cref="https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice"/>
        /// </summary>
        /// <param name="address">the bluetooth device address to connect</param>
        /// <param name="broadcastTime">the time broadcast message received</param>
        /// <param name="rssi">the signal strength received</param>
        /// <returns></returns>
        private async Task <DnaBluetoothLEDevice> GetBluetoothLEDeviceAsync(ulong address, DateTimeOffset broadcastTime, short rssi)
        {
            // get bluetooth device info
            var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();

            // null check
            if (device == null)
            {
                return(null);
            }

            // NOTE: this can throw a System.Exception for failure
            // get GATT Services that are available
            var gatt = await device.GetGattServicesAsync().AsTask();

            // if we have any services..
            if (gatt.Status == GattCommunicationStatus.Success)
            {
                // loop each GATT Service
                foreach (var service in gatt.Services)
                {
                    // this id contains GATT Profile Assigned number
                    var gattProfileID = service.Uuid;

                    //if(service.Uuid.ToString("N").Substring(4,4) == "1808")
                    //{
                    //    System.Diagnostics.Debugger.Break();
                    //}
                }
            }

            // return the new device information
            return(new DnaBluetoothLEDevice
                   (
                       // Device Id
                       deviceId: device.DeviceId,
                       // Bluetooth address
                       address: device.BluetoothAddress,
                       // device name
                       name: device.Name,
                       // broadcast time
                       broadcastTime: broadcastTime,
                       // signal name
                       rssi: rssi,
                       // is connected?
                       connected: device.ConnectionStatus == BluetoothConnectionStatus.Connected,
                       // can pair?
                       canPair: device.DeviceInformation.Pairing.CanPair,
                       // is paired?
                       paired: device.DeviceInformation.Pairing.IsPaired
                   ));
        }
예제 #8
0
        public override IObservable <IDevice> GetKnownDevice(Guid deviceId) => Observable.FromAsync(async ct =>
        {
            IDevice device = null;
            var mac        = deviceId.ToMacAddress();
            var native     = await BluetoothLEDevice.FromBluetoothAddressAsync(mac).AsTask(ct);

            if (native != null)
            {
                device = this.context.AddOrGetDevice(mac, native);
            }

            return(device);
        });
        public async override Task <IDevice> ConnectToKnownDeviceAsync(Guid deviceGuid, ConnectParameters connectParameters, CancellationToken cancellationToken)
        {
            //convert GUID to string and take last 12 characters as MAC address
            var   guidString    = deviceGuid.ToString("N").Substring(20);
            ulong bluetoothAddr = Convert.ToUInt64(guidString, 16);
            var   nativeDevice  = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddr);

            var currDevice = new Device(this, nativeDevice, 0, guidString);

            await ConnectToDeviceAsync(currDevice);

            return(currDevice);
        }
예제 #10
0
        public async Task Connect()
        {
            if (this.NativeDevice != null && this.NativeDevice.ConnectionStatus == BluetoothConnectionStatus.Connected)
            {
                return;
            }

            this.connSubject.OnNext(ConnectionStatus.Connecting);
            this.NativeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(this.bluetoothAddress);

            this.NativeDevice.ConnectionStatusChanged += this.OnNativeConnectionStatusChanged;
            await this.NativeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached); // HACK: kick the connection on
        }
        private async Task <BluetoothLEDevice> ConnectToDeviceAsync(BrilliantSoleDevice sole)
        {
            Console.WriteLine("Attempting to connect to " + sole.name);
            sole.device = await BluetoothLEDevice.FromBluetoothAddressAsync(sole.address);

            if (sole.device == null)
            {
                Console.WriteLine("Failed to connect to " + sole.name);
                throw new Exception("Failed to connect."); // TODO - Recover
            }
            Console.WriteLine("Successfully connected to " + sole.name);
            return(sole.device);
        }
        /// <summary>
        /// Connects to the BLE device and extracts more information from the
        /// <seealso cref="https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice"/>
        /// </summary>
        /// <param name="address">The BT address of the device to connect to</param>
        /// <param name="broadcastTime">The time the broadcast message was received</param>
        /// <param name="rssi">The signal strength in dB</param>
        /// <returns></returns>
        private async Task <DnaBluetoothLEDevice> GetBluetoothLEDeviceAsync(ulong address, DateTimeOffset broadcastTime, short rssi)
        {
            // Get bluetooth device info
            using var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();

            // Null guard
            if (device == null)
            {
                return(null);
            }

            // Get GATT services that are available
            var gatt = await device.GetGattServicesAsync().AsTask();

            // If we have any services...
            if (gatt.Status == GattCommunicationStatus.Success)
            {
                // Loop each GATT service
                foreach (var service in gatt.Services)
                {
                    // This ID contains the GATT Profile Assigned number we want
                    // TODO: get more info to connect
                    var gattProfileId = service.Uuid;

                    if (service.Uuid.ToString("N").Substring(4, 4) == "1808")
                    {
                    }
                }
            }

            // Return the new device information
            return(new DnaBluetoothLEDevice
                   (
                       // Device Id
                       deviceId: device.DeviceId,
                       // Bluetooth Address
                       address: device.BluetoothAddress,
                       // Device Name
                       name: device.Name,
                       // Broadcast Time
                       broadcastTime: broadcastTime,
                       // Signal Strength
                       rssi: rssi,
                       // Is Connected?
                       connected: device.ConnectionStatus == BluetoothConnectionStatus.Connected,
                       // Can Pair?
                       canPair: device.DeviceInformation.Pairing.CanPair,
                       // Is Paired
                       paired: device.DeviceInformation.Pairing.IsPaired
                   ));
        }
예제 #13
0
        /// <summary>
        /// Connect to the BLE device and extracts information from the device
        /// </summary>
        /// <returns></returns>
        private async Task <DnaBluetoothLEDevice> GetBluetoothLEDeviceAsync(ulong address, DateTimeOffset brodcastTime, short rssi)
        {
            // Get bluetooth device info
            using var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();

            // Null guard
            if (device == null)
            {
                return(null);
            }

            // Get GATT services that are available
            var gatt = await device.GetGattServicesAsync().AsTask();

            // If we have any services...
            if (gatt.Status == GattCommunicationStatus.Success)
            {
                // loop each GATT Service
                foreach (var services in gatt.Services)
                {
                    // This Id contains the GATT profile assigned number we want!
                    // TODO: get more info and connect
                    var gattProfileId = services.Uuid;
                }
            }
            ;

            return(new DnaBluetoothLEDevice
                   (
                       // Device Id
                       deviceid: device.DeviceId,

                       // BlueTooth Address
                       address: device.BluetoothAddress,

                       // Device name
                       name: device.Name,

                       // Time of broadcast
                       broadcastTime: brodcastTime,

                       // Signal strength
                       rssi: rssi,

                       connected: device.ConnectionStatus == BluetoothConnectionStatus.Connected,

                       canpair: device.DeviceInformation.Pairing.CanPair,

                       paired: device.DeviceInformation.Pairing.IsPaired
                   ));
        }
        private async static Task <GattDeviceService> waitConnection(AnkiBLE.anki_vehicle vehicle)
        {
            BluetoothLEDevice bluetoothLeDevice = null;
            GattDeviceService service           = null;

            bluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(vehicle.mac_address);

            while (bluetoothLeDevice.ConnectionStatus != BluetoothConnectionStatus.Connected)
            {
                throw new Exception("Not connected!");
            }
            service = bluetoothLeDevice.GetGattService(Guid.Parse("be15beef-6186-407e-8381-0bd89c4d8df4"));
            return(service);
        }
예제 #15
0
        internal BluetoothAdvertisingEvent(BluetoothLEAdvertisementReceivedEventArgs args)
        {
            _rssi    = args.RawSignalStrengthInDBm;
            _txPower = args.TransmitPowerLevelInDBm.HasValue ? (sbyte)args.TransmitPowerLevelInDBm.Value : (sbyte)0;

            /*var sections = args.Advertisement.GetSectionsByType(0xA);
             * if(sections != null && sections.Count > 0)
             * {
             *  var array = sections[0].Data.ToArray();
             *
             *  _txPower = sections[0].Data.GetByte(0);
             * }*/

            var appearanceSections = args.Advertisement.GetSectionsByType(0x19);

            if (appearanceSections != null && appearanceSections.Count > 0)
            {
                var appearanceArray = appearanceSections[0].Data.ToArray();
                _appearance = BitConverter.ToUInt16(appearanceArray, 0);
            }

            // https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledevice.frombluetoothaddressasync?view=winrt-20348
            // If there are no other pending request, and the remote device is unreachable,
            // then the system will wait for seven (7) seconds before it times out. If
            // there are other pending requests, then each of the requests in the queue can
            // take seven (7) seconds to process, so the further yours is toward the back
            // of the queue, the longer you'll wait.
            IAsyncOperation <BluetoothLEDevice> deviceAsync = BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress, args.BluetoothAddressType);

            // https://github.com/inthehand/32feet/issues/96
            // Wait some time for this task to complete otherwise the event will fire
            // before the 'Device' property as been set.
            if (deviceAsync.AsTask().Wait(7000))
            {
                Device = deviceAsync.GetResults();
            }
            else
            {
                try
                {
                    // The documents state that it is not possible to cancel 'FromBluetoothAddressAsync'
                    // so mask any exceptions before calling this.
                    deviceAsync.Cancel();
                }
                catch
                {
                }
            }
            _advertisement = args.Advertisement;
        }
예제 #16
0
        public override async Task ConnectAsync()
        {
            if (ConnectionStatus.DISCONNECTED == ConnectionStatus)
            {
                ConnectionStatus  = ConnectionStatus.CONNECTING;
                BluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(BluetoothAddress);

                BluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChanged;
                var gattDeviceServicesResult = await BluetoothLeDevice.GetGattServicesForUuidAsync(SERVICE_UUID);

                Services = gattDeviceServicesResult.Services;
                var foundService = gattDeviceServicesResult.Services.Single(s => s.Uuid == SERVICE_UUID);
                GattCharacteristicsResult gattCharacteristicsResult = await foundService.GetCharacteristicsAsync();

                ReadData = gattCharacteristicsResult.Characteristics.Single(x => x.Uuid == CHARACTERISTIC_READ_UUID);
                Debug.WriteLine("Found Read Char");
                WriteData = gattCharacteristicsResult.Characteristics.Single(x => x.Uuid == CHARACTERISTIC_WRITE_UUID);
                Debug.WriteLine("Found Write Char");


                GattCommunicationStatus status = GattCommunicationStatus.Unreachable;
                int count = 0;
                do
                {
                    try
                    {
                        status = await ReadData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

                        Debug.WriteLine("Notify status: " + status);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Error during notify" + e.Message);
                    }
                } while (status != GattCommunicationStatus.Success && ++count < 5);
                if (status == GattCommunicationStatus.Success)
                {
                    ReadData.ValueChanged += HandleRealTimeData;

                    await WriteValue();

                    ConnectionStatus = ConnectionStatus.CONNECTED;
                }
                else
                {
                    ConnectionStatus = ConnectionStatus.DISCONNECTED;
                }
            }
        }
예제 #17
0
        private async void Initialize()
        {
            Console.WriteLine(tag, "Connecting...");
            this.Device = await BluetoothLEDevice.FromBluetoothAddressAsync(this.DeviceAddress);

            DevicePairingResult result = await this.Device.DeviceInformation.Pairing.PairAsync();

            if (result.Status != DevicePairingResultStatus.AlreadyPaired && result.Status != DevicePairingResultStatus.Paired)
            {
                Console.WriteLine(tag, "Failed to pair:" + result.Status);
                this.Device.Dispose();
                return;
            }
            EnableUpgradeMode();
        }
        private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
        {
            Debug.Write("Ad ");
            string deviceName = eventArgs.Advertisement.LocalName;

            Debug.WriteLine(deviceName);

            if (deviceName == "Nano33BLE")
            {
                BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);

                watcher.Stop();
                SetupConnection(device);
            }
        }
예제 #19
0
        // Pairs device with Sensortag
        public async Task PairSensorTagAsync()
        {
            device = await BluetoothLEDevice.FromBluetoothAddressAsync(bleadress);


            bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.DeviceId);



            var status = await device.DeviceInformation.Pairing.PairAsync();



            await GetGATTServicesDataAsync(device);
        }
예제 #20
0
파일: BuWizzHub.cs 프로젝트: tomjcook/BAP
        internal override async Task RenewCharacteristic()
        {
            if (Device != null)
            {
                Device = await BluetoothLEDevice.FromBluetoothAddressAsync(Device.BluetoothAddress);

                Gatt = await Device.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                AllCharacteristic = await Gatt.Services.Single(s => s.Uuid == Guid.Parse("4E050000-74FB-4481-88B3-9919B1676E93")).GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                Characteristic = AllCharacteristic.Characteristics.Single(s => s.Uuid == Guid.Parse("000092d1-0000-1000-8000-00805f9b34fb"));

                MainBoard.WriteLine("New Hub Found of type " + Enum.GetName(typeof(Hub.Types), Type), Color.Green);
            }
        }
예제 #21
0
        public async Task Start()
        {
            _device = await BluetoothLEDevice.FromBluetoothAddressAsync(_address);

            if (_device == null)
            {
                GlobalCounters.IncrementFailedCreate();
                return;
            }
            GlobalDeviceNameTracking.ReportName(_device.Name, _device.BluetoothAddress);

            _device.ConnectionStatusChanged += ConnectionStatusChanged;

            GlobalCounters.IncrementDevicesCreated();
        }
예제 #22
0
        /// <summary>
        /// Obtain a new Characteristic
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        internal virtual async System.Threading.Tasks.Task RenewCharacteristic()
        {
            if (Device != null)
            {
                Device = await BluetoothLEDevice.FromBluetoothAddressAsync(Device.BluetoothAddress);

                Gatt = await Device.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                AllCharacteristic = await Gatt.Services.Single(s => s.Uuid == Guid.Parse("00001623-1212-efde-1623-785feabcd123")).GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                Characteristic = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("00001624-1212-efde-1623-785feabcd123"));

                MainBoard.WriteLine("New Hub Found of type " + Enum.GetName(typeof(Hub.Types), Type), Color.Green);
            }
        }
예제 #23
0
        /// <summary>
        /// Handle the client's request to connect to a particular peripheral.
        /// Valid in the discovery state; transitions to connected state on success.
        /// </summary>
        /// <param name="parameters">
        /// A JSON object containing the UUID of a peripheral found by the most recent discovery request
        /// </param>
        private async Task Connect(JObject parameters)
        {
            if (_services != null)
            {
                //throw JsonRpcException.InvalidRequest("already connected to peripheral");
                return;
            }

            var peripheralId = parameters["peripheralId"].ToObject <ulong>();

            if (!_reportedPeripherals.Contains(peripheralId))
            {
                // the client may only connect to devices that were returned by the current discovery request
                throw JsonRpcException.InvalidParams($"invalid peripheral ID: {peripheralId}");
            }

            _peripheral = await BluetoothLEDevice.FromBluetoothAddressAsync(peripheralId);

            var servicesResult = await _peripheral.GetGattServicesAsync(BluetoothCacheMode.Uncached);

            if (servicesResult.Status != GattCommunicationStatus.Success)
            {
                throw JsonRpcException.ApplicationError($"failed to enumerate GATT services: {servicesResult.Status}");
            }

            _peripheral.ConnectionStatusChanged += OnPeripheralStatusChanged;
            _services = servicesResult.Services;

            // collect optional services plus all services from all filters
            // Note: this modifies _optionalServices for convenience since we know it'll go away soon.
            _allowedServices = _optionalServices ?? new HashSet <Guid>();
            _allowedServices = _filters
                               .Where(filter => filter.RequiredServices?.Count > 0)
                               .Aggregate(_allowedServices, (result, filter) =>
            {
                result.UnionWith(filter.RequiredServices);
                return(result);
            });

            // clean up resources used by discovery
            if (_watcher != null)
            {
                _watcher.Stop();
                _watcher = null;
            }
            //_reportedPeripherals.Clear();
            _optionalServices = null;
        }
        /// <summary>
        /// Connects to the BLE device and extracts more information from the
        /// <see cref="https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.bluetoothledvice"/>
        /// </summary>
        /// <param name="address">The Bluetooth address of the device to connect to</param>
        /// <param name="broadcastTime">The time the broadcast message was received</param>
        /// <param name="rssi">The signal strength in dB</param>
        /// <returns></returns>
        /// <Capabilities> <DeviceCapability Name = "bluetooth"/></Capabilities>
        private async Task <RoverBluetoothLEDevice> GetBluetoothLEDeviceAsync(ulong address, DateTimeOffset broadcastTime, short rssi)
        {
            // Get bluetooth device info
            var device = await BluetoothLEDevice.FromBluetoothAddressAsync(address).AsTask();

            // Null Guard
            if (device == null)
            {
                return(null);
            }

            // NOTE: This can throw a System.Exception for failures
            // Get GATT services that are available
            var gatt = await device.GetGattServicesAsync().AsTask();

            // If we have any services...
            if (gatt.Status == GattCommunicationStatus.Success)
            {
                // Loop each GATT service
                foreach (var service in gatt.Services)
                {
                    // This ID contains the GATT Profile Assigned number needed
                    // TODO: Get more info and connect
                    var gattProfileId = service.Uuid;
                }
            }

            // Return the new device information
            return(new RoverBluetoothLEDevice
                   (
                       // Device ID
                       deviceID: device.DeviceId,
                       // Bluetooth Address
                       addressBT: device.BluetoothAddress,
                       // Device name
                       name: device.Name,
                       // Broadcast time
                       broadcastTime: broadcastTime,
                       // Signal strength
                       rssi: rssi,
                       // Is Connected?
                       connected: device.ConnectionStatus == BluetoothConnectionStatus.Connected,
                       // Can Pair?
                       canPair: device.DeviceInformation.Pairing.CanPair,
                       // Is Paired?
                       paired: device.DeviceInformation.Pairing.IsPaired
                   ));
        }
예제 #25
0
        public override IObservable <IPeripheral?> GetKnownPeripheral(string peripheralUuid) => Observable.FromAsync(async ct =>
        {
            var mac = Guid.Parse(peripheralUuid).ToBluetoothAddress();
            var per = this.context.GetPeripheral(mac);

            if (per == null)
            {
                var native = await BluetoothLEDevice.FromBluetoothAddressAsync(mac).AsTask(ct);
                if (native != null)
                {
                    per = this.context.AddOrGetPeripheral(native);
                }
            }

            return(per);
        });
예제 #26
0
        internal override async Task RenewCharacteristic()
        {
            if (Device != null)
            {
                Device = await BluetoothLEDevice.FromBluetoothAddressAsync(Device.BluetoothAddress);

                Gatt = await Device.GetGattServicesAsync(BluetoothCacheMode.Uncached);

                AllCharacteristic = await Gatt.Services.Single(s => s.Uuid == Guid.Parse("49535343-FE7D-4AE5-8FA9-9FAFD205E455")).GetCharacteristicsAsync(BluetoothCacheMode.Uncached);

                Characteristic   = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("49535343-1E4D-4BD9-BA61-23C647249616"));
                TxCharacteristic = AllCharacteristic.Characteristics.Single(c => c.Uuid == Guid.Parse("49535343-8841-43F4-A8D4-ECBE34729BB3"));

                MainBoard.WriteLine("New Hub Found of type " + Enum.GetName(typeof(Hub.Types), Type), Color.Green);
            }
        }
예제 #27
0
        private async void AdbWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            if (args.Advertisement.ServiceUuids.Contains(this.targetUuid))
            {
                Debug.WriteLine("detect");
                this.adbWatcher.Stop();
                this.adbWatcher.Received -= AdbWatcher_Received;

                this.bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress); // MAC Address -> BLEDevice

                this.condition.Signal();
                await Task.Delay(1000);

                this.condition.Reset();
            }
        }
예제 #28
0
        private static async void bluetoothFoundAsync(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            string deviceName    = args.Advertisement.LocalName;
            string deviceAddress = args.BluetoothAddress.ToString();

            if (deviceName.Contains("Foldio"))
            {
                var bdevice = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                ScannedDevicesList.Add(bdevice);
                watcher.Stop();
            }
            else
            {
            }
        }
예제 #29
0
        // AdvertisementWatcher Detected device
        private async void DeviceDiscovered(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            bool returnDevice = scanServices.Count == 0;

            if (!returnDevice)
            {
                foreach (Guid uuid in args.Advertisement.ServiceUuids)
                {
                    returnDevice = scanServices.Contains(uuid.ToString().ToUpper());
                    if (returnDevice)
                    {
                        break;
                    }
                }
            }
            if (returnDevice)
            {
                BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

                if (device != null)
                {
                    if (!deviceAddresses.Contains(device.BluetoothAddress))
                    {
                        devices.Add(device);
                        deviceAddresses.Add(device.BluetoothAddress);
                    }
                    string advertisedName = device.Name;
                    List <BluetoothLEAdvertisementDataSection> complete  = new List <BluetoothLEAdvertisementDataSection>(args.Advertisement.GetSectionsByType(BluetoothLEAdvertisementDataTypes.CompleteLocalName));
                    List <BluetoothLEAdvertisementDataSection> smallName = new List <BluetoothLEAdvertisementDataSection>(args.Advertisement.GetSectionsByType(BluetoothLEAdvertisementDataTypes.ShortenedLocalName));
                    if (complete.Count > 0)
                    {
                        advertisedName = Encoding.UTF8.GetString(complete[0].Data.ToArray());
                    }
                    else if (smallName.Count > 0)
                    {
                        advertisedName = Encoding.UTF8.GetString(smallName[0].Data.ToArray());
                    }
                    callback.onDeviceDiscovered((device.BluetoothAddress + "").ToUpper(), advertisedName, args.RawSignalStrengthInDBm);
                }
                else
                {
                    Debug.WriteLine("-------------Error:------------");
                    Debug.WriteLine("Devie with address " + args.BluetoothAddress + " was a null device!");
                    Debug.WriteLine("-------------------------------");
                }
            }
        }
예제 #30
0
        private async Task <bool> ConnectDevice()
        {
            if (Device == null)
            {
                string bta = BluetoothAddress.ToString("X");
                Device = await BluetoothLEDevice.FromBluetoothAddressAsync(BluetoothAddress);

                if (Device == null)
                {
                    return(false);
                }
                Dbg("connected to device: " + bta);

                var characteristics = new List <GattCharacteristic>();
                var gatt            = await Device.GetGattServicesAsync();

                var svc_rest        = gatt.Services.First(s => s.Uuid == BT.SVC_REST);
                var svc_advertising = gatt.Services.First(s => s.Uuid == BT.SVC_ADVERTISING);
                characteristics.AddRange((await svc_rest.GetCharacteristicsAsync()).Characteristics);
                characteristics.AddRange((await svc_advertising.GetCharacteristicsAsync()).Characteristics);
                try
                {
                    // save TX/RX/Manufacturer channels
                    CharTX       = characteristics.First(c => c.Uuid == BT.CHAR_TX);
                    CharRX       = characteristics.First(c => c.Uuid == BT.CHAR_RX);
                    CharFeedback = characteristics.First(c => c.Uuid == BT.CHAR_FEEDBACK);
                }
                catch (Exception)
                {
                    Dbg("error configuring characteristics: " + bta);
                    Device = null;
                    return(false);
                }
                await RefreshData();

                #region there is a bug with UWP read notifications, this does not work (yet)
                //CharRX.ValueChanged += (obj, args) => ProcessRXData(args.CharacteristicValue);
                // var status = await CharRX.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                // if (status != GattCommunicationStatus.Success)
                // {
                //     throw new Exception("Could not connect to receive channel.");
                // }
                // Dbg("registered for rx notify: " + bta);
                #endregion
            }
            return(true);
        }