From ae71fbdebba18f0fbaf1dcdf6db135eb6e86edc2 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 23 Sep 2022 08:37:59 -1000 Subject: [PATCH] fix: clamp distance to max theoretical value (#12) --- src/ibeacon_ble/__init__.py | 3 ++- tests/test_init.py | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/ibeacon_ble/__init__.py b/src/ibeacon_ble/__init__.py index 15bbeb1..1ac1344 100644 --- a/src/ibeacon_ble/__init__.py +++ b/src/ibeacon_ble/__init__.py @@ -9,6 +9,7 @@ UNPACK_IBEACON = struct.Struct(">HHb").unpack +MAX_THEORETICAL_DISTANCE = 400.0 APPLE_MFR_ID = 76 IBEACON_FIRST_BYTE = 0x02 @@ -86,4 +87,4 @@ def calculate_distance_meters(power: int, rssi: int) -> float | None: distance = pow(ratio, 10) else: distance = cast(float, 0.89976 * pow(ratio, 7.7095) + 0.111) - return distance if distance < 1000 else None + return min(distance, MAX_THEORETICAL_DISTANCE) diff --git a/tests/test_init.py b/tests/test_init.py index c0fdffe..223e66e 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -77,8 +77,9 @@ def test_not_parse_short_service_info(): def tests_calculate_distance_meters(): assert calculate_distance_meters(-59, -60) == 1.1352362990362899 assert calculate_distance_meters(59, -60) == 1.183020818815412 - assert calculate_distance_meters(12, -80) is None + assert calculate_distance_meters(12, -80) == 400.0 assert calculate_distance_meters(59, 0) is None - assert calculate_distance_meters(-3, -100) 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