B4A Library felUsbSerial - Alternative Usb Serial library

Status
Not open for further replies.
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

  • felUsbSerial.zip
    75.2 KB · Views: 1,727
Last edited:

Wal

Member
Licensed User
Longtime User
I found the Error.

FTDISioIds.java:
new ConcreteDevice(0x04d8, 0x000a)

but the device is a cdcserial Device
 

Wal

Member
Licensed User
Longtime User
V1.00 is released (first post). It adds a new Initialize2 method that lets you to explicitly choose the serial class.

For example:
B4X:
fel.Initialize2("fel", Device, -1, "CDCSerialDevice")

Thank Erel it works, we need now is SetRTS and SetDTR. ;)
 

Kurt McCullum

Member
Licensed User
Is it possible to have both CTS/RTS and Xon/Xoff active at the same time. I've got a device that I'm trying to connect to that requires CTS/RTS to be active even though it doesn't always use it. With VB.Net I can set the port to Both which allows me to connect to the device but I don't see the setting here.

Kurt
 

JordiCP

Expert
Licensed User
Longtime User
I need to communicate with a CDC-device to stablish a simple protocol. On the other side there is an embedded board. I haven't used Android USB up to now, so I am quite new in this.

Should I use this library for this, or better use USB-Host library? (or both are good for the purpose?)
 

Yuretz2

Member
Licensed User
Hi
Im using example from the first post.

I connected FTDI device, but i know that in my tablet also is some internal device that usb.manager finds as device(0), so im using GetDevices(1) to connect to FTDI
B4X:
Dim device As UsbDevice = manager.GetDevices(1) 'assuming that there is exactly one device

After "usbserial.StartReading" my log look like that:

B4X:
Installing file.
PackageAdded: package:b4a.example
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Data obtained from Read buffer: �`
Raw data from Read buffer: 0xB1 0x60
Number of bytes obtained from Read buffer: 2
Data obtained from Read buffer: �`
Raw data from Read buffer: 0xB1 0x60
Number of bytes obtained from Read buffer: 2
Data obtained from Read buffer: �`
Raw data from Read buffer: 0xB1 0x60
Number of bytes obtained from Read buffer: 2
Data obtained from Read buffer: �`
Raw data from Read buffer: 0xB1 0x60
Number of bytes obtained from Read buffer: 2

My FTDI device does not transmit any data at that time. "serial_DataAvailable" is not rised as you can see.
Is it normal? Can this unknown data interfere with my data then FTDI will start transmit?
Thank You
 

yo3ggx

Active Member
Licensed User
Longtime User
Does this library supports FTDI based USB/Serial interfaces with different VID/PID than the standard chip?
Dan
 

Yuretz2

Member
Licensed User
Yes, you can specify that you device is FTDI with:
B4X:
fel.Initialize2("fel", Device, -1, "FTDISerialDevice")

For autostart app then device is connected:

Manifest:
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" />)
YourAppFolder\Objects\res\xml\device_filter.xml:
B4X:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 0x0403 / 0x6001: FTDI FT232R UART -->
    <usb-device vendor-id="1027" product-id="24577" />

    <!-- 0x067b / 0x2303 Prolific PL2303 -->
    <usb-device vendor-id="1659" product-id="8963"/>

    <!-- Your device PID/VID -->
    <usb-device vendor-id="YourVID" product-id="YourPID"/>

</resources>
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Note that you can use the new CreateResource keyword in the manifest editor to create the XML file:
B4X:
CreateResoutce(xml, device_filter.xml,
<resources>
<!-- 0x0403 / 0x6001: FTDI FT232R UART -->
<usb-device vendor-id="1027" product-id="24577" />

<!-- 0x067b / 0x2303 Prolific PL2303 -->
<usb-device vendor-id="1659" product-id="8963"/>

<!-- Your device PID/VID -->
<usb-device vendor-id="YourVID" product-id="YourPID"/>

</resources>
)
 

yo3ggx

Active Member
Licensed User
Longtime User
It seems that my chip is already included in the library. There is any way to get the USB device name using this library?
If i try device.DeviceName I get the full path to the device, not the device name.

The XML file is mandatory if I don't want the application to start automatically when the device is connected?

Thank you.
Dan
 

yo3ggx

Active Member
Licensed User
Longtime User
Maybe I will try to use USBserial v2 just to get all the device information with usb.DeviceInfo.
 

Emanuel Straub

Member
Licensed User
Longtime User
Thanks for your reply.

I wrote this sample code to test the multiple connection:

B4X:
#Region  Project Attributes
    #ApplicationLabel: USB Example
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: false
#End Region

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

Sub Process_Globals
    Dim usb As felUsbSerial
    Dim usb2 As felUsbSerial
    Dim manager As UsbManager
    Dim bc As ByteConverter
    Dim Timer1 As Timer
    Dim r_id As Int = 0x6001
    Dim r_vd As Int = 0x403
    Dim s_id As Int = 0x90a
    Dim s_vd As Int = 0xc2e
End Sub

Sub Globals

    Dim btnSend1,btnSend2,btnSend3, btnSend4, btnOpen As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    manager.Initialize
End Sub


Sub Activity_Resume

    btnSend1.Enabled = False
    btnSend2.Enabled = False
    btnSend3.Enabled = False
    btnSend4.Enabled = False
End Sub


Sub btnOpen_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)
             If (UsbDvc.ProductId = r_id) And (UsbDvc.VendorId = r_vd) Then           
                 If manager.HasPermission(UsbDvc) = False Then
                       manager.RequestPermission(UsbDvc)
                 Else
                       usb.Initialize("relais", UsbDvc,-1)
                       usb.BaudRate = 9600
                       usb.DataBits = usb.DATA_BITS_8
                       btnSend1.Enabled = True        
                       btnSend2.Enabled = True        
                       btnSend3.Enabled = True        
                       btnSend4.Enabled = True
                       ToastMessageShow("Relaise connected!",True)
                       usb.StartReading
                       Timer1.Initialize("Timer1",5000)
                       Timer1.Enabled = True
                 End If
            End If
            If (UsbDvc.ProductId = s_id) And (UsbDvc.VendorId = s_vd) Then           
                 If manager.HasPermission(UsbDvc) = False Then
                       manager.RequestPermission(UsbDvc)
                 Else
                       usb2.Initialize("scanner",UsbDvc,-1)
                       usb2.BaudRate = 9600
                       usb2.DataBits = usb.DATA_BITS_8
                       usb2.StartReading
                    ToastMessageShow("Scanner connected!",True)
                 End If
            End If
        Next
    End If
End Sub

Sub scanner_DataAvailable (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    ToastMessageShow(msg,True)
End Sub

Sub Timer1_Tick
    Dim b() As Byte
    Dim s As String
    Dim i As Int
    Dim wert As String
    For i = 1 To 4
        wert="00"
        If Rnd(0,2)=1 Then wert="01"
        s = s & "FF" & NumberFormat(i, 2, 0) & wert & "0D"
    Next
    b = bc.HexToBytes(s)
    usb.Write(b)
End Sub

Sub btnExit_Click
    ExitApplication
End Sub

After the first run into Scanner_DataAvailable my Tablet (Huawei MediaPad X1/Andoid 4.4.2) shows the Toastmessage and then reboot.
Any ideas?
 
Status
Not open for further replies.
Top