Git Product home page Git Product logo

usbserialforandroid's Introduction

UsbSerialForAndroid

This is a driver library to allow your Xamarin Android app to communicate with many common USB serial hardware. It uses the Android USB Host API available on Android 3.1+.

No root access, ADK, or special kernel drivers are required; all drivers are implemented in c#. You get a raw serial port with Read(), Write(), and other basic functions for use with your own protocols. The appropriate driver is picked based on the device's Vendor ID and Product ID.

This is a Xamarin C# port of Mike Wakerly's Java usb-serial-for-android library. It followed that library very closely when it was ported. The main changes were to make the method names follow C# standard naming conventions. Some Java specific data types were replaced with .NET types and the reflection code is .NET specific. Code examples written for the Java version of the library should translate more or less faithfully to C#.

It also includes code derived from a portion of LusoVU's XamarinUsbSerial library. XamarinUsbSerial was a C# wrapper for the Java usb-serial-for-android. It used an older version of the usb-serial-for-android .jar file. Only the the C# code was used, the Java library is not referenced.

The default branch has been renamed from master to main. if you have a local clone, you can run the following commands to update the name of the default branch

git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a

This library currently supports Xamarin.Android and .NET 6 (and .NET 7). The demo app currently targets .NET 7, but the code was written for Xamarin.Android.

Structure

This solution contains two projects.

  • UsbSerialForAndroid - A port of the Java library usb-serial-for-android
  • UsbSerialExampleApp - A Xamarin version of the example app that comes with usb-serial-for-android

Getting Started

1. Reference the library to your project

2. Copy the device_filter.axml from the example app to your Resources/xml folder. Make sure that the Build Action is set to AndroidResource

3. Add the following attribute to the main activity to enable the USB Host

[assembly: UsesFeature("android.hardware.usb.host")]

4. Add the following IntentFilter to the main activity to receive USB device attached notifications

[IntentFilter(new[] { UsbManager.ActionUsbDeviceAttached })]

5. Add the MetaData attribute to associate the device_filter with the USB attached event to only see the devices that we are looking for

[MetaData(UsbManager.ActionUsbDeviceAttached, Resource = "@xml/device_filter")]

6. Refer to MainActivity.cs in the example app to see how connect to a serial device and read data from it.

Working with unrecognized devices

The UsbSerialForAndroid has been compiled with the Vendor ID/Product ID pairs for many common serial devices. If you have a device that is not defined by the library, but will work with one of the drivers, you can manually add the VID/PID pair. If you have a device that is not in the GetSupportedDevices() method for that driver, you can submit a pull request that adds the vendor and product IDs to that driver.

UsbSerialProber is a class to help you find and instantiate compatible UsbSerialDrivers from the tree of connected UsbDevices. Normally, you will use the default prober returned by UsbSerialProber.getDefaultProber(), which uses the built-in list of well-known VIDs and PIDs that are supported by our drivers.

To use your own set of rules, create and use a custom prober:

// Probe for our custom CDC devices, which use VID 0x1234
// and PIDS 0x0001 and 0x0002.
var table = UsbSerialProber.DefaultProbeTable;
table.AddProduct(0x1b4f, 0x0008, typeof(CdcAcmSerialDriver)); // IOIO OTG

table.AddProduct(0x09D8, 0x0420, typeof(CdcAcmSerialDriver)); // Elatec TWN4

var prober = new UsbSerialProber(table);
List<UsbSerialDriver> drivers = prober.FindAllDrivers(usbManager);
// ...

Of course, nothing requires you to use UsbSerialProber at all: you can instantiate driver classes directly if you know what you're doing; just supply a compatible UsbDevice.

Compatible Devices

Additional information

This is a port of the usb-serial-for-android library and code examples written for it can be adapted to C# without much effort.

For common problems, see the Troubleshooting wiki page for usb-serial-for-android library. For other help and discussion, please join the usb-serial-for-android Google Group, usb-serial-for-android. These two resources are for the Android Java version, but this library is port of that code base.

Pull Requests are welcome, but please include what hardware was used for testing. We do not have the hardware or the bandwidth to test the various chipsets supported by the library.

We will do our best to repond to reported issues. If you have a code fix or suggestion, we are only looking at changes submitted as pull requests.

For more information about contributing or reporting an issue, please see for more information for what we are looking for and how to get started.

Author, License, and Copyright

This library is licensed under the MIT License. Please see LICENSE.txt for the complete license.

Copyright 2017, Tyler Technologies. All Rights Reserved. Portions of this library are based on the usb-serial-for-android and XamarinUsbSerial libraries. Their rights remain intact.

usbserialforandroid's People

Contributors

alexmedia avatar andrewhaighcell avatar anotherlab avatar diebblue avatar ihornehrutsa avatar nicsure avatar nwestfall avatar pravincar avatar thierrydfr avatar tiorac avatar widavies avatar wim-dekker avatar ygoe 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

usbserialforandroid's Issues

ControlTransfer with value 8 failed -1

System.IO.IOException: ControlTransfer with value 8 failed: -1
at Hoho.Android.UsbSerial.Driver.ProlificSerialDriver.ProlificSerialPort.OutControlTransfer(Int32 requestType, Int32 request, Int32 value, Int32 index, Byte[] data) in D:\log\UsbSerialForAndroid-main\UsbSerialForAndroid\driver\ProlificSerialDriver.cs:line 171
at Hoho.Android.UsbSerial.Driver.ProlificSerialDriver.ProlificSerialPort.VendorOut(Int32 value, Int32 index, Byte[] data) in D:\log\UsbSerialForAndroid-main\UsbSerialForAndroid\driver\ProlificSerialDriver.cs:line 184
at Hoho.Android.UsbSerial.Driver.ProlificSerialDriver.ProlificSerialPort.PurgeHwBuffers(Boolean purgeReadBuffers, Boolean purgeWriteBuffers) in D:\log\UsbSerialForAndroid-main\UsbSerialForAndroid\driver\ProlificSerialDriver.cs:line 653
at Hoho.Android.UsbSerial.Driver.ProlificSerialDriver.ProlificSerialPort.ResetDevice() in D:\log\UsbSerialForAndroid-main\UsbSerialForAndroid\driver\ProlificSerialDriver.cs:line 189
at Hoho.Android.UsbSerial.Driver.ProlificSerialDriver.ProlificSerialPort.Open(UsbDeviceConnection connection) in D:\log\UsbSerialForAndroid-main\UsbSerialForAndroid\driver\ProlificSerialDriver.cs:line 394
at Hoho.Android.UsbSerial.Extensions.SerialInputOutputManager.Open(UsbManager usbManager, Int32 bufferSize) in D:\log\UsbSerialForAndroid-main\UsbSerialForAndroid\Extensions\SerialInputOutputManager.cs:line 72

CdcAcmSerialDriver cannot be instantiated from ProbeDevice due to no matching constructor signature

Hi,
Whilst trying out the driver with an Arduino device, I found that it cannot correctly create a suitable driver instance of the CdcAcmSerialDriver class.

This is because there is no suitable matching function prototype to be called from the ProbeDevice():
https://github.com/anotherlab/UsbSerialForAndroid/blob/main/UsbSerialForAndroid/driver/UsbSerialProber.cs#L94
...
driver = (IUsbSerialDriver)Activator.CreateInstance(driverClass, new System.Object[] {usbDevice});
...

Does not match the constructor signature in:
https://github.com/anotherlab/UsbSerialForAndroid/blob/main/UsbSerialForAndroid/driver/CdcAcmSerialDriver.cs#L34

public CdcAcmSerialDriver(UsbDevice device, bool? enableAsyncReads = null)
{

My workaround for now was to add a constructor with a single argument and just default enableAsyncReads=false; Obviously this could do with something more sophisticated for a proper fix...

public CdcAcmSerialDriver(UsbDevice device)
{
...

I believe the original Java code does not have the same problem, because it only accepts a single UsbDevice argument for the ctor:
https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialProber.java#L82
https://github.com/mik3y/usb-serial-for-android/blob/master/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java#L38

Build error: Java.Interop version conflicts

First, I've downloaded the entire repository and built it with VS 2022 17.2.0 Preview 2.1. It did build and I could deploy the sample app on my Android phone and receive data from a microcontroller.

So the next step was to just use the library and add it to a new app. I started with a .NET MAUI app (which also worked as is) and tried to integrate the device listing and simple communication code into the default page that's created there. I added the library project from your solution to my solution and also added a project reference to it.

But now my build fails with some version conflicts of Java.Interop. It sees versions 0.1.0.0 and 0.2.0.2. I have no idea what these are. Can you please explain how this library should be used? There's no NuGet package so I have to find my own ways.

USBManager USB list permission works till next device restart

Hello everyone, I have a problem regarding the device's permissions to access the list of connected USBs.
Once authorization is given, it works correctly every time the list is requested but after restarting the device, it requests authorization.
Has anyone solved this using third-party systems?
Thank you

CP21xx driver, does not work on it's own when there are multiple interfaces/ports

So far it worked fine and there were no issues with FTDI. Now, I’m trying to work with a device which uses CP21xx driver which has two ports - “standard” and “enhanced”, my messages work on “standard” and I have changed the part of code in Android/drivers/CP21xx…cs to set the interface to the one with “Standard”, but my messages don’t get a response from the device.

Now, if I use a 3rd party app “Serial usb terminal” https://play.google.com/store/apps/details?id=de.kai_morich.serial_usb_terminal&hl=en_CA&gl=US

, whose source code I don’t have,and thensend my messages, get the reply from the device, and then use the UsbSerialForAndroid example app again, I now get responses to all my messages.

I tried setting it to always the "standard" interface by checking the name but that still doesn't work unless I use the third party app. I have also tried using a usb to ttl to see what the third party app sends as a message and what my app sends and they are identical.

Note that the code or configuration doesn’t change for the UsbSerialForAndroid. Also, once working, even if I close the app or send messages after a very long time , I still get replies, till the time I don’t remove the physical usb connection.

If I unplug and reply the usb or power cycle the device that uses the CP21x driver, then I again have to use the third party app first to get the UsbSerialForAndroid sample app working again. I don’t know why it needs that third party app to connect and send the messages first although I don’t change anything in the UsbSerialForAndroid app between those two scenarios.

this is the open function for the cp21xx driver, I edited it to not use enhanced port

public override void Open(UsbDeviceConnection connection)
{
if (mConnection != null)
{
throw new IOException("Already opened.");
}

mConnection = connection;
Boolean opened = false;
try
{
    for (int i = 0; i < mDevice.InterfaceCount; i++)
    {
        UsbInterface usbIface = mDevice.GetInterface(i);
        if (mConnection.ClaimInterface(usbIface, true))
        {
            Log.Debug(TAG, $"claimInterface {i} SUCCESS");
        }
        else
        {
            Log.Debug(TAG, $"claimInterface {i} FAIL");
        }
    }

    UsbInterface dataIface = mDevice.GetInterface(mDevice.InterfaceCount - 1);
    if (dataIface.Name.Contains("Enhanced"))
    {
        dataIface = mDevice.GetInterface(mDevice.InterfaceCount - 2); ;
    }
    for (int i = 0; i < dataIface.EndpointCount; i++)
    {
        UsbEndpoint ep = dataIface.GetEndpoint(i);
        if (ep.Type == (UsbAddressing)UsbSupport.UsbEndpointXferBulk)
        {
            if (ep.Direction == (UsbAddressing)UsbSupport.UsbDirIn)
            {
                mReadEndpoint = ep;
            }
            else
            {
                mWriteEndpoint = ep;
            }
        }
    }

    SetConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
    SetConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
    SetConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
    //            setParameters(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY);
    opened = true;
}
finally
{
    if (!opened)
    {
        try
        {
            Close();
        }
        catch (IOException e)
        {
            // Ignore IOExceptions during close()
        }
    }
}

}

I don't know if there's anywhere else to set it to one of two interfaces in the UsbSerialForAndroid "UsbSerialForAndroid" app.

Has anyone ever worked with CP21xx drivers that have multiple ports/ interfaces with Android and usb serial ? Or anything similar that has two ports/ interfaces ?

looking for how to work with xamarin android usb serial to work with a port driver having two interfaces/ ports

Read timeout is not appling

I am using FtdiSerial device on android 5.

When I am trying to read data, timeout is not applied.
My code works fine only if I will put thread. sleep (1000) before reading.

            DateTime now = DateTime.Now;
            int cnt = m_Port.Read(data, 5000);
            TimeSpan s = DateTime.Now - now;

as result
s < 10 ms.
cnt = 0

Error writing/reading data

I am trying to run the example code on in UsbSerialForAndroid and if I try to read or write anything the app crashes
It does detect the device which is using CdcAcmSerialDriver (STM32 Nucleo)
Initially on connect it will give a false result which is always 64 bytes in length and has false values

Read 64 bytes:
0x00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

However when I try to write to it I am greeted by this error message:

Java.IO.IOException: Exception of type 'Java.IO.IOException' was thrown. at Hoho.Android.UsbSerial.Driver.CdcAcmSerialDriver+CdcAcmSerialPort.Write (System.Byte[] src, System.Int32 timeoutMillis) [0x000d3] in <76b96e7b0d204cfe93490d0d3b6dfa0a>:0 at UsbSerialExampleApp.SerialConsoleActivity.WriteData (System.Byte[] data) [0x0002e] in <ed01142b0128460fae48f975e230055f>:0 --- End of managed Java.IO.IOException stack trace --- java.io.IOException: Error writing 46 bytes at offset 0 length=46 at mono.android.view.View_OnClickListenerImplementor.n_onClick(Native Method) at mono.android.view.View_OnClickListenerImplementor.onClick(View_OnClickListenerImplementor.java:30) at android.view.View.performClick(View.java:6306) at android.widget.TextView.performClick(TextView.java:11201) at android.view.View$PerformClick.run(View.java:23962)

What might be the issue? As I have Tested it with Serial USB Terminal it works fine

Would it be possible to get an example of a simple write() command?

Hi, I can't get my head around this, and cant find any good tutorials either.
I build and run the example app, and it finds my Arduino that's connected.
But how can I send a simple text over serial to it, using a serial.write() or something similar?

Would it be possible to add a very basic example for that?

Unhandled exception with sequential read/ writes

Thanks for your effort & sharing nice article about USB communication in Xamarin. I have tried your shared sample and managed to do read/write operations over USB channel. When I tried continuous sequential read, write operations after opening the channel I am getting exception "Unhandled exception" after the first try.

This issue might be related to threads & tasks. I am new to C# & Xamarin, can you please help me out how can I resolve this if I have to work on sequential read, writes over USB channel.

Greatly appreciate!!

Error loading project properties editor

This happens as long as monoandroid5.0 is specified as the targetframework in the UsbSerialForAndroid project. If I remove monoandroid5.0, then the error does not occur.

Visual Studio Version 17.6.2
Xamarin.Android SDK 13.2.0.6

System.ArgumentException: Expected 6 values for property AndroidRule::AndroidPackageFormat, but got 4. Parametername: values bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.Property.Update(ImmutableArray_1 values) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.Property..ctor(PropertyMetadata metadata, ImmutableArray_1 values, PropertyContext context, ImmutableHashSet_1 varyByDimensions) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.PropertyContextFactoryBase.ToProperty(IUIPropertySnapshot property, Page page, Category category, Int32 order, PropertyContext propertyContext, IPropertyEditorRegistry propertyEditorRegistry) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.ProjectPropertyDataAccess.Observer.<HandleDataAsync>g__CreateProperties|14_5(<>c__DisplayClass14_0& ) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.ProjectPropertyDataAccess.Observer.<HandleDataAsync>g__ProcessInitialData|14_1(<>c__DisplayClass14_0& ) --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde --- bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.ProjectPropertyDataAccess.Observer.<InitializeAsync>d__10.MoveNext() --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde --- bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) bei System.Runtime.CompilerServices.TaskAwaiter_1.GetResult() bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.ProjectPropertyDataAccess.Observer.<CreateAsync>d__9.MoveNext() --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde --- bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.ProjectPropertiesEditor.<>c__DisplayClass0_0.<<-ctor>b__0>d.MoveNext() --- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde --- bei System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) bei Microsoft.VisualStudio.ProjectSystem.VS.Implementation.PropertyPages.Designer.AsyncLoadContent.<>c__DisplayClass0_0.<<Initialize>b__0>d.MoveNext()

Porting to .NET MAUI?

I'm new to Xamarin, and also recently learned about .NET MAUI. I'd like to open a discussion about what would be necessary to port this to a MAUI project. For all I know, it might be possible to consume this library directly in a MAUI project, but am not sure how. Any thoughts or ideas on the practicality or steps to port this project? Looking forward to any ideas or advice.

assembly is not a valid attribute location

Edit: My bad, it had to be placed outside of the namespace.

Hi, trying to add this to a MAUI project, following the instructions:
3. Add the following attribute to the main activity to enable the USB Host

[assembly: UsesFeature("android.hardware.usb.host")]

I get an error:
Warning CS0657 'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored. ProffSkapMAUI (net6.0-android)

Also is there any very basic example of how to write to the serial port, I could not find any .write example in the example app?

timeout exeptions

Hi,
if I Plugin the USB device directly everything works fine.
But if I put an USB Hub between, I get timeout expetions during Connection, Open,....
If I start Debugging, no Problem appears because of the short delay of each step.
Any idea ?

STM devices

STM devices are included in the Usbld.cs file but are not included in the device dictionary in the CdcAcmSerialDriver.cs file.

Debugging on device impossible : android minimal version

Hello !
I downloaded project but can deploy or debug on any device (tablet or emulator).
It says that I have to change "android minimal version".
I Have various devices they are based on Android 7.1 or 8.1.
I checked the manifest and set as follow :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.PandaIHM">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="27" />
    <application android:label="PandaIHM.Android"></application>
</manifest>

But it is completely ignored, why ?
the target SDK is 8.1

The bulkTransfer supports offsets

// bulkTransfer does not support offsets, make a copy.

// bulkTransfer does not support offsets, make a copy.

// bulkTransfer does not support offsets, make a copy.

// bulkTransfer does not support offsets, make a copy.

amtWritten = mConnection.BulkTransfer(mWriteEndpoint, writeBuffer, writeLength, timeoutMillis);

There are 5 places in the code with the assertion that
"bulkTransfer does not support offsets, make a copy."

But bulkTransfer has overloaded method whith offset parameter, see
https://developer.android.com/reference/android/hardware/usb/UsbDeviceConnection#bulkTransfer(android.hardware.usb.UsbEndpoint,%20byte[],%20int,%20int,%20int)

public int bulkTransfer (UsbEndpoint endpoint, byte[] buffer, int offset, int length, int timeout)

It allows to reduce code(and make it faster) like in Cp21xxSerialDriver.cs
https://github.com/IhorNehrutsa/UsbSerialForAndroid/blob/c805220355feb0de034f8ffa9ea9cb9ea47b24a0/UsbSerialForAndroid/driver/Cp21xxSerialDriver.cs#L210-L236

Dotnet6 MAUI support

It would be great to have a version that supports Dotnet6 with MAUI. I could get it to work with a new project file:

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<TargetFrameworks>net6.0-android</TargetFrameworks>
		<UseMaui>true</UseMaui>
		<SingleProject>true</SingleProject>
		<ImplicitUsings>enable</ImplicitUsings>
		<SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">21.0</SupportedOSPlatformVersion>
		<ReleaseVersion>0.0.0.1</ReleaseVersion>
	</PropertyGroup>
</Project>

A NuGet version would be even better. If you need any help, happy to make a PR to get this going.

Move from LGPL to MIT license

HI @anotherlab,

I've found your work to be pretty useful and see the potential for this library to be used more widely while getting more involvement from the open source community.

Would you consider moving the License for this library from LGPL to MIT considering that the source that this project is based on also changed the license?
mik3y/usb-serial-for-android@2d13b90

UsbManager DeviceList is Empty

Hello,
I am trying to use this library to connect my Xamarin.Forms (mainly Android) app to my PC via USB. When trying just the example, everything compiles correctly on my tablet (Acer Iconia 7 B1-780), however no devices are ever found when connected to my PC. I have tried using both regular and OTG cables, neither have given me any success.

I have had success in connecting to an Arduino via the OTG cable, so I know the library works. Its just a matter of getting it to work with a PC connection that seems to escape me. The laptop is a Dell Lattitute with an Intel USB controller chip, but don't know the vendor id or its product id. Is the problem just with the driver?

Any help on this would be greatly appreciated.
Cheers!

How Can I Add Bluetooth Virtual COM Ports to deviceList?

I am using a classic bluetooth device which it can work as virtual com port. (I can see on Windows this device's COM Ports.)
I want to add this device's COM PORT to deviceList like USB Port. Have you any idea for this?

Thanks.

Requesting Permission has been failed on Android 14

On Android 14, There are 2 problems

  1. Receiver_Export issue

image

this error occurs on the following code line, UsbSerialForAndroid/Extensions/UsbManagerExtensions.cs
context.RegisterReceiver(usbPermissionReceiver, new IntentFilter(ACTION_USB_PERMISSION));

I changed it to following

if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
context.RegisterReceiver(usbPermissionReceiver, new IntentFilter(ACTION_USB_PERMISSION), (ActivityFlags)ReceiverFlags.Exported);
else
context.RegisterReceiver(usbPermissionReceiver, new IntentFilter(ACTION_USB_PERMISSION));

  1. PendingIntent parma issue

image

this error occurs on the following code line
PendingIntentFlags pendingIntentFlags = Build.VERSION.SdkInt >= BuildVersionCodes.S ? PendingIntentFlags.Mutable : 0;

I changed it Immutable. But I can't get the permission.

FTDI driver only reads NUL bytes

I just tried to use this library with an FTDI adapter. It reports the correct (I assume) number of bytes received, but the buffer is full of 0x00 bytes. The correct data is received with a CP21xx adapter.

I'm trying to find out why that is.

IOException for Prolific PL2303GT (prodId 9155 / 0x23c3)

Device in title is not recognized as the correct device type of HXN, but rather type T. This results in an IOException. It's because it does not do the TestHxStatus() check if deviceVersion == 0x300 & usbVersion ==0x200. The original Java code does do this check.

Method is Open(UsbDeviceConnection connection). Currently lines 373 to 392.

The following code in ProlificSerialDriver.cs needs to be replaced:
if (mDevice.DeviceClass == UsbClass.Comm || maxPacketSize0 != 64) { mDeviceType = DeviceType.DEVICE_TYPE_01; } else if (deviceVersion == 0x300 && usbVersion == 0x200) { mDeviceType = DeviceType.DEVICE_TYPE_T; // TA } else if (deviceVersion == 0x500) { mDeviceType = DeviceType.DEVICE_TYPE_T; // TB } else if (usbVersion == 0x200 && !TestHxStatus()) { mDeviceType = DeviceType.DEVICE_TYPE_HXN; } else { mDeviceType = DeviceType.DEVICE_TYPE_HX; }

Replace with:
if (mDevice.DeviceClass == UsbClass.Comm || maxPacketSize0 != 64) { mDeviceType = DeviceType.DEVICE_TYPE_01; } else if (usbVersion == 0x200) { if ((deviceVersion == 0x300 || deviceVersion == 0x500) && TestHxStatus()) { mDeviceType = DeviceType.DEVICE_TYPE_T; // TA & TB } else { mDeviceType = DeviceType.DEVICE_TYPE_HXN; } } else { mDeviceType = DeviceType.DEVICE_TYPE_HX; }

CdcAcmSerialDriver resolves wrong interfaces In/Out

I have a CDC device that wasn't working. After some debugging in the CDC driver code, I realised that the IN and OUT interfaces were mixed up. The code assumes the order is always the same.

I rewrote it to be like this;

int numberEndpoints = mDataInterface.EndpointCount;
                
                for(var i=0;i<=numberEndpoints-1;i++)
                {
                    var endpoint = mDataInterface.GetEndpoint(i);
                    if(endpoint.Type == UsbAddressing.XferBulk
                       && endpoint.Direction == UsbAddressing.In)
                    {
                        mReadEndpoint = endpoint;
                    }else if(endpoint.Type == UsbAddressing.XferBulk
                             && endpoint.Direction == UsbAddressing.Out)
                    {
                        mWriteEndpoint = endpoint;
                    }
                }

so the ordering of the interfaces no longer matters, it should resolve the In and Out interfaces according to their direction.

Hope this helps someone else stuck with this.

Changing Baud Rate

Hello,
I want to change Baud Rate in this project.

For example
Write("character");//in 300 Baud Rate
Read();
Write("character");//in 1200 Baud Rate
Read();

How Can I do this?
Help me please

921600 bauds support ?

Hi and thanks for your library.

I use a CH340e and
In your code I see the baud rate supported :
int[] baud = new int[]
{
2400, 0xd901, 0x0038, 4800, 0x6402,
0x001f, 9600, 0xb202, 0x0013, 19200, 0xd902, 0x000d, 38400,
0x6403, 0x000a, 115200, 0xcc03, 0x0008
};

But I want use a higger baud rate of 921 600 bauds.
It is possible with your library ?
if it is possible what is the good values for 921600 to complete the int[] baud value accepted ?

Ftdi throws error on Read method

Hi, I have a program I have been using with the Cp21xx driver for a while. I decided to switch my hardware to an FTDI driver for stock reasons. The problem is that, with exactly the same software I had with Cp21xx, that worked, when switching to the FTDI it throws an error in the Read method (while the Write method seems to be working fine).
The error is the following (The Read method shows a -1 which in a BulkTransfer means failure):

[FtdiSerialDriver] Total bytes read=-1
[SerialInputOutputManager] Task ending due to exception: Expected at least 2 bytes
[UsbDeviceConnectionJNI] close
[SerialInputOutputManager] Task Ended!

As you can see in the Debug trace, the USB is correctly recognised:

[USB] USB device attached: /dev/bus/usb/001/002

The Write method also works fine:

[FtdiSerialDriver] claimInterface 0 SUCCESS
[SerialInputOutputManager] Task Started!
[FtdiSerialDriver] Wrote amtWritten=7 attempted=7

I'm sure there is a difference in how the Cp21xx and the Ftdi work internally and there must be a parameter that has to be modified. If somebody could guide me on what to change to have the Ftdi working as the Cp21xx did, I'd ve really thankful.

Collaboration

Hi there,

Device.Net is a connected device framework for C#. I came across this library on the Xamarin Forums. Usb.Net is a USB library that supports Android. I was wondering if there would be anything we could do to collaborate and increase the compatibility of our libraries.

One way to create integration would be to implement these interfaces IDeviceFactory and IDevice. Or, a wrapper could be written around UsbSerialForAndroid to implement these interfaces.

Let me know if this sounds like a good idea.

Can connect to device but Java.IO.IOException when something should be received

Hello,
I'm using this library in the Android Project of a Xamarin.Forms app. My intent is to read data from a USB QR code reader, of course configured in USB-COM.
The device seems to communicate using CDC driver. I can use it with the SimpleUsbTerminal app (that should use the Java version that this c# code is derived from, if I understood correctly), using the "CDC" driver.

I Add the product before to use UsbSerialProber like this:
table.AddProduct(0xAC90, 0x3003, typeof(CdcAcmSerialDriver)); // Eyoyo 2D code reader
Then I find the driver, the port, I request user permission (that I never seen on screen... strange...) like this:
var permissionGranted = await usbManager.RequestPermissionAsync(drv.Device, context);
Then I open the port using SerialInputOutputManager.

All this is happening without errors. But then when I read something on the reader I get a ErrorReceived event with this exception:

[Java.IO.IOException]
Message:   Exception of type 'Java.IO.IOException' was thrown.
Source:    Android.UsbSerial
TargetSite:Read
HelpLink:  NULL
--- STACKTRACE ---
  at Hoho.Android.UsbSerial.Driver.CdcAcmSerialDriver+CdcAcmSerialPort.Read (System.Byte[] dest, System.Int32 timeoutMillis) [0x0004e] in <e3a5da9fe2874e459d590928e7bb2c5b>:0 
  at Hoho.Android.UsbSerial.Extensions.SerialInputOutputManager.Step () [0x00001] in <e3a5da9fe2874e459d590928e7bb2c5b>:0 
  at Hoho.Android.UsbSerial.Extensions.SerialInputOutputManager+<>c__DisplayClass34_0.<Open>b__1 () [0x00021] in <e3a5da9fe2874e459d590928e7bb2c5b>:0 
  --- End of managed Java.IO.IOException stack trace ---
java.io.IOException: Error queueing request.

After that the channel is stuck. The DataReceived event is never called and no other errors are received.

I'm lost... Do you have suggestions on what to check, do to let this thing work please?

PS: I've tried to add the USB data to the table in the example app but nothing happens there too when I read something. But no errors are shown there, I suspect that ErrorReceived is not monitored there.

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.