DEV Community

Cover image for bluetooth_spp: Bluetooth Classic serial for Flutter, for OBD dongles and printers
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

bluetooth_spp: Bluetooth Classic serial for Flutter, for OBD dongles and printers

Most Bluetooth plugins for Flutter are about Bluetooth Low Energy. A lot of hardware still speaks the older protocol: ELM327 OBD-II dongles, thermal printers, scales, barcode scanners, HC-05 modules. These devices expose a serial port over Bluetooth Classic, known as RFCOMM or SPP, and from the app's side it is a plain byte stream. You write bytes, you read bytes.

bluetooth_spp is a Flutter plugin for that byte stream on Android. Its README describes it as a maintained, clean-room replacement for flutter_bluetooth_serial.

What it does

The adapter. An adapterState stream, isEnabled(), and requestEnable(), which shows the system dialog through ACTION_REQUEST_ENABLE.

Paired devices. bondedDevices() returns the name, address, type, bond state and Class of Device of each one.

Discovery. startDiscovery() returns a Stream<DiscoveryResult> with RSSI. Cancel the subscription or call cancelDiscovery() to stop it.

Bonding. bond(address) waits for the pairing result. removeBond(address) is best-effort.

Connections. connect() returns an SppConnection with:

  • input, a Stream<Uint8List>;
  • write(bytes), whose future completes after the bytes are flushed to the socket, which gives you backpressure;
  • close(), isConnected, a state stream and disconnectReason.

Several connections at once. Each one has its own id, its own reader thread and its own writer thread.

Fallbacks for difficult devices. They are opt-in: an insecure RFCOMM socket, and the channel-1 createRfcommSocket reflection trick for clone ELM327 dongles.

Typed errors, no blocking. Nothing blocks the Android main thread. Every native exception is mapped to a typed Dart exception, such as SppConnectException, SppTimeoutException or BluetoothPermissionException.

Correct manifest permissions. For Android 12 and later, BLUETOOTH_CONNECT and BLUETOOTH_SCAN with neverForLocation. For older versions, BLUETOOTH, BLUETOOTH_ADMIN and location, all with maxSdkVersion="30".

Clean detach. When the engine detaches, broadcast receivers are unregistered, discovery is cancelled, and pending and open sockets are closed.

How to use it

Add it from GitHub:

dependencies:
  bluetooth_spp:
    git: https://github.com/AbdeldjalilChougui/bluetooth_spp
Enter fullscreen mode Exit fullscreen mode

minSdk is 21. The plugin's manifest merges the Bluetooth permissions into your app.

Here is the README's example, reading the battery voltage from an ELM327 dongle:

import 'dart:convert';

import 'package:bluetooth_spp/bluetooth_spp.dart';

Future<void> readVoltage() async {
  final spp = BluetoothSpp.instance;

  if (!await spp.isEnabled() && !await spp.requestEnable()) return;

  final paired = await spp.bondedDevices();
  final dongle = paired.firstWhere((d) => (d.name ?? '').contains('OBD'));

  final SppConnection connection;
  try {
    connection = await spp.connect(
      dongle.address,
      timeout: const Duration(seconds: 10),
      rfcommChannelFallback: true, // clone ELM327 dongles, see below
    );
  } on SppTimeoutException {
    return;
  } on SppConnectException catch (e) {
    print('connect failed: ${e.message}');
    return;
  }

  // Replies arrive in arbitrary chunks; ELM327 ends each one with '>'.
  final buffer = StringBuffer();
  final prompt = connection.input.map(latin1.decode).map((s) {
    buffer.write(s);
    return buffer.toString();
  }).firstWhere((text) => text.endsWith('>'));

  await connection.write(latin1.encode('ATRV\r')); // completes when flushed
  print(await prompt); // e.g. "12.6V\r\r>"
  await connection.close();
}
Enter fullscreen mode Exit fullscreen mode

Note how the reply is handled. input delivers bytes in whatever chunks the radio produced, so the code collects them until the protocol's delimiter arrives: > for ELM327, \r\n for most scales.

Two devices at once, for example a scale and a printer:

final scale = await BluetoothSpp.instance.connect(scaleAddress);
final printer = await BluetoothSpp.instance.connect(printerAddress);
scale.input.listen((bytes) => printer.write(bytes));
Enter fullscreen mode Exit fullscreen mode

Permissions

The plugin declares the permissions but never requests them at runtime, so you choose when and how to show the dialog. On Android 12 and later you need BLUETOOTH_CONNECT for paired devices, connect, bond and enable, plus BLUETOOTH_SCAN for discovery. On Android 6 to 11, discovery needs location permission and location services turned on.

permissionsStatus() tells you what is granted: status.allGranted is the quick check, and status.missing lists the exact Android permission names that are still denied. The README shows the full flow with a permissions plugin.

Connection fallbacks

By default connect() makes one attempt, createRfcommSocketToServiceRecord(uuid). This is an authenticated socket, and Android looks up the RFCOMM channel through SDP. You can opt in to more attempts, which share the same total timeout:

  • secure: false uses only the insecure socket, for devices that pair without a PIN or reject authenticated links.
  • insecureFallback: true tries the insecure socket after the secure one fails. Some printers and scanners only accept insecure links.
  • rfcommChannelFallback: true tries the hidden createRfcommSocket(1) through reflection, last. Many cheap ELM327 clones return a broken SDP record, so the lookup fails with read failed, socket might closed or timeout, read ret: -1, although the serial service really is on channel 1.

The channel-1 fallback is opt-in for three reasons the README states plainly: it uses a non-public API that Android may restrict, it assumes channel 1, which is wrong for devices that expose several services, and it skips the service UUID you asked for.

Migrating from flutter_bluetooth_serial

The README has a mapping table. The main changes:

  • FlutterBluetoothSerial.instance becomes BluetoothSpp.instance.
  • getBondedDevices() becomes bondedDevices(), and bondDeviceAtAddress(address) becomes bond(address).
  • BluetoothConnection.toAddress(address) becomes BluetoothSpp.instance.connect(address).
  • connection.output.add(bytes) followed by await output.allSent becomes await connection.write(bytes).
  • PlatformException(connect_error, ...) becomes typed exceptions.
  • The old plugin asked for location itself; here you ask, and check permissionsStatus().

Not carried over: setPairingRequestHandler, requestDiscoverable, changeName, openSettings, and the address and name of the local adapter. Pairing PINs are entered in the system dialog. input is single-subscription; call asBroadcastStream() if you need several listeners.

Things to know

  • Android only. iOS does not allow Bluetooth Classic SPP without MFi, Apple's accessory program, so there is no iOS implementation. There is no web or desktop implementation either.
  • Bluetooth Classic only. For BLE UART modules (HM-10, nRF UART) use a BLE plugin.
  • Client side only. There is no RFCOMM server socket.
  • Hidden APIs. removeBond and rfcommChannelFallback rely on hidden Android APIs and may stop working on future Android versions.
  • No background service. Connections live as long as the Flutter engine and are closed when it detaches.
  • Timeouts. Android's own connect has no timeout, so the plugin closes the socket when timeout expires.
  • Pairing tips from the README. Most ELM327 dongles, HC-05/HC-06 modules and thermal printers use 1234 or 0000 as PIN. Pairing in the Android Bluetooth settings first is often the most reliable path.
  • What was tested. The Dart API is tested with mocked method and event channels, and the Kotlin logic (UUID parsing, error mapping, connection registry, chunked write queue, read loop, connect plan, permission policy) with JUnit. The example app has an emulator integration test against the emulator's virtual Bluetooth controller. It checks permissionsStatus, adapterState, isEnabled, bondedDevices, the typed errors, a connect to an address with no device (a timeout or connect error within the timeout, with every fallback), a bond that returns false, and a discovery that ends after about 12 seconds.
  • Not tested: a real SPP link. This is the most important caveat. The emulator has no Bluetooth Classic device to talk to, so a successful connect, reading, writing, a remote disconnect, a successful bond, removeBond and the requestEnable dialog were not exercised, and discovery found no devices. Everything ran on the Android emulator (Pixel 10 image, API 37); a physical phone was not tested.

Why I built it

Serial devices are simple on paper and stubborn in practice. The README's troubleshooting section reads like a list of what goes wrong: the read failed, socket might closed or timeout error, which it calls the most common complaint about the old plugin; clone dongles with a broken SDP record; printers that refuse authenticated links; a connect call that blocks for about 12 seconds on an out-of-range device; replies that arrive split in pieces.

I wanted a plugin that treats those as normal cases. That means a connect plan with explicit, opt-in fallbacks instead of hidden retries, a real timeout, a write that completes only when the bytes are flushed, typed exceptions instead of one generic platform error, and permissions declared correctly for Android 12 and later without the plugin asking for anything on its own.

The limits are stated just as plainly. The code paths are covered by unit tests and by an emulator test, but no real SPP link has been exercised yet. If you try it with real hardware, a report of what worked and what did not is useful.

Get the code

The source, the migration table, the troubleshooting guide, the example app and the tests are on GitHub: https://github.com/AbdeldjalilChougui/bluetooth_spp. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)