Android Question java usb send and receive

hi, i have to implement this kind of communication and i wanna know that i just use the correct function in java:

example of what i wanna do:
whatiwannado.png


sendDataToIrda:
//invia tramite l'endpoint OUT della chiavetta USB IrDA. (ovvero la via di uscita per i dati verso il dispositivo USB, chiavetta USB IrDA prenderà questi dati e li invierà alla porta IRDA esterna.)
    public void sendDataToIrda(UsbDeviceConnection connection, UsbDevice device, byte[] data, int timeout) {
        if (connection == null) {
            BA.Log("Errore: Connessione USB non disponibile.");
            return;
        }
    
        UsbEndpoint outEndpoint = null;
        UsbInterface usbInterface = null;
    
        // Trova l'endpoint OUT
        for (int i = 0; i < device.getInterfaceCount(); i++) {
            usbInterface = device.getInterface(i);
            for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
                UsbEndpoint endpoint = usbInterface.getEndpoint(j);
                if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
                    outEndpoint = endpoint;
                    BA.Log("MaxPacketSize: " + outEndpoint.getMaxPacketSize());
                    break;
                }
            }
            if (outEndpoint != null) break;
        }
    
        if (outEndpoint == null) {
            BA.Log("Errore: Nessun endpoint OUT trovato! Numero interfacce: " + device.getInterfaceCount());
            return;
        } else {
            BA.Log("Endpoint OUT trovato: " + outEndpoint.getAddress());
        }
        
    
        // Reclama l'interfaccia USB
        if (usbInterface != null) {
            if (!connection.claimInterface(usbInterface, true)) {
                BA.Log("Errore: impossibile acquisire l'interfaccia USB.");
                return;
            }
        }
    
        // Invia i dati con bulkTransfer
        int result = connection.bulkTransfer(outEndpoint, data, data.length, timeout);
        /* bulkTransfer return the length of data transferred (or zero) for success, or negative value for failure*/

        if (result >= 0) BA.Log("Dati inviati con successo con bulkTransfer: " + result + " byte.");
        else BA.Log("Errore nell'invio dei dati con bulkTransfer. Codice di errore: " + result);
    }

receiveDataFromIrda:
//riceve tramite la chiavetta USB IrDA i dati della porta IRDa esterna
     public byte[] receiveDataFromIrda(UsbDeviceConnection connection, UsbDevice device, DDCMPProtocol protocol) {
        if (connection == null) {
            BA.Log("Errore: Connessione USB non valida.");
            return null;
        }
    
        UsbInterface usbInterface = device.getInterface(0);
        UsbEndpoint inEndpoint = null;
    
        // Trova l'endpoint di ingresso (IN)
        for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
            UsbEndpoint endpoint = usbInterface.getEndpoint(i);
            if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
                inEndpoint = endpoint;
                break;
            }
        }
    
        if (inEndpoint == null) {
            BA.Log("Errore: Endpoint di ingresso (IN) non trovato.");
            return null;
        }
    
        ByteBuffer buffer = ByteBuffer.allocate(512); // Buffer più grande per accumulare i dati
        int bytesRead;
        int totalBytesRead = 0;
    
        long startTime = System.currentTimeMillis();
        long timeout = 3000; // 3 secondi
    
        while (System.currentTimeMillis() - startTime < timeout) {
            byte[] tempBuffer = new byte[128];
            bytesRead = connection.bulkTransfer(inEndpoint, tempBuffer, tempBuffer.length, 500);
            if (bytesRead > 0) {
                buffer.put(tempBuffer, 0, bytesRead);
                totalBytesRead += bytesRead;
            } else {
                break;
            }
        }
    
        if (totalBytesRead > 0) {
            byte[] receivedData = Arrays.copyOf(buffer.array(), totalBytesRead);
            BA.Log("Dati ricevuti (" + totalBytesRead + " byte): " + bytesToHex(receivedData));
            return receivedData;
        } else {
            BA.Log("Timeout: Nessuna risposta ricevuta.");
            return null;
        }
    }
 
This API is wrapped with the USB library.
uhm what means erel? yes this is a piece of code of a java class the i call with my B4A app, but i dont understand when you say "api is wrapped with the usb library", i just use the usb.android default library and i found this type of function
 
Upvote 0
i decide to use the UsbSerial and AsyncStreams in B4A method but i obtained this:

Log:
USB Connessa
InputStream: anywheresoftware.b4a.objects.UsbSerial$1@305530a
OutputStream: anywheresoftware.b4a.objects.UsbSerial$2@c4d977b
Device Name: /dev/bus/usb/001/004
Device ID : 0x3EC
ProductId : 0x4200
VendorId : 0x66F
asstream1 inizializzato
Messaggio inviato con successo
Error: java.lang.NullPointerException: Attempt to invoke interface method 'int com.hoho.android.usbserial.driver.UsbSerialDriver.read(byte[], int)' on a null object reference



ConncetionUSBSerialPort and Send AsyncStream Message:
Sub btnTest_Click
    Dim device     As Int = 1
    Dim info       As String
    Dim deviceName As String
    Dim deviceId   As String
    Dim productId  As String
    Dim vendorId   As String
    Dim msg()      As Byte
    
    'Controllo se è presente un dispositivo USB
    If usb1.UsbPresent(device) = usb1.USB_NONE Then : Msgbox("Nessuna USB-IrDa Rilevaya, Collegane una e riprova", "Attenzione") : Return : End If
    
        'mi  da errore con: DRIVER_CDCACM | DRIVER_PROLIFIC
        'non da errore con: DRIVER_FTDI   | DRIVER_SILABS
        'con DRIVER_SILABS ha inviato ma da questo errore: Error: java.lang.NullPointerException: Attempt to invoke interface method 'int com.hoho.android.usbserial.driver.UsbSerialDriver.read(byte[], int)' on a null object reference
    
    'Se è presente, ne verifico i permessi
    If (usb1.HasPermission(device)) Then
        usb1.SetCustomDevice(usb1.DRIVER_SILABS, 0x66F, 0x4200)
        If usb1.Open(2400,1) <> usb1.USB_NONE Then
            Log("USB Connessa")
            'inizializzo lo Stream
            Log("InputStream: " & usb1.GetInputStream)
            Log("OutputStream: " & usb1.GetOutputStream)
            astreams1.Initialize(usb1.GetInputStream, usb1.GetOutputStream, "astreams1")
        Else
            Log("Errore nella connessione della USB")
        End If
    Else
        usb1.RequestPermission(device)
        Return
    End If

    ' Stampare VID e PID
    info       = usb1.DeviceInfo(device)
    deviceName = ExtractValue(info, "DeviceName : ")
    deviceId   = ExtractValue(info, "Device ID : ")
    productId  = ExtractValue(info, "ProductId : ")
    vendorId   = ExtractValue(info, "VendorId : ")
    Log("Device Name:   " & deviceName)
    Log("Device ID  :   " & deviceId)
    Log("ProductId  :   " & productId)
    Log("VendorId   :   " & vendorId)
    
    ' Configurare i parametri seriali
    usb1.SetParameters(115200, usb1.DATABITS_8, usb1.STOPBITS_1, usb1.PARITY_NONE)

    ' Messaggio da inviare
    msg = Array As Byte(0x05, 0x06, 0x40, 0x00, 0x08, 0x01, 0x5B, 0x95)
    
    If(Not(astreams1.IsInitialized)) Then
        Log("asstream1 non inizializzato, impossibile inviare il msg")
        Return
    Else
        Log("asstream1 inizializzato")
        ' Scrivere il messaggio sulla porta seriale
        'astreams1.Write(msg)
        astreams1.Write("abcde".GetBytes("UTF8"))
        Log("Messaggio inviato con successo")

        ' Chiudere la connessione
        usb1.Close
        End If
End Sub

Sub Astreams1_NewData (Buffer() As Byte)
    ' You must check for DeviceInfo or analyze Buffer data to know what is connected to the USB
    ' The order of the USB could change as you plug them and could change when changing the hub port they are connected to
    Log("NewData 1")
    Log(BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub

Sub AStreams1_Error
    Log("Error: " & LastException.Message)
    astreams1.Close
End Sub

Sub Astreams1_Terminated
    Log("Terminated")
    astreams1.Close
End Sub
 
Upvote 0
Top