使用python执行命令行获取Mac连接的蓝牙设备信息

前言

因为需要对蓝牙信息进行获取,但是找了一些python模块,比如bluepy只支持Linux、bleson项目文档又太烂。因此这里干脆就直接通过命令行获取,然后对信息进行处理了。

步骤

分析命令行

Mac获取蓝牙信息可以使用下面的命令:

system_profiler SPBluetoothDataType

使用python的os模块即可,执行完成之后如下。

Bluetooth:

      Apple Bluetooth Software Version: 7.0.0f8
      Hardware, Features, and Settings:
          Name: Zheyi的MacBook Pro
          Address: F0-18-98-0B-B7-35
          Bluetooth Low Energy Supported: Yes
          Handoff Supported: Yes
          Instant Hot Spot Supported: Yes
          Manufacturer: Broadcom
          Transport: UART
          Chipset: 4364B0
          Firmware Version: v83 c4405
          Bluetooth Power: On
          Discoverable: Off
          Connectable: Yes
          Auto Seek Pointing: On
          Remote wake: On
          Vendor ID: 0x05AC
          Product ID: 0x007B
          Bluetooth Core Spec: 5.0 (0x9)
          HCI Revision: 0x1135
          LMP Version: 5.0 (0x9)
          LMP Subversion: 0x2053
          Device Type (Major): Computer
          Device Type (Complete): Mac Portable
          Composite Class Of Device: 0x38010C
          Device Class (Major): 0x01
          Device Class (Minor): 0x03
          Service Class: 0x1C0
          Auto Seek Keyboard: On
      Devices (Paired, Configured, etc.):
          BlueBlueSky’s Beats Solo³:
              Address: D4-90-9C-3A-C6-41
              Major Type: Audio
              Minor Type: Headphones
              Services: Handsfree, AAP Server, SPP Server, AVRCP Controller, Audio Sink, Wireless iAP, AVRCP Target
              Paired: Yes
              Configured: Yes
              Connected: Yes
              Manufacturer: Apple (0x6, 0x03)
              Bluetooth Core Spec: 4.0
              Firmware Version: 0x0772
              Vendor ID: 0x004C
              Product ID: 0x2006
              Class of Device: 0x04 0x06 0x240418
              RSSI: -32
              Role: Master
              Connection Mode: Sniff Mode
              Interval: 441.25 ms
              EDR Supported: Yes
              eSCO Supported: Yes
              SSP Supported: Yes
......

剩下的一些输出信息就不写了,我们的目标其实是获取Devices那一部分后面的设备信息。其实有很明显的层级结构,第一行Bluetooth是第0级,Devices (Paired, Configured, etc.)与其他一些信息都是第1级,设备的名称处于第2级,设备的具体信息处于第3级。

还有一个很明显的特征,键值是通过:分割的,和json数据很相似,python里面我们就可以使用字典dict来表示。如果我们将这些字符串信息转化成字典dict那么就可以很方便的获取相关信息了,比如这样dict["Bluetooth"]["Devices"]就可以获取所有设备相关信息的数组。

步骤

简单描述一下代码思路

执行命令行并获取层级信息

获取每行的信息,主要是根据缩进判定该行的层级,我们将行的信息从字符串转化成如下结构, 篇幅限制我就写前两行:

[{
   'name': 'Bluetooth', 'value': '', 'level': 0}, 
{
   'name': 'Apple Bluetooth Software Version', 'value': '7.0.0f8', 'level': 1.0},  
....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值