Add data_logging/src/data_logging/core.py
This commit is contained in:
commit
4cbf8d72f8
1 changed files with 41 additions and 0 deletions
41
data_logging/src/data_logging/core.py
Normal file
41
data_logging/src/data_logging/core.py
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
def log_data(timestamp: str, temperature: float, signal_noise_ratio: float) -> None:
|
||||||
|
"""Schreibt einen Datenpunkt mit Zeitstempel, Temperatur und SNR in ein JSON-Logfile."""
|
||||||
|
# Validierung der Eingabewerte
|
||||||
|
if not isinstance(timestamp, str) or not timestamp:
|
||||||
|
raise ValueError("timestamp muss ein nicht-leerer String sein.")
|
||||||
|
if not isinstance(temperature, (int, float)):
|
||||||
|
raise ValueError("temperature muss numerisch sein.")
|
||||||
|
if not isinstance(signal_noise_ratio, (int, float)):
|
||||||
|
raise ValueError("signal_noise_ratio muss numerisch sein.")
|
||||||
|
|
||||||
|
datapoint = {
|
||||||
|
"timestamp": timestamp,
|
||||||
|
"temperature": float(temperature),
|
||||||
|
"signal_noise_ratio": float(signal_noise_ratio)
|
||||||
|
}
|
||||||
|
|
||||||
|
log_dir = Path("output")
|
||||||
|
log_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
log_file = log_dir / "log_data.json"
|
||||||
|
|
||||||
|
if log_file.exists():
|
||||||
|
try:
|
||||||
|
with log_file.open("r", encoding="utf-8") as f:
|
||||||
|
existing_data = json.load(f)
|
||||||
|
if not isinstance(existing_data, list):
|
||||||
|
existing_data = []
|
||||||
|
except (json.JSONDecodeError, OSError):
|
||||||
|
existing_data = []
|
||||||
|
else:
|
||||||
|
existing_data = []
|
||||||
|
|
||||||
|
existing_data.append(datapoint)
|
||||||
|
|
||||||
|
with log_file.open("w", encoding="utf-8") as f:
|
||||||
|
json.dump(existing_data, f, indent=2, ensure_ascii=False)
|
||||||
Loading…
Reference in a new issue