pauldemarco / flutter_blue

Bluetooth plugin for Flutter
BSD 3-Clause "New" or "Revised" License
2.36k stars 1.23k forks source link

How to refresh beacons RSSI continuesly. #905

Open imeteora opened 2 years ago

imeteora commented 2 years ago

How to refresh beacons RSSI continuesly. Now, I only get some scanned bluetooth devices with their static RSSI value. RSSI is NOT changing.

My Code is like this:

import 'package:BeaconSim/AppService/Models/ble_device_model.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:rxdart/rxdart.dart';

enum BleRunningState { yield, scanning }

class BleManager {

  BleManager._();
  static BleManager? _instance;
  static BleManager shared = BleManager._getInstance();
  factory BleManager._getInstance() => _instance ??= BleManager._();

  FlutterBlue get _ble => FlutterBlue.instance;

  List<BleDeviceModel> _bleDevices = <BleDeviceModel>[];

  List<BleDeviceModel> get devices => _bleDevices;

  final _discoverDeviceRx = BehaviorSubject<List<BleDeviceModel>>.seeded([]);

  Stream<List<BleDeviceModel>> get discoverDevices => _discoverDeviceRx.stream;

  final runningState = BehaviorSubject<BleRunningState>();

  Stream<BleRunningState> get runningStateStream => runningState.stream;

  void setupBle() {
    _ble.scanResults.listen((List<ScanResult> results) {
      results.forEach((element) =>
          _addBleDevToList(BleDeviceModel.from(scanResult: element)));
    });

    _ble.isScanning.listen((state) => runningState
        .add(state ? BleRunningState.scanning : BleRunningState.yield));
  }

  Future scanning() async => _ble.isAvailable
      .then((available) async => available && await _ble.isOn)
      .then((isOn) => isOn && runningState.value == BleRunningState.scanning)
      .then((state) => _ble.startScan(scanMode: ScanMode.balanced));

  Future stopScanning() async => _ble.isAvailable
      .then((available) async => available && await _ble.isOn)
      .then((isOn) => isOn && runningState.value == BleRunningState.scanning)
      .then((value) => _ble.stopScan());

  void _addBleDevToList(final BleDeviceModel dev) {
    final BleDeviceModel? found = _bleDevices
        .cast<BleDeviceModel?>()
        .firstWhere((e) => e?.mac == dev.mac, orElse: () => null);

    if (found != null) {
      print('dev.rssi = ${dev.rssi}, found.rssi = ${found.rssi}');
      found.reborn();
      found.update(dev);
    } else {
      dev.reborn();
      _bleDevices.add(dev);
    }

    _discoverDeviceRx.add([dev]);
  }
}
userentity commented 2 years ago

I have the same problem. Did you solve it? I would be grateful for your help. Thanks

qinjinze commented 2 years ago

Hope to get the real-time signal rssi value of the connected Bluetooth device

udit6023 commented 1 year ago

any updates on this issue??

altughamdi commented 1 year ago

I have same problem in Android app. The Rssi value is refreshed continuously on iOS but the same code don't work on Android. Is there any update?