A flutter SerialPort library using win32 API.

Overview

serial_port_win32

A SerialPort library using win32 API.

pub

Getting Started

Get Ports

final ports = SerialPort.getAvailablePorts();
print(ports);
/// result like [COM3, COM4]

Create Serial Port

The port instance is Singleton Pattern. Don't re-create port for same Com name.

final port = SerialPort("COM5", openNow: false, ByteSize: 8);
// port.open()
port.openWithSettings(BaudRate: CBR_115200);
// final port = SerialPort("COM5"); /// auto open with default settings

Set parameters

port.BaudRate = CBR_115200;
port.ByteSize = 8;
port.StopBits = ONESTOPBIT;
port.Parity = NOPARITY;
port.ReadIntervalTimeout = 10;
/// and so on, parameters like win32.

Read

port.readBytesOnListen(8, (value) => print(value));
// or
port.readOnListenFunction = (value) {
  print(value);
};
// port.readOnListenFunction = (value) {
//   print(value);
// };
// Future.delayed(Duration(seconds: 5)).then((value) {
//   port.writeBytesFromString('close');
//   sleep(Duration(seconds: 1));
//   port.close();
// });

Write

Write String

String buffer = "hello";
port.writeBytesFromString(buffer);

Write Uint8List

final uint8_data = Uint8List.fromList([1, 2, 3, 4, 5, 6]);
print(port.writeBytesFromUint8List(uint8_data));

Get Port Connection Status

port.isOpened == false;

Close Serial Port

Close Without Listen

port.close();

Close On Listen

port.closeOnListen(
  onListen: () => print(port.isOpened),
)
  ..onError((err) {
    print(err);
  })
  ..onDone(() {
    print("is closed");
    print(port.isOpened);
  });

Small Example

import 'package:serial_port_win32/src/serial_port.dart';

void main() {
    var ports = SerialPort.getAvailablePorts();
    print(ports);
    if(ports.isNotEmpty){
      var port = SerialPort(ports[0]);
      port.BaudRate = CBR_115200;
      port.StopBits = ONESTOPBIT;
      port.close();
    }
}
Comments
  • reader.listen

    reader.listen

    hi bro 👋😅 can you implement a stream for read data and a method onErr or onDone 🙏 For example,🤔 when the port is disconnected from the system, the error method is executed🌹

    opened by hamidjalili59 35
  • Port.onClose method

    Port.onClose method

    Hi 👋☺️ I want the port to close when the USB is disconnected and the onClose method to run. Is it possible? 🌹

    Currently, when the USB is disconnected from the device, the library will no longer work until the software is restarted.

    opened by hamidjalili59 7
  • no data after closing and reopening connection

    no data after closing and reopening connection

    Hi, Connecting works the first time and I receive data after connection, after closing connection and trying to connect again, no data is received on the new conenction

    ElevatedButton(
        onPressed: () async {
          sp = SerialPort("COM9", openNow: true);
          sp.readBytesOnListen(8, (value) {
            print(value.toString());
          });
        },
        child: Text("connect")),
    ElevatedButton(
        onPressed: () async {
          sp.close();
        },
        child: Text("disconnect")),
    
    
    opened by ali80 4
  • Not able to re-open a closed port

    Not able to re-open a closed port

    I have the package working pretty solidly for reading out data from a serial port. However when I try to re-open a port after closing it I am not able to do so and the SerialPort() function does not throw any exceptions.

    I use this to connect to a serial port:

        try {
          port = SerialPort(dropdownvalue, openNow: true, ByteSize: 8);
        } on Exception catch (_) {
          print("can't open port, exiting...");
          return;
        }
    

    The first time it works like a charm. Then I disconnect the port by calling:

    opened_port.closeOnListen(
          onListen: () => print(opened_port.isOpened),
        )
          ..onError((err) {
            print(err);
          })
          ..onDone(() {
            print("${opened_port.portName} is closed");
            print(opened_port.isOpened);
          });
    

    The port is closed properly because I am able to open it with other software but when I try to connect to it again with SerialPort() it doesn't fail but the COM port is not opened. Not sure if this is a bug in the close function or that I am missing something. Help would be appriciated, thanks!

    opened by Ssercon 2
  • port.readBytesOnListen make UI hang/freeze a few millisecond when data come

    port.readBytesOnListen make UI hang/freeze a few millisecond when data come

    Using this code, _port.readBytesOnListen(255, (Uint8List value) { debugPrint(value.toString()); }); then, _port.writeBytesFromUint8List(uint8Data);

    UI freeze a few millisecond, is there something i missed?

    opened by indrawow 2
  • not working in android

    not working in android

    The following ArgumentError was thrown attaching to the render tree:
    Invalid argument(s): Failed to load dynamic library 'advapi32.dll': dlopen failed: library "advapi32.dll" not found
    
    When the exception was thrown, this was the stack: 
    #0      _open (dart:ffi-patch/ffi_dynamic_library_patch.dart:11:55)
    #1      new DynamicLibrary.open (dart:ffi-patch/ffi_dynamic_library_patch.dart:20:12)
    #2      _advapi32 (package:win32/src/advapi32.dart:20:34)
    #3      _advapi32 (package:win32/src/advapi32.dart)
    #4      _RegOpenKeyEx (package:win32/src/advapi32.dart:947:28)
    
    

    When running it on Android, we encounter a high error. What is the offer?

    opened by Mrrsh2000 2
  • onDone or OnErr

    onDone or OnErr

    Salute bro 🙋 Can you put an function to execute codes before disconnecting the port Like onDone() or onErr() 🙏 These two are very useful in the serial port Thanks 🥰

    opened by hamidjalili59 2
  • Port is now availabel when open and readBytesOnListen bug

    Port is now availabel when open and readBytesOnListen bug

    The following are the two problems I met when using:

    1. Open port number that is greater than COM9, the open function will return INVALID_HANDLE_VALUE and the error is "COMXX is not available". see this https://support.microsoft.com/en-us/topic/howto-specify-serial-ports-larger-than-com9-db9078a5-b7b6-bf00-240f-f749ebfd913e. so i change the _portNameUtf16 value from TEXT(portName) to TEXT("\\\\.\\$portName") and solve this problem.
    2. The value in readBytesOnListen callback will change randomly. This problem is cause because the value in readBytesOnListen callback is cast from a pointer "lpBuffer" that has been free, here is the code i modify:
    -uint8list = lpBuffer.cast<Uint8>().asTypedList(_bytesRead.value);
    +var u8l = lpBuffer.cast<Uint8>().asTypedList(_bytesRead.value); 
    +uint8list = Uint8List.fromList(u8l); //return the copy instead of the direct cast
    free(lpBuffer);
    

    I'm not sure if this is the correct solution, please point it out if I'm wrong, thanks again for sharing

    bug enhancement 
    opened by yong5354 1
  • Help getting serial data as stream in flutter from arduino

    Help getting serial data as stream in flutter from arduino

    Hi, I'm very new to serial communication and Streams for that matter. However, as a little project I'm trying to listen to a serial feed from an arduino. connected via USB.

    I've initially used your sample code and the data comes across fine.

    I have then mutilated said code into what is shown below. I'm using flutter riverpod for state management. When I look into the source code I can see you are already using streams but my knowledge is lacking on how to access this data.

    I don't get any errors but the app just hangs. Any help is much much appreciated.

    ` final arduinoProvider = StreamProvider((ref) async* { final arduinoData = await fetchArduinoData();

    yield arduinoData; });

    Future fetchArduinoData() async { final port = SerialPort("COM3", openNow: false, ByteSize: 8);

    port.openWithSettings(BaudRate: 9600); port.writeBytesFromString('A'); String incomingData = ''; String completeData = '';

    while (port.isOpened && completeData == '') { incomingData = ''; port.readOnListenFunction = (value) { if (utf8.decode(value) != '>' && utf8.decode(value) != '\n') { incomingData += utf8.decode(value); } if (utf8.decode(value) == '\n') { completeData = incomingData; } }; } return completeData; }`

    opened by CadMunkey 0
  • Read time too much when scanner scanned a barcode.

    Read time too much when scanner scanned a barcode.

    Thanks for great work. I have problem with scanning barcode. When I scan a barcode with scanner, readBytesOnListen fires after 1 to 2 seconds. What should I do? Thanks for solution.

    opened by Abduraimbek 4
  • Getting this error on hot restarting

    Getting this error on hot restarting

    Getting this error on hot restarting!!! Please help

    The following _Exception was thrown while handling a gesture:
    Exception: Last error is 0
    
    When the exception was thrown, this was the stack: 
    #0      SerialPort.open (package:serial_port_win32/src/serial_port.dart:169:11)
    #1      _MyHomePageState._getPortsAndOpen (package:demo/main.dart:43:14)
    #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:1005:21)
    #3      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
    #4      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:613:11)
    #5      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:298:5)
    #6      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:269:7)
    #7      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
    #8      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:449:20)
    #9      GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:425:22)
    #10     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:329:11)
    #11     GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:380:7)
    #12     GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:344:5)
    #13     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:302:7)
    #14     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:285:7)
    #18     _invoke1 (dart:ui/hooks.dart:170:10)
    #19     PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:331:7)
    #20     _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)
    (elided 3 frames from dart:async)
    Handler: "onTap"
    Recognizer: TapGestureRecognizer#774c2
      debugOwner: GestureDetector
      state: ready
      won arena
      finalPosition: Offset(1212.8, 640.8)
      finalLocalPosition: Offset(19.2, 30.4)
      button: 1
      sent tap down
    ====================================================================================================
    
    opened by Kapish26 1
  • Port opens but can't read data

    Port opens but can't read data

    I have confirmed that the connection between my laptop and my serial device is correct and working. But when using this package, I am able to get the port, open it but it never reads data. I have no idea why it is so. The baud rate and everything is just as it should be, and I am using the example project made by you. What could be the reason?

    bug 
    opened by Zopenzop 19
  • Question: Is there any way I can get serial number, manufacturer name, PID and VID information.

    Question: Is there any way I can get serial number, manufacturer name, PID and VID information.

    I am making an windows application which communicates with hardware connected over serial port ( via USB to Serial converter). I want to the application to connected to an com port automatically if it meets certain criteria (Serial number, Manufacturer ID etc.).

    enhancement 
    opened by nirmalaranawat 3
  • USB port question

    USB port question

    Hello my name is Alex. I am kinda new to flutter and I want to build an app that allows me to read and write on NFC tags. The problem is that the app must be Windows. I saw that you posted a flutter package for the serial port but I need USB in order to use the following product : https://www.amazon.it/Fydun-ACR122U-Lettore-contatto-software/dp/B07Y3C8XXZ/ref=sr_1_1_sspa?crid=39IV26IF4358A&keywords=nfc+reader&qid=1642976720&sprefix=nfc+%2Caps%2C90&sr=8-1-spons&psc=1&smid=A1A6WWKJ95BCLL&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzUUc4RkZFUVNNTFY3JmVuY3J5cHRlZElkPUEwMTY1NzE3Q0daTE5YNFJYNDZNJmVuY3J5cHRlZEFkSWQ9QTEwMDg4NDQxMkFPMzlGVEs5QjlWJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==

    By any chance, it is a possibility to adapt your serial for a USB version too or not ? Because I really need to use the product above.

    Thank you in advance.
    Have a nice day.

    question 
    opened by IvanoiuAlexandruPaul 1
Owner
Yichen Zhao
Yichen Zhao
Win32 registry - A package that provides a friendly Dart API for accessing the Windows registry

A package that provides a friendly Dart API for accessing the Windows registry.

Tim Sneath 20 Dec 23, 2022
Win32 runner - Run a Flutter app without needing a lick of C/C++ code. Just Dart

Experimental package for running Flutter apps from a Dart runner, instead of the

Tim Sneath 51 Sep 25, 2022
Bhagavad Gita app using flutter & Bhagavad-Gita-API is A lightweight Node.js based Bhagavad Gita API [An open source rest api on indian Vedic Scripture Shrimad Bhagavad Gita].

Gita Bhagavad Gita flutter app. Download App - Playstore Web Application About Bhagavad Gita app using flutter & Bhagavad-Gita-API is A lightweight No

Ravi Kovind 7 Apr 5, 2022
Beautiful Weather App using API with support for dark mode. Created by Jakub Sobański ( API ) and Martin Gogołowicz (UI, API help)

Flutter Weather App using API with darkmode support Flutter 2.8.1 Null Safety Beautiful Weather App using https://github.com/MonsieurZbanowanYY/Weathe

Jakub Sobański 5 Nov 29, 2022
Flutter book library - Book Library Application with Flutter and Google Book API

Book Library Application Flutter iOS, Android and Web with Google Book API Demo

Nur Ahmad H 0 Jan 25, 2022
This library provides the easiest and powerful Dart/Flutter library for Mastodon API 🎯

The Easiest and Powerful Dart/Flutter Library for Mastodon API ?? 1. Guide ?? 1.1. Features ?? 1.2. Getting Started ⚡ 1.2.1. Install Library 1.2.2. Im

Mastodon.dart 55 Jul 27, 2023
A most easily usable RESAS API wrapper in Dart. With this library, you can easily integrate your application with the RESAS API.

A most easily usable RESAS API wrapper library in Dart! 1. About 1.1. What Is RESAS? 1.2. Introduction 1.2.1. Install Library 1.2.2. Import It 1.2.3.

Kato Shinya 2 Apr 7, 2022
An Imgur API Client Library that uses Imgur's v3 API for Dart

imgur.dart An Imgur API Client Library that uses Imgur's v3 API for Dart. Usage

null 2 Dec 2, 2022
An extension to the bloc state management library which lets you create State Machine using a declarative API

An extension to the bloc state management library which lets you create State Machine using a declarative API

null 25 Nov 28, 2022
This is a mostly auto-generated library for using the mattermost api from Dart.

Mattermost API Client in Dart This is an implementation of a Mattermost API client in dart. It is not the only one, but it has significant advantages

null 1 Jun 15, 2022
In this video we will learn how to Create CRUD Rest API for our Flutter application using NODEJS API.

Flutter CRUD Using NodeJS API In this video we will learn how to Create CRUD Rest API for our Flutter application using NODEJS API. ?? Packages Used h

SnippetCoder 14 Dec 30, 2022
Netflix app UI clone using bloc,Rest API and TMDB for API key

netflix_flutter project_using_bloc packages Used flutter_bloc json_serializable get_it dio A few resources to get you started if this is your first Fl

Pranav Pv 16 Nov 25, 2022
Flutter-Animated-Library-of-Books - Flutter App - Animated Book Library

bookshelf A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if thi

Ulfhrafn 1 Dec 4, 2022
Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Roman Hornak 23 Feb 23, 2022
[Flutter Library] Flamingo is a firebase firestore model framework library. 🐤

Flamingo Flamingo is a firebase firestore model framework library. https://pub.dev/packages/flamingo 日本語ドキュメント Example code See the example directory

shohei 117 Sep 22, 2022
A middleware library for Dart's http library.

http_middleware A middleware library for Dart http library. Getting Started http_middleware is a module that lets you build middleware for Dart's http

TED Consulting 38 Oct 23, 2021
🎯 This library automatically generates object classes from JSON files that can be parsed by the freezed library.

The Most Powerful Way to Automatically Generate Model Objects from JSON Files ⚡ 1. Guide ?? 1.1. Features ?? 1.1.1. From 1.1.2. To 1.2. Getting Starte

KATO, Shinya / 加藤 真也 14 Nov 9, 2022
The lightweight and powerful wrapper library for Twitter Ads API written in Dart and Flutter 🐦

TODO: Put a short description of the package here that helps potential users know whether this package might be useful for them. Features TODO: List w

Twitter.dart 2 Aug 26, 2022
A most easily usable Duolingo API wrapper in Dart. Duolingo4D is an open-sourced Dart library.

A most easily usable Duolingo API wrapper in Dart! 1. About Duolingo4D Duolingo4D is an open-sourced Dart library. With Duolingo4D, you can easily int

Kato Shinya 18 Oct 17, 2022