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,253
  • UsbSerial2.5.zip
    36.3 KB · Views: 928
  • UsbSerial2.6.zip
    36.3 KB · Views: 51
Last edited:

Wal

Member
Licensed User
Longtime User
Hello,
for users who have problems when you open the USB ports, after connecting other USB devices, can use this code. The app starts again automatically. Root is needed.
Tested on Nexus 7 2013 LTE

B4X:
Sub Open
Try
    Dim UsbMngr As UsbManager  ' USB library
    UsbMngr.Initialize
    Dim UsbDevices() As UsbDevice  ' USB library
    UsbDevices = UsbMngr.GetDevices  
    If UsbDevices.Length > 0 Then
        For i = 0 To UsbDevices.Length - 1
            Dim UsbDvc As UsbDevice
            UsbDvc = UsbDevices(i)
            If (UsbDvc.ProductId = UsbPid) AND (UsbDvc.VendorId = UsbVid) Then
                USB.SetCustomDevice(USB.DRIVER_CDCACM, UsbVid, UsbPid)
                If Not(UsbMngr.HasPermission(UsbDvc)) Then
                    UsbMngr.RequestPermission(UsbDvc)
                Else  
                    Dev = USB.Open(57600, i + 1)      
                    If Dev <> USB.USB_NONE Then   
                        astreams.Initialize(USB.GetInputStream, USB.GetOutputStream, "astreams")
                    End If
                End If
                Exit
            End If
        Next
    End If
Catch
    Dim Command, Runner As String
    Dim StdOut, StdErr As StringBuilder
    Dim Result As Int

    Runner = File.Combine(File.DirInternalCache, "runner")
    Command = File.Combine(File.DirInternalCache, "command")
    File.WriteString(File.DirInternalCache, "runner", "su < " & Command)
    File.WriteString(File.DirInternalCache, "command", "echo 0 > /sys/bus/usb/devices/2-1/authorized" & CRLF & _
                "echo 1 > /sys/bus/usb/devices/2-1/authorized" & CRLF & "Exit")
    StdOut.Initialize
    StdErr.Initialize
    Result = Ph.Shell("sh", Array As String(Runner), StdOut, StdErr)
    ExitApplication
End Try
End Sub
 

Toley

Active Member
Licensed User
Longtime User
Is there a known problem with this library on Android 5?

When I send the program to my phone (android 5) via the bridge it works very well. But when I try to restart it after, it looks like there is no usb connection at all. The same program connect all the time on my tablet (android 4.4.2).

B4X:
#Region  Project Attributes
    #ApplicationLabel: APC200a Receiver
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: True
    #IncludeTitle: False
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim usb As UsbSerial
    Dim ast As AsyncStreamsText
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

    Private btn_conn As Button
    Private lbl_rcv As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("apc200")
End Sub

Sub Activity_Resume
'    btn_conn.Enabled = True
'    btn_conn.Visible = True
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    ast.Close
    usb.Close
    ToastMessageShow("astreams & USB closed", False)
    ExitApplication
End Sub

Sub ast_NewText(Text As String)
    lbl_rcv.Text = Text
End Sub

Sub ast_Terminated
    ToastMessageShow("astreams terminated", False)
    ast.Close
End Sub

Sub btn_conn_Click
    If usb.UsbPresent = usb.USB_NONE Then
        ToastMessageShow("No USB device or accessory detected!", False)
        Return
    End If
    If  (usb.HasPermission) Then
'        Msgbox(usb.DeviceInfo, "Device Information 1")
        Dim dev As Int
        dev = usb.Open(9600)
        ToastMessageShow("USB Connected", False)
        If dev <> usb.USB_NONE Then
            btn_conn.Visible = False
            lbl_rcv.Visible = True
            ast.Initialize(Me, "ast", usb.GetInputStream, usb.GetOutputStream)
            ToastMessageShow("Astreams connected", False)
        Else
            ToastMessageShow("Error opening USB", False)
        End If
    Else
        usb.RequestPermission
    End If
End Sub

Edit: I've found a new info. I can make it work if I disconnect the USB device and reconnect it and then select my app in the pop up menu asking which application to use with this USB device. But if I start the application manually, the USB don't connect.
 
Last edited:

Toley

Active Member
Licensed User
Longtime User
OK I solved the problem. That was only a stupid mistake. I did change the package name during development so I end up having 2 progs. So when I started the one by the shortcut, it was the oldest instance that opened. Everything works fine now.
 

Bob Sabrook

Member
Licensed User
Longtime User
Using a Hub.

If you have problems with enumeration, or sustaining a connection, try connecting through an externally powered USB 2.0 hub.

I have found this to solve issues that I thought were due to software.

This tip could save you a lot of time.

Edit: This applies to FTDI devices.
 
Last edited:

logicielrl

Member
Licensed User
Longtime User
I used this lib with 45 tablet with 2 usb rs232 on each on android 4.1.1 work perfectly fine
i change tablet with android 4.4.2 but can get the streams to work
this is the code i use


If usb2.UsbPresent(2) = usb2.USB_NONE Then
Log("Msgbox - no device")
Msgbox("No USB device or accessory detected!", "Error")
Log("Msgbox - returned")
Return
End If
Log("Checking permission")
If (usb2.HasPermission(2)) Then
Msgbox(usb2.DeviceInfo(2), "Device Information")
Dim dev As Int
dev = usb2.Open(9600,2)
If dev <> usb2.USB_NONE Then


Log("Connected successfully!")
astreams2.Initialize(usb2.GetInputStream, usb2.GetOutputStream, "astreams2")
Else
Log("Error opening USB port")
End If
Else
usb2.RequestPermission(2)
End If


Any idea ?
 
Last edited:

logicielrl

Member
Licensed User
Longtime User
Do you think there is a problem with 4.4.2 ?
if so ,then i'll try to find other tablets ( i have to deliver 50 units by next week , and i'm stuck)
 
Last edited:

logicielrl

Member
Licensed User
Longtime User
Your right !
I bought other tablet with 4.2.2 ,Miracle it work

Thks very much for your input

p.s. : if you want to see a really nice product made with your B4A :www.androbc.com
 

JeanLC

Member
Licensed User
Longtime User
Hi GaNdAlF89,

Usually the bar code readers "LETTORE LASER DI CODICI A BARRE" send data like a keyboard and it's not suitable for this library. It's not an RS232, it's a keyboard. If you have the focus on a text box and plug a keyboard, type something and it writes, then if you plug the scanner, it will probably write the code when you scan it.
 

GaNdAlF89

Active Member
Licensed User
Longtime User
Hi GaNdAlF89,

Usually the bar code readers "LETTORE LASER DI CODICI A BARRE" send data like a keyboard and it's not suitable for this library. It's not an RS232, it's a keyboard. If you have the focus on a text box and plug a keyboard, type something and it writes, then if you plug the scanner, it will probably write the code when you scan it.
Thanks for reply, in that case I will change the model of the barcode reader...
 

Alberto Iglesias

Well-Known Member
Licensed User
Longtime User
Top