-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Create blackbox to record data (#44)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
- Loading branch information
1 parent
7bcc5d5
commit 9021aba
Showing
7 changed files
with
215 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
from datetime import datetime | ||
|
||
from loguru import logger | ||
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine | ||
|
||
from .timeseries_data import TimeseriesInput, add_timeseries_data | ||
from .timeseries_index import ( | ||
TimeseriesIndexMutation, | ||
create_timeseries_index, | ||
find_timeseries_index, | ||
) | ||
|
||
|
||
class Blackbox: | ||
"""The black box is used to store measurement data locally on the device. This data | ||
is stored to be send to the server at a later time. This is useful in case the device | ||
is not able to send the data to the server immediately. The black box stores the data | ||
in a SQLite database. The data is stored in the timeseries_data table. | ||
""" | ||
|
||
def __init__(self, engine: AsyncEngine): | ||
self._engine = engine | ||
self._timeseries_id_index: dict[str, dict[str, int]] = {} | ||
|
||
async def record( | ||
self, | ||
driver_identifier: str, | ||
read_timestamp: datetime, | ||
data: dict[str, float], | ||
) -> None: | ||
"""Inserts the reading into the database.""" | ||
|
||
async with self._engine.connect() as connection: | ||
|
||
await self._ensure_index_hydrated(connection, driver_identifier) | ||
|
||
timeseries_id_to_value: dict[int, float] = {} | ||
for driver_signal, value in data.items(): | ||
timeseries_id = await self._get_timeseries_id( | ||
connection=connection, | ||
driver_identifier=driver_identifier, | ||
driver_signal=driver_signal, | ||
) | ||
timeseries_id_to_value[timeseries_id] = value | ||
|
||
await add_timeseries_data( | ||
connection=connection, | ||
timeseries_input=TimeseriesInput( | ||
timestamp_utc=read_timestamp, values=timeseries_id_to_value | ||
), | ||
) | ||
|
||
logger.debug(f"Recorded data from driver {driver_identifier}.") | ||
|
||
async def _ensure_index_hydrated( | ||
self, connection: AsyncConnection, driver_identifier: str | ||
): | ||
"""Hydrates the timeseries_id index for the given driver_identifier.""" | ||
|
||
if driver_identifier in self._timeseries_id_index: | ||
return | ||
|
||
matching = await find_timeseries_index( | ||
connection=connection, driver_identifier=driver_identifier | ||
) | ||
|
||
driver_index = {} | ||
for match in matching: | ||
driver_index[match.driver_signal] = match.timeseries_id | ||
self._timeseries_id_index[driver_identifier] = driver_index | ||
|
||
async def _get_timeseries_id( | ||
self, connection: AsyncConnection, driver_identifier: str, driver_signal: str | ||
) -> int: | ||
"""Fetches the timeseries_id for the given driver_identifier and driver_signal. | ||
If the timeseries_id does not exist, it is created and returned. | ||
:param connection: The connection to the database. | ||
:param driver_identifier: The driver identifier. | ||
:param driver_signal: The driver signal. | ||
:return: The timeseries_id. | ||
""" | ||
|
||
try: | ||
return self._timeseries_id_index[driver_identifier][driver_signal] | ||
except KeyError: | ||
created = await create_timeseries_index( | ||
connection=connection, | ||
timeseries_index=TimeseriesIndexMutation( | ||
driver_identifier=driver_identifier, | ||
driver_signal=driver_signal, | ||
), | ||
) | ||
self._timeseries_id_index[driver_identifier][ | ||
driver_signal | ||
] = created.timeseries_id | ||
|
||
return created.timeseries_id |
78 changes: 78 additions & 0 deletions
78
lib/py_edge_device/carlos/edge/device/storage/blackbox_test.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
from datetime import UTC, datetime | ||
from random import randint | ||
|
||
from sqlalchemy import delete, func, select | ||
from sqlalchemy.ext.asyncio import AsyncEngine | ||
|
||
from .blackbox import Blackbox | ||
from .orm import TimeseriesDataOrm, TimeseriesIndexOrm | ||
from .timeseries_index import find_timeseries_index | ||
|
||
|
||
async def test_blackbox(async_engine: AsyncEngine): | ||
"""This function ensures that the blackbox works as expected.""" | ||
|
||
blackbox = Blackbox(engine=async_engine) | ||
|
||
fake_data = { | ||
"driver_signal_int": 1, | ||
"driver_signal_float": 2.0, | ||
"driver_signal_bool": True, | ||
} | ||
driver_identifier = "driver_identifier" | ||
|
||
await blackbox.record( | ||
driver_identifier=driver_identifier, | ||
read_timestamp=datetime.now(tz=UTC), | ||
data=fake_data, | ||
) | ||
|
||
# check if all index entries are made | ||
async with async_engine.connect() as connection: | ||
index_entries = await find_timeseries_index( | ||
connection, driver_identifier=driver_identifier | ||
) | ||
assert len(index_entries) == len(fake_data) | ||
|
||
for index_entry in index_entries: | ||
assert index_entry.driver_identifier == driver_identifier | ||
assert index_entry.driver_signal in fake_data | ||
assert index_entry.server_timeseries_id is None | ||
|
||
sample_cnt = randint(3, 10) | ||
|
||
# Record with multiple blackboxes to hit different paths of the code | ||
blackbox2 = Blackbox(engine=async_engine) | ||
|
||
# check if the data is recorded correctly | ||
for _ in range(sample_cnt): | ||
fake_data = { | ||
"driver_signal_int": randint(-100, 100), | ||
"driver_signal_float": randint(-100, 100) * 1.0, | ||
"driver_signal_bool": bool(randint(0, 1)), | ||
} | ||
|
||
await blackbox2.record( | ||
driver_identifier=driver_identifier, | ||
read_timestamp=datetime.now(tz=UTC), | ||
data=fake_data, | ||
) | ||
|
||
# count the number of entries per timeseries_id | ||
async with async_engine.connect() as connection: | ||
query = select( | ||
TimeseriesDataOrm.timeseries_id, | ||
func.count(TimeseriesDataOrm.timeseries_id).label("sample_cnt"), | ||
).group_by(TimeseriesDataOrm.timeseries_id) | ||
|
||
result = (await connection.execute(query)).all() | ||
|
||
for timeseries_id, cnt in result: | ||
assert cnt == sample_cnt + 1 # +1 because of the first record | ||
|
||
# final cleanup | ||
async with async_engine.connect() as connection: | ||
# clean up | ||
await connection.execute(delete(TimeseriesDataOrm)) | ||
await connection.execute(delete(TimeseriesIndexOrm)) | ||
await connection.commit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.