python-siseli 0.2.0__tar.gz → 0.2.2__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 (39) hide show
  1. {python_siseli-0.2.0 → python_siseli-0.2.2}/PKG-INFO +1 -1
  2. {python_siseli-0.2.0 → python_siseli-0.2.2}/pyproject.toml +1 -1
  3. {python_siseli-0.2.0 → python_siseli-0.2.2}/python_siseli.egg-info/PKG-INFO +1 -1
  4. {python_siseli-0.2.0 → python_siseli-0.2.2}/python_siseli.egg-info/SOURCES.txt +1 -0
  5. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/state.py +59 -0
  6. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/open_auth.py +21 -30
  7. python_siseli-0.2.2/tests/test_normalized_telemetry.py +88 -0
  8. {python_siseli-0.2.0 → python_siseli-0.2.2}/tests/test_open_auth.py +47 -18
  9. {python_siseli-0.2.0 → python_siseli-0.2.2}/README.md +0 -0
  10. {python_siseli-0.2.0 → python_siseli-0.2.2}/python_siseli.egg-info/dependency_links.txt +0 -0
  11. {python_siseli-0.2.0 → python_siseli-0.2.2}/python_siseli.egg-info/requires.txt +0 -0
  12. {python_siseli-0.2.0 → python_siseli-0.2.2}/python_siseli.egg-info/top_level.txt +0 -0
  13. {python_siseli-0.2.0 → python_siseli-0.2.2}/setup.cfg +0 -0
  14. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/__init__.py +0 -0
  15. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/_utils.py +0 -0
  16. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/alarms.py +0 -0
  17. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/auth.py +0 -0
  18. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/client.py +0 -0
  19. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/config.py +0 -0
  20. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/const.py +0 -0
  21. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/dashboard.py +0 -0
  22. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/device.py +0 -0
  23. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/dictionary.py +0 -0
  24. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/exceptions.py +0 -0
  25. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/history.py +0 -0
  26. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/__init__.py +0 -0
  27. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/alarm.py +0 -0
  28. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/auth.py +0 -0
  29. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/common.py +0 -0
  30. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/config.py +0 -0
  31. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/dashboard.py +0 -0
  32. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/device.py +0 -0
  33. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/dictionary.py +0 -0
  34. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/history.py +0 -0
  35. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/models/station.py +0 -0
  36. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/state.py +0 -0
  37. {python_siseli-0.2.0 → python_siseli-0.2.2}/siseli/station.py +0 -0
  38. {python_siseli-0.2.0 → python_siseli-0.2.2}/tests/test_auth.py +0 -0
  39. {python_siseli-0.2.0 → python_siseli-0.2.2}/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.0
3
+ Version: 0.2.2
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.0"
7
+ version = "0.2.2"
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.0
3
+ Version: 0.2.2
4
4
  Summary: Python SDK for Siseli Cloud
5
5
  License: MIT
6
6
  Requires-Python: >=3.11
@@ -32,5 +32,6 @@ siseli/models/history.py
32
32
  siseli/models/state.py
33
33
  siseli/models/station.py
34
34
  tests/test_auth.py
35
+ tests/test_normalized_telemetry.py
35
36
  tests/test_open_auth.py
36
37
  tests/test_phase3.py
@@ -9,6 +9,19 @@ from typing import Any
9
9
  from .common import LookupValue
10
10
 
11
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
+
12
25
  @dataclass
13
26
  class StateAttribute:
14
27
  """A single telemetry attribute."""
@@ -76,6 +89,52 @@ class DeviceState:
76
89
  """Return an attribute by its key, or *None* if not present."""
77
90
  return self.fields.get(key)
78
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
+ voltage = number("batteryVoltage")
108
+ charging = number("batteryChargingCurrent")
109
+ discharging = number("batteryDischargeCurrent")
110
+ current = (
111
+ charging - discharging
112
+ if charging is not None and discharging is not None
113
+ else None
114
+ )
115
+ pv_power = number("generationPower")
116
+ load_power = number("acOutputActivePower")
117
+ battery_power = (
118
+ voltage * current
119
+ if voltage is not None and current is not None
120
+ else None
121
+ )
122
+ return {
123
+ "battery_soc": number("batteryCapacity"),
124
+ "battery_voltage": voltage,
125
+ "battery_current": current,
126
+ "battery_power": battery_power,
127
+ "pv_voltage": number("pvInputVoltage1"),
128
+ "pv_current": number("pv1InputCurrentForBattery"),
129
+ "pv_power": pv_power * 1000 if pv_power is not None else None,
130
+ "grid_voltage": number("gridVoltage"),
131
+ "grid_frequency": number("gridFrequency"),
132
+ "output_voltage": number("acOutputVoltage"),
133
+ "output_frequency": number("acOutputFrequency"),
134
+ "load_power": load_power * 1000 if load_power is not None else None,
135
+ "inverter_state": value("workingMode"),
136
+ }
137
+
79
138
 
80
139
  @dataclass
81
140
  class FlowNode:
@@ -7,18 +7,20 @@ client (CryptoJS-based) exactly:
7
7
  1. Decrypt the base64-encoded app secret with AES-128-CBC.
8
8
  Key and IV are derived from MD5(app_id) as ASCII hex chars.
9
9
  2. Compute a body hash: empty string for GET; SHA-256 hex for everything else.
10
- 3. Collect query params, inject the three open-auth fields, sort by key,
11
- serialise without URL-encoding, hex-encode the UTF-8 bytes.
12
- 4. Sign: HMAC-SHA256(hex_string, secret) → MD5 → lowercase hex.
10
+ 3. Sign input: ``IOT-Open-AppID``, ``IOT-Open-Body-Hash`` and
11
+ ``IOT-Open-Nonce`` only, sorted by key, joined as ``k=v&k=v`` without
12
+ URL-encoding, then base64-encoded (UTF-8).
13
+ 4. Sign: HMAC-SHA256(base64_string, secret) raw digest → MD5 → lowercase hex.
14
+ 5. The body hash is part of the signature but is NOT sent as an HTTP header.
13
15
  """
14
16
 
15
17
  from __future__ import annotations
16
18
 
19
+ import base64
17
20
  import hashlib
18
21
  import hmac
19
22
  import uuid
20
23
  from typing import TYPE_CHECKING, Any
21
- from urllib.parse import parse_qs
22
24
 
23
25
  from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
24
26
 
@@ -37,8 +39,6 @@ def decrypt_open_secret(app_id: str, encrypted_secret_b64: str) -> str:
37
39
 
38
40
  ZeroPadding is assumed: trailing null bytes are stripped from the output.
39
41
  """
40
- import base64
41
-
42
42
  md5_hex = hashlib.md5(app_id.encode()).hexdigest() # noqa: S324
43
43
  key = md5_hex[:16].encode("ascii")
44
44
  iv = md5_hex[16:].encode("ascii")
@@ -72,7 +72,8 @@ def build_open_headers(
72
72
  method:
73
73
  HTTP method ("GET", "POST", …).
74
74
  query:
75
- The raw query string portion of the URL (without the leading "?").
75
+ The raw query string portion of the URL. Accepted for API
76
+ compatibility; it does not take part in the signature.
76
77
  body:
77
78
  Raw request body bytes, or *None* / empty for GET requests.
78
79
  app_id:
@@ -90,39 +91,28 @@ def build_open_headers(
90
91
  else:
91
92
  body_hash = _sha256_hex(body if body else b"")
92
93
 
93
- # --- params for the sign input -------------------------------------------
94
- params: dict[str, str] = {}
95
- if query:
96
- for key, values in parse_qs(query, keep_blank_values=True).items():
97
- params[key] = values[0]
98
-
99
- # Remove any stale open-auth fields so they cannot influence the new sign.
100
- for field in ("IOT-Open-AppID", "IOT-Open-Nonce", "IOT-Open-Sign", "IOT-Open-Body-Hash"):
101
- params.pop(field, None)
102
-
103
- params["IOT-Open-AppID"] = app_id
104
- params["IOT-Open-Nonce"] = nonce
105
- params["IOT-Open-Body-Hash"] = body_hash
106
-
107
- # Sort alphabetically (case-sensitive, matching JS default sort order).
108
- query_str = "&".join(f"{k}={v}" for k, v in sorted(params.items()))
94
+ # --- sign input: exactly three params, sorted, no URL-encoding -----------
95
+ params = {
96
+ "IOT-Open-AppID": app_id,
97
+ "IOT-Open-Body-Hash": body_hash,
98
+ "IOT-Open-Nonce": nonce,
99
+ }
100
+ signing_string = "&".join(f"{k}={v}" for k, v in sorted(params.items()))
109
101
 
110
- # --- sign ----------------------------------------------------------------
111
- # CryptoJS: Utf8.parse(query_str) → Hex.stringify → hex_string
112
- # Then: HmacSHA256(hex_string, secret) → MD5 → hex
113
- hex_str = query_str.encode("utf-8").hex()
102
+ # --- sign: base64 -> HMAC-SHA256 (raw digest) -> MD5 hex -----------------
103
+ base64_input = base64.b64encode(signing_string.encode("utf-8")).decode("ascii")
114
104
  hmac_digest = hmac.new(
115
105
  app_secret.encode("utf-8"),
116
- hex_str.encode("utf-8"),
106
+ base64_input.encode("ascii"),
117
107
  hashlib.sha256,
118
108
  ).digest()
119
109
  sign = hashlib.md5(hmac_digest).hexdigest() # noqa: S324
120
110
 
111
+ # The body hash takes part in the signature but is not sent as a header.
121
112
  return {
122
113
  "IOT-Time-Zone": timezone,
123
114
  "IOT-Open-AppID": app_id,
124
115
  "IOT-Open-Nonce": nonce,
125
- "IOT-Open-Body-Hash": body_hash,
126
116
  "IOT-Open-Sign": sign,
127
117
  }
128
118
 
@@ -141,9 +131,10 @@ def attach_open_auth(
141
131
  - ``IOT-Time-Zone``
142
132
  - ``IOT-Open-AppID``
143
133
  - ``IOT-Open-Nonce``
144
- - ``IOT-Open-Body-Hash``
145
134
  - ``IOT-Open-Sign``
146
135
 
136
+ ``IOT-Open-Body-Hash`` is part of the signature but is not sent.
137
+
147
138
  Parameters
148
139
  ----------
149
140
  client:
@@ -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
@@ -2,14 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import hashlib
6
-
7
5
  import httpx
8
6
  import pytest
9
7
 
10
8
  from siseli.const import SISELI_APP_ID, SISELI_APP_SECRET_ENCRYPTED
11
9
  from siseli.open_auth import (
12
- _sha256_hex,
13
10
  attach_open_auth,
14
11
  build_open_headers,
15
12
  decrypt_open_secret,
@@ -48,8 +45,8 @@ def test_get_request_signing_uses_empty_body_hash() -> None:
48
45
  timezone="UTC",
49
46
  nonce="nonce-123",
50
47
  )
51
- assert headers["IOT-Open-Body-Hash"] == ""
52
- assert headers["IOT-Open-Sign"] == "bee1c1c32629baf72be698fbe53fdc11"
48
+ assert "IOT-Open-Body-Hash" not in headers
49
+ assert headers["IOT-Open-Sign"] == "a325bd9e648a5cd75ca803ccb801906e"
53
50
 
54
51
 
55
52
  def test_post_request_signing_with_json_body() -> None:
@@ -65,8 +62,7 @@ def test_post_request_signing_with_json_body() -> None:
65
62
  timezone="UTC",
66
63
  nonce="nonce-123",
67
64
  )
68
- assert headers["IOT-Open-Body-Hash"] == hashlib.sha256(body).hexdigest()
69
- assert headers["IOT-Open-Sign"] == "1f3525cce7ea5fa378409070c17f0076"
65
+ assert headers["IOT-Open-Sign"] == "6fa65e7127b26486b752cdfdf6e60793"
70
66
 
71
67
 
72
68
  def test_unicode_json_body_signing() -> None:
@@ -82,8 +78,7 @@ def test_unicode_json_body_signing() -> None:
82
78
  timezone="UTC",
83
79
  nonce="nonce-123",
84
80
  )
85
- assert headers["IOT-Open-Body-Hash"] == hashlib.sha256(body).hexdigest()
86
- assert headers["IOT-Open-Sign"] == "8d4c8f2771f9f7f419fd4cbec1d0f1e6"
81
+ assert headers["IOT-Open-Sign"] == "ef3d8c0d1834f59ae76312fcb43356aa"
87
82
 
88
83
 
89
84
  def test_empty_post_body_signing() -> None:
@@ -98,11 +93,7 @@ def test_empty_post_body_signing() -> None:
98
93
  timezone="UTC",
99
94
  nonce="nonce-123",
100
95
  )
101
- assert (
102
- headers["IOT-Open-Body-Hash"]
103
- == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
104
- )
105
- assert headers["IOT-Open-Sign"] == "9f8506bc2a8f3da76eebc4f99691d271"
96
+ assert headers["IOT-Open-Sign"] == "c9fc185f18a1082b3499aa2d74b08240"
106
97
 
107
98
 
108
99
  @pytest.mark.asyncio
@@ -125,13 +116,51 @@ async def test_header_generation_includes_required_iot_open_values() -> None:
125
116
  "IOT-Time-Zone",
126
117
  "IOT-Open-AppID",
127
118
  "IOT-Open-Nonce",
128
- "IOT-Open-Body-Hash",
129
119
  "IOT-Open-Sign",
130
120
  ):
131
121
  assert key in request.headers
122
+ assert "IOT-Open-Body-Hash" not in request.headers
132
123
  assert request.headers["IOT-Time-Zone"] == "Europe/Moscow"
133
124
  assert request.headers["IOT-Open-AppID"] == SISELI_APP_ID
134
- expected_hash = _sha256_hex(request.content)
135
- assert request.headers["IOT-Open-Body-Hash"] == expected_hash
136
- assert request.headers["IOT-Open-Sign"]
125
+ expected_sign = build_open_headers(
126
+ method="POST",
127
+ query="",
128
+ body=request.content,
129
+ app_id=SISELI_APP_ID,
130
+ app_secret=secret,
131
+ timezone="Europe/Moscow",
132
+ nonce=request.headers["IOT-Open-Nonce"],
133
+ )["IOT-Open-Sign"]
134
+ assert request.headers["IOT-Open-Sign"] == expected_sign
137
135
  assert request.headers["IOT-Open-Sign"] != secret
136
+
137
+
138
+ def test_body_change_changes_signature_and_query_is_ignored() -> None:
139
+ """Body bytes affect the signature; query string does not."""
140
+ secret = decrypt_open_secret(SISELI_APP_ID, SISELI_APP_SECRET_ENCRYPTED)
141
+
142
+ def sign(body: bytes, query: str = "") -> str:
143
+ return build_open_headers(
144
+ method="POST",
145
+ query=query,
146
+ body=body,
147
+ app_id=SISELI_APP_ID,
148
+ app_secret=secret,
149
+ timezone="UTC",
150
+ nonce="n",
151
+ )["IOT-Open-Sign"]
152
+
153
+ assert sign(b"{}") != sign(b"{ }")
154
+ assert sign(b"{}") == sign(b"{}", "a=1")
155
+
156
+
157
+ @pytest.mark.asyncio
158
+ async def test_each_request_gets_new_nonce() -> None:
159
+ client = _MockSiseliClient()
160
+ attach_open_auth(client)
161
+ hook = client._http.event_hooks["request"][0]
162
+ r1 = httpx.Request("GET", "https://solar.siseli.com/apis/x")
163
+ r2 = httpx.Request("GET", "https://solar.siseli.com/apis/x")
164
+ await hook(r1)
165
+ await hook(r2)
166
+ assert r1.headers["IOT-Open-Nonce"] != r2.headers["IOT-Open-Nonce"]
File without changes
File without changes