Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

bash - bluetootctl scan on parsing

I have a problem with bluetootctl command and awk. If I run bluetoothctl scan on | awk '{print $0}' it not print anythink. But only bluetoothctl scan on works fine. How can I take the scan on output line by line for parsing ?

question from:https://stackoverflow.com/questions/65936587/bluetootctl-scan-on-parsing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My understanding is that bluetoothctl was not intended to be used in this way. It is expected that the D-Bus API is used for such scripting.

The API is documented at: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc

The repository has an example script of how to do discovery: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/test/test-discovery

I have also included an alternative below that deletes the device details from BlueZ after printing. This is useful if you are trying to get Manufacturer or Service data from beacons as by default BlueZ does some filtering of duplicate device data.

from gi.repository import GLib
from pydbus import SystemBus
from pprint import pprint

SCAN_TIME = 15
DEVICE_INTERFACE = 'org.bluez.Device1'

remove_list = set()

def stop_scan():
    adapter.StopDiscovery()
    mainloop.quit()


def clean_device(rm_dev):
    try:
        adapter.RemoveDevice(rm_dev)
    except GLib.Error as err:
        pass

def on_iface_added(path, interfaces):
    if DEVICE_INTERFACE in interfaces:
        on_device_found(path, interfaces[DEVICE_INTERFACE])

def on_device_found(device_path, device_props):
    address = device_props.get('Address')
    manufacturer_data = device_props.get('ManufacturerData')
    print(f'{address} found! Manufacturer Data: [{manufacturer_data}]')
    clean_device(device_path)


bus = SystemBus()
adapter = bus.get('org.bluez', '/org/bluez/hci0')
mngr = bus.get('org.bluez', '/')
mngr.onInterfacesAdded = on_iface_added

mainloop = GLib.MainLoop()

GLib.timeout_add_seconds(SCAN_TIME, stop_scan)
adapter.SetDiscoveryFilter({'DuplicateData': GLib.Variant.new_boolean(True)})
adapter.StartDiscovery()

mainloop.run()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...