earn-e-p1 0.1.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.
- earn_e_p1/__init__.py +15 -0
- earn_e_p1/const.py +5 -0
- earn_e_p1/listener.py +210 -0
- earn_e_p1/models.py +17 -0
- earn_e_p1/py.typed +0 -0
- earn_e_p1-0.1.0.dist-info/METADATA +128 -0
- earn_e_p1-0.1.0.dist-info/RECORD +9 -0
- earn_e_p1-0.1.0.dist-info/WHEEL +4 -0
- earn_e_p1-0.1.0.dist-info/licenses/LICENSE +21 -0
earn_e_p1/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Async Python library for communicating with EARN-E P1 energy meters via UDP."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .const import DEFAULT_PORT
|
|
6
|
+
from .listener import EarnEP1Listener, discover, validate
|
|
7
|
+
from .models import EarnEP1Device
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"DEFAULT_PORT",
|
|
11
|
+
"EarnEP1Device",
|
|
12
|
+
"EarnEP1Listener",
|
|
13
|
+
"discover",
|
|
14
|
+
"validate",
|
|
15
|
+
]
|
earn_e_p1/const.py
ADDED
earn_e_p1/listener.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""UDP listener for EARN-E P1 devices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Any, Callable
|
|
9
|
+
|
|
10
|
+
from .const import DEFAULT_PORT
|
|
11
|
+
from .models import EarnEP1Device
|
|
12
|
+
|
|
13
|
+
_LOGGER = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
Callback = Callable[[EarnEP1Device, dict[str, Any]], None]
|
|
16
|
+
|
|
17
|
+
_IDENTIFY_KEYS = {"power_delivered", "serial"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _EarnEP1Protocol(asyncio.DatagramProtocol):
|
|
21
|
+
"""UDP protocol that receives and parses EARN-E P1 packets."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, listener: EarnEP1Listener) -> None:
|
|
24
|
+
self._listener = listener
|
|
25
|
+
|
|
26
|
+
def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
|
|
27
|
+
"""Handle incoming UDP datagram."""
|
|
28
|
+
source_ip = addr[0]
|
|
29
|
+
try:
|
|
30
|
+
payload = json.loads(data)
|
|
31
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
32
|
+
_LOGGER.warning("Failed to decode UDP packet from %s", source_ip)
|
|
33
|
+
return
|
|
34
|
+
|
|
35
|
+
if not isinstance(payload, dict):
|
|
36
|
+
_LOGGER.warning("Non-dict UDP payload from %s", source_ip)
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
if not _IDENTIFY_KEYS.intersection(payload):
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
self._listener._handle_packet(source_ip, payload)
|
|
43
|
+
|
|
44
|
+
def error_received(self, exc: Exception) -> None:
|
|
45
|
+
"""Handle protocol errors."""
|
|
46
|
+
_LOGGER.warning("UDP protocol error: %s", exc)
|
|
47
|
+
|
|
48
|
+
def connection_lost(self, exc: Exception | None) -> None:
|
|
49
|
+
"""Handle connection lost."""
|
|
50
|
+
if exc:
|
|
51
|
+
_LOGGER.warning("UDP connection lost: %s", exc)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class EarnEP1Listener:
|
|
55
|
+
"""UDP listener that demultiplexes EARN-E P1 packets by source IP."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, port: int = DEFAULT_PORT) -> None:
|
|
58
|
+
self._port = port
|
|
59
|
+
self._devices: dict[str, tuple[EarnEP1Device, Callback]] = {}
|
|
60
|
+
self._transport: asyncio.DatagramTransport | None = None
|
|
61
|
+
self._discover_state: dict[str, EarnEP1Device] | None = None
|
|
62
|
+
self._validate_state: (
|
|
63
|
+
tuple[str, EarnEP1Device, asyncio.Future[EarnEP1Device]] | None
|
|
64
|
+
) = None
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def port(self) -> int:
|
|
68
|
+
"""Return the port the listener is bound to."""
|
|
69
|
+
if self._transport is not None:
|
|
70
|
+
sock = self._transport.get_extra_info("socket")
|
|
71
|
+
if sock is not None:
|
|
72
|
+
return sock.getsockname()[1]
|
|
73
|
+
return self._port
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def is_running(self) -> bool:
|
|
77
|
+
"""Return True if the listener is active."""
|
|
78
|
+
return self._transport is not None
|
|
79
|
+
|
|
80
|
+
def register(self, host: str, callback: Callback) -> None:
|
|
81
|
+
"""Register a device by IP address."""
|
|
82
|
+
device = EarnEP1Device(host=host)
|
|
83
|
+
self._devices[host] = (device, callback)
|
|
84
|
+
_LOGGER.debug("Registered device %s", host)
|
|
85
|
+
|
|
86
|
+
def unregister(self, host: str) -> None:
|
|
87
|
+
"""Unregister a device by IP address."""
|
|
88
|
+
self._devices.pop(host, None)
|
|
89
|
+
_LOGGER.debug("Unregistered device %s", host)
|
|
90
|
+
|
|
91
|
+
async def start(self) -> None:
|
|
92
|
+
"""Open UDP socket and start listening."""
|
|
93
|
+
loop = asyncio.get_running_loop()
|
|
94
|
+
transport, _ = await loop.create_datagram_endpoint(
|
|
95
|
+
lambda: _EarnEP1Protocol(self),
|
|
96
|
+
local_addr=("0.0.0.0", self._port),
|
|
97
|
+
allow_broadcast=True,
|
|
98
|
+
)
|
|
99
|
+
self._transport = transport
|
|
100
|
+
_LOGGER.debug("UDP listener started on port %s", self.port)
|
|
101
|
+
|
|
102
|
+
async def stop(self) -> None:
|
|
103
|
+
"""Close the socket and stop listening."""
|
|
104
|
+
if self._transport:
|
|
105
|
+
self._transport.close()
|
|
106
|
+
self._transport = None
|
|
107
|
+
_LOGGER.debug("UDP listener stopped")
|
|
108
|
+
|
|
109
|
+
async def discover(self, timeout: int | float = 10) -> list[EarnEP1Device]:
|
|
110
|
+
"""Discover devices using the active socket.
|
|
111
|
+
|
|
112
|
+
Temporarily accepts packets from all IPs for the timeout duration.
|
|
113
|
+
Normal registered callbacks continue to fire.
|
|
114
|
+
"""
|
|
115
|
+
discovered: dict[str, EarnEP1Device] = {}
|
|
116
|
+
self._discover_state = discovered
|
|
117
|
+
try:
|
|
118
|
+
await asyncio.sleep(timeout)
|
|
119
|
+
finally:
|
|
120
|
+
self._discover_state = None
|
|
121
|
+
return list(discovered.values())
|
|
122
|
+
|
|
123
|
+
async def validate(
|
|
124
|
+
self, host: str, timeout: int | float = 65
|
|
125
|
+
) -> EarnEP1Device | None:
|
|
126
|
+
"""Validate a host using the active socket.
|
|
127
|
+
|
|
128
|
+
Temporarily accepts packets from the specified host.
|
|
129
|
+
Normal registered callbacks continue to fire.
|
|
130
|
+
"""
|
|
131
|
+
found: asyncio.Future[EarnEP1Device] = (
|
|
132
|
+
asyncio.get_running_loop().create_future()
|
|
133
|
+
)
|
|
134
|
+
device = EarnEP1Device(host=host)
|
|
135
|
+
self._validate_state = (host, device, found)
|
|
136
|
+
try:
|
|
137
|
+
async with asyncio.timeout(timeout):
|
|
138
|
+
return await found
|
|
139
|
+
except TimeoutError:
|
|
140
|
+
return None
|
|
141
|
+
finally:
|
|
142
|
+
self._validate_state = None
|
|
143
|
+
|
|
144
|
+
def _handle_packet(self, source_ip: str, payload: dict[str, Any]) -> None:
|
|
145
|
+
"""Dispatch a parsed packet to registered devices and discover/validate."""
|
|
146
|
+
# Normal registered device handling
|
|
147
|
+
entry = self._devices.get(source_ip)
|
|
148
|
+
if entry is not None:
|
|
149
|
+
device, callback = entry
|
|
150
|
+
_update_device(device, payload)
|
|
151
|
+
callback(device, payload)
|
|
152
|
+
|
|
153
|
+
# Instance discover — accept from any IP
|
|
154
|
+
if self._discover_state is not None:
|
|
155
|
+
if source_ip not in self._discover_state:
|
|
156
|
+
self._discover_state[source_ip] = EarnEP1Device(host=source_ip)
|
|
157
|
+
_update_device(self._discover_state[source_ip], payload)
|
|
158
|
+
|
|
159
|
+
# Instance validate — accept from specific host
|
|
160
|
+
if self._validate_state is not None:
|
|
161
|
+
v_host, v_device, v_future = self._validate_state
|
|
162
|
+
if source_ip == v_host and not v_future.done():
|
|
163
|
+
_update_device(v_device, payload)
|
|
164
|
+
v_future.set_result(v_device)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _update_device(device: EarnEP1Device, payload: dict[str, Any]) -> None:
|
|
168
|
+
"""Update device state from a parsed packet."""
|
|
169
|
+
if "serial" in payload and device.serial is None:
|
|
170
|
+
device.serial = payload["serial"]
|
|
171
|
+
if "model" in payload:
|
|
172
|
+
device.model = payload["model"]
|
|
173
|
+
if "swVersion" in payload:
|
|
174
|
+
device.sw_version = str(payload["swVersion"])
|
|
175
|
+
device.data.update(payload)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def discover(
|
|
179
|
+
timeout: int | float = 10,
|
|
180
|
+
port: int = DEFAULT_PORT,
|
|
181
|
+
) -> list[EarnEP1Device]:
|
|
182
|
+
"""Listen for EARN-E devices on the network.
|
|
183
|
+
|
|
184
|
+
Opens a temporary UDP socket, collects unique devices (by source IP)
|
|
185
|
+
for `timeout` seconds. Raises OSError if the port can't be bound.
|
|
186
|
+
"""
|
|
187
|
+
listener = EarnEP1Listener(port=port)
|
|
188
|
+
await listener.start()
|
|
189
|
+
try:
|
|
190
|
+
return await listener.discover(timeout=timeout)
|
|
191
|
+
finally:
|
|
192
|
+
await listener.stop()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
async def validate(
|
|
196
|
+
host: str,
|
|
197
|
+
timeout: int | float = 65,
|
|
198
|
+
port: int = DEFAULT_PORT,
|
|
199
|
+
) -> EarnEP1Device | None:
|
|
200
|
+
"""Validate that a specific host is an EARN-E device.
|
|
201
|
+
|
|
202
|
+
Returns as soon as the first valid packet arrives from the target host,
|
|
203
|
+
or None on timeout. Raises OSError if the port can't be bound.
|
|
204
|
+
"""
|
|
205
|
+
listener = EarnEP1Listener(port=port)
|
|
206
|
+
await listener.start()
|
|
207
|
+
try:
|
|
208
|
+
return await listener.validate(host=host, timeout=timeout)
|
|
209
|
+
finally:
|
|
210
|
+
await listener.stop()
|
earn_e_p1/models.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Data models for EARN-E P1 devices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class EarnEP1Device:
|
|
11
|
+
"""Represents an EARN-E P1 meter's accumulated state."""
|
|
12
|
+
|
|
13
|
+
host: str
|
|
14
|
+
serial: str | None = None
|
|
15
|
+
model: str | None = None
|
|
16
|
+
sw_version: str | None = None
|
|
17
|
+
data: dict[str, Any] = field(default_factory=dict)
|
earn_e_p1/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: earn-e-p1
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Async Python library for communicating with EARN-E P1 energy meters via UDP
|
|
5
|
+
Project-URL: Homepage, https://github.com/Miggets7/earn-e-p1
|
|
6
|
+
Project-URL: Repository, https://github.com/Miggets7/earn-e-p1
|
|
7
|
+
Project-URL: Issues, https://github.com/Miggets7/earn-e-p1/issues
|
|
8
|
+
Author-email: Michael Rademaker <michael@appbriek.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: earn-e,energy,home-assistant,p1,smart-meter,udp
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Home Automation
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# earn-e-p1
|
|
24
|
+
|
|
25
|
+
Async Python library for communicating with [EARN-E](https://earn-e.com) P1 energy meters via UDP.
|
|
26
|
+
|
|
27
|
+
The EARN-E P1 meter reads a smart meter's P1 port and broadcasts real-time energy data via UDP on the local network. This library listens for those broadcasts and provides parsed device data.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install earn-e-p1
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
### Persistent listener
|
|
38
|
+
|
|
39
|
+
For long-running applications (e.g., Home Assistant integrations) that need continuous updates:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import asyncio
|
|
43
|
+
from earn_e_p1 import EarnEP1Listener, EarnEP1Device
|
|
44
|
+
|
|
45
|
+
def on_update(device: EarnEP1Device, raw: dict) -> None:
|
|
46
|
+
print(f"Power: {device.data.get('power_delivered')} kW")
|
|
47
|
+
print(f"Serial: {device.serial}")
|
|
48
|
+
|
|
49
|
+
async def main() -> None:
|
|
50
|
+
listener = EarnEP1Listener()
|
|
51
|
+
listener.register("192.168.1.100", callback=on_update)
|
|
52
|
+
await listener.start()
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
await asyncio.sleep(3600) # listen for 1 hour
|
|
56
|
+
finally:
|
|
57
|
+
await listener.stop()
|
|
58
|
+
|
|
59
|
+
asyncio.run(main())
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The listener supports multiple devices — call `register()` for each device IP. Packets are demultiplexed by source IP and each device maintains its own merged state.
|
|
63
|
+
|
|
64
|
+
### Discover devices
|
|
65
|
+
|
|
66
|
+
Find EARN-E devices on the network:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from earn_e_p1 import discover
|
|
70
|
+
|
|
71
|
+
devices = await discover(timeout=10)
|
|
72
|
+
for device in devices:
|
|
73
|
+
print(f"Found {device.host} (serial: {device.serial})")
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Validate a specific host
|
|
77
|
+
|
|
78
|
+
Check if a specific IP is an EARN-E device:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from earn_e_p1 import validate
|
|
82
|
+
|
|
83
|
+
device = await validate("192.168.1.100", timeout=10)
|
|
84
|
+
if device:
|
|
85
|
+
print(f"Confirmed: {device.serial}")
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Discover/validate while a listener is running
|
|
89
|
+
|
|
90
|
+
If a listener is already active, use the instance methods to avoid port conflicts:
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
# Discover using the active socket
|
|
94
|
+
devices = await listener.discover(timeout=10)
|
|
95
|
+
|
|
96
|
+
# Validate using the active socket
|
|
97
|
+
device = await listener.validate("192.168.1.100", timeout=10)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Data Model
|
|
101
|
+
|
|
102
|
+
The callback receives two arguments:
|
|
103
|
+
|
|
104
|
+
- `device` (`EarnEP1Device`) — accumulated device state with merged data from all packets
|
|
105
|
+
- `raw` (`dict`) — the raw packet as received
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
@dataclass
|
|
109
|
+
class EarnEP1Device:
|
|
110
|
+
host: str # Device IP address
|
|
111
|
+
serial: str | None = None # Serial number (set once from first full telegram)
|
|
112
|
+
model: str | None = None # Device model
|
|
113
|
+
sw_version: str | None = None # Firmware version
|
|
114
|
+
data: dict[str, Any] = field(...) # Merged sensor data from all packets
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The device sends two types of UDP broadcasts:
|
|
118
|
+
|
|
119
|
+
| Type | Keys | Frequency |
|
|
120
|
+
|------|------|-----------|
|
|
121
|
+
| Realtime | `power_delivered`, `power_returned`, `voltage_l1`, `current_l1` | ~1s |
|
|
122
|
+
| Full telegram | `energy_delivered_tariff1/2`, `energy_returned_tariff1/2`, `gas_delivered`, `wifiRSSI`, `serial`, `model`, `swVersion` | ~10s |
|
|
123
|
+
|
|
124
|
+
The library merges all packets into `device.data`, so it always contains the latest value for every key.
|
|
125
|
+
|
|
126
|
+
## License
|
|
127
|
+
|
|
128
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
earn_e_p1/__init__.py,sha256=J_mPPSfZkys1BUuwKm1PcsKtKznUFhviqk1vZsnJglo,355
|
|
2
|
+
earn_e_p1/const.py,sha256=nGATK4-uDm6kdQYS36Ni4og7t4CGYsQwyBIx7WjNisM,101
|
|
3
|
+
earn_e_p1/listener.py,sha256=iz8qkA7tc7yR7L2QEsNqm2QBwGKGFL6RDMzdZf0WPvE,7261
|
|
4
|
+
earn_e_p1/models.py,sha256=zN6MRWw4Y9yF5wer3poDlVaVplmWREhLSlb32HzO-4o,400
|
|
5
|
+
earn_e_p1/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
earn_e_p1-0.1.0.dist-info/METADATA,sha256=lowGLnZ7y4fYiPyFkIzhPAuGdSOBrdVGc08Wi8_kut4,3915
|
|
7
|
+
earn_e_p1-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
8
|
+
earn_e_p1-0.1.0.dist-info/licenses/LICENSE,sha256=fuk-O472QtfyLH23C75lvdDy5woqWlXV6t8FAPXLiOM,1074
|
|
9
|
+
earn_e_p1-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michael Rademaker
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|