B4A Library UsbSerial library 2.0 - supports more devices

This is an expanded version of the original UsbSerial library. It has added support for Prolific PL2303 USB to serial converters, Android ADK devices and USB permissions. All devices use the same simple interface intended to be used with AsyncStreams and AsyncStreamsText. Note that AsyncStreams prefix mode is not supported. The library is based on the same open source project Android USB host serial driver library as the existing UsbSerial library but no longer needs a separate jar file as the project source code is incorporated in the library.

The specific enhancements to the library over the original UsbSerial library are :

UsbPresent, HasPermission and RequestPermission are added to identify any attached device or Accessory available to the library and deal with permission to access it.

SetParameters, which must be used after Open(), and the constants for SetParameters provides acess to all the serial line parameters instead of just baud rate.

DeviceInfo provides a string containing information about a device. This works for slave devices only.

Android Accessories, which are host mode devices, are recognised and can be used in the same way as the other slave mode devices.

Prolific PL2303 support is added.

Silicon Labs CP210x support is added - maybe only the CP2102 as I have no hardware to test.

The FTDI "status byte" bug on reading input that existed in version 1.0 of this library is hopefully fixed.


The usb-serial-for-android project and therefore also this library is licensed under the GNU Lesser General Public License v3. http://www.gnu.org/licenses/lgpl.html|http://www.gnu.org/licenses/lgpl.html
Copies of both the General Public License and Lesser General Public License are in the provided archive.

The user has to give your application permission to access the USB device before it can be opened. You can do this in two ways.

As with the original UsbSerial library you can add the following code to the manifest editor

B4X:
AddActivityText(main, <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" />)
Then copy device_filter.xml from the demo in the attached archive to: <your project>\objects\res\xml and mark it as read-only. Note that this is an expanded version of the original device_filter.xml file.

Finally install the program and attach the USB device. A dialog will appear asking whether you want to start your program. If you check the “Use by default…” checkbox from now on when the USB device is plugged in your program will be started. If you don’t check the checkbox then you will be asked each time the device is plugged in.

A similar procedure can be used for Accessories as detailed in the “Using an intent filter” section here USB Accessory | Android Developers


Alternatively you can use the new HasPermission and RequestPermission methods without requiring any of the above steps. The demo in the archive incorporates both ways of obtaining permission.

EDIT:- Version 2.1 now posted. See post #4 for details

EDIT:- Version 2.2 now posted. See post #14 for details

EDIT:- Version 2.3 now posted. See post #26 for details

V2.4 is available here: http://www.b4x.com/android/forum/th...pports-more-devices.28176/page-11#post-259167
This update adds support for devices connected to multiple USB adapters.


V2.5 is available as an attachment to this post. It is identical to version 2.4 referenced above but adds the required flag for Pending Intents when targeting SDK 31+.

V2.6 is available as an attachment to this post. It is identical to version 2.5 referenced above but adds the required flag for Pending Intents when targeting SDK 34+.
 

Attachments

  • UsbSerial2.3.zip
    99.2 KB · Views: 6,272
  • UsbSerial2.5.zip
    36.3 KB · Views: 951
  • UsbSerial2.6.zip
    36.3 KB · Views: 99
Last edited:

mrodriguez

Member
Licensed User
Longtime User
UsbSerial Ver 2.4
What's new: Support for multiple USB devices
Version history Updated. You can find the changes by searching "Ver_2.4"
Maybe I over documented it. It was for me... feel free to remove the Nonsense
Library and Example updated to Ver 2.4
hoho driver also updated to support multiple devices

Thanks a lot!
 

maleche

Active Member
Licensed User
Longtime User
After reading through all of this list, I seemed to have missed something...
I too am connecting my Android device (Phone, Tablet) to the Arduino Uno.
Is there a recommended OTG to USB-Serial converter to use?
From eBay, Amazon, SparkFun, Adafruit?
I tried to program my Android to IOIO with Rx,Tx but was unable to achieve reliable communication using the examples provided. I don't want to use a timer to check for received data.

anyone have an example for IOIO serial communications without using a Timer?

Thanks in advance!
 

maleche

Active Member
Licensed User
Longtime User
A privilege to chat with you Erel.

My apologies for having two different questions under one topic.

Sorry for the confusion. My comment pertained to using this USBSerial library with an Arduino and I am asking for a recommended USB to Serial converter to connect to the OTG for communications with the Arduino.

My second comment pertained to the IOIO communication library (which I finally got to work). Specifically, is there a “NewData” event that can be employed vice using a timer to check for incoming data?

An honor to chat with you sir.
 

joedarock

Member
Licensed User
Longtime User
I'm trying to use the USB Serial library to build an app that communicates with a device using binary data. I've been able to compile and run the example app and, using a pair of FTDI converters between my tablet and my PC's USB port, I can send/receive ASCII data between a terminal program on the PC and the tablet. Now I want to send binary data from the tablet, but I can't get my arms around how to write the "Astreams.Write" line so that it uses a binary variable as the data argument instead of an ASCII literal.

Thanks for any help

Joe
 

joedarock

Member
Licensed User
Longtime User
AStreams.Write always write binary data. It takes an array or bytes.


Thanks, but that's where I'm having difficulty. In the example, if I replace the literal (quoted) string with a single byte variable or a constant, I get a compiler exception. Can you provide examples on how to code the following into the "Streams.Write" statement?:

1) A literal hex value = 0xFE
2) A pre-defined variable of the same value
3) A literal binary value = 0b11111110
4) A pre-defined variable of the same value.

In each case, I'd expect a single byte of the corresponding value to be transmitted.

Joe
 

hogiebaer

Active Member
Licensed User
Longtime User
First:
Thanks for this great work (UsbserialLib2.4)

But i have a problem.
I use a Serial Interface with prolifti pl2303 chipset. My app needs to print on a serial printer
How can i figure out, what "DevNuml (X)" from the several usb devices from the used device i have to mount with usb1.open(X,9600) ?
Ok, i can try to scan and isolate with usb1.usbpresent(x...y) and if present with usb.deviceinfo(x) to read the
vendor id from the pl2303, but exactly at this point is my problem. From time to time the recognized "DevNum"
changed to another Id, because my customer uses the UsbSlot temporarly for another device. And then he connect after
2 days to the pl2303 adapter and the Id is changing to another DevNumber ?

I have tried with the scan method, but on some devices the app crashes with the
usb1.getdeviceinfo(x), if the scanned DevNum isn´t my pl2303 adapter.
Exactly i tried to get information about a Rfid Device , what is not interesting me and the app crashes

Thanks for your help
 
Last edited:

JeanLC

Member
Licensed User
Longtime User
Hello Hogiebaer,

In fact every time you plug the USB it will change the USB number.

Try this:
1.- Get the Serial Number or some usable info from the Prolific or FTDI. DeviceInfo(DevNum)
2.- If any of the devices attached have some sort of command that have an answer you know, use it.
3.- If any of the devices attached have some sort of particular data format. Identify all but the printer.

Example:
If you have a GPS, you'll get as soon as it's connected a stream of recognizable data. Then you can tell it's not the printer.

If you are using a POS/ESC printer most of them have a Status Command that is answered, so if it responds correctly, it's the printer.
If the printer doesn't have that command but the other devices does, by elimination you have the printer.

Quote: "my customer uses the UsbSlot temporarly for another device. And then he connect after 2 days to the pl2303 adapter and the Id is changing to another DevNumber ?"
Buy one Prolific, one FTDI and glue them to the RS232 device. The you know with DeviceInfo(DevNum) which one is attached to the FTDI and which one is attached to the Prolific.

If you have 3 printers attached and no Prolific/FTDI Serial Number you are doomed :eek:
If you are doomed... buy a modern Prolific/FTDI and change manually the Serial Number then get it with DeviceInfo(DevNum).

Take care of redirecting the Streams to the desired buffer/data_proccessor after identification.

Hope this helps,
Jean
 

Roberto Pattaro

New Member
Licensed User
Longtime User
UsbSerial Ver 2.4
What's new: Support for multiple USB devices
Version history Updated. You can find the changes by searching "Ver_2.4"
Maybe I over documented it. It was for me... feel free to remove the Nonsense
Library and Example updated to Ver 2.4
hoho driver also updated to support multiple devices

Good Morning,
we are trying to use the ver 2.4, without success. While we are building the example in attachment with the library, the compiler show an error:

*** Remote compilation mode ***
Parsing code. 0.00
Compiling code. 0.03
Compiling layouts code. 0.02
Compiling debugger engine code. 0.53
Sending data to remote compiler. Error
step: Compiling generated Java code.
javac 1.7.0_09
src\b4a\example1\main.java:318: error: cannot find symbol
public static anywheresoftware.b4a.objects.UsbSerial _usb1 = null;
^
symbol: class UsbSerial
location: package anywheresoftware.b4a.objects
1 error

So, we have tryed to do a lot of test, checking version of Android SDK (now is 14) and also with Java SDK (try 1.6 and 1.7) every time with the same error posted above.

Anyone can help us?
Thank you
Roberto
 

Roberto Pattaro

New Member
Licensed User
Longtime User
Good Morning,
we are trying to use the ver 2.4, without success. While we are building the example in attachment with the library, the compiler show an error:

*** Remote compilation mode ***
Parsing code. 0.00
Compiling code. 0.03
Compiling layouts code. 0.02
Compiling debugger engine code. 0.53
Sending data to remote compiler. Error
step: Compiling generated Java code.
javac 1.7.0_09
src\b4a\example1\main.java:318: error: cannot find symbol
public static anywheresoftware.b4a.objects.UsbSerial _usb1 = null;
^
symbol: class UsbSerial
location: package anywheresoftware.b4a.objects
1 error

So, we have tryed to do a lot of test, checking version of Android SDK (now is 14) and also with Java SDK (try 1.6 and 1.7) every time with the same error posted above.

Anyone can help us?
Thank you
Roberto

OK! Problem solved, we have "Remote compilation mode" activated. We have removed the check from the menu Tools and everything work like a charm.

Thank you guys
 

DetTigersFan

New Member
Licensed User
Longtime User
B4a is a great programming language to get experience with Android programming, Thanks.
I've got a novice question; When I load UsbSerialDemo.b4a, I get the following error - Missing Jar File for Library...device_filter.xml.
However, the program compiles and connects to the emulator and runs.
I cannot find device_filter.jar anywhere, Why the error?
 

raphael75

Active Member
Licensed User
Longtime User
I use a Serial Interface with prolifti pl2303 chipset. My app needs to print on a serial printer
How can i figure out, what "DevNuml (X)" from the several usb devices from the used device i have to mount with usb1.open(X,9600) ?
Ok, i can try to scan and isolate with usb1.usbpresent(x...y) and if present with usb.deviceinfo(x) to read the vendor id from the pl2303, but exactly at this point is my problem. From time to time the recognized "DevNum" changed to another Id, because my customer uses the UsbSlot temporarly for another device. And then he connect after 2 days to the pl2303 adapter and the Id is changing to another DevNumber ?

I have tried with the scan method, but on some devices the app crashes with the
usb1.getdeviceinfo(x), if the scanned DevNum isn´t my pl2303 adapter.

If you only have one PL2303 USB/Serial adapter device, then you can try something like this to detect the DeviceNumber:

B4X:
Sub Process_Globals
    Dim UsbPidPL2303 As Int = 0x2303  ' Product ID = 2303h for PL2303 USB/Serial adapter
    Dim UsbSerPL2303 As UsbSerial  ' UsbSerial library
    Dim AsStreamsPL2303 As AsyncStreams  ' RandomAccessFile library
End Sub

Sub xxxxxxxxxxxxx
    Dim UsbMngr As UsbManager  ' USB library
    UsbMngr.Initialize
    Dim UsbDevices() As UsbDevice  ' USB library
    UsbDevices = UsbMngr.GetDevices
    'Iterate over USB devices and find the correct one
    If UsbDevices.Length > 0 Then
        For i = 0 To UsbDevices.Length - 1
            Dim UsbDvc As UsbDevice
            UsbDvc = UsbDevices(i)
            If UsbDvc.ProductId = UsbPidPL2303 Then
                UsbSerPL2303.Open(9600, i+1)  ' UsbDevices(i) is like UsbSerial(i+1)
                AsStreamsPL2303.Initialize(UsbSerPL2303.GetInputStream, UsbSerPL2303.GetOutputStream, "AsStreamsPL2303")
                Exit  ' Exit Loop For i
            End If
        Next
    End If
End Sub

Sub AsStreamsPL2303_NewData (Buffer() As Byte)
    ' ...
End Sub

In this code you don't use UsbSerial.DeviceInfo(x), so you don't need to request permission to get access to ProductId.

I'm not sure if the code will work if you have USB Accessories in addition to USB devices.
 
Last edited:

robyx_16

New Member
Licensed User
Longtime User
Hi there. I'm building a custom device with a tablet and using your library. Thank you, it's working grat so far.

I was wondering if you could grant permission automatically for a certain device. Every time i install a new update for my application, i have to grant permission manually (through the PERMISSION dialog) and if the application fails because of the missing permission, it doesn't get written in the system. Next time, i'm being asked again. Could you write a sub to grant permission automatically, please?
 

jjspike

Member
Licensed User
Longtime User
I also have a Galaxy device that exhibits the same detection of a Qualcomm device on port1. Has an alternate version of the library been created or is there another solution available? I would be willing to contribute some funds to assist with the effort.

Thank you!


You will not be able to use the library with the Galaxy S4 without modifying the library. The library assumes that the first USB device it finds is a serial port which is usually a reasonable assumption as Android should only make USB devices visible to applications if they are not handled by Android itself. In this case it is making the Qualcomm, device, probably a Wifi adaptor, visible.

You could try the workaround that I suggested for the same problem in post #54 of this thread.
 
Top