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: 275

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
Unfortunately nothing, we were rehearsing now.
I attach the log, but the second connect of the previous version depended on the fact that the first one was not successful and the program restarted the scan, and then another connect.
Has anyone had similar skills?
We have our customer waiting for.....
Thanks all
Marcom
B4X:
Logger connesso a:  samsung SM-T585
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
CC:50:E3:99:B9:AA
Connecting to CC:50:E3:99:B9:AA
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
I repeat the test without log filters and I have this log line:

B4X:
onClientConnectionState() - status=133 clientIf=8 device=CC:50:E3:99:B9:AA

I read some posts about status 133 but nothing for B4A.
Someone know something about this status?
 
Upvote 0

emexes

Expert
Licensed User
I attach the log, but the second connect of the previous version depended on the fact that the first one was not successful and the program restarted the scan, and then another connect.
Ok, that's good to know.

Perhaps 5 seconds is not a long-enough scan time, so try changing this section of the StartScan Sub from:
B4X:
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
to:
B4X:
Else
    manager.Scan2(Null, True)
    BLEState = BLE_STATE_SCANNING
    Log("Scanning...")    '''added
    
    Sleep(20000)    '''was 5000
    
    If BLEState = BLE_STATE_SCANNING Then
        manager.StopScan
        BLEState = BLE_STATE_IDLE
        Log("StopScan")    '''added
    End If
End If

Another tack would be to try connecting with the other BLE device that is shown in your log, by changing the Id filter from:
B4X:
If Id.EndsWith("B9:AA") Then
to:
B4X:
If Id.EndsWith("3B:5D") Then
Or do you have any other BLE devices nearby that you can test with?
 
Upvote 0

emexes

Expert
Licensed User
This might be a stupid question, but: is it possible that some other device in the room, or app on the phone, is connected to the SCP32? BLE devices generally allow one connection at a time, and if a connection is already active, I would expect it to not accept any additional connections.

With the BLE pressure sensors that I've got here, they stop advertising when someone is connected to them, but I'm guessing it's entirely plausible, and even reasonable, that a BLE device could continue advertising even when it has an active connection.
 
Upvote 0

emexes

Expert
Licensed User
I repeat the test without log filters and I have this log line:

B4X:
onClientConnectionState() - status=133 clientIf=8 device=CC:50:E3:99:B9:AA

I read some posts about status 133 but nothing for B4A.
Someone know something about this status?
What I found in your earlier post of an unfiltered log was status 133 but for the "ID130Plus Color HR" device:
B4X:
Found: Name = ID130Plus Color HR, id = FC:C3:E9:71:3B:5D, RSSI = -86, AdvertisingData = ...
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 = ...
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
so that does not bode well for being able to connect to that device either.

What I missed previously is that there is yet another BLE device in the room, the Gear S3 with id ending in DE:3A. And that the connect request to that device might be what clobbered the attempted connection to the ID130 Plus Color HR device.

So perhaps try connecting to the Gear S3 too. Third time's the charm!
 
Upvote 0

emexes

Expert
Licensed User
Righto, I did some searching about Bluetooth status 133, and you're not the first to have experienced it ;-)

In some cases, there were fixes made to Android itself. If you have other Android phones available that have BLE, give them a try.

Other people have said they've fixed it by various actions, including:

- reboot phone
- "I am consistently able to avoid the problem by restarting Bluetooth in the related Bluetooth Settings application. The most likely reason is the clearing of the GATT cache when stopping the Bluetooth subsystem."
- issue a Disconnect even though you don't seem to have connected (not quite sure how this will work - perhaps use a Try .. Catch)
- "I try to reconnect up to 5 times with a delay of 1000ms In most cases 2nd or 3rd retry will connect without the error."

So perhaps give some (or all) of those a try too.
 
Upvote 0

emexes

Expert
Licensed User
And one pretty convincing post said this:
After months of research and pulling my hair out, I have found a solution that is not normally talked about.

Your normal connect request looks something like this:

cGatt.connectGatt(this, false, gattCallback);

There is another version of the connectGatt command, with a 4th parameter. This parameter specifies what type of bluetooth device you are connecting to. I added a "2" to specify that I am connecting via Bluetooth LE. (it's called "transport", forgive me if my explanation is incorrect, but it solved all my problems)

Try this:

cGatt.connectGatt(this, false, gattCallback, 2);

And BAM, now my #133 nightmare is over (I pray)!

answered Jan 30 '18 at 17:07

Dude, you ended a 5+ hours search! THANKS!!!!!!! – Boris Apr 27 '18 at 21:55
but that would be something internal to the BLE2 library, and I expect that Erel would have already done this given that it is specifically Bluetooth Low Energy, not Bluetooth Classic. But you never know. Still, try the other options first, before we ask him about this.
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
I noticed another thing.
I have the primary service id of my chip: 0000a002-0000-1000-8000-00805f9b34fb
I use this code in two cases:

CASE 1
B4X:
        manager.Scan(Array(UUID("a002")))
...
...
...
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

CASE 2
B4X:
        manager.Scan(null)

On CASE 1 I doesn't find my device
On CASE 2 I find my device but I can't connect

I Tried to use same 2 cases with B4A Peripheral app (by Erel)
On CASE 1 I find and connect B4a Peripheral
On CASE 2 I can't find B4a Peripheral

This is the opposite, but whit B4A Peripheral i can connect...
Why does it happen?
 
Upvote 0
I also searched for the following error and I noticed just like you that we are not the first to ask these questions, to answer your previous questions the chip is not associated with any device and I'm sure nobody is connected to the chip, I know this because if I connect to the chip from the Nrf Connect application, I see on Realterm the chip that answers me in case a device connects to it.
 
Upvote 0

emexes

Expert
Licensed User
B4X:
manager.Scan(Array(UUID("a002")))
B4X:
manager.Scan(null)
I've been reading a lot about BLE status 133. In amongst all that, a couple of times I've seen advice that filtered scans don't work, but also one person says they haven't had a problem. It sounds like a lot of the issues depend on what Android version is being used.

I Tried to use same 2 cases with B4A Peripheral app (by Erel)
On CASE 1 I find and connect B4a Peripheral
STOP RIGHT THERE!!!! and then tread very carefully, lest we upset the Bluetooth Gods!

Ok, so you've got working code that hooks up to your SCP32 BLE device? From that point, I would be putting Log() around every BLE call in the working and not-working programs, and finding out what is different between the two. DateTime.Now will give you millisecond timestamps - several people advised putting delays between BLE operations.
 
Upvote 0
yes the code is working but it connects to the peripheral B4A and not to the SCP32 chip, to the SCP32 chip I can connect only through an application called Nrf Connect, this indicates to me that the chip is turned on and that inside I read all the UUID of the services configured on the SCP32 chip, in fact when I connect to the chip via nrf connect, on the terminal of my pc where I currently connected the chip in test by micro usb, it returns the log that my phone has connected. I hope I was clear, I'm not very good with the English language.
 
Upvote 0

emexes

Expert
Licensed User
Try the attached super basic app. Press button to do BLE2 manager actions. Generally go top to bottom, one button press per line. No rush ;-)

upload_2019-6-27_6-13-53.png


My log looked like this. Note that it took 6 seconds to connect. Sometimes it takes up to 15 seconds. Probably does not help that the BLE device is on the other side of the room at the moment, but... always good to test stuff in realistic conditions ;-)
B4X:
Logger connected to:  TCL 5009A
--------- beginning of system
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
DoInitialize
Good to go
DoScan
Device Found Id=[FF:FF:C0:20:9A:E5] Name=[iTAG            ], RSSI=-64
Device Found Id=[69:43:90:16:A9:F8] Name=[], RSSI=-64
Device Found Id=[3A:3C:A1:9F:4B:FB] Name=[], RSSI=-94
Device Found Id=[A0:E6:F8:4D:1D:26] Name=[63607], RSSI=-48
Device Found Id=[F8:B4:86:32:9D:0A] Name=[34506               ], RSSI=-80
Device Found Id=[A0:E6:F8:4D:1D:71] Name=[63472], RSSI=-71
Device Found Id=[C8:69:CD:10:1E:C9] Name=[], RSSI=-94
Device Found Id=[5C:D8:D7:B9:FD:09] Name=[], RSSI=-96
Device Found Id=[79:C1:3D:BA:10:DA] Name=[], RSSI=-97
DoStopScan
DoConnect F8:B4:86:32:9D:0A
Discovering services.
Manager_Connected
connection time = 6.100 s
  [00001800-0000-1000-8000-00805f9b34fb]
  [00001801-0000-1000-8000-00805f9b34fb]
  [cc4a6a80-51e0-11e3-b451-0002a5d5c51b]
  [0000180f-0000-1000-8000-00805f9b34fb]
  [00001804-0000-1000-8000-00805f9b34fb]
  [0000180a-0000-1000-8000-00805f9b34fb]
  [000018ff-0000-1000-8000-00805f9b34fb]
DoDisconnect
 

Attachments

  • TestBLE.zip
    10 KB · Views: 241
Upvote 0

emexes

Expert
Licensed User
Note that it took 6 seconds to connect. Sometimes it takes up to 15 seconds.
I was wrong - make that 20-something seconds :-/
B4X:
DoScan2False
Device Found Id=[A0:E6:F8:4D:1D:26] Name=[63607], RSSI=-46
Device Found Id=[6E:87:8A:40:70:50] Name=[], RSSI=-66
Device Found Id=[C8:69:CD:10:1E:C9] Name=[], RSSI=-92
Device Found Id=[3A:3C:A1:9F:4B:FB] Name=[], RSSI=-93
Device Found Id=[F8:B4:86:32:9D:0A] Name=[34506               ], RSSI=-71
Device Found Id=[A0:E6:F8:4D:1D:71] Name=[63472], RSSI=-67
Device Found Id=[2B:AE:8F:C3:1E:9C] Name=[], RSSI=-98
DoStopScan
DoConnect F8:B4:86:32:9D:0A
Discovering services.
Manager_Connected
connection time = 22.444 s
  [00001800-0000-1000-8000-00805f9b34fb]
  [00001801-0000-1000-8000-00805f9b34fb]
  [cc4a6a80-51e0-11e3-b451-0002a5d5c51b]
  [0000180f-0000-1000-8000-00805f9b34fb]
  [00001804-0000-1000-8000-00805f9b34fb]
  [0000180a-0000-1000-8000-00805f9b34fb]
  [000018ff-0000-1000-8000-00805f9b34fb]
DoDisconnect

Update: I was wrong again - make that 30-something seconds :-(
B4X:
DoScan
Device Found Id=[6E:87:8A:40:70:50] Name=[], RSSI=-64
Device Found Id=[3A:3C:A1:9F:4B:FB] Name=[], RSSI=-97
Device Found Id=[C8:69:CD:10:1E:C9] Name=[], RSSI=-91
Device Found Id=[A0:E6:F8:4D:1D:26] Name=[63607], RSSI=-49
Device Found Id=[F8:B4:86:32:9D:0A] Name=[34506               ], RSSI=-72
Device Found Id=[A0:E6:F8:4D:1D:71] Name=[63472], RSSI=-67
DoStopScan
DoConnect F8:B4:86:32:9D:0A
Discovering services.
Manager_Connected
connection time = 33.567 s
  [00001800-0000-1000-8000-00805f9b34fb]
  [00001801-0000-1000-8000-00805f9b34fb]
  [cc4a6a80-51e0-11e3-b451-0002a5d5c51b]
  [0000180f-0000-1000-8000-00805f9b34fb]
  [00001804-0000-1000-8000-00805f9b34fb]
  [0000180a-0000-1000-8000-00805f9b34fb]
  [000018ff-0000-1000-8000-00805f9b34fb]
DoDisconnect

Keywords for search: BLE long connect time long connection time long time to connect
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
I hope I was clear, I'm not very good with the English language.
Your English is much better than my Italian ;-)

Sometimes I've had to read it several times word-by-word, but I think that is because it is a complicated topic which requires precision. I have less problem understanding your descriptions of events than I do understanding my teenage son's explanations of why he is late for school or whatever.

But I should remember to keep my sentences shorter, with just one thought per sentence, to lighten the translation load at your end.
 
Upvote 0
I would like to update you on the problem since you have been very kind to help us, after many tests and tests and above all after your advice, we have noticed that the BT chip was accessible from Nrf Connect from android and not from Iphone, The chip was started correctly with the AT commands that I had obtained from the documentation, but in the AT command to start the service it was necessary to send the parameter bit1 of the flags LE General Discoverable mode, currently the connection runs but we have not yet tested the reading and writing of the Services set in the Chip but we are confident.
 
Upvote 0

emexes

Expert
Licensed User
So we'll call this a win? Sometimes programming, and especially BLE programming, needs a healthy dose of perseverance:

upload_2019-3-8_23-50-49-png.78161


;-)
 
Upvote 0

emexes

Expert
Licensed User
we have noticed that the BT chip was accessible from Nrf Connect from android and not from Iphone
Well, that's a bit of a worry. I am relying on: if it is not connectable from B4A, then it is not connectable from Nrf Connect.

... it was necessary to send the parameter bit1 of the flags LE General Discoverable mode
Are you certain that you could connect to the SCP32 using Android Nrf Connect even though the SCP32 was not discoverable? If you could temporarily put that bit back to the non-discoverable state and then try connecting from Nrf Connect on Android and iPhone, that information could be useful for future BLE programmers.

I would be happy if neither of them connect to a non-discoverable SCP32, and to assume your earlier achieving-the-impossible-and-connecting-anyway was enabled by some other forgotten change made in the heat of battle, eg, maybe you'd temporarily used some other example firmware when trying to isolate the problem, or maybe the SCP32 defaults on startup to being discoverable and thus there was a window of opportunity between SCP32 startup and your firmware sending a new configuration.

not yet tested the reading and writing of the Services set in the Chip but we are confident.
+1
 
Upvote 0
Top