B4J Question RPi & B4j - How to delay BT.initialise

Mark Read

Well-Known Member
Licensed User
Longtime User
I am connecting a headless RPi 2 with bluetooth dongle to a tablet running a B4A App. Everything was working fine some months ago but suddenly I have a problem.

The b4j app is a non UI and can be started from the menu to debug etc. It is also started in the rc.local on boot.

If I boot the Rpi, it seems that the BT is not ready for about 5 seconds after the GUI appears (the icon is grey and then goes blue). During this time, my app has tried to initialise BT, fails and closes. If I start the app manually via the menu, it works fine as the icon is blue - clear I hope.
This is the code I am using(b4j ver. 4.70):

B4X:
'Start bluetooth
    bt.Initialize("bt")
    If bt.IsEnabled = False Then
        Log("Bluetooth not available1")
        ExitApplication
    End If
   
    RPiStatus.State=True    ' turn on green LED to show ready status of RPi
   
    Log($"My address: ${GetBluetoothAddress}"$)
    Log("***************************************************************************")
    bt.Listen        'bt_Connected is called when connection is made
   
    StartMessageLoop

I think it would be better to use a

B4X:
Wait For bt.IsEnabled = True
instead of the If-End. Am I correct or not and would this be the correct code?

Many thanks.
 

Knoppi

Active Member
Licensed User
Longtime User
You can insert in rc.local a sleep 5s command before your b4j prg is called
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
Thx Knoppi, already tried 20 secs - didn't work.
 
Upvote 0

Knoppi

Active Member
Licensed User
Longtime User
Try
raspi-config
boot-options/wait-for-network

Edit:
Not ideal but it works in most cases
insert in crontab
sudo crontab -e
@reboot sleep 5 && /full/path/to/your/app
 
Last edited:
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
That only applies to the network or not. I need bluetooth.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is the code I am using(b4j ver. 4.70):
You should use the latest version of B4J.

You can do something like:
B4X:
Do While bt.IsEnabled = False
Sleep(1000)
Loop

Or better:
B4X:
Dim start As Long = DateTime.Now
Do While bt.IsEnabled = False
If DateTime.Now > start + 30000 Then
  Log("BT not available.")
  ExitApplication
End If
Sleep(1000)
Loop

Note that this code can't be in AppStart sub. It should be in a different sub that you call from AppStart.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Upvote 0

OliverA

Expert
Licensed User
Longtime User
It is only relevant for non-ui programs.
Whew... I already thought this (not to use in AppStart) may apply to UI apps too. Panic averted...
 
Upvote 0
Top