Android Example Use a handheld Bluetooth scanner via SPP mode

Update: Code to reconnect added


I've bought a BT handheld scanner on Ebay for about 45€ like this:
scanner.jpg

It comes with a sheet with barcodes which can be scanned to do some settings:
SPP2.jpg


Here the steps to use it with B4A. This is a SIMPLE example. If you need it a bit advanced, you can use the BT-Admin example: https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/#content The code is quite similar but with the BT-Admin you can control BT more comfortable.

1. Scan the SPP barcode to set the scanner to SPP mode
2. Switch BT to "on" on your device
3. Start the app
4. At the first time a pair message appears. Press accept to pair.
5. Happy scanning!

Note: This BASIC example does not need an UI. Just set some breakpoints or take a look at the logs. The example should work with all types of scanners using SPP mode.

With a timer you can re-connect to the scanner if it goes to sleep and the app throws "AStream_Error" instead of getting back to the list of paired devices. Same thing if the app resumes. You could store the scanner's mac address and try to reconnect to it instead of showing the device's list.

The app now uses a timer to reconnect to the scanner if it goes to sleep

B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: true
    #ApplicationLabel: Scan Example
    #VersionCode: 1
    #VersionName: V1.0
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

'Activity module
Sub Process_Globals
    Dim serial1 As Serial
    Dim AStream As AsyncStreams
    Dim T As Timer
End Sub

Sub Globals
    Dim ScannerMacAddress As String
    Dim ScannerOnceConnected As Boolean
End Sub

Sub Activity_Create(FirstTime As Boolean)
 
    serial1.Initialize("Serial")
    T.Initialize("Timer", 2000)
 
End Sub

Sub ShowPairedDevices

    Dim PairedDevices As Map
    PairedDevices = serial1.GetPairedDevices
    Dim l As List
    l.Initialize
    For i = 0 To PairedDevices.Size - 1
        l.Add(PairedDevices.GetKeyAt(i))
    Next
    If l.Size=0 Then
       l.Add("No device(s) found...")
    End If
    Dim res As Int
    res = InputList(l, "Choose device", -1) 'show list with paired devices
    If res <> DialogResponse.CANCEL Then
        If l.Get(res)="No device(s) found..." Then
           Return
        Else
           ScannerMacAddress=PairedDevices.Get(l.Get(res)) 'convert the name to mac address and connect
           serial1.Connect(ScannerMacAddress)
        End If
    End If
 
End Sub

Sub Serial_Connected (success As Boolean)
    If success = True Then
       Log("Scanner is now connected. Waiting for data...")
       AStream.Initialize(serial1.InputStream, serial1.OutputStream, "AStream")
       ScannerOnceConnected=True
       T.Enabled=False
    Else
       If ScannerOnceConnected=False Then
          MsgboxAsync("Please switch on the scanner...","Scanner is offline")
          ShowPairedDevices
       Else
          Log("Still waiting for the scanner to reconnect: " & ScannerMacAddress)
        T.Enabled=True
       End If
    End If
End Sub

Sub AStream_NewData (Buffer() As Byte)
    Log("Received: " & BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub

Sub AStream_Error
    Log("Connection broken...")
 
    AStream.Close
    serial1.Disconnect
    If ScannerOnceConnected=True Then
       T.Enabled=True
    Else
       ShowPairedDevices
    End If
End Sub

Sub AStream_Terminated
    Log("Connection terminated...")
    AStream_Error
End Sub

Sub Timer_Tick
    T.Enabled=False
    serial1.Connect(ScannerMacAddress)
    Log ("Trying to connect...")
End Sub

Sub Activity_Resume
    Log("Resuming...")
    ShowPairedDevices
    If ScannerOnceConnected=True Then
       T.Enabled=True
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    Log ("Activity paused. Disconnecting...")
    AStream.Close
    serial1.Disconnect
    T.Enabled=False
End Sub
 
Last edited:

canalrun

Well-Known Member
Licensed User
Longtime User
I bought the same model scanner several years ago and also use it with B4A in SPP Bluetooth mode.

A handy trick I learned:

Using the command codes on the included sheet, or maybe from the downloadable manual, you can turn on a mode where the scanner pre-pends a character that identifies the type of code that was scanned.

The target code for which I am using scanning to acquire data is UPC/EAN

I use a different type of code, maybe code 39 I think, to send "commands" my B4A software – such as Begin New Set or End Set …

That way I can use websites to print barcodes for "commands" to my software that I scan with the scanner.

Barry.
 

EduardoElias

Well-Known Member
Licensed User
Longtime User
Great, the test app works fine.

However, in a practical scenario the user is happy scanning and the stops, the connection stream will be broken, how can it be started again just scanning?

I mean, after broken the connection I see that the program needs to reconnect and that is a program side decision. How can it be different? so that the scanned as soon as available again it gets reconnected?

Thank you !
 

KMatle

Expert
Licensed User
Longtime User
how can it be started again just scanning

Just use a timer which starts when the connection is broken. The timer will call

B4X:
serial1.Connect(PairedDevices.Get(MACADDRESS))
every 5 secs or so. If Success is true, stop the timer and go on. If it's false, just do nothing.

In Rresume start the timer, in Pause stop it. Will add this to my example the next days.
 
Top