hBasic > hManual > Commands > Bluetooth BLE

hBasic Manual
Bluetooth Low Energy Grau API

This is the BLE Client API from GRAU BASIC! designed by greymfm76 plus a few enhancements.

Error Handling Read This First
BLE.OPEN open BLE session
BLE.CLOSE close BLE session
BLE.CONNECT connect to a device
BLE.STATUS get connection status
BLE.DISCONNECT disconnect from a device
BLE.STATUS get connection status
BLE.SCAN start/stop scanning
BLE.NOTIFY set characteristic notifications (push updates)
BLE.READ.REQUEST request a read from a characteristic
BLE.READ read a device characteristic
BLE.WRITE write to a device characteristic
BLE.DEVICES get scanned devices to an array
BLE.NAME get the name of a device
BLE.RSSI get the RSSI of a device
BLE.TEASERS get service teasers from connected device
BLE.SERVICES get services from connected device
BLE.CHARACTERISTICS get characteristics of a service from connected device
BLE.PROPERTIES get properties of a characteristic from connected device
BLE.TIMEOUT set timeout for some command actions

Use of getError$() and other tips.

A copy of the original grau sample files are can be found here.
Error Handling

Use of getError$()
Run-time-errors are intentionally kept to a minimum.
Many errors are non-fatal and so instead, most BLE commands will record an error message
into the system function getError$() and your program will not stop.

If there is no error, getError$() will be empty.

e,g
BLE.WRITE chwrite$, chr$(byte)
e$ = getError$()
if e$<>"" then print "Error: "+e$ : END

Commands that support getError$() are
BLE.OPEN
BLE.CONNECT
BLE.NOTIFY
BLE.READ.REQUEST
BLE.WRITE
BLE.PROPERTIES

Exceptions
You will still get Run-Time-Errors for
Syntax-Errors
If No Bluetooth permsissions granted

Use of an error block
Use of the system Interrupt label onError: is discouraged because you will be trapping all errors,
  i.e if you have another error after onError: , e.g BLE.CLOSE, then you may enter an infinite loop and the interpreter will crash.

Use a normal label instead     e.g doError:

Example

BLE.write chwrite$, chr$(byte)
if getError$()<>"" then goto doError
PRINT "Write was sent"
END
            % be sure to stop any data
doError:
        PRINT "Error> ";getError$()
onBackKey:
        BLE.notify chdata$, 0
        BLE.close
END

BLE.OPEN 

BT.OPEN
Opens a BLE session

Any error message is recorded into getError$() otherwise it will be empty.

Example
BLE.OPEN
if getError$()<>"" then goto doError

BLE.CLOSE 

BT.CLOSE
Closes the BLE session.
Also disconnects any connected device and disables any scanning.

This will not stop any notifications from a device (server).

BLE.CONNECT

BLE.CONNECT  mac$_sexp
Connects directly to a device given the MAC address mac$.

After the call, the status of the connection is updated asynchronously. Get it using BLE.STATUS.

Any error message is recorded into getError$() otherwise it will be empty.

mac$
A MAC address is 6 hex bytes separated with colons
e.g 11:22:33:DD:EE:FF
It is exactly 17 characters long.

The MAC address is not optional.
If you don't already have a MAC address, you can get one from BLE.DEVICES

Example
BLE.OPEN

tout = 20
st$ = "Disconnected"
do
  if st$ = "Disconnected"
     BLE.CONNECT "
11:22:33:DD:EE:FF"
     if getError$()<>"" then goto doError
  endif

  if --tout < 0 then print "Stop. Timed out.":END
  pause 500

  BLE.STATUS st$
  if st$ <> last$
     last$ = st$
     print st$
  endif
until st$ = "Connected"
END
doError:
  print "Connect Error"
END


BLE.DISCONNECT

BLE.DISCONNECT
Disconnects the current device (if connected).

BLE.STATUS

BLE.STATUS  status_var
Get current connection status

status_var
A numeric or string variable to hold the result.

Returns values are;
Number
String
0
Disconnected
2
Connecting
3
Discovering
4
Connected

BLE.SCAN

BLE.SCAN  enable_lexp
Enables or Disables scanning for nearby devices.

BLE.NOTIFY

BLE.NOTIFY  characteristic_sexp , enable_nexp
Enable or Disable a characteristic notification for push updates on the currently connected device.

This is a request for continuous updates.
The device (server) responds by sending an (internal) acknowledgement and will later send data as updates.
Use BLE.READ to actually read them.

When an update occurs it is received and held in a session read-value holder.
It is up to you as to when to read it with BLE.READ.
There is no buffering at all. Each received value will overwrite any previous value, so your timing is important.

The update occurance is entirely up to the device (server).
Some devices only update if there are changes, while other devices might update periodically.

By default, hBasic will synchronise the request with the device(server) acknowledgement using a common timeout.
The timeout is by default 500ms, you can change it with BLE.TIMEOUT.
If this timeout is set to 0ms, then it becomes asynchronous (there is no wait) and you must insert pauses yourself.
A successful request only means an acknowledgement from the server. It does not mean any data has been sent.

Any error message is recorded into getError$() otherwise it will be empty.

characterisitic
The characteristic ID
e.g 00002a37-0000-1000-8000-00805f9b34fb
It must match one of the characteristic IDs of a service in the current connected device.
It must have the Notify Property.

enable
True = Request to turn on updates.
False = Request to turn off updates.

BLE.READ.REQUEST

BLE.READ.REQUEST  characteristic_sexp
Request a read for a given characteristic

This is a request for a one-time-read from the connected device.
The session read-value holder is cleared and a request is sent.
The device (server) responds by sending the characteristic value and the holder is filled.
Use BLE.READ to actually read it.

Note that values from the device (server) are not buffered.
Each received value will overwrite any previous value, so your timing is important.

By default, hBasic will synchronise the exchange with the device(server) using a common timeout.
The timeout is by default 500ms, you can change it with BLE.TIMEOUT.
If this timeout is set to 0ms, then it becomes asynchronous (there is no wait) and you must insert pauses yourself.
On a successful exchange, the data will have arrived and be ready to read.

Any error message is recorded into getError$() otherwise it will be empty.

characterisitic
The characteristic ID
e.g 00002a37-0000-1000-8000-00805f9b34fb
It must match one of the characteristic IDs of a service in the current connected device.

Example
BLE.READ.REQUEST chread$
if getError$()<>"" then goto doError

BLE.READ v$
END

BLE.READ

BLE.READ  value$_svar
Read a value that is held by the session read holder into value$.

Values are sent by the device (server) after BLE.NOTIFY or BLE.REQUEST.READ, and held in a temporary holder.
After a value is read, the holder is cleared.

The holder maybe overwritten at any time by the device (if using BLE.NOTIFY) or by the next BLE.REQUEST.READ,
so your timing is important.

value$
The string variable to get the data.

The value is binary data in the form of a Basic 'buffer string'. Each character is 16 bits.
The upper 8 bits are always zero. The lower 8 bits contains the value.

You can get the number of bytes returned with LEN(value$)
Byte values can be extracted with ASCII(value$, index) which will return a value from 0 to 255 (extended ASCII).
If a value$ is returned empy ("") It means nothing was received and ASCII(value$, index) returns a special 256.

Example
BLE.READ.REQUEST chread$
if getError$()<>"" then goto doError

BLE.READ v$         % expect 1 byte.
print "Read> ";
v=ascii(v$)        % empty string is always 256

if v=256 then print "(empty)" else print v
END

BLE.WRITE

BLE.WRITE  characteristic_sexp,  data_sexp
Write data to characteristic of the connected device.

By default, hBasic will synchronise the request with the device(server) using a common timeout.
The timeout is by default 500ms, you can change it with BLE.TIMEOUT.
If this timeout is set to 0ms, then it becomes asynchronous (there is no wait) and you must insert pauses yourself.
A successful request is only for the link layer, this means the server acknowledged this request before any actual write.

Any error message is recorded into getError$() otherwise it will be empty.

characterisitic
The characteristic ID
e.g 00002a37-0000-1000-8000-00805f9b34fb
It must match one of the characteristic IDs of a service in the current connected device.

data
The string to write.
The value is binary data in the form of a Basic 'buffer string'. Each character is 16 bits and is converted to a byte.
The upper 8 bits are always discarded. The lower 8 bits contains the value.

You can encode a value with CHR$(byte1,byte2,..).
An empy string ("") is still a valid payload, although it is discouraged depending on the device (server) recieving it.

Example
BLE.WRITE charac$, chr$(1)
if getError$()<>"" then goto doError

END
BLE.DEVICES

BLE.DEVICES  devices_array$[]
Returns scanned devices.

devices_array$[]
The string array to return the list of device addresses.
If the array does not exist, it will be created, otherwise it will be overwritten.

The device addresses are MAC addresses
e.g 11:22:33:DD:EE:FF

The internal list is updated continuously while scanning is enabled.

Example
BLE.DEVICES dl$[] : array.length dlen,dl$[]

for i=1 to dlen
  ble.rssi dl$[i], rssi
  ble.name dl$[i], name$
  if dl$[i] <> ""
    print name$;"\n";dl$[i] ; " rssi=";rssi
  endif
next i
END

BLE.NAME

BLE.NAME  device_sexp , name$_svar
Returns a name for a given device.

device
The device address.
This must be one of the scanned devices gathered in your BLE session,
 i.e it must be present inside the list from  BLE.DEVICES.

name$
The name to return.

BLE.RSSI

BLE.RSSI  device_sexp , rssi_nvar
Returns the Received Signal Strength Indicator for a device as dBm (decibels milliwatts).
Is negative and closer to zero is stronger.

device
The device address.
This must be one of the scanned devices gathered in your BLE session,
 i.e it must be present inside the list from  BLE.DEVICES.

rssi_nvar
The variable to return the rssi

BLE.TEASERS

BLE.TEASERS  device_sexp , teasers$[]
Returns teaser service IDs from a device into a string array.

Teasers are advertised services from a device that show up during a scan (even without a connection).
Teasers are optional depending on the configured (server) device.

device_sexp
The device address.
This must be one of the scanned devices gathered in your BLE session,
 i.e it must be present inside the list from  BLE.DEVICES.

teasers$[]
The string array variable to return the teaser list.

Example

        BLE.TEASERS dev$,t$[] : array.length tlen,t$[]
        for j=1 to tlen
            if STARTS_WITH ("0000180d", t$[j])
                print "Found Heart Rate teaser"
                f_n.break
            endif
            print "HR teaser not found"
        next j
END

How to Test Teasers

The sample program h43_ble_heart.bas shows how to scan for a Heart Rate teaser service.
Instructions
To emulate a Heart Rate service, you can

1. Run an nRF Connect app on another Device 2, to simulate a BLE server.

2. Configure the gatt-server to add a Heart Rate.
Add an Advertiser with service UUID 180d inside Advertising data
(type '180d' and it will find it).

3. Start your Advertiser on Device 2.
You may have to disable power savings for the nRF Connect app under Android Apps or App Settings to let it run in the background.

4. Run h43_ble_heart.bas on Device 1.






BLE.SERVICES

BLE.SERVICES  services$[]
Returns services from the currently connected device into a string array.
If the array does not exist, it will be created, otherwise it will be overwritten.
If the service has no characteristics, the array will still have one entry of an empty string.

This will be the list of service IDs found from the device.
The device with this service must be connected.
e.g  "0000180d-0000-1000-8000-00805f9b34fb"     % hear rate service

services$[]
The string array variable to return the services list.

Example
       
BLE.SERVICES sv$[] : array.length svlen,sv$[]

    for i=1 to svlen
        print "sv " ; sv$[i]
    next i

END
BLE.CHARACTERISTICS

BLE.CHARACTERISTICS  service_sexp ,  characs$[]
Returns characteristics for a given service of the currently connected device into a string array.
If the array does not exist, it will be created, otherwise it will be overwritten.
If the service has no characteristics, the array will still have one entry of an empty string.

service
The service ID

The service ID of the device.
The device with this service must be connected.
e.g  "0000180d-0000-1000-8000-00805f9b34fb"     % hear rate service


characs$[]
The string array variable to return the characteristics list.

This will be the list of characteristics found for the service.
The device with this service characteristic must be connected.
e.g 
"00002a38-0000-1000-8000-00805f9b34fb"     % body sensor location
"00002a37-0000-1000-8000-00805f9b34fb"     % measurement notification

Example
       
BLE.CHARACTERISTICS serviceID$, ch$[]
    array.length chlen,ch$[]
    for j=1 to chlen
        print ch$[j]
    next
END

BLE.PROPERTIES

BLE.PROPERTIES  charac_sexp ,  props_nvar
Returns properties of the given characteristic of the currently connected device.

charac_sexp
The characteristic ID
The device with this characteristic must be connected.
e.g  "00002a37-0000-1000-8000-00805f9b34fb"     % heart rate measurements

props_nvar
The number variable to return the result.
If this variable does not already exist, it will be created.

If the characteristic has no properties or if there was an error, the value returned will be 0.
Any error message is recorded into getError$() otherwise it will be empty.

This will be the byte value of a property mask with each bit representing a property;

Hex
Dec
Bit Position  
Property
hBasic supported
Remarks
0x01 1
0
Broadcast  
No
billboard. defunct. unused.
0x02 2
1
Read Yes

0x04 4
2
Write Without Response No
no ack
0x08 8
3
Write Yes
server ack
0x10 16
4
Notify Yes

0x20 32
5
Indicate No
client auto-ack. design bug.
0x40 64
6
Authenticated Signed Writes No
signing. buggy.
0x80 128
7
Extended Properties No
descriptor offload

As an example, a Characteristic without the Notify Property (0x10) will not support BLE.NOTIFY.

Example
       
BLE.PROPERTIES ch$ , props

if band (props, hex ("10")) then

    BLE.NOTIFY ch$, 1
    PRINT "Notifications Requested"
else
   PRINT "Notifications Not Supported"
endif

   
BLE.TIMEOUT

BLE.TIMEOUT  max_ms_nexp
Sets the general maximum timeout for some commands in milliseconds.

This is the maximum time taken before the session gives up waiting for an action (i.e synchronised on timeout).
The action depends upon the command. Most commands wait for an acknowledgement from the server,
but this is not always the case. Please read the command description if you are unsure how timeout affects it.

If a timeout occurs, a "... timed out ." error message is recorded into getError$() , otherwise it will be enpty ("").
It is up to you if you want to check the error message or let it pass. Either way, your program will just continue.

Default Timeout
The default maximum timeout is 500ms, although most commands usually complete before 100ms.
You can change the maximum with this command.

Timeout of Zero
If you set the timeout to 0 or less, this is essentially no_waiting and no_timeout_errors, which is an asynchronous operation.
This will be true to the original Grau Api spec which does not have timeouts.
You will have to add your own pauses in-between commands to ensure they do not overlap each other and confuse the session.

Commands that are affected by this command are
BLE.OPEN
BLE.NOTIFY
BLE.READ.REQUEST
BLE.WRITE

-END