Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix rounding #35

Merged
merged 2 commits into from
Apr 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion aqimon/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ async def get_averaged_reads(dbconn: databases.Database, lookback_to: datetime)
lookback = int(lookback_to.timestamp())
result = await dbconn.fetch_one(
"SELECT "
"AVG(pm25) as avg_pm25, AVG(pm10) as avg_pm10, COUNT(*) as count, MIN(event_time) as oldest_time "
"ROUND(AVG(pm25), 2) as avg_pm25, ROUND(AVG(pm10), 2) as avg_pm10, "
"COUNT(*) as count, "
"MIN(event_time) as oldest_time "
"FROM read_log "
"WHERE (event_time >= :lookback) OR "
"(event_time = (SELECT MAX(event_time) FROM read_log WHERE event_time <= :lookback)) ORDER BY event_time ASC",
Expand Down
2 changes: 1 addition & 1 deletion aqimon/read/novapm.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async def read(self) -> AqiRead:
pm10_reads.append(result.pm10)
self.reader.sleep()
self.state = ReaderState(ReaderStatus.IDLE, None)
return AqiRead(pmtwofive=mean(pm25_reads), pmten=mean(pm10_reads))
return AqiRead(pmtwofive=round(mean(pm25_reads), 2), pmten=round(mean(pm10_reads), 2))
except Exception as e:
self.state = ReaderState(ReaderStatus.ERRORING, e)
self.reader.sleep()
Expand Down
15 changes: 15 additions & 0 deletions tests/test_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,21 @@ async def test_get_averaged_reads(database_conn):
assert result.oldest_read_time == current_time - timedelta(hours=8)


@pytest.mark.asyncio
async def test_get_averaged_reads_rounding(database_conn):
# Add reads every two hours
current_time = datetime(2020, 1, 1, 12, 0, 0)
lookback_to = current_time - timedelta(hours=8)
await database.add_read(database_conn, current_time - timedelta(hours=2), pm10=2, pm25=2)
await database.add_read(database_conn, current_time - timedelta(hours=4), pm10=4, pm25=3)
await database.add_read(database_conn, current_time - timedelta(hours=6), pm10=4, pm25=3)

result = await database.get_averaged_reads(database_conn, lookback_to)
assert result.count == 3
assert result.avg_pm10 == 3.33
assert result.avg_pm25 == 2.67


@pytest.mark.asyncio
async def test_get_averaged_reads_looks_past(database_conn):
current_time = datetime(2020, 1, 1, 12, 0, 0)
Expand Down