Ejemplo n.º 1
0
        public ScanEventSource()
        {
            ScanResults = Observable.FromEvent<ScanResult>(h => OnDeviceDetected += h, h => OnDeviceDetected -= h);
            var appContext = Application.Context;
            var builder = new ScanSettings.Builder();
            builder.SetReportDelay(0);
            builder.SetScanMode(ScanMode.LowLatency);
            var manager = (BluetoothManager)appContext.GetSystemService(Context.BluetoothService);
            var adapter = manager.Adapter;
            bluetoothLeScanner = adapter.BluetoothLeScanner;
            var simpleScanCallback = new SimpleScanCallback(result =>
            {
                var payload = result.ScanRecord.GetBytes();
                var majorId = payload[26];
                if (payload[5] == 76 && majorId == Constants.MajorId)
                {
                    var txPower = 255 - payload[29];
                    var minorId = (payload[27] << 8) + payload[28];

                    var deviceId = new DeviceIdentifier(new Guid(), majorId, minorId);
                    var data = new ScanResult(deviceId, result.Rssi, txPower);
                    OnDeviceDetected?.Invoke(data);
                }
            });
            // taken from https://www.pubnub.com/blog/2015-04-15-build-android-beacon-ibeacon-detector/ , but not detecting our beacons
            //bluetoothLeScanner.StartScan(new List<ScanFilter> {CreateScanFilter()}, CreateScanSettings(), simpleScanCallback);
            bluetoothLeScanner.StartScan(simpleScanCallback);
        }
Ejemplo n.º 2
0
 public Bluetooth(Context context)
 {
     _manager      = (BluetoothManager)context.GetSystemService(Class.FromType(typeof(BluetoothManager)));
     _scanner      = _manager.Adapter.BluetoothLeScanner;
     _scanCallback = new ScanCallback(this);
     _identifier   = Injection.GetDeviceId(context);
 }
Ejemplo n.º 3
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            // Start scanning for the beacon we want to write a value to
            var scanModeBuilder = new ScanSettings.Builder();

            scanModeBuilder.SetScanMode(ScanMode.LowLatency);

            var deviceAddressFilterBuilder = new ScanFilter.Builder();

            deviceAddressFilterBuilder.SetDeviceAddress(_MyDeviceAddress);

            _Manager      = (BluetoothManager)GetSystemService("bluetooth");
            _Adapter      = _Manager.Adapter;
            _Scanner      = _Adapter.BluetoothLeScanner;
            _ScanCallback = new BleScanCallback(this);
            _GattCallback = new BleGattCallback(this);

            _LogTextView = FindViewById <TextView>(Resource.Id.logTextView);

            _Scanner.StartScan(
                new List <ScanFilter>
            {
                deviceAddressFilterBuilder.Build()
            }, scanModeBuilder.Build(), _ScanCallback);

            _LogTextView.Text = "Started scanning....";
        }
Ejemplo n.º 4
0
        public void PrepareForScan(Action <string, bool> message)
        {
            LogMessage2 = message;

            Connected = false;

            if (MainActivity.PackageManager.HasSystemFeature(PackageManager.FeatureBluetoothLe))
            {
                Scanner = BluetoothAdapter.BluetoothLeScanner;
                if (BluetoothAdapter.IsEnabled)
                {
                    if (ContextCompat.CheckSelfPermission(MainActivity, Manifest.Permission.AccessFineLocation) == Permission.Granted)
                    {
                        StartLeScan();
                    }
                    else
                    {
                        ActivityCompat.RequestPermissions(MainActivity, new[] { Manifest.Permission.AccessFineLocation }, REQUEST_LOCATION);
                    }
                }
                else
                {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
                    MainActivity.StartActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
            }
            else
            {
                Toast.MakeText(MainActivity, "BLE is not supported", ToastLength.Long).Show();
                MainActivity.Finish();
            }
        }
Ejemplo n.º 5
0
 public void OnAnimationStart(Animator animation)
 {
     LbStatus.Text = "Se cauta dispozitive...";
     if (_bluetoothManager == null)
     {
         return;
     }
     _bluetoothAdapter = _bluetoothManager.Adapter;
     if (!_bluetoothAdapter.IsEnabled)
     {
         StartActivityForResult(new Intent(BluetoothAdapter.ActionRequestEnable), 11);
     }
     else
     {
         BluetoothScanner = _bluetoothAdapter.BluetoothLeScanner;
         BluetoothScanner.StartScan(ScanCallback);
         handler.PostDelayed(() => {
             //mScanning = false;
             if (!isDeviceConnected)
             {
                 Log.Error("ScanTest", "Timeout");
                 BluetoothScanner.StopScan(ScanCallback);
                 LbStatus.Text = "Nu s-au gasit dispozitive";
                 _animationView.CancelAnimation();
             }
         }, SCAN_PERIOD);
         //_scanButton.Enabled = false;
         _dataContainer.Visibility = ViewStates.Gone;
     }
 }
Ejemplo n.º 6
0
        void InitializeScanner()
        {
            if (_adapter == null)
            {
                return;
            }

            // initialize scanner
            var sb = new ScanSettings.Builder()
                     .SetCallbackType(ScanCallbackType.AllMatches)
                     .SetScanMode(ScanMode.LowLatency);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                sb = sb.SetMatchMode(BluetoothScanMatchMode.Aggressive).SetNumOfMatches(1);
            }

            _scanSettings = sb.Build();
            sb.SetReportDelay(1000);
            _scanSettingsBatch = sb.Build();

            _scanner           = _adapter.BluetoothLeScanner;
            _scanCallback      = new ScanCallbackImpl(this);
            _scanCallbackBatch = new BatchScanCallbackImpl();
        }
Ejemplo n.º 7
0
        public void connect()
        {
            if (adapter == null)
            {
                Log.Debug(tag, "BluetoothAdapter is null");
            }

            BluetoothLeScanner scaner = adapter.BluetoothLeScanner;

            if (scaner == null)
            {
                Log.Error(tag, "BluetoothLeScanner is null");
            }

            try
            {
                device = adapter.GetRemoteDevice(mac);
                if (device == null)
                {
                    Log.Debug(tag, "Device não encontrado");
                }

                gatt = device.ConnectGatt(this, true, gattCallBack);
            }
            catch (System.Exception ex)
            {
                Log.Debug(tag, ex.ToString());
            }
        }
Ejemplo n.º 8
0
 public BluetoothService(BluetoothManager manager)
 {
     bluetoothManager = manager;
     adapter          = manager.Adapter;
     scanner          = adapter.BluetoothLeScanner;
     scanCallback     = new BluetoothScanCallback(this);
 }
Ejemplo n.º 9
0
        protected BluetoothLEManager()
        {
            var appContext = Android.App.Application.Context;

            this._manager = (BluetoothManager)appContext.GetSystemService("bluetooth");
            this._scanner = this._manager.Adapter.BluetoothLeScanner;
        }
Ejemplo n.º 10
0
        public void Start()
        {
            ScanSettings.Builder scanSettingsBuilder = null;
            ScanSettings         scanSettings        = null;

            switch (this.DriverState)
            {
            case BluetoothDriverStates.NotPresent:
                return;

            case BluetoothDriverStates.Enabled:
                this.scannerCallback    = new DroidLEScannerCallback();
                this.bluetoothLeScanner = this.bluetoothAdapter.BluetoothLeScanner;
                if (this.scanfiltersList.Count == 0)
                {
                    this.bluetoothLeScanner.StartScan(this.scannerCallback);
                }
                else
                {
                    scanSettingsBuilder = new ScanSettings.Builder();
                    scanSettingsBuilder.SetMatchMode(BluetoothScanMatchMode.Aggressive);
                    scanSettingsBuilder.SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency);
                    scanSettings = scanSettingsBuilder.Build();
                    try
                    {
                        this.bluetoothLeScanner.StartScan(this.scanfiltersList, scanSettings, this.scannerCallback);
                    }
                    catch (Exception)
                    {
                    }
                }
                this.DriverState = BluetoothDriverStates.Discovering;
                break;
            }
        }
Ejemplo n.º 11
0
        public void StartScan()
        {
            if (!SupportsBluetooth())
            {
                throw new BluetoothUnsupportedException("This device does not support Bluetooth.");
            }

            if (!IsReadyToUseBluetooth())
            {
                throw new BluetoothTurnedOffException("Bluetooth service on this device is turned off.");
            }

            if (IsScanning)
            {
                return;
            }

            if (OS_VER < BuildVersionCodes.Lollipop)
            {
                #pragma warning disable CS0618 // Type or member is obsolete
                _btAdapter.StartLeScan(_scanCallbackOld);
                #pragma warning restore CS0618 // Type or member is obsolete
            }
            else
            {
                if (_bleScanner == null)
                {
                    _bleScanner = _btAdapter.BluetoothLeScanner;
                }
                _bleScanner.StartScan(_scanCallbackNew);
            }
            IsScanning = true;
        }
 public iBeaconEventTriggerService()
 {
     _btManager    = (BluetoothManager)Android.App.Application.Context.GetSystemService("bluetooth");
     _btAdapter    = _btManager.Adapter;
     _bleScanner   = _btAdapter.BluetoothLeScanner;
     _scanCallback = new BleScanCallback();
 }
Ejemplo n.º 13
0
        public void Init()
        {
            BluetoothAdapter btAdapter = BluetoothAdapter.DefaultAdapter;

            _leScanner  = btAdapter?.BluetoothLeScanner;
            Initialized = _leScanner != null;
            _manager    = DeviceManagerProvider.GetInstance();
            _logger     = Covi.Logs.Logger.Get(this);
        }
Ejemplo n.º 14
0
        // It checks appropiate premissions, gets paired BT devices, scans and enables listeners for new BT devices.
        private void Init()
        {
            _instance = this;

            BluetoothAccessValidator.RequestAccessIfNeeded(this);

            _bluetoothLeScanner = bluetoothAdapter.BluetoothLeScanner;
            _bleAdapterCallback = new BLEScanCallback();
        }
Ejemplo n.º 15
0
        //public void OnClick(View v)
        //{
        //    Console.WriteLine("OnClick");
        //}

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            if (requestCode == _openBluetoothRequesetCode)
            {
                _bluetoothAdapter   = _bluetoothManager.Adapter;
                _bluetoothLeScanner = _bluetoothAdapter?.BluetoothLeScanner;
            }
            base.OnActivityResult(requestCode, resultCode, data);
        }
Ejemplo n.º 16
0
        protected override void OnStart()
        {
            base.OnStart();

            _bluetoothManager = (BluetoothManager)GetSystemService(BluetoothService);
            _bluetoothAdapter = _bluetoothManager.Adapter;

            _bluetoothLeScanner = _bluetoothAdapter?.BluetoothLeScanner;
        }
Ejemplo n.º 17
0
        private void setLollipopProperty()
        {
            Console.WriteLine("Setting up lollipop property");
            this._bleScanner       = this._adapter.BluetoothLeScanner;
            this._lollipopCallback = new LollipopScanCallback();
            this._lollipopCallback.deviceFoundEvent += OnLeScan;

            //ScanMode is declared in Util object due to namespace conflict of ScanMode object in both Android.Bluetooth and Android.Bluetooth.LE
            this._scanSettings = new ScanSettings.Builder().SetScanMode(Util.ScanModeLowLatency).Build();
        }
Ejemplo n.º 18
0
 public BluetoothConnector()
 {
     this.context      = Android.App.Application.Context;
     bluetoothManager  = (BluetoothManager)context.GetSystemService(Context.BluetoothService);
     bluetoothAdapter  = bluetoothManager.Adapter;
     bluetoothScanner  = bluetoothManager.Adapter.BluetoothLeScanner;
     bluetoothReceiver = new BluetoothReceiver(devicesResults, macAddressMapping);
     context.RegisterReceiver(bluetoothReceiver, new IntentFilter(BluetoothDevice.ActionFound));
     context.RegisterReceiver(bluetoothReceiver, new IntentFilter(BluetoothDevice.ExtraRssi));
     this.scanThread   = new Thread(Scan);
     this.scanCallback = new BluetoothScanCallback(devicesResults, macAddressMapping);
 }
Ejemplo n.º 19
0
        public AndroidBluetooth()
        {
            bluetoothManager   = Xamarin.Forms.Forms.Context.GetSystemService(Context.BluetoothService) as BluetoothManager;
            bluetoothLeScanner = bluetoothManager.Adapter.BluetoothLeScanner;


            gattServerCallback = new LeServerCallback();
            gattServerCallback.OnDeviceAdded += GattServerCallback_OnDeviceAdded;
            gattServerCallback.OnReadRequest += GattServerCallback_OnReadRequest;

            scanCallback = new LeScanCallback();
            scanCallback.OnScanFinished += Callback_OnScanFinished;
        }
Ejemplo n.º 20
0
        public AndroidBluetooth()
        {
            _context         = Application.Context;
            bluetoothManager = _context.GetSystemService(Context.BluetoothService) as BluetoothManager;
            bluetoothScanner = bluetoothManager.Adapter.BluetoothLeScanner;


            gattServerCallback = new ServerCallback();
            gattServerCallback.OnDeviceAdded += GattServerCallback_OnDeviceAdded;
            gattServerCallback.OnReadRequest += GattServerCallback_OnReadRequest;

            scanCallback = new ScanCallback();
            scanCallback.OnScanFinished += Callback_OnScanFinished;
        }
Ejemplo n.º 21
0
        internal BluetoothLEScan(BluetoothLEScanOptions options, BluetoothLeScanner scanner)
        {
            _options = options;
            if (options != null)
            {
                _filters = options.Filters;
            }

            //var settings = new ScanSettings.Builder().SetScanMode(ScanMode.LowLatency).Build();

            _callback = new Callback(this);
            _scanner  = scanner;
            scanner.StartScan(_callback);
            Active = true;
        }
Ejemplo n.º 22
0
        public void Scanner()
        {
            bluetoothLeScanner = mBluetoothAdapter.BluetoothLeScanner;
            mScanning          = true;

            /*
             * Handler mHandler = new Handler();
             * mHandler.PostDelayed(new Action(delegate {
             *  mScanning = false;
             *  bluetoothLeScanner.StopScan(this);
             *  if (ScanResultEvent != null) {
             *      ScanResultEvent(mLeDevices);
             *  }
             * }), SCAN_PERIOD);
             */
            bluetoothLeScanner.StartScan(this);
        }
Ejemplo n.º 23
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            // Bluetooth Low Energyがサポートされているかのチェック。
            if (!PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureBluetoothLe))
            {
                Toast.MakeText(this, Resource.String.ble_not_supported, ToastLength.Short).Show();
                Finish();
            }

            // BluetoothManager,BluetoothAdapter,BluetoothLeScannerをインスタンス化。
            BluetoothManager manager = (BluetoothManager)GetSystemService(BluetoothService);
            BluetoothAdapter adapter = manager.Adapter;
            scanner = adapter.BluetoothLeScanner;

            // BluetoothのAdapterが取得できているか=Bluetoothがサポートされているかのチェック。
            if (adapter == null)
            {
                Toast.MakeText(this, Resource.String.error_bluetooth_not_supported, ToastLength.Short).Show();
                Finish();
                return;
            }

            var scanButton = FindViewById<Button>(Resource.Id.scanButton);
            scanButton.Click += (sender, e) =>
            {
                bleDevices = new List<BleDeviceData>();

                scanCallback.ScanResultEvent += ScanCallback_ScanResultEvent;
                scanner.StartScan(scanCallback);
                Thread.Sleep(5000);
                scanner.StopScan(scanCallback);
            };

            listView = FindViewById<ListView>(Resource.Id.deviceList);
            listView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
            {
                var intent = new Intent(this, typeof(ServiceListActivity));
                var sendData = new string[] { bleDevices[e.Position].Name, bleDevices[e.Position].Id };
                intent.PutExtra("data", sendData);
                StartActivity(intent);
            };
        }
Ejemplo n.º 24
0
        public static void stopScan(ScanCallback callback)
        {
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;

            if (adapter == null)
            {
                Log.Debug(tag, "BluetoothAdapter is null");
            }

            BluetoothLeScanner scaner = adapter.BluetoothLeScanner;

            if (scaner == null)
            {
                Log.Debug(tag, "BluetoothLeScanner is null");
            }

            scaner.StopScan(callback);
        }
Ejemplo n.º 25
0
        public iBeaconEventTriggerService()
        {
            OS_VER = Build.VERSION.SdkInt;

            _btManager = (BluetoothManager)Android.App.Application.Context.GetSystemService("bluetooth");
            _btAdapter = _btManager.Adapter;

            if (OS_VER < BuildVersionCodes.Lollipop)
            {
                // 4.4參和はこちら
                _scanCallbackOld = new LeScanCallback();
            }
            else
            {
                // 5.0參貧はこちら
                _scanCallbackNew = new BleScanCallback();
                _bleScanner      = _btAdapter?.BluetoothLeScanner;
            }
        }
        void IAdvertiseAndDiscoverBluetoothDevice.Discover()
        {
            try
            {
                Analytics.TrackEvent(Build.Model + " Discover method called.");

                List <ScanFilter> filters = new List <ScanFilter>();

                ScanFilter filter = new ScanFilter.Builder()
                                    .SetServiceUuid(new ParcelUuid(MY_UUID))
                                    .Build();
                filters.Add(filter);

                //ScanSettings settings = new ScanSettings.Builder()
                //        .SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency)
                //        .Build();

                ScanSettings.Builder builder = new ScanSettings.Builder();
                builder.SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency);

                if (Build.VERSION.SdkInt >= BuildVersionCodes.M /* Marshmallow */)
                {
                    builder.SetMatchMode(BluetoothScanMatchMode.Aggressive);
                    builder.SetNumOfMatches((int)BluetoothScanMatchNumber.MaxAdvertisement);
                    builder.SetCallbackType(ScanCallbackType.AllMatches);
                }

                var settings = builder.Build();

                myScanCallback     = new MyScanCallback();
                bluetoothLeScanner = BluetoothAdapter.DefaultAdapter.BluetoothLeScanner;


                bluetoothLeScanner.StartScan(filters, settings, myScanCallback);
            }
            catch (System.Exception ex)
            {
                Analytics.TrackEvent(Build.Model + " Something went wrong in Discover method.");
            }
        }
Ejemplo n.º 27
0
        public async void StartScanning()
        {
            if (IsScanning)
            {
                return;
            }

            IsScanning = true;

            // TODO: Handle power on state.

            if (_sdkInt >= Android.OS.BuildVersionCodes.Lollipop) // 21
            {
                _bleScanner   = _adapter.BluetoothLeScanner;
                _scanCallback = new OWBLE_ScanCallback(this);
                var scanFilters         = new List <ScanFilter>();
                var scanSettingsBuilder = new ScanSettings.Builder();

                var scanFilterBuilder = new ScanFilter.Builder();
                scanFilterBuilder.SetServiceUuid(OWBoard.ServiceUUID.ToParcelUuid());
                scanFilters.Add(scanFilterBuilder.Build());
                _bleScanner.StartScan(scanFilters, scanSettingsBuilder.Build(), _scanCallback);
            }
            else if (_sdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr2) // 18
            {
                _leScanCallback = new OWBLE_LeScanCallback(this);
#pragma warning disable 0618
                _adapter.StartLeScan(new Java.Util.UUID[] { OWBoard.ServiceUUID.ToUUID() }, _leScanCallback);
#pragma warning restore 0618
            }
            else
            {
                throw new NotImplementedException("Can't run bluetooth scans on device lower than Android 4.3");
            }

            await Task.Delay(15 * 1000);

            StopScanning();
        }
Ejemplo n.º 28
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            Context appContext = Android.App.Application.Context;

            _manager = (BluetoothManager)appContext.GetSystemService("bluetooth");
            _adapter = _manager.Adapter;
            //		_gattCallback = new GattCallback(this);
            _scanner         = _adapter.BluetoothLeScanner;
            _scannerCallback = new BLEScannerCallback(this);
            _textView        = FindViewById <TextView>(Resource.Id.textView);
            _advertiser      = _adapter.BluetoothLeAdvertiser;
            Button button = FindViewById <Button> (Resource.Id.button);

            button.Click += delegate {
                button.Text = string.Format("{0} clicks!", count++);
                if (!_isScanning)
                {
                    Task.Run(async() =>
                    {
                        await BeginScanningForDevices();
                    });
                }
                else
                {
                    StopScanningForDevices();
                }
            };

            _advertiserCallback = new BLEAdvertiserCallback(this);
            Button button2 = FindViewById <Button>(Resource.Id.button2);

            button2.Click += (sender, e) =>
            {
                if (!_isAdvertizing)
                {
                    AdvertiseSettings settings = new AdvertiseSettings.Builder()
                                                 .SetAdvertiseMode(AdvertiseMode.Balanced)
                                                 .SetConnectable(true)
                                                 .SetTimeout(0)
                                                 .SetTxPowerLevel(AdvertiseTx.PowerMedium)
                                                 .Build();

                    AdvertiseData data = new AdvertiseData.Builder()
                                         .SetIncludeDeviceName(true)
                                         .SetIncludeTxPowerLevel(true)
                                         .AddServiceUuid(THERM_SERVICE)
                                         //.AddServiceData(THERM_SERVICE, buildTempPacket())
                                         .Build();

                    _advertiser.StartAdvertising(settings, data, _advertiserCallback);
                    button2.Text = "Stop Advertizing";
                    UpdateTextView("Advertizing");
                    _isAdvertizing = true;
                }
                else
                {
                    _advertiser.StopAdvertising(_advertiserCallback);
                    button2.Text = "Start Advertizing";
                    UpdateTextView("Stopped Advertizing");
                    _isAdvertizing = false;
                }
            };

            _listView            = FindViewById <ListView>(Resource.Id.listView1);
            _listView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
            {
                UpdateTextView("ListView clicked item, Id: " + e.Id + " Pos: " + e.Position);
            };

            UpdateTextView("OnCreate Complete");
        }
 private void ScanDevices()
 {
     _scanner = _bluetoothAdapter.BluetoothLeScanner;
     _scanner.StartScan(_scanCallback);
 }
Ejemplo n.º 30
0
        static DeviceInformation()
        {
            BluetoothManager bluetoothManager = (BluetoothManager)Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity.GetSystemService(Android.MainApplication.BluetoothService);
            _scanner = bluetoothManager.Adapter.BluetoothLeScanner;

        }
Ejemplo n.º 31
0
 public BLEAdapter(TimeSpan scanTimeout)
 {
     _adapter    = ((BluetoothManager)Application.Context.GetSystemService("bluetooth")).Adapter.BluetoothLeScanner;
     ScanTimeout = scanTimeout;
 }
 private void Initialize()
 {
     handler          = new Handler();
     bluetoothAdapter = ((BluetoothManager)Android.App.Application.Context.GetSystemService(Context.BluetoothService)).Adapter;
     leScanner        = bluetoothAdapter?.BluetoothLeScanner;
 }
Ejemplo n.º 33
0
		private void setLollipopProperty()
		{
			Console.WriteLine("Setting up lollipop property");
			this._bleScanner = this._adapter.BluetoothLeScanner;
			this._lollipopCallback = new LollipopScanCallback();
			this._lollipopCallback.deviceFoundEvent += OnLeScan;

			//ScanMode is declared in Util object due to namespace conflict of ScanMode object in both Android.Bluetooth and Android.Bluetooth.LE
			this._scanSettings = new ScanSettings.Builder().SetScanMode(Util.ScanModeLowLatency).Build();

		}