Android Question BT autopair error

valekuatro

Member
Licensed User
Hi!
I have taken an example of other thread on how to handle an autopaired BT connection. It works sometimes and sometimes doesn't. Sometimes it connects and it does not transmit, sometimes it does not connect and sometimes it connects and transmits correctly. I am using an arduino module hc06 which I tried with a program downloaded from the playstore and it works correctly (turn on and off a led) So I have no choice but to think that it is due to a problem on the side of my program. The irregularity of the errors gives me to think that it is due to synchronization problems but I am not an expert in the subject and for that reason I request the help of some of the experts. I would like to clarify that it is important for me to work in an autopaired way in the development approach. The code I put here corresponds to a modified example from
HTML:
https://www.b4x.com/android/forum/threads/btautopair-programmatic-bluetooth-device-bonding.25675/#content
It uses:
BtAutoPair, BluetoothAdmin, BtSerial and Broadcast libraries
Tested on api 14 and above with same result

At the botton... the log

B4X:
Sub Process_Globals
    Dim BtAdmin As BluetoothAdmin
    Dim BtSerial As Serial
    Dim Broadcast As BroadCastReceiver
    Dim AStreams As AsyncStreams
    Dim DeviceName As String = ""
    Dim DeviceMac As String = ""
End Sub

Sub Globals
    Dim btnStartDiscovery As  Button
End Sub
'Activity
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("main")
    BtAdmin.Initialize("BtAdmin")
    BtAdmin.Enable
    BtSerial.Initialize("BtSerial")
    Broadcast_Init
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub btnStartDiscovery_Click
    DeviceName  = ""
    DeviceMac = ""
    BtAdmin.StartDiscovery
    Log("Start discovery")
End Sub
'BtAdmin
Sub BtAdmin_DiscoveryFinished    'Event handler
    Log("Discovery stopped")
End Sub

Sub BtAdmin_StateChanged (NewState As Int, OldState As Int) 'Event handler
    If   (NewState =BtAdmin.STATE_OFF) Then
        BtAdmin.Enable
    End If
End Sub

Sub BtAdmin_DeviceFound (Name As String, Mac As String)    'Event handler
    BtAdmin.CancelDiscovery
    DeviceName  = Name
    DeviceMac = Mac
    Log("Device found: " & DeviceName & ", " & DeviceMac)
    BtSerial.Connect(DeviceMac)
End Sub

Sub BtSerial_Connected (Success As Boolean)    ' Event handler
    If (Success=True) Then
        If AStreams.IsInitialized = False Then AStreams.Initialize(BtSerial.InputStream, BtSerial.OutputStream, "Astreams")
        Log("Connected")
        If AStreams.IsInitialized = True Then
            Dim buffer() As Byte
            Dim sendchar As String = "a"
            buffer = sendchar.GetBytes("UTF8")
            AStreams.Write(buffer)
        End If
    Else
        Log("Not Connected: " & LastException.Message)
    End If
End Sub

Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    Log(msg)
End Sub

Sub AStreams_Error
    Log(LastException.Message)
    ToastMessageShow(LastException.Message, True)
End Sub

Sub AStreams_Terminated
    Log("end")
End Sub
'Broadcast
Sub Broadcast_Init
    Broadcast.Initialize("BroadCastReceiver")
    Broadcast.addAction("android.bluetooth.device.action.PAIRING_REQUEST")
    Broadcast.SetPriority(2147483647)
    Broadcast.registerReceiver("")
End Sub

Sub BroadCastReceiver_OnReceive (Action As String,  i As  Object)    'Event handler
    Dim  intnt  As  Intent = i
    Broadcast.AbortBroadcast
    Dim autopair As BtAutoPair
    Dim pinBytes() As  Byte
    If (Action = "android.bluetooth.device.action.PAIRING_REQUEST") Then
        If (intnt.HasExtra("android.bluetooth.device.extra.DEVICE")) Then
            Log("Pairing request: " & DeviceName & ", " & DeviceMac)
            pinBytes = Array As Byte(0x31, 0x32, 0x33, 0x34)'1234
            autopair.Start4(intnt, pinBytes)
        End If
    End If
End Sub

B4A Log....
Start discovery
Device found: HC-06, 98:D3:32:10:91:A3
Discovery stopped
Not Connected: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
Start discovery
Device found: HC-06, 98:D3:32:10:91:A3
Discovery stopped
Pairing request: HC-06, 98:D3:32:10:91:A3
Connected <---- here has connected but not transmitted
java.io.IOException: bt socket closed, read return: -1
Start discovery
Device found: HC-06, 98:D3:32:10:91:A3
Discovery stopped
Connected <------ here connected and transmitted
java.io.IOException: socket closed
Start discovery
Device found: HC-06, 98:D3:32:10:91:A3
Discovery stopped
Not Connected: java.io.IOException: read failed, socket might closed or timeout, read ret: -1


Any help would be appreciated
 
Last edited:

valekuatro

Member
Licensed User
I've already tried that example. It remains searching devices without sucess. Anyway this approach require user intervention. I would like to autoconnect and transmit. I've done this with the code i posted, but works just sometimes. I tested introducing a sleep(10000) and btserial.disconnect, it worked few times, randomly.
Most of the time it gives closed socket error. It´s possible to review this code instead of another approach?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Reviewing the complete code and finding out why it sometimes work and sometimes doesn't can be difficult.

The example code only requires user intervention once when the devices are paired. If this is critical for you then add the pairing code to that example.
It is better than the code you posted as all the communication is managed in a service.
 
Upvote 0

valekuatro

Member
Licensed User
Thanks i'll take a look. However with "my" (not all really mine) code I made it work correctly by separating the steps into button events. Connect, disconnect, switch on and off. What confuses me is that joining that same code works 1 out of 10 times.
 
Upvote 0
Top