簡體   English   中英

獲取未連接藍牙設備的RSSI

[英]Get RSSI of non connected bluetooth device

我目前正在使用 raspberry pi 並且想要獲取未連接的藍牙地址的 RSSI。 我在用

import bluetooth

result=bluetooth.lookup_name('XX:XX:XX:XX:XX:XX',timeout=5)

if(result !=None):
  print("user near")
else:
  print("user far")

但我想更精確一點,並在更近的距離內轉到 else 塊,因此我需要一個 RSSI 值。 請幫忙。 我是樹莓派和 Python 的新手。 (我在 python3 中工作)

Bluepy 庫看起來對 RaspberryPI 有益。 不要忘記你應該像"sudo python3 name.py"從終端運行。

更多信息: https : //github.com/IanHarvey/bluepy/tree/master/docs

from bluepy.btle import Scanner

while True:
    try:
        #10.0 sec scanning
        ble_list = Scanner().scan(10.0)
        for dev in ble_list:
            print("rssi: {} ; mac: {}".format(dev.rssi,dev.addr))
    except:
        raise Exception("Error occured")
   

BlueZ 設備 API支持在 Raspberry Pi 上獲取 RSSI 值。

在下面的示例中,我使用pydbus作為庫來訪問 BlueZ 的 D-Bus API。 此示例掃描 60 秒並將設備地址和 RSSI 值寫入文件。 您可以修改代碼以在找到特定地址和 RSSI 值時采取行動。

from datetime import datetime
from pathlib import Path
import pydbus
from gi.repository import GLib

discovery_time = 60
log_file = Path('/home/pi/device.log')


def write_to_log(address, rssi):
    """Write device and rssi values to a log file"""
    now = datetime.now()
    current_time = now.strftime('%H:%M:%S')
    with log_file.open('a') as dev_log:
        dev_log.write(f'Device seen[{current_time}]: {address} @ {rssi} dBm\n')

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

class DeviceMonitor:
    """Class to represent remote bluetooth devices discovered"""
    def __init__(self, path_obj):
        self.device = bus.get('org.bluez', path_obj)
        self.device.onPropertiesChanged = self.prop_changed
        rssi = self.device.GetAll('org.bluez.Device1').get('RSSI')
        if rssi:
            print(f'Device added to monitor {self.device.Address} @ {rssi} dBm')
        else:
            print(f'Device added to monitor {self.device.Address}')

    def prop_changed(self, iface, props_changed, props_removed):
        """method to be called when a property value on a device changes"""
        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():
    """method called at the end of discovery scan"""
    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
print('Adding already known device 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()

如果您需要安裝gi.repository庫,請按照 Debian 說明中的“安裝系統提供的 PyGObject”進行操作: https ://pygobject.readthedocs.io/en/latest/getting_started.html#ubuntu-getting-started

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM