Android Question Connect and manage a scp32 Via BLE

I thank you for your help so far, this is the situation right now, I have the scp32 chip configured with the following services:


The control unit provides the tablet client with a single primary station service with uuid: 0000a002-0000-1000-8000-00805f9b34fb.
Below are summarized in a table the features present in the service:

1
C300-0000-1000-8000- 00805f9b34fb
COMMAND
1
READ-WRITE
ASCII CODE
2
C301 ...
ANSWER
2
READ-WRITE
ASCII CODE
3
C302 ...
HEIGHT
4
READ-WRITE
ASCII CODE
4
C303 ...
POSIZIONEBILANCIA
1
READ-WRITE
ASCII CODE
5
C304 ...
CIRCUMFERENCE
4


etc ..


currently I have configured the code in this way:


ON STARTER

B4X:
Sub Service_Create
            'This is the program entry point.
            'This is a good place for a single activity.
            Log ("Service Create Starter")
            CallSubDelayed (FirebaseMessaging, "SubscribeToTopics")

            'BLE
            manager.Initialize ( "manager")
            ServiceId = UUID ("0000a002")
            ReadChar = UUID ("1001")
            WriteChar = UUID ("1002")
            messagesToSend.Initialize
            Serial1.Initialize (115200)

End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Sub Service_TaskRemoved
            'This event will be raised when the user removes the app from the recent apps list.
End Sub

Private Sub Manager_StateChanged (State As Int)
            If State <> manager.STATE_POWERED_ON Then
                        ToastMessageShow ("Please enable Bluetooth", True)
            else
                        StartScan
                      
            End If
End Sub

Public Sub StartScan
            If rp.Check (rp.PERMISSION_ACCESS_COARSE_LOCATION) Then
                        If manager.State = manager.STATE_POWERED_ON Then
'manager.Scan (Array (ServiceId))
                                    manager.Scan (Null)
                        End If
            End If
End Sub

Private Sub Manager_DeviceFound (Name As String, DeviceId As String, AdvertisingData As Map, RSSI As Double)
            Log ($ "DeviceFound: $ {Name}" $)
            Log ("Found: Name =" & Name & ", id =" & DeviceId & ", RSSI =" & RSSI & ", AdvertisingData =" & AdvertisingData) 'ignore
            manager.Connect2 (DeviceId, False)
            manager.StopScan
End Sub

Private Sub Manager_Connected (Services As List)
            Log ( "Connected")
            manager.SetNotify (ServiceId, ReadChar, True)
            connected = True
            CallSub2 (Main, "SetState", connected)
            messagesToSend.Clear
End Sub

ON MAIN
B4X:
Public Sub SetState (connected As Boolean)

            If connected Then
                        ProgressDialogHide
            else
                        ProgressDialogShow2 ("Trying to connect", False)
            End If
End Sub






The startup application sees my chip with its MAc Adress, but remains in a connection waiting state, as you can see from my attachment.




if I try to connect with Nrf connect I connect and retrieve all the UUIDs present in the chip database correctly. Thank you in advance for your help.
 

Attachments

  • image001.png
    image001.png
    17.2 KB · Views: 263
as far as the connection is concerned I confirm that I can conclude it with nrf connect, I am attaching the connection images, in fact after the connection it reads all the features that have been implemented in the Gatt Server, I am attaching the log as text:


B4X:
*** Service (starter) Create ***
Service Create Starter
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
intcount massagrassaideale 18
intcount rangetrattamenti 14
2019-06-25 15:48:52
** Activity (main) Resume **
*** Service (firebasemessaging) Create ***
Service Create Firebasemessaging
Tokken fac6BeA3l1Y:APA91bEEfwDscZ_VMcLr85vgBwk0B6XHd6wq2xm5L4Oo1PEiSSyOAik6ytxa6sVTTDaRAfMTZe0EtCQue9G_ey-TVrVA_67bAJQ1BvKllsIs5RyTMhn3D-0OKNkCZ7R60U9poLou5ibV
** Service (firebasemessaging) Start **
SubscribeToTopics Firebasemessaging
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -63, AdvertisingData = (MyMap) {0=[B@f7aafda}
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -61, AdvertisingData = (MyMap) {0=[B@f589501}
Disconnesso
Disconnesso
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -61, AdvertisingData = (MyMap) {0=[B@391e90}
Disconnesso
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -63, AdvertisingData = (MyMap) {0=[B@45cd2d8}
Disconnesso


I forgot to tell you, Currently if I connect with Nrf Connect to the chip, I can see through Realterm on windows the device that connects to the Chip, I can see even when I execute a read or write request.
 

Attachments

  • OKScreenshot_20190625-155140_nRF Connect.jpg
    OKScreenshot_20190625-155140_nRF Connect.jpg
    167.8 KB · Views: 357
  • Screen scp.png
    Screen scp.png
    282.9 KB · Views: 249
Upvote 0
Here is Erel this and the log if I try to connect with the BLE Example:

B4X:
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Starter.connected false
Found: , CC:50:E3:99:B9:AA, RSSI = -64, (MyMap) {0=[B@a8448b}
Found: , CC:50:E3:99:B9:AA, RSSI = -63, (MyMap) {0=[B@b09b968}
Disconnected
Starter.connected false
Disconnected
Starter.connected false
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
Hi all,
I'm trying to implement this code with Marco Laudati.
We can't connect with a ble device (a chip scp32).
My code works with BLE chat periperal.

I use two simple instructions:
manager.Scan (Null)
and
manager.Connect2 (DeviceId, False) (once Manager_DeviceFound)

I find the device and have the Mac addreaa also, but connect doesn't work.
I put a log("Disconnesso") into Manager_Disconnected routine
Has anyone tried a connection like this?
Thanks all
Marcom
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
Point 1 and 2 ok.
Point 3 : I send unfiltered log.
I tried to read it but found nothing useful


B4X:
2019-06-25 17:22:09
** Activity (main) Resume **
initGoToTop
initGoToTop
Input channel constructed: fd=65
setView = DecorView@d8538bc[main] TM=true MM=false
MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1920, 1200) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 36 - 0, 0) or=2
MSG_WINDOW_FOCUS_CHANGED 1
Starting input: tba=android.view.inputmethod.EditorInfo@66aa045 nm : com.mamavi.slimup ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=66
Relayout returned: old=[0,0][1920,1200] new=[0,0][1920,1200] result=0x3 surface={valid=true 3775719424} changed=false
Loading /vendor/lib/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace.
dispatchAttachedToWindow
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][0,0] new=[528,531][1392,705] result=0x27 surface={valid=true 3493849088} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [960x270]-format:1
eglCreateWindowSurface = 0xd0762ab8, 0xd03fe808
*** Service (firebasemessaging) Create ***
Service Create Firebasemessaging
Tokken fac6BeA3l1Y:APA91bEEfwDscZ_VMcLr85vgBwk0B6XHd6wq2xm5L4Oo1PEiSSyOAik6ytxa6sVTTDaRAfMTZe0EtCQue9G_ey-TVrVA_67bAJQ1BvKllsIs5RyTMhn3D-0OKNkCZ7R60U9poLou5ibV
** Service (firebasemessaging) Start **
SubscribeToTopics Firebasemessaging
MSG_WINDOW_FOCUS_CHANGED 1
stopLeScan()
STATE_ON
uid=10159(com.mamavi.slimup) identical 1 line
STATE_ON
STATE_ON
Stop Scan with callback
startLeScan(): null
STATE_ON
uid=10159(com.mamavi.slimup) identical 4 lines
STATE_ON
Start Scan with callback
onScannerRegistered() - status=0 scannerId=9 mScannerId=0
Starting input: tba=android.view.inputmethod.EditorInfo@666c53e nm : com.mamavi.slimup ic=null
startInputInner - Id : 0
After accept
MSG_RESIZED_REPORT: frame=Rect(528, 531 - 1392, 705) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
MSG_RESIZED: frame=Rect(0, 0 - 1920, 1200) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -60, AdvertisingData = (MyMap) {0=[B@283c51c}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=68feae2d-7554-407a-874b-85b51bfda76d
stopLeScan()
STATE_ON
STATE_ON
onClientRegistered() - status=0 clientIf=10
STATE_ON
STATE_ON
Stop Scan with callback
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -60, AdvertisingData = (MyMap) {0=[B@6961708}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=908c53f5-ab5c-4206-9774-c97e34af9043
onClientRegistered() - status=0 clientIf=9
DeviceFound: ID130Plus Color HR
Found: Name = ID130Plus Color HR, id = FC:C3:E9:71:3B:5D, RSSI = -86, AdvertisingData = (MyMap) {25=[B@11c6ea1, 1=[B@45658c6, 3=[B@6f45087, 9=[B@5f99bb4, -1=[B@9f053dd, 0=[B@ecf3b52}
connect() - device: FC:C3:E9:71:3B:5D, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=028ae3e3-7293-4e0a-867a-1c7255f8f4be
MSG_WINDOW_FOCUS_CHANGED 0
DeviceFound: Gear S3 (2F1D) LE
onClientRegistered() - status=0 clientIf=11
Found: Name = Gear S3 (2F1D) LE, id = E4:25:1C:EB:DE:3A, RSSI = -61, AdvertisingData = (MyMap) {1=[B@5bb6e23, -1=[B@e6ebf20, 25=[B@62350d9, 9=[B@81ba9e, 0=[B@24cc97f}
connect() - device: E4:25:1C:EB:DE:3A, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=04254aea-12e1-4d01-b773-0bb9146d4911
onClientRegistered() - status=0 clientIf=12
onClientConnectionState() - status=133 clientIf=11 device=FC:C3:E9:71:3B:5D
close()
unregisterApp() - mClientIf=11
Disconnesso
eglDestroySurface = 0xd0762ab8, 0xd03fe800
dispatchDetachedFromWindow
channel 'ba1e166 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~ Disposing input event receiver.
channel 'ba1e166 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~NativeInputEventReceiver.
Input channel destroyed: fd=65
initGoToTop
initGoToTop
Input channel constructed: fd=65
setView = DecorView@831b226[main] TM=true MM=false
startLeScan(): null
STATE_ON
uid=10159(com.mamavi.slimup) identical 4 lines
STATE_ON
Start Scan with callback
onScannerRegistered() - status=0 scannerId=7 mScannerId=0
dispatchAttachedToWindow
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][0,0] new=[528,513][1392,687] result=0x7 surface={valid=true 3467302912} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [960x270]-format:1
eglCreateWindowSurface = 0xd07634b8, 0xceaad808
MSG_WINDOW_FOCUS_CHANGED 1
sendUserActionEvent() returned.
MSG_WINDOW_FOCUS_CHANGED 1
MSG_RESIZED_REPORT: frame=Rect(528, 513 - 1392, 687) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
MSG_WINDOW_FOCUS_CHANGED 0
onClientConnectionState() - status=133 clientIf=9 device=CC:50:E3:99:B9:AA
onClientConnectionState() - status=133 clientIf=10 device=CC:50:E3:99:B9:AA
close()
unregisterApp() - mClientIf=9
close()
unregisterApp() - mClientIf=10
Disconnesso
eglDestroySurface = 0xd07634b8, 0xceaad800
dispatchDetachedFromWindow
channel '5f00d52 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~ Disposing input event receiver.
channel '5f00d52 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~NativeInputEventReceiver.
Input channel destroyed: fd=65
initGoToTop
initGoToTop
Input channel constructed: fd=65
setView = DecorView@d04fdba[main] TM=true MM=false
stopLeScan()
STATE_ON
uid=10159(com.mamavi.slimup) identical 2 lines
STATE_ON
Stop Scan with callback
startLeScan(): null
STATE_ON
STATE_ON
STATE_ON
STATE_ON
STATE_ON
STATE_ON
Start Scan with callback
onScannerRegistered() - status=0 scannerId=7 mScannerId=0
Disconnesso
dispatchDetachedFromWindow
channel 'dddac9e com.mamavi.slimup/com.mamavi.slimup.main (client)' ~ Disposing input event receiver.
channel 'dddac9e com.mamavi.slimup/com.mamavi.slimup.main (client)' ~NativeInputEventReceiver.
Input channel destroyed: fd=65
initGoToTop
initGoToTop
Input channel constructed: fd=65
setView = DecorView@a78496a[main] TM=true MM=false
stopLeScan()
STATE_ON
uid=10159(com.mamavi.slimup) identical 2 lines
STATE_ON
Stop Scan with callback
startLeScan(): null
STATE_ON
STATE_ON
STATE_ON
STATE_ON
uid=10159(com.mamavi.slimup) identical 1 line
STATE_ON
Start Scan with callback
onScannerRegistered() - status=0 scannerId=7 mScannerId=0
dispatchAttachedToWindow
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][0,0] new=[528,513][1392,687] result=0x7 surface={valid=true 3775584256} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [960x270]-format:1
eglCreateWindowSurface = 0xd0763e18, 0xe10ad808
MSG_WINDOW_FOCUS_CHANGED 1
sendUserActionEvent() returned.
sendUserActionEvent() returned.
MSG_WINDOW_FOCUS_CHANGED 1
sendUserActionEvent() returned.
MSG_WINDOW_FOCUS_CHANGED 1
MSG_RESIZED_REPORT: frame=Rect(528, 513 - 1392, 687) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -62, AdvertisingData = (MyMap) {0=[B@3c6ad10}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=758302d0-28b1-4a34-9f66-cd2dcbe320d0
stopLeScan()
onClientRegistered() - status=0 clientIf=9
STATE_ON
STATE_ON
STATE_ON
STATE_ON
Stop Scan with callback
MSG_WINDOW_FOCUS_CHANGED 0
onClientConnectionState() - status=133 clientIf=12 device=E4:25:1C:EB:DE:3A
close()
unregisterApp() - mClientIf=12
Disconnesso
eglDestroySurface = 0xd0763e18, 0xe10ad800
dispatchDetachedFromWindow
channel '59aef4c com.mamavi.slimup/com.mamavi.slimup.main (client)' ~ Disposing input event receiver.
channel '59aef4c com.mamavi.slimup/com.mamavi.slimup.main (client)' ~NativeInputEventReceiver.
Input channel destroyed: fd=65
initGoToTop
initGoToTop
Input channel constructed: fd=65
setView = DecorView@84f7972[main] TM=true MM=false
startLeScan(): null
STATE_ON
uid=10159(com.mamavi.slimup) identical 4 lines
STATE_ON
Start Scan with callback
onScannerRegistered() - status=6 scannerId=-1 mScannerId=0
dispatchAttachedToWindow
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][0,0] new=[528,513][1392,687] result=0x7 surface={valid=true 3467593728} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [960x270]-format:1
eglCreateWindowSurface = 0xd0764458, 0xceaf4808
MSG_WINDOW_FOCUS_CHANGED 1
sendUserActionEvent() returned.
MSG_WINDOW_FOCUS_CHANGED 1
MSG_RESIZED_REPORT: frame=Rect(528, 513 - 1392, 687) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
MSG_WINDOW_FOCUS_CHANGED 0
onClientConnectionState() - status=133 clientIf=9 device=CC:50:E3:99:B9:AA
close()
unregisterApp() - mClientIf=9
Disconnesso
eglDestroySurface = 0xd0764458, 0xceaf4800
dispatchDetachedFromWindow
channel '505b377 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~ Disposing input event receiver.
channel '505b377 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~NativeInputEventReceiver.
Input channel destroyed: fd=65
initGoToTop
initGoToTop
Input channel constructed: fd=65
setView = DecorView@20518a5[main] TM=true MM=false
stopLeScan()
STATE_ON
uid=10159(com.mamavi.slimup) identical 2 lines
STATE_ON
could not find callback wrapper
startLeScan(): null
STATE_ON
uid=10159(com.mamavi.slimup) identical 4 lines
STATE_ON
Start Scan with callback
onScannerRegistered() - status=6 scannerId=-1 mScannerId=0
dispatchAttachedToWindow
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][0,0] new=[528,513][1392,687] result=0x7 surface={valid=true 3467597824} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [960x270]-format:1
eglCreateWindowSurface = 0xd0764a98, 0xceaf5808
MSG_WINDOW_FOCUS_CHANGED 1
sendUserActionEvent() returned.
MSG_WINDOW_FOCUS_CHANGED 1
MSG_RESIZED_REPORT: frame=Rect(528, 513 - 1392, 687) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
MSG_WINDOW_FOCUS_CHANGED 0
eglDestroySurface = 0xd0764a98, 0xceaf5800
dispatchDetachedFromWindow
channel '6981013 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~ Disposing input event receiver.
channel '6981013 com.mamavi.slimup/com.mamavi.slimup.main (client)' ~NativeInputEventReceiver.
Input channel destroyed: fd=65
** Activity (main) Pause, UserClosed = false **
MSG_WINDOW_FOCUS_CHANGED 1
Starting input: tba=android.view.inputmethod.EditorInfo@4c10ff nm : com.mamavi.slimup ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=65
Input channel destroyed: fd=66
sendUserActionEvent() returned.
eglDestroySurface = 0xd0761e60, 0xe10ce800
Relayout returned: old=[0,0][1920,1200] new=[0,0][1920,1200] result=0x5 surface={valid=false 0} changed=true
MSG_WINDOW_FOCUS_CHANGED 0
 
Upvote 0

emexes

Expert
Licensed User
2. Make sure to only call Connect once.

Start Scan with callback
onScannerRegistered() - status=0 scannerId=9 mScannerId=0
Starting input: tba=android.view.inputmethod.EditorInfo@666c53e nm : com.mamavi.slimup ic=null
startInputInner - Id : 0
After accept
MSG_RESIZED_REPORT: frame=Rect(528, 531 - 1392, 705) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
MSG_RESIZED: frame=Rect(0, 0 - 1920, 1200) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -60, AdvertisingData = (MyMap) {0=[B@283c51c}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=68feae2d-7554-407a-874b-85b51bfda76d
stopLeScan()
STATE_ON
STATE_ON
onClientRegistered() - status=0 clientIf=10
STATE_ON
STATE_ON
Stop Scan with callback
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -60, AdvertisingData = (MyMap) {0=[B@6961708}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=908c53f5-ab5c-4206-9774-c97e34af9043
onClientRegistered() - status=0 clientIf=9
DeviceFound: ID130Plus Color HR
Found: Name = ID130Plus Color HR, id = FC:C3:E9:71:3B:5D, RSSI = -86, AdvertisingData = (MyMap) {25=[B@11c6ea1, 1=[B@45658c6, 3=[B@6f45087, 9=[B@5f99bb4, -1=[B@9f053dd, 0=[B@ecf3b52}
connect() - device: FC:C3:E9:71:3B:5D, auto: false
 
Upvote 0

emexes

Expert
Licensed User
I had a look in some BLE code of my own to see how I'd made sure I didn't accidentally try connecting multiple times to the one device, and what I found is... I didn't do anything, I was simply saved by the fact that the super-low-power device that I connect to, only emits an advertising packet once every two seconds.

In your case, the easy fix is to set a flag when you do the Connect bit, use that to make sure you only do the Connect once.

It seems to be normal for DeviceFound callbacks to come in even after you've issued the StopScan.
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
ok but my device never connects or I have the log "connected"

B4X:
Private Sub Manager_Connected (Services As List)
    Log("Connected")
    manager.SetNotify(ServiceId, ReadChar, True)
    connected = True
    CallSub2(Main, "SetState", connected)
    messagesToSend.Clear
End Sub
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
I send nonfiltred log for BLE Example
it seems that there are no differences with the log of my app

B4X:
Starting input: tba=android.view.inputmethod.EditorInfo@d8904bd nm : b4a.bbb ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=68
Input channel destroyed: fd=64
** Activity (main) Pause, UserClosed = false **
eglDestroySurface = 0xd0936180, 0xe10bf800
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x5 surface={valid=false 0} changed=true
MSG_WINDOW_FOCUS_CHANGED 0
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x1 surface={valid=false 0} changed=false
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x1 surface={valid=false 0} changed=false
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x7 surface={valid=true 3775657984} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [1200x1920]-format:1
eglCreateWindowSurface = 0xef39b298, 0xe10bf808
** Activity (main) Resume **
Starter.connected false
MSG_WINDOW_FOCUS_CHANGED 1
Starting input: tba=android.view.inputmethod.EditorInfo@782ba03 nm : b4a.bbb ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=65
Input channel destroyed: fd=68
ViewPostIme pointer 0
ViewPostIme pointer 1
startLeScan(): null
STATE_ON
uid=10153(b4a.bbb) identical 4 lines
STATE_ON
Start Scan with callback
onScannerRegistered() - status=0 scannerId=9 mScannerId=0
Found: , CC:50:E3:99:B9:AA, RSSI = -73, (MyMap) {0=[B@66cf35f}
stopLeScan()
STATE_ON
uid=10153(b4a.bbb) identical 2 lines
STATE_ON
Stop Scan with callback
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=c72f0e62-8dcc-4336-a085-8daf7883f3d6
onClientRegistered() - status=0 clientIf=9
onClientConnectionState() - status=133 clientIf=9 device=CC:50:E3:99:B9:AA
close()
unregisterApp() - mClientIf=9
Disconnected
Starter.connected false
ViewPostIme pointer 0
ViewPostIme pointer 1
Starting input: tba=android.view.inputmethod.EditorInfo@904c1ac nm : b4a.bbb ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=68
Input channel destroyed: fd=65
** Activity (main) Pause, UserClosed = false **
eglDestroySurface = 0xef39b298, 0xe10bf800
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x5 surface={valid=false 0} changed=true
MSG_WINDOW_FOCUS_CHANGED 0
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x1 surface={valid=false 0} changed=false
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x1 surface={valid=false 0} changed=false
sf_framedrop debug : 0x4f4c, game : false, logging : 0
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x7 surface={valid=true 3775657984} changed=true
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [1200x1920]-format:1
eglCreateWindowSurface = 0xef39b388, 0xe10bf808
** Activity (main) Resume **
Starter.connected false
MSG_WINDOW_FOCUS_CHANGED 1
Starting input: tba=android.view.inputmethod.EditorInfo@1110e75 nm : b4a.bbb ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=65
Input channel destroyed: fd=68
Starting input: tba=android.view.inputmethod.EditorInfo@a28fe0a nm : b4a.bbb ic=null
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Input channel constructed: fd=68
Input channel destroyed: fd=65
** Activity (main) Pause, UserClosed = false **
eglDestroySurface = 0xef39b388, 0xe10bf800
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x5 surface={valid=false 0} changed=true
MSG_WINDOW_FOCUS_CHANGED 0
Relayout returned: old=[0,0][1200,1920] new=[0,0][1200,1920] result=0x1 surface={valid=false 0} changed=false
 
Upvote 0

emexes

Expert
Licensed User
This code from Starter service works for me with my BLE sensor. Should at least connect for you too. Search for EndsWith and StartsWith to find the filters for device id, service and characteristic. Have already modified device id filter to suit your device, you'll have to change the other two depending on which service and characteristic your looking for. And the bit that decodes the data (for my sensor, is a 16-bit signed variable = B4A Short datatype).

Call StartScan (using a button press, or just at program start) to inititiate the process.
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: 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.

    Private manager As BleManager2
    Private rp As RuntimePermissions
    Private bc As ByteConverter
      
    Public BLEName As String
    Public BLEId As String
    Public BLEService As String
    Public BLECharacteristic As String
  
    Public BLE_STATE_OFF As Int = 0
    Public BLE_STATE_IDLE As Int = 1
    Public BLE_STATE_SCANNING As Int = 2
    Public BLE_STATE_CONNECTING As Int = 3
    Public BLE_STATE_READING As Int = 4
    Public BLE_STATE_STREAMING As Int = 5
  
    Public BLEState As Int = BLE_STATE_OFF
  
End Sub

Sub Service_Create
    'This is the program entry point.
    'This is a good place to load resources that are not specific to a single activity.

    manager.Initialize("manager")
      
End Sub

Sub Service_Start (StartingIntent As Intent)
  
End Sub

Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
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

Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
  
    Log(Id & " " & Name)
      
    If Id.EndsWith("B9:AA") Then    'last 4 digits of Id are usually enough to identify a particular device during testing
        manager.StopScan
      
        BLEName = Name
        BLEId = Id
      
        manager.Connect2(BLEId, False)
        BLEState = BLE_STATE_CONNECTING
    End If
  
End Sub

Sub Manager_Connected(Services As List)
  
    For Each S As String In Services
        Log(S)
        If S.StartsWith("cc4a6a80") Then
            BLEService = S
          
            manager.ReadData(BLEService)
            BLEState = BLE_STATE_READING
        End If
    Next
  
End Sub

Sub Manager_DataAvailable(ServiceID As String, Characteristics As Map)
  
    For Each S As String In Characteristics.Keys
        Log(S)
        If S.StartsWith("835ab4c0") Then
            BLECharacteristic = S
          
            Dim TempB() As Byte = Characteristics.Get(BLECharacteristic)
            Dim TempS() As Short = bc.ShortsFromBytes(TempB)
          
            Log(TempS(0))
          
            If BLEState <> BLE_STATE_STREAMING Then
                manager.SetNotify(BLEService, BLECharacteristic, True)
                BLEState = BLE_STATE_STREAMING
            End If
        End If
    Next
  
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, True)
        BLEState = BLE_STATE_SCANNING
      
        Sleep(5000)
      
        If BLEState = BLE_STATE_SCANNING Then
            manager.StopScan
            BLEState = BLE_STATE_IDLE
        End If
    End If

End Sub
 
Upvote 0

emexes

Expert
Licensed User
Create a new blank project, delete all text in Starter and replace it with above, then call from Main Activity_Create.

You might need these two Subs in Main Activity:
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

    Dim rp As RuntimePermissions
   
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")

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

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
Thanks emexes, i tried
but I have same problem.
Now scan stop after first time, but connectiopn doesn't work
I put code and log


ON STARTER
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

    Private manager As BleManager2
    Private rp As RuntimePermissions
    Private bc As ByteConverter
      
    Public BLEName As String
    Public BLEId As String
    Public BLEService As String
    Public BLECharacteristic As String
 
    Public BLE_STATE_OFF As Int = 0
    Public BLE_STATE_IDLE As Int = 1
    Public BLE_STATE_SCANNING As Int = 2
    Public BLE_STATE_CONNECTING As Int = 3
    Public BLE_STATE_READING As Int = 4
    Public BLE_STATE_STREAMING As Int = 5
 
    Public BLEState As Int = BLE_STATE_OFF
 
End Sub

Sub Service_Create
    'This is the program entry point.
    'This is a good place to load resources that are not specific to a single activity.

    manager.Initialize("manager")
      
End Sub

Sub Service_Start (StartingIntent As Intent)
 
End Sub

Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
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

Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
 
    Log(Id & " " & Name)
      
    If Id.EndsWith("B9:AA") Then    'last 4 digits of Id are usually enough to identify a particular device during testing
        manager.StopScan
      
        BLEName = Name
        BLEId = Id
      
        manager.Connect2(BLEId, False)
        BLEState = BLE_STATE_CONNECTING
    End If
 
End Sub

Sub Manager_Connected(Services As List)
 
    For Each S As String In Services
        Log(S)
        If S.StartsWith("cc4a6a80") Then
            BLEService = S
          
            manager.ReadData(BLEService)
            BLEState = BLE_STATE_READING
        End If
    Next
 
End Sub

Sub Manager_DataAvailable(ServiceID As String, Characteristics As Map)
 
    For Each S As String In Characteristics.Keys
        Log(S)
        If S.StartsWith("835ab4c0") Then
            BLECharacteristic = S
          
            Dim TempB() As Byte = Characteristics.Get(BLECharacteristic)
            Dim TempS() As Short = bc.ShortsFromBytes(TempB)
          
            Log(TempS(0))
          
            If BLEState <> BLE_STATE_STREAMING Then
                manager.SetNotify(BLEService, BLECharacteristic, True)
                BLEState = BLE_STATE_STREAMING
            End If
        End If
    Next
 
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, True)
        BLEState = BLE_STATE_SCANNING
      
        Sleep(5000)
      
        If BLEState = BLE_STATE_SCANNING Then
            manager.StopScan
            BLEState = BLE_STATE_IDLE
        End If
    End If

End Sub

ON MAIN
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

    Dim rp As RuntimePermissions
  
End Sub


Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")

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

LOG
B4X:
Logger connesso a:  samsung SM-T585
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
sending message to waiting queue (activity_permissionresult)
running waiting messages (1)
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
sending message to waiting queue (activity_permissionresult)
running waiting messages (1)
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
Logger connesso a:  samsung SM-T585
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
sending message to waiting queue (activity_permissionresult)
running waiting messages (1)
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
sending message to waiting queue (activity_permissionresult)
running waiting messages (1)
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
sending message to waiting queue (activity_permissionresult)
running waiting messages (1)
** Activity (main) Resume **
CC:50:E3:99:B9:AA
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Service (starter) Destroy (ignored)**

Program find device but can't connect
 
Upvote 0

emexes

Expert
Licensed User
have same problem.
Now scan stop after first time, but connection doesn't work
Program find device but can't connect
I did test that minimal code at this end and it worked fine, but... Einstein here forgot that your BLE problem is probably due to multiple DeviceFounds coming in at a faster rate than they do from my BLE device. Sorry. Cure for that would be:
B4X:
Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
 
    Log(Id & " " & Name)
      
    If Id.EndsWith("B9:AA") Then    'last 4 digits of Id are usually enough to identify a particular device during testing
        If BLEState = BLE_SCANNING then    '''added
            manager.StopScan
      
            BLEName = Name
            BLEId = Id
      
            manager.Connect2(BLEId, False)
            BLEState = BLE_STATE_CONNECTING
            Log("Connecting to " & BLEId)    '''added
        End If    '''added
    End If
 
End Sub
where I've added three lines, all marked with '''added.

If that still doesn't work, my next test would be to just comment out the manager.StopScan, see if that makes a difference.
 
Upvote 0

emexes

Expert
Licensed User
Sorry emexes, what means?
In the log you supplied, I highlighted three calls to Connect() in red.

The first Connect(), to the correct device, is probably clobbered by the second Connect() which is to the same device, which is probably clobbered by the third Connect() which is to the "ID130Plus Color HR" device.

We shouldn't even be trying to connect to that last device, and we've temporarily fixed that by filtering Id using: If Id.EndsWith("B9:AA") Then


Start Scan with callback
onScannerRegistered() - status=0 scannerId=9 mScannerId=0
Starting input: tba=android.view.inputmethod.EditorInfo@666c53e nm : com.mamavi.slimup ic=null
startInputInner - Id : 0
After accept
MSG_RESIZED_REPORT: frame=Rect(528, 531 - 1392, 705) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
MSG_RESIZED: frame=Rect(0, 0 - 1920, 1200) ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=2
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -60, AdvertisingData = (MyMap) {0=[B@283c51c}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=68feae2d-7554-407a-874b-85b51bfda76d
stopLeScan()
STATE_ON
STATE_ON
onClientRegistered() - status=0 clientIf=10
STATE_ON
STATE_ON
Stop Scan with callback
DeviceFound:
Found: Name = , id = CC:50:E3:99:B9:AA, RSSI = -60, AdvertisingData = (MyMap) {0=[B@6961708}
connect() - device: CC:50:E3:99:B9:AA, auto: false
isSecureModeEnabled
registerApp()
registerApp() - UUID=908c53f5-ab5c-4206-9774-c97e34af9043
onClientRegistered() - status=0 clientIf=9
DeviceFound: ID130Plus Color HR
Found: Name = ID130Plus Color HR, id = FC:C3:E9:71:3B:5D, RSSI = -86, AdvertisingData = (MyMap) {25=[B@11c6ea1, 1=[B@45658c6, 3=[B@6f45087, 9=[B@5f99bb4, -1=[B@9f053dd, 0=[B@ecf3b52}
connect() - device: FC:C3:E9:71:3B:5D, auto: false



 
Upvote 0
Top