#Region Service Attributes
#StartAtBoot: False
#ExcludeFromLibrary: True
#End Region
Sub Process_Globals
Public manager As BleManager2
Public currentStateText As String = "UNKNOWN"
Private serviceId, charId As String
Private connected As Boolean
Public rp As RuntimePermissions
End Sub
Sub Service_Create
manager.Initialize("manager")
serviceId = "442F1570-8A00-9A28-CBE1-E1D4212D53EB"
charId = "442F1572-8A00-9A28-CBE1-E1D4212D53EB"
Log("Service_Create")
End Sub
Sub Service_Start (StartingIntent As Intent)
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
CallSub(Main, "BleStateChanged")
StartScan
End Sub
Public Sub StartScan
If rp.Check(rp.PERMISSION_ACCESS_COARSE_LOCATION) And manager.State = manager.STATE_POWERED_ON Then
Log("scanning!")
manager.Scan2(Array (serviceId), False)
'manager.Scan2(Null, False)
Else
Log("No permission or not powered on")
End If
End Sub
Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
Log("Dev found = " & Name)
Log($"Device found: ${Name}"$)
manager.StopScan 'disabling auto connect can make the connection quicker
manager.Connect2(Id, False)
End Sub
Sub manager_Connected (Services As List)
Log("connected: " & Services)
connected = True
End Sub
Sub Manager_Disconnected
connected = False
manager.Scan2(Array (serviceId), False)
End Sub
Sub Manager_DataAvailable (sid As String, Characteristics As Map)
Dim b() As Byte = Characteristics.Get(charId)
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, charId, msg)
End Sub
Private Sub UUID(id As String) As String
#if B4A
Return "0000" & id.ToLowerCase & "-0000-1000-8000-00805f9b34fb"
#else if B4I
Return id.ToUpperCase
#End If
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