pseg-nj-mymeter 0.2.0__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.
- pseg_nj_mymeter-0.2.0/LICENSE +21 -0
- pseg_nj_mymeter-0.2.0/PKG-INFO +54 -0
- pseg_nj_mymeter-0.2.0/README.md +33 -0
- pseg_nj_mymeter-0.2.0/pyproject.toml +30 -0
- pseg_nj_mymeter-0.2.0/setup.cfg +4 -0
- pseg_nj_mymeter-0.2.0/src/pseg_mymeter/__init__.py +3 -0
- pseg_nj_mymeter-0.2.0/src/pseg_mymeter/client.py +197 -0
- pseg_nj_mymeter-0.2.0/src/pseg_mymeter/data.py +114 -0
- pseg_nj_mymeter-0.2.0/src/pseg_mymeter/exceptions.py +30 -0
- pseg_nj_mymeter-0.2.0/src/pseg_mymeter/py.typed +0 -0
- pseg_nj_mymeter-0.2.0/src/pseg_nj_mymeter.egg-info/PKG-INFO +54 -0
- pseg_nj_mymeter-0.2.0/src/pseg_nj_mymeter.egg-info/SOURCES.txt +13 -0
- pseg_nj_mymeter-0.2.0/src/pseg_nj_mymeter.egg-info/dependency_links.txt +1 -0
- pseg_nj_mymeter-0.2.0/src/pseg_nj_mymeter.egg-info/requires.txt +4 -0
- pseg_nj_mymeter-0.2.0/src/pseg_nj_mymeter.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 brylee123
|
|
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.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pseg-nj-mymeter
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Asynchronous PSE&G NJ MyMeter export client and electricity data models
|
|
5
|
+
Author: brylee123
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: pseg,mymeter,home-assistant,electricity,energy
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Framework :: AsyncIO
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.13
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: aiohttp<4,>=3.12
|
|
19
|
+
Requires-Dist: tzdata>=2026.1; platform_system == "Windows"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# PSE&G NJ MyMeter client
|
|
23
|
+
|
|
24
|
+
An experimental, unofficial client for PSE&G New Jersey's MyMeter portal.
|
|
25
|
+
Author: **brylee123**. License: **MIT**. Requires Python 3.13 or newer.
|
|
26
|
+
This project is not affiliated with or endorsed by PSE&G.
|
|
27
|
+
|
|
28
|
+
Install with `python -m pip install pseg-nj-mymeter`.
|
|
29
|
+
|
|
30
|
+
An independent asynchronous Python library. It has no Home Assistant imports.
|
|
31
|
+
It accepts an injected `aiohttp.ClientSession`, reads the current export form,
|
|
32
|
+
maps displayed meters to internal IDs, and downloads Hourly consumption CSV.
|
|
33
|
+
The data module validates exports and constructs hourly cumulative statistics.
|
|
34
|
+
It supports an existing user session; password login and MFA are not implemented.
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from aiohttp import ClientSession, CookieJar
|
|
38
|
+
from pseg_mymeter.client import PsegClient
|
|
39
|
+
|
|
40
|
+
async with ClientSession(cookie_jar=CookieJar()) as session:
|
|
41
|
+
client = PsegClient(session, cookie_header, meter_number)
|
|
42
|
+
await client.async_validate_session()
|
|
43
|
+
csv_text = await client.async_usage()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Build locally with `python -m build library` from the repository root.
|
|
47
|
+
Use `python -m pip install -e library` for development. A public source repository,
|
|
48
|
+
issue tracker, release tags and automated publishing are still prerequisites
|
|
49
|
+
before this library is ready to become a Home Assistant core dependency.
|
|
50
|
+
|
|
51
|
+
The current custom integration bundles an exact copy under
|
|
52
|
+
`_vendor/pseg_mymeter`; `scripts/sync_vendor.py --check` verifies it against this
|
|
53
|
+
canonical source. The bundle is a temporary custom-integration accommodation,
|
|
54
|
+
not the final core dependency architecture.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# PSE&G NJ MyMeter client
|
|
2
|
+
|
|
3
|
+
An experimental, unofficial client for PSE&G New Jersey's MyMeter portal.
|
|
4
|
+
Author: **brylee123**. License: **MIT**. Requires Python 3.13 or newer.
|
|
5
|
+
This project is not affiliated with or endorsed by PSE&G.
|
|
6
|
+
|
|
7
|
+
Install with `python -m pip install pseg-nj-mymeter`.
|
|
8
|
+
|
|
9
|
+
An independent asynchronous Python library. It has no Home Assistant imports.
|
|
10
|
+
It accepts an injected `aiohttp.ClientSession`, reads the current export form,
|
|
11
|
+
maps displayed meters to internal IDs, and downloads Hourly consumption CSV.
|
|
12
|
+
The data module validates exports and constructs hourly cumulative statistics.
|
|
13
|
+
It supports an existing user session; password login and MFA are not implemented.
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from aiohttp import ClientSession, CookieJar
|
|
17
|
+
from pseg_mymeter.client import PsegClient
|
|
18
|
+
|
|
19
|
+
async with ClientSession(cookie_jar=CookieJar()) as session:
|
|
20
|
+
client = PsegClient(session, cookie_header, meter_number)
|
|
21
|
+
await client.async_validate_session()
|
|
22
|
+
csv_text = await client.async_usage()
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Build locally with `python -m build library` from the repository root.
|
|
26
|
+
Use `python -m pip install -e library` for development. A public source repository,
|
|
27
|
+
issue tracker, release tags and automated publishing are still prerequisites
|
|
28
|
+
before this library is ready to become a Home Assistant core dependency.
|
|
29
|
+
|
|
30
|
+
The current custom integration bundles an exact copy under
|
|
31
|
+
`_vendor/pseg_mymeter`; `scripts/sync_vendor.py --check` verifies it against this
|
|
32
|
+
canonical source. The bundle is a temporary custom-integration accommodation,
|
|
33
|
+
not the final core dependency architecture.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pseg-nj-mymeter"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Asynchronous PSE&G NJ MyMeter export client and electricity data models"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.13"
|
|
11
|
+
authors = [{name = "brylee123"}]
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
keywords = ["pseg", "mymeter", "home-assistant", "electricity", "energy"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Framework :: AsyncIO",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["aiohttp>=3.12,<4", "tzdata>=2026.1; platform_system == 'Windows'"]
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["src"]
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.package-data]
|
|
30
|
+
pseg_mymeter = ["py.typed"]
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Session-only MyMeter export client. Never logs cookies or response bodies."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from datetime import date, datetime, timedelta
|
|
6
|
+
from html.parser import HTMLParser
|
|
7
|
+
from http.cookies import CookieError, SimpleCookie
|
|
8
|
+
from typing import Any
|
|
9
|
+
from zoneinfo import ZoneInfo
|
|
10
|
+
|
|
11
|
+
from aiohttp import ClientError, ClientSession, ClientTimeout
|
|
12
|
+
from yarl import URL
|
|
13
|
+
|
|
14
|
+
from .data import meter_id
|
|
15
|
+
from .exceptions import CannotConnect, InvalidResponse, MeterNotFound, SessionExpired
|
|
16
|
+
|
|
17
|
+
BASE = "https://mysmartenergy.nj.pseg.com"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ExportForm(HTMLParser):
|
|
21
|
+
"""Extract successful input/select fields from the recorded export form."""
|
|
22
|
+
|
|
23
|
+
def __init__(self) -> None:
|
|
24
|
+
"""Initialize a form-only parser."""
|
|
25
|
+
super().__init__(convert_charrefs=True)
|
|
26
|
+
self.active = False
|
|
27
|
+
self.fields: list[tuple[str, str]] = []
|
|
28
|
+
self.select: str | None = None
|
|
29
|
+
self.options: list[tuple[str, bool]] = []
|
|
30
|
+
self.label: str | None = None
|
|
31
|
+
self.labels: dict[str, str] = {}
|
|
32
|
+
|
|
33
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
34
|
+
"""Collect successful form controls and meter labels."""
|
|
35
|
+
a = dict(attrs)
|
|
36
|
+
if tag == "form":
|
|
37
|
+
self.active = a.get("id") == "downloadOptions"
|
|
38
|
+
if not self.active:
|
|
39
|
+
return
|
|
40
|
+
if tag == "input" and a.get("name") and "disabled" not in a:
|
|
41
|
+
kind = a.get("type", "text")
|
|
42
|
+
if kind in ("submit", "button", "file"):
|
|
43
|
+
return
|
|
44
|
+
if kind in ("checkbox", "radio") and "checked" not in a:
|
|
45
|
+
return
|
|
46
|
+
self.fields.append((a["name"], a.get("value") or ""))
|
|
47
|
+
elif tag == "select" and a.get("name"):
|
|
48
|
+
self.select, self.options = a["name"], []
|
|
49
|
+
elif tag == "option" and self.select:
|
|
50
|
+
self.options.append((a.get("value") or "", "selected" in a))
|
|
51
|
+
elif tag == "label" and a.get("for"):
|
|
52
|
+
self.label = a["for"]
|
|
53
|
+
self.labels[self.label] = ""
|
|
54
|
+
|
|
55
|
+
def handle_data(self, data: str) -> None:
|
|
56
|
+
"""Retain label text to map displayed meters to internal IDs."""
|
|
57
|
+
if self.label:
|
|
58
|
+
self.labels[self.label] += data
|
|
59
|
+
|
|
60
|
+
def handle_endtag(self, tag: str) -> None:
|
|
61
|
+
"""Finish select controls and labels."""
|
|
62
|
+
if tag == "label":
|
|
63
|
+
self.label = None
|
|
64
|
+
elif tag == "select" and self.select:
|
|
65
|
+
selected = next(
|
|
66
|
+
(x for x in self.options if x[1]),
|
|
67
|
+
self.options[0] if self.options else None,
|
|
68
|
+
)
|
|
69
|
+
if selected:
|
|
70
|
+
self.fields.append((self.select, selected[0]))
|
|
71
|
+
self.select = None
|
|
72
|
+
elif tag == "form":
|
|
73
|
+
self.active = False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def download_fields(
|
|
77
|
+
payload: dict[str, Any], meter: str, start: date, end: date
|
|
78
|
+
) -> list[tuple[str, str]]:
|
|
79
|
+
"""Use current server selectors/token; override only export-specific fields."""
|
|
80
|
+
parser = ExportForm()
|
|
81
|
+
for item in payload.get("AjaxResults", []):
|
|
82
|
+
if not isinstance(item, dict):
|
|
83
|
+
raise InvalidResponse
|
|
84
|
+
if (
|
|
85
|
+
isinstance(item.get("Value"), str)
|
|
86
|
+
and 'id="downloadOptions"' in item["Value"]
|
|
87
|
+
):
|
|
88
|
+
parser.feed(item["Value"])
|
|
89
|
+
fields = parser.fields
|
|
90
|
+
if not any(k == "__RequestVerificationToken" and v for k, v in fields):
|
|
91
|
+
raise SessionExpired("Export form unavailable; reconnect your session")
|
|
92
|
+
meter_indices = []
|
|
93
|
+
for key, value in fields:
|
|
94
|
+
match = re.fullmatch(r"Meters\[(\d+)\]\.Value", key)
|
|
95
|
+
if match:
|
|
96
|
+
label = parser.labels.get(f"Meters_{match[1]}__Selected", "")
|
|
97
|
+
displayed = re.search(r"Meter\s*#\s*([0-9]+)", label, re.IGNORECASE)
|
|
98
|
+
if displayed and displayed[1] == meter_id(meter):
|
|
99
|
+
meter_indices.append(match[1])
|
|
100
|
+
if len(meter_indices) != 1:
|
|
101
|
+
raise MeterNotFound
|
|
102
|
+
updates = {
|
|
103
|
+
"FileFormat": "download-usage-csv",
|
|
104
|
+
"SelectedFormat": "2",
|
|
105
|
+
"SelectedServiceType": "1",
|
|
106
|
+
"SelectedInterval": "5",
|
|
107
|
+
"SelectedUsageType": "1",
|
|
108
|
+
"Start": start.isoformat(),
|
|
109
|
+
"End": end.isoformat(),
|
|
110
|
+
}
|
|
111
|
+
result = [
|
|
112
|
+
(k, v)
|
|
113
|
+
for k, v in fields
|
|
114
|
+
if k not in updates and not re.fullmatch(r"Meters\[\d+\]\.Selected", k)
|
|
115
|
+
]
|
|
116
|
+
result.extend(updates.items())
|
|
117
|
+
result.append((f"Meters[{meter_indices[0]}].Selected", "true"))
|
|
118
|
+
return result
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class PsegClient:
|
|
122
|
+
"""An asynchronous, session-injected client without Home Assistant imports."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, session: ClientSession, cookie: str, meter: str) -> None:
|
|
125
|
+
"""Initialize an isolated cookie jar with an existing session."""
|
|
126
|
+
if "\n" in cookie or "\r" in cookie:
|
|
127
|
+
raise SessionExpired
|
|
128
|
+
parsed = SimpleCookie()
|
|
129
|
+
try:
|
|
130
|
+
parsed.load(cookie)
|
|
131
|
+
except CookieError:
|
|
132
|
+
raise SessionExpired from None
|
|
133
|
+
if not parsed:
|
|
134
|
+
raise SessionExpired
|
|
135
|
+
self.session, self.meter = session, meter
|
|
136
|
+
self.session.cookie_jar.update_cookies(parsed, response_url=URL(BASE))
|
|
137
|
+
|
|
138
|
+
async def _async_request(
|
|
139
|
+
self, method: str, path: str, *, data: list[tuple[str, str]] | None = None
|
|
140
|
+
) -> str:
|
|
141
|
+
"""Read a response without redirects or leaking server error text."""
|
|
142
|
+
try:
|
|
143
|
+
async with self.session.request(
|
|
144
|
+
method,
|
|
145
|
+
BASE + path,
|
|
146
|
+
headers={
|
|
147
|
+
"Referer": BASE + "/Dashboard",
|
|
148
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
149
|
+
},
|
|
150
|
+
allow_redirects=False,
|
|
151
|
+
timeout=ClientTimeout(total=90),
|
|
152
|
+
data=data,
|
|
153
|
+
) as response:
|
|
154
|
+
if response.status in (301, 302, 303, 307, 308, 401, 403):
|
|
155
|
+
raise SessionExpired
|
|
156
|
+
if response.status == 429 or response.status >= 500:
|
|
157
|
+
raise CannotConnect
|
|
158
|
+
if response.status != 200:
|
|
159
|
+
raise InvalidResponse
|
|
160
|
+
if "text/html" in response.headers.get("Content-Type", "").lower():
|
|
161
|
+
raise SessionExpired
|
|
162
|
+
body = await response.text()
|
|
163
|
+
if len(body) > 25_000_000:
|
|
164
|
+
raise InvalidResponse
|
|
165
|
+
return body
|
|
166
|
+
except (ClientError, TimeoutError):
|
|
167
|
+
raise CannotConnect from None
|
|
168
|
+
|
|
169
|
+
async def _async_form(self) -> dict[str, Any]:
|
|
170
|
+
"""Retrieve fresh form controls and verification token."""
|
|
171
|
+
text = await self._async_request("GET", "/Usage/InitializeDownloadSettings")
|
|
172
|
+
try:
|
|
173
|
+
payload = json.loads(text)
|
|
174
|
+
except (ValueError, TypeError):
|
|
175
|
+
raise InvalidResponse from None
|
|
176
|
+
if not isinstance(payload, dict) or not isinstance(
|
|
177
|
+
payload.get("AjaxResults"), list
|
|
178
|
+
):
|
|
179
|
+
raise InvalidResponse
|
|
180
|
+
return payload
|
|
181
|
+
|
|
182
|
+
async def async_validate_session(self) -> None:
|
|
183
|
+
"""Validate authentication and meter membership without downloading."""
|
|
184
|
+
today = datetime.now(ZoneInfo("America/New_York")).date()
|
|
185
|
+
download_fields(await self._async_form(), self.meter, today, today)
|
|
186
|
+
|
|
187
|
+
async def async_usage(self) -> str:
|
|
188
|
+
"""Download Hourly electricity for the previous seven days."""
|
|
189
|
+
end = datetime.now(ZoneInfo("America/New_York")).date() - timedelta(days=1)
|
|
190
|
+
fields = download_fields(
|
|
191
|
+
await self._async_form(), self.meter, end - timedelta(days=6), end
|
|
192
|
+
)
|
|
193
|
+
return await self._async_request("POST", "/Usage/Download", data=fields)
|
|
194
|
+
|
|
195
|
+
async def async_close(self) -> None:
|
|
196
|
+
"""Close the caller-owned isolated session on teardown."""
|
|
197
|
+
await self.session.close()
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Parse hourly MyMeter exports without depending on Home Assistant."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import re
|
|
5
|
+
from datetime import UTC, datetime, timedelta
|
|
6
|
+
from decimal import Decimal, InvalidOperation
|
|
7
|
+
from io import StringIO
|
|
8
|
+
from typing import TypedDict
|
|
9
|
+
from zoneinfo import ZoneInfo
|
|
10
|
+
|
|
11
|
+
from .exceptions import InvalidUsage
|
|
12
|
+
|
|
13
|
+
type HourLedger = dict[str, str]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ImportReport(TypedDict):
|
|
17
|
+
"""Aggregate import counts without personal data."""
|
|
18
|
+
|
|
19
|
+
rows: int
|
|
20
|
+
other_meter_rows: int
|
|
21
|
+
dst_rows_skipped: int
|
|
22
|
+
hours: int
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def meter_id(value: str) -> str:
|
|
26
|
+
"""Normalize a displayed meter number, preserving leading zeroes."""
|
|
27
|
+
return re.sub(r"[^0-9]", "", value)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_csv(text: str, meter: str) -> tuple[HourLedger, ImportReport]:
|
|
31
|
+
"""Parse Hourly exports; reject sub-hourly, daily and billing data."""
|
|
32
|
+
reader = csv.DictReader(StringIO(text.lstrip("\ufeff")))
|
|
33
|
+
if not reader.fieldnames or not {"Start", "kWh"} <= set(reader.fieldnames):
|
|
34
|
+
raise InvalidUsage("invalid_columns")
|
|
35
|
+
if len(reader.fieldnames) != len(set(reader.fieldnames)):
|
|
36
|
+
raise InvalidUsage("invalid_columns")
|
|
37
|
+
expected_meter = meter_id(meter)
|
|
38
|
+
if not expected_meter:
|
|
39
|
+
raise InvalidUsage("invalid_meter")
|
|
40
|
+
zone = ZoneInfo("America/New_York")
|
|
41
|
+
hours: HourLedger = {}
|
|
42
|
+
seen: set[datetime] = set()
|
|
43
|
+
report: ImportReport = {
|
|
44
|
+
"rows": 0,
|
|
45
|
+
"other_meter_rows": 0,
|
|
46
|
+
"dst_rows_skipped": 0,
|
|
47
|
+
"hours": 0,
|
|
48
|
+
}
|
|
49
|
+
for row in reader:
|
|
50
|
+
report["rows"] += 1
|
|
51
|
+
if None in row or any(value is None for value in row.values()):
|
|
52
|
+
raise InvalidUsage("invalid_row")
|
|
53
|
+
if "Meter" in row and meter_id(row["Meter"]) != expected_meter:
|
|
54
|
+
report["other_meter_rows"] += 1
|
|
55
|
+
continue
|
|
56
|
+
try:
|
|
57
|
+
local = datetime.strptime(row["Start"].strip(), "%m/%d/%Y %I:%M:%S %p")
|
|
58
|
+
value = Decimal(row["kWh"].replace(",", "").strip())
|
|
59
|
+
except (ValueError, InvalidOperation) as err:
|
|
60
|
+
raise InvalidUsage("invalid_row") from err
|
|
61
|
+
if not value.is_finite() or not 0 <= value <= Decimal("1000000000"):
|
|
62
|
+
raise InvalidUsage("invalid_value")
|
|
63
|
+
if local.second or local.minute:
|
|
64
|
+
raise InvalidUsage("hourly_required")
|
|
65
|
+
if local in seen:
|
|
66
|
+
raise InvalidUsage("duplicate_time")
|
|
67
|
+
seen.add(local)
|
|
68
|
+
candidates: set[datetime] = set()
|
|
69
|
+
for fold in (0, 1):
|
|
70
|
+
candidate = local.replace(tzinfo=zone, fold=fold).astimezone(UTC)
|
|
71
|
+
if candidate.astimezone(zone).replace(tzinfo=None) == local:
|
|
72
|
+
candidates.add(candidate)
|
|
73
|
+
if len(candidates) != 1:
|
|
74
|
+
report["dst_rows_skipped"] += 1
|
|
75
|
+
continue
|
|
76
|
+
hours[candidates.pop().isoformat()] = str(value)
|
|
77
|
+
starts = sorted(datetime.fromisoformat(key) for key in hours)
|
|
78
|
+
if not starts:
|
|
79
|
+
raise InvalidUsage("no_hours")
|
|
80
|
+
# Headers alone do not distinguish daily/monthly exports. Require an hourly
|
|
81
|
+
# pair to establish resolution while allowing gaps elsewhere in the file.
|
|
82
|
+
if not any(b - a == timedelta(hours=1) for a, b in zip(starts, starts[1:])):
|
|
83
|
+
raise InvalidUsage("hourly_required")
|
|
84
|
+
report["hours"] = len(hours)
|
|
85
|
+
return hours, report
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class HourStatistic(TypedDict, total=False):
|
|
89
|
+
"""Standalone recorder payload before the Home Assistant adapter."""
|
|
90
|
+
|
|
91
|
+
start: datetime
|
|
92
|
+
state: float
|
|
93
|
+
sum: float
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def build_statistics(
|
|
97
|
+
hours: HourLedger, now: datetime | None = None
|
|
98
|
+
) -> list[HourStatistic]:
|
|
99
|
+
"""Build stable sums with baseline markers before contiguous segments."""
|
|
100
|
+
now = now or datetime.now(UTC)
|
|
101
|
+
total = Decimal(0)
|
|
102
|
+
previous: datetime | None = None
|
|
103
|
+
result: list[HourStatistic] = []
|
|
104
|
+
for timestamp in sorted(hours):
|
|
105
|
+
start = datetime.fromisoformat(timestamp)
|
|
106
|
+
if start + timedelta(hours=1) > now:
|
|
107
|
+
continue
|
|
108
|
+
if previous is None or previous + timedelta(hours=1) != start:
|
|
109
|
+
result.append({"start": start - timedelta(hours=1), "sum": float(total)})
|
|
110
|
+
value = Decimal(hours[timestamp])
|
|
111
|
+
total += value
|
|
112
|
+
result.append({"start": start, "state": float(value), "sum": float(total)})
|
|
113
|
+
previous = start
|
|
114
|
+
return result
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Safe client/parser errors that never retain raw input or secrets."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class PsegError(Exception):
|
|
5
|
+
"""Base utility client error."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SessionExpired(PsegError):
|
|
9
|
+
"""The portal requires authentication."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CannotConnect(PsegError):
|
|
13
|
+
"""The portal could not be reached."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InvalidResponse(PsegError):
|
|
17
|
+
"""The portal returned an unsupported response."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MeterNotFound(PsegError):
|
|
21
|
+
"""The requested meter is unavailable."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class InvalidUsage(ValueError):
|
|
25
|
+
"""A controlled translation key describing invalid CSV data."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, translation_key: str) -> None:
|
|
28
|
+
"""Initialize without retaining raw data."""
|
|
29
|
+
super().__init__(translation_key)
|
|
30
|
+
self.translation_key = translation_key
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pseg-nj-mymeter
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Asynchronous PSE&G NJ MyMeter export client and electricity data models
|
|
5
|
+
Author: brylee123
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: pseg,mymeter,home-assistant,electricity,energy
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Framework :: AsyncIO
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.13
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: aiohttp<4,>=3.12
|
|
19
|
+
Requires-Dist: tzdata>=2026.1; platform_system == "Windows"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# PSE&G NJ MyMeter client
|
|
23
|
+
|
|
24
|
+
An experimental, unofficial client for PSE&G New Jersey's MyMeter portal.
|
|
25
|
+
Author: **brylee123**. License: **MIT**. Requires Python 3.13 or newer.
|
|
26
|
+
This project is not affiliated with or endorsed by PSE&G.
|
|
27
|
+
|
|
28
|
+
Install with `python -m pip install pseg-nj-mymeter`.
|
|
29
|
+
|
|
30
|
+
An independent asynchronous Python library. It has no Home Assistant imports.
|
|
31
|
+
It accepts an injected `aiohttp.ClientSession`, reads the current export form,
|
|
32
|
+
maps displayed meters to internal IDs, and downloads Hourly consumption CSV.
|
|
33
|
+
The data module validates exports and constructs hourly cumulative statistics.
|
|
34
|
+
It supports an existing user session; password login and MFA are not implemented.
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from aiohttp import ClientSession, CookieJar
|
|
38
|
+
from pseg_mymeter.client import PsegClient
|
|
39
|
+
|
|
40
|
+
async with ClientSession(cookie_jar=CookieJar()) as session:
|
|
41
|
+
client = PsegClient(session, cookie_header, meter_number)
|
|
42
|
+
await client.async_validate_session()
|
|
43
|
+
csv_text = await client.async_usage()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Build locally with `python -m build library` from the repository root.
|
|
47
|
+
Use `python -m pip install -e library` for development. A public source repository,
|
|
48
|
+
issue tracker, release tags and automated publishing are still prerequisites
|
|
49
|
+
before this library is ready to become a Home Assistant core dependency.
|
|
50
|
+
|
|
51
|
+
The current custom integration bundles an exact copy under
|
|
52
|
+
`_vendor/pseg_mymeter`; `scripts/sync_vendor.py --check` verifies it against this
|
|
53
|
+
canonical source. The bundle is a temporary custom-integration accommodation,
|
|
54
|
+
not the final core dependency architecture.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/pseg_mymeter/__init__.py
|
|
5
|
+
src/pseg_mymeter/client.py
|
|
6
|
+
src/pseg_mymeter/data.py
|
|
7
|
+
src/pseg_mymeter/exceptions.py
|
|
8
|
+
src/pseg_mymeter/py.typed
|
|
9
|
+
src/pseg_nj_mymeter.egg-info/PKG-INFO
|
|
10
|
+
src/pseg_nj_mymeter.egg-info/SOURCES.txt
|
|
11
|
+
src/pseg_nj_mymeter.egg-info/dependency_links.txt
|
|
12
|
+
src/pseg_nj_mymeter.egg-info/requires.txt
|
|
13
|
+
src/pseg_nj_mymeter.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pseg_mymeter
|