flutter_bluetooth_serial 0.2.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 92

flutter_bluetooth_serial #

pub package

Flutter basic implementation for Classical Bluetooth (only RFCOMM for now).

Features #

The first goal of this project, started by Edufolly was making an interface for Serial Port Protocol (HC-05 Adapter). Now the plugin features:

  • Adapter status monitoring,

  • Turning adapter on and off,

  • Opening settings,

  • Discovering devices (and requesting discoverability),

  • Listing bonded devices and pairing new ones,

  • Connecting to multiple devices at the same time,

  • Sending and recieving data (multiple connections).

The plugin (for now) uses Serial Port profile for moving data over RFCOMM, so make sure there is running Service Discovery Protocol that points to SP/RFCOMM channel of the device. There could be max up to 7 Bluetooth connections.

For now there is only Android support.

Getting Started #

Depending #

# Add dependency to `pubspec.yaml` of your project.
dependencies:
    # ...
    flutter_bluetooth_serial: ^0.2.2

Installing #

# With pub manager
pub get
# or with Flutter
flutter pub get

Importing #

import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

Usage #

You should look to the Dart code of the library (mostly documented functions) or to the examples code.

// Some simplest connection :F
try {
    BluetoothConnection connection = await BluetoothConnection.toAddress(address);
    print('Connected to the device');

    connection.input.listen((Uint8List data) {
        print('Data incoming: ${ascii.decode(data)}');
        connection.output.add(data); // Sending data

        if (ascii.decode(data).contains('!')) {
            connection.finish(); // Closing connection
            print('Disconnecting by local host');
        }
    }).onDone(() {
        print('Disconnected by remote request');
    });
}
catch (exception) {
    print('Cannot connect, exception occured');
}

Note: Work is underway to make the communication easier than operations on byte streams. See #41 for discussion about the topic.

Examples #

Check out example application with connections with both Arduino HC-05 and Raspberry Pi (RFCOMM) Bluetooth interfaces.

Main screen and optionsDiscovery and connectingSimple chat with serverBackground connection

To-do list #

  • Add some utils to easier manage BluetoothConnection (see discussion #41),
  • Allow connection method/protocol/UUID specification,
  • Listening/server mode,
  • Recognizing and displaying BluetoothClass of device,
  • Maybe integration with flutter_blue one day ;)

You might also want to check milestones.

[0.2.2] - 2019-08-19

Patch release.

  • Fix closing connections which are not listening to input (solved #60),
  • Add more clear example of detecting which side caused disconnection,
  • Add exception on adding to output if connection closed,
  • BluetoothConnection cancel is deprecated now, use close instead. It was stupid to name cancel something that closes (it was even documented that way, lol).

[0.2.1] - 2019-08-05

Patch release.

  • apply patch #48 for some disconnection issues,
  • update ChatPage to newer API,
  • fix and update AndroidX declaration.

[0.2.0] - 2019-07-02

Two big features packs:

  • Bonding (Pairing):
    • starting outgoing pairing requests,
    • handling incoming pairing requests,
    • remove current bondings to devices,
  • Discoverability!
    • requesting discoverable mode for specified duration,
    • example with timeout countdown,
    • checking discoverable mode.

And few more features:

  • get/set for local (discoverable) device name,
  • getting local adapter address (with some hacks to work on newer Androids),
  • checking for isConnected for discovered or bonded devices,
  • fixed few broadcast receiver leaks.

[0.1.1] - 2019-07-01

  • Patch #43 for "Error when meet unknown devices".

[0.1.0] - 2019-06-19

Pull request #35 by @PsychoXIVI changes a lot:

  • Discovering other devices,
  • Multiple connections,
  • Interesting example application,
  • Enabling/Disabling Bluetooth,
  • Byte streams,
  • Overall improvements and fixes.

[0.0.5] - 2019-03-18

  • Upgrade for AndroidX support (thanks @akilinomendez)
  • New default constructor (thanks @MohiuddinM)
  • Added method write passing byte[] (thanks @rafaelterada)
  • Upgrade to Android Studio 3.3.2

[0.0.4] - 2018-12-20

  • Unsupported value error correction (thanks @rafaelterada)
  • Added openSettings, which opens the bluetooth settings screen (thanks @rafaelterada)

[0.0.3] - 2018-11-22

  • async connection and null exception handled (thanks @MohiuddinM)

[0.0.2] - 2018-09-27

  • isConnected Implementation (thanks @Riscue)

[0.0.1] - 2018-08-20

  • Only Android support.

example/README.md

flutter_bluetooth_serial_example #

Example application demonstrates key features of the flutter_bluetooth_serial plugin:

  • Adapter status monitoring,

  • Turning adapter on and off,

  • Opening settings,

  • Discovering devices (and requesting discoverability),

  • Listing bonded devices and pairing new ones,

  • Connecting to multiple devices at the same time,

  • Sending and recieving data (multiple connections).

The plugin (for now) uses Serial Port profile for moving data over RFCOMM, so make sure there is running Service Discovery Protocol that points to SP/RFCOMM channel of the device.

Screens #

Main screen and optionsDiscovery and connectingSimple chat with serverBackground connection

Note: There screen-shots might be out-dated. Build and see the example app for yourself, you won't regret it. :)

Tests #

There is a recording of the tests (click for open video as WEBM version):

Test with multiple connections

General #

The basics are simple, so there is no need to write about it so much.

Discovery page #

On devices list you can long tap to start pairing process. If device is already paired, you can use long tap to unbond it.

Chat example #

There is implemented simple chat. Client (the Flutter host) connects to selected from bonded devices server in order to exchange data - asynchronously.

Simple (console) server on Raspberry Pi: #

  1. Enable Bluetooth and pair Raspberry with the Flutter host device (only first time)
$ sudo bluetoothctl
# power on
# agent on
# scan on
# pair [MAC of the Flutter host]
# quit
  1. Add SP/RFCOMM entry to the SDP service
$ sudo sdptool add SP         # There can be channel specified one of 79 channels by adding `--channel N`.
$ sudo sdptool browse local   # Check on which channel RFCOMM will be operating, to select in next step.

SDP tool tends to use good (and free) channels, so you don't have to keep track of other services if you let it decide.

  1. Start RFCOMM listening
$ sudo killall rfcomm
$ sudo rfcomm listen /dev/rfcomm0 N picocom -c /dev/rfcomm0 --omap crcrlf   # `N` should be channel number on which SDP is pointing the SP.
  1. Now you can connect and chat to the server with example application using the console. Every character is send to your device and buffered. Only full messages, between new line characters (\n) are displayed. You can use Ctrl+A and Ctrl+Q to exit from picocom utility if you want to end stream from server side (and Ctrl+C for exit watch-mode of rfcomm utility).

If you experiencing problems with your terminal (some term_exitfunc of picocom errors), you should try saving good terminal settings (stty --save > someFile) and loading them after picocom exits (adding ; stty `cat someFile` to the second command of 3. should do the thing).

You can also use the descriptor (/dev/rfcomm0) in other way, not necessarily to run interactive terminal on it, in order to chat. It can be used in various ways, providing more automation and/or abstraction.

Background monitor example #

For testing multiple connections there were created background data collector, which connects to Arduino controller equiped with HC-05 Bluetooth interface, 2 DS18B20 termometers and water pH level meter. There are very nice graphs to displaying the recieved data.

The example uses Celsius degree, which was chosen because it utilizes standard conditions of water freezing and ice melting points instead of just rolling a dice over periodic table of elements like a Fahrenheit do...

Project of the Arduino side could be found in /arduino folder, but there is a note: the code is prepared for testing in certain environment and will not work without its hardware side (termometers, pH meter). If you can alter the real termometer code for example for random data generator or your own inputs.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_bluetooth_serial: ^0.2.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
92
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
92
Learn more about scoring.

We analyzed this package on Nov 22, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.6

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/BluetoothBondState.dart.

Run flutter format to format lib/BluetoothBondState.dart.

Format lib/BluetoothConnection.dart.

Run flutter format to format lib/BluetoothConnection.dart.

Format lib/BluetoothDevice.dart.

Run flutter format to format lib/BluetoothDevice.dart.

Fix additional 5 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/BluetoothDeviceType.dart (Run flutter format to format lib/BluetoothDeviceType.dart.)
  • lib/BluetoothPairingRequest.dart (Run flutter format to format lib/BluetoothPairingRequest.dart.)
  • lib/BluetoothState.dart (Run flutter format to format lib/BluetoothState.dart.)
  • lib/FlutterBluetoothSerial.dart (Run flutter format to format lib/FlutterBluetoothSerial.dart.)
  • lib/flutter_bluetooth_serial.dart (Run flutter format to format lib/flutter_bluetooth_serial.dart.)

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-a <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8