Giter Club home page Giter Club logo

flutter_web_bluetooth's Introduction

pub package

Introduction

Flutter web bluetooth is a Flutter Dart plugin to add support for the web bluetooth api.

The library doesn't require Flutter at all giving you the option to use it with projects like AngularDart.

It is also written in such a way that it will play nicely with Dart native projects. So if you have a cross-platform app and want to add web support you don't have to use conditional exports to exclude the library in native releases.

For example:

export 'src/unsupported_library.dart'
    if (dart.library.html) 'src/web_library.dart';

It will (of course) not work when not used in a browser, but it will compile!

The example code in this project is hosted on Github pages. Checkout jeroen1602.github.io/flutter_web_bluetooth/ for a proof of concept.

Limited support

The web bluetooth is still a draft, because of this it is not (yet) supported in every browser. Check canIUse.com for information about browser support.

Some parts of the api aren't available in every version of the browser.

Requirements

The device and browser you're testing on needs to support the web api. For Chrome on Linux this is hidden behind a flag. I've created a patch file which you can use to launch Google Chrome, from flutter run with the required flag enabled. Check the chrome-experimental-launch folder's README for more information.

You will also need a secure context or else the api will not be available. So either https, or localhost.

Usage

First check if the current browser supports the web bluetooth api.

// The bluetooth api exists in this user agent.
final supported = FlutterWebBluetooth.instance.isBluetoothApiSupported;

After this we will need to check if bluetooth is available

// A stream that says if a bluetooth adapter is available to the browser.
final available = FlutterWebBluetooth.instance.isAvailable;

Now request a device from the browser. You must beforehand specify which services you want to connect to! If you do not request access to a specific service then you won't be able to discover the service!

Some services are also part of a so called blocklist. This is different per browsers and these services are just off limit.

// Define the services you want to communicate with here!
final requestOptions = RequestOptionsBuilder.acceptAllDevices(optionalServices: [
  BluetoothDefaultServiceUUIDS.deviceInformation.uuid
]);

try {
  final device = await FlutterWebBluetooth.instance.requestDevice(requestOptions);
} on UserCancelledDialogError {
  // The user cancelled the dialog
} on DeviceNotFoundError {
  // There is no device in range for the options defined above
}

Now that you have a device, you can go through the services and then find the characteristics you want to read.

await device.connect();
final services = await device.discoverServices();
final service = services.firstWhere((service) => service.uuid == BluetoothDefaultServiceUUIDS.deviceInformation.uuid);
// Now get the characteristic
final characteristic = await service.getCharacteristic(BluetoothDefaultCharacteristicUUIDS.manufacturerNameString.uuid);
final value = characteristic.readValue();
// Now we have a [ByteData] object with the manufacturer name in it.
device.disconnect();

Once you have paired to a device you can communicate with it again without the user needing to pair to it again. Get a reference back to all the connected devices by listening to the devices stream.

Note: This feature will only work if the "Experimental Web Platform features" flag is enabled.

// A stream with a [Set] of all the devices that the user has paired, and given permission for.
FlutterWebBluetooth.instance.devices;

You can also overwrite the logger that his library uses. This allows you to decide where log messages go. See logging on pub.dev for more info on how to intercept these messages.

import 'package:flutter_web_bluetooth/web_bluetooth_logger.dart';

setWebBluetoothLogger(Logger("my logger"));

flutter_web_bluetooth's People

Contributors

alextekartik avatar dependabot[bot] avatar jeroen1602 avatar msmithdev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

flutter_web_bluetooth's Issues

Support Notifications

It looks like this plugin doesn't support notification characteristics. Is it possible?

Can We Get Manufacturer Data or FilterOption by Manufacturer data

As title Says , can we get Manufacturer data of Scanned Devices , i know name and id is available Api , so it will be tricky to add manufacturer data in BluetoothDevice
but At least we have filter by Manufacturer data option in requestDevice, can you implement that in this plugin

How to determine the current connected device ?

@jeroen1602 How can I determine the device with which the interaction is currently taking place. My program works with the same type of devices with different IDs. I need to show the user the number of the device with which he is now interacting.
The code below permanently prints all devices that were connected during the current browser session.
At the same time, the browser works with the last one connected, how to determine the last one?

FlutterWebBluetooth.instance.devices.listen((devices) {
      for (var device in devices) {
        print(device.name);
        device.connected.listen((connected) {
          if (connected) {
            print('Connected ${device.name}');
          }
        });
      }

MTU

can u support MTU size api?

Unable to read data using .value property from a BluetoothCharacteristic object.

Hi,
After going through a ton of effort, I'm still unable to read data. Please help!
I'm using this simple code to read data from a characteristic but the value stream seems to be empty.


readCharacteristic = await services
                  .firstWhere((service) => service.uuid == SERVICE_UUID)
                  .getCharacteristic(READ_UUID);

print("read characteristic: ${readCharacteristic.uuid}");
await readCharacteristic.startNotifications();
try {
  await readCharacteristic.value
      .timeout(Duration(seconds: 5))
      .firstWhere((element) {
    print("buffer: ${element.buffer}");
    print("elementSizeInBytes: ${element.elementSizeInBytes}");
    print("lengthInBytes: ${element.lengthInBytes}");
    print("offsetInBytes: ${element.offsetInBytes}");
    return false;
  });
} catch (e) {
  print("err: $e");
}

I printed out the readCharacteristic.uuid to make sure that the characteristic is recognized properly. But when I'm expecting to receive data immediately, after 10 seconds the timeout exceeds and I catch a timeout error which I suppose indicates that the stream was empty until that time. If I'm being correct, at least my terminal should have prompted the properties of whatever ByteData is being received.

I have also tried .lastValue.

To make sure that my transmitter device is indeed transmitting, I successfully read data using two other platforms using a similar method.

Regards.

Support for getting list of characteristics from a service

According to the API: https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService#methods

It seems this is currently implemented:

BluetoothRemoteGATTService.getCharacteristic() 
Returns a Promise to an instance of BluetoothRemoteGATTCharacteristic for a given universally unique identifier (UUID).

But not this:

BluetoothRemoteGATTService.getCharacteristics() 
Returns a Promise to an Array of BluetoothRemoteGATTCharacteristic instances for an optional universally unique identifier (UUID).

I am trying to retrieve a list of characteristics from a given service, these UUID's could be unknown so I cant get by UUID. It seems like flutter_web_bluetooth does not have this yet.

Can't find any service

This is my code

 bool sup = FlutterWebBluetooth.instance.isBluetoothApiSupported;
    print('isBluetoothApiSupported  ' + sup.toString());
    FlutterWebBluetooth.instance.isAvailable.listen((event) {
      print('isAvailable  ' + event.toString());
    });

    final requestOptions = RequestOptionsBuilder.acceptAllDevices(optionalServices: BluetoothDefaultServiceUUIDS.VALUES.map((e) => e.uuid).toList());

    try {
      final BluetoothDevice device = await FlutterWebBluetooth.instance.requestDevice(requestOptions);

      print(device);
      device.connected.listen((event) {
        print('connected  ' + event.toString());
      });
      await device.connect();
      print('connect');

      sers = await device.discoverServices();
      print('sers  ' + sers.toString());
      device.services.listen((event) {
        setState(() {
          sers2 = event;
          print('services.listen  ' + sers.toString());
        });
      });
    } on UserCancelledDialogError {
      print(1);
    } on DeviceNotFoundError {
      print(2);
    }
  }

I run on MacOS with Android Studio, This is the console:

isBluetoothApiSupported true
isAvailable true
isAvailable true
Instance of 'BluetoothDevice'
connected true
connect
connected true
sers []

I can connect, but I can't get any services
How to resolve?

Browser supports

creating a Bluetooth communication web application in flutter.

I am using flutter_web_bluetooth: ^0.2.1 library for achieve the bluetooth functionality.

  • First I enable the Experimental Web Platform Features flag in chrome
  • After enable write code for current browser supports the web bluetooth api.

Issue

In my chrome Experimental Web Platform Features flag is enable, but when i run the code in flutter after that a new chrome tab is open, in it the browser is showing browser web bluetooth api support false because the Experimental Web Platform Features flag appears disabled even after enabling the flag . Again i enabled the flag and restarted, And then run the Flutter application and again the flag is disable.
how can i enable this flag?

Screenshots/ GIF

Screencast.from.17-08-23.03.21.57.PM.IST.webm

Error with brand new Flutter project

  1. Ran flutter create
  2. Added package to pubspect.yaml
  3. Ran application
  4. Getting warning

Flutter Doctor output
image

Warning: Operand of null-aware operation '!' has type 'Set<BluetoothDevice>' which excludes null
'Set' is from 'dart:core'.
'BluetoothDevice' is from 'package:flutter_web_bluetooth/src/flutter_web_bluetooth_web.dart' ? _knownDevicesStream.value!

image

Misleading description on pub.dev

Please change the description on pub.dev for this package. Windows, Linux, MacOS, iOS and Android don't work. This is misleading for people looking for a genuine cross platform solution.

Unable to getting Services of Bluetooth Device

I have connected ble device using flutter_web_bluetooth library, now i trying to get ble device services but i'm getting empty list of services, here is my code, could you please tell me do i need to do some modification in this code for getting services.

connectedDevice?.discoverServices().then((services) async {
services.forEach((service) {
print("uuid - ${service.uuid}");
});
});

and I tried this also.

List? services = await connectedDevice?.discoverServices();

Signal strength

Thanks for your great work
Is it possible to get the signal strength of a device without pairing it ?

Couldn't find all of the services!

I've successfully managed to connect to the ble device and get its services by both calling discoverServices and services on the BluetoothDevice object.
The problem is that it only returns 3 primary services namely 1800, 1801, and 180a which are not useful to me and are for generic access, generic attributes, and device information respectively.
I'm looking for FFF0 service which holds the characteristics FFF1 and FFF2 for reading and writing data.
*Note that I've already found and worked with the FFF0 service with both the flutter_blue package for android and ios and NRF connect mobile app; meaning that the service indeed exists.
As I decided to expand my project to the web, I thought that flutter_web_bluetooth is a suitable alternative.
In short:
A service is missing from the services list. Does anyone know how to solve this problem?

/// getting bluetooth devices
await FlutterWebBluetooth.instance.requestDevice(
        RequestOptionsBuilder.acceptAllDevices(
            optionalServices: BluetoothDefaultServiceUUIDS.VALUES
                .map((e) => e.uuid)
                .toList()));

FlutterWebBluetooth.instance.devices
        .firstWhere(
            (devices) => devices.any((device) => device.name == "NAME"))
        .then((devices) async {
      /// storing the device in a custom object member of type BluetoothDevice
      Bluetooth.connectedDevice =
          devices.firstWhere((device) => device.name == "NAME");
      Bluetooth.connectedDevice.connect();
      
      /// getting services after device is connected 
      StreamSubscription subscription;
      subscription = Bluetooth.connectedDevice.connected.listen((event) async {
        print("waiting for device to be connected");
        if (event) {
          Bluetooth.connectedDevice.discoverServices().then((services) async {
            services.forEach((service) {
              print(service.uuid);
            });
          });
          subscription.cancel();
        }
      });
    });

It returns three services with uuids:
00001800-0000-1000-8000-00805F9B34FB
00001801-0000-1000-8000-00805F9B34FB
0000180a-0000-1000-8000-00805F9B34FB

But I'm looking for:
0000FFF0-0000-1000-8000-00805F9B34FB

Thermal Printers compatibility?

Wrote data to a Thermal POS printer but nothing happens. Tried this same approach using other bluetooth libraries on native platforms and it works fine. I'm I missing something??

` for (var i = 0; i < data.length; i++) {

  try {
    await charac.writeValueWithResponse(data[i] as Uint8List);
  } catch (e) {
    print("web: error $e");
    return false;
 }
   }`

Getting meta dependency issue

flutter_web_bluetooth ^0.0.8 requires meta >=1.3.0 <1.8.0. And because every version of flutter_localizations from sdk depends on meta 1.8.0

Because every version of flutter_test from sdk depends on meta 1.8.0 and flutter_web_bluetooth depends on meta >=1.3.0 <1.8.0, flutter_test from sdk is incompatible with flutter_web_bluetooth

Cannot listen for changes on characteristic.startNotifications()

Does there exist a valueListener in Web ble for flutter to listen for changes in notifications?

example for web ble:


  function handleScaleMeasurementCharacteristic(characteristic) {
      console.log(characteristic);
      console.log("Starting notifications...");
      return characteristic.startNotifications().then((char) => {
        console.log("Adding event listener...");
        char.addEventListener(
          "oncharacteristicvaluechanged",
          onCharacteristicValueChanged
        );
      });
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.