草庐IT

c# - 获取蓝牙端口名称

coder 2023-11-10 原文

有什么方法可以枚举所有蓝牙 com 端口并获取它们的名称吗? 我的名字不是指 COM10,在这种情况下我指的是 GNSS:51622 'GNSS Server'

使用 32Feet 我已经能够找到端口的名称,但仍然无法将它们映射到实际的 com 端口。

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Connecting to Bluetooth");
        var client = new BluetoothClient();
        Console.WriteLine("DiscoverDevices");
        var devices = client.DiscoverDevices();
        Console.WriteLine("Enumerating");
        foreach (var device in devices)
        {
            if (!device.DeviceName.StartsWith("GNSS"))
                continue;
            Console.WriteLine(device.DeviceName);
            try
            {
                Console.WriteLine("Getting serial ports");
                var serviceRecords = device.GetServiceRecords(BluetoothService.SerialPort);
                foreach (var serviceRecord in serviceRecords)
                {
                    var name = GetName(serviceRecord);
                    Console.WriteLine(name);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to get SerialPort");
                Console.WriteLine(ex.ToString());
            }
        }
        Console.ReadKey();
    }

    private static string GetName(ServiceRecord serviceRecord)
    {
        var nameAttribute = serviceRecord.SingleOrDefault(a => a.Id == 0);
        var name = serviceRecord.GetPrimaryMultiLanguageStringAttributeById(nameAttribute.Id);
        return name;
    }
}

输出:

连接到蓝牙 发现设备 枚举 全局导航卫星系统:51622 获取串口 COM1 COM2 COM3 全局导航卫星系统服务器

最佳答案

我在这里发布了一个要点 https://gist.github.com/peterfoot/b4f61c81023a1e181b9f3940bca344ba使用代码枚举蓝牙虚拟 COM 端口。服务记录中的端口名称值存储在注册表中,因此可以根据设置 API 中的设备路径获取它。它在要点代码中公开为 RemoteServiceName 。例如,在我的 Zebra 打印机上,它返回“Serial Printer”。我没有可处理多个公开服务的设备,但这将为您提供上面显示在设备名称旁边的字符串,例如“GNSS 服务器”、“COM1”等

代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace BluetoothDiagnostics
{
    public sealed class BluetoothComPort
    {
        /// <summary>
        /// Returns a collection of all the Bluetooth virtual-COM ports on the system.
        /// </summary>
        /// <returns></returns>
        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).Trim();
                                        }
                                    }
                                }
                            }
                            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("{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}");
            internal static Guid GUID_DEVCLASS_PORTS = new Guid("{4d36e978-e325-11ce-bfc1-08002be10318}");

            [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;
            }
        }
    }
}

关于c# - 获取蓝牙端口名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45299710/

有关c# - 获取蓝牙端口名称的更多相关文章

  1. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  2. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  3. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  4. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  5. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  6. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  7. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  8. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

  9. ruby - 没有类方法获取 Ruby 类名 - 2

    如何在Ruby中获取BasicObject实例的类名?例如,假设我有这个:classMyObjectSystem我怎样才能使这段代码成功?编辑:我发现Object的实例方法class被定义为returnrb_class_real(CLASS_OF(obj));。有什么方法可以从Ruby中使用它? 最佳答案 我花了一些时间研究irb并想出了这个:classBasicObjectdefclassklass=class这将为任何从BasicObject继承的对象提供一个#class您可以调用的方法。编辑评论中要求的进一步解释:假设你有对象

  10. ruby-on-rails - 如何在 Gem 中获取 Rails 应用程序的根目录 - 2

    是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在

随机推荐