我无法列出我的Raspberry Pi(python、btmgmt)附近的BLE设备

2024-10-01 07:43:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的Raspberry环境中扫描ble设备,方法是使用从cron脚本调用的python脚本。 但是当我在cron中这样做时(我的意思是我添加到sudocrontab-e中),我总是得到一个空列表

当我以pi用户身份登录时-btmgmt(仅限)使用su权限正常工作:

pi@Pluto:~ $ btmgmt find
Unable to start discovery. status 0x14 (Permission Denied)

pi@Pluto:~ $ sudo btmgmt find
Discovery started
hci0 type 7 discovering on
hci0 dev_found: 77:F8:D7:8A:1E:E5 type LE Random rssi -83 flags 0x0000 
...

因此,在我的python脚本中,我写道:

flog.write("P01:\r\n")
out = subprocess.Popen(['sudo', '/usr/bin/btmgmt', 'find'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
flog.write("stderr: " + str(stderr) + "\r\n")
cDvc = stdout.split('\n')
flog.write("Amount of lines = " + str(len(cDvc)) + "\r\n")
for line in cDvc:
    line = line + '\r\n'
    if debugflag:
        print(line)
        flog.write(line)
..

从shell提示符运行此脚本可以正常工作。。在日志文件(flog)中,我得到:

P01:
stderr: None
Amount of lines = 40
Discovery started
hci0 type 7 discovering on
hci0 dev_found: 70:D0:FD:74:34:AC type LE Random rssi -59 flags 0x0000 
AD flags 0x1a 
..

运行与crontab-e行相同的脚本:没有设备显示&;我找不到原因:

...
P01:
stderr: None
Amount of lines = 1
P02:
...

有人能帮我吗


Tags: 脚本typestderrstdoutlinepifindwrite
2条回答

我有完全相同的问题。我需要使用树莓pi来检查附近是否有特定的蓝牙设备,并向监控服务发送心跳信号

在像* * * * * sudo btmgmt find > /tmp/ble_devices.txt这样的cron作业中执行命令时,我没有从sudo btmgmt find获得任何输出,如果我使用python捕获Popen调用的输出也是如此。所以我问自己是否可以在另一个屏幕上执行它,结果它成功了

我的解决方案相当老套。我做了以下工作:

  1. 在raspberry pi上安装了屏幕工具:sudo apt install screen
  2. 已创建用于运行扫描命令的屏幕:screen -S blescan
  3. 从屏幕ctrl+a+d中分离我自己
  4. /home/pi/scan_job中创建了一个shell脚本,内容如下:
   #!/bin/bash 
   cd <to python project> && ./<file to be executed>
  1. 使其可执行chmod +x /home/pi/scan_job
  2. blescan屏幕中设置cronjob以执行文件:
*/10 * * * * screen -S blescan -X screen '/home/pi/scan_job'

如果您使用bluezdbusapi来获取信息,那么就不需要使用sudo。它还避免了您必须使用btmgmt,因为我不确定它是否打算以这种方式编写脚本

DBus API的文档可从以下网址获得:

https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/adapter-api.txt

https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/device-api.txt

pydbus库对于访问bluezdbusapi非常有用:https://pypi.org/project/pydbus/

要开始学习,需要了解一些有用的事情:

  1. bluez的Dbus服务称为“org.bluez”
  2. 默认蓝牙适配器通常将“/org/bluez/hci0”作为其DBus对象路径
  3. BlueZ/DBus有一个存储设备信息的对象管理器

我编写了以下脚本来测试这个想法:

from datetime import datetime
import os
import pydbus
from gi.repository import GLib

discovery_time = 60
log_file = '/home/pi/device.log'

# Create an empty log file
def write_to_log(address, rssi):
    if os.path.exists(log_file):
        open_mode = 'a'
    else:
        open_mode = 'w'

    with open(log_file, open_mode) as dev_log:
        now = datetime.now()
        current_time = now.strftime('%H:%M:%S')
        dev_log.write(f'Device seen[{current_time}]: {address} @ {rssi} dBm\n')

bus = pydbus.SystemBus()
mainloop = GLib.MainLoop()

class DeviceMonitor:
    def __init__(self, path_obj):
        self.device = bus.get('org.bluez', path_obj)
        self.device.onPropertiesChanged = self.prop_changed
        print(f'Device added to monitor {self.device.Address}')

    def prop_changed(self, iface, props_changed, props_removed):
        rssi = props_changed.get('RSSI', None)
        if rssi is not None:
            print(f'\tDevice Seen: {self.device.Address} @ {rssi} dBm')
            write_to_log(self.device.Address, rssi)


def end_discovery():
    """Handler for end of discovery"""
    mainloop.quit()
    adapter.StopDiscovery()

def new_iface(path, iface_props):
    """If a new dbus interfaces is a device, add it to be  monitored"""
    device_addr = iface_props.get('org.bluez.Device1', {}).get('Address')
    if device_addr:
        DeviceMonitor(path)

# BlueZ object manager
mngr = bus.get('org.bluez', '/')
mngr.onInterfacesAdded = new_iface

# Connect to the DBus api for the Bluetooth adapter
adapter = bus.get('org.bluez', '/org/bluez/hci0')
adapter.DuplicateData = False

# Iterate around already known devices and add to monitor
mng_objs = mngr.GetManagedObjects()
for path in mng_objs:
    device = mng_objs[path].get('org.bluez.Device1', {}).get('Address', [])
    if device:
        DeviceMonitor(path)

# Run discovery for discovery_time
adapter.StartDiscovery()
GLib.timeout_add_seconds(discovery_time, end_discovery)
print('Finding nearby devices...')
try:
    mainloop.run()
except KeyboardInterrupt:
    end_discovery()

相关问题 更多 >