2 回答

TA貢獻1848條經(jīng)驗 獲得超6個贊
問題中的代碼片段正在掃描新設備,而不是報告已連接的設備。
作為如何在 Python3 中實現(xiàn)它的示例:
import pydbus
bus = pydbus.SystemBus()
adapter = bus.get('org.bluez', '/org/bluez/hci0')
mngr = bus.get('org.bluez', '/')
def list_connected_devices():
? ? mngd_objs = mngr.GetManagedObjects()
? ? for path in mngd_objs:
? ? ? ? con_state = mngd_objs[path].get('org.bluez.Device1', {}).get('Connected', False)
? ? ? ? if con_state:
? ? ? ? ? ? addr = mngd_objs[path].get('org.bluez.Device1', {}).get('Address')
? ? ? ? ? ? name = mngd_objs[path].get('org.bluez.Device1', {}).get('Name')
? ? ? ? ? ? print(f'Device {name} [{addr}] is connected')
if __name__ == '__main__':
? ? list_connected_devices()

TA貢獻1796條經(jīng)驗 獲得超4個贊
使用前需要安裝依賴
布魯斯
代碼
def get_connected_devices():
? ? bounded_devices = check_output(['bt-device', '-l']).decode().split("\n")[1:-1]
? ? connected_devices = list()
? ? for device in bounded_devices:
? ? ? ? name = device[:device.rfind(' ')]
? ? ? ? #mac_address regex
? ? ? ? regex = '([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}\\.[0-9a-fA-F]{4}\\.[0-9a-fA-F]{4})$'
? ? ? ? mac_address = re.search(regex, device).group(0)
? ? ? ? device_info = check_output(['bt-device', '-i', mac_address]).decode()
? ? ? ? connection_state = device_info[device_info.find('Connected: ') + len('Connected: ')]
? ? ? ? if connection_state == '1':
? ? ? ? ? ? connected_devices.append({"name": name, "address": mac_address})
? ? return connected_devices
添加回答
舉報