unit BTUnit3;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
Androidapi.JNI.BluetoothAdapter,
Androidapi.JNI.JavaTypes,
Androidapi.JNIBridge,
Android.JNI.Toast,
FMX.ListBox, FMX.Layouts, FMX.Memo, FMX.Edit, FMX.Objects, FMX.ListView.Types,
FMX.ListView, System.Rtti, FMX.Grid, Data.Bind.GenData,
System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.ObjectScope;
type
TForm1 = class(TForm)
Timer1: TTimer;
OutLabel2: TLabel;
procedure FormShow(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
targetMAC:string; // remote MAC address of the selected
targetName: string;
ostream:JOutputStream;
istream:JInputstream;
uid:JUUID; // UUID for SPP traffic
Sock:JBluetoothSocket;
Adapter:JBluetoothAdapter; // Local BLUETOOTH adapter
remoteDevice:JBluetoothDevice;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.FormShow(Sender: TObject);
var
s:string;
i:integer;
list:TStringList;
begin
list:=TStringList.Create;
s:=checkBluetooth; // Make sure bluetooth is enabled
Toast(s);
if pos('disabled',s)<>0 then exit;
// This is the well known SPP UUID for connection to a Bluetooth serial device
uid:=TJUUID.JavaClass.fromString(stringtojstring('00001101-0000-1000-8000-00805F9B34FB'));
list.Clear;
list.AddStrings(getbonded); // produce a list of bonded/paired devices
for i := 0 to list.Count-1 do
begin
targetName := list[i].Split(['='])[0];
targetMAC := list[i].Split(['='])[1];
if targetName = 'HC05' then
begin
Adapter:=TJBluetoothAdapter.JavaClass.getDefaultAdapter;
remoteDevice:=Adapter.getRemoteDevice(stringtojstring(targetMAC));
Toast('Connecting to ' + targetName +' (' + targetMAC + ')');
sock:=remoteDevice.createRfcommSocketToServiceRecord(UID);
try sock.connect;
except Toast('Could not create service record!');
end;
if not sock.isConnected then
begin
Toast('Failed to connect to '+targetMAC+'! Try again...');
exit;
end;
Toast('Connected!');
ostream:=sock.getOutputStream; // record io streams
istream:=sock.getInputStream;
Application.ProcessMessages;
sleep(200);
timer1.Enabled:=True;
exit;
end;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
len,i:integer;
s:string;
buffer:TJavaArray<byte>;
begin
len:=istream.available;
if len=0 then exit;
timer1.Enabled := false;
buffer:=TJavaArray<byte>.create(len);
istream.read(buffer,0,len);
s:='';
for i:=0 to len-1 do
begin
s := s + chr(buffer[i]);
ostream.write(buffer[i]);
end;
OutLabel2.text := s;
FillChar(buffer, SizeOf(buffer), 0);
timer1.Enabled:=True;
end;
end.