Android Question BLE connect with new devices (recent devices).

Eugenio

Member
Licensed User
Longtime User
Hello!

I created a button to send (write)

I created a Sub in the Starter (Service)

But I can not pass the ServiceId and CharID (Characteristic)

Follow the code.

B4X:
Main

#Region  Project Attributes
    #ApplicationLabel: BLE Teste New
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#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.
    
End Sub

Sub Globals
    
    Private btnReadData As Button
    Private btnDisconnect As Button
    Private btnScan As Button
    Private lblDeviceStatus As Label
    Private lblState As Label
    Private pbReadData As ProgressBar
    Private pbScan As ProgressBar
    Private clv As CustomListView
    Private btEnviar As Button
    Private Label3 As Label
    Private lblDeviceMessage As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
End Sub

Sub Activity_Resume
    
    StateChanged
End Sub

Public Sub StateChanged
    lblState.Text = Starter.currentStateText
    If Starter.connected Then
        lblDeviceStatus.Text = "Connected: " & Starter.ConnectedName
    Else
        lblDeviceStatus.Text = "Not connected"
    End If
    btnDisconnect.Enabled = Starter.connected
    btnScan.Enabled = Not(Starter.connected)
    pbReadData.Visible = False
    pbScan.Visible = False
    btnReadData.Enabled = Starter.connected
    btnScan.Enabled = (Starter.currentState = Starter.manager.STATE_POWERED_ON) And Starter.connected = False
End Sub

Public Sub QualID
    Label3.Text = "X"
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub btnScan_Click
    Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_COARSE_LOCATION)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then Return
    pbScan.Visible = True
    CallSub(Starter, "StartScan")
End Sub

Sub DataAvailable (Service As String, Characteristics As Map)
    pbReadData.Visible = False
    clv.Add(CreateServiceItem(Service), "")
    For Each id As String In Characteristics.Keys
        clv.Add(CreateCharacteristicItem(id, Characteristics.Get(id)), "")
    Next
End Sub

Sub btnDisconnect_Click
    CallSub(Starter, "Disconnect")
End Sub

Sub btnReadData_Click
    pbReadData.Visible = True
    clv.Clear
    CallSub(Starter, "ReadData")
End Sub

Sub CreateServiceItem (service As String) As Panel
    Dim pnl As Panel
    pnl.Initialize("")
    pnl.Color = 0xFF808080
    pnl.SetLayoutAnimated(0, 0, 0, clv.AsView.Width, 30dip)
    Dim lbl As Label
    lbl.Initialize("")
    lbl.Text = service
    lbl.Gravity = Gravity.CENTER
    lbl.Typeface = Typeface.DEFAULT_BOLD
    pnl.AddView(lbl, 0, 0, clv.AsView.Width, 30dip)
    Return pnl
End Sub

Sub CreateCharacteristicItem(Id As String, Data() As Byte) As Panel
    Dim pnl As Panel
    pnl.Initialize("")
    pnl.SetLayoutAnimated(0, 0, 0, clv.AsView.Width, 40dip)
    pnl.Color = Colors.White
    Dim lbl As Label
    lbl.Initialize("")
    lbl.Text = Id
    pnl.AddView(lbl, 0, 0, clv.AsView.Width, 20dip)
    Dim lbl2 As Label
    lbl2.Initialize("")
    Try
        lbl2.Text = BytesToString(Data, 0, Data.Length, "UTF8")
    Catch
        Log(LastException)
        lbl2.Text = "Error reading data as string"
    End Try
    lbl2.TextColor = 0xFF909090
    lbl2.TextSize = 14
    pnl.AddView(lbl2, 0, 20dip, clv.AsView.Width, 20dip)
    Return pnl
End Sub

Sub btEnviar_Click
    CallSub(Starter, "WriteData")
End Sub

Public Sub DeviceMessage (s As String)
    lblDeviceMessage.Text = "Device message: " & s
End Sub

B4X:
'Service

Sub Process_Globals
    Public manager As BleManager2
    Public currentStateText As String = "UNKNOWN"
    Public currentState As Int
    Public connected As Boolean = False
    Public ConnectedName As String
    Private ConnectedServices As List
    Public rp As RuntimePermissions
    Dim  mGserviceId2 As String
    Dim  mGcharId As String
End Sub

Sub Service_Create
    manager.Initialize("manager")
End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Public Sub ReadData
    For Each s As String In ConnectedServices
        manager.ReadData(s)
    Next
End Sub

Public Sub WriteData
    Dim ByteC As ByteConverter
    Dim data() As Byte
    data=ByteC.HexToBytes("11")
    manager.WriteData(mGserviceId2, mGcharId, data)
End Sub


Sub Manager_DataAvailable (serviceId As String, Characteristics As Map)
    CallSub3(Main, "DataAvailable", serviceId, Characteristics)
    'Dim b() As Byte = Characteristics.Get(Characteristics)
    'Dim msg As String = BytesToString(b, 0, b.Length, "utf8")
    'CallSub2(Main, "DeviceMessage", msg)
End Sub

Public Sub SendMessage(msg() As Byte)
    If Not(connected) Then Return
    'manager.WriteData(serviceId, Characteristics, msg) 'HERE MY QUESTION
End Sub

Public Sub Disconnect
    manager.Disconnect
    Manager_Disconnected
End Sub

Sub Manager_StateChanged (State As Int)
    Select State
        Case manager.STATE_POWERED_OFF
            currentStateText = "POWERED OFF"
        Case manager.STATE_POWERED_ON
            currentStateText = "POWERED ON"
        Case manager.STATE_UNSUPPORTED
            currentStateText = "UNSUPPORTED"
    End Select
    currentState = State
    CallSub(Main, "StateChanged")
End Sub

Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
    Log("Found: " & Name & ", " & Id & ", RSSI = " & RSSI & ", " & AdvertisingData)
    ConnectedName = Name
    manager.StopScan
    manager.Connect2(Id, False) 'disabling auto connect can make the connection quicker
End Sub

Public Sub StartScan
    If manager.State <> manager.STATE_POWERED_ON Then
        Log("Not powered on.")
    Else If rp.Check(rp.PERMISSION_ACCESS_COARSE_LOCATION) = False Then
        Log("No location permission.")
    Else
        manager.Scan2(Null, False)
    End If
End Sub


Sub Manager_Disconnected
    Log("Disconnected")
    connected = False
    CallSub(Main, "StateChanged")
End Sub

Sub Manager_Connected (services As List)
    Log("Connected")
    connected = True
    ConnectedServices = services
    CallSub(Main, "StateChanged")
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy
    
End Sub


Thanks for any help!
 
Upvote 0

Eugenio

Member
Licensed User
Longtime User
Hi, thanks for your reply.

I would just like an example, which sends a command to a BLE.

Can you send me an example, please?

Because all I've tested so far work just fine with older versions of Android.

With new versions of Android I can not send commands (write) on the BLE device.

That's all I need.

Thank you for any help!
 
Upvote 0

Eugenio

Member
Licensed User
Longtime User
Hi, thanks for your reply.

No errors

It simply does not connect when the Android version is newer.

In previous versions it works fine

Thanks for help!
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…