RTL.ClassicBluetooth Sample
Contents
Location
You can find the Classic Bluetooth Basic app sample project at:
- Start | Programs | Embarcadero RAD Studio 10.1 Berlin | Samples and navigate to:
Object Pascal\Multi-Device Samples\Device Sensors and Services\Bluetooth\Classic Bluetooth Basic appCPP\Multi-Device Samples\Device Sensors and Services\Bluetooth\Classic Bluetooth Basic app
- Subversion Repository:
- http://sourceforge.net/p/radstudiodemos/code/HEAD/tree/branches/RADStudio_Berlin/Object%20Pascal/Multi-Device%20Samples/Device%20Sensors%20and%20Services/Bluetooth/Classic%20Bluetooth%20Basic%20app
- http://sourceforge.net/p/radstudiodemos/code/HEAD/tree/branches/RADStudio_Berlin/CPP/Multi-Device%20Samples/Device%20Sensors%20and%20Services/Bluetooth/Classic%20Bluetooth%20Basic%20app
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
Labeldiscoverablecontrol shows the name under which other devices can see your device. - Discover devices: The
ButtonDiscovercontrol fires theButtonDiscoverClickevent handler. - Pair: The
ButtonPaircontrol fires theButtonPairClickevent handler. - UnPair: The
ButtonUnPaircontrol fires theButtonUnPairClickevent handler. - The
ComboBoxDevicescontrol allows you to choose a device from the list of discovered devices. - Paired Devices: The
ButtonPairedDevicescontrol fires theButtonPairedDeviceClickevent handler. - The
ComboBoxPairedcontrol 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
ButtonServicescontrol fires theButtonServicesClickevent handler. - The
ComboBoxServicescontrol allows you to choose a service from a list of available services. - The
DisplayRcontrol 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
ButtonOpenReadingSocketcontrol fires theButtonOpenReadingSocketClickevent handler. - Remove text service: The
ButtonCloseReadingSocketcontrol fires theButtonCloseReadingSocketClickevent handler. - Send text to->: The
ButtonConnectToRFCOMMcontrol fires theButtonConnectToRFCOMMClickevent handler. - The
LabelNameSarverdisplays the name of the device that you selected from the list of paired devices. - The
Edit1control allows you to modify the text that you send to the other device (default is "I am the text sent"). - Clear: The
Button2control fires theButton2Clickevent handler. - Free Client Socket: The
FreeSocketcontrol fires theFreeSocketClickevent handler. - The
DisplayRcontrol 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:
ButtonPairClickcalls 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".ButtonUnPairClickcalls 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".ComboBoxPairedChangeoccurs every time the list of paired devices is updated.ComboBoxPairedChangeupdates the value displayed in theLabelNameSarveron the Service Demo tab with the name of the selected device from the list of paired devices.ButtonPairedDeviceClickcallsPairedDevicesand opens theComboboxPairedcontrol.ButtonServicesClickclears theComboBoxServicescontrol, adds the names of services available on the device you selected from the list of paired devices to theComboBoxServicescontrol and opens theComboBoxServicescontrol. If you do not select a device, the event handler displays an alert: "No paired device selected".FreeSocketClickfrees 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 theDisplayRcontrol. 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.Button2Clickclears all the text in theDisplayRcontrol.ButtonConnectToRFCOMMClickcallsSendDatathat tries to send the text in theEdit1control to the device that you select from the list of paired devices. If you do not select a device,ButtonConnectToRFCOMMClickdisplays the exception "Argument out of range" in theDisplayRcontrol. If the paired device that you send the text to does not have a text service running,ButtonConnectToRFCOMMClickdisplays the exception "IOException: read failed, socket might closed, read ret: -1" in theDisplayRcontrol. If the paired device, that you send the text to, removes the text service and creates a new one,ButtonConnectToRFCOMMClickdisplays the exception "IOException: Broken pipe" in theDisplayRcontrol. You can solve this problem by using the "Free Client Socket" functionality on the sending device.ButtonDiscoverClickclears theComboboxDevicescontrol and starts a discovery with a timeout of 10 seconds.ButtonDiscoverClickalso assignes theDevicesDiscoveryEndevent handler to the OnDiscoveryEnd event of the manager.DevicesDiscoveryEndhandles the OnDiscoveryEnd event of the manager.DevicesDiscoveryEndadds the names of discovered devices to theComboboxDevicescontrols and selects the first device.ButtonOpenReadingSocketClickcallsTServerConnectionTH.Createto initialize an instance of theTServerConnectionTHclass. ThenButtonOpenReadingSocketClickcreates a server socket for that instance and callsTServerConnectionTH.Startto start the server thread. Finally,ButtonOpenReadingSocketClickdisplays a message in theDisplayRcontrol: " - Service created: <ServiceName>". If you start the application on an unsupported device or with the Bluetooth module turned off,ButtonOpenReadingSocketClickdisplays the exception "No Bluetooth device found" in theDisplayRcontrol.ButtonCloseReadingSocketClickcallsTServerConnectionTH.TerminateandTServerConnectionTH.WaitForand then frees the instance ofTServerConnectionTHthat was created inButtonOpenReadingSocketClick. Finally,ButtonCloseReadingSocketClickdisplays a message in theDisplayRcontrol: " - Service removed -".
- The application also defines the following methods:
PairedDevicesclears theComboboxPairedcontrol and adds the names of the paired devices of the current manager to theComboboxPairedcontrol. If there are no paired devices,PairedDevicesdisplays a message "No Paired Devices" in theDisplayRcontrol.GetServiceNameaccepts a Bluetooth service GUID as a parameter and returns the name of the corresponding Bluetooth service.ManagerConnectedreturnsTrueif the connection state of the manager is Connected and sets the text ofLabeldiscoverableto "Device discoverable as <CurrentAdapter.AdapterName>". If the connection state isFalseit displays a message "No Bluetooth device found" in theDisplayRcontrol and returnsFalse.SendDataconverts the text in theEdit1control into bytes and sends them to the device you selected from the list of paired devices. If the client socket instance is nil,SendDatacalls CreateClientSocket. If the socket creation fails,SendDatadisplays an alert "Out of time -15s-". If you did not select a device from the list of paired devices,SendDatadisplays an alert "No paired device selected". IfSendDatasucessfully sends the text, it displays a message "Text Sent" in theDisplayRcontrol.
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:
Createis the constructor.Destroyis the destructor that frees the client socket and the server socket instance of this class.executeis the implementation of the Execute method that runs when the thread is run.executelistens for incoming data on the instance of the server socket. When the data arrives,executeconverts that data into a string and displays it in theDisplayRcontrol. If the connected client device frees its socket,executedisplays the exception "Server Socket closed: Channel is closed, cannot read data" in theDisplayRcontrol.
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