string FetchDetailedText(CBCharacteristic characteristic)
		{
			if (characteristic.Descriptors != null)
				return GetDescription (characteristic.Descriptors);
			else
				return "Select to discover characteristic descriptors.";
		}
        // Overridden from BaseIOSConnection
        protected override bool ValidateServices()
        {
            readCharacteristic  = null;
            writeCharacteristic = null;

            foreach (CBService service in device.Services)
            {
                if (service != null && service.Characteristics != null)
                {
                    // Apparently services can be null after discovery?
                    foreach (CBCharacteristic characteristic in service.Characteristics)
                    {
                        if (READ_CHARACTERISTIC.characteristic.Equals(characteristic.UUID))
                        {
                            readCharacteristic = characteristic;
                            device.SetNotifyValue(true, readCharacteristic);
                        }
                        else if (WRITE_CHARACTERISTIC.characteristic.Equals(characteristic.UUID))
                        {
                            writeCharacteristic = characteristic;
                        }
                        else if (NAME_CHARACTERISTIC.characteristic.Equals(characteristic.UUID))
                        {
                            nameCharacteristic = characteristic;
                            device.SetNotifyValue(true, nameCharacteristic);
                        }
                    }
                }
            }

            return(readCharacteristic != null && writeCharacteristic != null && nameCharacteristic != null);
        }
Example #3
0
        public async Task <NSData> ReadValue(CBPeripheral peripheral, CBCharacteristic characteristic)
        {
            var taskCompletion = new TaskCompletionSource <bool>();
            var task           = taskCompletion.Task;
            EventHandler <CBCharacteristicEventArgs> handler = (s, e) =>
            {
                if (e.Characteristic.UUID?.Uuid == characteristic.UUID?.Uuid)
                {
                    taskCompletion.SetResult(true);
                }
            };

            try
            {
                peripheral.UpdatedCharacterteristicValue += handler;
                peripheral.ReadValue(characteristic);
                await this.WaitForTaskWithTimeout(task, ConnectionTimeout);

                return(characteristic.Value);
            }
            finally
            {
                peripheral.UpdatedCharacterteristicValue -= handler;
            }
        }
Example #4
0
 void HandleData(CBCharacteristic ch, byte[] val)
 {
     if (ch == _characteristic)
     {
         observer.OnNext(val);
     }
 }
Example #5
0
        public async Task <NSError> WriteValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSData value)
        {
            var taskCompletion = new TaskCompletionSource <NSError>();
            var task           = taskCompletion.Task;
            EventHandler <CBCharacteristicEventArgs> handler = (s, e) =>
            {
                if (e.Characteristic.UUID?.Uuid == characteristic.UUID?.Uuid)
                {
                    taskCompletion.SetResult(e.Error);
                }
            };

            try
            {
                peripheral.WroteCharacteristicValue += handler;
                peripheral.WriteValue(value, characteristic, CBCharacteristicWriteType.WithResponse);
                await this.WaitForTaskWithTimeout(task, ConnectionTimeout);

                return(task.Result);
            }
            finally
            {
                peripheral.WroteCharacteristicValue -= handler;
            }
        }
        /// <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;
            _nativeCharacteristic = nativeCharacteristic;

            _id = _nativeCharacteristic.UUID.ToString().ToGuid();
        }
Example #7
0
 public Characteristic(CBCharacteristic nativeCharacteristic, CBPeripheral parentDevice, IService service, IBleCentralManagerDelegate bleCentralManagerDelegate)
     : base(service)
 {
     _nativeCharacteristic      = nativeCharacteristic;
     _parentDevice              = parentDevice;
     _bleCentralManagerDelegate = bleCentralManagerDelegate;
 }
 public Characteristic(CBCharacteristic nativeCharacteristic, CBPeripheral parentDevice, IService service, CBCentralManager centralManager)
     : base(service)
 {
     _nativeCharacteristic = nativeCharacteristic;
     _parentDevice         = parentDevice;
     _centralManager       = centralManager;
 }
Example #9
0
 public override void WroteCharacteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
 {
     lock (_lock)
     {
         _writeCompletionSource?.SetResult(error == null);
     }
 }
Example #10
0
        private async Task <Characteristic> ConvertCharacteristic(CBCharacteristic nativeCharacteristic)
        {
            var device = nativeCharacteristic.Service.Peripheral;

            device.DiscoveredDescriptor += device_DiscoveredDescriptor;

            device.DiscoverDescriptors(nativeCharacteristic);
            await Task.Run(() => _descriptorDiscovered.WaitOne(TimeSpan.FromSeconds(10)));

            device.DiscoveredDescriptor -= device_DiscoveredDescriptor;
            _descriptorDiscovered.Reset();

            var characteristic = new Characteristic()
            {
                Id                   = BluetoothConverter.ConvertBluetoothLeUuid(nativeCharacteristic.UUID.Uuid),
                Descriptors          = nativeCharacteristic.Descriptors.Select(ConvertDescriptor).ToList(),
                NativeCharacteristic = nativeCharacteristic
            };

            foreach (var descriptor in characteristic.Descriptors)
            {
                descriptor.Characteristic = characteristic;
            }
            return(characteristic);
        }
        public Characteristic(Guid uuid, CharacterisiticPermissionType permissions, CharacteristicPropertyType properties)
        {
            CBAttributePermissions nativePermissions = 0;

            nativePermissions     = GetNativePermissions(permissions);
            _nativeCharacteristic = new CBMutableCharacteristic(CBUUID.FromString(uuid.ToString()), (CBCharacteristicProperties)properties, null, nativePermissions);
        }
            public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
            {
                UITableViewCell cell = tableView.DequeueReusableCell(cellID);

                if (cell == null)
                {
                    cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellID);
                }

                CBCharacteristic characteristic = this._characteristics [indexPath.Row];

                cell.TextLabel.Text = "Characteristic: " + characteristic.Description;
                StringBuilder descriptors = new StringBuilder();

                if (characteristic.Descriptors != null)
                {
                    foreach (var descriptor in characteristic.Descriptors)
                    {
                        descriptors.Append(descriptor.Description + " ");
                    }
                    cell.DetailTextLabel.Text = descriptors.ToString();
                }
                else
                {
                    cell.DetailTextLabel.Text = "Select to discover characteristic descriptors.";
                }

                return(cell);
            }
        public override void ReadCharacteristic(object characteristic)
        {
            CBCharacteristic c = characteristic as CBCharacteristic;
            if (c == null)
                return;

            Peripheral.ReadValue(c);
        }
Example #14
0
 public override void WroteCharacteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
 {
     // Method used to test successful data sends.
     if (error != null)
     {
         Console.WriteLine($"Error: {error}");
     }
 }
Example #15
0
        public BLECharacteristic(CBCharacteristic characteristic)
        {
            _nativeCharacteristic = characteristic;

            Value = _nativeCharacteristic?.Value.ToArray();
            Guid  = Guid.Parse(_nativeCharacteristic.UUID.ToString());
            //Properties = (CharacteristicPropertyType)(int)_nativeCharacteristic.Properties;
        }
		/// <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();
		}
        /// <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();
        }
        internal BLECharacteristic(BLECBPeripheralWrapper peripheral, CBCharacteristic characteristic)
        {
            _peripheralReference = new WeakReference(peripheral);
            _characteristic      = characteristic;

            PeripheralWrapper.UpdatedCharacterteristicValue += OnUpdatedCharacterteristicValue;
            PeripheralWrapper.WroteCharacteristicValue      += OnWroteCharacteristicValue;
            PeripheralWrapper.UpdatedNotificationState      += OnUpdatedNotificationState;
            PeripheralWrapper.DiscoveredDescriptor          += OnDiscoveredDescriptor;
        }
            public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
            {
                CBCharacteristic characteristic = this._characteristics [indexPath.Row];

                Console.WriteLine("Selected: " + characteristic.Description);

                this.CharacteristicSelected(this, new CharacteristicSelectedEventArgs(characteristic));

                tableView.DeselectRow(indexPath, true);
            }
Example #20
0
 string FetchDetailedText(CBCharacteristic characteristic)
 {
     if (characteristic.Descriptors != null)
     {
         return(GetDescription(characteristic.Descriptors));
     }
     else
     {
         return("Select to discover characteristic descriptors.");
     }
 }
        /// <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;
            _nativeCharacteristic = nativeCharacteristic;
            _peripheral.UpdatedCharacterteristicValue += OnUpdatedCharacteristicValue;
            _peripheral.UpdatedNotificationState      += PeripheralOnUpdatedNotificationState;
            _peripheral.WroteCharacteristicValue      += OnWroteCharacteristicValue;
            _peripheral.WroteDescriptorValue          += OnWroteDescriptorValue;

            _id = _nativeCharacteristic.UUID.ToString().ToGuid();
        }
Example #22
0
 internal GattCharacteristic(
     CBPeripheral peripheral,
     PeripheralDelegate @delegate,
     GattService service,
     CBCharacteristic characteristic)
 {
     this.peripheral     = peripheral;
     this.@delegate      = @delegate;
     Service             = service;
     this.characteristic = characteristic;
 }
        // Overridden from BaseIOSConnection
        public override void UpdatedCharacterteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
        {
            if (characteristic.Equals(readCharacteristic))
            {
                lastPacket = readCharacteristic.Value.ToArray();
            }
            else
            {
//          Log.D(this, "Received unknown characteristic value: " + args.Characteristic);
            }
        }
Example #24
0
 public override void DiscoveredDescriptor(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
 {
     client.completedDesc += 1;
     if (characteristic.Descriptors != null)
     {
         foreach (var descriptor in characteristic.Descriptors)
         {
             client.descriptorObjects.Add(descriptor);
         }
     }
     client.allDiscovered();
 }
            /// <summary>
            /// Occurs when a Descripter for a characteristic is discovered
            /// </summary>
            /// <param name="peripheral">Peripheral.</param>
            /// <param name="characteristic">Characteristic.</param>
            /// <param name="error">Error.</param>
            public override void DiscoveredDescriptor(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
            {
                if (monitor.disposed)
                {
                    return;
                }

                foreach (var descriptor in characteristic.Descriptors)
                {
                    Console.WriteLine($"discovered descriptor: {descriptor.UUID}");
                }
            }
Example #26
0
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = tableView.DequeueReusableCell(cellID);

            cell = cell ?? new UITableViewCell(UITableViewCellStyle.Subtitle, cellID);

            CBCharacteristic characteristic = Characteristics [indexPath.Row];

            cell.TextLabel.Text       = string.Format("Characteristic: {0}", characteristic.Description);
            cell.DetailTextLabel.Text = FetchDetailedText(characteristic);

            return(cell);
        }
Example #27
0
        public void UpdatedCharacterteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
        {
#if DEBUG
            string name = OWBoard.GetNameFromUUID(characteristic.UUID.ToString());
            Debug.WriteLine($"Peripheral_UpdatedCharacterteristicValue - {name}");
#endif

            if (_characteristics.ContainsKey(characteristic.UUID) == false)
            {
                Debug.WriteLine($"ERROR: Peripheral missing ({characteristic.UUID})");
                return;
            }


            if (_readQueue.ContainsKey(characteristic.UUID) || _notifyList.Contains(characteristic.UUID))
            {
                byte[] dataBytes = null;

                if (characteristic.Value != null)
                {
                    var data = characteristic.Value;
                    dataBytes = new byte[data.Length];
                    System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

                    // Don't reveres for serial read or write
                    var characteristicGuid = characteristic.UUID.ToString();
                    if (OWBoard.SerialWriteUUID.Equals(characteristicGuid, StringComparison.InvariantCultureIgnoreCase) == false &&
                        OWBoard.SerialReadUUID.Equals(characteristicGuid, StringComparison.InvariantCultureIgnoreCase) == false)
                    {
                        // If our system is little endian, reverse the array.
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(dataBytes);
                        }
                    }
                }


                if (_notifyList.Contains(characteristic.UUID))
                {
                    BoardValueChanged?.Invoke(characteristic.UUID.ToString(), dataBytes);
                }

                if (_readQueue.ContainsKey(characteristic.UUID))
                {
                    var task = _readQueue[characteristic.UUID];
                    _readQueue.Remove(characteristic.UUID);
                    task.SetResult(dataBytes);
                }
            }
        }
        public override void WriteCharacteristic(object characteristic, byte[] value, bool isReliable)
        {
            CBCharacteristic c = characteristic as CBCharacteristic;
            if (c == null)
                return;

            if (isReliable)
            {
                Peripheral.WriteValue(NSData.FromArray(value), c, CBCharacteristicWriteType.WithResponse);
            }
            else
            {
                Peripheral.WriteValue(NSData.FromArray(value), c, CBCharacteristicWriteType.WithoutResponse);
            }
        }
        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);
            }
        }
        // Overridden from BaseIOSConnection
        public override void UpdatedCharacterteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
        {
            if (characteristic.Equals(nameCharacteristic))
            {
                var bytes = nameCharacteristic?.Value?.ToArray();
                name = System.Text.Encoding.UTF8.GetString(bytes);
            }
            else if (characteristic.Equals(readCharacteristic))
            {
                lastPacket = readCharacteristic.Value.ToArray();
            }
            else
            {
//          Log.D(this, "Received unknown characteristic value: " + args.Characteristic);
            }
        }
Example #31
0
        public void WroteCharacteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
        {
            Debug.WriteLine("Peripheral_WroteCharacteristicValue");


            if (_characteristics.ContainsKey(characteristic.UUID) == false)
            {
                return;
            }

            var writeCharacteristicValueRequest = _writeQueue.FirstOrDefault(t => t.CharacteristicId.Equals(characteristic.UUID));

            if (writeCharacteristicValueRequest == null)
            {
                return;
            }

            var data = characteristic.Value;

            byte[] dataBytes;
            if (data != null)
            {
                dataBytes = new byte[data.Length];
                System.Runtime.InteropServices.Marshal.Copy(data.Bytes, dataBytes, 0, Convert.ToInt32(data.Length));

                var characteristicGuid = characteristic.UUID.ToString();
                if (OWBoard.SerialWriteUUID.Equals(characteristicGuid, StringComparison.InvariantCultureIgnoreCase) == false &&
                    OWBoard.SerialReadUUID.Equals(characteristicGuid, StringComparison.InvariantCultureIgnoreCase) == false)
                {
                    // If our system is little endian, reverse the array.
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(dataBytes);
                    }
                }
            }
            else
            {
                dataBytes = null;
            }

            _writeQueue.Remove(writeCharacteristicValueRequest);
            writeCharacteristicValueRequest.CompletionSource.SetResult(dataBytes);
        }
Example #32
0
        bool Equals(CBCharacteristic ch)
        {
            if (!this.NativeCharacteristic.UUID.Equals(ch.UUID))
            {
                return(false);
            }

            if (!this.NativeService.UUID.Equals(ch.Service.UUID))
            {
                return(false);
            }

            if (!this.Peripheral.Identifier.Equals(ch.Service.Peripheral.Identifier))
            {
                return(false);
            }

            return(true);
        }
 public override void UpdatedCharacterteristicValue(CBPeripheral peripheral, CBCharacteristic characteristic, NSError error)
 {
     Console.WriteLine ("Value of characteristic " + characteristic.ToString () + " is " + characteristic.Value);
 }
        private void DiscoveredCharacteristic(object sender, CBServiceEventArgs args)
        {
            var characteristics = args.Service.Characteristics;

            try
            {
                MessageCharacteristic = characteristics.First(ch => ch.IsUuidEqual(BluetoothServiceUuid.MessageCharacteristic));
                InvitationCharacteristic = characteristics.First(ch => ch.UUID == BluetoothServiceUuid.ConnectionInviteCharacteristic);
                StatusCharacteristic = characteristics.First(ch => ch.UUID == BluetoothServiceUuid.StatusCharacteristic);
                NameCharacteristic = characteristics.First(ch => ch.UUID == BluetoothServiceUuid.NameCharacteristic);

                //Subscribe notify characteristic to receive messages from another user
                _peripheral.SetNotifyValue(true, StatusCharacteristic);
                _peripheral.SetNotifyValue(true, NameCharacteristic);
            }
            catch (Exception ex)
            {
                _discoveryTaskSource.TrySetException(new Exception("Bluetooth: Failed to discover characteristics", ex));
            }
        }
Example #35
0
		public Characteristic (CBCharacteristic nativeCharacteristic, CBPeripheral parentDevice)
		{
			this._nativeCharacteristic = nativeCharacteristic;
			this._parentDevice = parentDevice;
		}
				public CharacteristicSelectedEventArgs (CBCharacteristic characteristic)
				{
					this._characteristic = characteristic;
				}
Example #37
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);
			}
		}