usb_serial 0.2.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 92

Pub Build Status Coverage Status

usb_serial #

An Android USB Serial Flutter Plugin

This plugin allows Flutter code to interact with USB serial devices connected to your Android device. For example an FTDI or CDC based USB device.

Getting Started #

Add a dependency to your pubspec.yaml

dependencies:
	usb_serial: ^0.2.4

include the usbserial package at the top of your dart file.

import 'package:usb_serial/usb_serial.dart'

IMPORTANT app\build.gradle #

Edit android\app\build.gradle and add

    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }

to the 'android' object, see build.grade from the example project for a template on how to do this. Without this you'll get a bunch or Java errors.

Optional #

Add

	<intent-filter>
		<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
	</intent-filter>

	<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
		android:resource="@xml/device_filter" />

to your AndroidManifest.xml

and place device_filter.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 0x0403 / 0x6001: FTDI FT232R UART -->
    <usb-device vendor-id="1027" product-id="24577" />
    
    <!-- 0x0403 / 0x6015: FTDI FT231X -->
    <usb-device vendor-id="1027" product-id="24597" />

    <!-- 0x2341 / Arduino -->
    <usb-device vendor-id="9025" />

    <!-- 0x16C0 / 0x0483: Teensyduino  -->
    <usb-device vendor-id="5824" product-id="1155" />

    <!-- 0x10C4 / 0xEA60: CP210x UART Bridge -->
    <usb-device vendor-id="4292" product-id="60000" />
    
    <!-- 0x067B / 0x2303: Prolific PL2303 -->
    <usb-device vendor-id="1659" product-id="8963" />

    <!-- 0x1366 / 0x0105: Segger JLink -->
    <usb-device vendor-id="4966" product-id="261" />

    <!-- 0x1366 / 0x0105: CH340 JLink -->
    <usb-device vendor-id="1A86" product-id="7523" />

</resources>

in the res/xml directory. This will notify your app when one of the specified devices is plugged in.

Usage of Asynchronous API #

...
onPressed: () async {
	List<UsbDevice> devices = await UsbSerial.listDevices();
	print(devices);

	UsbPort port;
	if (devices.length == 0) {
		return;
	}
	port = await devices[0].create();

	bool openResult = await _port.open();
	if ( !openResult ) {
		print("Failed to open");
		return;
	}
	
	await port.setDTR(true);
	await port.setRTS(true);

	port.setPortParameters(115200, UsbPort.DATABITS_8,
	  UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);

	// print first result and close port.
	port.inputStream.listen((Uint8List event) {
		print(event);
		port.close();
	});

	await port.write(Uint8List.fromList([0x10, 0x00]));
}
...

Usage of transaction API #

This API is a layer on top of the asynchronous part of the library. It provides two Stream Transformers and a Transaction helper based on the StreamQueue class.

  1. Terminated Transformer, this splits incoming data based on a configurable end of message bytes "terminator".
  2. Magic Header + Length byte, this splits incoming data based on a configurable header ( with wildcards! ) and a length byte directly following the header.

In case neither is a fit, you can use one of those Transformers to create you own that is specific to the binary format you are dealing with.

	
    ...
    Transaction<String> transaction = Transaction.stringTerminated(port.inputStream, Uint8List.fromList([13,10]));
    ...

    // While using transactions you can still listen to all 
    // incoming messages!    
    transaction.stream.listen( (String data) {
      print(data);
    });

    // you can write asynchronous messages as before!
    p.write(Uint8List.fromList([65,66,13,10]));
    
    // BUT you can also write 'transactions'. This is a combination of a flush, write and wait for response
    // with a timeout. If no response is received within the timeout a null value is returned.
    // this sends "AB\r\n"
    var response = await transaction.transaction(p, Uint8List.fromList([65,66,13,10]), Duration(seconds: 1) );
    print("The response was $response");
    

Dependencies #

This library depends on:

https://github.com/felHR85/UsbSerial

0.2.4 #

  • Added interfaceCount
  • Added CH340 VID/PID to example xml.
  • Added exception catch for Device Create

0.2.3 #

  • Fixed threading issue ( PR10 )

0.2.2 #

  • Fixed 3 dart lint warnings.

0.2.1 #

  • Updated the underlying UsbSerial library to 6.0.6
  • Updated the examples

0.2.0 #

  • Added Transformers and Transactions
  • Added unit tests
  • Changed Java naming, if your compile fails delete the 'build' directory and try again.

0.1.1 #

  • Merged pull request 1: Fix for NoSuchMethodException thrown on api level less than 21 during device enumeration.

0.1.0 #

  • Modified the USB Attached/Detach stream from Stream
  • Added ACTION_USB_ATTACHED and ACTION_USB_DETACHED constants to dart interface.

0.0.2 #

  • Fixed crasher when connected or disconnecting a USB device without having a sink attached.

0.0.1 #

  • Initial release, providing easy UART access to Android Flutter apps

example/lib/main.dart

import 'package:flutter/material.dart';
import 'dart:typed_data';
import 'dart:async';
import 'package:usb_serial/usb_serial.dart';
import 'package:usb_serial/transaction.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  UsbPort _port;
  String _status = "Idle";
  List<Widget> _ports = [];
  List<Widget> _serialData = [];
  StreamSubscription<String> _subscription;
  Transaction<String> _transaction;
  int _deviceId;
  TextEditingController _textController = TextEditingController();

  Future<bool> _connectTo(device) async {
    _serialData.clear();

    if (_subscription != null) {
      _subscription.cancel();
      _subscription = null;
    }

    if (_transaction != null) {
      _transaction.dispose();
      _transaction = null;
    }

    if (_port != null) {
      _port.close();
      _port = null;
    }

    if (device == null) {
      _deviceId = null;
      setState(() {
        _status = "Disconnected";
      });
      return true;
    }

    _port = await device.create();
    if (!await _port.open()) {
      setState(() {
        _status = "Failed to open port";
      });
      return false;
    }

    _deviceId = device.deviceId;
    await _port.setDTR(true);
    await _port.setRTS(true);
    await _port.setPortParameters(
        115200, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);

    _transaction = Transaction.stringTerminated(
        _port.inputStream, Uint8List.fromList([13, 10]));

    _subscription = _transaction.stream.listen((String line) {
      setState(() {
        _serialData.add(Text(line));
        if (_serialData.length > 20) {
          _serialData.removeAt(0);
        }
      });
    });

    setState(() {
      _status = "Connected";
    });
    return true;
  }

  void _getPorts() async {
    _ports = [];
    List<UsbDevice> devices = await UsbSerial.listDevices();
    print(devices);

    devices.forEach((device) {
      _ports.add(ListTile(
          leading: Icon(Icons.usb),
          title: Text(device.productName),
          subtitle: Text(device.manufacturerName),
          trailing: RaisedButton(
            child:
                Text(_deviceId == device.deviceId ? "Disconnect" : "Connect"),
            onPressed: () {
              _connectTo(_deviceId == device.deviceId ? null : device)
                  .then((res) {
                _getPorts();
              });
            },
          )));
    });

    setState(() {
      print(_ports);
    });
  }

  @override
  void initState() {
    super.initState();

    UsbSerial.usbEventStream.listen((UsbEvent event) {
      _getPorts();
    });

    _getPorts();
  }

  @override
  void dispose() {
    super.dispose();
    _connectTo(null);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('USB Serial Plugin example app'),
      ),
      body: Center(
          child: Column(children: <Widget>[
        Text(
            _ports.length > 0
                ? "Available Serial Ports"
                : "No serial devices available",
            style: Theme.of(context).textTheme.title),
        ..._ports,
        Text('Status: $_status\n'),
        ListTile(
          title: TextField(
            controller: _textController,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Text To Send',
            ),
          ),
          trailing: RaisedButton(
            child: Text("Send"),
            onPressed: _port == null
                ? null
                : () async {
                    if (_port == null) {
                      return;
                    }
                    String data = _textController.text + "\r\n";
                    await _port.write(Uint8List.fromList(data.codeUnits));
                    _textController.text = "";
                  },
          ),
        ),
        Text("Result Data", style: Theme.of(context).textTheme.title),
        ..._serialData,
      ])),
    ));
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  usb_serial: ^0.2.4

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:usb_serial/usb_serial.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
84
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
92
Learn more about scoring.

We analyzed this package on Mar 27, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.68.0 <3.0.0
async ^2.1.0 2.4.1
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
coveralls ^5.2.0
flutter_test