Skip to content

Commit

Permalink
Merge e713f42 into 32917e0
Browse files Browse the repository at this point in the history
  • Loading branch information
puddly committed Mar 31, 2023
2 parents 32917e0 + e713f42 commit 7264c68
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 8 deletions.
4 changes: 2 additions & 2 deletions bellows/zigbee/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,9 +688,9 @@ async def energy_scan(
for channel, rssi in results:
all_results.setdefault(channel, []).append(rssi)

# Remap RSSI to LQI
# Remap RSSI to Energy
return {
channel: util.remap_rssi_to_lqi(statistics.mean(rssis))
channel: util.map_rssi_to_energy(statistics.mean(rssis))
for channel, rssis in all_results.items()
}

Expand Down
20 changes: 17 additions & 3 deletions bellows/zigbee/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,26 @@ def logistic(x: float, *, L: float = 1, x_0: float = 0, k: float = 1) -> float:
return L / (1 + math.exp(-k * (x - x_0)))


def remap_rssi_to_lqi(rssi: int) -> float:
"""Remaps RSSI (in dBm) to LQI (0-255)."""

def map_rssi_to_energy(rssi: int) -> float:
"""Remaps RSSI (in dBm) to Energy (0-255)."""
return logistic(
x=rssi,
L=255,
x_0=RSSI_MIN + 0.45 * (RSSI_MAX - RSSI_MIN),
k=0.13,
)


def logit(y: float, *, L: float = 1, x_0: float = 0, k: float = 1) -> float:
"""Logit function (inverse of logistic)."""
return x_0 - math.log(L / y - 1) / k


def map_energy_to_rssi(lqi: float) -> float:
"""Remaps Energy (0-255) back to RSSI (in dBm)."""
return logit(
y=lqi,
L=255,
x_0=RSSI_MIN + 0.45 * (RSSI_MAX - RSSI_MIN),
k=0.13,
)
11 changes: 8 additions & 3 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ def test_zigpy_key_to_ezsp_key(zigpy_key, ezsp_key, ezsp_mock):
assert util.zigpy_key_to_ezsp_key(zigpy_key, ezsp_mock) == ezsp_key


def test_remap_rssi_to_lqi():
assert 0 <= util.remap_rssi_to_lqi(-200) <= 0.01
assert 254 <= util.remap_rssi_to_lqi(100) <= 255
def test_map_rssi_to_energy():
assert 0 <= util.map_rssi_to_energy(-200) <= 0.01
assert 254 <= util.map_rssi_to_energy(100) <= 255

# Make sure the two functions are inverses
for rssi in range(-100, 100):
energy = util.map_rssi_to_energy(rssi)
assert abs(util.map_energy_to_rssi(energy) - rssi) < 0.1

0 comments on commit 7264c68

Please sign in to comment.