public AndroidBluetoothClientScannerCallback(BluetoothGattService service, BluetoothGattCharacteristic characteristic, AndroidBluetoothDeviceProximityProbe probe) { _service = service; _characteristic = characteristic; _probe = probe; _scanResults = new List <ScanResult>(); }
public sealed override void BuildService(BluetoothGattService service) { foreach (var c in service.Characteristics) { _concreteCharacteristics.FirstOrDefault(x => x.Uuid.Equals(c.Uuid))?.BuildCharacteristic(service.GetCharacteristic(c.Uuid)); } }
/// <summary> /// Process a callback from the Gatt for changes in the device connection State /// </summary> private void GattCallback_ConnectionStateChange(object sender, ConnectionStateChangeEventArgs e) { Debug.WriteLineIf(sw.TraceInfo, $"++> GattCallback_ConnectionStateChange: {e.NewState}"); switch (e.NewState) { case ProfileState.Connected: _gatt = e.Gatt; _service = _gatt.GetService(uuidService); _gatt.DiscoverServices(); // return without setting State // wait until ServicesDiscovered callback to announce we're actually connected break; case ProfileState.Connecting: State = BlueState.Connecting; break; case ProfileState.Disconnected: State = BlueState.Disconnected; break; case ProfileState.Disconnecting: State = BlueState.Disconnecting; break; default: break; } }
public BattByteTestServer() { _serverCallback = new ServerCallback(); _advertiseCallback = new AdvertiseCallback(); var appContext = Android.App.Application.Context; var manager = (BluetoothManager)appContext.GetSystemService(Application.BluetoothService); var server = manager.OpenGattServer(appContext, _serverCallback); _serverCallback.GattServer = server; _adapter = manager.Adapter; var battByteService = new BluetoothGattService(UUID.FromString("BEEF".ToGuid().ToString()), GattServiceType.Primary); var voltageCharacteristic = new BluetoothGattCharacteristic(UUID.FromString("BEF0".ToGuid().ToString()), GattProperty.Read, GattPermission.Read); voltageCharacteristic.SetValue(new byte[] { 0xB0, 0x0B }); battByteService.AddCharacteristic(voltageCharacteristic); var tempCharacteristic = new BluetoothGattCharacteristic(UUID.FromString("BEF1".ToGuid().ToString()), GattProperty.Read, GattPermission.Read); tempCharacteristic.SetValue(9876, GattFormat.Sint16, 0); battByteService.AddCharacteristic(tempCharacteristic); server.AddService(battByteService); _server = server; StartAdvertising("Blah!"); }
protected override void OnCreate(Bundle savedInstanceState) { RequestWindowFeature(WindowFeatures.NoTitle); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_set_characteristic_value); gatt = SingleGattService.GetInstance().CurGatt; service = SingleGattService.GetInstance().CurService; characteristic = SingleGattService.GetInstance().CurCharacteristic; callBack = SingleGattService.GetInstance().CurCallback; back = FindViewById <Button>(Resource.Id.settings_back); setValue = FindViewById <Button>(Resource.Id.settings_set_value); registNotify = FindViewById <Button>(Resource.Id.settings_regist_char_notify); unregistNotify = FindViewById <Button>(Resource.Id.settings_unregist_char_notify); valueHex = FindViewById <TextView>(Resource.Id.settings_value_hex); valueStr = FindViewById <TextView>(Resource.Id.settings_value_str); valueInput = FindViewById <EditText>(Resource.Id.settings_value_input); back.SetOnClickListener(this); setValue.SetOnClickListener(this); registNotify.SetOnClickListener(this); unregistNotify.SetOnClickListener(this); InitView(); }
public Service(PeripheralConnection connection, BluetoothGattService service) { _connection = connection; _service = service; _uuid = new ServiceUuid(service.Uuid.ToUuid()); _characteristics = _service.Characteristics.SelectArray(ch => new Characteristic(this, ch)); }
public Service(BluetoothGattService nativeService, BluetoothGatt gatt, IGattCallback gattCallback, IDevice device) : base(device) { this._nativeService = nativeService; this._gatt = gatt; this._gattCallback = gattCallback; }
/// <summary> /// Get the UUID's for the device details and sets the list /// </summary> /// <param name="gatt">Gatt.</param> private void getDeviceDetails(BluetoothGatt gatt) { try { UUID deviceInfoUUID = UUID.FromString(BluetoothConstants.DEVICE_INFO_SERVICE); BluetoothGattService deviceInfoSer = gatt.GetService(deviceInfoUUID); deviceChar = new List <BluetoothGattCharacteristic> { deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SERIALNUM)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_MODELNUM)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_SOFTWARE_REV)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_FIRMWARE_REV)), deviceInfoSer.GetCharacteristic(UUID.FromString(BluetoothConstants.DEVICE_HARDWARE_REV)) }; foreach (BluetoothGattCharacteristic c in deviceChar) { try { gatt.SetCharacteristicNotification(c, false); requestCharacteristic(gatt); } catch (System.Exception e) { string t = ""; // if the char dont exit for thiss } } } catch (System.Exception e) { // stop ourselves sendStateUpdate(gatt.Device.Address, false, "Device could not be read from: " + e.Message); } }
public void AddReadOnlyService( Guid serviceName, Dictionary <Guid, Func <byte[]> > characteristics) { var manager = (BluetoothManager)context.GetSystemService( Context.BluetoothService); var adapter = manager.Adapter; if (!adapter.IsEnabled) { // TODO: restarts the server when the BLE adapter goes down. adapter.Enable(); Thread.Sleep(10 * 1000); } // Creates a Gatt server with the requested service { var callback = new AndroidBLEGattServerCallback( characteristics); var server = manager.OpenGattServer(context, callback); callback.Server = server; var service = new BluetoothGattService(AsJavaUUID(serviceName), GattServiceType.Primary); foreach (var i in characteristics) { var ch = new BluetoothGattCharacteristic(AsJavaUUID(i.Key), GattProperty.Read | GattProperty.Notify, GattPermission.Read); service.AddCharacteristic(ch); } server.AddService(service); } // Starts advertising for the availaible services over BLE. { var advertiser = adapter.BluetoothLeAdvertiser; var setts = new AdvertiseSettings.Builder() .SetAdvertiseMode(AdvertiseMode.Balanced) .SetConnectable(true) .SetTimeout(0) .SetTxPowerLevel(AdvertiseTx.PowerMedium) .Build(); var data = new AdvertiseData.Builder() //.AddServiceUuid(AsParcelUuid(ser)) .Build(); var callback = new AndroidBLEAdvertiseCallback(); advertiser.StartAdvertising(setts, data, callback); } }
// Supoort func to hadle all the mess of enumerating chars and descs private void AddService(BluetoothGattService service) { if (!serviceObjects.Contains(service)) { if (service.Type == GattServiceType.Primary) { foreach (var s in service.IncludedServices) { if (!serviceObjects.Contains(s)) { AddService(s); } } } foreach (var c in service.Characteristics) { if (!characteristicObjects.Contains(c)) { foreach (var d in c.Descriptors) { if (!descriptorObjects.Contains(d)) { descriptorObjects.Add(d); } } characteristicObjects.Add(c); } } serviceObjects.Add(service); } }
internal Service(BluetoothGattService nativeService, BluetoothGatt gatt, IGattCallback gattCallback, Device device) : this(device) { NativeService = nativeService; _gatt = gatt; _gattCallback = gattCallback; }
internal BLEService(BluetoothGatt gatt, BLEGATTCallback callback, BluetoothGattService service) : this() { _gatt = gatt; _callback = callback; _service = service; }
protected override async Task InitializeAsync() { await base.InitializeAsync(); // BLE requires location permissions if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Location) != PermissionStatus.Granted) { // throw standard exception instead of NotSupportedException, since the user might decide to enable location in the future // and we'd like the probe to be restarted at that time. string error = "Geolocation is not permitted on this device. Cannot start Bluetooth probe."; await SensusServiceHelper.Get().FlashNotificationAsync(error); throw new Exception(error); } _deviceIdCharacteristic = new BluetoothGattCharacteristic(UUID.FromString(DEVICE_ID_CHARACTERISTIC_UUID), GattProperty.Read, GattPermission.Read); _deviceIdCharacteristic.SetValue(Encoding.UTF8.GetBytes(SensusServiceHelper.Get().DeviceId)); _deviceIdService = new BluetoothGattService(UUID.FromString(Protocol.Id), GattServiceType.Primary); _deviceIdService.AddCharacteristic(_deviceIdCharacteristic); _bluetoothAdvertiserCallback = new AndroidBluetoothServerAdvertisingCallback(_deviceIdService, _deviceIdCharacteristic); if (ScanMode.HasFlag(BluetoothScanModes.Classic)) { _bluetoothBroadcastReceiver = new AndroidBluetoothDeviceReceiver(this); IntentFilter intentFilter = new IntentFilter(); intentFilter.AddAction(BluetoothDevice.ActionFound); Application.Context.RegisterReceiver(_bluetoothBroadcastReceiver, intentFilter); } }
public void Start(Context context, TracingInformation tracingInformation) { if (!Initialized) { _logger.LogError("Advertiser - Starting failed - not initialized."); return; } _tracingInformation = tracingInformation; try { _logger.LogDebug("Advertiser - starting."); var serviceUuid = ParcelUuid.FromString(_tracingInformation.ServiceId); var characteristicUuid = ParcelUuid.FromString(_tracingInformation.CharacteristicId); _logger.LogDebug($"Advertiser - initializing. ServiceId: {_tracingInformation.ServiceId}. CharacteristicId: {_tracingInformation.CharacteristicId}"); BtGattServerCallback bluetoothGattServerCallback = new BtGattServerCallback(_tracingInformation); _gattServer = _bluetoothManager.OpenGattServer(context, bluetoothGattServerCallback); bluetoothGattServerCallback._gattServer = _gattServer; BluetoothGattService service = new BluetoothGattService(serviceUuid.Uuid, GattServiceType.Primary); BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(characteristicUuid.Uuid, GattProperty.Read, GattPermission.Read); service.AddCharacteristic(characteristic); _gattServer.AddService(service); _logger.LogDebug("Advertiser - started."); } catch (Exception ex) { _logger.LogError(ex, "Advertiser - failed advertising initialization."); } }
public Service(Guid uuid, bool isPrimary) { NativeService = new BluetoothGattService(UUID.FromString(uuid.ToString()), isPrimary ? GattServiceType.Primary : GattServiceType.Secondary); var characteristics = new ObservableCollection <ICharacteristic>(); characteristics.CollectionChanged += CharacteristicsOnCollectionChanged; Characteristics = characteristics; }
public GattService(GattContext context, IGattServer server, Guid uuid, bool primary) : base(server, uuid, primary) { this.context = context; this.Native = new BluetoothGattService( UUID.FromString(uuid.ToString()), primary ? GattServiceType.Primary : GattServiceType.Secondary ); }
private BluetoothGattService createService() { var service = new BluetoothGattService(Const.UUID_SERVICE, GattServiceType.Primary); var write_ch = new BluetoothGattCharacteristic(Const.UUID_DATA, GattProperty.WriteNoResponse, GattPermission.Write); service.AddCharacteristic(write_ch); return(service); }
public async Task <List <BluetoothDeviceProximityDatum> > ReadPeripheralCharacteristicValuesAsync(CancellationToken cancellationToken) { List <BluetoothDeviceProximityDatum> bluetoothDeviceProximityData = new List <BluetoothDeviceProximityDatum>(); // copy list of peripherals to read. note that the same device may be reported more than once. read each once. List <ScanResult> scanResults; lock (_scanResults) { scanResults = _scanResults.GroupBy(scanResult => scanResult.Device.Address).Select(group => group.First()).ToList(); } _probe.ReadAttemptCount += scanResults.Count; // read characteristic from each peripheral foreach (ScanResult scanResult in scanResults) { if (cancellationToken.IsCancellationRequested) { break; } AndroidBluetoothClientGattCallback readCallback = null; try { readCallback = new AndroidBluetoothClientGattCallback(_service, _characteristic); BluetoothGatt gatt = scanResult.Device.ConnectGatt(global::Android.App.Application.Context, false, readCallback); BluetoothGattService service = gatt.GetService(_service.Uuid); string characteristicValue = null; bool runningSensus = service != null; if (runningSensus) { characteristicValue = await readCallback.ReadCharacteristicValueAsync(cancellationToken); } if (_probe.DiscoverAll || runningSensus) { long msSinceEpoch = Java.Lang.JavaSystem.CurrentTimeMillis() - SystemClock.ElapsedRealtime() + scanResult.TimestampNanos / 1000000; DateTimeOffset encounterTimestamp = new DateTimeOffset(1970, 1, 1, 0, 0, 0, new TimeSpan()).AddMilliseconds(msSinceEpoch); bluetoothDeviceProximityData.Add(new BluetoothDeviceProximityDatum(encounterTimestamp, characteristicValue, scanResult.Device.Address, scanResult.Device.Name, scanResult.Rssi, scanResult.Device.BondState != Bond.None, runningSensus)); _probe.ReadSuccessCount++; } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Exception while reading peripheral: " + ex, LoggingLevel.Normal, GetType()); } finally { readCallback?.DisconnectPeripheral(); } } return(bluetoothDeviceProximityData); }
public GattService(IPeripheral peripheral, DeviceContext context, BluetoothGattService native) : base(peripheral, native.Uuid.ToGuid(), native.Type == GattServiceType.Primary) { this.context = context; this.native = native; }
public GattService(IDevice device, DeviceContext context, BluetoothGattService native) : base(device, native.Uuid.ToGuid(), native.Type == GattServiceType.Primary) { this.context = context; this.native = native; }
public BluetoothGattService CreateService() { var serviceUuid = UUID.FromString(ServiceUuid); var service = new BluetoothGattService(serviceUuid, GattServiceType.Primary); service.AddCharacteristic(new BluetoothGattCharacteristic(UUID.FromString(WriteCharacteristic), GattProperty.WriteNoResponse, GattPermission.Write)); return(service); }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothLE.Droid.Service"/> class. /// </summary> /// <param name="nativeService">Native service.</param> /// <param name="gatt">Native Gatt.</param> /// <param name="callback">Callback.</param> public Service(BluetoothGattService nativeService, BluetoothGatt gatt, GattCallback callback) { _nativeService = nativeService; _gatt = gatt; _callback = callback; _id = ServiceIdFromUuid(_nativeService.Uuid); Characteristics = new List <ICharacteristic>(); }
/// <summary> /// Initializes a new instance of the <see cref="BluetoothLE.Droid.Service"/> class. /// </summary> /// <param name="nativeService">Native service.</param> /// <param name="gatt">Native Gatt.</param> /// <param name="callback">Callback.</param> public Service(BluetoothGattService nativeService, BluetoothGatt gatt, GattCallback callback) { NativeService = nativeService; _gatt = gatt; _callback = callback; _id = ServiceIdFromUuid(NativeService.Uuid); Characteristics = new ObservableCollection <ICharacteristic>(); }
private void StepintoService() { BluetoothGattService service = services[adapter.GetChooseItem()]; SingleGattService.GetInstance().CurService = service; Intent intent = new Intent(); intent.SetClass(this, typeof(CharacteristicsActivity)); StartActivity(intent); }
public static void Dump(BluetoothGattService service, string serviceName) { if (service != null) { foreach (BluetoothGattCharacteristic characteristic in service.Characteristics) { Log.Debug(serviceName, string.Format("'0x{0:X}: characteristic's UUID : '0x{1:X}'", GetAssignedNumber(service.Uuid), GetAssignedNumber(characteristic.Uuid))); } } }
/// <summary> /// /// </summary> public virtual void OnServicesDiscovered(BluetoothGatt gatt, int status) { Log.i("BluetoothScannerGUI", "OnServicesDiscovered:" + status.ToString()); if (status == BluetoothGatt.GATT_SUCCESS) { BluetoothGattService srv = gatt.GetService(UUID.FromString("0000faea-0000-1000-8000-00805f9b34fb")); BluetoothGattCharacteristic chr = srv.GetCharacteristic(UUID.FromString("0000faeb-0000-1000-8000-00805f9b34fb")); gatt.SetCharacteristicNotification(chr, true); } }
public override void OnServiceAdded(ProfileState status, BluetoothGattService service) { Debug.WriteLine("Added service " + service.Uuid); var handler = ServiceAdded; if (handler != null) { handler(status, service); } }
protected static Java.Util.UUID CHAR_APPEARANCE = Java.Util.UUID.FromString("00002A01-0000-1000-8000-00805f9b34fb"); //org.bluetooth.characteristic.gap.appearance public GenericAccessService(BluetoothGatt gatt, BluetoothGattService service, GattDevice device) : base(gatt, service, device) { if (service != null) { BluetoothGattCharacteristic characteristic = service.GetCharacteristic(CHAR_DEVICE_NAME); if (characteristic != null) { gatt.ReadCharacteristic(characteristic); } } }
public override void OnServicesDiscovered(BluetoothGatt gatt, GattStatus status) { System.Threading.Tasks.Task.Run(() => { base.OnServicesDiscovered(gatt, status); if (gatt != null) { try { var serviceUuid = ParcelUuid.FromString(_tracingInformation.ServiceId); BluetoothGattService service = gatt.GetService(serviceUuid.Uuid); if (service != null) { _deviceManager.HandleDeviceCommunicationDiscoveredService(_descriptor, (d) => { var characteristicUuid = ParcelUuid.FromString(_tracingInformation.CharacteristicId); BluetoothGattCharacteristic characteristic = service.GetCharacteristic(characteristicUuid.Uuid); if (characteristic != null) { _deviceManager.HandleDeviceCommunicationDiscoveredCharacteristic(_descriptor, (d) => { gatt.ReadCharacteristic(characteristic); }); } else { _deviceManager.HandleIncorrectDevice(_descriptor, (d) => { gatt.Disconnect(); }); } }); } else { _deviceManager.HandleIncorrectDevice(_descriptor, (d) => { gatt.Disconnect(); }); } } catch (Exception ex) { _deviceManager.HandleDeviceCommunicationDiscoveryServiceError(_descriptor, ex.Message, (d) => { gatt.Disconnect(); }); } } }).FireAndForget(); }
private View GetServiceView(BluetoothGattService service) { var itemView = _context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null); var itemText = itemView.FindViewById <TextView>(Android.Resource.Id.Text1); itemText.Text = "Service " + service.Uuid; itemText.SetTextSize(ComplexUnitType.Sp, 15); itemText.SetTextColor(Color.Gray); return(itemView); }