RTL.ClassicBluetooth Sample
Contents
Location
You can find the Classic Bluetooth Basic app sample project at:
- Start | Programs | Embarcadero RAD Studio Athens | Samples and navigate to:
Object Pascal\Multi-Device Samples\Device Sensors and Services\Bluetooth\Classic Bluetooth Basic app
CPP\Multi-Device Samples\Device Sensors and Services\Bluetooth\Classic Bluetooth Basic app
- Subversion Repository:
- You can find Delphi and C++ code samples in GitHub Repositories. Search by name into the samples repositories according to your RAD Studio version.
Description
- Note: This sample application does not work on iOS devices. For more information about platform support, see Using Classic Bluetooth.
This sample provides a FireMonkey application that is based on TTabControl with two different TTabItem: Bluetooth settings and Service demo.
You need another device that supports Classic Bluetooth to use this sample. You can try the functionality of a simple text service presented in the Service demo tab only if you install this sample on another device.
Bluetooth settings
The Bluetooth settings TTabItem provides options for discovering, pairing/unpairing devices and displaying services available on the paired device.
- The
Labeldiscoverable
control shows the name under which other devices can see your device. - Discover devices: The
ButtonDiscover
control fires theButtonDiscoverClick
event handler. - Pair: The
ButtonPair
control fires theButtonPairClick
event handler. - UnPair: The
ButtonUnPair
control fires theButtonUnPairClick
event handler. - The
ComboBoxDevices
control allows you to choose a device from the list of discovered devices. - Paired Devices: The
ButtonPairedDevices
control fires theButtonPairedDeviceClick
event handler. - The
ComboBoxPaired
control allows you to choose a device from a list of paired devices. If there are any paired devices when you start the application, the first device on the list is automatically chosen. - Services: The
ButtonServices
control fires theButtonServicesClick
event handler. - The
ComboBoxServices
control allows you to choose a service from a list of available services. - The
DisplayR
control shows text output from the application, such as feedback on button clicks or errors that occur.
Service demo
The Service demo TTabItem provides both server and client functionality for a simple text service.
- Create text service: The
ButtonOpenReadingSocket
control fires theButtonOpenReadingSocketClick
event handler. - Remove text service: The
ButtonCloseReadingSocket
control fires theButtonCloseReadingSocketClick
event handler. - Send text to->: The
ButtonConnectToRFCOMM
control fires theButtonConnectToRFCOMMClick
event handler. - The
LabelNameSarver
displays the name of the device that you selected from the list of paired devices. - The
Edit1
control allows you to modify the text that you send to the other device (default is "I am the text sent"). - Clear: The
Button2
control fires theButton2Click
event handler. - Free Client Socket: The
FreeSocket
control fires theFreeSocketClick
event handler. - The
DisplayR
control shows text output from the application, such as feedback on button clicks or errors that occur.
How to Use the Sample
- Navigate to the location given above and open:
- Delphi: ClBluetooth.dproj.
- C++: ClBluetoothCpp.cbproj.
- As a target platform, select a device that supports Classic Bluetooth.
- Note: For more information about client platform support on Classic Bluetooth, see Using Classic Bluetooth.
- Press F9 or choose Run > Run.
- Discover devices.
- Choose a device from the list of discovered devices.
- Pair with that device.
- Note: On Android, after you successfully pair two devices you need to force-close (close in task manager) the application and reopen it. The paired device will then show in the list of paired devices. Pairing is not supported on Android lower than 4.4. To use this application on a device that has a lower version of Android, pair the devices using native system functionality and then run the sample application.
- See the services available on the paired device.
- Note: Devices with Android system version lower than 4.0.3. do not support this functionality.
- Unpair from a device (not supported on Android).
To try the functionality of the simple text service presented in the Service demo tab, you need to install this sample on another device. Follow the steps 1-6 from above on the second device and then:
- Choose the Service demo tab.
- Create a text service (on one or both of the devices).
- Send text from one device to the other (the receiving device needs to have a previously-created text service).
- Note: In C++ version, you need to free the client socket before sending the text (if you do not, the "Broken pipe" error will show).
- You can remove the text service and create it again.
- Note: In Delphi version, creating the text service after removing it has no effect. If you remove the text service you need to close the application and reopen it in order to use the text service.
Implementation
On initialization, the FormShow
procedure creates a reference of the current Bluetooth manager and its adapter. If it successfully connects to the manager, it updates the ComboBoxPaired
with the list of paired devices and displays the name of your device in the Labeldiscoverable
control. If you run the sample application on an unsupported device or with the Bluetooth module turned off, FormShow
shows the following exception in an alert: "Bluetooth device not found: disconnected or turned off".
TForm1
- The application defines the following event handlers:
ButtonPairClick
calls the Pair method of the current adapter. The parameter it passes, is the device that you select from the list of discovered devices. If you do not select a device, the event handler displays an alert: "No device selected".ButtonUnPairClick
calls the UnPair method of the current adapter. The parameter it passes, is the device that you select from the list of paired devices. If you do not select a device, the event handler displays an alert: "No Paired device selected".ComboBoxPairedChange
occurs every time the list of paired devices is updated.ComboBoxPairedChange
updates the value displayed in theLabelNameSarver
on the Service Demo tab with the name of the selected device from the list of paired devices.ButtonPairedDeviceClick
callsPairedDevices
and opens theComboboxPaired
control.ButtonServicesClick
clears theComboBoxServices
control, adds the names of services available on the device you selected from the list of paired devices to theComboBoxServices
control and opens theComboBoxServices
control. If you do not select a device, the event handler displays an alert: "No paired device selected".FreeSocketClick
frees the instance of TBluetoothSocket that you initialize the first time you send text in the Service demo tab and displays the message "Client socket set free" in theDisplayR
control. This method allows you to solve the problem where you cannot send the text to a device after removing and creating a text service on that device, because the client socket is still connected to the previous service.Button2Click
clears all the text in theDisplayR
control.ButtonConnectToRFCOMMClick
callsSendData
that tries to send the text in theEdit1
control to the device that you select from the list of paired devices. If you do not select a device,ButtonConnectToRFCOMMClick
displays the exception "Argument out of range" in theDisplayR
control. If the paired device that you send the text to does not have a text service running,ButtonConnectToRFCOMMClick
displays the exception "IOException: read failed, socket might closed, read ret: -1" in theDisplayR
control. If the paired device, that you send the text to, removes the text service and creates a new one,ButtonConnectToRFCOMMClick
displays the exception "IOException: Broken pipe" in theDisplayR
control. You can solve this problem by using the "Free Client Socket" functionality on the sending device.ButtonDiscoverClick
clears theComboboxDevices
control and starts a discovery with a timeout of 10 seconds.ButtonDiscoverClick
also assignes theDevicesDiscoveryEnd
event handler to the OnDiscoveryEnd event of the manager.DevicesDiscoveryEnd
handles the OnDiscoveryEnd event of the manager.DevicesDiscoveryEnd
adds the names of discovered devices to theComboboxDevices
controls and selects the first device.ButtonOpenReadingSocketClick
callsTServerConnectionTH.Create
to initialize an instance of theTServerConnectionTH
class. ThenButtonOpenReadingSocketClick
creates a server socket for that instance and callsTServerConnectionTH.Start
to start the server thread. Finally,ButtonOpenReadingSocketClick
displays a message in theDisplayR
control: " - Service created: <ServiceName>". If you start the application on an unsupported device or with the Bluetooth module turned off,ButtonOpenReadingSocketClick
displays the exception "No Bluetooth device found" in theDisplayR
control.ButtonCloseReadingSocketClick
callsTServerConnectionTH.Terminate
andTServerConnectionTH.WaitFor
and then frees the instance ofTServerConnectionTH
that was created inButtonOpenReadingSocketClick
. Finally,ButtonCloseReadingSocketClick
displays a message in theDisplayR
control: " - Service removed -".
- The application also defines the following methods:
PairedDevices
clears theComboboxPaired
control and adds the names of the paired devices of the current manager to theComboboxPaired
control. If there are no paired devices,PairedDevices
displays a message "No Paired Devices" in theDisplayR
control.GetServiceName
accepts a Bluetooth service GUID as a parameter and returns the name of the corresponding Bluetooth service.ManagerConnected
returnsTrue
if the connection state of the manager is Connected and sets the text ofLabeldiscoverable
to "Device discoverable as <CurrentAdapter.AdapterName>". If the connection state isFalse
it displays a message "No Bluetooth device found" in theDisplayR
control and returnsFalse
.SendData
converts the text in theEdit1
control into bytes and sends them to the device you selected from the list of paired devices. If the client socket instance is nil,SendData
calls CreateClientSocket. If the socket creation fails,SendData
displays an alert "Out of time -15s-". If you did not select a device from the list of paired devices,SendData
displays an alert "No paired device selected". IfSendData
sucessfully sends the text, it displays a message "Text Sent" in theDisplayR
control.
TServerConnectionTH
This application implements a class TServerConnectionTH that is a subclass of TThread. This class provides the methods that support the server-side functionality of the text service on the Service demo tab.
- TServerConnectionTH defines the following methods:
Create
is the constructor.Destroy
is the destructor that frees the client socket and the server socket instance of this class.execute
is the implementation of the Execute method that runs when the thread is run.execute
listens for incoming data on the instance of the server socket. When the data arrives,execute
converts that data into a string and displays it in theDisplayR
control. If the connected client device frees its socket,execute
displays the exception "Server Socket closed: Channel is closed, cannot read data" in theDisplayR
control.
Uses
- System.SysUtils
- System.Types
- System.UITypes
- System.Classes
- System.Variants
- System.Bluetooth
- FMX.Types
- FMX.Controls
- FMX.Forms
- FMX.Graphics
- FMX.Dialogs
- FMX.Layouts
- FMX.ListBox
- FMX.StdCtrls
- FMX.Memo
- FMX.Controls.Presentation
- FMX.Edit
- FMX.TabControl
- FMX.ScrollBox