Ejemplo n.º 1
0
		public void SetPeripheralAndService (CBPeripheral peripheral, CBService service)
		{
			this._connectedPeripheral = peripheral;
			this._currentService = service;

			// discover the charactersistics
			this._connectedPeripheral.DiscoverCharacteristics(service);

			// should be named "DiscoveredCharacteristic"
			this._connectedPeripheral.DiscoverCharacteristic += (object sender, CBServiceEventArgs e) => {
				Console.WriteLine ("Discovered Characteristic.");
				foreach (CBService srv in ((CBPeripheral)sender).Services) {

					// if the service has characteristics yet
					if(srv.Characteristics != null) {
						foreach (var characteristic in service.Characteristics) {
							Console.WriteLine("Characteristic: " + characteristic.Description);

							this._characteristics.Add (characteristic);
							this.CharacteristicsTable.ReloadData();
						}
					}
				}
			};

			// when a descriptor is dicovered, reload the table.
			this._connectedPeripheral.DiscoveredDescriptor += (object sender, CBCharacteristicEventArgs e) => {
				foreach (var descriptor in e.Characteristic.Descriptors) {
					Console.WriteLine ("Characteristic: " + e.Characteristic.Value + " Discovered Descriptor: " + descriptor);	
				}
				// reload the table
				this.CharacteristicsTable.ReloadData();
			};

		}
Ejemplo n.º 2
0
 public BluetoothServiceHandler(CBPeripheral peripheral)
 {
     _peripheral = peripheral;
     _peripheral.DiscoveredService += OnDiscoveredService;
     _peripheral.DiscoverCharacteristic += DiscoveredCharacteristic;
     _peripheral.UpdatedNotificationState += OnUpdatedNotificationState;
 }
Ejemplo n.º 3
0
 public PeripheralHandler(CBPeripheral peripheral)
 {
     _peripheral = peripheral;
     _serviceHandler = new BluetoothServiceHandler(peripheral);
     User = UserStorage.Instance.GetUser(peripheral.Identifier);
     _peripheral.UpdatedCharacterteristicValue += OnUpdatedValue;
 }
Ejemplo n.º 4
0
		public Service (CBService nativeService, CBPeripheral parentDevice )
		{
			this._nativeService = nativeService;
			this._parentDevice = parentDevice;


		}
 public override void DiscoveredService(CBPeripheral peripheral, NSError error)
 {
     System.Console.WriteLine ("Discovered a service");
     foreach (var service in peripheral.Services) {
         Console.WriteLine (service.ToString ());
         peripheral.DiscoverCharacteristics (service);
     }
 }
 public override void DiscoveredCharacteristic(CBPeripheral peripheral, CBService service, NSError error)
 {
     System.Console.WriteLine ("Discovered characteristics of " + peripheral);
     foreach (var c in service.Characteristics) {
         Console.WriteLine (c.ToString ());
         peripheral.ReadValue (c);
     }
 }
Ejemplo n.º 7
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BluetoothLE.iOS.Characteristic"/> class.
		/// </summary>
		/// <param name="peripheral">The native peripheral.</param>
		/// <param name="nativeCharacteristic">The native characteristic.</param>
		public Characteristic(CBPeripheral peripheral, CBCharacteristic nativeCharacteristic)
		{
			_peripheral = peripheral;
			_peripheral.UpdatedCharacterteristicValue += UpdatedCharacteristicValue;
			_nativeCharacteristic = nativeCharacteristic;

			_id = _nativeCharacteristic.UUID.ToString().ToGuid();
		}
 protected virtual void OnConnectionUpdated(CBPeripheral peripheral)
 {
     var peripheralHandler = _peripheralHandlerList.FirstOrDefault(p => p.Uuid.IsUuidEqual(peripheral.Identifier));
     if (peripheralHandler != null)
     {
         peripheralHandler.User.IsConnected = peripheralHandler.IsConnected;
     }
 }
Ejemplo n.º 9
0
		NSUuid GetIdentifier(CBPeripheral peripheral)
		{
			// TODO: https://trello.com/c/t1dmC7hh
			if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
				return peripheral.Identifier;
			else
				return new NSUuid (); // here we should get UUID instead of Identifier
		}
Ejemplo n.º 10
0
        public async Task<PeripheralHandler> CreateHandlerAsync(CBPeripheral peripheral)
        {
            var handler = new PeripheralHandler(peripheral);

            await handler.InitializeAsync();

            List.Add(handler);
            return handler;
        }
Ejemplo n.º 11
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BluetoothLE.iOS.Device"/> class.
		/// </summary>
		/// <param name="peripheral">Native peripheral.</param>
		public Device(CBPeripheral peripheral)
		{
			_peripheral = peripheral;
			_id = DeviceIdentifierToGuid(_peripheral.Identifier);

			_peripheral.DiscoveredService += DiscoveredService;

			Services = new List<IService>();
		}
Ejemplo n.º 12
0
		public Device (CBPeripheral nativeDevice)
		{
			this._nativeDevice = nativeDevice;

			this._nativeDevice.DiscoveredService += (object sender, NSErrorEventArgs e) => {
				// 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 (this._nativeDevice.Services != null) {
					
					foreach (CBService s in this._nativeDevice.Services) 
					{
						if(!ServiceExists(s)) 
						{
							Console.WriteLine ("Device.Discovered Service: " + s.Description);
							this._services.Add (new Service(s, this._nativeDevice));
						}
					}

					this.ServicesDiscovered(this, new EventArgs());
				}
			};

			#if __UNIFIED__
			// fixed for Unified https://bugzilla.xamarin.com/show_bug.cgi?id=14893
			this._nativeDevice.DiscoveredCharacteristic += (object sender, CBServiceEventArgs e) => {
			#else
			//BUGBUG/TODO: this event is misnamed in our SDK
			this._nativeDevice.DiscoverCharacteristic += (object sender, CBServiceEventArgs e) => {
			#endif
				Console.WriteLine ("Device.Discovered Characteristics.");
				//loop through each service, and update the characteristics
				foreach (CBService srv in ((CBPeripheral)sender).Services) {
					// if the service has characteristics yet
					if(srv.Characteristics != null) {

						// locate the our new service
						foreach (var item in this.Services) {
							// if we found the service
							if (item.ID == Service.ServiceUuidToGuid(srv.UUID) ) {
								item.Characteristics.Clear();

								// add the discovered characteristics to the particular service
								foreach (var characteristic in srv.Characteristics) {
									Console.WriteLine("Device: Characteristic: " + characteristic.Description);
									Characteristic newChar = new Characteristic(characteristic, _nativeDevice);
									item.Characteristics.Add(newChar);
								}
								// inform the service that the characteristics have been discovered
								// TODO: really, we should just be using a notifying collection.
								(item as Service).OnCharacteristicsDiscovered();
							}
						}
					}
				}			
			};
		}
Ejemplo n.º 13
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BluetoothLE.iOS.Service"/> class.
		/// </summary>
		/// <param name="peripheral">The native peripheral.</param>
		/// <param name="service">The native service.</param>
		public Service(CBPeripheral peripheral, CBService service)
		{
			_peripheral = peripheral;
			_nativeService = service;

			_id = service.UUID.ToString().ToGuid();

			_peripheral.DiscoveredCharacteristic += DiscoveredCharacteristic;

			Characteristics = new List<ICharacteristic>();
		}
Ejemplo n.º 14
0
        public void Add(CBPeripheral peripheral, string localNameKey)
        {
            if (_userList.Any(u => u.DeviceUuid.IsUuidEqual(peripheral.Identifier)))
            {
                return;
            }

            StoreInList(peripheral);
            var user = new User(localNameKey, peripheral.Identifier);
            _userList.Add(user);

            OnFoundUser(user);
        }
Ejemplo n.º 15
0
        public Device(Adapter adapter, CBPeripheral nativeDevice, string name, int rssi, List<AdvertisementRecord> advertisementRecords) : base(adapter)
        {
            _nativeDevice = nativeDevice;
            Id = Guid.ParseExact(_nativeDevice.Identifier.AsString(), "d");
            Name = name;

            Rssi = rssi;
            AdvertisementRecords = advertisementRecords;

            // TODO figure out if this is in any way required,  
            // https://github.com/xabre/xamarin-bluetooth-le/issues/81
            //_nativeDevice.UpdatedName += OnNameUpdated;
        }
Ejemplo n.º 16
0
		public void SetPeripheralAndService (CBPeripheral peripheral, CBService service)
		{
			connectedPeripheral = peripheral;

			connectedPeripheral.DiscoveredCharacteristic += (sender, e) => {
				HandleDiscoveredCharacteristic((CBPeripheral)sender, service);
			};

			// when a descriptor is dicovered, reload the table.
			connectedPeripheral.DiscoveredDescriptor += HandleDiscoveredDescriptor;

			// discover the charactersistics
			connectedPeripheral.DiscoverCharacteristics(service);
		}
Ejemplo n.º 17
0
		void HandleDiscoveredCharacteristic (CBPeripheral peripheral, CBService service)
		{
			Console.WriteLine ("Discovered Characteristic.");
			foreach (CBService srv in peripheral.Services) {
				// if the service has characteristics yet
				if (srv.Characteristics == null)
					continue;

				foreach (var characteristic in service.Characteristics) {
					Console.WriteLine("Characteristic: {0}", characteristic.Description);
					characteristics.Add (characteristic);
				}
				CharacteristicsTable.ReloadData();
			}
		}
Ejemplo n.º 18
0
		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 ();
		}
        void HandleDiscoveredCharacteristic(CBPeripheral peripheral, CBService service)
        {
            Console.WriteLine("Discovered Characteristic.");
            foreach (CBService srv in peripheral.Services)
            {
                // if the service has characteristics yet
                if (srv.Characteristics == null)
                {
                    continue;
                }

                foreach (var characteristic in service.Characteristics)
                {
                    Console.WriteLine("Characteristic: {0}", characteristic.Description);
                    characteristics.Add(characteristic);
                }
                CharacteristicsTable.ReloadData();
            }
        }
Ejemplo n.º 20
0
            /// <summary>
            /// Occurs when a new service is discovered for the peripheral
            /// </summary>
            /// <param name="peripheral">Peripheral.</param>
            /// <param name="error">Error.</param>
            public override void DiscoveredService(CBPeripheral peripheral, NSError error)
            {
                if (monitor.disposed)
                {
                    return;
                }

                foreach (var service in peripheral.Services)
                {
                    // Right now limited to POC and Zephyr services
                    if (service.UUID == BluetoothIdentifiers.POCServiceUUID ||
                        service.UUID == BluetoothIdentifiers.ZephyrServiceUUID)                           //GetCBUUID(S_PERIPHERAL_UUID))
                    {
                        peripheral.DiscoverCharacteristics(service);
                    }

                    Console.WriteLine($"discovered service: {service.UUID}");
                }
            }
        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();
        }
Ejemplo n.º 22
0
            /// <summary>
            /// Occurs when the value for a characteristic is updated
            /// </summary>
            /// <param name="peripheral">Peripheral.</param>
            /// <param name="characteristic">Characteristic.</param>
            /// <param name="error">Error.</param>
            public override void UpdatedCharacterteristicValue(
                CBPeripheral peripheral,
                CBCharacteristic characteristic, NSError error)
            {
                DateTime dtNow = DateTime.Now;

                /* If we haven't yet reach cutoff time for current update,
                 * OR we've passed the time after which we want to start updates...*/
                if ((dtNow < _dtCurrentUpdateEnd)
                    ||
                    ((dtNow > _dtNextTimeToUpdate)))
                {
                    //Console.WriteLine($"updating value for characteristic {characteristic.UUID}");
                    if (monitor.disposed || error != null || characteristic.Value == null)
                    {
                        return;
                    }

                    if (characteristic.UUID == BluetoothIdentifiers.POCHeartRateMeasurementCharacteristicUUID ||
                        characteristic.UUID == BluetoothIdentifiers.ZephyrHeartRateCharacteristicUUID)
                    {
                        monitor.UpdateData(characteristic.Value);
                    }

                    // If no update is currently occurring, set flag and update next times
                    if (!_bUpdateOccurring)
                    {
                        // set flag for a new update session
                        _bUpdateOccurring = true;

                        // calculate ending time of current session
                        _dtCurrentUpdateEnd = dtNow.AddSeconds(_secondsToGatherUpdates);

                        // calculate next starting time based on ending time
                        _dtNextTimeToUpdate = _dtCurrentUpdateEnd.AddSeconds(_secondsBetweenUpdateProcessing);
                    }
                }
                else
                {
                    _bUpdateOccurring = false;
                }
            }
Ejemplo n.º 23
0
            /// <summary>
            /// Occurs when a new characteristic is discovered for  aservice
            /// </summary>
            /// <param name="peripheral">Peripheral.</param>
            /// <param name="service">Service.</param>
            /// <param name="error">Error.</param>
            public override void DiscoveredCharacteristic(CBPeripheral peripheral,
                                                          CBService service, NSError error)
            {
                if (monitor.disposed)
                {
                    return;
                }

                foreach (var characteristic in service.Characteristics)
                {
                    Console.WriteLine($"discovered characteristic: {characteristic.UUID}");

                    // Right now limited to POC and Zephyr hear rate characteristics
                    if (characteristic.UUID == BluetoothIdentifiers.POCHeartRateMeasurementCharacteristicUUID ||
                        characteristic.UUID == BluetoothIdentifiers.ZephyrHeartRateCharacteristicUUID)
                    {
                        service.Peripheral.SetNotifyValue(true, characteristic);
                    }
                }
            }
Ejemplo n.º 24
0
        public bool openConnection(string ids)
        {
            throw new NotImplementedException();
#pragma warning disable CS0162 // Se ha detectado código inaccesible
            foreach (CBPeripheral p in discoveredDevices)
#pragma warning restore CS0162 // Se ha detectado código inaccesible
            {
                if (p.UUID.Equals(CBUUID.FromString(ids)))
                {
                    CurrentPeripheral = p;
                }
            }
            if (CurrentPeripheral != null)
            {
                bluetoothManager.ConnectPeripheral(CurrentPeripheral);
            }
            //    List<CBPeripheral> peri= bluetoothManager.RetrieveConnectedPeripherals();
            //  CBPeripheral peripheral = bluetoothManager.RetrievePeripherals(CBUUID.FromString(ids));
            //bluetoothManager.ConnectPeripheral
        }
Ejemplo n.º 25
0
        public override void UpdatedCharacterteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
        {
            lock (_lock)
            {
                var data = error == null?characteristic.Value?.ToArray() : null;

                if (_readCompletionSource != null)
                {
                    _readCompletionSource.TrySetResult(data);
                }
                else
                {
                    if (error == null)
                    {
                        var guid = characteristic.UUID.ToGuid();
                        _onCharacteristicChanged?.Invoke(guid, data);
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public void CentralManager_DisconnectedPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error)
        {
            Debug.WriteLine("CentralManager_DisconnectedPeripheral");

            BoardDisconnected?.Invoke();


            if (_requestingDisconnect)
            {
                // Disconnect was because the user hit the disconnect button.
                if (_disconnectionCompletionSource != null)
                {
                    _disconnectionCompletionSource.TrySetResult(true);
                }
            }
            else
            {
                Reconnect();
            }
        }
Ejemplo n.º 27
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();
        }
Ejemplo n.º 28
0
        //TODO Submit Bug to change the methid name to "DiscoveredServices" as this method will fire only when all the Services are discovered
        public async override void DiscoveredService(CBPeripheral peripheral, NSError error)
        {
            base.DiscoveredService(peripheral, error);

            foreach (var item in peripheral.Services)
            {
                var service = new BLEService(item);

                if (peripheral.Delegate == null)
                {
                    peripheral.Delegate = this;
                }

                service.Characteristics = await service.GetCharacteristicsAsync(peripheral, _deviceTaskCompletitionSource.CharacteristicDiscoveryTCS);

                servicesList.Add(service);
            }

            _deviceTaskCompletitionSource.ServicesDiscoveryTCS.SetResult(servicesList);
        }
Ejemplo n.º 29
0
 public Device(CBPeripheral nativeDevice)
 {
     this.nativeDevice = nativeDevice;
     this.nativeDevice.DiscoveredService += (object sender, NSErrorEventArgs e) =>
     {
         if (this.nativeDevice.Services != null)
         {
             foreach (CBService s in this.nativeDevice.Services)
             {
                 Console.WriteLine("Device.Discovered Service: " + s.Description);
                 if (!ServiceExists(s))
                 {
                     services.Add(new Service(s, this.nativeDevice));
                 }
             }
             ServicesDiscovered(this, new EventArgs());
         }
     };
     this.nativeDevice.DiscoveredCharacteristic += NativeDeviceDiscoveredCharacteristic;
 }
Ejemplo n.º 30
0
        public BleDeviceiOS(BleManageriOS owner, CBPeripheral peripheral, NSDictionary advertisement, int rssi)
        {
            Owner = owner;


            Peripheral = peripheral;

            Name = Peripheral.Name;
            ID = Peripheral.Identifier.ToString();

            //Todo: check this won't cause memory leak when object get delete.
            Peripheral.DiscoveredService += HandleDiscoveredService;
            Peripheral.RssiUpdated += HandleRssiUpdated;
            Peripheral.UpdatedCharacterteristicValue += HandleUpdatedCharacterteristicValue;
            Peripheral.WroteCharacteristicValue += HandleWroteCharacteristicValue;
            Peripheral.UpdatedValue += HandleUpdatedValue;
            Peripheral.WroteDescriptorValue += HandleWroteDescriptorValue;


        }
Ejemplo n.º 31
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            CBCentralManager manager    = new CBCentralManager();
            CBPeripheral     peripheral =
                //manager.ConnectPeripheral(new CBPeripheral())

                //var communication = new BluetoothCommunication(@"PPAP09");
                //var brick = new Brick(communication);
                //var command = new DirectCommand(brick);

                //brick.ConnectAsync();

                communication.ReportReceived += async(object sender, ReportReceivedEventArgs e) => {
                await command.TurnMotorAtSpeedAsync(OutputPort.B, 50);

                await command.StartMotorAsync(OutputPort.B);

                await Task.Delay(2000);
            };

            btnForward.TouchUpInside += (sender, e) => {
            };

            btnBackward.TouchUpInside += (sender, e) => {
            };

            btnLeft.TouchUpInside += (sender, e) => {
            };

            btnRight.TouchUpInside += (sender, e) => {
            };


            btnGo.TouchUpInside += (sender, e) => {
            };

            btnStop.TouchUpInside += (sender, e) => {
            };
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Connects to known device async.
        /// https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForInteractingWithARemotePeripheralDevice/BestPracticesForInteractingWithARemotePeripheralDevice.html
        /// </summary>
        /// <returns>The to known device async.</returns>
        /// <param name="deviceGuid">Device GUID.</param>
        public override async Task <IDevice> ConnectToKnownDeviceAsync(Guid deviceGuid,
                                                                       ConnectParameters connectParameters = default(ConnectParameters),
                                                                       CancellationToken cancellationToken = default(CancellationToken))
        {
            // Wait for the PoweredOn state
            await this.WaitForState(CBCentralManagerState.PoweredOn, cancellationToken, true);

            if (cancellationToken.IsCancellationRequested)
            {
                throw new TaskCanceledException("ConnectToKnownDeviceAsync cancelled");
            }

            //FYI attempted to use tobyte array insetead of string but there was a problem with byte ordering Guid->NSUui
            NSUuid uuid = new NSUuid(deviceGuid.ToString());

            Trace.Message($"[Adapter] Attempting connection to {uuid}");

            CBPeripheral[] peripherials = this._centralManager.RetrievePeripheralsWithIdentifiers(uuid);
            CBPeripheral   peripherial  = peripherials.SingleOrDefault();

            if (peripherial == null)
            {
                CBPeripheral[] systemPeripherials = this._centralManager.RetrieveConnectedPeripherals(new CBUUID[0]);

                CBUUID cbuuid = CBUUID.FromNSUuid(uuid);
                peripherial = systemPeripherials.SingleOrDefault(p => p.UUID.Equals(cbuuid));

                if (peripherial == null)
                {
                    throw new Exception($"[Adapter] Device {deviceGuid} not found.");
                }
            }


            Device device = new Device(this, peripherial, this._centralManager, peripherial.Name,
                                       peripherial.RSSI?.Int32Value ?? 0, new List <AdvertisementRecord>());

            await this.ConnectToDeviceAsync(device, connectParameters, cancellationToken);

            return(device);
        }
Ejemplo n.º 33
0
        Task PlatformWriteValue(byte[] value, bool requireResponse)
        {
            TaskCompletionSource <bool> tcs = null;
            CBPeripheral peripheral         = Service.Device;

            if (requireResponse)
            {
                tcs = new TaskCompletionSource <bool>();

                void handler(object s, CBCharacteristicEventArgs e)
                {
                    if (e.Characteristic == _characteristic)
                    {
                        peripheral.WroteCharacteristicValue -= handler;

                        if (!tcs.Task.IsCompleted)
                        {
                            tcs.SetResult(e.Error == null);
                        }
                    }
                };

                peripheral.WroteCharacteristicValue += handler;
            }

            CBCharacteristicWriteType writeType = requireResponse ? CBCharacteristicWriteType.WithResponse : CBCharacteristicWriteType.WithoutResponse;

            if (!requireResponse && !peripheral.CanSendWriteWithoutResponse)
            {
                writeType = CBCharacteristicWriteType.WithResponse;
            }

            ((CBPeripheral)Service.Device).WriteValue(NSData.FromArray(value), _characteristic, writeType);

            if (requireResponse)
            {
                return(tcs.Task);
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 34
0
        public void connect(string deviceAddress)
        {
            if (connectedPeripheral != null)
            {
                disconnect();
            }
            var dev = devices.FirstOrDefault((item) => item.Identifier.ToString().ToUpper().Equals(deviceAddress.ToUpper()));

            if (dev == null)
            {
                return;
            }
            connectedPeripheral = dev; // Make sure we have a reference to this so that it can be canceled while connection is pending
            var options = new PeripheralConnectionOptions();

            options.NotifyOnConnection    = true;
            options.NotifyOnDisconnection = true;
            options.NotifyOnNotification  = true;

            centralManager.ConnectPeripheral(dev, options);
        }
Ejemplo n.º 35
0
        public void DiscoveredService(CBPeripheral peripheral, NSError error)
        {
            Debug.WriteLine($"Peripheral_DiscoveredService: {peripheral.Name}");

            CBService foundService = null;

            foreach (var service in peripheral.Services)
            {
                if (service.UUID == OWBoard.ServiceUUID.ToCBUUID())
                {
                    foundService = service;
                    break;
                }
            }

            if (foundService != null)
            {
                _service = foundService;
                _peripheral.DiscoverCharacteristics(_service);
            }
        }
Ejemplo n.º 36
0
        public void DiscoveredCharacteristic(CBPeripheral peripheral, CBService service, NSError error)
        {
            Debug.WriteLine("Peripheral_DiscoveredCharacteristic");
            //var cbuuid = CBUUID.FromString(characteristicGuid);
            foreach (var characteristic in _service.Characteristics)
            {
                if (_characteristics.ContainsKey(characteristic.UUID))
                {
                    _characteristics[characteristic.UUID] = characteristic;
                }
                else
                {
                    _characteristics.Add(characteristic.UUID, characteristic);
                }
            }

            _connectionCompletionSource.SetResult(true);

            //BoardConnected?.Invoke(null);
            //BoardConnected?.Invoke(new OWBoard(_board));
        }
Ejemplo n.º 37
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);
            }
        }
Ejemplo n.º 38
0
        Task <byte[]> PlatformReadValue()
        {
            TaskCompletionSource <byte[]> tcs = new TaskCompletionSource <byte[]>();
            CBPeripheral peripheral           = Characteristic.Service.Device;

            void handler(object s, CBDescriptorEventArgs e)
            {
                if (e.Descriptor == _descriptor)
                {
                    peripheral.UpdatedValue -= handler;

                    if (!tcs.Task.IsCompleted)
                    {
                        tcs.SetResult(NSObjectToBytes(e.Descriptor.Value));
                    }
                }
            };

            peripheral.UpdatedValue += handler;

            ((CBPeripheral)Characteristic.Service.Device).ReadValue(_descriptor);
            return(tcs.Task);
        }
Ejemplo n.º 39
0
        public FirmwareUpdater(CBPeripheral peripheral)
        {
            cbCentralManager = new CBCentralManager();

            /**
             * Creates the DFU Firmware object from a Distribution packet (ZIP).
             * returns: The DFU firmware object or `nil` in case of an error.
             */
            var path    = NSBundle.MainBundle.PathForResource("softdevice_s140", ".zip");
            var urlPath = new NSUrl("file://" + path);

            dfuFirmware = new DFUFirmware(urlPath);


            dfuServiceInitiator = new DFUServiceInitiator(cbCentralManager, peripheral);
            dfuServiceInitiator.PacketReceiptNotificationParameter = 12;

            dfuServiceInitiator.EnableUnsafeExperimentalButtonlessServiceInSecureDfu = true;
            dfuServiceInitiator.ProgressDelegate = new DfuServiceDelegateImplementation(dfuLogger);
            dfuServiceInitiator.Logger           = new DfuLogger();

            dfuServiceInitiator.WithFirmware(dfuFirmware);
        }
Ejemplo n.º 40
0
        public BLECBPeripheralWrapper(CBPeripheral peripheral)
        {
            _wes = new WeakEventSource();

            Peripheral = peripheral;

            Peripheral.DidOpenL2CapChannel               += OnDidOpenL2CapChannel;
            Peripheral.DiscoveredCharacteristic          += OnDiscoveredCharacteristic;
            Peripheral.DiscoveredDescriptor              += OnDiscoveredDescriptor;
            Peripheral.DiscoveredIncludedService         += OnDiscoveredIncludedService;
            Peripheral.DiscoveredService                 += OnDiscoveredService;
            Peripheral.InvalidatedService                += OnInvalidatedService;
            Peripheral.IsReadyToSendWriteWithoutResponse += OnIsReadyToSendWriteWithoutResponse;
            Peripheral.ModifiedServices += OnModifiedServices;
            Peripheral.RssiRead         += OnRssiRead;
            Peripheral.RssiUpdated      += OnRssiUpdated;
            Peripheral.UpdatedCharacterteristicValue += OnUpdatedCharacterteristicValue;
            Peripheral.UpdatedName += OnUpdatedName;
            Peripheral.UpdatedNotificationState += OnUpdatedNotificationState;
            Peripheral.UpdatedValue             += OnUpdatedValue;
            Peripheral.WroteCharacteristicValue += OnWroteCharacteristicValue;
            Peripheral.WroteDescriptorValue     += OnWroteDescriptorValue;
        }
Ejemplo n.º 41
0
        public void SetPeripheralAndService(CBPeripheral peripheral, CBService service)
        {
            this._connectedPeripheral = peripheral;
            this._currentService      = service;

            // discover the charactersistics
            this._connectedPeripheral.DiscoverCharacteristics(service);

            // should be named "DiscoveredCharacteristic"
            this._connectedPeripheral.DiscoverCharacteristic += (object sender, CBServiceEventArgs e) => {
                Console.WriteLine("Discovered Characteristic.");
                foreach (CBService srv in ((CBPeripheral)sender).Services)
                {
                    // if the service has characteristics yet
                    if (srv.Characteristics != null)
                    {
                        foreach (var characteristic in service.Characteristics)
                        {
                            Console.WriteLine("Characteristic: " + characteristic.Description);

                            this._characteristics.Add(characteristic);
                            this.CharacteristicsTable.ReloadData();
                        }
                    }
                }
            };

            // when a descriptor is dicovered, reload the table.
            this._connectedPeripheral.DiscoveredDescriptor += (object sender, CBCharacteristicEventArgs e) => {
                foreach (var descriptor in e.Characteristic.Descriptors)
                {
                    Console.WriteLine("Characteristic: " + e.Characteristic.Value + " Discovered Descriptor: " + descriptor);
                }
                // reload the table
                this.CharacteristicsTable.ReloadData();
            };
        }
        public override void DiscoverCharacteristic(CBPeripheral peripheral, CBService service, NSError error)
        {
            if (disposed)
            {
                return;
            }

            foreach (var characteristic in service.Characteristics)
            {
                if (characteristic.UUID == HeartRateMeasurementCharacteristicUUID)
                {
                    service.Peripheral.SetNotifyValue(true, characteristic);
                }
                else if (characteristic.UUID == BodySensorLocationCharacteristicUUID)
                {
                    service.Peripheral.ReadValue(characteristic);
                }
                else if (characteristic.UUID == HeartRateControlPointCharacteristicUUID)
                {
                    service.Peripheral.WriteValue(NSData.FromBytes((IntPtr)1, 1),
                                                  characteristic, CBCharacteristicWriteType.WithResponse);
                }
            }
        }
Ejemplo n.º 43
0
        private Task <GattService> PlatformGetIncludedServiceAsync(BluetoothUuid service)
        {
            TaskCompletionSource <GattService> tcs = new TaskCompletionSource <GattService>();
            CBPeripheral peripheral = Device;

            void handler(object sender, CBServiceEventArgs args)
            {
                peripheral.DiscoveredIncludedService -= handler;

                if (args.Error != null)
                {
                    tcs.SetException(new Exception(args.Error.ToString()));
                }
                else
                {
                    tcs.SetResult(new GattService(Device, args.Service));
                }
            }

            peripheral.DiscoveredIncludedService += handler;
            peripheral.DiscoverIncludedServices(new CBUUID[] { service }, _service);

            return(tcs.Task);
        }
Ejemplo n.º 44
0
        public Device(CBPeripheral nativeDevice)
        {
            this.nativeDevice = nativeDevice;

            this.nativeDevice.DiscoveredService += (object sender, NSErrorEventArgs e) => {
                // 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 (this.nativeDevice.Services != null)
                {
                    foreach (CBService s in this.nativeDevice.Services)
                    {
                        Console.WriteLine("Device.Discovered Service: " + s.Description);

                        if (!ServiceExists(s))
                        {
                            services.Add(new Service(s, this.nativeDevice));
                        }
                    }
                    ServicesDiscovered(this, new EventArgs());
                }
            };

            this.nativeDevice.DiscoveredCharacteristic += NativeDeviceDiscoveredCharacteristic;
        }
Ejemplo n.º 45
0
 public override void RetrievedConnectedPeripherals(CBCentralManager central, CBPeripheral[] peripherals)
 {
     base.RetrievedConnectedPeripherals(central, peripherals);
 }
Ejemplo n.º 46
0
		public override void DiscoveredService (CBPeripheral peripheral, NSError error)
		{
			if (disposed) {
				return;
			}

			foreach (var service in peripheral.Services) {
				if (service.UUID == PeripheralUUID) {
					peripheral.DiscoverCharacteristics (service);
				}
			}
		}
Ejemplo n.º 47
0
		//TODO: rename to DisconnectDevice
		public void DisconnectPeripheral (CBPeripheral peripheral)
		{
			_central.CancelPeripheralConnection (peripheral);
		}
Ejemplo n.º 48
0
 //Hack: In order for CBPeripheral object not to be deallocated hold it's reference
 private void StoreInList(CBPeripheral peripheral)
 {
     CBPeripheral storedPeripheral;
     if (Peripherals.TryGetValue(peripheral.Identifier, out storedPeripheral))
     {
         if (storedPeripheral.IsUuidEqual(peripheral.Identifier))
         {
             return;
         }
     }
     Peripherals[peripheral.Identifier] = peripheral;
 }
Ejemplo n.º 49
0
 public BluetoothLEDevice(CBCentralManager centralManager, CBPeripheral peripheral)
 {
     _peripheral          = peripheral;
     _peripheral.Delegate = this;
     _centralManager      = centralManager;
 }
Ejemplo n.º 50
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BluetoothDevice"/> class.
		/// </summary>
		/// <param name="device">The device.</param>
		public BluetoothDevice(CBPeripheral device)
		{
			this.device = device;
		}
Ejemplo n.º 51
0
 internal DeviceInformation(CBPeripheral peripheral, string name)
 {
     _peripheral = peripheral;
     _name = name;
 }
Ejemplo n.º 52
0
		public Characteristic (CBCharacteristic nativeCharacteristic, CBPeripheral parentDevice)
		{
			this._nativeCharacteristic = nativeCharacteristic;
			this._parentDevice = parentDevice;
		}
Ejemplo n.º 53
0
 public Service(CBService service, CBPeripheral device)
 {
     _service = service;
     _device = device;
 }
Ejemplo n.º 54
0
		public override void UpdatedCharacterteristicValue (CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
		{
			if (disposed || error != null || characteristic.Value == null) {
				return;
			}

			if (characteristic.UUID == HeartRateMeasurementCharacteristicUUID) {
				UpdateHeartRate (characteristic.Value);
			} else if (characteristic.UUID == BodySensorLocationCharacteristicUUID) {
				UpdateBodySensorLocation (characteristic.Value);
			}
		}
Ejemplo n.º 55
0
 private static Guid ParseDeviceGuid(CBPeripheral peripherial)
 {
     return(Guid.ParseExact(peripherial.Identifier.AsString(), "d"));
 }
Ejemplo n.º 56
0
 public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
 {
     base.DiscoveredPeripheral(central, peripheral, advertisementData, RSSI);
 }
Ejemplo n.º 57
0
 private static bool ContainsDevice(IEnumerable <IDevice> list, CBPeripheral device)
 {
     return(list.Any(d => Guid.ParseExact(device.Identifier.AsString(), "d") == d.Id));
 }
Ejemplo n.º 58
0
		public override void DiscoveredCharacteristic (CBPeripheral peripheral, CBService service, NSError error)
		{
			if (disposed) {
				return;
			}

			foreach (var characteristic in service.Characteristics) {
				if (characteristic.UUID == HeartRateMeasurementCharacteristicUUID) {
					service.Peripheral.SetNotifyValue (true, characteristic);
				} else if (characteristic.UUID == BodySensorLocationCharacteristicUUID) {
					service.Peripheral.ReadValue (characteristic);
				} else if (characteristic.UUID == HeartRateControlPointCharacteristicUUID) {
					service.Peripheral.WriteValue (NSData.FromBytes ((IntPtr)1, 1),
						characteristic, CBCharacteristicWriteType.WithResponse);
				}
			}
		}
Ejemplo n.º 59
0
        public Device(CBPeripheral nativeDevice)
        {
            _nativeDevice = nativeDevice;

            try
            {
                _nativeDevice.DiscoveredService += (sender, e) =>
                {
                    // 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)
                    {
                        foreach (var s in _nativeDevice.Services)
                        {
                            Console.WriteLine("Device.Discovered Service: " + s.Description);
                            if (!ServiceExists(s))
                            {
                                _services.Add(new Service(s, _nativeDevice));
                            }
                        }
                        if (ServicesDiscovered != null)
                        {
                            ServicesDiscovered(this, new EventArgs());
                        }
                    }
                };


#if __UNIFIED__
                // fixed for Unified https://bugzilla.xamarin.com/show_bug.cgi?id=14893
                _nativeDevice.DiscoveredCharacteristic += (sender, e) =>
                {
#else
                //BUGBUG/TODO: this event is misnamed in our SDK
                this._nativeDevice.DiscoverCharacteristic += (object sender, CBServiceEventArgs e) => {
                                        #endif
                    Console.WriteLine("Device.Discovered Characteristics.");
                    //loop through each service, and update the characteristics
                    foreach (var srv in ((CBPeripheral)sender).Services)
                    {
                        // if the service has characteristics yet
                        if (srv.Characteristics != null)
                        {
                            // locate the our new service
                            foreach (var item in Services)
                            {
                                // if we found the service
                                if (item.ID == Service.ServiceUuidToGuid(srv.UUID))
                                {
                                    item.Characteristics.Clear();

                                    // add the discovered characteristics to the particular service
                                    foreach (var characteristic in srv.Characteristics)
                                    {
                                        Console.WriteLine("Characteristic: " + characteristic.Description);
                                        var newChar = new Characteristic(characteristic, _nativeDevice);
                                        item.Characteristics.Add(newChar);
                                    }
                                    // inform the service that the characteristics have been discovered
                                    // TODO: really, we shoul just be using a notifying collection.
                                    var service = item as Service;
                                    if (service != null)
                                    {
                                        service.OnCharacteristicsDiscovered();
                                    }
                                }
                            }
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 60
0
				public PeripheralSelectedEventArgs (CBPeripheral peripheral)
				{
					this._peripheral = peripheral;
				}