Android Question Occasionally bluetooth not receive the data stream

fifiddu70

Well-Known Member
Licensed User
Longtime User
hello everyone, I have made an application that serves as a case for restaurants and another that sends the orders in this case via the bluetooth with texwriter.flush.
the application that sends commands to checkout connects and immediately after transmitting the data stream disconnects freeing other devices to send more comande, everything seems to work fine, but every so often the case it receives the commands, while on the transmitting adding fails me that the command was sent, of course, I use a msgbox but I can not be certain of the order sent, how come the chest every so often does not receive the commands? I post my code I use on the receiving party and that is the case, I'd like to make sure that the commands having been regularly sent by the device that transmits the commands but also want to understand because sometimes the cash is not getting it.
this my code for receive the order from device.
B4X:
#Region  Project Attributes
    #ApplicationLabel: Cassa
    #VersionCode: 1
    #VersionName: 1.0
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: True   
    #BridgeLogger: True
#End Region

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

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim BtAdmin As BluetoothAdmin
    Dim Serial As Serial
    Dim connected As Boolean
    Dim BTConnection As Serial
    Dim Printer As TextWriter
    Dim TextWriter As TextWriter
    Dim TextReader As TextReader
    Dim Timer1 As Timer
    Dim timer2 As Timer
    Dim timer3 As Timer
    Dim timer4 As Timer
    Dim p As Phone
    Dim pw As PhoneWakeState
    Dim dbSQL As SQL
    Dim dbCursor As Cursor
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
       
    Dim txtLog As EditText
    Dim txtSend As EditText
    Private pnlbase As Panel
    Private txttavolo As EditText
    Private txttavolozza As EditText
    Private txtdisplay As EditText
    Private lbltavolo As Label
    Private btnapritavolo As Button
    Private btneliminatavolo As Button
  
End Sub


Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    If FirstTime Then
        Serial.Initialize("Serial")
        BtAdmin.Initialize("BlueTooth")
        BTConnection.Initialize("Printer")
       
       
    End If
    Activity.LoadLayout("cassa")
   
    Timer1.Initialize("Timer1", 200)
    timer2.Initialize("timer2",8000)
    timer3.Initialize("timer3",2000)
    timer4.Initialize("timer4",3000)

    mp1.Initialize
    p.SetScreenOrientation(1)
    pnlsetup.Visible=False
    pnlbase.SetLayout(0%x,0%y,100%x,100%y)
    txtdisplay.SetLayout(1%x,1%y,98%x,85%y)
    lbltavolo.SetLayout(1%x,84%y,30%x,8%y)
    txttavolo.SetLayout(1%x,90%y,15%x,8%y)
    btnapritavolo.SetLayout(18%x,89%y,15%x,10%y)
    btneliminatavolo.SetLayout(35%x,89%y,20%x,10%y)
    
    txtLog.Color=Colors.White
    txtSend.Color=Colors.White
    txtdisplay.Color=Colors.White
   
    If File.Exists(File.DirInternal, "intestazione.db") = False Then ' se non trova il database  allora lo copia usando il rigo di sotto altrimenti non fa nulla.
        File.Copy(File.DirAssets, "intestazione.db", File.DirInternal, "intestazione.db")
    Else
       
    End If
    dbSQL.Initialize(File.DirInternal, "intestazione.db", True) ' inizializza il database
   
End Sub
Sub Activity_KeyPress (KeyCode As Int)  As Boolean
    Dim answ As Int
    If KeyCode = KeyCodes.KEYCODE_BACK Then
        answ = Msgbox2("Sei sicuro di voler uscire dal programma?","AVVISO!!","SI","","NO",Null)
        If answ = DialogResponse.POSITIVE Then
            ExitApplication
            Return False
        Else
            Return True
   
        End If
    End If
End Sub
Sub Activity_Resume
    pw.KeepAlive(True)
   
    If Serial.IsEnabled = False Then
        Dim i As Intent
        i.Initialize("android.settings.BLUETOOTH_SETTINGS", "")
        StartActivity(i)
   
        Else
        Serial.Listen 'listen for incoming connections
       
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    pw.ReleaseKeepAlive
   
End Sub
Sub txttavolo_TextChanged (Old As String, New As String)

End Sub
Sub Timer1_Tick
    If connected Then
       
        If TextReader.Ready Then 'check if there is any data waiting to be read
            txtLog.Text = txtLog.Text & TextReader.ReadLine & CRLF
            txtLog.SelectionStart = txtLog.Text.Length
            txtdisplay.Text=txtLog.Text
           
           
            Dim k As Int
            k = txtLog.Text.IndexOf("id ")' eseguo la ricerca di Tavolo: per poter estrapolare solo la cifra da inserire nella txteuro.text
            If k >= 0 Then
                txttavolo.Text = txtLog.Text.SubString2(k + 2, txtLog.Text.Length)' da qui estrapolo il tavolo
                               
            End If
               
        End If
    End If
   
   
End Sub
Sub txtLog_TextChanged (Old As String, New As String)
    If txtdisplay.Text = txtLog.Text Then
        timer2.Enabled=False
       
    Else
        timer2.Enabled=True
       
       
    End If
End Sub

Sub timer2_Tick
    timer2.Enabled=False
    timer3.Enabled=True
End Sub

Sub timer3_Tick
    Timer1.Enabled=False
   
    btnSend_Click
    timer3.Enabled=False
End Sub
Sub btnSend_Click
   
   Dim PairedDevices As Map
    PairedDevices = BTConnection.GetPairedDevices
    Dim l As List
    Dim DeviceName, MacAddress As String
    l.Initialize
    For i = 0 To PairedDevices.Size - 1 'Check all devices
        l.Add(PairedDevices.GetKeyAt(i))
        DeviceName=PairedDevices.Getkeyat(i)
        MacAddress=PairedDevices.GetValueAt(i)
        Log(DeviceName & " -> " & MacAddress)
        If DeviceName.Contains("Thermal") Then 'Insert the BT-Name of the printer or use the MAC address
            Exit
        End If
    Next
    BTConnection.Connect(MacAddress)
   

   
End Sub
Sub Serial_Connected (Success As Boolean)
       
    If Success Then
        ToastMessageShow("Connessione riuscita", False)
        txtdisplay.Text=""
        TextReader.Initialize(Serial.InputStream)
        TextWriter.Initialize(Serial.OutputStream)
        Timer1.Enabled = True
        connected = True
    Else
        connected = False
        'Timer1.Enabled = False
        Msgbox(LastException.Message, "Errore di connessione.")
       
    End If
           
End Sub


Sub Printer_Connected (Success As Boolean)   
    If Success Then
        Printer.Initialize2(BTConnection.OutputStream,"windows-1252") 'important to print f.e. German/French chars
        'PrintBuffer=Chr(27)&"t"&Chr(16)&"Hello öäüßéèê" 'Set codepage 1252
        Printer.WriteLine(txtdisplay.Text)
        Printer.Flush
        Printer.Close
        BTConnection.Disconnect 'disable this if you like
        ToastMessageShow("Disconnessione riuscita", False)
    Else
        Msgbox("Nessuna stampante trovata...","ERRORE DI STAMPA")
        timer4.Enabled=True
    End If
  
Sub timer4_Tick
   BTConnection.Disconnect
   timer4.Enabled=False
End Sub
   
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I have made an application that serves as a case for restaurants and another that sends the orders in this case via the bluetooth with texwriter.flush.
You should never use TextWriter or TextReader with Bluetooth or any other network streams. It will eventually fail and the program will hang.

1. You should use AsyncStreams.
2. Move all the communication code to a service.
 
Upvote 0
Top