Bluetooth programming - available devices
I used the following function, gots from Microsoft:
public List<Device> DiscoverAllDevices()
{
List<Device> devices = new List<Device>();
// Initialize WinSock
WsaData wsadata = new WsaData();
int result =
BluetoothHelper.WSAStartup(BluetoothHelper.MakeWord(2, 2),
ref wsadata);
if (result != 0)
BluetoothHelper.GetError();
// Scan for bluetooth devices
QuerySet wsaq = new QuerySet();
//Initialize queryset structure with device specific
//information.
wsaq.Size = Marshal.SizeOf(typeof(QuerySet));
wsaq.NameSpace = BluetoothHelper.NS_BTH;
IntPtr lookup = IntPtr.Zero;
uint flags = BluetoothHelper.LUP_RETURN_NAME
| BluetoothHelper.LUP_CONTAINERS
| BluetoothHelper.LUP_RETURN_ADDR
| BluetoothHelper.LUP_FLUSHCACHE
| BluetoothHelper.LUP_RETURN_TYPE
| BluetoothHelper.LUP_RETU开发者_Python百科RN_BLOB
| BluetoothHelper.LUP_RES_SERVICE;
//Initiates a client query that is constrained by the
//information contained within a queryset structure.
result = BluetoothHelper.WSALookupServiceBegin(wsaq,
flags,
ref lookup);
if (result != 0)
BluetoothHelper.GetError();
while (0 == result)
{
int buffer = 0x10000;
IntPtr bufferPtr = Marshal.AllocHGlobal(buffer);
QuerySet qsResult = new QuerySet();
//Retrieves the requested device information.
result = BluetoothHelper.WSALookupServiceNext(lookup,
flags,
ref buffer,
bufferPtr);
if (0 == result)
{
Marshal.PtrToStructure(bufferPtr, qsResult);
devices.Add(new Device(qsResult));
}
else
{
BluetoothHelper.GetError();
}
}
//end device-lookup
result = BluetoothHelper.WSALookupServiceEnd(lookup);
if (result != 0)
BluetoothHelper.GetError();
// cleanup winsock
result = BluetoothHelper.WSACleanup();
if (result != 0)
BluetoothHelper.GetError();
return devices;
}
but I need to know actual data if device in range or not. This code always find device, if it was found before, even if this device is switched off. Why and how to solve this problem? I spent almost full day to find solution Thanks
There is no direct API for that unfortunately. :-( It's a major gap in the API of the Microsoft Bluetooth stack on Win32.
However it is possible by combining an number of APIs. I investigated and implemented this for my my shared-source .NET Bluetooth, http://32feet.codeplex.com If your program could be written in managed code then it will save you much time in using Bluetooth. :-)
Anyway my way of getting the 'discoverable only' device list is documented at http://32feetnetdev.wordpress.com/2010/11/15/device-discovery-improvements-on-msftwin32/ So that's to use the Bluetooth events API to see the discovered devices, and run a normal discovery at the same time.
精彩评论