Update of "ble command"
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview

Artifact ID: a6e7a05540e4d09f6ae542de96a0626b32bbf9fd
Page Name:ble command
Date: 2021-08-14 04:06:07
Original User: chw
Parent: d612080851c76cf8b78cb5f498df6d1caa6caeaf
Content

ble command

Name

ble - interact with Bluetooth Low Energy (BLE) devices. Requires Android 4.3 or higher.

Synopsis

package require Ble
ble subcommand ?options?

Description

This command is used to deal with Bluetooth Low Energy (BLE) devices. The legal subcommands (which may be abbreviated) are:

ble abort handle

Abort the current write transaction on the BLE connection identified by handle which was obtained earlier by a ble connect command. Returns an integer indicating success (1), failure (0), or system error (less than 0).

ble begin handle

Starts a write transaction on the BLE connection identified by handle which was obtained earlier by a ble connect command. Returns an integer indicating success (1), failure (0), or system error (less than 0).

ble callback handle ?callback?

If the callback argument is provided that argument replaces the callback function on the BLE connection identified by handle and returns the old callback function. Otherwise the current callback function is returned. In contrast to e.g. the Tk event bind mechanism, the callback argument has not all the freedom of a Tcl bind script, i.e. it must be a single command and be parseable as a list since internally the Tcl core function Tcl_EvalObjv() is used for executing the callback instead of the Tcl_Eval*() function family supporting full scripts.

ble characteristics handle suuid sinstance

Returns a list of characteristics of the service described by its UUID suuid and instance number sinstance on the BLE connection handle. The list is layed out as a table with the five columns characteristic UUID, characteristic instance number, permissions, properties, and write type suitable for iterating using foreach {cuuid cinstance perm prop wrtype} [ble characteristics ...] {...}.

ble close handle

Closes the BLE connection identified by handle which was obtained earlier by a ble connect or ble scanner command.

ble connect address callback ?flag?

Connects to the Bluetooth LE device with address address (expressed as six hexadecimal 8 bit numbers separated by colons, like a Ethernet MAC address), and arranges for the callback command to be invoked on events on the connection to this device. The optional flag is a boolean with default false controlling automatic connection setup (see the Android documentation for more details). The callback command is called with two additional arguments, the first is a string (connection, scan, service, characteristic, descriptor, or transaction) indicating the kind of event, the second is a dictionary with event related information, see the section Event Data below. For restrictions of the callback argument see the description in ble callback above. The result of the ble connect command is a handle (a string identifying the BLE connection) to be used in other ble subcommands. During connection establishment an automatic discovery takes place which detects all advertised services, characteristics, and descriptors of the remote Bluetooth LE device.

ble descriptors handle suuid sinstance cuuid cinstance

Returns a list of descriptors of the service and characteristic described by its UUIDs suuid and cuuid and instance numbers sinstance and cinstance on the BLE connection handle. The list is layed out as a table with the two columns descriptor UUID and permissions suitable for iterating using foreach {duuid perm} [ble descriptors ...] {...}.

ble disable handle suuid sinstance cuuid cinstance

Turns off notifications of a characteristic of the BLE connection handle identified by suuid (128 bit service UUID), sinstance (service instance identifier, integer, usually 0), cuuid (128 bit characteristic UUID), and cinstance (characteristic identifier, integer, usually 0).

ble disconnect handle

Initiates a disconnect of the BLE connection handle if the current connection state is disconnected. When the operation completes the callback function of the connection is invoked.

ble dread handle suuid sinstance cuuid cinstance duuid

Initiates the read of a descriptor of the BLE connection handle identified by suuid (128 bit service UUID), sinstance (service instance identifier, integer, usually 0), cuuid (128 bit characteristic UUID), cinstance (characteristic identifier, integer, usually 0), and duuid (128 bit descriptor UUID). The result is a positive integer when the descriptor read operation is in progress, 0 or negative on error. The completion of the descriptor read operation is indicated through the callback function of the connection.

ble dwrite handle suuid sinstance cuuid cinstance duuid value

Initiates the write of a descriptor of the BLE connection handle identified by suuid (128 bit service UUID), sinstance (service instance identifier, integer, usually 0), cuuid (128 bit characteristic UUID), cinstance (characteristic identifier, integer, usually 0), and duuid (128 bit descriptor UUID). value is the value to be written and should be a string or byte array. The result is a positive integer when the descriptor write operation is in progress, 0 or negative on error. The completion of the descriptor write operation is indicated through the callback function of the connection.

ble enable handle suuid sinstance cuuid cinstance

Turns on notifications of a characteristic of the BLE connection handle identified by suuid (128 bit service UUID), sinstance (service instance identifier, integer, usually 0), cuuid (128 bit characteristic UUID), and cinstance (characteristic identifier, integer, usually 0).

ble equal handle uuid1 uuid2

Tests if the given UUIDs are equal. Both can be specified in abbreviated form and are expanded before comparison. Returns true, if the UUIDs are the same. Unknown abbreviated or long UUIDs with respect to the connection handle compare always to false.

ble execute handle

Dispatches execute (commit) of the current write transaction which was started earlier using ble begin on the BLE connection identified by handle which was obtained earlier by a ble connect command. Returns an integer indicating success (1), failure (0), or system error (less than 0). The result of the transaction is reported in the callback with event kind transaction.

ble expand handle uuid

Expands the given (abbreviated, short) UUID to its 128 bit (long, canonical) form and returns a 128 bit UUID string. An error is reported if an abbreviated or long UUID is unknown with respect to the connection handle.

ble getrssi handle

Requests remote SSI information from the BLE connection identified by handle which was obtained earlier by a ble connect command. Returns an integer indicating success (1), failure (0), or system error (less than 0). The updated remote SSI is reported in later callbacks.

ble info ?handle?

Returns information of the BLE connection identified by handle as a dictionary made up the fields handle (the connection identifier), address (Bluetooth address), and state (connection state, one of disconnected, discovery, scanning, connected, or idle. If handle is omitted, a list of all known connection identifiers is returned.

ble mtu handle ?value?

Returns or sets the maximum transmission unit (MTU) of the BLE connection identified by handle. Support of this function varies between Android versions.

ble pair address

Initiates pairing with the Bluetooth device with address address (expressed as six hexadecimal 8 bit numbers separated by colons, like a Ethernet MAC address).

ble read handle suuid sinstance cuuid cinstance

Initiates the read of a characteristic of the BLE connection handle identified by suuid (128 bit service UUID), sinstance (service instance identifier, integer, usually 0), cuuid (128 bit characteristic UUID), and cinstance (characteristic identifier, integer, usually 0). The result is a positive integer when the read operation is in progress, 0 or negative on error. The completion of the read operation is indicated through the callback function of the connection.

ble reconnect handle

Initiates a reconnect of the BLE connection handle if the current connection state is disconnected. When the operation completes the callback function of the connection is invoked with information on the new connection state.

ble scanner callback

Creates a BLE connection to be used for detection (scan) of BLE devices and returns a handle (a string identifying the BLE scanner) to be used to deal with this scanner and arranges for the callback command to be invoked on events on the connection. See the description of ble connect and the section Event Data for more details on the callback argument.

ble services handle

Returns a list of services of the BLE connection handle. The list is layed out as a table with the three columns service UUID, service instance number, and service type suitable for iterating using foreach {suuid sinstance type} [ble services ...] {...}.

ble shorten handle uuid

Shorten the given (long, canonical) UUID to its shortest (16 or 32 bit) form. An error is reported if the long UUID is unknown with respect to the connection handle. If no unique abbreviation is found, the full 128 bit UUID is returned.

ble start handle

Starts scanning for BLE devices. Scan status and scan results are indicated by invocations of the callback function given to the corresponding ble scanner command.

ble stop handle

Stops scanning for BLE devices. Scan status is indicated by invocations of the callback function given to the corresponding ble scanner command.

ble unpair address

Initiates release of the pairing with the Bluetooth device with address address (expressed as six hexadecimal 8 bit numbers separated by colons, like a Ethernet MAC address).

ble userdata handle ?data?

Associate or retrieve user data with the BLE connection handle. When data is given it replaces the former associated user data. When omitted, the current user data or an empty list is returned.

ble write handle suuid sinstance cuuid cinstance value

Initiates the write of a characteristic of the BLE connection handle identified by suuid (128 bit service UUID), sinstance (service instance identifier, integer, usually 0), cuuid (128 bit characteristic UUID), and cinstance (characteristic identifier, integer, usually 0). value is the value to be written and should be a string or byte array. The result is a positive integer when the write operation is in progress, 0 or negative on error. The completion of the write operation is indicated through the callback function of the connection. Note: not all Android implementations allow more than one active command (example, issuing a "ble read" immediately after a "ble write"). For best compatibility, you should wait for the callback that your write operation has completed before issuing the next ble write/read command.

Abbreviated UUIDs

The 128 bit UUID arguments to ble commands can be specified in abbreviated 16 or 32 bit form as long as the value is unique with respect to the UUIDs learned during the discovery phase. Examples:

 TI SensorTag Base UUID:        F0000000-0451-4000-B000-000000000000

 IR Temperature Sensor Service: F000AA00-0451-4000-B000-000000000000
          abbreviated (32 bit): F000AA00
          abbreviated (16 bit):     AA00

 IR Temperature Sensor Value:   F000AA01-0451-4000-B000-000000000000
          abbreviated (32 bit): F000AA01
          abbreviated (16 bit):     AA01

 Generic descriptor for notify: 00002902-0000-1000-8000-00805F9B34FB
          abbreviated (32 bit): 00002902
          abbreviated (16 bit):     2902

Event Data

The first argument to callback functions is the type of event, as described below.

connection

Indicates change in connection state.

scan

Indicates change in scan state or reports newly detected Bluetooth LE devices.

service

Information about a service.

characteristic

Information about a characteristic, used for data exchange.

descriptor

Information about a descriptor (meta information of a characteristic).

transaction

Indicates status of a write transaction.

The second argument to callback functions is a dictionary with keys depending on the kind of the event. The following paragraphs list the various event formats.

handle h state s

Connection state event for ble scan. state can be one of scanning or idle.

handle h address a state s rssi r

Connection state event for ble connect. state can be one of disconnected, discovery, or connected. In the discovery phase the services, characteristics, and descriptors of the remote device are gathered. The rssi field contains the last read remote SSI (signal strength indicator) in dBm as integer number.

handle h state s address a name n type t rssi r

Scan result event. address is the Bluetooth address of the remote device, name it's advertised friendly name, type the device type as integer, rssi the receive SSI in dBm as integer.

handle h address a state s rssi r suuid su sinstance si type t

Service discovery event. suuid is the UUID of the service, sinstance the instance of that service as integer number. Refer to BluetoothGattService for details.

handle h address a state s rssi r suuid su sinstance si cuuid ci cinstance ci permissions p properties q writetype w access a value v

Characteristic event. cuuid is the UUID of the characteristic, cinstance the instance of that characteristic as integer number. The items permission, properties, and writetype are integer numbers, too. The access item contains a one letter code indicating the type of access ('c' for change notification, 'd' for discovery, 'r' for read, 'w' for write). The value item holds the data of the characteristic as a byte array. It's interpretation is device/characteristic depending. This event is reported during discovery and normal operation when ble read or ble write are performed locally or notifications for the characteristic are enabled using ble enable. Refer to BluetoothGattCharacteristic for details.

handle h address a state s rssi r suuid su sinstance si cuuid ci cinstance ci duuid di permissions p access a value v

Descriptor event. duuid is the UUID of the descriptor. The item permission is an integer number, too. The access item contains a one letter code indicating the type of access ('d' for discovery, 'r' for read, 'w' for write). The value item holds the data of the descriptor as a byte array. It's interpretation is device/characteristic/descriptor depending. This event is reported during discovery and normal operation when ble dread or ble dwrite are performed locally. Refer to BluetoothGattDescriptor for details.

handle h success s

Transaction result event. success is the transaction result and is 1 for success or 0 for failure.

Example

The following example scans for Bluetooth LE devices, connects to a TI SensorTag and enables notifications of the buttons of the device.


    proc ble_handler {what data} {
        switch -- $what {
            scan {
                if {[dict get $data name] eq "SensorTag"} {
                    # found the TI SensorTag, connect it, stop the scanner
                    ble connect [dict get $data address] ble_handler 1
                    ble close [dict get $data handle]
                }
            }
            connection {
                if {[dict get $data state] == "disconnected"} {
                    # fall back to scanning
                    ble close [dict get $data handle]
                    ble start [ble scanner ble_handler]
                } elseif {[dict get $data state] == "connected"} {
                    # if the TI SensorTag buttons were found,
                    # it will be enabled for notifications now
                    set handle [dict get $data handle]
                    set cmd [ble userdata $handle]
                    if {$cmd ne {}} {
                        if {[{*}$cmd]} {
                            # success, clear userdata
                            ble userdata $handle {}
                        }
                    }
                }
            }
            descriptor {
                if {[string match "*2902-*" [dict get $data duuid]] &&
                    [string match "*FFE1-*" [dict get $data cuuid]]} {
                    # descriptor for TI SensorTag buttons found
                    set flag 0
                    # notification enable state, 16 bit little-endian
                    #  0x0000 = disabled, 0x0001 = enabled
                    binary scan [dict get $data value] s flag
                    if {!$flag} {
                        # later turn on notifications of button changes
                        set handle [dict get $data handle]
                        ble userdata $handle [list ble enable $handle \
                            [dict get $data suuid] [dict get $data sinstance] \
                            [dict get $data cuuid] [dict get $data cinstance]]
                    }
                }
            }
        }
        # dump data to stdout
        if {[dict exists $data value]} {
            # make hex string from byte array
            binary scan [dict get $data value] H* value
            dict set data value $value
        }
        puts "$what: $data"
    }

    ble start [ble scanner ble_handler]