B4i Library BLE (Bluetooth Low Energy) library

B4i BLE library is now available. This library allows you to connect and read data from BLE peripheral devices.

Using this library is quite simple. There are three main steps:
1. Search for devices (assuming that the state is STATE_POWERED_ON).
2. Connect to a device.
3. Read data from the device.

There are several events which you need to handle:
StateChanged (State As Int) - This event is raised when you initialize BleManager and when the BLE adapter state changes. Only if the state is STATE_POWERED_ON then you can use this feature.

DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double) - Raised when a new device is discovered (after you call BleManager.Scan). The event parameters include the device Id, name, RSSI value and a Map with additional advertised data.

Connected (Services As List) - Raised when a device is connected. The Services list holds the device service ids. The data on the device is stored in a tree like structure made of services that hold characteristics.

DataAvailable (Service As String, Characteristics As Map) - Raised after you call Manager.ReadData. Service is the service that was read and Characteristics is a Map that holds the characteristics ids and values. The values are arrays of bytes.

Disconnected - Raised after a failed connection or after a device has disconnected.

Make sure to see the video in HD mode (click on the small gear button).


iBLE is now included as a preinstalled library.

Example was updated with a new requirement:
B4X:
#PlistExtra: <key>NSBluetoothAlwaysUsageDescription</key><string>Bluetooth used to connect to ...</string>
You should change the description as needed.

B4XPages example: https://www.b4x.com/android/forum/threads/b4x-ble-2-bluetooth-low-energy.59937/
 

Attachments

  • BleExample.zip
    4.1 KB · Views: 448
Last edited:
D

Deleted member 103

Guest
Hi,

I can connect this keyboard with the iPhone and it works with the installed apps.
With this BLE-example, but does not work, why?
The keyboard is not found.
 

andreahaku

Member
Licensed User
Longtime User
BLE is not Bluetooth. It is based on Bluetooth and it's part of Bluetooth 4.0 but it's a different things. BLE devices are different than Bluetooth ones and vice versa. So a bluetooth keyboard can't be connected using BLE.
 

Alberto Iglesias

Well-Known Member
Licensed User
Longtime User
In the original BLE sample, in this post, when I scan for devices, I got this error

ErrorBLE.jpg


???

Anyone have an idea?

Thanks
 

vincentehsu

Member
Licensed User
Longtime User
Dear Sir:
is there any sample code with wirtedata? i don't know how to get the response from bt device
 

vincentehsu

Member
Licensed User
Longtime User
the second parameter characteristic is the bt mac address?I always receive error as below

B4X:
Dim TriggerPayment() As Byte=Array As Byte(0, 2, 242, 242)
    manager.WriteData(AStream_NewData,TerminalID,TriggerPayment)

Sub AStream_NewData ()
    If AStreamType=1 Then
        Dim TagData As String=""
        Dim i As Int
'        For i=0 To Buffer.Length-1
'            TagData=TagData & IIF(Len(Bit.ToHexString((Bit.AND(Buffer(i),0xFF))))=1,"0" & Bit.ToHexString((Bit.AND(Buffer(i),0xFF))),Bit.ToHexString((Bit.AND(Buffer(i),0xFF))))
'        Next
        lbl_Parameter1.Text=Mid(TagData,135,2)
        lbl_Parameter2.Text=Mid(TagData,137,2)
    Else If AStreamType=2 Then
        Dim TagData As String=""
        Dim i As Int
'        For i=0 To Buffer.Length-1
'            TagData=TagData & IIF(Len(Bit.ToHexString((Bit.AND(Buffer(i),0xFF))))=1,"0" & Bit.ToHexString((Bit.AND(Buffer(i),0xFF))),Bit.ToHexString((Bit.AND(Buffer(i),0xFF))))
'        Next
        If TagData="0003000000" Then
           
        Else
            Msgbox("Update Fail...","TMS")
        End If
    End If
End Sub

B4X:
Error occurred on line: 515 (main)
Service not found
Stack Trace: (
  CoreFoundation       <redacted> + 150
  libobjc.A.dylib      objc_exception_throw + 38
  CoreFoundation       <redacted> + 0
  Apple test           -[BleManager getService:] + 532
  Apple test           -[BleManager WriteData:::] + 190
  Apple test           -[b4i_main _getparameter] + 1304
  CoreFoundation       <redacted> + 68
  CoreFoundation       <redacted> + 300
  Apple test           +[B4I runDynamicMethod:method:throwErrorIfMissing:args:] + 1928
  Apple test           -[B4IShell runMethod:] + 496
Apple test           -[B4IShell raiseEventImpl:method:args::] + 2060
Apple test           -[B4IShellBI raiseEvent:event:params:] + 1316
Apple test           __33-[B4I raiseUIEvent:event:params:]_block_invoke + 74
libdispatch.dylib    <redacted> + 10
libdispatch.dylib    <redacted> + 22
libdispatch.dylib    _dispatch_main_queue_callback_4CF + 718
CoreFoundation       <redacted> + 8
CoreFoundation       <redacted> + 1512
CoreFoundation       CFRunLoopRunSpecific + 476
CoreFoundation       CFRunLoopRunInMode + 106
GraphicsServices     GSEventRunModal + 136
UIKit                UIApplicationMain + 1440
Apple test           main + 116
libdyld.dylib        <redacted> + 2
)
when i writedata to my bt device i need get the response data from it,there is no other way to get response?
 
D

Deleted member 103

Guest
Hi,

I should send and receive asynchronous single character, but I do not understand how it should work.
Can someone give me an example?
 
D

Deleted member 103

Guest
Start with reading. Run the example in the first post.
Should I done the reading into a timer? I can not always have to press the button.
I beg your pardon, but I do not understand. :(
 
D

Deleted member 103

Guest
I still need help, because I do not understand this "Characteristics".
This is part of my code:
B4X:
Private Sub btManager_Connected (services As List)
'   lblDeviceStatus.Text = "Connected - " & connectedDevice.Name
   ConnectedServices = services
   SetState(True)
   timerSpeed.Enabled = IsBtConnected
End Sub

Private Sub btManager_DataAvailable (Service As String, Characteristics As Map)
   Dim bc As ByteConverter
   Dim KeyCode As String

   For Each id As String In Characteristics.Keys
     KeyCode = Characteristics.Get(id)
     Log("KeyCode=" & KeyCode)
     Log( bc.HexFromBytes( Characteristics.Get(id) ) )
   Next
End Sub
   
Sub timerSpeed_Tick   
   btManager.ReadData(ConnectedServices.Get(0))
     
   'Led blinken lassen solange eine BT-Verbindung vorhanden ist.
   ledBlinkTime = ledBlinkTime + timerSpeed.Interval
   If ledBlinkTime > 200 Then
     If IsBtConnected Then btManager.WriteData(ConnectedServices.Get(0), 0x00, "1".GetBytes("UTF8")) 'Led ON
     ledBlinkTime = 0
'     Log("Led ON")
   End If
End Sub

and these are the logs:
Found: HMSoft, 226C1B21-B1B2-E90F-6D71-2ACE4A61D0C8, RSSI = -57, (read only map) {
kCBAdvDataIsConnectable = 1;
kCBAdvDataLocalName = HMSoft;
kCBAdvDataManufacturerData = <484db499 4c7177eb>;
kCBAdvDataServiceData = {
B000 = <00000000>;
};
kCBAdvDataServiceUUIDs = (
FFE0
);
kCBAdvDataTxPowerLevel = 0;
}
Discovering services
Services discovery completed.
KeyCode=<B4IArray: 0x16759e00>
00
KeyCode=<B4IArray: 0x17865330>
00
KeyCode=<B4IArray: 0x1677e1b0>
00
KeyCode=<B4IArray: 0x1650bd90>
00
KeyCode=<B4IArray: 0x16782ad0>
00
KeyCode=<B4IArray: 0x17885fa0>
00
KeyCode=<B4IArray: 0x1653a5c0>
00
KeyCode=<B4IArray: 0x178409e0>
00
KeyCode=<B4IArray: 0x16780df0>
00
Error occurred on line: 430 (clsbluetooth)
Characteristic not found: 0
Stack Trace: (
CoreFoundation <redacted> + 150
libobjc.A.dylib objc_exception_throw + 38
CoreFoundation <redacted> + 0
CMM-Ultra -[BleManager WriteData:::] + 516
CoreFoundation <redacted> + 68
CoreFoundation <redacted> + 300
CMM-Ultra +[B4I runDynamicMethod:method:throwErrorIfMissing:args:] + 1928
CMM-Ultra -[B4IShell runVoidMethod] + 210
CMM-Ultra -[B4IShell raiseEventImpl:method:args::] + 2002
CMM-Ultra -[B4IShellBI raiseEvent:event:params:] + 1316
CMM-Ultra __24-[B4ITimer startTicking]_block_invoke + 298
libdispatch.dylib <redacted> + 10
libdispatch.dylib <redacted> + 66
libdispatch.dylib <redacted> + 22
libdispatch.dylib <redacted> + 626
libdispatch.dylib <redacted> + 212
libdispatch.dylib _dispatch_main_queue_callback_4CF + 330
CoreFoundation <redacted> + 8
CoreFoundation <redacted> + 1512
CoreFoundation CFRunLoopRunSpecific + 476
CoreFoundation CFRunLoopRunInMode + 106
GraphicsServices GSEventRunModal + 136
UIKit UIApplicationMain + 1440
CMM-Ultra main + 116
libdyld.dylib <redacted> + 2
)
 
Last edited by a moderator:
Top