Skip to content

Commit 5366958

Browse files
committed
Refactor database handling to support multiple fields.
Updated `write_to_database` to accept and process multiple fields, simplifying usage for batch operations. Removed unused `InfluxDBTag` class, consolidating data handling.
1 parent 9e74731 commit 5366958

File tree

3 files changed

+21
-32
lines changed

3 files changed

+21
-32
lines changed

README.md

+8-5
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,13 @@ It saves the following data:
213213

214214
## InfluxDB commands
215215

216-
- See all `energy_price`s: `influx query -org default -token <token> '
217-
import "experimental"
218-
from(bucket: "default")
219-
|> range(start: 0, stop: experimental.addDuration(d: 2d, to: now()))
220-
|> filter(fn: (r) => r._measurement == "energy_price")'`
221216
- Create bucket: `influx bucket create -org default -token <token> --name default`
222217
- Delete bucket: `influx bucket delete -org default -token <token> --name default`
218+
- Retrieve all solar forecast values: `influx query -org default -token <token> 'from(bucket: "default")
219+
|> range(start: -1d)
220+
|> filter(fn: (r) => r._measurement == "sun_forecast")
221+
|> pivot(rowKey:["_time"], columnKey:["_field"], valueColumn:"_value")'`
222+
- Retrieve all energy prices: `influx query -org default -token <token> 'import "experimental"
223+
from(bucket: "default")
224+
|> range(start: 0, stop: experimental.addDuration(d: 2d, to: now()))
225+
|> filter(fn: (r) => r._measurement == "energy_price")'`

source/database_handler.py

+8-16
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,11 @@
99

1010

1111
@dataclasses.dataclass
12-
class InfluxDBComponent: # TODO: Find better name
12+
class InfluxDBField:
1313
name: str
1414
value: float | str
1515

1616

17-
@dataclasses.dataclass
18-
class InfluxDBField(InfluxDBComponent):
19-
pass
20-
21-
22-
@dataclasses.dataclass
23-
class InfluxDBTag(InfluxDBComponent):
24-
pass
25-
26-
2717
class DatabaseHandler(LoggerMixin):
2818
def __init__(self, measurement: str):
2919
super().__init__()
@@ -39,19 +29,21 @@ def __init__(self, measurement: str):
3929
self.write_api = client.write_api(write_options=SYNCHRONOUS)
4030

4131
def write_to_database(
42-
self, field_to_insert: InfluxDBField, tags: list[InfluxDBTag] = None, timestamp: datetime = None
32+
self, fields_to_insert: InfluxDBField | list[InfluxDBField], timestamp: datetime = None
4333
) -> None:
4434
if timestamp is not None and timestamp.tzinfo is None:
4535
self.log.warning(f"Timestamp {timestamp} has no timezone information, adding it")
4636
timestamp = timestamp.replace(tzinfo=TimeHandler.get_timezone())
4737
if timestamp is None:
4838
timestamp = datetime.now(tz=TimeHandler.get_timezone())
4939

50-
point = Point(self.measurement).field(field_to_insert.name, field_to_insert.value)
51-
if tags is not None:
52-
for tag in tags:
53-
point = point.tag(tag.name, tag.value)
40+
point = Point(self.measurement)
41+
if type(fields_to_insert) is not list:
42+
fields_to_insert = [fields_to_insert]
43+
for field_to_insert in fields_to_insert:
44+
point = point.field(field_to_insert.name, field_to_insert.value)
5445
point = point.time(timestamp)
46+
# point = Point("sun_forecast").field("pv_estimate", 20.52).time(TimeHandler.get_time())
5547

5648
self.log.trace(f"Writing to database: {point}")
5749
self.write_api.write(bucket=self.bucket, record=point)

source/sun_forecast_handler.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from datetime import datetime, timedelta
22

33
import requests
4-
from database_handler import DatabaseHandler, InfluxDBField, InfluxDBTag
4+
from database_handler import DatabaseHandler, InfluxDBField
55
from energy_amount import EnergyAmount, Power
66
from environment_variable_getter import EnvironmentVariableGetter
77
from isodate import parse_duration
@@ -94,8 +94,10 @@ def get_solar_output_in_timeframe_for_rooftop(
9494
timeslot_start = timeslot_end - timeslot_duration
9595

9696
self.database_handler.write_to_database(
97-
InfluxDBField("pv_estimate", float(timeslot["pv_estimate"])),
98-
tags=[InfluxDBTag("retrieval_timestamp", now.isoformat())],
97+
[
98+
InfluxDBField("pv_estimate", float(timeslot["pv_estimate"] * 1000)),
99+
InfluxDBField("retrieval_timestamp", now.isoformat()),
100+
],
99101
timestamp=timeslot_start,
100102
)
101103

@@ -152,11 +154,3 @@ def get_solar_output_in_timeframe(self, timestamp_start: datetime, timestamp_end
152154
expected_solar_output += solar_forecast_for_rooftop
153155

154156
return expected_solar_output
155-
156-
157-
if __name__ == "__main__":
158-
s = SunForecastHandler()
159-
f = InfluxDBField("pv_estimate", 23.52)
160-
t = [InfluxDBTag("retrieval_timestamp", TimeHandler.get_time().isoformat())]
161-
start = TimeHandler.get_time() + timedelta(hours=5)
162-
s.database_handler.write_to_database(f, t, timestamp=start)

0 commit comments

Comments
 (0)