Android Question Send files through usb port...

Ulises-25

Member
Licensed User
Hello everyone, I am newbie and I want to make an application that can select a file in a certain folder and send it through the usb port, I think I have to use felusbserial libraries and AsyncStream but I have very little knowledge about it any help is appreciated beforehand
 

Ulises-25

Member
Licensed User
Is an arduino with 1mb of ssram receives files up to 115.2 kbps without any problem. I already tried it with an application of FTDI, my goal is an application that will work for cnc type machines, the design files created in a pc will be sent to a tablet via wifi the user of the machine will select a file that will be sent via usb to the Interface between the tablet and the machine in this case the arduino. These files contain coordinates for the movement of the machine the application will show them in an xy chart. Any help will be welcome and in advance thank you very much.
 
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
Is an arduino with 1mb of ssram receives files up to 115.2 kbps without any problem. I already tried it with an application of FTDI, my goal is an application that will work for cnc type machines, the design files created in a pc will be sent to a tablet via wifi the user of the machine will select a file that will be sent via usb to the Interface between the tablet and the machine in this case the arduino. These files contain coordinates for the movement of the machine the application will show them in an xy chart. Any help will be welcome and in advance thank you very much.

Will you be using g-code?
If so, most CNC arduino projects use the serial connection (USB or other) to receive the G-code so the interpreter can act... This way you only need to use the PC/tablet combo to share the G-code, and serial to send each g-code string to the arduino.
 
Upvote 0

Ulises-25

Member
Licensed User
No, it's a type of ternary code, which the arduino will take care of. I am trying to use part of the code of the file transfer and felusbserial examples of Erel, for you it is easy, not for me that I am new to programming android applications, any help will be infinitely thank you.
 
Upvote 0

Ulises-25

Member
Licensed User
Hi Erel, I'm lost, I use part of code of the examples file transfer and serial usb and when I select the file to transfer it stays in sending, as I'm missing the connection that sends it through the usb port, can you help me? Thank you.
B4X:
#Region  Project Attributes
    #ApplicationLabel: USB Serial Example
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: false
#End Region

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

Sub Process_Globals
    Private CC As ContentChooser
    Dim usb As UsbSerial   
    Dim astreams As AsyncStreams
End Sub

Sub Globals
    Private btnChooseFile As Button
    Private lblFile As Label
    Private lblProgress As Label
    Private ProgressBar1 As ProgressBar
End Sub

Sub Activity_Create(FirstTime As Boolean)
        If FirstTime Then
        StartService(FileTransfer)
        CC.Initialize("CC")
        End If
    Activity.LoadLayout("1")
    btnChooseFile.Enabled = False
    If usb.UsbPresent(1) = usb.USB_NONE Then
        Log("Msgbox - no device")
        Msgbox("No USB device or accessory detected!", "Error")
        Log("Msgbox - returned")
        Return
    End If
    Log("Checking permission 1")
    If (usb.HasPermission(1)) Then       
        Dim dev As Int
        dev = usb.Open(19200, 1)   
        If dev <> usb.USB_NONE Then
            Log("Connected successfully! 1")
            btnChooseFile.Enabled = True           
            astreams.Initialize(usb.GetInputStream, usb.GetOutputStream, "astreams")
        Else
            Log("Error opening USB port 1")
        End If
    Else
        usb.RequestPermission(1)
    End If
End Sub


Public Sub UpdateProgress
    lblProgress.Text = FileTransfer.progressText
    ProgressBar1.Progress = FileTransfer.progressValue
    lblFile.Text = FileTransfer.lblFile
End Sub

Sub btnChooseFile_Click
    CC.Show("*/*", "Choose file to send")
End Sub

Sub CC_Result (Success As Boolean, Dir As String, FileName As String)
    If Success Then
        Dim normalizedFile As String = GetPathFromContentResult(FileName)
        If File.Exists("", normalizedFile) == False Then
            ToastMessageShow("File is not accessible.", True)
            Return
        End If
        CallSubDelayed3(FileTransfer, "SendFile", "", normalizedFile)
    Else
        If LastException.IsInitialized Then ToastMessageShow(LastException.Message, True)
    End If
End Sub

'this code tries to retrieve the real file from the uri
Sub GetPathFromContentResult(UriString As String) As String
    If UriString.StartsWith("/") Then Return UriString 'If the user used a file manager to choose the image
    Dim Proj() As String
    Proj = Array As String("_data")
    Dim Cursor As Cursor
    Dim r As Reflector
    Dim Uri As Object
    Uri = r.RunStaticMethod("android.net.Uri", "parse", _
        Array As Object(UriString), _
        Array As String("java.lang.String"))
    r.Target = r.GetContext
    r.Target = r.RunMethod("getContentResolver")
    Cursor = r.RunMethod4("query", _
    Array As Object(Uri, Proj, Null, Null, Null), _
    Array As String("android.net.Uri", _
        "[Ljava.lang.String;", "java.lang.String", _
        "[Ljava.lang.String;", "java.lang.String"))
   
    Cursor.Position = 0
    Dim res As String
    res = Cursor.GetString("_data")
    Cursor.Close
    Return res
End Sub

Sub Exit_Click
    astreams.Close
    usb.Close
    ExitApplication
End Sub

Sub AStreams1_Error
    Log("Error: " & LastException)
    astreams.Close
End Sub
Sub Astreams1_Terminated
    Log("Terminated")
    astreams.Close
End Sub



Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
B4X:
#Region  Service Attributes
    #StartAtBoot: False
#End Region

Sub Process_Globals
    Public progressValue As Int
    Public progressText, lblFile As String
    Public SendingFile As Boolean
    Public ReceivingFile As Boolean
    Private timer1 As Timer
    Private astream As AsyncStreams
    Private countingStream As CountingInputStream
    Private totalSizeForSending As Long
    Private currentFile As String
End Sub

Sub Service_Create
    timer1.Initialize("timer1", 1000)
End Sub


Sub Service_Start (StartingIntent As Intent)

End Sub
Private Sub UpdateUI
    CallSub(Main, "UpdateUI")
End Sub
Private Sub UpdateProgress
    CallSub(Main, "UpdateProgress")
End Sub

Public Sub SendFile(Dir As String, FileName As String)
    Dim totalSizeForSending As Long = File.Size(Dir, FileName)
    Dim In As InputStream = File.OpenInput(Dir, FileName)
    countingStream.Initialize(In)
    currentFile = FileName.SubString(FileName.LastIndexOf("/") + 1)
    astream.Write(currentFile.GetBytes("UTF8")) 'write the file name
    astream.WriteStream(countingStream, totalSizeForSending)
    lblFile = "Sending: " & currentFile
    timer1.Enabled = True
    SendingFile = True
    UpdateProgress
End Sub

Private Sub StartAStream (In As InputStream, out As OutputStream)
    Log("StartAStream")
    astream.InitializePrefix(In, True, out, "astream")
    If File.ExternalWritable Then
        astream.StreamFolder = File.DirDefaultExternal
    Else
        astream.StreamFolder = File.DirInternalCache
    End If
End Sub

Sub Astream_Error
    Log("Error: " & LastException)
    astream.Close
    AStream_Terminated 'manually call this method as it will not be called
    'when we explicitly close the connection.
End Sub

Sub AStream_Terminated
    timer1.Enabled = False
    ReceivingFile = False
    SendingFile = False
    UpdateUI
End Sub

Sub AStream_NewStream (Dir As String, FileName As String)
    'this event is raised when a file was received successfully
    Timer1_Tick
    timer1.Enabled = False
    lblFile = currentFile & " completed"
    ReceivingFile = False
    UpdateProgress
    File.Copy(Dir, FileName, Dir, currentFile)
    File.Delete(Dir, FileName)
End Sub

Sub AStream_NewData (Buffer() As Byte)
    'get the file name
    timer1.Enabled = True
    currentFile = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    lblFile = "Receiving file: " & currentFile
    ReceivingFile = True
End Sub

Sub Timer1_Tick
    Dim count, total As Long
    If SendingFile Then
        count = countingStream.count
        total = totalSizeForSending
        If count = total Then
            lblFile = currentFile & " completed"
            'stop the timer.
            'when a file is received the NewStream event will be raised
            SendingFile = False
            timer1.Enabled = False
        End If
    Else If ReceivingFile Then
        count = astream.StreamReceived
        total = astream.StreamTotal
    End If
    progressValue = 100 * count / total
    progressText = NumberFormat2(count / 1000, 0, 0, 0, True) & _
            "kb / " & NumberFormat2(total / 1000, 0, 0, 0, True) & "kb"
    UpdateProgress       
End Sub

Sub Service_Destroy

End Sub
 
Upvote 0

Ulises-25

Member
Licensed User
Hello Erel, in the previous comment forget to tell you that the files I handle are binary, so I have been reading not any class handles it.
 
Upvote 0

Ulises-25

Member
Licensed User
Help ... I am stuck with this application when selecting a file only sends to the serial port the name, the original application uses asyncrostream in prefix mode, but according to investigate this mode is not supported by serial usb, which code I am missing to send me the file? In advance thanks any help.
 

Attachments

  • files to usb.zip
    9.8 KB · Views: 304
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top