Skip to content

Commit

Permalink
feat: add calculate_distance_meters to estimate distance to a bluetoo…
Browse files Browse the repository at this point in the history
…th device (#28)
  • Loading branch information
Jc2k committed Sep 1, 2023
1 parent a6d8710 commit c6f0150
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/bluetooth_data_tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from struct import Struct

from .distance import calculate_distance_meters
from .gap import (
BLEGAPAdvertisement,
BLEGAPType,
Expand All @@ -26,6 +27,7 @@
"BLEGAPAdvertisement",
"parse_advertisement_data",
"parse_advertisement_data_tuple",
"calculate_distance_meters",
]


Expand Down
14 changes: 14 additions & 0 deletions src/bluetooth_data_tools/distance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from typing import cast

MAX_THEORETICAL_DISTANCE = 400.0


def calculate_distance_meters(power: int, rssi: int) -> float | None:
"""Calculate the distance in meters between the scanner and the device."""
if rssi == 0 or power == 0:
return None
if (ratio := rssi * 1.0 / power) < 1.0:
distance = pow(ratio, 10)
else:
distance = cast(float, 0.89976 * pow(ratio, 7.7095) + 0.111)
return min(distance, MAX_THEORETICAL_DISTANCE)
14 changes: 14 additions & 0 deletions tests/test_distance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Test utils."""
from bluetooth_data_tools import calculate_distance_meters


def tests_calculate_distance_meters():
"""Test distance estimate calculation."""
assert calculate_distance_meters(-59, -60) == 1.1352362990362899
assert calculate_distance_meters(59, -60) == 1.183020818815412
assert calculate_distance_meters(12, -80) == 400.0
assert calculate_distance_meters(59, 0) is None
assert calculate_distance_meters(-3, -100) == 400.0
assert calculate_distance_meters(-3, -96) == 400.0
assert calculate_distance_meters(-3, -3) == 1.01076
assert calculate_distance_meters(-4, -3) == 0.056313514709472656

0 comments on commit c6f0150

Please sign in to comment.