Android Question Bluetooth connection java error

Marc DANIEL

Well-Known Member
Licensed User
How can I avoid blocking the Bluetooth connection of my Android Smartphone with a B4R device via an HC-05 module?
The Java error message is always the same: "java.io.IOException: read failed, socket might closes or timeout, read ret: -1"

This never happens on the first connection, the error is generated by the 2nd connection attempt.
And if I restart my Smartphone, this error does not occur.

Is a B4A code change planned to prevent these Java bugs from recurring?
BluetoothAsynchStream.bas:
Sub Class_Globals
    Private Admin As BluetoothAdmin
    Public Astreams As AsyncStreams
    Private Serial As Serial
    Private PH As Phone
    Private mParent As Object
    Private mEventName As String
    Private lblStatus As Label
    Private ProgressBar1 As ProgressBar
    Private GenericDeviceName, DeviceName As String
    Public BluetoothState, ConnectionState, DeviceFound As Boolean
    Private DeviceName = "HC-05", DeviceMacAdress As String
    Public CharSet = "UTF-8" As String
    Private sb As StringBuilder
    Public State As String
    End Sub


Public Sub Initialize(Parent As Object, EventName As String, StatusLabel As Label, Pgb As ProgressBar)
    mParent = Parent
    mEventName = EventName
    lblStatus = StatusLabel
    Admin.Initialize("Admin")
    Serial.Initialize("Serial")
    ProgressBar1 = Pgb
    sb.Initialize
    
    If Admin.IsEnabled = False Then
        If Admin.Enable = False Then
            ToastMessageShow("Bluetooth module not available", True)
        Else
            ToastMessageShow("Bluetooth module available...", False)
        End If
    Else
        BluetoothState = True
    End If
End Sub

Public Sub Connect(Name As String)
    GenericDeviceName = Name
    Dim success As Boolean = Admin.StartDiscovery
    If success = False Then
        lblStatus.Text = "Search process error"
    Else
        lblStatus.Text = "Device search in progress"
        'ProgressBar1.Visible = True
    End If
End Sub

Public Sub Disconnect
    If Astreams.IsInitialized Then Astreams.Close
    If Serial.IsInitialized Then Serial.Disconnect
End Sub

Private Sub Admin_DeviceFound (Name As String, MacAddress As String)
    Log(Name & ":" & MacAddress)
    If Name.Contains(GenericDeviceName) Then
        Log(GenericDeviceName & " found")
        DeviceName = Name
        DeviceMacAdress = MacAddress
        If PH.SdkVersion <= 33 Then
            Admin.CancelDiscovery
            lblStatus.Text = GenericDeviceName & " found"
        Else
            lblStatus.Text = GenericDeviceName & " found, please wait."
        End If
    End If
End Sub

Private Sub Admin_DiscoveryFinished
    If DeviceName = "" Then
        lblStatus.Text = "Module " & GenericDeviceName & " non détecté"
        Msgbox2Async("The HC-05 Bluetooth Module does not seem to be powered, turn on the car, the red mini-LED on the module should flash quickly then press the “Connect” button again.","Check the module power", "OK", "", "", Null, True)
    Wait For Msgbox_Result (Result As Int)
        Else
        lblStatus.Text = "Connection to " & GenericDeviceName
        Serial.Connect(DeviceMacAdress)
    End If
End Sub

Private Sub Admin_StateChanged (NewState As Int, OldState As Int)
    Log("Status change: " & NewState)
    lblStatus.Text = "Actual status: " & NewState
    BluetoothState = NewState = Admin.STATE_ON
End Sub

Sub Serial_Connected (Success As Boolean)
    Private msg As String
    If Success = True Then
        If Astreams.IsInitialized Then Astreams.Close
        Astreams.Initialize(Serial.InputStream, Serial.OutputStream, "Astreams")
        msg = "HC05 Bluetooth Module connected"
        ProgressBar1.Visible = False
        
    Else
        Log(LastException.Message)
        msg = LastException.Message
    End If
    lblStatus.Text = msg
    CallSubDelayed2(mParent, mEventName & "_Connected", Success)
End Sub

Public Sub SendBytes(Buffer() As Byte)
    Astreams.Write(Buffer)
End Sub

Public Sub SendText(Text As String)
    Astreams.Write(Text.GetBytes(CharSet))
End Sub

Public Sub Ast_NewText(Text As String)
    CallSubDelayed2(mParent, mEventName & "_NewText", Text)
    Log(Text)
End Sub

Public Sub WriteText(Text As String)
    Astreams.Write(Text.GetBytes(CharSet))
End Sub

Public Sub WriteBytes(Buffer() As Byte)
    Astreams.Write(Buffer)
End Sub

Private Sub Astreams_NewData (Buffer() As Byte)
    Dim newDataStart As Int = sb.Length
    sb.Append(BytesToString(Buffer, 0, Buffer.Length, CharSet))
    Dim s As String = sb.ToString
    Dim start As Int = 0
    For i = newDataStart To s.Length - 1
        Dim c As Char = s.CharAt(i)
        If i = 0 And c = Chr(10) Then '\n...
            start = 1
            Continue
        End If
        If c = Chr(10) Then
            CallSubDelayed2(mParent, mEventName & "_NewText", s.SubString2(start, i))
            start = i + 1
        Else If c = Chr(13) Then
            CallSubDelayed2(mParent, mEventName & "_NewText", s.SubString2(start, i))
            If i < s.Length - 1 And s.CharAt(i + 1) = Chr(10) Then
                i = i + 1
            End If
            start = i + 1
        End If
    Next
    If start > 0 Then sb.Remove(0, start)
End Sub

Private Sub Astreams_Terminated
    CallSubDelayed(mParent, mEventName & "_Finished")
End Sub

Private Sub Astreams_Error
    Log("error: " & LastException)
    Astreams.Close
    CallSubDelayed(mParent, mEventName & "_Finished")
End Sub

Public Sub Close
    Astreams.Close
End Sub
 

Marc DANIEL

Well-Known Member
Licensed User
How can I avoid blocking the Bluetooth connection of my Android Smartphone with a B4R device via an HC-05 module?
The Java error message is always the same: "java.io.IOException: read failed, socket might closes or timeout, read ret: -1"

This never happens on the first connection, the error is generated by the 2nd connection attempt.
And if I restart my Smartphone, this error does not occur.

Is a B4A code change planned to prevent these Java bugs from recurring?
BluetoothAsynchStream.bas:
Sub Class_Globals
    Private Admin As BluetoothAdmin
    Public Astreams As AsyncStreams
    Private Serial As Serial
    Private PH As Phone
    Private mParent As Object
    Private mEventName As String
    Private lblStatus As Label
    Private ProgressBar1 As ProgressBar
    Private GenericDeviceName, DeviceName As String
    Public BluetoothState, ConnectionState, DeviceFound As Boolean
    Private DeviceName = "HC-05", DeviceMacAdress As String
    Public CharSet = "UTF-8" As String
    Private sb As StringBuilder
    Public State As String
    End Sub


Public Sub Initialize(Parent As Object, EventName As String, StatusLabel As Label, Pgb As ProgressBar)
    mParent = Parent
    mEventName = EventName
    lblStatus = StatusLabel
    Admin.Initialize("Admin")
    Serial.Initialize("Serial")
    ProgressBar1 = Pgb
    sb.Initialize
   
    If Admin.IsEnabled = False Then
        If Admin.Enable = False Then
            ToastMessageShow("Bluetooth module not available", True)
        Else
            ToastMessageShow("Bluetooth module available...", False)
        End If
    Else
        BluetoothState = True
    End If
End Sub

Public Sub Connect(Name As String)
    GenericDeviceName = Name
    Dim success As Boolean = Admin.StartDiscovery
    If success = False Then
        lblStatus.Text = "Search process error"
    Else
        lblStatus.Text = "Device search in progress"
        'ProgressBar1.Visible = True
    End If
End Sub

Public Sub Disconnect
    If Astreams.IsInitialized Then Astreams.Close
    If Serial.IsInitialized Then Serial.Disconnect
End Sub

Private Sub Admin_DeviceFound (Name As String, MacAddress As String)
    Log(Name & ":" & MacAddress)
    If Name.Contains(GenericDeviceName) Then
        Log(GenericDeviceName & " found")
        DeviceName = Name
        DeviceMacAdress = MacAddress
        If PH.SdkVersion <= 33 Then
            Admin.CancelDiscovery
            lblStatus.Text = GenericDeviceName & " found"
        Else
            lblStatus.Text = GenericDeviceName & " found, please wait."
        End If
    End If
End Sub

Private Sub Admin_DiscoveryFinished
    If DeviceName = "" Then
        lblStatus.Text = "Module " & GenericDeviceName & " non détecté"
        Msgbox2Async("The HC-05 Bluetooth Module does not seem to be powered, turn on the car, the red mini-LED on the module should flash quickly then press the “Connect” button again.","Check the module power", "OK", "", "", Null, True)
    Wait For Msgbox_Result (Result As Int)
        Else
        lblStatus.Text = "Connection to " & GenericDeviceName
        Serial.Connect(DeviceMacAdress)
    End If
End Sub

Private Sub Admin_StateChanged (NewState As Int, OldState As Int)
    Log("Status change: " & NewState)
    lblStatus.Text = "Actual status: " & NewState
    BluetoothState = NewState = Admin.STATE_ON
End Sub

Sub Serial_Connected (Success As Boolean)
    Private msg As String
    If Success = True Then
        If Astreams.IsInitialized Then Astreams.Close
        Astreams.Initialize(Serial.InputStream, Serial.OutputStream, "Astreams")
        msg = "HC05 Bluetooth Module connected"
        ProgressBar1.Visible = False
       
    Else
        Log(LastException.Message)
        msg = LastException.Message
    End If
    lblStatus.Text = msg
    CallSubDelayed2(mParent, mEventName & "_Connected", Success)
End Sub

Public Sub SendBytes(Buffer() As Byte)
    Astreams.Write(Buffer)
End Sub

Public Sub SendText(Text As String)
    Astreams.Write(Text.GetBytes(CharSet))
End Sub

Public Sub Ast_NewText(Text As String)
    CallSubDelayed2(mParent, mEventName & "_NewText", Text)
    Log(Text)
End Sub

Public Sub WriteText(Text As String)
    Astreams.Write(Text.GetBytes(CharSet))
End Sub

Public Sub WriteBytes(Buffer() As Byte)
    Astreams.Write(Buffer)
End Sub

Private Sub Astreams_NewData (Buffer() As Byte)
    Dim newDataStart As Int = sb.Length
    sb.Append(BytesToString(Buffer, 0, Buffer.Length, CharSet))
    Dim s As String = sb.ToString
    Dim start As Int = 0
    For i = newDataStart To s.Length - 1
        Dim c As Char = s.CharAt(i)
        If i = 0 And c = Chr(10) Then '\n...
            start = 1
            Continue
        End If
        If c = Chr(10) Then
            CallSubDelayed2(mParent, mEventName & "_NewText", s.SubString2(start, i))
            start = i + 1
        Else If c = Chr(13) Then
            CallSubDelayed2(mParent, mEventName & "_NewText", s.SubString2(start, i))
            If i < s.Length - 1 And s.CharAt(i + 1) = Chr(10) Then
                i = i + 1
            End If
            start = i + 1
        End If
    Next
    If start > 0 Then sb.Remove(0, start)
End Sub

Private Sub Astreams_Terminated
    CallSubDelayed(mParent, mEventName & "_Finished")
End Sub

Private Sub Astreams_Error
    Log("error: " & LastException)
    Astreams.Close
    CallSubDelayed(mParent, mEventName & "_Finished")
End Sub

Public Sub Close
    Astreams.Close
End Sub
Main Page:
Sub Process_Globals
    Public xui As XUI
    Public rp As RuntimePermissions
End Sub

Sub Globals
    Private BTA As BluetoothAsynchStream
    Private BtnConnect, Sortie As Button
    Private lblStatus, Pilotage As Label
    Private pnlMain As B4XView
    Private Forward, Backward, STOP, TR, TL, Square, Etoile, Pen As ImageView
    Private ProgressBar1 As ProgressBar
    Public DeviceName = "HC-05" As String
    Public Connected As Boolean
    Private x=0, y=0 As Int 'Default values not triggering any turtle maneuvers
    Private BLT As ImageView
    Private turtle As ImageView
    Public Write=False As Boolean
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Main")
    BTA.Initialize(Me, "BTA", lblStatus, ProgressBar1)
    Pilotage.Text=" Welcome aboard the Graphic " & CRLF & "  Turtle Bluetooth cockpit! "
    Pilotage.Text=Pilotage.Text & CRLF & " The commands will appear   " & CRLF & " as soon as the connection is " & CRLF & " established with the turtle."
    Pilotage.Text=Pilotage.Text & CRLF &  CRLF &" Please, press the green " & CRLF & " CONNECTION button! "
End Sub

Sub Activity_Resume
    
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed = True And Connected = True Then
        BTA.SendBytes(Array As Byte(0, 0))
        BTA.Disconnect
    End If
End Sub

Private Sub Activity_PermissionResult (Permission As String, Result As Boolean)
    
End Sub

Sub BtnConnect_Click
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_LOCATION)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        lblStatus.Text = "Status: Permission denied..."
    Else
        BTA.Connect(DeviceName)
    End If
End Sub

Sub Pen_LongClick
    ' pencil up or down
    ' A long press on the PEN key causes the pencil to descend >>> Pen Down
    ' A second long press on the PEN key causes the pencil to rise >>>  Pen Up
    
    If Write = False Then
        Pen.Bitmap = LoadBitmap(File.DirAssets,"Pen_Down.jpg")
        Write = True
        x = 1
        y = 1  'The value y = 1 triggers the lighting of an LED when the pencil is lowered
    Else
        Pen.Bitmap = LoadBitmap(File.DirAssets,"Pen_Up.jpg")
        Write = False
        x = 2
        y = 0
    End If
    BTA.SendBytes(Array As Byte(x,y))
End Sub

Sub Etoile_Click
    x=3
    BTA.SendBytes(Array As Byte(x,y))
End Sub

Sub Square_Click
    x = 4
    BTA.SendBytes(Array As Byte(x,y))
End Sub

Sub Cercle_Click
    x=13
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub STOP_Click
    x=0
    BTA.SendBytes(Array As Byte(x,y))
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
End Sub

Sub Forward_Click 'Forward
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
    x = 5
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub Forward_LongClick 'Quick Forward
    Forward.Bitmap = LoadBitmap(File.DirAssets,"avplus.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
    x=6
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub Backward_Click 'Backward
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
    x=7
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub Backward_LongClick ' Quick Backward
    Backward.Bitmap = LoadBitmap(File.DirAssets,"arplus.jpg")
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
    x=8
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub TR_Click 'Right
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    x=9
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub TR_LongClick 'Right +
    TR.Bitmap = LoadBitmap(File.DirAssets,"tdplus.jpg")
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    x=10
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub TL_Click 'Left
    TL.Bitmap = LoadBitmap(File.DirAssets,"tg.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    x=11
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Sub TL_LongClick ' Left +
    TL.Bitmap = LoadBitmap(File.DirAssets,"tgplus.jpg")
    TR.Bitmap = LoadBitmap(File.DirAssets,"td.jpg")
    Forward.Bitmap = LoadBitmap(File.DirAssets,"av.jpg")
    Backward.Bitmap = LoadBitmap(File.DirAssets,"ar.jpg")
    x=12
    BTA.SendBytes(Array As Byte(x, y))
End Sub

Private Sub BTA_Connected (Success As Boolean)
    If Success = True Then
        Connected = Success
        BtnConnect.Visible=False
        BLT.Visible=True
        Sortie.Visible=True
        Pilotage.Visible=False
        Forward.Visible=True
        Backward.Visible=True
        TR.Visible=True
        TL.Visible=True
        Square.Visible=True
        STOP.Visible=True
        Pen.Visible=True
        Etoile.Visible=True
    End If
End Sub
        
Private Sub BTA_StateChanged (State As String)
    If State <> "" Then
        Connected = False
        BtnConnect.Visible=True
        BLT.Visible=False
        Sortie.Visible=False
        Pilotage.Visible=True
        Forward.Visible=False
        Backward.Visible=False
        TR.Visible=False
        TL.Visible=False
        Square.Visible=False
        STOP.Visible=False
        Pen.Visible=False
        Etoile.Visible=False
    End If
End Sub


Sub Sortie_Click
    Msgbox2Async("Are you sure you want to close the Bluetooth connection?","To leave ?", "Yes", "", "No", Null, True)
    Wait For Msgbox_Result (Result As Int)
    If Result=DialogResponse.POSITIVE Then
        BTA.SendBytes(Array As Byte(0,0)) 'Stopping the engines
        Activity.Finish
    End If
End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean
    If KeyCode = KeyCodes.KEYCODE_BACK Then    openMsgBox
            Return True
End Sub

Sub openMsgBox
    Msgbox2Async("Are you sure you want to close the Bluetooth connection? ?","To leave ?", "Yes", "", "No", Null, True)
    Wait For Msgbox_Result (Result As Int)
    If Result=DialogResponse.POSITIVE Then
        BTA.SendBytes(Array As Byte(0,0)) 'Stopping the engines
        Activity.Finish
    End If
End Sub
 
Upvote 0

Marc DANIEL

Well-Known Member
Licensed User
Thank you for your response, Erel, I was making the changes proposed by Eldritch
and I'll come back here to tell you if that fixed the bug

I had already installed ChatPage (version B4A) on my Smartphone. Congratulations on this application that I tested between two Smartphones. And I noticed that you can connect one or more times in a row to the HC-05 module without the slightest bug. On the other hand, the difficulty will be, for me, to adapt and transform this application to control my B4R device with simple digital data, but I will try.
 
Last edited:
Upvote 0

Brian Dean

Well-Known Member
Licensed User
Longtime User
I am not sure what your problem is, but here is something that might be of help. I have used HC-05s in a number of projects. A good way to test them is to do a simple "wrap-test" - that is connect the Rx directly to the Tx pin. Here is a project that will run a wrap-test between a 'phone and an HC-05. I hope its useful.
 

Attachments

  • Testbed.zip
    13.2 KB · Views: 32
Upvote 0

Marc DANIEL

Well-Known Member
Licensed User
Thank you for taking an interest in my problem. I will study what you sent me and I will not fail to come back here
 
Upvote 0

Marc DANIEL

Well-Known Member
Licensed User
Finally, I followed EREL's advice (You should always listen to EREL!) and I modified the Bluetooth application "ChatPage" which I adapted to my needs.
The hardest part was replacing the sending of STRING messages with BYTES and then adapting my B4R program to receiving data with different bytes but I think I succeeded.

I am building a robot (in fact a kind of rolling and tracing LOGO turtle) that I want to control from my Smartphone with the use of an HC-05 Bluetooth module.
As this is an experimental prototype, I will upload the final code when everything is working correctly.

Thanks to EREL, I was able to resolve the problem of Bluetooth connection bugs caused by my old B4A application.

These bugs have disappeared with the new B4A application based on "ChatPage" technology : tracing_turtle_pilot.zip

On the other hand, I have not yet understood why my two B4A applications do not send the same kind of bytes but it works thanks to these B4R lines:

Sub AStream_Newdata:
Sub AStream_NewData (Buffer() As Byte)
    L = Buffer.Length
    If Buffer.Length = 2 Then X= Buffer(0) ' for my old application which has bugs during the 2nd bluetooth connection
    If Buffer.Length = 5 Then X = Buffer(4) 'for the new application based on the "ChatPage" which I adapted to my needs
   
    Log("Buffer Length: ", L)
    Log("Valeur de X: ", X)
   
    Select X  ' Management of data received by Bluetooth from the Android Smartphone
        Case 0
            SpeedD = 0
            SpeedG = 0
            Envoi
            ' Pencil control (up or down)
           
           
        Case 1 ' PenDown
            ' Transmission of values to the servomotor which lowers or raises the pencil
            Write = True
            IndicatorLight
            MonServo.Write(120)
               
        Case 2 ' PenUp
            Write = False
            IndicatorLight
            MonServo.Write(35)
 
Last edited:
Upvote 0

Marc DANIEL

Well-Known Member
Licensed User
TortueLOGO_Arduino.jpg


Prototype

Components


Pen UP by servomotor







 
Last edited:
Upvote 0
Top