Skip to content

Commit

Permalink
Merge pull request #35 from TimOrme/fix_average_read_rounding
Browse files Browse the repository at this point in the history
Fix rounding
  • Loading branch information
TimOrme authored Apr 24, 2023
2 parents 8922052 + 81909de commit a099ec5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
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

0 comments on commit a099ec5

Please sign in to comment.