Exemple #1
0
        static void OnManagerConnectedPeripheral(object sender, CBPeripheralEventArgs e)
        {
            Console.WriteLine("Connected peripheral");

            peripheral.DiscoveredService             += OnPeripheralDiscoveredService;
            peripheral.DiscoveredCharacteristic      += OnPeripheralDiscoveredCharacteristic;
            peripheral.UpdatedCharacterteristicValue += OnPeripheralUpdatedCharacteristicValue;
            peripheral.DiscoverServices();
        }
Exemple #2
0
        public async Task <CBService> GetService(CBPeripheral peripheral, string serviceUuid)
        {
            var service = this.GetServiceIfDiscovered(peripheral, serviceUuid);

            if (service != null)
            {
                return(service);
            }

            var taskCompletion = new TaskCompletionSource <bool>();
            var task           = taskCompletion.Task;
            EventHandler <NSErrorEventArgs> handler = (s, e) =>
            {
                if (this.GetServiceIfDiscovered(peripheral, serviceUuid) != null)
                {
                    taskCompletion.SetResult(true);
                }
            };

            try
            {
                peripheral.DiscoveredService += handler;
                peripheral.DiscoverServices(new[] { CBUUID.FromString(serviceUuid) });
                await this.WaitForTaskWithTimeout(task, ConnectionTimeout);

                return(this.GetServiceIfDiscovered(peripheral, serviceUuid));
            }
            finally
            {
                peripheral.DiscoveredService -= handler;
            }
        }
Exemple #3
0
 protected override Task <IEnumerable <IService> > GetServicesNativeAsync()
 {
     return(TaskBuilder.FromEvent <IEnumerable <IService>, EventHandler <NSErrorEventArgs> >(
                execute: () => _nativeDevice.DiscoverServices(),
                getCompleteHandler: (complete, reject) => (sender, args) =>
     {
         // If args.Error was not null then the Service might be null
         if (args.Error != null)
         {
             reject(new Exception($"Error while discovering services {args.Error.LocalizedDescription}"));
         }
         else if (_nativeDevice.Services == null)
         {
             // No service discovered.
             reject(new Exception($"Error while discovering services: returned list is null"));
         }
         else
         {
             var services = _nativeDevice.Services
                            .Select(nativeService => new Service(nativeService, this))
                            .Cast <IService>().ToList();
             complete(services);
         }
     },
                subscribeComplete: handler => _nativeDevice.DiscoveredService += handler,
                unsubscribeComplete: handler => _nativeDevice.DiscoveredService -= handler));
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:WatchTower.iOS.BluetoothSensorMonitor"/> class.
        /// </summary>
        /// <param name="manager">Manager.</param>
        /// <param name="peripheral">Peripheral.</param>
        public BluetoothSensorMonitor(CBCentralManager manager, CBPeripheral peripheral)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

            if (peripheral == null)
            {
                throw new ArgumentNullException(nameof(peripheral));
            }

            // set creation order to allow for sorting
            this.CreationOrder = ++BluetoothSensorMonitor._creationOrder;

            Manager = manager;

            Peripheral          = peripheral;
            Peripheral.Delegate = new SensorPeripheralDelegate(this);

            // Find the services advertised by the peripheral
            Peripheral.DiscoverServices();
            SensorHandler = new SensorHandler(GetDeviceDetailsMap(peripheral.Name), _watchTowerSettings.UserID);

            PresentButDisconnected = false;

            bIsHexoskinMonitor = false;
            _name = peripheral.Name;
        }
        private IReadOnlyList <GattDeviceService> GetGattServices()
        {
            if (_services.Count == 0)
            {
                _peripheral.DiscoveredService += _peripheral_DiscoveredService;
                var state = _peripheral.State;
                if (state == CBPeripheralState.Disconnected)
                {
                    BluetoothAdapter.Default.Manager.ConnectPeripheral(_peripheral);
                    Thread.Sleep(1000);
                }

                if (_peripheral.State == CBPeripheralState.Connected)
                {
                    _peripheral.DiscoverServices();
                    Task.Run(() =>
                    {
                        Task.Delay(6000);
                        _servicesHandle.Set();
                    });
                    _servicesHandle.WaitOne();
                    foreach (CBService service in _peripheral?.Services)
                    {
                        _services.Add(new GattDeviceService(service, _peripheral));
                    }
                }
            }


            return(_services.AsReadOnly());
        }
        public override void DiscoverServices()
        {
            if (Peripheral == null)
                return;

            Peripheral.DiscoverServices();
        }
Exemple #7
0
        // This method gets the services of connected device
        public async Task GetServices(CBPeripheral peripheral)
        {
            peripheral.Delegate = new PeripheralDelegate();

            peripheral.DiscoverServices();
            await Task.Delay(2000);
        }
Exemple #8
0
 private void GetServices(CBPeripheral peripheral)
 {
     peripheral.DiscoveredService += (o, e) =>
     {
     };
     peripheral.DiscoverServices();
 }
Exemple #9
0
 public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
 {
     client._isConnected = true;
     peripheral.Delegate = client.peripheralDelegate;
     peripheral.DiscoverServices(null);
     client.connectedPeripheral = peripheral;
     client.serviceObjects.Clear();
     client.characteristicObjects.Clear();
     client.descriptorObjects.Clear();
 }
Exemple #10
0
        void ConnectedPeripheral(object sender, CBPeripheralEventArgs e)
        {
            Console.Error.WriteLine("Connected. Discovering services.");
            central.ConnectedPeripheral -= ConnectedPeripheral;
            central.StopScan();
            connectedCbPeripheral = e.Peripheral;

            connectedCbPeripheral.DiscoveredService             += DiscoveredService;
            connectedCbPeripheral.UpdatedCharacterteristicValue += UpdatedCharacterteristicValue;
            connectedCbPeripheral.WroteCharacteristicValue      += WroteCharacteristicValue;
            connectedCbPeripheral.DiscoverServices();
        }
        public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
        {
            SensusServiceHelper.Get().Logger.Log("Connected to peripheral. Discovering its services...", LoggingLevel.Normal, GetType());

            try
            {
                peripheral.DiscoverServices(new CBUUID[] { _service.UUID });
            }
            catch (Exception ex)
            {
                SensusServiceHelper.Get().Logger.Log("Exception while discovering services:  " + ex.Message, LoggingLevel.Normal, GetType());
            }
        }
Exemple #12
0
 public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
 {
     // discover services for newly connected peripheral
     try
     {
         peripheral.DiscoverServices(new CBUUID[] { _probe.DeviceIdService.UUID });
     }
     catch (Exception ex)
     {
         SensusServiceHelper.Get().Logger.Log("Exception while discovering services." + ex.Message, LoggingLevel.Normal, GetType());
         DisconnectPeripheral(central, peripheral);
     }
 }
Exemple #13
0
        public async partial Task <IEnumerable <GattService> > GetServicesAsync(IEnumerable <Guid>?uuids)
        {
            var cbUuids      = uuids?.Select(x => CBUUID.FromString(x.ToString())).ToArray();
            var errorAwaiter = @delegate.DiscoveredServiceObservable.FirstAsync().GetAwaiter();

            peripheral.DiscoverServices(cbUuids);
            var error = await errorAwaiter;

            if (error is not null)
            {
                throw new NSErrorException(error);
            }

            return(peripheral.Services?.Select(x => new GattService(peripheral, @delegate, this, x))
                   ?? Enumerable.Empty <GattService>());
        }
Exemple #14
0
        void InitializePeripheral()
        {
            // update all our shit

            // > peripheral
            //   > service[s]
            //		> characteristic
            //			> value
            //			> descriptor[s]

            Title = connectedPeripheral.Name;

            // when a device disconnects, show an alert and unload this screen
            BluetoothLEManager.Current.DeviceDisconnected += HandleDeviceDisconnected;
            connectedPeripheral.DiscoveredService         += HandleDiscoveredService;
            connectedPeripheral.DiscoverServices();
        }
Exemple #15
0
        protected override Task <IReadOnlyList <IService> > GetServicesNativeAsync()
        {
            var exception = new Exception($"Device {Name} disconnected while fetching services.");

            return(TaskBuilder.FromEvent <IReadOnlyList <IService>, EventHandler <NSErrorEventArgs>, EventHandler <CBPeripheralErrorEventArgs> >(
                       execute: () =>
            {
                if (_nativeDevice.State != CBPeripheralState.Connected)
                {
                    throw exception;
                }

                _nativeDevice.DiscoverServices();
            },
                       getCompleteHandler: (complete, reject) => (sender, args) =>
            {
                // If args.Error was not null then the Service might be null
                if (args.Error != null)
                {
                    reject(new Exception($"Error while discovering services {args.Error.LocalizedDescription}"));
                }
                else if (_nativeDevice.Services == null)
                {
                    // No service discovered.
                    reject(new Exception($"Error while discovering services: returned list is null"));
                }
                else
                {
                    var services = _nativeDevice.Services
                                   .Select(nativeService => new Service(nativeService, this, _bleCentralManagerDelegate))
                                   .Cast <IService>().ToList();
                    complete(services);
                }
            },
                       subscribeComplete: handler => _nativeDevice.DiscoveredService += handler,
                       unsubscribeComplete: handler => _nativeDevice.DiscoveredService -= handler,
                       getRejectHandler: reject => ((sender, args) =>
            {
                if (args.Peripheral.Identifier == _nativeDevice.Identifier)
                {
                    reject(exception);
                }
            }),
                       subscribeReject: handler => _bleCentralManagerDelegate.DisconnectedPeripheral += handler,
                       unsubscribeReject: handler => _bleCentralManagerDelegate.DisconnectedPeripheral -= handler));
        }
Exemple #16
0
        public void CentralManager_ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
        {
            Debug.WriteLine("CentralManager_ConnectedPeripheral: " + peripheral.Name);

            if (_reconnecting)
            {
                _reconnecting = false;
                BoardReconnected?.Invoke();
            }
            else
            {
                //_connectionCompletionSource.SetResult(true);

                var services = _peripheral.Services;
                _peripheral.DiscoverServices(new CBUUID[] { OWBoard.ServiceUUID.ToCBUUID() });
            }
        }
        public HeartRateMonitor(CBCentralManager manager, CBPeripheral peripheral)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            else if (peripheral == null)
            {
                throw new ArgumentNullException("peripheral");
            }

            Location = HeartRateMonitorLocation.Unknown;

            Manager = manager;

            Peripheral          = peripheral;
            Peripheral.Delegate = this;
            Peripheral.DiscoverServices();
        }
Exemple #18
0
        public HeartRateMonitor(CBCentralManager manager, CBPeripheral peripheral)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

            if (peripheral == null)
            {
                throw new ArgumentNullException(nameof(peripheral));
            }

            Location = HeartRateMonitorLocation.Unknown;

            Manager = manager;

            Peripheral          = peripheral;
            Peripheral.Delegate = new HeartRateMonitorDelegate(this);
            Peripheral.DiscoverServices();
        }
Exemple #19
0
        internal void OnDeviceConnected()
        {
            lock (_lock)
            {
                if (State == BluetoothLEDeviceState.Connecting)
                {
                    State = BluetoothLEDeviceState.Discovering;
                    Task.Run(() =>
                    {
                        Thread.Sleep(750);

                        lock (_lock)
                        {
                            if (State == BluetoothLEDeviceState.Discovering)
                            {
                                _peripheral.DiscoverServices();
                            }
                        }
                    });
                }
            }
        }
Exemple #20
0
        private async Task MapDevice(Device device, CBPeripheral nativeDevice)
        {
            nativeDevice.DiscoveredService += nativeDevice_DiscoveredService;

            nativeDevice.DiscoverServices();
            await Task.Run(() => _servicesDiscovered.WaitOne(TimeSpan.FromSeconds(10)));

            nativeDevice.DiscoveredService -= nativeDevice_DiscoveredService;
            _servicesDiscovered.Reset();

            foreach (var cbService in nativeDevice.Services)
            {
                nativeDevice.DiscoveredCharacteristic += nativeDevice_DiscoveredCharacteristic;

                nativeDevice.DiscoverCharacteristics(cbService);
                await Task.Run(() => _characteristicsDiscovered.WaitOne(TimeSpan.FromSeconds(10)));

                nativeDevice.DiscoveredCharacteristic -= nativeDevice_DiscoveredCharacteristic;
                _characteristicsDiscovered.Reset();

                var service = new Service()
                {
                    Id              = BluetoothConverter.ConvertBluetoothLeUuid(cbService.UUID.Uuid),
                    Device          = device,
                    Characteristics = new List <Characteristic>()
                };

                foreach (var cbCharacteristic in cbService.Characteristics)
                {
                    var characteristic = await ConvertCharacteristic(cbCharacteristic);

                    characteristic.Service = service;
                    service.Characteristics.Add(characteristic);
                }
                service.Device = device;
                device.Services.Add(service);
            }
        }
Exemple #21
0
        protected override async Task <IEnumerable <IService> > GetServicesNativeAsync()
        {
            var tcs = new TaskCompletionSource <IEnumerable <IService> >();
            EventHandler <NSErrorEventArgs> handler = null;

            handler = (sender, args) =>
            {
                _nativeDevice.DiscoveredService -= handler;

                if (args.Error != null)
                {
                    Trace.Message("Error while discovering services {0}", args.Error.LocalizedDescription);
                }

                // why we have to do this check is beyond me. if a service has been discovered, the collection
                // shouldn't be null, but sometimes it is. le sigh, apple.
                if (_nativeDevice.Services == null)
                {
                    // TODO: review: return? really? Will the Task end?
                    return;
                }

                var services = new Dictionary <CBUUID, IService>();
                foreach (var s in _nativeDevice.Services)
                {
                    Trace.Message("Device.Discovered Service: " + s.Description);
                    services[s.UUID] = new Service(s, this);
                }

                tcs.TrySetResult(services.Values);
            };

            _nativeDevice.DiscoveredService += handler;
            _nativeDevice.DiscoverServices();

            return(await tcs.Task);
        }
 /// <summary>
 /// Initiate a service discovery on the device
 /// </summary>
 public void DiscoverServices()
 {
     _peripheral.DiscoverServices();
 }
Exemple #23
0
 public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
 {
     _parent.OnStatusUpdated("Discovering services");
     peripheral.DiscoverServices(new[] { CBUUID.FromString(ServiceUuid) });
 }
		public HeartRateMonitor (CBCentralManager manager, CBPeripheral peripheral)
		{
			if (manager == null) {
				throw new ArgumentNullException ("manager");
			} else if (peripheral == null) {
				throw new ArgumentNullException ("peripheral");
			}
			
			Location = HeartRateMonitorLocation.Unknown;
			
			Manager = manager;

			Peripheral = peripheral;
			Peripheral.Delegate = this;
			Peripheral.DiscoverServices ();
		}
Exemple #25
0
 public Task <List <IBLEService> > GetServicesAsync()
 {
     deviceTaskCompletitionSource.ServicesDiscoveryTCS = new TaskCompletionSource <List <IBLEService> >();
     _device.DiscoverServices();
     return(deviceTaskCompletitionSource.ServicesDiscoveryTCS.Task);
 }
Exemple #26
0
 public void DiscoverServices()
 {
     nativePeripheral.DiscoverServices();
 }
Exemple #27
0
 public override void DiscoverServices()
 {
     _nativeDevice.DiscoverServices();
 }
Exemple #28
0
 /// <summary>
 /// Initiate a service discovery on the device
 /// </summary>
 public void DiscoverServices()
 {
     _peripheral.DiscoverServices();
     _peripheral.DiscoveredService -= DiscoveredService;
     _peripheral.DiscoveredService += DiscoveredService;
 }