python-siseli 0.2.1__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {python_siseli-0.2.1 → python_siseli-0.2.3}/PKG-INFO +1 -1
  2. {python_siseli-0.2.1 → python_siseli-0.2.3}/pyproject.toml +1 -1
  3. {python_siseli-0.2.1 → python_siseli-0.2.3}/python_siseli.egg-info/PKG-INFO +1 -1
  4. {python_siseli-0.2.1 → python_siseli-0.2.3}/python_siseli.egg-info/SOURCES.txt +3 -0
  5. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/_utils.py +6 -1
  6. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/client.py +58 -0
  7. python_siseli-0.2.3/siseli/models/state.py +205 -0
  8. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/station.py +24 -0
  9. python_siseli-0.2.3/siseli/overview.py +95 -0
  10. python_siseli-0.2.3/tests/test_normalized_telemetry.py +88 -0
  11. python_siseli-0.2.3/tests/test_overview.py +140 -0
  12. python_siseli-0.2.1/siseli/models/state.py +0 -106
  13. {python_siseli-0.2.1 → python_siseli-0.2.3}/README.md +0 -0
  14. {python_siseli-0.2.1 → python_siseli-0.2.3}/python_siseli.egg-info/dependency_links.txt +0 -0
  15. {python_siseli-0.2.1 → python_siseli-0.2.3}/python_siseli.egg-info/requires.txt +0 -0
  16. {python_siseli-0.2.1 → python_siseli-0.2.3}/python_siseli.egg-info/top_level.txt +0 -0
  17. {python_siseli-0.2.1 → python_siseli-0.2.3}/setup.cfg +0 -0
  18. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/__init__.py +0 -0
  19. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/alarms.py +0 -0
  20. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/auth.py +0 -0
  21. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/config.py +0 -0
  22. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/const.py +0 -0
  23. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/dashboard.py +0 -0
  24. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/device.py +0 -0
  25. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/dictionary.py +0 -0
  26. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/exceptions.py +0 -0
  27. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/history.py +0 -0
  28. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/__init__.py +0 -0
  29. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/alarm.py +0 -0
  30. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/auth.py +0 -0
  31. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/common.py +0 -0
  32. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/config.py +0 -0
  33. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/dashboard.py +0 -0
  34. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/device.py +0 -0
  35. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/dictionary.py +0 -0
  36. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/models/history.py +0 -0
  37. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/open_auth.py +0 -0
  38. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/state.py +0 -0
  39. {python_siseli-0.2.1 → python_siseli-0.2.3}/siseli/station.py +0 -0
  40. {python_siseli-0.2.1 → python_siseli-0.2.3}/tests/test_auth.py +0 -0
  41. {python_siseli-0.2.1 → python_siseli-0.2.3}/tests/test_open_auth.py +0 -0
  42. {python_siseli-0.2.1 → python_siseli-0.2.3}/tests/test_phase3.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-siseli
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-siseli"
7
- version = "0.2.1"
7
+ version = "0.2.3"
8
8
  description = "Python SDK for Siseli Cloud"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-siseli
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -18,6 +18,7 @@ siseli/dictionary.py
18
18
  siseli/exceptions.py
19
19
  siseli/history.py
20
20
  siseli/open_auth.py
21
+ siseli/overview.py
21
22
  siseli/state.py
22
23
  siseli/station.py
23
24
  siseli/models/__init__.py
@@ -32,5 +33,7 @@ siseli/models/history.py
32
33
  siseli/models/state.py
33
34
  siseli/models/station.py
34
35
  tests/test_auth.py
36
+ tests/test_normalized_telemetry.py
35
37
  tests/test_open_auth.py
38
+ tests/test_overview.py
36
39
  tests/test_phase3.py
@@ -9,7 +9,12 @@ from typing import Any
9
9
  def parse_datetime(value: str | None) -> datetime | None:
10
10
  if not value:
11
11
  return None
12
- return datetime.fromisoformat(value.replace("Z", "+00:00"))
12
+ text = value.replace("Z", "+00:00")
13
+ if len(text) == 4 and text.isdigit():
14
+ text = f"{text}-01-01"
15
+ elif len(text) == 7 and text[4] == "-":
16
+ text = f"{text}-01"
17
+ return datetime.fromisoformat(text)
13
18
 
14
19
 
15
20
  def serialize_datetime(value: datetime | str | None) -> str | None:
@@ -42,6 +42,13 @@ from .models.dictionary import DictionaryData
42
42
  from .models.history import HistorySeries
43
43
  from .models.state import AttributeGroupSet, AttributeMetadata, DeviceState, EnergyFlow
44
44
  from .models.station import Station, StationEnergyFlow, StationSummary
45
+ from .overview import (
46
+ ENERGY_SUMMARY_CATEGORY,
47
+ fetch_device_generated_energy_daily,
48
+ fetch_device_power_class_daily_detail,
49
+ fetch_device_state_summary,
50
+ fetch_owner_state_summary,
51
+ )
45
52
  from .state import (
46
53
  fetch_device_attribute_groups,
47
54
  fetch_device_attributes,
@@ -369,6 +376,57 @@ class SiseliClient:
369
376
  time=time,
370
377
  )
371
378
 
379
+ async def get_device_summary(
380
+ self,
381
+ device_id: str,
382
+ aggregation: str,
383
+ *,
384
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
385
+ time: datetime | str | None = None,
386
+ ) -> StationSummary:
387
+ return await fetch_device_state_summary(
388
+ self._request,
389
+ device_id,
390
+ aggregation,
391
+ summary_category_key=summary_category_key,
392
+ time=time,
393
+ )
394
+
395
+ async def get_device_energy_totals(self, device_id: str) -> dict[str, float | None]:
396
+ """Return lifetime energy counters (kWh) keyed by property key."""
397
+ summary = await self.get_device_summary(device_id, "total")
398
+ return summary.to_totals()
399
+
400
+ async def get_owner_summary(
401
+ self,
402
+ aggregation: str,
403
+ *,
404
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
405
+ time: datetime | str | None = None,
406
+ ) -> StationSummary:
407
+ return await fetch_owner_state_summary(
408
+ self._request,
409
+ aggregation,
410
+ summary_category_key=summary_category_key,
411
+ time=time,
412
+ )
413
+
414
+ async def get_device_generated_energy_daily(
415
+ self,
416
+ device_id: str,
417
+ *,
418
+ time: datetime | str | None = None,
419
+ ) -> list[TimePoint]:
420
+ return await fetch_device_generated_energy_daily(self._request, device_id, time=time)
421
+
422
+ async def get_device_power_daily_detail(
423
+ self,
424
+ device_id: str,
425
+ *,
426
+ time: datetime | str | None = None,
427
+ ) -> dict[str, Any]:
428
+ return await fetch_device_power_class_daily_detail(self._request, device_id, time=time)
429
+
372
430
  async def get_latest_alarm(
373
431
  self,
374
432
  *,
@@ -0,0 +1,205 @@
1
+ """State, attribute, and energy-flow models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any
8
+
9
+ from .common import LookupValue
10
+
11
+
12
+ def _numeric(value: Any) -> float | None:
13
+ """Return finite numeric telemetry as a float, otherwise None."""
14
+ if value is None or isinstance(value, bool):
15
+ return None
16
+ try:
17
+ number = float(value)
18
+ except (TypeError, ValueError, OverflowError):
19
+ return None
20
+ if number != number or number in (float("inf"), float("-inf")):
21
+ return None
22
+ return number
23
+
24
+
25
+ @dataclass
26
+ class StateAttribute:
27
+ """A single telemetry attribute."""
28
+
29
+ key: str
30
+ unit: str
31
+ value: Any
32
+ value_display: str
33
+ name_display: str
34
+ is_hidden: bool | None
35
+
36
+
37
+ @dataclass
38
+ class AttributeMetadata:
39
+ """Metadata describing a state or configuration attribute."""
40
+
41
+ key: str
42
+ name: str
43
+ name_display: str
44
+ unit: str
45
+ value_type: int | None
46
+ category: int | None
47
+ operation_mode: int | None
48
+ is_hidden: bool | None
49
+ is_config_attribute: bool | None
50
+ is_writable_config_attribute: bool | None
51
+ is_readable_config_attribute: bool | None
52
+ is_state_attribute: bool | None
53
+ is_event_attribute: bool | None
54
+ enum_values: list[LookupValue]
55
+ raw: dict = field(repr=False)
56
+
57
+
58
+ @dataclass
59
+ class AttributeGroup:
60
+ """A group of related device attributes."""
61
+
62
+ id: str
63
+ key: str
64
+ category: int | None
65
+ name: str
66
+ description: str
67
+ attributes: list[AttributeMetadata]
68
+ raw: dict = field(repr=False)
69
+
70
+
71
+ @dataclass
72
+ class AttributeGroupSet:
73
+ """Grouped attribute metadata for a device."""
74
+
75
+ gather_protocol_version_id: str
76
+ groups: list[AttributeGroup]
77
+ raw: dict = field(repr=False)
78
+
79
+
80
+ @dataclass
81
+ class DeviceState:
82
+ """Latest telemetry snapshot for a device."""
83
+
84
+ time: datetime | None
85
+ fields: dict[str, StateAttribute]
86
+ raw: dict = field(repr=False)
87
+
88
+ def get(self, key: str) -> StateAttribute | None:
89
+ """Return an attribute by its key, or *None* if not present."""
90
+ return self.fields.get(key)
91
+
92
+ def to_sensor_data(self) -> dict[str, Any]:
93
+ """Return stable, typed semantic telemetry fields for integrations.
94
+
95
+ API-specific field names, unit conversions, and derived battery values
96
+ belong here rather than in consumer integrations. Invalid numeric
97
+ telemetry is represented as None. Power values reported in kW by this
98
+ device are converted to W.
99
+ """
100
+ def value(api_key: str) -> Any:
101
+ attribute = self.fields.get(api_key)
102
+ return attribute.value if attribute is not None else None
103
+
104
+ def number(api_key: str) -> float | None:
105
+ return _numeric(value(api_key))
106
+
107
+ def display(api_key: str) -> str | None:
108
+ attribute = self.fields.get(api_key)
109
+ text = attribute.value_display if attribute is not None else None
110
+ return text.strip() or None if isinstance(text, str) else None
111
+
112
+ def power_watts(api_key: str) -> float | None:
113
+ # The API reports power as kW unless the unit is explicitly W.
114
+ result = number(api_key)
115
+ attribute = self.fields.get(api_key)
116
+ if result is None or attribute is None:
117
+ return result
118
+ return result if attribute.unit == "W" else result * 1000
119
+
120
+ voltage = number("batteryVoltage")
121
+ charging = number("batteryChargingCurrent")
122
+ discharging = number("batteryDischargeCurrent")
123
+ current = (
124
+ charging - discharging
125
+ if charging is not None and discharging is not None
126
+ else None
127
+ )
128
+ pv_power = power_watts("generationPower")
129
+ load_power = power_watts("acOutputActivePower")
130
+ battery_power = (
131
+ voltage * current
132
+ if voltage is not None and current is not None
133
+ else None
134
+ )
135
+ return {
136
+ "battery_soc": number("batteryCapacity"),
137
+ "battery_voltage": voltage,
138
+ "battery_current": current,
139
+ "battery_power": battery_power,
140
+ "pv_voltage": number("pvInputVoltage1"),
141
+ "pv_current": number("pv1InputCurrentForBattery"),
142
+ "pv_power": pv_power,
143
+ "grid_voltage": number("gridVoltage"),
144
+ "grid_frequency": number("gridFrequency"),
145
+ "output_voltage": number("acOutputVoltage"),
146
+ "output_frequency": number("acOutputFrequency"),
147
+ "load_power": load_power,
148
+ "inverter_state": value("workingMode"),
149
+ "inverter_mode": display("workingMode"),
150
+ "load_percent": number("outputLoadPercent"),
151
+ "load_apparent_power": number("ratedApparentPower"),
152
+ "heat_sink_temperature": number("inverterHeatSinkTemperature"),
153
+ "bus_voltage": number("busVoltage"),
154
+ "charging_status": display("chargingStatus"),
155
+ "scc_charging_status": display("sccChargingStatus"),
156
+ "ac_charging_status": display("acChargingStatus"),
157
+ "mains_status": display("mainsStatus"),
158
+ "load_status": display("loadStatus"),
159
+ "charger_source_priority": display("chargerSourcePriority"),
160
+ "output_source_priority": display("outputSourcePriority"),
161
+ "battery_type": display("batteryType"),
162
+ }
163
+
164
+ def to_device_info(self) -> dict[str, str | None]:
165
+ """Return identification fields suitable for a device registry entry."""
166
+ def display(api_key: str) -> str | None:
167
+ attribute = self.fields.get(api_key)
168
+ text = attribute.value_display if attribute is not None else None
169
+ return text.strip() or None if isinstance(text, str) else None
170
+
171
+ return {
172
+ "protocol": display("protocolId"),
173
+ "machine_type": display("machineType"),
174
+ "firmware_version": display("mainCpuFirmwareVersion"),
175
+ "secondary_firmware_version": display("secondaryCpuFirmwareVersion"),
176
+ }
177
+
178
+
179
+ @dataclass
180
+ class FlowNode:
181
+ """One node of the energy-flow diagram (PV panel, grid, battery, load…)."""
182
+
183
+ key: str
184
+ locale_title: str
185
+ value: StateAttribute | None
186
+ flow_direction: int | None
187
+ is_light: bool | None
188
+ is_enabled: bool
189
+ extra_values: list[StateAttribute]
190
+ raw: dict = field(repr=False)
191
+
192
+
193
+ @dataclass
194
+ class EnergyFlow:
195
+ """Energy-flow snapshot for a device."""
196
+
197
+ device_state: DeviceState
198
+ pv_panel: FlowNode | None
199
+ grid: FlowNode | None
200
+ battery: FlowNode | None
201
+ load: FlowNode | None
202
+ generator: FlowNode | None
203
+ ups: FlowNode | None
204
+ ct: FlowNode | None
205
+ raw: dict = field(repr=False)
@@ -71,6 +71,22 @@ class SummaryProperty:
71
71
  has_real_time_points: bool | None
72
72
  raw: dict = field(repr=False)
73
73
 
74
+ @property
75
+ def key(self) -> str:
76
+ return self.property.get("key", "")
77
+
78
+ @property
79
+ def unit(self) -> str:
80
+ return self.property.get("unit") or self.property.get("unitI18n", {}).get("en", "")
81
+
82
+ @property
83
+ def latest_value(self) -> float | None:
84
+ """Value of the last time point, or None when the series is empty."""
85
+ for point in reversed(self.time_points):
86
+ if isinstance(point.value, (int, float)) and not isinstance(point.value, bool):
87
+ return float(point.value)
88
+ return None
89
+
74
90
 
75
91
  @dataclass
76
92
  class StationSummary:
@@ -80,3 +96,11 @@ class StationSummary:
80
96
  properties: list[SummaryProperty]
81
97
  has_real_time_points: bool
82
98
  raw: dict = field(repr=False)
99
+
100
+ def get(self, key: str) -> SummaryProperty | None:
101
+ """Return a summary property by its key, or None if absent."""
102
+ return next((item for item in self.properties if item.key == key), None)
103
+
104
+ def to_totals(self) -> dict[str, float | None]:
105
+ """Return the latest value of every property keyed by property key."""
106
+ return {item.key: item.latest_value for item in self.properties}
@@ -0,0 +1,95 @@
1
+ """Device and owner overview (energy statistics) helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any, Awaitable, Callable
7
+
8
+ from .models.common import TimePoint
9
+ from .models.station import StationSummary
10
+ from .station import _parse_station_summary, _parse_time_point
11
+
12
+ RequestFunc = Callable[..., Awaitable[Any]]
13
+
14
+ ENERGY_SUMMARY_CATEGORY = "pvInverterElectricityQuantityClass"
15
+ POWER_SUMMARY_CATEGORY = "pvInverterPowerClass"
16
+ AGGREGATIONS = ("daily", "monthly", "yearly", "total")
17
+
18
+ _TIME_FORMATS = {"daily": "%Y-%m-%d", "monthly": "%Y-%m", "yearly": "%Y"}
19
+
20
+
21
+ def _time_payload(aggregation: str, time: datetime | str | None) -> dict[str, str]:
22
+ """Build the request body using the time format the web UI sends."""
23
+ if aggregation not in AGGREGATIONS:
24
+ raise ValueError(f"aggregation must be one of {AGGREGATIONS}, got {aggregation!r}")
25
+ if isinstance(time, str):
26
+ return {"time": time}
27
+ moment = time or datetime.now().astimezone()
28
+ pattern = _TIME_FORMATS.get(aggregation)
29
+ return {"time": moment.strftime(pattern) if pattern else moment.isoformat()}
30
+
31
+
32
+ async def fetch_device_state_summary(
33
+ request: RequestFunc,
34
+ device_id: str,
35
+ aggregation: str,
36
+ *,
37
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
38
+ time: datetime | str | None = None,
39
+ ) -> StationSummary:
40
+ """Return aggregated device statistics (daily, monthly, yearly or total)."""
41
+ data = await request(
42
+ "POST",
43
+ f"/apis/deviceOverView/stateAttributeSummary/category/{aggregation}",
44
+ params={"deviceId": device_id, "summaryCategoryKey": summary_category_key},
45
+ json=_time_payload(aggregation, time),
46
+ )
47
+ return _parse_station_summary(data)
48
+
49
+
50
+ async def fetch_owner_state_summary(
51
+ request: RequestFunc,
52
+ aggregation: str,
53
+ *,
54
+ summary_category_key: str = ENERGY_SUMMARY_CATEGORY,
55
+ time: datetime | str | None = None,
56
+ ) -> StationSummary:
57
+ """Return aggregated statistics across all stations of the account."""
58
+ data = await request(
59
+ "POST",
60
+ f"/apis/ownerOverView/station/stateAttributeSummary/category/{aggregation}",
61
+ params={"summaryCategoryKey": summary_category_key},
62
+ json=_time_payload(aggregation, time),
63
+ )
64
+ return _parse_station_summary(data)
65
+
66
+
67
+ async def fetch_device_generated_energy_daily(
68
+ request: RequestFunc,
69
+ device_id: str,
70
+ *,
71
+ time: datetime | str | None = None,
72
+ ) -> list[TimePoint]:
73
+ """Return half-hourly generated energy for one day."""
74
+ data = await request(
75
+ "POST",
76
+ "/apis/deviceOverView/generatedEnergy/daily",
77
+ params={"deviceId": device_id},
78
+ json=_time_payload("daily", time),
79
+ )
80
+ return [_parse_time_point(item) for item in data]
81
+
82
+
83
+ async def fetch_device_power_class_daily_detail(
84
+ request: RequestFunc,
85
+ device_id: str,
86
+ *,
87
+ time: datetime | str | None = None,
88
+ ) -> dict[str, Any]:
89
+ """Return the raw per-day PV inverter power series (``timeSeries`` payload)."""
90
+ return await request(
91
+ "POST",
92
+ "/apis/deviceOverView/pvInverterPowerClass/daily/detail",
93
+ params={"deviceId": device_id},
94
+ json=_time_payload("daily", time),
95
+ )
@@ -0,0 +1,88 @@
1
+ """Tests for semantic device telemetry normalization."""
2
+
3
+ from datetime import UTC, datetime
4
+
5
+ import pytest
6
+
7
+ from siseli.models.state import DeviceState, StateAttribute
8
+
9
+
10
+ def make_state(values: dict) -> DeviceState:
11
+ fields = {
12
+ key: StateAttribute(
13
+ key=key,
14
+ unit="",
15
+ value=value,
16
+ value_display=str(value),
17
+ name_display=key,
18
+ is_hidden=False,
19
+ )
20
+ for key, value in values.items()
21
+ }
22
+ return DeviceState(time=datetime.now(UTC), fields=fields, raw={})
23
+
24
+
25
+ def test_to_sensor_data_maps_fields_and_converts_power_units() -> None:
26
+ result = make_state(
27
+ {
28
+ "batteryCapacity": 85,
29
+ "batteryVoltage": 52.1,
30
+ "batteryChargingCurrent": 10.5,
31
+ "batteryDischargeCurrent": 0,
32
+ "pvInputVoltage1": 380,
33
+ "pv1InputCurrentForBattery": 3.2,
34
+ "generationPower": 1.216,
35
+ "gridVoltage": 230,
36
+ "gridFrequency": 50,
37
+ "acOutputVoltage": 230,
38
+ "acOutputFrequency": 50,
39
+ "acOutputActivePower": 0.420,
40
+ "workingMode": "B",
41
+ }
42
+ ).to_sensor_data()
43
+
44
+ assert result["battery_soc"] == pytest.approx(85)
45
+ assert result["battery_voltage"] == pytest.approx(52.1)
46
+ assert result["pv_voltage"] == pytest.approx(380)
47
+ assert result["pv_current"] == pytest.approx(3.2)
48
+ assert result["grid_voltage"] == pytest.approx(230)
49
+ assert result["grid_frequency"] == pytest.approx(50)
50
+ assert result["output_voltage"] == pytest.approx(230)
51
+ assert result["output_frequency"] == pytest.approx(50)
52
+ assert result["battery_current"] == pytest.approx(10.5)
53
+ assert result["battery_power"] == pytest.approx(547.05)
54
+ assert result["pv_power"] == pytest.approx(1216)
55
+ assert result["load_power"] == pytest.approx(420)
56
+ assert result["inverter_state"] == "B"
57
+ assert "grid_power" not in result
58
+
59
+
60
+ def test_to_sensor_data_handles_discharge_and_invalid_values() -> None:
61
+ result = make_state(
62
+ {
63
+ "batteryVoltage": 52.1,
64
+ "batteryChargingCurrent": 0,
65
+ "batteryDischargeCurrent": 4.2,
66
+ "pvInputVoltage1": "--",
67
+ "pv1InputCurrentForBattery": True,
68
+ "generationPower": float("nan"),
69
+ "acOutputActivePower": "not available",
70
+ "workingMode": "B",
71
+ }
72
+ ).to_sensor_data()
73
+
74
+ assert result["battery_current"] == pytest.approx(-4.2)
75
+ assert result["battery_power"] == pytest.approx(-52.1 * 4.2)
76
+ assert result["pv_voltage"] is None
77
+ assert result["pv_current"] is None
78
+ assert result["pv_power"] is None
79
+ assert result["load_power"] is None
80
+ assert result["inverter_state"] == "B"
81
+
82
+
83
+ def test_to_sensor_data_returns_none_when_derived_inputs_missing() -> None:
84
+ result = make_state(
85
+ {"batteryVoltage": 12.8, "batteryChargingCurrent": 1}
86
+ ).to_sensor_data()
87
+ assert result["battery_current"] is None
88
+ assert result["battery_power"] is None
@@ -0,0 +1,140 @@
1
+ """Tests for overview statistics and extended telemetry normalization."""
2
+
3
+ import asyncio
4
+ from datetime import UTC, datetime
5
+
6
+ import pytest
7
+
8
+ from siseli.models.state import DeviceState, StateAttribute
9
+ from siseli.overview import (
10
+ fetch_device_generated_energy_daily,
11
+ fetch_device_state_summary,
12
+ fetch_owner_state_summary,
13
+ )
14
+
15
+
16
+ def make_request(response):
17
+ calls = []
18
+
19
+ async def request(method, path, **kwargs):
20
+ calls.append((method, path, kwargs))
21
+ return response
22
+
23
+ return request, calls
24
+
25
+
26
+ def summary_payload() -> dict:
27
+ def prop(key, points):
28
+ return {
29
+ "property": {"key": key, "unitI18n": {"en": "kWh"}, "unit": "kWh"},
30
+ "timePoints": points,
31
+ "hasRealTimePoints": True,
32
+ }
33
+
34
+ return {
35
+ "category": {"id": "2", "key": "pvInverterElectricityQuantityClass", "name": "Energy"},
36
+ "properties": [
37
+ prop("pvGeneratedEnergy", [{"time": "2026", "timeDisplay": "2026", "value": 12.5, "isRealValue": True}]),
38
+ prop("buyElectricityQuantity", []),
39
+ ],
40
+ }
41
+
42
+
43
+ def test_device_total_summary_request_and_totals() -> None:
44
+ request, calls = make_request(summary_payload())
45
+ summary = asyncio.run(
46
+ fetch_device_state_summary(
47
+ request, "dev1", "total", time=datetime(2026, 10, 12, 12, 0, tzinfo=UTC)
48
+ )
49
+ )
50
+
51
+ method, path, kwargs = calls[0]
52
+ assert method == "POST"
53
+ assert path == "/apis/deviceOverView/stateAttributeSummary/category/total"
54
+ assert kwargs["params"] == {
55
+ "deviceId": "dev1",
56
+ "summaryCategoryKey": "pvInverterElectricityQuantityClass",
57
+ }
58
+ assert kwargs["json"] == {"time": "2026-10-12T12:00:00+00:00"}
59
+ assert summary.get("pvGeneratedEnergy").unit == "kWh"
60
+ assert summary.to_totals() == {"pvGeneratedEnergy": 12.5, "buyElectricityQuantity": None}
61
+
62
+
63
+ @pytest.mark.parametrize(
64
+ ("aggregation", "expected"),
65
+ [("daily", "2026-10-12"), ("monthly", "2026-10"), ("yearly", "2026")],
66
+ )
67
+ def test_summary_time_format_per_aggregation(aggregation: str, expected: str) -> None:
68
+ request, calls = make_request(summary_payload())
69
+ asyncio.run(
70
+ fetch_owner_state_summary(request, aggregation, time=datetime(2026, 10, 12, tzinfo=UTC))
71
+ )
72
+ assert calls[0][1].endswith(f"/ownerOverView/station/stateAttributeSummary/category/{aggregation}")
73
+ assert calls[0][2]["json"] == {"time": expected}
74
+
75
+
76
+ def test_invalid_aggregation_rejected() -> None:
77
+ request, _ = make_request(summary_payload())
78
+ with pytest.raises(ValueError):
79
+ asyncio.run(fetch_device_state_summary(request, "dev1", "weekly"))
80
+
81
+
82
+ def test_generated_energy_daily_points() -> None:
83
+ request, calls = make_request(
84
+ [{"time": "2026-10-12 10:00:00", "timeDisplay": "10:00", "value": 0.5, "isRealValue": True}]
85
+ )
86
+ points = asyncio.run(fetch_device_generated_energy_daily(request, "dev1", time="2026-10-12"))
87
+ assert calls[0][2]["json"] == {"time": "2026-10-12"}
88
+ assert points[0].value == 0.5
89
+ assert points[0].time_display == "10:00"
90
+
91
+
92
+ def make_state(fields: dict) -> DeviceState:
93
+ return DeviceState(
94
+ time=None,
95
+ fields={
96
+ key: StateAttribute(key, unit, value, display, key, False)
97
+ for key, (value, display, unit) in fields.items()
98
+ },
99
+ raw={},
100
+ )
101
+
102
+
103
+ def test_extended_sensor_data_and_unit_aware_power() -> None:
104
+ data = make_state(
105
+ {
106
+ "workingMode": ("L", "Line Mode", ""),
107
+ "outputLoadPercent": (1, "1", "%"),
108
+ "inverterHeatSinkTemperature": (49, "49", "°C"),
109
+ "busVoltage": (419, "419", "V"),
110
+ "ratedApparentPower": (23, "23", "VA"),
111
+ "chargingStatus": ("1", "Charging On", ""),
112
+ "acOutputActivePower": (350, "350", "W"),
113
+ "generationPower": (0.5, "0.5", "kW"),
114
+ }
115
+ ).to_sensor_data()
116
+
117
+ assert data["inverter_state"] == "L"
118
+ assert data["inverter_mode"] == "Line Mode"
119
+ assert data["load_percent"] == 1
120
+ assert data["heat_sink_temperature"] == 49
121
+ assert data["bus_voltage"] == 419
122
+ assert data["load_apparent_power"] == 23
123
+ assert data["charging_status"] == "Charging On"
124
+ assert data["load_power"] == 350
125
+ assert data["pv_power"] == 500
126
+ assert data["mains_status"] is None
127
+
128
+
129
+ def test_device_info() -> None:
130
+ info = make_state(
131
+ {
132
+ "protocolId": ("PI30", "PI30", ""),
133
+ "machineType": ("x", "Off Grid", ""),
134
+ "mainCpuFirmwareVersion": ("v", "00019.06", ""),
135
+ }
136
+ ).to_device_info()
137
+ assert info["protocol"] == "PI30"
138
+ assert info["machine_type"] == "Off Grid"
139
+ assert info["firmware_version"] == "00019.06"
140
+ assert info["secondary_firmware_version"] is None
@@ -1,106 +0,0 @@
1
- """State, attribute, and energy-flow models."""
2
-
3
- from __future__ import annotations
4
-
5
- from dataclasses import dataclass, field
6
- from datetime import datetime
7
- from typing import Any
8
-
9
- from .common import LookupValue
10
-
11
-
12
- @dataclass
13
- class StateAttribute:
14
- """A single telemetry attribute."""
15
-
16
- key: str
17
- unit: str
18
- value: Any
19
- value_display: str
20
- name_display: str
21
- is_hidden: bool | None
22
-
23
-
24
- @dataclass
25
- class AttributeMetadata:
26
- """Metadata describing a state or configuration attribute."""
27
-
28
- key: str
29
- name: str
30
- name_display: str
31
- unit: str
32
- value_type: int | None
33
- category: int | None
34
- operation_mode: int | None
35
- is_hidden: bool | None
36
- is_config_attribute: bool | None
37
- is_writable_config_attribute: bool | None
38
- is_readable_config_attribute: bool | None
39
- is_state_attribute: bool | None
40
- is_event_attribute: bool | None
41
- enum_values: list[LookupValue]
42
- raw: dict = field(repr=False)
43
-
44
-
45
- @dataclass
46
- class AttributeGroup:
47
- """A group of related device attributes."""
48
-
49
- id: str
50
- key: str
51
- category: int | None
52
- name: str
53
- description: str
54
- attributes: list[AttributeMetadata]
55
- raw: dict = field(repr=False)
56
-
57
-
58
- @dataclass
59
- class AttributeGroupSet:
60
- """Grouped attribute metadata for a device."""
61
-
62
- gather_protocol_version_id: str
63
- groups: list[AttributeGroup]
64
- raw: dict = field(repr=False)
65
-
66
-
67
- @dataclass
68
- class DeviceState:
69
- """Latest telemetry snapshot for a device."""
70
-
71
- time: datetime | None
72
- fields: dict[str, StateAttribute]
73
- raw: dict = field(repr=False)
74
-
75
- def get(self, key: str) -> StateAttribute | None:
76
- """Return an attribute by its key, or *None* if not present."""
77
- return self.fields.get(key)
78
-
79
-
80
- @dataclass
81
- class FlowNode:
82
- """One node of the energy-flow diagram (PV panel, grid, battery, load…)."""
83
-
84
- key: str
85
- locale_title: str
86
- value: StateAttribute | None
87
- flow_direction: int | None
88
- is_light: bool | None
89
- is_enabled: bool
90
- extra_values: list[StateAttribute]
91
- raw: dict = field(repr=False)
92
-
93
-
94
- @dataclass
95
- class EnergyFlow:
96
- """Energy-flow snapshot for a device."""
97
-
98
- device_state: DeviceState
99
- pv_panel: FlowNode | None
100
- grid: FlowNode | None
101
- battery: FlowNode | None
102
- load: FlowNode | None
103
- generator: FlowNode | None
104
- ups: FlowNode | None
105
- ct: FlowNode | None
106
- raw: dict = field(repr=False)
File without changes
File without changes