This Dart package is based on libserialport, which is a minimal C-library created by the sigrok project, and released under the LGPL3+ license.
Supported platforms:
This package uses dart:ffi to call libserialport's C APIs, which implies that libserialport must be bundled to or deployed with the host application. It can be tedious to build and deploy libserialport on all target platforms, but in case you are building a Flutter app instead of a pure Dart app, there is a ready-made drop-in solution called flutter_libserialport that utilizes Flutter's build system to build and deploy libserialport on all supported platforms:
import 'package:libserialport/libserialport.dart';
final name = SerialPort.availablePorts.first;
final port = SerialPort(name);
if (!port.openReadWrite()) {
print(SerialPort.lastError);
exit(-1);
}
port.write(/* ... */);
final reader = SerialPortReader(port);
reader.stream.listen((data) {
print('received: $data');
});
To use this package, add libserialport as a dependency in your pubspec.yaml file.
Run this command:
With Dart:
$ dart pub add libserialport
With Flutter:
$ flutter pub add libserialport
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):
dependencies:
libserialport: ^0.2.0+3
Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:libserialport/libserialport.dart';
Example
import 'package:libserialport/libserialport.dart';
// ignore_for_file: avoid_print
void main() {
print('Available ports:');
var i = 0;
for (final name in SerialPort.availablePorts) {
final sp = SerialPort(name);
print('${++i}) $name');
print('\tDescription: ${sp.description}');
print('\tManufacturer: ${sp.manufacturer}');
print('\tSerial Number: ${sp.serialNumber}');
print('\tProduct ID: 0x${sp.productId!.toRadixString(16)}');
print('\tVendor ID: 0x${sp.vendorId!.toRadixString(16)}');
sp.dispose();
}
}