-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add calculate_distance_meters to estimate distance to a bluetoo…
…th device (#28)
- Loading branch information
Showing
3 changed files
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |