RTL.BLEScanner Sample

From RAD Studio Code Examples
Jump to: navigation, search

This is a sample that shows the use of the Bluetooth API to search for nearby Bluetooth devices and check whether they broadcast any services.

Location

You can find the BLEScanner sample project at:

Description

This application uses the Bluetooth API to search for nearby devices.

The application uses the following controls:

  • Start Scan: Fires the Button1Click event handler.
  • STOP Scan: Fires the Button2Click event handler.
  • ProgressBar1: Shows the progress of the discovery.
  • ListBox1: Displays the information about discovered devices.
  • ListBox2: Displays the information about discovered services.
  • TBluetoothLE: The BluetoothLE component that handles discovery of devices.
  • Timer1: The timer that fires events used for the progress bar tracking.

How to Use the Sample

  1. Navigate to one of the locations given above and open:
    • Delphi: BLEScanner.dproj.
    • C++: BLEScannerCPP.cbproj.
  2. Press F9 or choose Run > Run.
  3. Click the Start Scan button to start searching for devices.
  4. Wait until the discovery completes.
  5. Choose a discovered device from the list.
  6. The services that the device broadcasts are displayed in the ListBox2 control. If that device does not broadcast any services, the text "Discover services not allow" is displayed in the ListBox2 control.

To interrupt a discovery, click the STOP Scan button.

Implementation

This application uses an instance of TBluetoothLE to:

  • Search for nearby Bluetooth Low Energy devices.
  • Display names of discovered devices in the ListBox1 control.
  • Search for services on a specific device.
  • Display the information about discovered services in the ListBox2 control.

Main Form

On initialization, the FormShow method initializes a Boolean that is used as a control for the discovery interruption and to prevent multiple simultaneous scanning.

  • The application defines the following event handlers:
    • Button1Click: Resets the progress bar, clears the ListBox1 control, enables the timer and initiates discovery.
    • Button2Click: Resets the timer and cancels discovery.
    • BluetoothLE1DiscoverLEDevice: Occurs for every discovered device. Adds the name of the discovered device to the ListBox1 control.
    • BluetoothLE1EndDiscoverDevices: Occurs when the discovery finishes. Disables the timer.
    • BluetoothLE1ServicesDiscovered: Occurs for every discovered service. Reads the name and the UUID from the list of characteristics and adds them to the ListBox2 control.
    • ListBox1ItemClick: Clears the ListBox2 control and initiates service discovery.
    • Timer1Timer: Occurs for every timer interval (default is 1 second). Calculates the progress of the discovery based on the maximum discovery time and updates the progress bar accordingly.

Uses

See Also