diff --git a/aqimon/database.py b/aqimon/database.py index 6489238..55b46e9 100644 --- a/aqimon/database.py +++ b/aqimon/database.py @@ -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", diff --git a/aqimon/read/novapm.py b/aqimon/read/novapm.py index 5fc6a87..c79f296 100644 --- a/aqimon/read/novapm.py +++ b/aqimon/read/novapm.py @@ -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() diff --git a/tests/test_database.py b/tests/test_database.py index eef7713..354b2bf 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -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)