Giter Site home page Giter Site logo

usbserial's Introduction

Pub Flutter

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.5.0

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

import 'package:usb_serial/usb_serial.dart'

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");

Upgrading from pre-0.3.0

In version 0.3.0 a resource bug was fixed (issue #35) which required signature changes.

Transformer Class changes

The Transformer classes previously inherited directly from StreamTransformer, this class however has no dispose method. So a new abstract class was added to include dispose and called by Transaction.dispose().

abstract class DisposableStreamTransformer<T, R> implements StreamTransformer<T, R> {
  void dispose();
}

Steps:

  • Change parent class to DisposableStreamTransformer
  • Implement dispose class, and make sure to dispose of your StreamController

Transaction Class changes

The Transaction class previously did not have access to the transformer, only the stream. The signature of Transaction constructor changed from

Transaction<T>(Stream<T>);

to

Transaction(Stream<Uint8List> stream, DisposableStreamTransformer<Uint8List, T> transformer);

If you are using the static factory methods you should not have to make any changes to your code. Only if you created your own Transformer/Transactions.

FAQ

Always ask permission to use USB port

#49 #38

Dependencies

This library depends on:

https://github.com/felHR85/UsbSerial

usbserial's People

Contributors

4ntoine avatar altera2015 avatar berdroid avatar chaseguru avatar codemelted avatar dippa-1 avatar dpkristensen avatar eparisot avatar eternali avatar foxushka avatar kgamecarter avatar luke265 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

usbserial's Issues

Build failure after Flutter 1.12 upgrade

I get the following error

FAILURE: Build failed with an exception.                                
                                                                        
* What went wrong:                                                      
Execution failed for task ':usb_serial:verifyReleaseResources'.         
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed                                    
     /Users/user/.gradle/caches/transforms-2/files-2.1/0a271e99b6771ad4a84318244d532fb7/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/fontVariationSettings not found.
                                                                        
     /Users/user/.gradle/caches/transforms-2/files-2.1/0a271e99b6771ad4a84318244d532fb7/core-1.0.0/res/values/values.xml:57:5-88:25: AAPT: error: resource android:attr/ttcIndex not found.

PlatformException(UsbSerialPortAdapter)

I'm getting E/flutter (29253): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(UsbSerialPortAdapter, Not an Serial device., null)

USB device:

    +-o ACR1252 Dual Reader@14200000  <class AppleUSBDevice, id 0x100016c10, registered, matched, active, busy 0 (6 ms), retain 19>

Null-terminated strings

Hi there,

What is the proper way to use this with null-terminated strings?

Transaction.stringTerminated(
_port.inputStream, Uint8List.fromList([0]));

Appears to work, but of course it also splits some of the data if it happens to be 0x00.

How to display the value?

I'm using the example main.dart. How do I make it only show once and kept changing? Something like a meter for temperature.

Screenshot_20200629-042304

Screenshot_20200629-043245
15933765280476888268031943688254

Always ask permission to use USB port

Every time I open the program it asks me for authorization to use the USB port every time.

Is it possible to remove the dialog once permissions have been granted?
Or somehow add the permissions so that the dialog doesn't open?

Usb Accessory

Is there a way to use this plugin to have the Android device go in accessory mode instead of usb host?

[Question] Needs some help receiving serial message without the package breaking a single message into multiple messages.

Hi,
First of, thank you very much for this package. I have used it on multiple projects now and it has worked super well :D

I am trying to receive and parse MAVLink message. This is the message format https://mavlink.io/en/guide/serialization.html

I know we can do something like this to set terminator bytes
Transaction.terminated(port.inputStream, Uint8List.fromList([48, 49]));
but MAVLink doesn't seem to have any terminator bytes.

Do you have any suggestions on how I can get the package to stop breaking a single message into multiple messages?

Add support for parity even

In usb_serial version 0.1.1 there seems to be no constant for setting the parity of a UsbPort object to 'even'.

I explored the underlying java library and noticed that this option is supported there. (link) I tried using '2' as a constant for setting the parity in UsbPort.setPortParameters() with no success. EDIT: Passing 2 in UsbPort.setParameters(...) worked for me.

Will the option to set the parity to 'even' be available in the near future or is there any workaround for that?

Need to get USB status

Hi,

I'm trying to create a stream for listening to the USB status (permission allowed/denied, OTG available or not, etc.). Is there any functionality built into this library to check for the same?

here is the sample pseudo code:

class USBStatusMonitor implements ReactiveState<USBStatus> {
  const USBStatusMonitor(this._usb);

  final UsbSerial _usb;

  @override
  Stream<USBStatus> get state => _usb.statusStream;
}

Is this functionality like statusStream or USBStatus available in this library for easy detection of sudden changes from the user (user suddenly disables OTG, OTG is not available on this device etc.)?

Data still present in stream after transaction done and disposed

Hi, I faced a very anoying issue I can't figure out :

my code goes goes like :

// we are in a statefull widget

bool listening;

@override
void initState() {
    super.initState();
    listening= false;
}

Transaction<Uint8List> transaction_0;

Future<void> startStop() async {
  if (listening) {
  
      // stop listening
      transaction_0.dispose();
      
      // send the stop command to usb device (no answer to wait)
      Transaction<String> transaction_1 = Transaction.stringTerminated(
            usbPort.inputStream, Uint8List.fromList([13, 10]));
       await transaction_1.transaction(
            usbPort,
            Uint8List.fromList(("stop").codeUnits + [13, 10]),
            Duration(seconds: 1));
        // end this transaction_1
        transaction_1.dispose();
        
        listening= false;
      
  } else {
  
      // send some config commands to usb device witch will answer with confirmation
      Transaction<String> transaction_1 = Transaction.stringTerminated(
            usbPort.inputStream, Uint8List.fromList([13, 10])); // note the ending condition
       String response = transaction_1.transaction(
            usbPort,
            Uint8List.fromList(("config bla bla").codeUnits + [13, 10]),
            Duration(seconds: 1));
        // little check here, always returns the good value
        print(response);
        // end this transaction_1
        transaction_1.dispose();
        
        -------------> HERE I need to completely clear the data
  
      // start listening from  the device (terminated needed here because of the "<END>" termination)
      transaction_0= Transaction.terminated(
              usbPort.inputStream, Uint8List.fromList("<END>".codeUnits)); // this ending condition
      transaction_0.stream.listen((Uint8List data) {
            // do stuff like writing the data from usb to a file... HERE the problem append to be visible with previous data leaked to the file
      });
      
      // send the start command to usb device (no answer, just run...)
      await usbPort.write(Uint8List.fromList(("start").codeUnits + [13, 10]));
      
      listening= true;
  }
}

It all works great, ... on the first run... but if I stop the listening (from a button -> onTap: StartStop) and then restarts a new one, data leaks from the config response of transaction_1 to the transaction_0 and finish in my file where I write the return of transaction_0 ... but only after a first, clean run...

I tried flushing, disposing stream... nothing seems to prevent the data from being still disponible to transaction_0, after, transaction_1 already handled it...
My guess is that the transaction_0 stream is never ended at all and just listen to every data disponible on the port...

How to dispatch, successively, data from a transaction (temporary) to another one (witch is more persistent) ?

EDIT: as a workaroud, I close the port and re-execute the connexion routine but this feels wrong...

Another systems support.

Will you in the future make this plugin on another systems ? i solve this problem using processing ide . I communicate using udp and local host. Processing ide receive this udp and send Serial data. ?

java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread.

I tried to use your example but it is giving a exception:

E/AndroidRuntime(30424): FATAL EXCEPTION: Thread-5 E/AndroidRuntime(30424): Process: dev.bessems.usbserialexample, PID: 30424 E/AndroidRuntime(30424): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: Thread-5 E/AndroidRuntime(30424): at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:794) E/AndroidRuntime(30424): at io.flutter.embedding.engine.FlutterJNI.dispatchPlatformMessage(FlutterJNI.java:684) E/AndroidRuntime(30424): at io.flutter.embedding.engine.dart.DartMessenger.send(DartMessenger.java:80) E/AndroidRuntime(30424): at io.flutter.embedding.engine.dart.DartExecutor.send(DartExecutor.java:174) E/AndroidRuntime(30424): at io.flutter.view.FlutterNativeView.send(FlutterNativeView.java:144) E/AndroidRuntime(30424): at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler$EventSinkImplementation.success(EventChannel.java:226) E/AndroidRuntime(30424): at dev.bessems.usbserial.UsbSerialPortAdapter$1.onReceivedData(UsbSerialPortAdapter.java:60) E/AndroidRuntime(30424): at com.felhr.usbserial.UsbSerialDevice$WorkerThread.onReceivedData(UsbSerialDevice.java:361) E/AndroidRuntime(30424): at com.felhr.usbserial.UsbSerialDevice$WorkerThread.doRun(UsbSerialDevice.java:336) E/AndroidRuntime(30424): at com.felhr.usbserial.AbstractWorkerThread.run(AbstractWorkerThread.java:21)

When I remove this part of the code, the error disappears
_subscription = _transaction.stream.listen((String line) { setState(() { _serialData.add(Text(line)); if (_serialData.length > 20) { _serialData.removeAt(0); } }); });
But i need to receive data from UART.

Flutter Doctor:
Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, v1.7.8+hotfix.3, on Microsoft Windows [versão 10.0.17134.829], locale pt-BR) [√] Android toolchain - develop for Android devices (Android SDK version 28.0.3) [!] Android Studio (version 3.4) X Flutter plugin not installed; this adds Flutter specific functionality. X Dart plugin not installed; this adds Dart specific functionality. [√] VS Code (version 1.36.0) [√] Connected device (2 available)

Any ideia what is might be?

Add support for synchronous write/read sequence

In version 0.1.1 usb_serial supports asynchronous communications, but not synchronous ones.

In my case I need kind of a handshake-type synchronous communication: whenever something is written to the attached USB device I need to know the response from the device for that specific command.

The feature request is the following:
When sending a String in synchronous manner...

  1. empty the input buffer if there is still some content
  2. write the given String to the device
  3. wait until the return message is available in the input buffer (e.g. when a configureable "STOP" sequence is fetched like "\r\n") or the maximum amount of milliseconds (configureable) has elapsed
  4. return the fetched message as byte array or NULL if the device did not response in time

The point is: I have to wait for the response prior to sending the next command.

So I would like so see interfaces in the UsbPort class like:

byte[] writeWithRead(String message, [byte[] stopSequence, int maximumWaitTime]);

byte[] writeWithRead(String message, [byte[] stopSequence]);

byte[] writeWithRead(String message, [int maximumWaitTime]);

void setDefaultStopSequence(byte[] defaultStopSequence);

void setDefaultMaximumWaitTime(int maximumWaitTime);

defaultStopSequence and maximumWaitTime should have reasonable defaults (e.g. "\n" and 100).

In my case I need different maximumWaitTimes for different calls to de attached device, thus I need the option to specify it in the writeWithRead call when sending commands which are taking more time on the attached device (e.g. "RESET" needs much more time then "GET_STATUS").

A mixture of sync/async USB communications should be suppored as well:
Code using this library should be able to:

  • stop the InputBuffer listener prior to synchronous port.writeWithRead(..) calls
  • start the InputBuffer listener prior to asynchronous port.write(...) calls

In fact what I need to do is:

  • setup the attached USB device using multiple commands beeing sent synchronous (I need to know the USB device response for each call prior to sending the next command)
  • sending asynchronous "GET_STATUS" commands in a timed manner (the responses are processed asynchronous)
  • shutdown / reset the attached USB device using synchronous commands (again I need to know the device responses for each call individually)

App forced to close

Running on Android 6.0.1 my app was closed by the system.

Android LogCat showed an null-reference exception at UsbSerialPortAdapter.java:67:

02-11 16:46:10.849 5944-5944/com.bytecmed.custom_slider D/AndroidRuntime: Shutting down VM
02-11 16:46:10.851 5944-5944/com.bytecmed.custom_slider E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.bytecmed.custom_slider, PID: 5944
    java.lang.NullPointerException: **Attempt to invoke interface method 'void io.flutter.plugin.common.EventChannel$EventSink.success(java.lang.Object)' on a null object reference**
        at dev.bessems.usbserial.UsbSerialPortAdapter$1$1.run(UsbSerialPortAdapter.java:67)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-11 16:47:15.405 5944-5944/com.bytecmed.custom_slider I/Process: Sending signal. PID: 5944 SIG: 9

Not working with SmartCard Reader

Flutter (Channel stable, 2.5.3, on Mac OS X 10.15.4 19E287 darwin-x64, locale en-TH)

Build on Android OS connect with SmartCard Reader

SmartCard Information:

I/flutter (19180): [UsbDevice: 58f-9540 EMV Smartcard Reader, Generic null]
I/flutter (19180): Device Id : 2002
I/flutter (19180): Hash Code : 449461508
I/flutter (19180): Product Name : EMV Smartcard Reader
I/flutter (19180): Vendor Id : 1423
I/flutter (19180): Product Id : 38208
I/flutter (19180): Port : null
I/flutter (19180): Serial No : null

source code in line:
_port = await device.create();

found error message:

I/flutter (19180): [UsbDevice: 58f-9540 EMV Smartcard Reader, Generic null]
I/usbhost (19180): usb_device_new /dev/bus/usb/002/002 fd: 119
I/usbhost (19180): usb_device_new read returned 111 errno 11
E/flutter (19180): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(UsbSerialPortAdapter, Not an Serial device., null, null)
E/flutter (19180): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (19180): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (19180):
E/flutter (19180): #2 UsbSerial.createFromDeviceId (package:usb_serial/usb_serial.dart:431:33)
E/flutter (19180):
E/flutter (19180): #3 UsbDevice.create (package:usb_serial/usb_serial.dart:327:13)
E/flutter (19180):
E/flutter (19180): #4 _MyAppState._getPorts.. (package:flutterapp/main.dart:146:29)
E/flutter (19180):
E/flutter (19180):

The library does not support ABACUS ELECTRICS Optical Probe

Hello guys!

I am learning about USB serial in Flutter language and see that your library is supporting this issue

But I import the library and run the example code, I get an error like this

When running to the section: "_port = await device.create ();" then it reports an error
"[ERROR: flutter / lib / ui / ui_dart_state.cc (148)] Unhandled Exception: PlatformException (UsbSerialPortAdapter, Not an Serial device., Null)"

Link driver: http://www.abacuselectrics.com/usbsoft.htm

Can you support me?

p / s: please I am not fluent in English so thanks to google translation, I hope you guys will apologize

THANK YOU!

Android 10 SecurityException

Google Pixel 2 XL. Android 10
When
List<UsbDevice> devices = await UsbSerial.listDevices();

E/MethodChannel#usb_serial(25991): Failed to handle method call E/MethodChannel#usb_serial(25991): java.lang.SecurityException: User has not given 10197/tw.kgame.chameleonminiapp permission to access device /dev/bus/usb/001/002 E/MethodChannel#usb_serial(25991): at android.os.Parcel.createException(Parcel.java:2071) E/MethodChannel#usb_serial(25991): at android.os.Parcel.readException(Parcel.java:2039) E/MethodChannel#usb_serial(25991): at android.os.Parcel.readException(Parcel.java:1987) E/MethodChannel#usb_serial(25991): at android.hardware.usb.IUsbSerialReader$Stub$Proxy.getSerial(IUsbSerialReader.java:123) E/MethodChannel#usb_serial(25991): at android.hardware.usb.UsbDevice.getSerialNumber(UsbDevice.java:143) E/MethodChannel#usb_serial(25991): at dev.bessems.usbserial.UsbSerialPlugin.serializeDevice(UsbSerialPlugin.java:205) E/MethodChannel#usb_serial(25991): at dev.bessems.usbserial.UsbSerialPlugin.listDevices(UsbSerialPlugin.java:220) E/MethodChannel#usb_serial(25991): at dev.bessems.usbserial.UsbSerialPlugin.onMethodCall(UsbSerialPlugin.java:258)E/MethodChannel#usb_serial(25991): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:222) E/MethodChannel#usb_serial(25991): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:96) E/MethodChannel#usb_serial(25991): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:656) E/MethodChannel#usb_serial(25991): at android.os.MessageQueue.nativePollOnce(Native Method) E/MethodChannel#usb_serial(25991): at android.os.MessageQueue.next(MessageQueue.java:336) E/MethodChannel#usb_serial(25991): at android.os.Looper.loop(Looper.java:174) E/MethodChannel#usb_serial(25991): at android.app.ActivityThread.main(ActivityThread.java:7356) E/MethodChannel#usb_serial(25991): at java.lang.reflect.Method.invoke(Native Method) E/MethodChannel#usb_serial(25991): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) E/MethodChannel#usb_serial(25991): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) E/MethodChannel#usb_serial(25991): Caused by: android.os.RemoteException: Remote stack trace: E/MethodChannel#usb_serial(25991): at com.android.server.usb.UsbUserSettingsManager.checkPermission(UsbUserSettingsManager.java:177) E/MethodChannel#usb_serial(25991): at com.android.server.usb.UsbSerialReader.getSerial(UsbSerialReader.java:96) E/MethodChannel#usb_serial(25991): at android.hardware.usb.IUsbSerialReader$Stub.onTransact(IUsbSerialReader.java:84) E/MethodChannel#usb_serial(25991): at android.os.Binder.execTransactInternal(Binder.java:1021) E/MethodChannel#usb_serial(25991): at android.os.Binder.execTransact(Binder.java:994)

Send value as string format.

I need to send value to Ingenico iUC 180B device.

I need to send value as this format. This code from my C# program.

writedata = "\x02" + "C20000000000000100s" + "\x03";
_serialPort.Write(writedata);

Please help

Not an Serial device

I connect a print device and run the example code then get the error, how can I fix it. thank!

Not detecting CH340. But it works perfectly with FTDI

Hello,

Not detecting CH340. But it works perfectly with FTDI. The felHR85/usbSerial dependency tells you it should work. Other apps like Google Play/Serial USB Terminal work with both cards.
Any suggestion?

Att

Raphael

How can i perform a write soon as i read some string from my device?

I have a microcontroller that sends a string 'Device Boot' on restart. I am using a regex to parse it, but soon as it does find it, i wish to perform a write - to send a $ signal which makes the microcontroller send logs.

I am using USB_SERIAL for Flutter.

This is the current setup:

Future<bool> _connectTo(device) async {

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

    _port = await device.create();

    if (!await _port!.open()) {
      setState(() {
        _status = "FAILED";
      });
      return false;
    }

    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) {
      //Set in progress flag for first time read.
      if (line.contains('Device Boot')) {
        setState(() {
          Wakelock.enable();
        });

        //Set timer for timeout
        _timer = Timer(const Duration(seconds: 300), () {
          Wakelock.disable();
          _saveData(); // to save logs
        });
      }
    return true;
  }

And i wish to perform a write soon as it finds the first line Device Boot.

The USB_SERIAL's document suggests to use

await port.write(Uint8List.fromList('\$'.codeunits));

So i used the above code right after it found the boot line, like below

.....
    _subscription = _transaction!.stream.listen((String line) {
      //Set in progress flag for first time read.
      if (line.contains('Device Boot')) {

        // writing to device
        await _port.write(Uint8List.fromList('\$'.codeunits));

        setState(() {
          Wakelock.enable();
        });

.....

But this doesn't work for me, so i am really confused if this is where i should be performing the write, this is first time i am working with usb package. Any help is appreciated.

Communicate with FTDI 232HL at 4Mbaud

I have been communicating with FTDI 232HL using the package usb_serial.
Our flutter based app requires speed of 4Mbaud+.
Till 3Mbaud there are no issues but at any speeds higher than this there is no Communication with the application. I have tested the FTDI's communication on windows com port up to speed of 5Mbaud.
I had sent an email to FTDI support regarding communication at higher speeds. They had pointed out that there have been some changes in the JAVA file in relation to setting the baud rate for high speed devices.
How can I achieve 4Mbaud in the flutter application using usb_serial?

Communication with always streaming device

Hello,

Thank you for the great package. I am having issues obtaining a data stream.

I am attempting to communicate with a device that is always streaming 01 and 60 once the serial connection is established. The screen shot below is of the raw data view of a usb sniffer. The data needed is only returned once A\r is sent to the device [41 0d].

I am wondering what method of this package would be best to pull the desired data out of the following stream?

Captureas

I have tried several methods of obtaining a stream and keep receiving null or Instance of '_ControllerStream'. I am not sure if it is a matter of converting the data to something that the device can receive and read or if the data returned is not readable or nothing is being sent back at all.

Many thanks to anyone with suggestions

the listDevices always null

I simulation usb COM1(android) and usb COM2,but the listDevices always null,when I click send,
error:

E/flutter ( 2498): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception: E/flutter ( 2498): NoSuchMethodError: The method 'write' was called on null. E/flutter ( 2498): Receiver: null E/flutter ( 2498): Tried calling: write(Uint8Array) E/flutter ( 2498): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5) E/flutter ( 2498): #1 _MyAppState.build.<anonymous closure> package:usb/main.dart:71 E/flutter ( 2498): <asynchronous suspension> E/flutter ( 2498): #2 _InkResponseState._handleTap package:flutter/…/material/ink_well.dart:507

ch340 no detected!

Hello, I'm trying to conduct communication with the CH340 driver who owns the Nodemcu or the Arduino Nano but it does not go: c I tested with ESP32 and with this if it detects me without problems.

Android 12 "Failed to acquire USB device."

Trying to connect to a device fails throws a platform exception with the message "Failed to acquire USB device.".

Only occurs on Android 12.

This looks to suggest something went wrong between in android/src/main/java/dev/bessems/usbserial/UsbSerialPlugin.java lines 145-166.

final devices = await UsbSerial.listDevices();
if (devices.isNotEmpty) {
    devices.first.create();
}

receive error with ftdi chip like FT232H

the lusb communication is working well with CP210x device, but with ftdi chip like FT232H we receive 2 bytes less than sended and also this exception

E/AndroidRuntime( 8729): java.lang.ArrayIndexOutOfBoundsException: src.length=193 srcPos=130 dst.length=185 dstPos=124 length=62
E/AndroidRuntime( 8729): at java.lang.System.arraycopy(Native Method)
E/AndroidRuntime( 8729): at com.felhr.usbserial.FTDISerialDevice.copyData(FTDISerialDevice.java:527)
E/AndroidRuntime( 8729): at com.felhr.usbserial.FTDISerialDevice.adaptArray(FTDISerialDevice.java:508)
E/AndroidRuntime( 8729): at com.felhr.usbserial.UsbSerialDevice$WorkerThread.doRun(UsbSerialDevice.java:329)
E/AndroidRuntime( 8729): at com.felhr.usbserial.AbstractWorkerThread.run(AbstractWorkerThread.java:21)

Any plans to update the library to android embedding v2?

Getting warning: [deprecation] Registrar in PluginRegistry has been deprecated with a clean build. Looking in the code, the reason seems to be that the library is using Android embedding v1.

Any plans to update the library to Android embedding v2 any time soon?

Thanks

Is there any way to read and write data in utf-8 format?

I'm developing a project for IoT for home sensors. I want to retrieve data stored from the devices (Atmega running on arduino bootloader). But all the data is in string format and the device also accepts strings in the serial console. Is it possible to read and write strings using this library? Or would I have to encode and decode the messages on both ends?

Thermal Printer

Hi,

We are connecting to a thermal printer, however for some reason the port just won't open, do you have any advice?

Convertion of results

I am not sure it is the right place to ask for such a question but I am struggling to for 2 days to manage to read the results coming from a usb device.

I manage to get the connection and I get the inputStream but I cannot find a way to get the data.

If i convert the stream to string I get :
[255,0,0,0,255....]

If I try to use:

newTag = new String.fromCharCodes(asyncSnapshot.data);

I get a string but with not the correct results something like YYYYYY, my string should be a number (12528548654213).

If i try to use :

newTag = ascii.decode(asyncSnapshot.data).trim();

I get an error

format exception invalid format exception : 255

Web Serial support

I've been looking at ways to encompass my current android only flutter app into a web app since web supports usb now. If I were to create a PR here, what are the guidelines and is it needed or is my use case isolated?

App Crashes - port.open()

Good Day,

When calling port.open(type, iface), at times it causes an entire app crash.

We have noticed it is when you pass the incorrect iface or type, when we looked a little deeper we noticed you are only catching the security exception.

Is it possible to add some further error handling to avoid the complete app crash?

Update version on pub.dev

The current package version on pub.dev is on 0.1.1.

Could you update this to the current version, so the package can be used with flutter?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.