Android Question Help for use of felUsbSerial-Library

D

Deleted member 103

Guest
Hi,

I use the felUsbSerial library for the USB communication and I have a question about the connection establishment.

With this code, I ask for the approval and build the connection to the USB device.
After the approval request, I wait with a "do while" loop until approval is granted.
My question: is there a better solution or is my solution OK?

B4X:
Public Sub ConnectUsbButton
    Dim indexUsbDevice As Int = GetUsbDevice
    If indexUsbDevice = -1 Then
        Log("No connected usb devices.")
        ToastMessageShow(Starter.Language.Value("USBNotConnected"), True)
        IsConnected = False
    Else
        Dim device As UsbDevice = usbmanager.GetDevices(indexUsbDevice)
        If usbmanager.HasPermission(device) = False Then
            'ToastMessageShow(Starter.Language.Value("USBAllowConnection"), True)
            usbmanager.RequestPermission(device)
            
            Dim timeout As Int
            Do While Not(usbmanager.HasPermission(device)) And timeout < 30
                Sleep(1000)
                timeout = timeout + 1
                Log("Sleep(1000)" & timeout)
            Loop
            
            If timeout < 30 Then
                LogColor("ConnectUsbButton", Colors.Green)
                ConnectUsbButton
            End If
        Else
            LogColor("usbserial.Initialize", Colors.red)
            If usbserial.IsInitialized Then usbserial.Close
            usbserial.Initialize("serial", device, -1)
            usbserial.BaudRate = 9600 '115200
            usbserial.DataBits = usbserial.DATA_BITS_8

            usbserial.StartReading
            
            IsConnected = True
        End If
    End If
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is necessary so that I know if the user does not give permission.
It is better (safer) to check whether you have permission or not at that point.
The result will be the same and you will not need to update it if you change the timeout at some point.
 
Upvote 0
D

Deleted member 103

Guest
It is better (safer) to check whether you have permission or not at that point.
The result will be the same and you will not need to update it if you change the timeout at some point.
Erel! From time to time you might be right too. :D:)
 
Upvote 0
Top