In additions to my previouse post. This is the code from Monitoring thread of TBFBluetoothDiscovery component:
procedure TBFBluetoothMonitoringThread.Execute;
var
Discovery: TBFBluetoothDiscovery;
OldDevices: TBFBluetoothDevices;
NewDevices: TBFBluetoothDevices;
Devices: TBFBluetoothDevices;
Loop: Integer;
ADevice: TBFBluetoothDevice;
begin
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, 0, NM_DISCOVERY_BEGIN);
// Initialization.
Discovery := TBFBluetoothDiscovery.Create(nil);
OldDevices := TBFBluetoothDevices.Create;
NewDevices := TBFBluetoothDevices.Create;
while not Terminated do begin
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, 0, NM_DISCOVERY_SEARCH_BEGIN);
// Trying discovery devices.
try
Devices := Discovery.Discovery(False, FNeedServices);
except
Devices := nil;
end;
if Assigned(Devices) then begin
// Building new devices list. We adds only connected devices. Not
// remembered.
for Loop := 0 to Devices.Count - 1 do
if (API.BluetoothAPI in [baBlueSoleil, baWidComm]) or ((API.BluetoothAPI = baWinSock) and Devices[Loop].Connected) then begin
ADevice := TBFBluetoothDevice.Create;
ADevice.Assign(Devices[Loop]);
NewDevices.FList.Add(ADevice);
end;
if FAlwaysNew then
for Loop := 0 to NewDevices.Count - 1 do begin
// All founded devices reports as New.
ADevice := TBFBluetoothDevice.Create;
ADevice.Assign(NewDevices[Loop]);
// Main thread must dispose object.
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, Integer(ADevice), NM_DISCOVERY_DEVICE_FOUND);
end
else
// Checks for new founded devices.
for Loop := 0 to NewDevices.Count - 1 do
if OldDevices.IndexOf(NewDevices[Loop].FBTAddress) = -1 then begin
// New device found. Send message to main thread about this fact.
// Main thread MUST dispose object.
ADevice := TBFBluetoothDevice.Create;
ADevice.Assign(NewDevices[Loop]);
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, Integer(ADevice), NM_DISCOVERY_DEVICE_FOUND);
end;
// Check for losted devices.
for Loop := 0 to OldDevices.Count - 1 do
if NewDevices.IndexOf(OldDevices[Loop].FBTAddress) = -1 then begin
// Old device losted. Send message to main thread about this fact.
// Main thread MUST dispose object.
ADevice := TBFBluetoothDevice.Create;
ADevice.Assign(OldDevices[Loop]);
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, Integer(ADevice), NM_DISCOVERY_DEVICE_LOST);
end;
// Now nes devices be a old devices.
OldDevices.Assign(NewDevices);
NewDevices.FList.Clear;
// Dispose object.
Devices.Free;
end;
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, 0, NM_DISCOVERY_SEARCH_END);
// Delay.
Sleep(FDiscovery.FDelay);
end;
// Finalization.
NewDevices.Free;
OldDevices.Free;
Discovery.Free;
PostMessage(FDiscovery.Wnd, BFNM_BLUETOOTH_DISCOVERY_EVENT, 0, NM_DISCOVERY_END);
end;