smartmeter-austria 1.0.0__py3-none-any.whl

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 (41) hide show
  1. smartmeter_austria/__init__.py +10 -0
  2. smartmeter_austria/bgld/__init__.py +0 -0
  3. smartmeter_austria/bgld/data.py +114 -0
  4. smartmeter_austria/bgld/read.py +8 -0
  5. smartmeter_austria/bgld/sensors.py +113 -0
  6. smartmeter_austria/config_validation.py +64 -0
  7. smartmeter_austria/dlms/__init__.py +0 -0
  8. smartmeter_austria/dlms/read.py +94 -0
  9. smartmeter_austria/fix_source_encoding.py +51 -0
  10. smartmeter_austria/meter_data.py +26 -0
  11. smartmeter_austria/noe/__init__.py +1 -0
  12. smartmeter_austria/noe/data.py +70 -0
  13. smartmeter_austria/noe/decrypt.py +38 -0
  14. smartmeter_austria/noe/mbus.py +93 -0
  15. smartmeter_austria/noe/obis.py +54 -0
  16. smartmeter_austria/noe/read.py +184 -0
  17. smartmeter_austria/noe/sensors.py +97 -0
  18. smartmeter_austria/obis/__init__.py +11 -0
  19. smartmeter_austria/obis/axdr.py +144 -0
  20. smartmeter_austria/obis/cipher.py +117 -0
  21. smartmeter_austria/obis/decode.py +31 -0
  22. smartmeter_austria/obis/dsmr.py +127 -0
  23. smartmeter_austria/obis/framing.py +280 -0
  24. smartmeter_austria/obis/reader.py +131 -0
  25. smartmeter_austria/obis/registers.py +233 -0
  26. smartmeter_austria/obis/sensors.py +109 -0
  27. smartmeter_austria/profile.py +300 -0
  28. smartmeter_austria/py.typed +0 -0
  29. smartmeter_austria/sensor_spec.py +39 -0
  30. smartmeter_austria/serial/__init__.py +0 -0
  31. smartmeter_austria/serial/rawlog.py +38 -0
  32. smartmeter_austria/serial/read.py +150 -0
  33. smartmeter_austria/serial/transport.py +171 -0
  34. smartmeter_austria/supervisor.py +212 -0
  35. smartmeter_austria/wien/__init__.py +0 -0
  36. smartmeter_austria/wien/data.py +127 -0
  37. smartmeter_austria/wien/sensors.py +77 -0
  38. smartmeter_austria-1.0.0.dist-info/METADATA +110 -0
  39. smartmeter_austria-1.0.0.dist-info/RECORD +41 -0
  40. smartmeter_austria-1.0.0.dist-info/WHEEL +4 -0
  41. smartmeter_austria-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,10 @@
1
+ """Read Austrian smart meters from their customer interface.
2
+
3
+ ``smartmeter_austria.profile`` is the entry point: ``get_profile(name)``
4
+ returns the profile of a grid operator's meter, ``create_reader`` builds an
5
+ asyncio reader for it. The package is shared by the Home Assistant
6
+ integration ``smartmeter_at`` and the MQTT add-on of the same repository.
7
+
8
+ Importing this package does not import gurux-dlms; see
9
+ ``smartmeter_austria.fix_source_encoding`` for why that matters.
10
+ """
File without changes
@@ -0,0 +1,114 @@
1
+ """Data structure definition for burgenland smartmeter"""
2
+
3
+ from typing import Any
4
+
5
+ from ..meter_data import BaseMeterData
6
+
7
+
8
+ class MeterData(BaseMeterData):
9
+ """Smart meter reply data parsed
10
+
11
+ Values provided
12
+ - Momentanspannung L1
13
+ - Momentanspannung L2
14
+ - Momentanspannung L3
15
+ - Momentanstrom L1
16
+ - Momentanstrom L2
17
+ - Momentanstrom L3
18
+ - Wirkleistung +P
19
+ - Wirkleistung -P
20
+ - Wirkenergietotal +A
21
+ - Wirkenergietotal -A
22
+ - Winkel Spannung L1 zu Strom L1
23
+ - Winkel Spannung L2 zu Strom L3
24
+ - Winkel Spannung L3 zu Strom L3
25
+ - Zähleridentifikationsnummern des Netzbetreibers
26
+ """
27
+
28
+ def __init__(self, dlms_data: list[Any]):
29
+ self.dlms_data = dlms_data
30
+
31
+ self.voltage_l1 = 0
32
+ self.voltage_l2 = 0
33
+ self.voltage_l3 = 0
34
+
35
+ self.current_l1: float = 0
36
+ self.current_l2: float = 0
37
+ self.current_l3: float = 0
38
+
39
+ self.power_consumed = 0
40
+ self.power_provided = 0
41
+
42
+ self.total_consumed = 0
43
+ self.total_provided = 0
44
+
45
+ self.meter_id: str | None = None
46
+
47
+ # Winkel Spannung L1 zu Strom L1
48
+ self.angle_1 = 0
49
+ # Winkel Spannung L2 zu Strom L3
50
+ self.angle_2 = 0
51
+ # Winkel Spannung L3 zu Strom L3
52
+ self.angle_3 = 0
53
+
54
+ self.parse()
55
+
56
+ def parse(self):
57
+ """Parse dlms data."""
58
+ if not self.dlms_data:
59
+ return
60
+
61
+ (
62
+ self.voltage_l1,
63
+ self.voltage_l2,
64
+ self.voltage_l3,
65
+ self.current_l1,
66
+ self.current_l2,
67
+ self.current_l3,
68
+ self.power_consumed,
69
+ self.power_provided,
70
+ self.total_consumed,
71
+ self.total_provided,
72
+ *rest,
73
+ ) = self.dlms_data
74
+
75
+ # the value seems to be in 10mA
76
+ self.current_l1 = self.current_l1 / 100
77
+ self.current_l2 = self.current_l2 / 100
78
+ self.current_l3 = self.current_l3 / 100
79
+
80
+ if len(rest) >= 3:
81
+ (self.angle_1, self.angle_2, self.angle_3, *rest2) = rest
82
+ if len(rest) > 3:
83
+ self.meter_id = str(rest[3], "UTF-8")
84
+
85
+ def __str__(self) -> str:
86
+ return (
87
+ f"MeterData["
88
+ f"U({self.voltage_l1}V,{self.voltage_l2}V,{self.voltage_l3}V),"
89
+ f"I({self.current_l1}A,{self.current_l2}A,{self.current_l3}A),"
90
+ f"P({self.power_consumed}W,-{self.power_provided}W),"
91
+ f"W({self.total_consumed}Wh,-{self.total_provided}Wh)"
92
+ f"Angle({self.angle_1},{self.angle_2},{self.angle_3})"
93
+ # f"id({self.meter_id})"
94
+ f"]"
95
+ )
96
+
97
+ def to_dict(self) -> dict:
98
+ """Return item as dict"""
99
+ return {
100
+ "u1": self.voltage_l1,
101
+ "u2": self.voltage_l2,
102
+ "u3": self.voltage_l3,
103
+ "i1": self.current_l1,
104
+ "i2": self.current_l2,
105
+ "i3": self.current_l3,
106
+ "w_con": self.power_consumed,
107
+ "w_prov": self.power_provided,
108
+ "total_con": self.total_consumed,
109
+ "total_prov": self.total_provided,
110
+ # "meter_id": self.meter_id,
111
+ "angle1": self.angle_1,
112
+ "angle2": self.angle_2,
113
+ "angle3": self.angle_3,
114
+ }
@@ -0,0 +1,8 @@
1
+ from .data import MeterData
2
+ from ..dlms.read import parse_dlms_data
3
+
4
+
5
+ def parse_dlms_data_bgld(data: bytes, key: str):
6
+ """Parse the data and construct a MeterData object"""
7
+ decrypted_data = parse_dlms_data(data, key)
8
+ return MeterData(decrypted_data)
@@ -0,0 +1,113 @@
1
+ """Home Assistant MQTT sensor catalog for the Burgenland / L+G E450 profile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..sensor_spec import SensorSpec
6
+
7
+ SENSOR_SPECS: tuple[SensorSpec, ...] = (
8
+ SensorSpec(name="Raw Data", suffix="", raw=True),
9
+ SensorSpec(
10
+ name="Total Energy consumed",
11
+ suffix="_total_energy_consumed",
12
+ value_template="{{ value_json.total_con }}",
13
+ unit_of_measurement="Wh",
14
+ device_class="energy",
15
+ state_class="total_increasing",
16
+ ),
17
+ SensorSpec(
18
+ name="Total Energy provided",
19
+ suffix="_total_energy_provided",
20
+ value_template="{{ value_json.total_prov }}",
21
+ unit_of_measurement="Wh",
22
+ device_class="energy",
23
+ state_class="total_increasing",
24
+ ),
25
+ SensorSpec(
26
+ name="Power consumed",
27
+ suffix="_power_consumed",
28
+ value_template="{{ value_json.w_con }}",
29
+ unit_of_measurement="W",
30
+ device_class="power",
31
+ state_class="measurement",
32
+ ),
33
+ SensorSpec(
34
+ name="Power provided",
35
+ suffix="_power_provided",
36
+ value_template="{{ value_json.w_prov }}",
37
+ unit_of_measurement="W",
38
+ device_class="power",
39
+ state_class="measurement",
40
+ ),
41
+ SensorSpec(
42
+ name="Voltage L1",
43
+ suffix="_voltage_l1",
44
+ value_template="{{ value_json.u1 }}",
45
+ unit_of_measurement="V",
46
+ device_class="voltage",
47
+ state_class="measurement",
48
+ ),
49
+ SensorSpec(
50
+ name="Voltage L2",
51
+ suffix="_voltage_l2",
52
+ value_template="{{ value_json.u2 }}",
53
+ unit_of_measurement="V",
54
+ device_class="voltage",
55
+ state_class="measurement",
56
+ ),
57
+ SensorSpec(
58
+ name="Voltage L3",
59
+ suffix="_voltage_l3",
60
+ value_template="{{ value_json.u3 }}",
61
+ unit_of_measurement="V",
62
+ device_class="voltage",
63
+ state_class="measurement",
64
+ ),
65
+ SensorSpec(
66
+ name="Current L1",
67
+ suffix="_current_l1",
68
+ value_template="{{ value_json.i1 }}",
69
+ unit_of_measurement="A",
70
+ device_class="current",
71
+ state_class="measurement",
72
+ ),
73
+ SensorSpec(
74
+ name="Current L2",
75
+ suffix="_current_l2",
76
+ value_template="{{ value_json.i2 }}",
77
+ unit_of_measurement="A",
78
+ device_class="current",
79
+ state_class="measurement",
80
+ ),
81
+ SensorSpec(
82
+ name="Current L3",
83
+ suffix="_current_l3",
84
+ value_template="{{ value_json.i3 }}",
85
+ unit_of_measurement="A",
86
+ device_class="current",
87
+ state_class="measurement",
88
+ ),
89
+ SensorSpec(
90
+ name="Angle between voltage L1 to current L1",
91
+ suffix="_angle_l1",
92
+ value_template="{{ value_json.angle1 }}",
93
+ unit_of_measurement="°",
94
+ state_class="measurement",
95
+ enabled_by_default=False,
96
+ ),
97
+ SensorSpec(
98
+ name="Angle between voltage L2 to current L2",
99
+ suffix="_angle_l2",
100
+ value_template="{{ value_json.angle2 }}",
101
+ unit_of_measurement="°",
102
+ state_class="measurement",
103
+ enabled_by_default=False,
104
+ ),
105
+ SensorSpec(
106
+ name="Angle between voltage L3 to current L3",
107
+ suffix="_angle_l3",
108
+ value_template="{{ value_json.angle3 }}",
109
+ unit_of_measurement="°",
110
+ state_class="measurement",
111
+ enabled_by_default=False,
112
+ ),
113
+ )
@@ -0,0 +1,64 @@
1
+ """Fail-fast validation for the add-on configuration."""
2
+
3
+ import re
4
+
5
+ import serial
6
+
7
+ from .profile import DEFAULT_METER_TYPE, known_meter_types
8
+
9
+ HEX_KEY_RE = re.compile(r"^[0-9a-fA-F]{32}$")
10
+
11
+ VALID_PARITY_LETTERS = set(serial.PARITY_NAMES.keys())
12
+ VALID_PARITY_NAMES = {name.upper() for name in serial.PARITY_NAMES.values()}
13
+
14
+ # Derived from the profile registry so a new profile is accepted everywhere
15
+ # as soon as it is registered.
16
+ VALID_METER_TYPES = frozenset(known_meter_types())
17
+
18
+ __all__ = ["ConfigError", "DEFAULT_METER_TYPE", "VALID_METER_TYPES", "validate_config"]
19
+
20
+
21
+ class ConfigError(ValueError):
22
+ """Raised when the add-on configuration is invalid."""
23
+
24
+
25
+ def validate_config(config: dict) -> None:
26
+ """Validate required add-on configuration keys.
27
+
28
+ Raises ConfigError if anything mandatory is missing or malformed.
29
+ """
30
+ if not isinstance(config, dict):
31
+ raise ConfigError("config must be a mapping")
32
+
33
+ meter_type = config.get("meter_type", DEFAULT_METER_TYPE)
34
+ if meter_type not in VALID_METER_TYPES:
35
+ raise ConfigError(
36
+ f"meter_type {meter_type!r} is not valid; "
37
+ f"allowed: {sorted(VALID_METER_TYPES)}"
38
+ )
39
+
40
+ mqtt = config.get("mqtt") or {}
41
+ if not isinstance(mqtt, dict):
42
+ raise ConfigError("mqtt config must be a mapping")
43
+ if not mqtt.get("host"):
44
+ raise ConfigError("mqtt.host is required")
45
+
46
+ dlms = config.get("dlms") or {}
47
+ if not isinstance(dlms, dict):
48
+ raise ConfigError("dlms config must be a mapping")
49
+
50
+ key = dlms.get("key")
51
+ if not key or not HEX_KEY_RE.match(str(key)):
52
+ raise ConfigError("dlms.key must be a 32-character hex string")
53
+
54
+ parity = dlms.get("parity")
55
+ if parity is not None and parity != "":
56
+ parity_str = str(parity)
57
+ if (
58
+ parity_str not in VALID_PARITY_LETTERS
59
+ and parity_str.upper() not in VALID_PARITY_NAMES
60
+ ):
61
+ allowed = sorted(VALID_PARITY_LETTERS | VALID_PARITY_NAMES)
62
+ raise ConfigError(
63
+ f"dlms.parity {parity_str!r} is not valid; allowed: {allowed}"
64
+ )
File without changes
@@ -0,0 +1,94 @@
1
+ import logging
2
+
3
+ from bs4 import BeautifulSoup
4
+ from gurux_common import GXCommon
5
+ from gurux_dlms import (
6
+ GXByteBuffer,
7
+ GXDLMSTranslator,
8
+ GXDLMSTranslatorMessage,
9
+ GXReplyData,
10
+ )
11
+ from gurux_dlms.enums import InterfaceType, Security, TranslatorOutputType
12
+ from gurux_dlms.secure import GXDLMSSecureClient
13
+
14
+ log = logging.getLogger("smartmeter_austria.dlms.read")
15
+
16
+
17
+ def parse_dlms_data(data: bytes, key: str):
18
+ """Parse DLMS data."""
19
+ bb = GXByteBuffer(data)
20
+ cl = GXDLMSSecureClient()
21
+ data = GXReplyData()
22
+ notify = GXReplyData()
23
+ # cl.interfaceType = InterfaceType.PDU
24
+ cl.interfaceType = InterfaceType.HDLC
25
+ cl.ciphering.security = Security.ENCRYPTION
26
+ # key as hex str
27
+ cl.ciphering.blockCipherKey = GXCommon.hexToBytes(key)
28
+ # plaintext = cl.getData(bb, data, notify)
29
+ cl.getData(bb, data, notify)
30
+ # notify.value is an instance of type GXStructure, which is a list
31
+ # log.info("notify.value: %s", notify.value)
32
+ # notify.data are the decryted hex values of the body
33
+ # log.info("notify data: %s", notify.data)
34
+ # log.info("plain: %s", plaintext)
35
+
36
+ # or plaintext?
37
+ return notify
38
+
39
+
40
+ def parse_pyhiscal_dlms_data(data: bytes, key: str):
41
+ """Parse DLMS data from an phyisical interface."""
42
+ tr = GXDLMSTranslator()
43
+ tr.blockCipherKey = GXByteBuffer(key)
44
+ tr.comments = True
45
+ msg = GXDLMSTranslatorMessage()
46
+ msg.message = GXByteBuffer(data)
47
+ # Pin the framing to HDLC. Without this, ``interfaceType`` stays ``None`` and
48
+ # ``findNextFrame`` scans the buffer trying every framing; a misaligned byte
49
+ # can match ``isWirelessMBusData`` and enter the wireless M-Bus branch, which
50
+ # calls the broken ``_GXCommon.decryptManufacturer`` (removed in gurux-dlms
51
+ # >= 1.0.193) and raises AttributeError. Our serial meters are always HDLC.
52
+ # See https://github.com/r00tat/smartmeter_homeassistant_burgenland/issues/98
53
+ msg.interfaceType = InterfaceType.HDLC
54
+ xml = ""
55
+ pdu = GXByteBuffer()
56
+ tr.completePdu = True
57
+ while tr.findNextFrame(msg, pdu):
58
+ pdu.clear()
59
+ xml += tr.messageToXml(msg)
60
+ return xml
61
+
62
+
63
+ def convert_to_xml(notify: GXReplyData):
64
+ """Convert parsed data to xml."""
65
+ t = GXDLMSTranslator(TranslatorOutputType.SIMPLE_XML)
66
+ xml = t.dataToXml(notify.data)
67
+ # log.info("xml: %s", xml)
68
+ return xml
69
+
70
+
71
+ def parse_xml(xml: str) -> list:
72
+ """Parsing xml response"""
73
+ soup = BeautifulSoup(xml, "xml")
74
+ struct = soup.find("Structure")
75
+
76
+ all_values: list = []
77
+ if struct is None:
78
+ log.debug("no <Structure> element found")
79
+ return all_values
80
+
81
+ log.debug("struct: %s", struct)
82
+ for child in struct.findChildren():
83
+ parsed_value: int | bytearray | None = None
84
+ if child.name.startswith("UInt"):
85
+ parsed_value = int(child["Value"], 16)
86
+
87
+ if child.name.startswith("OctetString"):
88
+ parsed_value = bytearray.fromhex(child["Value"])
89
+
90
+ if parsed_value is not None:
91
+ all_values.append(parsed_value)
92
+
93
+ log.debug("all values: %s", all_values)
94
+ return all_values
@@ -0,0 +1,51 @@
1
+ """Re-encode non-UTF-8 source files of installed packages to UTF-8.
2
+
3
+ gurux-dlms 1.0.197 ships ``objects/GXDLMSObjectCollection.py`` with a Latin-1
4
+ encoded comment and no encoding declaration. Python up to 3.14 tolerated
5
+ invalid UTF-8 inside comments, Python 3.15 rejects the file with a
6
+ ``SyntaxError`` and ``import gurux_dlms`` fails, so the add-on did not start
7
+ on the current Home Assistant base image (#128).
8
+
9
+ Usage (at image build time, after ``pip install``)::
10
+
11
+ python3 -m smartmeter_austria.fix_source_encoding gurux_dlms gurux_common
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import importlib.util
17
+ import sys
18
+ from pathlib import Path
19
+
20
+
21
+ def fix_directory(root: Path) -> list[Path]:
22
+ """Convert every ``*.py`` file below ``root`` that is not valid UTF-8."""
23
+ fixed: list[Path] = []
24
+ for path in sorted(root.rglob("*.py")):
25
+ raw = path.read_bytes()
26
+ try:
27
+ raw.decode("utf-8")
28
+ except UnicodeDecodeError:
29
+ path.write_bytes(raw.decode("latin-1").encode("utf-8"))
30
+ fixed.append(path)
31
+ return fixed
32
+
33
+
34
+ def package_dirs(name: str) -> list[Path]:
35
+ """Return the source directories of ``name`` without importing it."""
36
+ spec = importlib.util.find_spec(name)
37
+ if spec is None or not spec.submodule_search_locations:
38
+ raise SystemExit(f"package {name!r} not found")
39
+ return [Path(location) for location in spec.submodule_search_locations]
40
+
41
+
42
+ def main(names: list[str]) -> None:
43
+ """Fix the given installed packages."""
44
+ for name in names:
45
+ for directory in package_dirs(name):
46
+ for path in fix_directory(directory):
47
+ print(f"re-encoded {path} from latin-1 to utf-8")
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main(sys.argv[1:])
@@ -0,0 +1,26 @@
1
+ """Common base for the decoded readings of every meter profile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from abc import ABC, abstractmethod
7
+ from typing import Any
8
+
9
+
10
+ class BaseMeterData(ABC):
11
+ """One decoded telegram, ready to be published.
12
+
13
+ Every profile maps its meter's telegram onto a subclass. The MQTT side
14
+ only relies on ``to_json`` (the state payload the sensor templates read)
15
+ and ``meter_id`` (the serial number shown in Home Assistant, if the
16
+ meter sends one).
17
+ """
18
+
19
+ meter_id: str | None = None
20
+
21
+ @abstractmethod
22
+ def to_dict(self) -> dict[str, Any]:
23
+ """Return the values keyed by the names the sensor templates use."""
24
+
25
+ def to_json(self) -> str:
26
+ return json.dumps(self.to_dict())
@@ -0,0 +1 @@
1
+ """Netz Niederösterreich / EVN Sagemcom T210-D profile."""
@@ -0,0 +1,70 @@
1
+ """Parsed meter data from the Sagemcom T210-D (Netz NÖ / EVN)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ..meter_data import BaseMeterData
8
+
9
+ # Scaling is expressed as a divisor (not a float multiplier) to keep
10
+ # the serialised result exact (2301/10 == 230.1, but 2301*0.1 is not).
11
+ _VOLTAGE_DIVISOR = 10
12
+ _CURRENT_DIVISOR = 100
13
+ _POWER_FACTOR_DIVISOR = 1000
14
+
15
+
16
+ class MeterData(BaseMeterData):
17
+ """Netz-NÖ meter data keyed by OBIS field name.
18
+
19
+ Values are provided by the meter as plain integers and must be
20
+ scaled for the physical quantity they represent.
21
+ """
22
+
23
+ def __init__(self, obis_values: dict[str, Any]):
24
+ self.obis_values = obis_values
25
+
26
+ self.voltage_l1: float = obis_values.get("voltage_l1", 0) / _VOLTAGE_DIVISOR
27
+ self.voltage_l2: float = obis_values.get("voltage_l2", 0) / _VOLTAGE_DIVISOR
28
+ self.voltage_l3: float = obis_values.get("voltage_l3", 0) / _VOLTAGE_DIVISOR
29
+
30
+ self.current_l1: float = obis_values.get("current_l1", 0) / _CURRENT_DIVISOR
31
+ self.current_l2: float = obis_values.get("current_l2", 0) / _CURRENT_DIVISOR
32
+ self.current_l3: float = obis_values.get("current_l3", 0) / _CURRENT_DIVISOR
33
+
34
+ self.power_consumed: int = obis_values.get("power_consumed", 0)
35
+ self.power_provided: int = obis_values.get("power_provided", 0)
36
+
37
+ self.total_consumed: int = obis_values.get("energy_consumed", 0)
38
+ self.total_provided: int = obis_values.get("energy_provided", 0)
39
+
40
+ self.power_factor: float = (
41
+ obis_values.get("power_factor", 0) / _POWER_FACTOR_DIVISOR
42
+ )
43
+
44
+ self.meter_id: str | None = None
45
+
46
+ def __str__(self) -> str:
47
+ return (
48
+ f"MeterData["
49
+ f"U({self.voltage_l1}V,{self.voltage_l2}V,{self.voltage_l3}V),"
50
+ f"I({self.current_l1}A,{self.current_l2}A,{self.current_l3}A),"
51
+ f"P({self.power_consumed}W,-{self.power_provided}W),"
52
+ f"W({self.total_consumed}Wh,-{self.total_provided}Wh),"
53
+ f"pf({self.power_factor})"
54
+ f"]"
55
+ )
56
+
57
+ def to_dict(self) -> dict:
58
+ return {
59
+ "u1": self.voltage_l1,
60
+ "u2": self.voltage_l2,
61
+ "u3": self.voltage_l3,
62
+ "i1": self.current_l1,
63
+ "i2": self.current_l2,
64
+ "i3": self.current_l3,
65
+ "w_con": self.power_consumed,
66
+ "w_prov": self.power_provided,
67
+ "total_con": self.total_consumed,
68
+ "total_prov": self.total_provided,
69
+ "power_factor": self.power_factor,
70
+ }
@@ -0,0 +1,38 @@
1
+ """AES-GCM decryption of the DLMS APDU embedded in an M-Bus frame.
2
+
3
+ DLMS Security Suite 0 (as used by the Sagemcom T210-D customer interface)
4
+ encrypts the APDU with AES-128-GCM. The 12-byte nonce is the
5
+ concatenation of the 8-byte system title and the 4-byte invocation
6
+ (frame) counter found in the M-Bus user data.
7
+
8
+ We do not verify the GCM authentication tag – the reference
9
+ implementation at greenMikeEU/SmartMeterEVN does not transmit it in the
10
+ on-wire layout that the T210-D exposes to the customer interface, and
11
+ the parsed DLMS APDU carries its own structural integrity check
12
+ (``pduToXml`` rejects malformed input).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from Cryptodome.Cipher import AES
18
+
19
+ _KEY_LENGTH = 16
20
+ _NONCE_LENGTH = 12
21
+
22
+
23
+ class DecryptionError(ValueError):
24
+ """Raised when AES-GCM decryption cannot proceed."""
25
+
26
+
27
+ def aes_gcm_decrypt(ciphertext: bytes, key: bytes, nonce: bytes) -> bytes:
28
+ """Decrypt ``ciphertext`` with AES-128-GCM using ``key`` and ``nonce``."""
29
+ if len(key) != _KEY_LENGTH:
30
+ raise DecryptionError(
31
+ f"key must be {_KEY_LENGTH} bytes, got {len(key)}"
32
+ )
33
+ if len(nonce) != _NONCE_LENGTH:
34
+ raise DecryptionError(
35
+ f"nonce must be {_NONCE_LENGTH} bytes, got {len(nonce)}"
36
+ )
37
+ cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
38
+ return cipher.decrypt(ciphertext)