Android Question [SOLVED]Write in 0x2902 BT characteristic

stefanoxjx

Active Member
Licensed User
Longtime User
Hi, I've a Cypress Bluetooth module and I need to receive and send data to this by serial service.
I've downloaded the Bluetooth example from here: https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/
I can connect to module, but can't send data.
Through LightBlue App I can send data without problems, to 0x2902 characteristic.
I don't undestand how I can modify to Bluetooth example to send data in this characteristic.
Can you help me?
Thanks.
Regards.
 

f0raster0

Well-Known Member
Licensed User
Longtime User
Hi, I've a Cypress Bluetooth module and I need to receive and send data to this by serial service.
I've downloaded the Bluetooth example from here: https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/
I can connect to module, but can't send data.
Through LightBlue App I can send data without problems, to 0x2902 characteristic.
I don't undestand how I can modify to Bluetooth example to send data in this characteristic.
Can you help me?
Thanks.
Regards.
don't know that modules..but probably you need something like
manager.writeData("00001554-1212-efde-1523-785feabcd123","0000155f-1212-efde-1523-785feabcd123", data)
look for writedata ble in the forum
 
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
I still don't know b4a very well and to speed up the result I need, I tried to find an already working software.
I found 4020Serial (https://www.b4x.com/android/forum/t...guration-descriptor-0x2902.81881/#post-559930).
I've changed name ed mac address of device to connect and the id of characteristic.
But, when I send data, I receive this error:

Error occurred on line: 141 (BT_Service)
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.keywords.Common.CallSubDebug2(Common.java:1055)
at rn4020.my_chat.main._btnsend_click(main.java:996)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:732)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:348)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:197)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:80)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at anywheresoftware.b4a.debug.Debug.CallSub4(Debug.java:336)
at anywheresoftware.b4a.debug.Debug.CallSubNew2(Debug.java:285)
... 21 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.debug.Debug.CallSub4(Debug.java:318)
... 22 more
Caused by: java.lang.RuntimeException: Service not found
at anywheresoftware.b4a.objects.BleManager2.getService(BleManager2.java:397)
at anywheresoftware.b4a.objects.BleManager2.WriteData(BleManager2.java:350)
at rn4020.my_chat.bt_service._writepkt(bt_service.java:535)
at rn4020.my_chat.bt_service._sendstr(bt_service.java:214)
... 24 more

The line 141 contains writeData instruction.
 
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
Hi Erel, I haven't posted the code because I've taken the software of "Metti Claude" and modified only two particulars.
This is the code:
B4X:
B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Service
Version=7.3
@EndOfDesignText@
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region
'------------------------------------------------
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
Public TimeConnected As Long
Public TimeDiscon As Long
Public ConnId As String
Public ConnRetry As Int
Public WriteStatus As Int
Public msgLen As Int            ' for sendStr
Public msgPtr As Int            ' for sendStr
Public msgPkt As String         ' for sendStr
Public msgAll As String
Public CR_LF As String = Chr(13) & Chr(10)

Public Name0 As String = "BTTEST"  '//Modified by Stefanoxjx
Public Name1 As String = "MyBleVT"

Private MLDP_PRIVATE_SERVICE As String = "00002902-0000-1000-8000-00805f9b34fb" '//Modified by Stefanoxjx
Private MLDP_DATA_PRIVATE_CHAR As String = "00002902-0000-1000-8000-00805f9b34fb"  'TX '//Modified by Stefanoxjx


End Sub
'------------------------------------------------

Sub Service_Create
    
    manager.Initialize("manager")
'event, Sub Manager_StateChanged will be rised

End Sub
'------------------------------------------------

Sub Service_Start (StartingIntent As Intent)

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
'------------------------------------------------

Public Sub Scan
    Log ("Scanning")
    ConnRetry = 0
    'manager.Scan(Null)
    manager.Scan2(Null,False)   'all devices, no duplicates
End Sub
'------------------------------------------------

public Sub stopScan
    Log ("scan stopped")
    manager.StopScan
End Sub
'------------------------------------------------

Public Sub ReadData
    ' Read message on the data channel
    manager.ReadData2(MLDP_PRIVATE_SERVICE, MLDP_DATA_PRIVATE_CHAR)
End Sub
'------------------------------------------------

Public Sub SendStr(Data As String)  'CallSub2(BT_Service, "SendStr", "Chat test" & CR) 'identify app to RN4020.
                                    '    Public CR As String = Chr(13) & Chr(10)
        Log("Sending: " & Data)
    msgAll = Data
    msgAll = msgAll & CR_LF
    msgLen = msgAll.Length
    msgPtr=0
    
    writePkt
End Sub
'------------------------------------------------

Sub Manager_WriteComplete (Characteristic As String, Status As Int)
    If connected = False Then Return
        Log("Writecomplete: " & Characteristic)
        Log("Status=" & Status)
    writePkt
End Sub
'------------------------------------------------

Sub writePkt
' if the string to send is longer than 20 bytes (BLE limit) this breaks
' it down to multiple "packets" of 20 to complete the message.
    If msgLen = 0 Then  Return    'meer dan 19 bytes werkt niet
    
    If msgLen > 20 Then
        msgPkt = msgAll.SubString2(msgPtr,msgPtr+20)
        msgPtr = msgPtr+20
        msgLen = msgLen -20
    Else
        msgPkt = msgAll.SubString(msgPtr)
        msgLen = 0
    End If

    Dim D() As Byte = msgPkt.GetBytes("UTF8")
    delay(125)    '125 sending multiple back to back packets fails without this delay.
    
manager.WriteData(MLDP_PRIVATE_SERVICE, MLDP_DATA_PRIVATE_CHAR, D)
    manager.SetNotify(MLDP_PRIVATE_SERVICE, MLDP_DATA_PRIVATE_CHAR, True)
    
End Sub
'------------------------------------------------

Sub Manager_DataAvailable (ServiceId As String, Characteristics As Map)'MLDP_PRIVATE_SERVICE
    Log("DA")
    Log(ServiceId)
    Log(Characteristics)
    CallSub3(Main, "DataAvailable", ServiceId, Characteristics)
End Sub
'------------------------------------------------

Public Sub Disconnect
    Log("Disconnecting")
    If connected Then   'Boolean
        manager.SetNotify(MLDP_PRIVATE_SERVICE, MLDP_DATA_PRIVATE_CHAR, False)
        manager.Disconnect
    End If
    
End Sub
'------------------------------------------------

Sub Manager_StateChanged (State As Int)  'will be raised at start
    Select State
        Case manager.STATE_POWERED_OFF
            currentStateText = "POWERED OFF"

            Case manager.STATE_POWERED_ON
            currentStateText = "POWERED ON"
                        Log("BT State = Powered On")
                        
        Case manager.STATE_UNSUPPORTED
            currentStateText = "UNSUPPORTED"
            
    End Select
    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
    ConnId = Id
    If ConnectedName = Null Then
        Log("no name found")
        ConnectedName = "no name"
    End If
    
        If ConnId = "DB:38:03:98:58:6D" Then '//Modified by Stefanoxjx
        manager.StopScan
        CallSub2(Main, "putStatus", "Connecting")
        manager.Connect2(ConnId,False)
        Log(ConnectedName & " connected")
        Return
        End If
       
End Sub


Sub Manager_Disconnected
    Log("Disconnected")
    connected = False
    TimeDiscon = DateTime.Now
    Log ("Connect duration = " & (TimeDiscon - TimeConnected) & " miliseconds")
    If (TimeDiscon - TimeConnected)< 400 Then    ' if < 400 msec do a connect retry
        ConnRetry = ConnRetry + 1
        CallSub2(Main,"putStatus","Retry " & ConnRetry)
        If ConnRetry < 5 Then                    ' max of 5 retries
            Log ("Retry = " & ConnRetry)
            manager.Connect2(ConnId,False)
        End If
    End If
    
    CallSub(Main, "BT_Disconnected")
        
End Sub
'------------------------------------------------

Sub Manager_Connected (services As List)  'list my services in the log
    Log("Manager-Connected-EVENT")
    Dim List1 As List
List1.Initialize
List1.AddAll(services)
For i=0 To List1.Size-1
Log(List1.Get(i))
Next

    TimeConnected = DateTime.Now
    connected = True
    CallSub(Main, "BT_Connected")
End Sub
'------------------------------------------------

public Sub delay(ms As Int)  'delay between packets
    Dim temp As Int
    Dim futuretime As Long
    futuretime = DateTime.Now + ms
    Do While DateTime.Now < futuretime
        temp=temp+1   'dummy stuff, not used
    Loop
End Sub
'------------------------------------------------


Thanks.
 
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
I would like to add that with LightBlue app, I see this:
1.png


and into "65333333-a115-11e2-9e9a-0800200ca101" I found this:
2.png


then (if I don't wrong), service "65333333-a115-11e2-9e9a-0800200ca101" and characteristic "00002902-0000-1000-8000-00805f9b34fb".
I tried to change call to WriteData with:
B4X:
manager.WriteData("65333333-a115-11e2-9e9a-0800200ca101", "00002902-0000-1000-8000-00805f9b34fb", D)
but I've error too.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
public Sub delay(ms As Int) 'delay between packets
I would never use code that create such delays.

I haven't posted the code because I've taken the software of "Metti Claude" and modified only two particulars.
It doesn't matter. We are not familiar with every piece of code that was posted in the forum...

Useful sub to get the long characteristic UUID from the short one:
B4X:
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

Start with the BLE example. Is this service listed?
 
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
You sure it's not a descriptor? Descriptors are treated differently to characteristics.

I searching to understand bluetooth and b4a toghether.
Too much meat on the fire, but I need to make as fast as possible an app to make some tests on one device I'm working.
Told this, I must write data on Service or descriptor?


Already seen, this is first discussione that I read.
 
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
Also page of its datasheet referring to what and why to write to descriptor 0x2902 ?

Pretty sure that descriptor 0x2902 is a 1-bit field, and that writes to it are done in B4A using BLE2 SetNotify.

One bit?
But if I send a string to this, it arrives without problem.
I don't understand anything anymore :eek:
 
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
No no, I explained myself wrong.
I intend that if I send a string with LightBlue it arrives.
The strings sent from b4a app don't arrives.
 
Upvote 0

emexes

Expert
Licensed User
I intend that if I send a string with LightBlue it arrives.
What characteristic do you write the string to with LightBlue to have it arrive on your BLE device?

Screen capture showing string about to be sent would be useful. Include as thumbnail rather than full image, to keep the thread easier to read.

I guess I'm going to have to download the LightBlue app to guess what it's doing, even though I don't have a BLE device to send strings to. 👍
 
Last edited:
Upvote 0

stefanoxjx

Active Member
Licensed User
Longtime User
Hi, I send to service 65333333-a115-11e2-9e9a-0800200ca100 and characteristics:
65333333-a115-11e2-9e9a-0800200ca101
65333333-a115-11e2-9e9a-0800200ca102

This is a screenshot of LightBlue of service: 65333333-a115-11e2-9e9a-0800200ca100
1.png
 
Upvote 0
Top