Windows com port bluetooth

Bluetooth Virtual COM Ports

I was thinking about a comment on a Gist I wrote some time ago and thought I’d written a blog post on the topic, but when I couldn’t find any sign of it I decided to start from scratch as I’d have probably needed to update it anyway.
The Bluetooth stack in Windows has supported virtual COM ports since the beginning (Windows XP SP2 if you can remember that far back!). It’s important to understand the difference between these and any Serial Port Bluetooth device. The Virtual COM port functionality exists purely for interop with older software – you can make a Bluetooth device appear to the system as a wired Serial device and open a COM port and talk to the device as if it was plugged into your PC.
If you’re writing modern software which talks to devices then you would use a Bluetooth API – either 32feet.NET or the platform specific Bluetooth API directly. If not you can create a virtual COM port. Throughout Windows 10’s lifetime the Bluetooth options have been slowly moving to the modern Settings experience but the old Control Panel still exists and is used for some additional functionality – Virtual Serial ports are still in there.
The port can be either incoming – you have a listening service which other devices can connect to; or outgoing where you connect to a specific remote device. From Settings > Devices select “More Bluetooth options” from the righthand menu.

2020-11-22 (1)

From the resulting “classic” control panel applet select the “COM ports” tab to see configured ports or to set one up.

2020-11-22

When I reworked the 32feet.NET library I decided not to include the COM port functionality as it’s only relevant to Windows and is for legacy code only. However I put together the required code to enumerate all the Bluetooth virtual COM ports on the system in a Gist which you can find here:-

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

using System ;
using System . Collections . Generic ;
using System . Diagnostics ;
using System . Runtime . InteropServices ;
using System . Text ;
namespace BluetoothDiagnostics
public sealed class BluetoothComPort
///
/// Returns a collection of all the Bluetooth virtual-COM ports on the system.
///
///
public static IReadOnlyList < BluetoothComPort >FindAll ( )
List < BluetoothComPort >ports = new List < BluetoothComPort >( ) ;
IntPtr handle = NativeMethods . SetupDiGetClassDevs ( ref NativeMethods . GUID_DEVCLASS_PORTS , null , IntPtr . Zero , NativeMethods . DIGCF . PRESENT ) ;
if ( handle != IntPtr . Zero )
try
NativeMethods . SP_DEVINFO_DATA dat = new NativeMethods . SP_DEVINFO_DATA ( ) ;
dat . cbSize = Marshal . SizeOf ( dat ) ;
uint i = 0 ;
while ( NativeMethods . SetupDiEnumDeviceInfo ( handle , i ++ , ref dat ) )
string remoteServiceName = string . Empty ;
StringBuilder sbid = new StringBuilder ( 256 ) ;
int size ;
NativeMethods . SetupDiGetDeviceInstanceId ( handle , ref dat , sbid , sbid . Capacity , out size ) ;
Debug . WriteLine ( sbid ) ;
long addr = GetBluetoothAddressFromDevicePath ( sbid . ToString ( ) ) ;
// only valid if an outgoing Bluetooth port
if ( addr != long . MinValue && addr != 0 )
IntPtr hkey = NativeMethods . SetupDiOpenDevRegKey ( handle , ref dat , NativeMethods . DICS . GLOBAL , 0 , NativeMethods . DIREG . DEV , 1 ) ;
var key = Microsoft . Win32 . RegistryKey . FromHandle ( new Microsoft . Win32 . SafeHandles . SafeRegistryHandle ( hkey , true ) ) ;
object name = key . GetValue ( » PortName » ) ;
var pkey = Microsoft . Win32 . Registry . LocalMachine . OpenSubKey ( » SYSTEM \\ CurrentControlSet \\ Services \\ BTHPORT \\ Parameters \\ Devices \\ » + addr . ToString ( » x12 » ) ) ;
if ( pkey != null )
foreach ( string nm in pkey . GetSubKeyNames ( ) )
if ( nm . StartsWith ( » ServicesFor » ) )
var skey = pkey . OpenSubKey ( nm ) ;
string s = sbid . ToString ( ) ;
//bluetooth service uuid from device id string
int ifirst = s . IndexOf ( » < " ) ;
string uuid = s . Substring ( ifirst , s . IndexOf ( » > » ) — ifirst + 1 ) ;
var ukey = skey . OpenSubKey ( uuid ) ;
// instance id from device id string
string iid = s . Substring ( s . LastIndexOf ( » _ » ) + 1 ) ;
var instKey = ukey . OpenSubKey ( iid ) ;
// registry key contains service name as a byte array
object o = instKey . GetValue ( » PriLangServiceName » ) ;
if ( o != null )
byte [ ] chars = o as byte [ ] ;
remoteServiceName = Encoding . UTF8 . GetString ( chars ) ;
remoteServiceName = remoteServiceName . Substring ( 0 , remoteServiceName . IndexOf ( ‘ \0 ‘ ) ) ;
>
>
>
>
ports . Add ( new BluetoothComPort ( sbid . ToString ( ) , addr , name . ToString ( ) , remoteServiceName ) ) ;
key . Dispose ( ) ;
>
>
>
finally
NativeMethods . SetupDiDestroyDeviceInfoList ( handle ) ;
>
>
return ports ;
>
private string _deviceId ;
private long _bluetoothAddress ;
private string _portName ;
private string _remoteServiceName ;
internal BluetoothComPort ( string deviceId , long bluetoothAddress , string portName , string remoteServiceName )
_deviceId = deviceId ;
_bluetoothAddress = bluetoothAddress ;
_portName = portName ;
_remoteServiceName = remoteServiceName ;
>
public string DeviceId
get
return _deviceId ;
>
>
public long BluetoothAddress
get
return _bluetoothAddress ;
>
>
public string PortName
get
return _portName ;
>
>
public string RemoteServiceName
get
return _remoteServiceName ;
>
>
private static long GetBluetoothAddressFromDevicePath ( string path )
if ( path . StartsWith ( » BTHENUM » ) )
int start = path . LastIndexOf ( ‘&’ ) ;
int end = path . LastIndexOf ( ‘_’ ) ;
string addressString = path . Substring ( start + 1 , ( end — start ) — 1 ) ;
// may return zero if it is an incoming port (we’re not interested in these)
return long . Parse ( addressString , System . Globalization . NumberStyles . HexNumber ) ;
>
// not a bluetooth port
return long . MinValue ;
>
private static class NativeMethods
// The SetupDiGetClassDevs function returns a handle to a device information set that contains requested device information elements for a local machine.
[ DllImport ( » setupapi.dll » , SetLastError = true , CharSet = CharSet . Auto ) ]
internal static extern IntPtr SetupDiGetClassDevs (
ref Guid classGuid ,
[ MarshalAs ( UnmanagedType . LPTStr ) ] string enumerator ,
IntPtr hwndParent ,
DIGCF flags ) ;
// The SetupDiEnumDeviceInfo function returns a SP_DEVINFO_DATA structure that specifies a device information element in a device information set.
[ DllImport ( » setupapi.dll » , SetLastError = true , CharSet = CharSet . Auto ) ]
[ return : MarshalAs ( UnmanagedType . Bool ) ]
internal static extern bool SetupDiEnumDeviceInfo (
IntPtr deviceInfoSet ,
uint memberIndex ,
ref SP_DEVINFO_DATA deviceInfoData ) ;
// The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory.
[ DllImport ( » setupapi.dll » , SetLastError = true , CharSet = CharSet . Auto ) ]
[ return : MarshalAs ( UnmanagedType . Bool ) ]
internal static extern bool SetupDiDestroyDeviceInfoList ( IntPtr deviceInfoSet ) ;
// The SetupDiGetDeviceInstanceId function retrieves the device instance ID that is associated with a device information element.
[ DllImport ( » setupapi.dll » , SetLastError = true , CharSet = CharSet . Auto ) ]
[ return : MarshalAs ( UnmanagedType . Bool ) ]
internal static extern bool SetupDiGetDeviceInstanceId (
IntPtr deviceInfoSet ,
ref SP_DEVINFO_DATA deviceInfoData ,
System . Text . StringBuilder deviceInstanceId ,
int deviceInstanceIdSize ,
out int requiredSize ) ;
//static Guid GUID_DEVCLASS_BLUETOOTH = new Guid(«»);
internal static Guid GUID_DEVCLASS_PORTS = new Guid ( » » ) ;
[ DllImport ( » setupapi.dll » , SetLastError = true ) ]
internal static extern IntPtr SetupDiOpenDevRegKey ( IntPtr DeviceInfoSet , ref SP_DEVINFO_DATA DeviceInfoData ,
DICS Scope , int HwProfile , DIREG KeyType , int samDesired ) ;
[ Flags ]
internal enum DICS
GLOBAL = 0x00000001 , // make change in all hardware profiles
CONFIGSPECIFIC = 0x00000002 , // make change in specified profile only
>
internal enum DIREG
DEV = 0x00000001 , // Open/Create/Delete device key
DRV = 0x00000002 , // Open/Create/Delete driver key
>
// changes to follow.
// SETUPAPI.H
[ Flags ( ) ]
internal enum DIGCF
PRESENT = 0x00000002 , // Return only devices that are currently present in a system.
ALLCLASSES = 0x00000004 , // Return a list of installed devices for all device setup classes or all device interface classes.
PROFILE = 0x00000008 , // Return only devices that are a part of the current hardware profile.
>
[ StructLayout ( LayoutKind . Sequential ) ]
internal struct SP_DEVINFO_DATA
internal int cbSize ; // = (uint)Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
internal Guid ClassGuid ;
internal uint DevInst ;
internal IntPtr Reserved ;
>
>
>
>

I’ve just updated it as I noticed an issue with the null termination of the port names so it is now correctly trimmed. The class is very simple to use – the following will write out all the configured ports to the debug console:-

foreach (var p in BluetoothDiagnostics.BluetoothComPort.FindAll())  System.Diagnostics.Debug.WriteLine($"  "); > 

Источник

Создание устройства Bluetooth, распознаваемого как COM-порт?

Посмотрите, как это показано, как подключено в окне Bluetooth:

Также посмотрите, как это отображается в диспетчере устройств:

Проблема в том, что мой HM10 отображается в действительных устройствах Bluetooth в диспетчере устройств, но не отображается в списке после нажатия "Входящие". Список просто пуст. Есть ли что-то, чего мне не хватает, чтобы это появилось в этом списке?

Не отображается в этом списке!

2 ответа 2

Я понял, что проблема в том, что HM-10 и HM-11 не имеют функции "Стандартный последовательный канал через Bluetooth", такой как модуль HC-05, если кто-нибудь знает, как добавить эту функцию к нему, это может сработать!

Если у вас есть модуль Bluetooth HC-05, вы можете без проблем использовать его как прямое соединение UART с вашим компьютером.

Чтобы открыть окна функций оборудования: Панель управления> Оборудование и звук> Устройства и принтеры> дважды щелкните устройство Bluetooth> выберите вкладку «Оборудование».

Я был не в состоянии разобраться в проблеме, но пошел совсем другим путем. Поскольку целью этого вопроса было беспроводное подключение моего Arduino к компьютеру, я решил использовать радиочастотную передачу вместо Bluetooth. При этом я приобрел следующее:

Qty Item 2 433 MHz Transciever that supports UART (or any frequency so long as both match) 1 USB to UART Converter 

Я считаю, что моей самой большой проблемой было то, что у меня не было конвертера USB в UART. Это также могло быть причиной того, что мои модули Bluetooth не работали, так как они были просто трансиверами без конвертера usb в UART. В любом случае, если кто-то пытается установить беспроводную связь между Arduino и компьютером под управлением Windows, я бы предложил метод RF.

Источник

Making a bluetooth device recognized as a COM port?

See how it is shown as connected in the bluetooth window:

enter image description here

Also see how it does show up in device manager:

enter image description here

The problem that I have is even though my HM10 shows up in the valid Bluetooth devices under device manager, it does not show up in the list after I click "Incoming". The list is simply blank. Is there something I am missing to make it show up in this list?

enter image description here

Does not show up in this list!

3 Answers 3

I figured out that the problem is HM-10 and HM-11 do not have the "Standard Serial over Bluetooth link" function like HC-05 module, if anybody know how to add that function to it, it might work!

if you have HC-05 bluetooth module, you can use it as direct UART connection to your computer without problem.

To open the hardware funtions windows: Control panel > Hardware and Sound > Devices and Printers > double click on the bluetooth device > choose Hardware tab.

I was unable to directly figure out the problem however went a different route altogether. Since the goal of this question was to connect my Arduino to my computer wirelessly, I decided to use RF transmission instead of bluetooth. In doing this I purchased the following:

Qty Item 2 433 MHz Transciever that supports UART (or any frequency so long as both match) 1 USB to UART Converter 

I believe that my biggest issue was that I did not have the USB to UART converter. This also may have been the reason my bluetooth modules didn't work as they were simply transcievers as well without the usb to UART converter. Either way, if someone else is trying to have wireless communication between an Arduino and a Windows based computer, I would suggest the RF method instead.

Источник

Читайте также:  Bluetooth наушники можно ли вернуть
Оцените статью
Adblock
detector