[SOLVED] Bluetooth using Winsock lazarus / 21-General ---------------------------------------------------------------------- Graham1 · 2021-03-25 03:45 I'm trying to send data to and read data from a Bluetooth device that doesn't have a Serial Port Profile set up. I've been told that 'all' I need to do is open it at a specific address on channel 10. Looking into this I find that the Bluetooth package for Lazarus was Beta 8 years ago and even then only for Linux, so I suspect there is no need for a package now. I looked at the documentation here: https://docs.microsoft.com/en-us/windows/win32/bluetooth/bluetooth- programming-with-windows-sockets which helped a bit, and then I found this post: https://forum.lazarus.freepascal.org/index.php?topic=28913.0 which seems to come even closer. I've tried amending the code by Thaddy to this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program sendtest; {$APPTYPE CONSOLE} uses   SysUtils, windows, winsock2; const  AF_BTH          = 32;       BTHPROTO_RFCOMM = 3; var    MyData        : WSADATA;       Rslt          : Integer;       s             : TSocket;       SendBuf       : Array[0..31] of AnsiChar;       clientservice : sockaddr_in;       BytesSent     : Integer; begin    try      Rslt := WSAStartup(MAKEWORD(2,2), MyData);       if Rslt = NO_ERROR then begin         s := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);          if s <> INVALID_SOCKET then begin          clientservice.sin_family := AF_BTH;            clientservice.sin_addr.s_addr := bth_addr('11:22:33:44:55:66');  // FAILS!            clientservice.sin_port := 10;             if connect(s,clientservice,sizeof(clientservice)) <> SOCKET_ERROR then begin               sendbuf := 'la la la la la la la :)';             bytesSent := send(s,sendbuf,Length(sendbuf),0);               writeln('Bytes sent: ',bytesSent);             end else               writeln('Failed to connect');         end else            writeln('Error at Socket: ',WSAGetLastError);      end else           writeln('Error at WSAStartup');    finally      Writeln(SysErrorMessage(GetLastError));      WSACleanUp;   end; end. The immediate problem I have is that Winsock2.pp in FPC doesn't seem to know anything about Bluetooth. It doesn't have AF_BTH for example. Then the next problem is how to use the address? In the original code Thaddy used inet_addr because he was accessing a php server but of course that won't work here. There must be somebody that has already done this as BT has been around now for so long. Or is there a package I can use? Any help really appreciated! If you do reply though please don't assume I know anything about this as I've never worked with sockets or BT at a programming level before. Thanks, Graham ---------------------------------------------------------------------- jamie · 2021-03-25 20:59 I didn't know blue tooth devices cam IP active? maybe they do but what ever... also I thought V6Ip had 8 indexes ? also, shouldn't they be separated via "." ? ---------------------------------------------------------------------- trev · 2021-03-25 21:33 Quote from: jamie on March 25, 2021, 09:59:08 pmalso, shouldn't they be separated via "." ? Bluetooth addresses are usually 6 bytes in hexadecimal separated by colons. ---------------------------------------------------------------------- Graham1 · 2021-03-25 22:17 Quote from: trev on March 25, 2021, 10:33:21 pmQuote from: jamie on March 25, 2021, 09:59:08 pmalso, shouldn't they be separated via "." ? Bluetooth addresses are usually 6 bytes in hexadecimal separated by colons. Yes, Bluetooth addresses are different to IP addresses: https://macaddresschanger.com/what-is-bluetooth-address-BD_ADDR Winsock handles a lot more protocols than just IP! ---------------------------------------------------------------------- Remy Lebeau · 2021-03-26 01:03 Quote from: trev on March 25, 2021, 10:33:21 pmBluetooth addresses are usually 6 bytes in hexadecimal separated by colons. That is because Bluetooth uses MAC addresses, not IP addresses.  SOCKADDR_IN is meant for IPv4 IP addresses only.  You have to use SOCKADDR_BTH for Bluetooth.  This is even stated as much in Microsoft's Bluetooth and connect documentation, which is linked to by the 1st document linked to by Graham1's initial question. WinSock does not have a function like inet_addr() for Bluetooth, but it is not hard to write such a function, eg: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program sendtest;     {$APPTYPE CONSOLE}     uses  SysUtils, Windows, Winsock2;     const   AF_BTH          = 32;  BTHPROTO_RFCOMM = 3; type  BTH_ADDR = ULONGLONG;  SOCKADDR_BTH = record    addressFamily: USHORT;    btAddr: BTH_ADDR;    serviceClassId: TGUID;    port: ULONG;  end;     function str2ba(const str_bt_addr: string): BTH_ADDR;var  addr: array[1..6] of Integer;  i, first, last: Integer;  bt_addr: BTH_ADDR;begin  Result := 0;  bt_addr := 0;  first := 1;  for i := 1 to 5 do  begin    last := Pos(':', str_bt_addr, first);    if last = 0 then Exit;    if not TryStrToInt('$'+Copy(str_bt_addr, first, last-first), addr[i]) then Exit;    first := last + 1;  end;  if not TryStrToInt('$'+Copy(str_bt_addr, first, MaxInt), addr[6]) then Exit;  for i := 1 to 6 do bt_addr := (bt_addr shl 8) or BTH_ADDR(Byte(addr[i]));  Result := bt_addr;end; var  MyData: WSADATA;  Rslt: Integer;  s: TSocket;  SendBuf: Array[0..31] of AnsiChar;  clientservice: sockaddr_bth;  BytesSent: Integer;     begin  try    Rslt := WSAStartup(MAKEWORD(2,2), MyData);    if Rslt = NO_ERROR then begin      s := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);           if s <> INVALID_SOCKET then begin        clientservice.addressFamily := AF_BTH;        clientservice.btAddr := str2ba('11:22:33:44:55:66');        clientservice.serviceClassId = ...;        clientservice.port := 10;             if connect(s, PSockAddr(@clientservice), SizeOf(clientservice)) <> SOCKET_ERROR then begin          sendbuf := 'la la la la la la la :)';          bytesSent := send(s, sendbuf, Length(sendbuf), 0);          writeln('Bytes sent: ', bytesSent);               closesocket(s);      end else          writeln('Failed to connect');      end else      writeln('Error at Socket: ', WSAGetLastError);    end else      writeln('Error at WSAStartup');  finally    Writeln(SysErrorMessage(GetLastError));    WSACleanUp;  end;     end. ---------------------------------------------------------------------- Graham1 · 2021-03-26 02:59 Quote from: Remy Lebeau on March 26, 2021, 02:03:52 amQuote from: trev on March 25, 2021, 10:33:21 pmBluetooth addresses are usually 6 bytes in hexadecimal separated by colons. That is because Bluetooth uses MAC addresses, not IP addresses.  SOCKADDR_IN is meant for IPv4 IP addresses only.  You have to use SOCKADDR_BTH for Bluetooth.  This is even stated as much in Microsoft's Bluetooth and connect documentation, which is linked to by the 1st document linked to by Graham1's initial question. WinSock does not have a function like inet_addr() for Bluetooth, but it is not hard to write such a function, eg: I suppose 'not hard' is relative! Thank you so much for your information and code. Of course I still have a question about the line: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i clientservice.serviceClassId = ...; Am I right in thinking that the service class id can be found in the Properties of the device manager? If so I have some choices: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Class GUID: {e0cbf06c-cd8b-4647-bb8a-263b43f0f974}Bluetooth class of device: 00000000Bluetooth service GUID: {00000000-0000-0000-0000-000000000000} or there are 50 or so other settings. And if it's one of the ones with '{...}' how do I represent that in Pascal in the line required? And if it isn't found there where do I find it? Your linked description says it is ignored anyway if the port is specified so I tried: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const      MyGUID : TGUID = '{00000000-0000-0000-0000- 000000000000}'; : :clientservice.serviceClassId := MyGUID; which compiles OK. But when I run it I'm getting the error: Failed to connect The specified system semaphore name was not found. I have no idea what that means though. I'm sorry if these are stupid questions but I did warn you that I know nothing!! Once again, thank you so much for your help, Graham EDIT: I found an error in the function: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i if not TryStrToInt('$'+Copy(str_bt_addr, first, last-1), addr[i]) then Exit;should be: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i if not TryStrToInt('$'+Copy(str_bt_addr, first, last-first), addr[i]) then Exit; Unfortunately that doesn't fix the semaphore error. ---------------------------------------------------------------------- Remy Lebeau · 2021-03-26 16:23 Quote from: Graham1 on March 26, 2021, 03:59:41 amAm I right in thinking that the service class id can be found in the Properties of the device manager? I don't know.  One would hope.  Otherwise, you can use  WSALookupServiceBegin() and WSALookupServiceNext() to discover service GUIDs. Quote from: Graham1 on March 26, 2021, 03:59:41 amIf so I have some choices: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Class GUID: {e0cbf06c-cd8b-4647-bb8a-263b43f0f974}Bluetooth class of device: 00000000Bluetooth service GUID: {00000000-0000-0000-0000-000000000000} That Class GUID is the general ID for Bluetooth devices.  So I think you are looking for the service GUID, which is just NULL in that example. Quote from: Graham1 on March 26, 2021, 03:59:41 amAnd if it's one of the ones with '{...}' how do I represent that in Pascal in the line required? You already know the answer to that - as a TGUID, which you can assign a string literal to and the compiler will convert it for you.  Or you can use a function like SysUtils.StringToGUID(). Quote from: Graham1 on March 26, 2021, 03:59:41 amYour linked description says it is ignored anyway if the port is specified so I tried: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const      MyGUID : TGUID = '{00000000-0000-0000-0000- 000000000000}'; : :clientservice.serviceClassId := MyGUID; which compiles OK. That is what I would have done. Quote from: Graham1 on March 26, 2021, 03:59:41 amBut when I run it I'm getting the error: Failed to connect The specified system semaphore name was not found. I have no idea what that means though. Neither do I.  I don't ever code for Bluetooth. First thing I would check is the alignment settings of the SOCKADDR_BTH record, make sure all of the fields are at the expected offsets in memory.  Maybe the record needs to be byte-aligned or quad- aligned (probably the latter). Quote from: Graham1 on March 26, 2021, 03:59:41 amEDIT: I found an error in the function: Fixed. ---------------------------------------------------------------------- Graham1 · 2021-03-27 04:52 Well, this is about as far as I can get: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program sendtest; {$APPTYPE CONSOLE} uses  SysUtils, windows, winsock2; const  AF_BTH          = 32;  BTHPROTO_RFCOMM = 3;  BT_MAC          = 'B8:27:EB:F1:38:CC';  BT_PORT         = 10;  BT_CLASS        = '{00000000-0000-0000-0000-000000000000}'; type  BTH_ADDR = UINT64;   SOCKADDR_BTH = record    addressFamily  : USHORT;    btAddr         : BTH_ADDR;    serviceClassId : TGUID;    port           : ULONG;  end; function connectBT(const s:TSocket; const name:SOCKADDR_BTH; namelen:Longint): Longint; stdcall;external WINSOCK2_DLL name 'connect'; function str2ba(const str_bt_addr: string): BTH_ADDR;var  addr           : array[1..6] of Integer;  i, first, last : Integer;  bt_addr        : BTH_ADDR;begin  Result := 0;  bt_addr := 0;  first := 1;  for i := 1 to 5 do begin    last := Pos(':', str_bt_addr, first);    if last = 0 then Exit;    if not TryStrToInt('$'+Copy(str_bt_addr, first, last-first), addr[i]) then Exit;    if addr[i]>255 then Exit;  first := last+1;  end;  if not TryStrToInt('$'+Copy(str_bt_addr, first, MaxInt), addr[6]) then Exit;  if addr[6]>255 then Exit;  for i := 1 to 6 do bt_addr := (bt_addr shl 8) or BTH_ADDR(Byte(addr[i]));  Result := bt_addr;end;  var  MyData         : WSADATA;  Rslt, i        : Integer;  s              : TSocket;  clientservice  : SOCKADDR_BTH;  SendBuf        : Array[0..5] of Byte;  BytesSent      : Integer;  begin   try    Rslt := WSAStartup(MAKEWORD(2,2), MyData);   if Rslt = NO_ERROR then begin      s := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);       if s <> INVALID_SOCKET then begin        clientservice.addressFamily := AF_BTH;        clientservice.btAddr := str2ba(BT_MAC);        clientservice.serviceClassId := StringtoGUID(BT_CLASS);        clientservice.port := BT_PORT;         if connectBT(s, clientservice, SizeOf(clientservice)) <> SOCKET_ERROR then begin          for i:=0 to 5 do SendBuf[i]:=0;          bytesSent := send(s, SendBuf, 6, 0);          writeln('Bytes sent: ', bytesSent);          closesocket(s);        end else          writeln('Failed to connect');                                            end else        writeln('Error at Socket: ', WSAGetLastError);                                  end else      writeln('Error at WSAStartup');   finally    if WSAGetLastError<>0 then      Writeln(SysErrorMessage(WSAGetLastError)+' [Error code '+Inttostr(WSAGetLastError)+']');    WSACleanUp;  end; end. I'm sure the problem is related to the layout of the SOCKADDR_BTH but I can't see what's wrong. All I get is the error 187 about the semaphore name. ---------------------------------------------------------------------- engkin · 2021-03-27 20:30 Try using "packed record" ---------------------------------------------------------------------- jamie · 2021-03-27 21:29 on the CONNECTBT function that got imported,,.. Try to remove the first CONST and for the second const use CONSTREF instead so that the compile will always pass a pointer to it. removing the first CONST will stop the compiler from making its own choice of how to pass the parameter. the Second CONST is really not useful if you ask me, just change the it a pointer only so the compiler.. you don't care about the CONST definition here because that code is outside of your code space.  So try to reconfigure the protocol header with no constants and use a Pointer to the ClientService entry... ---------------------------------------------------------------------- engkin · 2021-03-28 16:58 FYI, SOCKADDR_BTH is already defined in JwaWindows (more precisely  in unit JwaWs2Bth) and it uses packed record. The record size is 30 bytes, the same size I saw in its C counterpart in header file ws2bth.h: Code: C  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i #include #include #include  int main(){  printf("Size of SOCKADDR_BTH: %d", sizeof(SOCKADDR_BTH));  //<--- gives 30  return 0;} Without "packed" your record is 40 bytes on a 32bit system. ---------------------------------------------------------------------- Graham1 · 2021-03-29 00:44 Jamie and Engkin, you were both right! Although the const on the socket wasn't a problem I rechecked the Microsoft documentation and the socket address does have to be set as a pointer not raw data. And the record did need to be packed to ensure that all the bytes were in the correct place, not realigned by the compiler. I didn't even know there was a JwaWs2Bth file so it looks like I might have just reinvented the wheel, but I'll stick with what I have now it works. The finished code has been rearranged to use an ugly 'while true do' but it makes it easier to follow what is going on as the nested Ifs were getting a bit too deep. I also found I had to be more careful with closing the socket. Because my device keeps sending data I must shutdown the connection properly before closing the socket. So the final version: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program sendtest; {$APPTYPE CONSOLE} uses  SysUtils, windows, winsock2; const  AF_BTH          = 32;  BTHPROTO_RFCOMM = 3;  BT_MAC          = 'B8:27:EB:F1:38:CC';  BT_PORT         = 10;  BT_CLASS        = '{00000000-0000-0000-0000-000000000000}'; type  BTH_ADDR = UInt64;   PSockAddrBth = ^TSockAddrBth;  TSockAddrBth = packed record    addressFamily  : USHORT;    btAddr         : BTH_ADDR;    serviceClassId : TGUID;    port           : ULONG;  end; function connectBT(const s: TSocket; name: PSockAddrBth; namelen: Longint): Longint; stdcall;external WINSOCK2_DLL name 'connect'; function str2ba(const str_bt_addr: string): BTH_ADDR;var  addr           : array[1..6] of Integer;  i, first, last : Integer;  bt_addr        : BTH_ADDR;begin  Result := 0;  bt_addr := 0;  first := 1;  for i := 1 to 5 do begin    last := Pos(':', str_bt_addr, first);    if last = 0 then Exit;    if not TryStrToInt('$'+Copy(str_bt_addr, first, last- first), addr[i]) then Exit;    if addr[i] > 255 then Exit;    first := last+1;  end;  if not TryStrToInt('$'+Copy(str_bt_addr, first, MaxInt), addr[6]) then Exit;  if addr[6] > 255 then Exit;  for i := 1 to 6 do bt_addr := (bt_addr shl 8) or BTH_ADDR(Byte(addr[i]));  Result := bt_addr;end;  var  WSinfo         : WSADATA;  Rslt, i, ErrNo : Integer;  s              : TSocket;  clientservice  : TSockAddrBth;  clientservptr  : PSockAddrBth;  SendBuf        : Array[0..5] of Byte;  BytesSent      : Integer;  RecvBuf        : Array[0..1023] of Byte;  BytesRecv      : Integer;  BEGIN   for i := 0 to 5    do SendBuf[i] := 0;  for i := 0 to 1023 do RecvBuf[i] := 0;  ErrNo := 0;   while true do begin     Rslt := WSAStartup(MAKEWORD(2,2), WSinfo);    if Rslt <> NO_ERROR then begin      ErrNo := WSAGetLastError;      writeln('Error at WSAStartup');      break;    end;     s := socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);    if s = INVALID_SOCKET then begin    ErrNo := WSAGetLastError;      writeln('Error at Socket');      break;    end;     clientservice.addressFamily := AF_BTH;    clientservice.btAddr := str2ba(BT_MAC);    clientservice.serviceClassId := StringtoGUID(BT_CLASS);    clientservice.port := BT_PORT;    clientservptr := @clientservice;   if connectBT(s, clientservptr, SizeOf(clientservice)) = SOCKET_ERROR then begin      ErrNo := WSAGetLastError;      writeln('Error at Connect');      break;    end;     BytesSent := send(s, SendBuf, 6, 0);    writeln('Bytes sent: ', BytesSent);    if BytesSent <> 6 then begin      ErrNo := WSAGetLastError;      writeln('Error at Send');    break;    end;     BytesRecv := recv(s, RecvBuf, 1024, 0);    writeln('Bytes received A: ', BytesRecv);     if s <> INVALID_SOCKET then begin       Rslt := shutdown(s, SD_SEND);      if Rslt <> 0 then begin        ErrNo := WSAGetLastError;        writeln('Error at Shutdown Send');        break;      end;       repeat        BytesRecv := recv(s, RecvBuf, 1024, 0);        writeln('Bytes received B: ', BytesRecv);      until BytesRecv = 0;       Rslt := shutdown(s, SD_RECEIVE);      if Rslt <> 0 then begin        ErrNo := WSAGetLastError;        writeln('Error at Shutdown Receive');        break;      end;       Rslt := closesocket(s);      if Rslt <> 0 then begin        ErrNo := WSAGetLastError;        writeln('Error at Close Socket');        break;      end;     end;     break;   end;   if ErrNo <> 0 then     writeln(SysErrorMessage(ErrNo)+' [Error code '+Inttostr(ErrNo)+']')  else     writeln('Success!');   WSACleanUp; END. Thank you everybody for your input. I honestly didn't think I was going to get it working and without your help I never would have! ---------------------------------------------------------------------- Graham1 · 2021-04-09 04:30 My program above connects to a Bluetooth device and sends/receives data but relies on already knowing the BT address. I thought I'd post here how I do my searches for addresses since although there are C examples online there don't seem to be many in Pascal. Maybe this will be useful to somebody. I first thought I'd try the JWA package mentioned above and it worked fine on my 64 bit Windows PC until I compiled my program as 32 bit. Then it didn't find any devices any more. I think this is because it uses the procedures in a 64 bit Control Panel program (irprops.cpl) rather than the Windows DLL file (BluetoothApis.dll). Perhaps the DLL file was added in a later update to Windows. So I extracted the parts I needed using https://docs.microsoft.com/en- us/windows/win32/bluetooth/bluetooth-functions and linked them to the DLL file giving me: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program finddev; {$APPTYPE CONSOLE} uses  SysUtils, crt, LazUTF8;   const  WINBT_DLL               = 'BluetoothApis.dll';  BLUETOOTH_MAX_NAME_SIZE = 248;  type  BTH_ADDR = UInt64;  BOOL = Longbool;   SYSTEMTIME = record    wYear          : Word;    wMonth       : Word;    wDayOfWeek     : Word;    wDay           : Word;    wHour          : Word;    wMinute        : Word;    wSecond        : Word;    wMilliseconds  : Word;  end;   BLUETOOTH_ADDRESS = record    case Integer of      0: (ullLong: BTH_ADDR);      1: (rgBytes: array [0..5] of Byte);  end;   BLUETOOTH_DEVICE_SEARCH_PARAMS = record    dwSize               : DWORD;    fReturnAuthenticated : BOOL;    fReturnRemembered    : BOOL;    fReturnUnknown       : BOOL;    fReturnConnected     : BOOL;    fIssueInquiry        : BOOL;    cTimeoutMultiplier   : Byte;    hRadio               : THandle;  end;   BLUETOOTH_DEVICE_INFO = record    dwSize          : DWORD;    Address         : BLUETOOTH_ADDRESS;    ulClassofDevice : DWORD;    fConnected      : BOOL;    fRemembered     : BOOL;    fAuthenticated  : BOOL;    stLastSeen      : SYSTEMTIME;    stLastUsed      : SYSTEMTIME;    szName          : array[0..BLUETOOTH_MAX_NAME_SIZE-1] of WideChar;  end;   HBLUETOOTH_DEVICE_FIND = THandle;  function BluetoothFindFirstDevice(const pbtsp: BLUETOOTH_DEVICE_SEARCH_PARAMS; var pbtdi: BLUETOOTH_DEVICE_INFO): HBLUETOOTH_DEVICE_FIND; stdcall; external WINBT_DLL name 'BluetoothFindFirstDevice';function BluetoothFindNextDevice(hFind: HBLUETOOTH_DEVICE_FIND; var pbtdi: BLUETOOTH_DEVICE_INFO): BOOL; stdcall; external WINBT_DLL name 'BluetoothFindNextDevice';function BluetoothFindDeviceClose(hFind: HBLUETOOTH_DEVICE_FIND): BOOL; stdcall; external WINBT_DLL name 'BluetoothFindDeviceClose';  var  DeviceFindHandle   : THandle;  DeviceInfo         : BLUETOOTH_DEVICE_INFO;  DeviceSearchParams : BLUETOOTH_DEVICE_SEARCH_PARAMS;  devcnt             : Integer = 0;  devnam             : string;  BEGIN   DeviceInfo.dwSize:=sizeof(DeviceInfo);   DeviceSearchParams.dwSize := sizeof(DeviceSearchParams);  DeviceSearchParams.fReturnAuthenticated := False;  DeviceSearchParams.fReturnRemembered := True;  DeviceSearchParams.fReturnUnknown := True;  DeviceSearchParams.fReturnConnected := False;  DeviceSearchParams.fIssueInquiry := True;  DeviceSearchParams.cTimeoutMultiplier := 1;   DeviceFindHandle := BluetoothFindFirstDevice(DeviceSearchParams, DeviceInfo);   if DeviceFindHandle <> 0 then begin     repeat      devnam:=InttoHex(DeviceInfo.Address.ullLong,12);      devnam:=devnam+' is '+UTF16ToUTF8(StrPas(DeviceInfo.szName));      if DeviceInfo.fConnected then        devnam:=devnam+'  (Connected)';    writeln(devnam);      inc(devcnt);    until not BluetoothFindNextDevice(DeviceFindHandle, DeviceInfo);     BluetoothFindDeviceClose(DeviceFindHandle);   end;   writeln;  if devcnt = 0 then     writeln('No devices found')  else     writeln(inttostr(devcnt)+' device(s) found!');   writeln;  writeln('Press any key');  readkey; END. Then I thought I'd also try doing the searches using Winsock based on this https://docs.microsoft.com/en- us/windows/win32/bluetooth/bluetooth-and-wsalookupservicebegin and ended up with this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program findwsa; {$APPTYPE CONSOLE} uses  SysUtils, crt, windows, winsock2;   const  NS_BTH = 16;   BTHNS_RESULT_DEVICE_CONNECTED     = $00010000;  BTHNS_RESULT_DEVICE_REMEMBERED    = $00020000;  BTHNS_RESULT_DEVICE_AUTHENTICATED = $00040000;  type  BTH_ADDR = UInt64;   PSockAddrBth = ^TSockAddrBth;  TSockAddrBth = packed record    addressFamily  : Word;    btAddr         : BTH_ADDR;    serviceClassId : TGUID;    port           : Longword;  end;   SOCKET_ADDRESSB = record    lpSockaddr      : PSockAddrBth;    iSockaddrLength : Longint;  end;   CSADDR_INFOB = record    LocalAddr     : SOCKET_ADDRESSB;    RemoteAddr      : SOCKET_ADDRESSB;    iSocketType     : LongInt;    iProtocol       : LongInt;  end;  PCSADDR_INFOB = ^CSADDR_INFOB;   TWSAQuerySetB = record    dwSize                : LongInt;    lpszServiceInstanceName : PWideChar;    lpServiceClassId        : PGUID;    lpVersion               : PWSAVERSION;    lpszComment             : PWideChar;    dwNameSpace           : LongInt;    lpNSProviderId          : PGUID;    lpszContext             : PWideChar;    dwNumberOfProtocols     : LongInt;    lpafpProtocols          : PAFProtocols;    lpszQueryString         : PWideChar;    dwNumberOfCsAddrs       : LongInt;    lpcsaBuffer           : PCSADDR_INFOB;    dwOutputFlags           : LongInt;    lpBlob                : PBLOB;  end;  PWSAQuerySetB = ^TWSAQuerySetB;    TQueryResult = record    QrySet          : TWSAQuerySetB;    buffer        : array[0..2047] of byte;  end;  function WSALookupServiceBeginB(const lpqsRestrictions:PWSAQuerySetB; const dwControlFlags:DWORD; lphLookup:PHANDLE):Longint; stdcall; external WINSOCK2_DLL name 'WSALookupServiceBeginW';function WSALookupServiceNextB(const hLookup:THandle; const dwControlFlags:DWORD; var lpdwBufferLength:DWORD; lpqsResults:PWSAQuerySetB):Longint; stdcall; external WINSOCK2_DLL name 'WSALookupServiceNextW';  var  WSinfo            : WSADATA;  WSquery           : TWSAQuerySetB;  WSresult          : TQueryResult;  hLookUp           : THandle;  len               : DWORD;  flags           : DWORD;   Rslt, ErrNo       : Integer;  devcnt            : Integer = 0;  devnam            : string;  BEGIN   while true do begin     WSinfo.wHighVersion:=0;    Rslt := WSAStartup(MAKEWORD(2,2), WSinfo);    if Rslt <> NO_ERROR then begin      ErrNo := WSAGetLastError;      writeln('Error at WSAStartup');      break;    end;    writeln('WinSock '+inttostr(lobyte(WSinfo.wVersion))+'.'+intto str(hibyte(WSinfo.wVersion)));    writeln;     zeromemory(@WSquery, sizeof(WSquery));    WSquery.dwSize := sizeof(WSquery);    WSquery.dwNameSpace := NS_BTH;    flags := LUP_RETURN_ADDR OR LUP_RETURN_NAME OR LUP_CONTAINERS OR LUP_FLUSHCACHE;    hLookup := 0;     if WSALookupServiceBeginB(@WSquery, flags, @hLookup) = SOCKET_ERROR then begin      ErrNo := WSAGetLastError;      writeln('Error at WSABegin');      break;    end;     len := sizeof(WSresult);    zeromemory(@WSresult, len);    WSresult.QrySet.dwSize := len;    WSresult.QrySet.dwNameSpace := NS_BTH;     while WSALookupServiceNextB(hLookup, flags, len, @WSresult) = NO_ERROR do begin       devnam:=InttoHex(WSresult.QrySet. lpcsaBuffer^.RemoteAddr.lpSockaddr^.btAddr,12);       devnam:=devnam+' is '+string(WSresult.QrySet.lpszServiceInstanceName);       if (WSresult.QrySet.dwOutputFlags AND BTHNS_RESULT_DEVICE_CONNECTED) <> 0 then         devnam:=devnam+'  (Connected)';       writeln(devnam);     inc(devcnt);    end;    ErrNo := WSAGetLastError;    if (ErrNo <> WSAENOMORE) and (ErrNo <> WSA_E_NO_MORE) then begin       writeln('Error at WSANext');       break;    end else       ErrNo := 0;     if WSALookupServiceEnd(hLookup) = SOCKET_ERROR then begin       ErrNo := WSAGetLastError;       writeln('Error at WSAEnd');       break;    end;     break;   end;   WSACleanUp;   writeln;  if ErrNo <> 0 then     writeln(SysErrorMessage(ErrNo)+' [Error code '+Inttostr(ErrNo)+']')  else  if devcnt = 0 then     writeln('No devices found')  else     writeln(inttostr(devcnt)+' device(s) found!');   writeln;  writeln('Press any key');  readkey; END. In my machine the Winsock version is noticeably slower. Since both of these return addresses as 12 character strings the string-to-BTaddress function in the original program becomes: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function StrtoBTaddr(btstr:string):Bth_Addr;var    addr           : array[1..6] of integer;       i, first, last : integer;       bt_addr        : Bth_Addr;begin   result:=0;   bt_addr:=0;   first:=1;    if (pos(':',btstr)=0) and (length(btstr)=12) then begin      for i:=1 to 6 do begin         if not TryStrToInt('$'+Copy(btstr, first, 2), addr[i]) then exit;         first:=first+2;      end;   end else begin      for i:=1 to 5 do begin         last:=Pos(':', btstr, first);         if last=0 then exit;         if not TryStrToInt('$'+copy(btstr, first, last-first), addr[i]) then exit;       if addr[i]>255 then exit;         first:=last+1;      end;      if not TryStrToInt('$'+copy(btstr, first, REST), addr[6]) then exit;    if addr[6]>255 then exit;   end;    for i:=1 to 6 do bt_addr:= (bt_addr shl 8) OR Bth_Addr(addr[i]);   result:=bt_addr; end;