B4A Library felUsbSerial - Alternative Usb Serial library

Status
Not open for further replies.

Erel

Administrator
Staff member
Licensed User
This library wraps the following open source project: https://github.com/felHR85/UsbSerial (MIT license).

It is an alternative to the UsbSerial2 library.

The following devices are supported: CP210x, CDC, FTDI, PL2303 and CH34x.

Usage is simple. You find the UsbDevice with USB library and then initialize felUsbSerial, configure it and start reading.

B4X:
Sub Process_Globals
   Private usbserial As felUsbSerial
   Private manager As UsbManager
   Private bc As ByteConverter
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
     manager.Initialize
   End If
   Dim btnConnect As Button
   btnConnect.Initialize("btnConnect")
   btnConnect.Text = "Connect"
   Activity.AddView(btnConnect, 10dip, 10dip, 100dip, 100dip)
End Sub

Sub btnConnect_Click
   If manager.GetDevices.Length = 0 Then
     Log("No connected usb devices.")
   Else
     Dim device As UsbDevice = manager.GetDevices(0) 'assuming that there is exactly one device
     If manager.HasPermission(device) = False Then
       ToastMessageShow("Please allow connection and click again.", True)
       manager.RequestPermission(device)
     Else
       usbserial.Initialize("serial", device, -1)
       usbserial.BaudRate = 115200
       usbserial.DataBits = usbserial.DATA_BITS_8
       usbserial.StartReading
     End If
   End If
End Sub

Private Sub serial_DataAvailable (Buffer() As Byte)
   Log("New data: " & bc.HexFromBytes(Buffer))
End Sub
SetFlowControl is only implemented for CP2102, FTDI and CH34x chips.

Updates

V1.12 - BUFFER_READ_SIZE / BUFFER_WRITE_SIZE fields. Default value is 16 * 1024. You can change these values before initializing the object to change the internal buffers sizes.
 

Attachments

Last edited:

Abílio Magalhães

Member
Licensed User
Dear Erel,

This library is working perfectly!!!

Thank you for so dedicated support.

I'm very happy with Basic4Android. it had proveed to be the best RAD tool for developing in a large and complex Android app.

Kind regards,
Abilio
 

Toley

Active Member
Licensed User
Thank you Erel, very usefull one since it supports CH340. But do you think it can be used with AsyncStreams since it don't have any GetInputStream and GetOutputStream methods?
 

Kurt McCullum

Member
Licensed User
You don't need to use AsyncStreams here. It raises a similar NewData event.
I've only been using B4a for about a week so I may be missing something here. I took the code from above and used it in a new project. I can write data using usbserial.write but the NewData event is never fired when I send data to the device.

I noticed in your code that it is serial_NewData, should it be usbserial_NewData.

I'm using an FTDI usb to serial device.

Thanks

Kurt
 

Kurt McCullum

Member
Licensed User
I've only been using B4a for about a week so I may be missing something here. I took the code from above and used it in a new project. I can write data using usbserial.write but the NewData event is never fired when I send data to the device.

Kurt
I just figured it out. The event name should be serial_dataavailable. Once that change is made to your code it works great.

Kurt
 

mtselection

Member
Licensed User
Hello Erel,

I'm using this library instead of USBSerial, but I need to use the RTS control. I'm using the property FlowControl with FLOW_CONTROL_RTS_CTS but seems not to work. For the reference site is a function in development. You know if this is possible?

Thank you

Maurizio
 

Erel

Administrator
Staff member
Licensed User
I've checked the internal library source code.

The SetFlowControl is only implemented for the following chips: CP2102 and FTDI.

I will add a message about it in the documentation.
 

Kurt McCullum

Member
Licensed User
Is it possible to check the status of the DSR line with this library? I have a situation where a remote device sets the DSR line whenever it opens its serial port and my app needs to know when there is a change so I can start sending data. It's a bit different than a flow control using DSR since I'm only checking the status of it.

Kurt
 

Kurt McCullum

Member
Licensed User
Thanks Erel. I thought it was possible with GetDSR() function but when I went and looked at the code I noticed the //TODO comment and no code. I suppose that's a future enhancement.
 

Wal

Member
Licensed User
I use this code with a CDC-Device:
B4X:
Sub Process_Globals
    Private usbserial As felUsbSerial
    Private manager As UsbManager
    Private UsbPid As Int = 0xa
    Private UsbVid As Int = 0x4D8
   
    Private bc As ByteConverter
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
     manager.Initialize
   End If
   Dim btnConnect As Button
   btnConnect.Initialize("btnConnect")
   btnConnect.Text = "Connect"
   Activity.AddView(btnConnect, 10dip, 10dip, 100dip, 100dip)
End Sub

Sub btnConnect_Click
    Dim UsbDevices() As UsbDevice
    UsbDevices = manager.GetDevices
    If UsbDevices.Length = 0 Then
        ToastMessageShow("No connected usb devices.", True)           
    Else
        For z = 0 To UsbDevices.Length - 1
            Dim UsbDvc As UsbDevice
            UsbDvc = UsbDevices(z)
            Log("USBDeviceNr. " & z & " --- UsbPid = " & UsbDvc.ProductId)
             If (UsbDvc.ProductId = UsbPid) And (UsbDvc.VendorId = UsbVid) Then               
                If manager.HasPermission(UsbDvc) = False Then
                       ToastMessageShow("Please allow connection and click again.", True)
                       manager.RequestPermission(UsbDvc)
                 Else   
                    If usbserial.IsInitialized Then usbserial.Close
                    Log("Initialize USBDeviceNr. " & z )
                    usbserial.Initialize("serial", UsbDvc, -1)  <-- Line55
                       usbserial.BaudRate = 57600
                       usbserial.DataBits = usbserial.DATA_BITS_8
                       Set232(usbserial, True, False)
                       usbserial.StartReading
                End If
                Exit
            End If
        Next
    End If
End Sub

Private Sub serial_DataAvailable (Buffer() As Byte)
   Log("New data: " & bc.HexFromBytes(Buffer))
End Sub

Sub Waitms(ms As Int)
   Dim Ti As Long
   Ti = DateTime.Now + (ms)
   Do While DateTime.Now < Ti
      DoEvents
   Loop
End Sub

Sub Set232(USB As felUsbSerial, RTSBool As Boolean, DTRBool As Boolean)
    Dim r As Reflector
    r.Target = USB
    r.Target = r.getField("driver")
    r.RunMethod2("setRTS", RTSBool, "java.lang.boolean")
    r.RunMethod2("setDTR", DTRBool, "java.lang.boolean")
    Waitms(2000)
End Sub
Error :
B4X:
Installing file.
PackageAdded: package:b4a.example
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
USBDeviceNr. 0 --- UsbPid = 33145
USBDeviceNr. 1 --- UsbPid = 10
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
USBDeviceNr. 0 --- UsbPid = 33145
USBDeviceNr. 1 --- UsbPid = 10
Initialize USBDeviceNr. 1
Error occurred on line: 55 (Main)
java.lang.RuntimeException: Error opening serial device.
    at anywheresoftware.b4a.objects.usb.felUsbSerial.Initialize(felUsbSerial.java:60)
    at b4a.example.main._btnconnect_click(main.java:447)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:697)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:339)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:246)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:134)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:157)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:153)
    at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:78)
    at android.view.View.performClick(View.java:4443)
    at android.view.View$PerformClick.run(View.java:18443)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)
** Activity (main) Pause, UserClosed = true **
Can you help me ?
 

Erel

Administrator
Staff member
Licensed User
Check the unfiltered logs. There might be more information there.
 

Erel

Administrator
Staff member
Licensed User
I don't think that it is related. To actually see the unfiltered logs you will need to connect with usb debug mode. Now that I think about it, it is probably not really possible in this case.

You can try to explicitly set the interface index (instead of setting it to -1). Go over the interfaces and find the correct one.

The felUsbSerial library searches for an interface with interface class of 10.
 

Wal

Member
Licensed User
I was just wondering that the FTDI device emerges, although the USBPid 10's.

You can try to explicitly set the interface index (instead of setting it to -1). Go over the interfaces and find the correct one.
That's what I've done, to no avail.

That's not bad, USB Serial Lib works.
I wanted to test only the new Lib.
 
Status
Not open for further replies.
Top