Hello.
I gathered some bits and pieces on the tutorials, examples and so on and was able to developed an app that comnunicates between PCs and Android devices over Wifi and Bluetooth using AsyncStreamsObject.
It works both ways (PC->Android and Android->PC) with Wifi, but when I try to use Bluetooth, it can only send data from Android to PC (Android->PC). Whenever I try sending data from PC to Android (PC->Android), B4A complains about CRC not matching.
Can you take a look at the code and offer some corrections?
B4A Code
B4J Code
I gathered some bits and pieces on the tutorials, examples and so on and was able to developed an app that comnunicates between PCs and Android devices over Wifi and Bluetooth using AsyncStreamsObject.
It works both ways (PC->Android and Android->PC) with Wifi, but when I try to use Bluetooth, it can only send data from Android to PC (Android->PC). Whenever I try sending data from PC to Android (PC->Android), B4A complains about CRC not matching.
Can you take a look at the code and offer some corrections?
B4A Code
B4X:
#Region Activity Attributes
#FullScreen: False
#IncludeTitle: True
#End Region
Sub Process_Globals
Private BTAdmin As BluetoothAdmin
Private serial1 As Serial
Private btDevices As List
Type NameAndMac (name As String, mac As String)
Private searchInProgress As Boolean
Private astreamO As ASyncStreamsObject
Private server As ServerSocket
Private client As Socket
Private port As Int = 32118
Private Tipo_Conexao As String
End Sub
Sub Globals
Dim spnrPairedDevices As Spinner
Dim btnConnectBT As Button
Dim lblWifiStatus As Label
Dim lblBTStatus As Label
Dim btnChooseFile As Button
Dim lblProgress As Label
Dim lblFile As Label
Dim btnBTSearch As Button
Private lbl_DB_Name As Label
Private Label1 As Label
Private rdo_Wifi As RadioButton
Private rdo_BT As RadioButton
Private rdo_Remoto As RadioButton
Private Label2 As Label
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("1")
Activity.Title = "Data Transfer"
Activity.AddMenuItem("Disconnect", "mnuDisconnect")
If FirstTime Then
btDevices.Initialize
BTAdmin.Initialize("Admin")
astreamO.Initialize(Me, "astreamO")
server.Initialize(port, "server")
client.Initialize("client")
End If
End Sub
Sub Activity_Resume
spnrPairedDevices.Clear
For Each nm As NameAndMac In btDevices
spnrPairedDevices.Add(nm.name)
Next
'try to turn on Bluetooth if it is disabled
If BTAdmin.IsEnabled = False Then
If BTAdmin.Enable = False Then
ToastMessageShow("Error enabling Bluetooth adapter", True)
Else
ToastMessageShow("Enabling Bluetooth adapter... ", False)
'the StateChanged event will be soon raised
End If
End If
server.Listen
End Sub
Sub mnuDisconnect_Click
serial1.Disconnect
server.Close
client.Close
End Sub
Sub Activity_Pause (UserClosed As Boolean)
If UserClosed Then
astreamO.Close
serial1.Disconnect
client.Close
End If
End Sub
Sub btnConnectBT_Click
If spnrPairedDevices.SelectedIndex = -1 Then Return
Dim nm As NameAndMac = btDevices.Get(spnrPairedDevices.SelectedIndex)
serial1.Initialize("serial1")
serial1.Connect(nm.mac)
Tipo_Conexao = "Bluetooth"
SetBTStatus("Conectado")
btnChooseFile.Enabled = True
End Sub
'starts a search process
Sub btnBTSearch_Click
spnrPairedDevices.Clear
btDevices.Clear
If BTAdmin.StartDiscovery = False Then
ToastMessageShow("Error on search start...", True)
Else
searchInProgress = True
SetBTStatus("Searching Bluetooth...")
End If
End Sub
Sub SetBTStatus(status As String)
lblBTStatus.Text = status
End Sub
Sub Admin_DiscoveryFinished
searchInProgress = False
If spnrPairedDevices.Size = 0 Then
SetBTStatus("No Bluetooth device found")
Else
SetBTStatus(spnrPairedDevices.Size & " found.")
End If
End Sub
Sub Admin_DeviceFound (Name As String, MacAddress As String)
Log(Name & ":" & MacAddress)
spnrPairedDevices.Add(Name)
Dim nm As NameAndMac
nm.Initialize
nm.Name = Name
nm.mac = MacAddress
btDevices.Add(nm)
SetBTStatus("Searching... (" & btDevices.Size & " found")
End Sub
' This is thr code that transfers data from Android to PC
Sub btnChooseFile_Click
'myFile
If File.Exists(File.DirDefaultExternal, "myFile.txt") Then
astreamO.WriteFile("myFile.txt", File.DirDefaultExternal, "myFile.txt")
lblFile.Text = "Transmitting myFile.txt"
End If
Msgbox("Data sent!","Confirmed")
End Sub
Sub StartAstream(s As Socket)
astreamO.Start(s.InputStream, s.OutputStream)
SetUIState
End Sub
Sub StartAstream_Serial(s As Serial)
astreamO.Start(s.InputStream, s.OutputStream)
SetUIState
End Sub
Sub AstreamO_Terminated
SetUIState
client.Close
client.Initialize("client")
serial1.Disconnect
serial1.Initialize("")
End Sub
Sub client_Connected (Successful As Boolean)
If Successful Then
StartAstream(client)
Tipo_Conexao = "Wifi"
Else
ToastMessageShow("Error: " & LastException, True)
End If
End Sub
Sub Server_NewConnection (Successful As Boolean, NewSocket As Socket)
If Successful Then
StartAstream(NewSocket)
Else
ToastMessageShow("Error: " & LastException, True)
End If
End Sub
Sub astreamO_NewObject(Key As String, Value As Object)
Dim fileName As String = Value
Log("Received file " & Key & " File size: " & File.Size(astreamO.TempFolder, fileName))
If File.Exists(File.DirDefaultExternal, Key) Then
File.Delete(File.DirDefaultExternal, Key)
End If
File.Copy(astreamO.TempFolder, fileName, File.DirDefaultExternal, Key)
Log(File.ListFiles(File.DirDefaultExternal))
End Sub
Sub astreamO_ObjectSent (Key As String)
Log("Object sent: " & Key)
End Sub
Sub Serial1_Connected (Success As Boolean)
ProgressDialogHide
If Success = False Then
Log(LastException.Message)
ToastMessageShow("Error on connecting: " & LastException.Message, True)
btnChooseFile.Enabled = False
Else
Log("Connected: " & Success)
Tipo_Conexao = "Bluetooth"
StartAstream_Serial(serial1)
End If
End Sub
B4J Code
B4X:
#Region Project Attributes
#MainFormWidth: 500
#MainFormHeight: 500
#End Region
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Private sp As Serial
Private astreamO As AsyncStreamsObject
Private client As Socket
Private port As Int = 32118
Dim btnConnect As Button
Private btnSendFile As Button
Private cmbPort As ComboBox
Private btn_BT_Connect As Button
Private Tipo_Conexao As String
Private diretorio As String
End Sub
Sub AppStart (Form1 As Form, Args() As String)
MainForm = Form1
MainForm.Title = "myApp"
MainForm.RootPane.LoadLayout("Up_Data") 'Load the layout file.
MainForm.Show
MainForm.BackColor = fx.Colors.White
sp.Initialize("")
cmbPort.Items.AddAll(sp.ListPorts)
End Sub
Sub MainForm_Closed
astreamO.Close
sp.Close
End Sub
Sub btnConnect_Action
astreamO.Initialize(Me, "astreamO")
client.Initialize("client")
client.Connect(txtIP.Text,port, 30000)
File.WriteString(File.DirApp, "ip.txt", txtIP.Text)
Tipo_Conexao = "Wifi"
End Sub
Sub StartAstream(s As Socket)
astreamO.Start(s.InputStream, s.OutputStream)
End Sub
Sub StartAstream_Serial(s As Serial)
astreamO.Start(s.GetInputStream, s.GetOutputStream)
End Sub
Sub client_Connected (Successful As Boolean)
If Successful Then
StartAstream(client)
Tipo_Conexao = "Wifi"
Else
Log("Error: " & LastException)
txt_Eventos.Text = txt_Eventos.Text & "Error: " & LastException & CRLF
End If
End Sub
Sub Server_NewConnection (Successful As Boolean, NewSocket As Socket)
If Successful Then
StartAstream(NewSocket)
fx.Msgbox(MainForm, LastException.Message, "Exception")
Else
fx.Msgbox(MainForm, "Error", "Error")
End If
End Sub
Sub AstreamO_Terminated
client.Close
client.Initialize("client")
sp.Close
sp.Initialize("")
End Sub
Sub astreamO_NewObject(Key As String, Value As Object)
Dim fileName As String = Value
Log("File " & Key & " received - size: " & File.Size(astreamO.TempFolder, fileName))
If File.Exists(diretorio, Key) Then
File.Delete(diretorio, Key)
End If
File.Copy(astreamO.TempFolder, fileName, diretorio, Key)
End Sub
Sub btnSendFile_Action
If astreamO.IsConnected = True Then
Dim res As Int
diretorio = File.DirData("myApp")
astreamO.WriteFile("zEPI.cfg", diretorio & "\Temp", "txtfile.txt")
Else
fx.Msgbox(MainForm, "Not Connected", "Warning")
End If
End Sub
Sub btn_BT_Connect_Action
Tipo_Conexao = "Bluetooth"
Try
sp.Initialize("")
sp.Open(cmbPort.Value)
Catch
If LastException.Message.Contains("Port busy.") = True Then
Dim rspt As Int
rspt = fx.Msgbox2(MainForm, "Port " & cmbPort.Items.Get(cmbPort.SelectedIndex) & " is busy" & CRLF & CRLF & "Want to close it and try again?", "Warning", "Yes", "", "No", fx.MSGBOX_CONFIRMATION)
If rspt = fx.DialogResponse.POSITIVE Then
sp.Close
sp.Initialize("")
End If
End If
Return
End Try
astreamO.Initialize(Me, "astreamO")
StartAstream_Serial(sp)
End Sub