opower 0.0.1__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.
opower-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
opower-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.1
2
+ Name: opower
3
+ Version: 0.0.1
4
+ Summary: A Python library for getting historical and forecasted usage/cost from utilities that use opower.com such as PG&E
5
+ Author-email: tronikos <tronikos@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/tronikos/opower
8
+ Project-URL: Bug Tracker, https://github.com/tronikos/opower/issues
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+
13
+ # opower
14
+ A Python library for getting historical and forecasted usage/cost from utilities that use opower.com such as PG&amp;E.
15
+
16
+ To add support for a new utility that uses opower JSON API (you can tell if the energy dashboard of your utility is hosted on opower.com, e.g. pge.opower.com) add a file similar to [pge.py](https://github.com/tronikos/opower/blob/main/src/opower/utilities/pge.py).
17
+
18
+ ## Example
19
+
20
+ See [demo.py](https://github.com/tronikos/opower/blob/main/src/demo.py)
21
+
22
+ ## Development environment
23
+
24
+ ```sh
25
+ python3 -m venv .venv
26
+ source .venv/bin/activate
27
+ # for Windows CMD:
28
+ # .venv\Scripts\activate.bat
29
+ # for Windows PowerShell:
30
+ # .venv\Scripts\Activate.ps1
31
+
32
+ # Install dependencies
33
+ python -m pip install --upgrade pip
34
+ python -m pip install .
35
+
36
+ # Run formatter
37
+ python -m pip install isort black
38
+ isort .
39
+ black .
40
+
41
+ # Run lint
42
+ python -m pip install flake8 ruff
43
+ flake8 .
44
+ ruff .
45
+
46
+ # Run tests
47
+ python -m pip install pytest
48
+ pytest
49
+
50
+ # Run demo
51
+ python src/demo.py --help
52
+ # To output debug logs to a file:
53
+ python src/demo.py --verbose 2> out.txt
54
+
55
+ # Build package
56
+ python -m pip install build
57
+ python -m build
58
+ ```
opower-0.0.1/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # opower
2
+ A Python library for getting historical and forecasted usage/cost from utilities that use opower.com such as PG&amp;E.
3
+
4
+ To add support for a new utility that uses opower JSON API (you can tell if the energy dashboard of your utility is hosted on opower.com, e.g. pge.opower.com) add a file similar to [pge.py](https://github.com/tronikos/opower/blob/main/src/opower/utilities/pge.py).
5
+
6
+ ## Example
7
+
8
+ See [demo.py](https://github.com/tronikos/opower/blob/main/src/demo.py)
9
+
10
+ ## Development environment
11
+
12
+ ```sh
13
+ python3 -m venv .venv
14
+ source .venv/bin/activate
15
+ # for Windows CMD:
16
+ # .venv\Scripts\activate.bat
17
+ # for Windows PowerShell:
18
+ # .venv\Scripts\Activate.ps1
19
+
20
+ # Install dependencies
21
+ python -m pip install --upgrade pip
22
+ python -m pip install .
23
+
24
+ # Run formatter
25
+ python -m pip install isort black
26
+ isort .
27
+ black .
28
+
29
+ # Run lint
30
+ python -m pip install flake8 ruff
31
+ flake8 .
32
+ ruff .
33
+
34
+ # Run tests
35
+ python -m pip install pytest
36
+ pytest
37
+
38
+ # Run demo
39
+ python src/demo.py --help
40
+ # To output debug logs to a file:
41
+ python src/demo.py --verbose 2> out.txt
42
+
43
+ # Build package
44
+ python -m pip install build
45
+ python -m build
46
+ ```
@@ -0,0 +1,78 @@
1
+ [project]
2
+ name = "opower"
3
+ version = "0.0.1"
4
+ license = {text = "Apache-2.0"}
5
+ authors = [
6
+ { name="tronikos", email="tronikos@gmail.com" },
7
+ ]
8
+ description = "A Python library for getting historical and forecasted usage/cost from utilities that use opower.com such as PG&E"
9
+ readme = "README.md"
10
+ requires-python = ">=3.7"
11
+ dependencies = [
12
+ "aiohttp>=3.8",
13
+ "asyncio>=3.4.3",
14
+ ]
15
+
16
+ [project.urls]
17
+ "Homepage" = "https://github.com/tronikos/opower"
18
+ "Bug Tracker" = "https://github.com/tronikos/opower/issues"
19
+
20
+ [build-system]
21
+ requires = ["setuptools"]
22
+ build-backend = "setuptools.build_meta"
23
+
24
+ [tool.black]
25
+ extend-exclude = "_pb2.py|_pb2_grpc.py"
26
+
27
+ [tool.isort]
28
+ profile = "black"
29
+ force_sort_within_sections = true
30
+ combine_as_imports = true
31
+ extend_skip_glob = ["*_pb2.py", "*_pb2_grpc.py"]
32
+
33
+ [tool.ruff]
34
+ target-version = "py311"
35
+ exclude = ["*_pb2.py", "*_pb2_grpc.py", "*.pyi"]
36
+ line-length = 127
37
+
38
+ select = [
39
+ "B007", # Loop control variable {name} not used within loop body
40
+ "B014", # Exception handler with duplicate exception
41
+ "C", # complexity
42
+ "D", # docstrings
43
+ "E", # pycodestyle
44
+ "F", # pyflakes/autoflake
45
+ "ICN001", # import concentions; {name} should be imported as {asname}
46
+ "PGH004", # Use specific rule codes when using noqa
47
+ "PLC0414", # Useless import alias. Import alias does not rename original package.
48
+ "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
49
+ "SIM117", # Merge with-statements that use the same scope
50
+ "SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
51
+ "SIM201", # Use {left} != {right} instead of not {left} == {right}
52
+ "SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a}
53
+ "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'.
54
+ "SIM401", # Use get from dict with default instead of an if block
55
+ "T20", # flake8-print
56
+ "TRY004", # Prefer TypeError exception for invalid type
57
+ "RUF006", # Store a reference to the return value of asyncio.create_task
58
+ "UP", # pyupgrade
59
+ "W", # pycodestyle
60
+ ]
61
+
62
+ ignore = [
63
+ "D203", # 1 blank line required before class docstring
64
+ "D213", # Multi-line docstring summary should start at the second line
65
+ ]
66
+
67
+ [tool.ruff.flake8-pytest-style]
68
+ fixture-parentheses = false
69
+
70
+ [tool.ruff.pyupgrade]
71
+ keep-runtime-typing = true
72
+
73
+ [tool.ruff.per-file-ignores]
74
+ # Allow for demo script to write to stdout
75
+ "demo.py" = ["T201"]
76
+
77
+ [tool.ruff.mccabe]
78
+ max-complexity = 25
opower-0.0.1/setup.cfg ADDED
@@ -0,0 +1,16 @@
1
+ [flake8]
2
+ exclude = .venv,.git,docs,venv,bin,lib,deps,build,*_pb2.py,*_pb2_grpc.py
3
+ max-complexity = 25
4
+ doctests = True
5
+ ignore =
6
+ E501,
7
+ W503,
8
+ E203,
9
+ D202,
10
+ W504
11
+ noqa-require-code = True
12
+
13
+ [egg_info]
14
+ tag_build =
15
+ tag_date = 0
16
+
@@ -0,0 +1,138 @@
1
+ """Demo usage of Opower library."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ from datetime import datetime, timedelta
6
+ from getpass import getpass
7
+ import logging
8
+
9
+ import aiohttp
10
+
11
+ from opower import AggregateType, Opower, get_supported_utility_subdomains
12
+
13
+
14
+ async def _main():
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument(
17
+ "--utility",
18
+ help="Utility (subdomain of opower.com). Defaults to pge",
19
+ choices=get_supported_utility_subdomains(),
20
+ default="pge",
21
+ )
22
+ parser.add_argument(
23
+ "--username",
24
+ help="Username for logging into the utility's website. "
25
+ "If not provided, you will be asked for it",
26
+ )
27
+ parser.add_argument(
28
+ "--password",
29
+ help="Password for logging into the utility's website. "
30
+ "If not provided, you will be asked for it",
31
+ )
32
+ parser.add_argument(
33
+ "--aggregate_type",
34
+ help="How to aggregate historical data. Defaults to day",
35
+ choices=list(AggregateType),
36
+ default=AggregateType.DAY,
37
+ )
38
+ parser.add_argument(
39
+ "--start_date",
40
+ help="Start datetime for historical data. Defaults to 7 days ago",
41
+ type=lambda s: datetime.fromisoformat(s),
42
+ default=datetime.now() - timedelta(days=7),
43
+ )
44
+ parser.add_argument(
45
+ "--end_date",
46
+ help="end datetime for historical data. Defaults to now",
47
+ type=lambda s: datetime.fromisoformat(s),
48
+ default=datetime.now(),
49
+ )
50
+ parser.add_argument(
51
+ "--usage_only",
52
+ help="If true will output usage only, not cost",
53
+ action="store_true",
54
+ )
55
+ parser.add_argument(
56
+ "-v", "--verbose", help="enable verbose logging", action="store_true"
57
+ )
58
+ args = parser.parse_args()
59
+
60
+ logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
61
+
62
+ username = args.username or input("Username: ")
63
+ password = args.password or getpass("Password: ")
64
+
65
+ async with aiohttp.ClientSession() as session:
66
+ opower = Opower(session, args.utility, username, password)
67
+ await opower.async_login()
68
+ forecasts = await opower.async_get_forecast()
69
+ for forecast in forecasts:
70
+ print("\nData for meter:", forecast.account.meter_type)
71
+ print("\nCurrent bill forecast:", forecast)
72
+ print(
73
+ "\nGetting historical data: aggregate_type=",
74
+ args.aggregate_type,
75
+ "start_date=",
76
+ args.start_date,
77
+ "end_date=",
78
+ args.end_date,
79
+ )
80
+ if args.usage_only:
81
+ usage_data = await opower.async_get_usage_reads(
82
+ forecast.account,
83
+ args.aggregate_type,
84
+ args.start_date,
85
+ args.end_date,
86
+ )
87
+ prev_end = None
88
+ print(
89
+ "start_time\tend_time\tconsumption"
90
+ "\tstart_minus_prev_end\tend_minus_prev_end"
91
+ )
92
+ for usage_read in usage_data:
93
+ start_minus_prev_end = (
94
+ None if prev_end is None else usage_read.start_time - prev_end
95
+ )
96
+ end_minus_prev_end = (
97
+ None if prev_end is None else usage_read.end_time - prev_end
98
+ )
99
+ prev_end = usage_read.end_time
100
+ print(
101
+ f"{usage_read.start_time}"
102
+ f"\t{usage_read.end_time}"
103
+ f"\t{usage_read.consumption}"
104
+ f"\t{start_minus_prev_end}"
105
+ f"\t{end_minus_prev_end}"
106
+ )
107
+ else:
108
+ cost_data = await opower.async_get_cost_reads(
109
+ forecast.account,
110
+ args.aggregate_type,
111
+ args.start_date,
112
+ args.end_date,
113
+ )
114
+ prev_end = None
115
+ print(
116
+ "start_time\tend_time\tconsumption\tprovided_cost"
117
+ "\tstart_minus_prev_end\tend_minus_prev_end"
118
+ )
119
+ for cost_read in cost_data:
120
+ start_minus_prev_end = (
121
+ None if prev_end is None else cost_read.start_time - prev_end
122
+ )
123
+ end_minus_prev_end = (
124
+ None if prev_end is None else cost_read.end_time - prev_end
125
+ )
126
+ prev_end = cost_read.end_time
127
+ print(
128
+ f"{cost_read.start_time}"
129
+ f"\t{cost_read.end_time}"
130
+ f"\t{cost_read.consumption}"
131
+ f"\t{cost_read.provided_cost}"
132
+ f"\t{start_minus_prev_end}"
133
+ f"\t{end_minus_prev_end}"
134
+ )
135
+ print()
136
+
137
+
138
+ asyncio.run(_main())
@@ -0,0 +1,27 @@
1
+ """Library for getting historical and forecasted usage/cost from an utility using opower.com JSON API."""
2
+
3
+ from .opower import (
4
+ Account,
5
+ AggregateType,
6
+ CostRead,
7
+ Forecast,
8
+ MeterType,
9
+ Opower,
10
+ UnitOfMeasure,
11
+ UsageRead,
12
+ get_supported_utility_names,
13
+ get_supported_utility_subdomains,
14
+ )
15
+
16
+ __all__ = [
17
+ "Account",
18
+ "AggregateType",
19
+ "CostRead",
20
+ "Forecast",
21
+ "MeterType",
22
+ "Opower",
23
+ "UnitOfMeasure",
24
+ "UsageRead",
25
+ "get_supported_utility_names",
26
+ "get_supported_utility_subdomains",
27
+ ]
@@ -0,0 +1,395 @@
1
+ """Implementation of opower.com JSON API."""
2
+
3
+ import dataclasses
4
+ from datetime import date, datetime, timedelta
5
+ from enum import Enum
6
+ import json
7
+ import logging
8
+ import re
9
+ from typing import Any
10
+ from urllib.parse import urlencode
11
+
12
+ import aiohttp
13
+ from multidict import CIMultiDict
14
+
15
+ from .utilities import UtilityBase
16
+
17
+ _LOGGER = logging.getLogger(__file__)
18
+
19
+
20
+ class MeterType(Enum):
21
+ """Meter type. Electric or gas."""
22
+
23
+ ELEC = "ELEC"
24
+ GAS = "GAS"
25
+
26
+ def __str__(self):
27
+ """Return the value of the enum."""
28
+ return self.value
29
+
30
+
31
+ class UnitOfMeasure(Enum):
32
+ """Unit of measure for the associated meter type. kWh for electricity or Therm for gas,."""
33
+
34
+ KWH = "KWH"
35
+ THERM = "THERM"
36
+
37
+ def __str__(self):
38
+ """Return the value of the enum."""
39
+ return self.value
40
+
41
+
42
+ class AggregateType(Enum):
43
+ """How to aggregate historical data."""
44
+
45
+ BILL = "bill"
46
+ DAY = "day"
47
+ HOUR = "hour"
48
+
49
+ def __str__(self):
50
+ """Return the value of the enum."""
51
+ return self.value
52
+
53
+
54
+ @dataclasses.dataclass
55
+ class Account:
56
+ """Data about an account."""
57
+
58
+ uuid: str
59
+ utility_account_id: str
60
+ meter_type: MeterType
61
+
62
+
63
+ @dataclasses.dataclass
64
+ class Forecast:
65
+ """Forecast data for an account."""
66
+
67
+ account: Account
68
+ start_date: date
69
+ end_date: date
70
+ current_date: date
71
+ unit_of_measure: UnitOfMeasure
72
+ usage_to_date: float
73
+ cost_to_date: float
74
+ forecasted_usage: float
75
+ forecasted_cost: float
76
+ typical_usage: float
77
+ typical_cost: float
78
+
79
+
80
+ @dataclasses.dataclass
81
+ class CostRead:
82
+ """A read from the meter that has both consumption and cost data."""
83
+
84
+ start_time: datetime
85
+ end_time: datetime
86
+ consumption: float # taken from value field, in KWH or THERM
87
+ provided_cost: float # in $
88
+
89
+
90
+ @dataclasses.dataclass
91
+ class UsageRead:
92
+ """A read from the meter that has consumption data."""
93
+
94
+ start_time: datetime
95
+ end_time: datetime
96
+ consumption: float # taken from consumption.value field, in KWH or THERM
97
+
98
+
99
+ def get_supported_utility_names() -> list[str]:
100
+ """Return a list of names of all supported utilities."""
101
+ return [utility.name() for utility in UtilityBase.subclasses]
102
+
103
+
104
+ def get_supported_utility_subdomains() -> list[str]:
105
+ """Return a list of subdomains of all supported utilities."""
106
+ return [utility.subdomain() for utility in UtilityBase.subclasses]
107
+
108
+
109
+ def _select_utility(name_or_subdomain: str) -> type[UtilityBase]:
110
+ """Return the utility with the given name or subdomain."""
111
+ for utility in UtilityBase.subclasses:
112
+ if name_or_subdomain in [utility.name(), utility.subdomain()]:
113
+ return utility
114
+ raise ValueError(f"Utility {name_or_subdomain} not found")
115
+
116
+
117
+ def _get_form_action_url_and_hidden_inputs(html: str):
118
+ """Return the URL and hidden inputs from the single form in a page."""
119
+ match = re.search(r'action="([^"]*)"', html)
120
+ if not match:
121
+ return None, None
122
+ action_url = match.group(1)
123
+ inputs = {}
124
+ for match in re.finditer(
125
+ r'input\s*type="hidden"\s*name="([^"]*)"\s*value="([^"]*)"', html
126
+ ):
127
+ inputs[match.group(1)] = match.group(2)
128
+ return action_url, inputs
129
+
130
+
131
+ def _strip_time(date_time: datetime):
132
+ return date_time.astimezone().replace(hour=0, minute=0, second=0, microsecond=0)
133
+
134
+
135
+ class Opower:
136
+ """Class that can get historical and forecasted usage/cost from an utility."""
137
+
138
+ def __init__(
139
+ self, session: aiohttp.ClientSession, utility: str, username: str, password: str
140
+ ) -> None:
141
+ """Initialize."""
142
+ self.session = session
143
+ self.session._default_headers = CIMultiDict({"User-Agent": "Mozilla/5.0"})
144
+ self.session._raise_for_status = True
145
+ self.utility: type[UtilityBase] = _select_utility(utility)
146
+ self.username = username
147
+ self.password = password
148
+ self.customer = None
149
+
150
+ async def async_login(self) -> None:
151
+ """Login to the utility website and authorize opower.com for access."""
152
+ url = await self.utility.login(self.session, self.username, self.password)
153
+ await self._async_authorize(url)
154
+
155
+ async def _async_authorize(self, url: str) -> None:
156
+ # Fetch the URL on the utility website to get RelayState and SAMLResponse.
157
+ async with self.session.get(url) as resp:
158
+ result = await resp.text()
159
+ action_url, hidden_inputs = _get_form_action_url_and_hidden_inputs(result)
160
+ assert action_url == "https://sso2.opower.com/sp/ACS.saml2"
161
+ assert set(hidden_inputs.keys()) == {"RelayState", "SAMLResponse"}
162
+
163
+ # Pass them to https://sso2.opower.com/sp/ACS.saml2 to get opentoken.
164
+ async with self.session.post(action_url, data=hidden_inputs) as resp:
165
+ result = await resp.text()
166
+ action_url, hidden_inputs = _get_form_action_url_and_hidden_inputs(result)
167
+ assert set(hidden_inputs.keys()) == {"opentoken"}
168
+
169
+ # Pass it back to the utility website.
170
+ async with self.session.post(action_url, data=hidden_inputs) as resp:
171
+ pass
172
+
173
+ async def async_get_accounts(self) -> list[Account]:
174
+ """Get a list of accounts for the signed in user.
175
+
176
+ Typically one account for electricity and one for gas.
177
+ """
178
+ customer = await self._async_get_customer()
179
+ accounts = []
180
+ for account in customer["utilityAccounts"]:
181
+ accounts.append(
182
+ Account(
183
+ uuid=account["uuid"],
184
+ utility_account_id=account["preferredUtilityAccountId"],
185
+ meter_type=MeterType(account["meterType"]),
186
+ )
187
+ )
188
+ return accounts
189
+
190
+ async def async_get_forecast(self) -> list[Forecast]:
191
+ """Get current and forecasted usage and cost for the current monthly bill.
192
+
193
+ One forecast for each account, typically one for electricity, one for gas.
194
+ """
195
+ customer = await self._async_get_customer()
196
+ customer_uuid = customer["uuid"]
197
+ url = (
198
+ "https://"
199
+ f"{self.utility.subdomain()}"
200
+ ".opower.com/ei/edge/apis/bill-forecast-cws-v1/cws/"
201
+ f"{self.utility.subdomain()}"
202
+ "/customers/"
203
+ f"{customer_uuid}"
204
+ "/combined-forecast"
205
+ )
206
+ _LOGGER.debug("Fetching: %s", url)
207
+ async with self.session.get(url) as resp:
208
+ result = await resp.json()
209
+ _LOGGER.debug("Fetched: %s", json.dumps(result, indent=2))
210
+ forecasts = []
211
+ for forecast in result["accountForecasts"]:
212
+ forecasts.append(
213
+ Forecast(
214
+ account=Account(
215
+ uuid=forecast["accountUuids"][0],
216
+ utility_account_id=str(forecast["preferredUtilityAccountId"]),
217
+ meter_type=MeterType(forecast["meterType"]),
218
+ ),
219
+ start_date=date.fromisoformat(forecast["startDate"]),
220
+ end_date=date.fromisoformat(forecast["endDate"]),
221
+ current_date=date.fromisoformat(forecast["currentDate"]),
222
+ unit_of_measure=UnitOfMeasure(forecast["unitOfMeasure"]),
223
+ usage_to_date=float(forecast["usageToDate"]),
224
+ cost_to_date=float(forecast["costToDate"]),
225
+ forecasted_usage=float(forecast["forecastedUsage"]),
226
+ forecasted_cost=float(forecast["forecastedCost"]),
227
+ typical_usage=float(forecast["typicalUsage"]),
228
+ typical_cost=float(forecast["typicalCost"]),
229
+ )
230
+ )
231
+ return forecasts
232
+
233
+ async def _async_get_customer(self):
234
+ """Get information about the current customer."""
235
+ # Cache the customer data
236
+ if not self.customer:
237
+ async with self.session.get(
238
+ "https://"
239
+ f"{self.utility.subdomain()}"
240
+ ".opower.com/ei/edge/apis/multi-account-v1/cws/"
241
+ f"{self.utility.subdomain()}"
242
+ # Alternative to get multiple accounts:
243
+ # /customers?offset=0&batchSize=100&addressFilter=
244
+ "/customers/current"
245
+ ) as resp:
246
+ self.customer = await resp.json()
247
+ _LOGGER.debug("Fetched: %s", json.dumps(self.customer, indent=2))
248
+ assert self.customer
249
+ return self.customer
250
+
251
+ async def async_get_cost_reads(
252
+ self,
253
+ account: Account,
254
+ aggregate_type: AggregateType,
255
+ start_date: datetime | None = None,
256
+ end_date: datetime | None = None,
257
+ ) -> list[CostRead]:
258
+ """Get cost data for the selected account in the given date range aggregated by bill/day/hour.
259
+
260
+ The resolution for gas is typically 'day' while for electricity it's hour or quarter hour.
261
+ Opower typically keeps historical cost data for 3 years.
262
+ """
263
+ url = (
264
+ "https://"
265
+ f"{self.utility.subdomain()}"
266
+ ".opower.com/ei/edge/apis/DataBrowser-v1/cws/cost/utilityAccount/"
267
+ f"{account.uuid}"
268
+ )
269
+ reads = await self._async_get_dated_data(
270
+ url, aggregate_type, start_date, end_date
271
+ )
272
+ result = []
273
+ for read in reads:
274
+ result.append(
275
+ CostRead(
276
+ start_time=datetime.fromisoformat(read["startTime"]),
277
+ end_time=datetime.fromisoformat(read["endTime"]),
278
+ consumption=read["value"],
279
+ provided_cost=read["providedCost"],
280
+ )
281
+ )
282
+ # Remove last entries with 0 values
283
+ while result:
284
+ last = result.pop()
285
+ if last.provided_cost != 0 or last.consumption != 0:
286
+ result.append(last)
287
+ break
288
+ return result
289
+
290
+ async def async_get_usage_reads(
291
+ self,
292
+ account: Account,
293
+ aggregate_type: AggregateType,
294
+ start_date: datetime | None = None,
295
+ end_date: datetime | None = None,
296
+ ) -> list[UsageRead]:
297
+ """Get usage data for the selected account in the given date range aggregated by bill/day/hour.
298
+
299
+ The resolution for gas is typically 'day' while for electricity it's hour or quarter hour.
300
+ Opower typically keeps historical usage data for a bit over 3 years.
301
+ """
302
+ url = (
303
+ "https://"
304
+ f"{self.utility.subdomain()}"
305
+ ".opower.com/ei/edge/apis/DataBrowser-v1/cws/utilities/"
306
+ f"{self.utility.subdomain()}"
307
+ "/utilityAccounts/"
308
+ f"{account.uuid}"
309
+ "/reads"
310
+ )
311
+ reads = await self._async_get_dated_data(
312
+ url, aggregate_type, start_date, end_date
313
+ )
314
+ result = []
315
+ for read in reads:
316
+ result.append(
317
+ UsageRead(
318
+ start_time=datetime.fromisoformat(read["startTime"]),
319
+ end_time=datetime.fromisoformat(read["endTime"]),
320
+ consumption=read["consumption"]["value"],
321
+ )
322
+ )
323
+ return result
324
+
325
+ async def _async_get_dated_data(
326
+ self,
327
+ url: str,
328
+ aggregate_type: AggregateType,
329
+ start_date: datetime | None = None,
330
+ end_date: datetime | None = None,
331
+ ) -> list[Any]:
332
+ """Wrap _async_fetch by breaking requests for big date ranges to smaller ones to satisfy opower imposed limits."""
333
+ if start_date is None:
334
+ if aggregate_type == AggregateType.BILL:
335
+ return await self._async_fetch(
336
+ url, aggregate_type, start_date, end_date
337
+ )
338
+ raise ValueError("Missing start_date")
339
+
340
+ if end_date is None:
341
+ end_date = datetime.max
342
+ end_date = min(datetime.now(), end_date)
343
+
344
+ start_date = _strip_time(start_date)
345
+ end_date = _strip_time(end_date) + timedelta(days=1)
346
+ assert start_date
347
+ assert end_date
348
+
349
+ max_request_days = None
350
+ if aggregate_type == AggregateType.DAY:
351
+ max_request_days = 363
352
+ elif aggregate_type == AggregateType.HOUR:
353
+ max_request_days = 26
354
+
355
+ # Fetch data in batches in reverse chronological order
356
+ # until we reach start_date or there is no fetched data
357
+ # (non bill data are available up to 3 years ago).
358
+ result: list[Any] = []
359
+ req_end = end_date
360
+ while True:
361
+ req_start = start_date
362
+ if max_request_days:
363
+ req_start = max(start_date, req_end - timedelta(days=max_request_days))
364
+ if req_start >= req_end:
365
+ return result
366
+ reads = await self._async_fetch(url, aggregate_type, req_start, req_end)
367
+ if not reads:
368
+ return result
369
+ result = reads + result
370
+ req_end = req_start - timedelta(days=1)
371
+
372
+ async def _async_fetch(
373
+ self,
374
+ url: str,
375
+ aggregate_type: AggregateType,
376
+ start_date: datetime | None = None,
377
+ end_date: datetime | None = None,
378
+ ) -> list[Any]:
379
+ convert_to_date = not (
380
+ aggregate_type == AggregateType.DAY and "/cws/cost/" in url
381
+ )
382
+ params = {"aggregateType": aggregate_type.value}
383
+ if start_date:
384
+ params["startDate"] = (
385
+ start_date.date() if convert_to_date else start_date
386
+ ).isoformat()
387
+ if end_date:
388
+ params["endDate"] = (
389
+ end_date.date() if convert_to_date else end_date
390
+ ).isoformat()
391
+ _LOGGER.debug("Fetching: %s?%s", url, urlencode(params))
392
+ async with self.session.get(url, params=params) as resp:
393
+ result = await resp.json()
394
+ _LOGGER.debug("Fetched: %s", json.dumps(result, indent=2))
395
+ return result["reads"]
@@ -0,0 +1,16 @@
1
+ """Directory of all supported utility websites that use opower.com API."""
2
+
3
+ from .base import UtilityBase
4
+
5
+ __all__ = ["UtilityBase"]
6
+
7
+ # Import all modules in the current directory.
8
+ from importlib import import_module
9
+ from pathlib import Path
10
+
11
+ for f in Path(__file__).parent.glob("*.py"):
12
+ module_name = f.stem
13
+ if (not module_name.startswith("_")) and (module_name not in globals()):
14
+ import_module(f".{module_name}", __package__)
15
+ del f, module_name
16
+ del import_module, Path
@@ -0,0 +1,35 @@
1
+ """Base class that each utility needs to extend."""
2
+
3
+
4
+ import aiohttp
5
+
6
+
7
+ class UtilityBase:
8
+ """Base class that each utility needs to extend."""
9
+
10
+ subclasses: list[type["UtilityBase"]] = []
11
+
12
+ def __init_subclass__(cls, **kwargs) -> None:
13
+ """Keep track of all subclass implementations."""
14
+ super().__init_subclass__(**kwargs)
15
+ cls.subclasses.append(cls)
16
+
17
+ @staticmethod
18
+ def name() -> str:
19
+ """Distinct recognizable name of the utility."""
20
+ raise NotImplementedError
21
+
22
+ @staticmethod
23
+ def subdomain() -> str:
24
+ """Return the opower.com subdomain for this utility."""
25
+ raise NotImplementedError
26
+
27
+ @staticmethod
28
+ async def login(
29
+ session: aiohttp.ClientSession, username: str, password: str
30
+ ) -> str:
31
+ """Login to the utility website and return a URL where we can authorize opower.com.
32
+
33
+ Any failure to login should raise ClientResponseError with status 401 or 403.
34
+ """
35
+ raise NotImplementedError
@@ -0,0 +1,91 @@
1
+ """Pacific Gas & Electric (PG&E)."""
2
+
3
+ import aiohttp
4
+ from aiohttp.client_exceptions import ClientResponseError
5
+
6
+ from .base import UtilityBase
7
+
8
+
9
+ class PGE(UtilityBase):
10
+ """Pacific Gas & Electric (PG&E)."""
11
+
12
+ @staticmethod
13
+ def name() -> str:
14
+ """Distinct recognizable name of the utility."""
15
+ return "Pacific Gas & Electric"
16
+
17
+ @staticmethod
18
+ def subdomain() -> str:
19
+ """Return the opower.com subdomain for this utility."""
20
+ return "pge"
21
+
22
+ @staticmethod
23
+ async def login(
24
+ session: aiohttp.ClientSession, username: str, password: str
25
+ ) -> str:
26
+ """Login to the utility website and return a URL where we can authorize opower.com."""
27
+ # 1st way of login
28
+ async with session.post(
29
+ "https://www.pge.com/eimpapi/auth/login",
30
+ json={
31
+ "username": username,
32
+ "password": password,
33
+ "appName": "CustomerSSO",
34
+ },
35
+ ) as resp:
36
+ result = await resp.json()
37
+ if "errorMsg" in result:
38
+ raise ClientResponseError(
39
+ resp.request_info,
40
+ resp.history,
41
+ status=403,
42
+ message=result["errorMsg"],
43
+ )
44
+
45
+ # 2nd way of login
46
+ # async with session.get(
47
+ # "https://apigprd.cloud.pge.com/myaccount/v1/login",
48
+ # headers={
49
+ # "Authorization": "Basic "
50
+ # + base64.b64encode(f"{username}:{password}".encode()).decode(),
51
+ # },
52
+ # ) as resp:
53
+ # await resp.json()
54
+
55
+ # Skip the following 2 requests since emToolUrl is constant.
56
+ # If it ever changes consider uncommenting.
57
+ # These only work with the 2nd way of login.
58
+
59
+ # async with session.get(
60
+ # "https://apigprd.cloud.pge.com/myaccount/v1/cocaccount/secure/account/retrieveMyEnergyAccounts",
61
+ # params=(("userId", username),),
62
+ # ) as resp:
63
+ # energy_accounts = await resp.json()
64
+
65
+ # for energy_account in energy_accounts["accounts"]:
66
+ # accountNumber = energy_account["accountNumber"]
67
+ # addressAsString = energy_account["accountAddress"]["addressAsString"]
68
+ # print(accountNumber)
69
+ # print(addressAsString)
70
+ # break
71
+
72
+ # async with session.get(
73
+ # f"https://apigprd.cloud.pge.com/myaccount/v1/cocaccount/secure/retrieveEnergyManagementInfo/{accountNumber}/myusage"
74
+ # ) as resp:
75
+ # result = await resp.json()
76
+
77
+ # for energyManagementInfo in result["energyManagementInfoList"]:
78
+ # if energyManagementInfo["vendorType"] == "OPOWER":
79
+ # emToolUrl = energyManagementInfo["emToolUrl"]
80
+ # break
81
+ # assert emToolUrl == (
82
+ # "https://itiamping.cloud.pge.com/idp/startSSO.ping?"
83
+ # "PartnerSpId=sso.opower.com&TargetResource="
84
+ # "https%3A%2F%2Fpge.opower.com%2Fei%2Fapp%2Fr%2Fenergy-usage-details"
85
+ # )
86
+
87
+ return (
88
+ "https://itiamping.cloud.pge.com/idp/startSSO.ping?"
89
+ "PartnerSpId=sso.opower.com&TargetResource="
90
+ "https%3A%2F%2Fpge.opower.com%2Fei%2Fapp%2Fr%2Fenergy-usage-details"
91
+ )
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.1
2
+ Name: opower
3
+ Version: 0.0.1
4
+ Summary: A Python library for getting historical and forecasted usage/cost from utilities that use opower.com such as PG&E
5
+ Author-email: tronikos <tronikos@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/tronikos/opower
8
+ Project-URL: Bug Tracker, https://github.com/tronikos/opower/issues
9
+ Requires-Python: >=3.7
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+
13
+ # opower
14
+ A Python library for getting historical and forecasted usage/cost from utilities that use opower.com such as PG&amp;E.
15
+
16
+ To add support for a new utility that uses opower JSON API (you can tell if the energy dashboard of your utility is hosted on opower.com, e.g. pge.opower.com) add a file similar to [pge.py](https://github.com/tronikos/opower/blob/main/src/opower/utilities/pge.py).
17
+
18
+ ## Example
19
+
20
+ See [demo.py](https://github.com/tronikos/opower/blob/main/src/demo.py)
21
+
22
+ ## Development environment
23
+
24
+ ```sh
25
+ python3 -m venv .venv
26
+ source .venv/bin/activate
27
+ # for Windows CMD:
28
+ # .venv\Scripts\activate.bat
29
+ # for Windows PowerShell:
30
+ # .venv\Scripts\Activate.ps1
31
+
32
+ # Install dependencies
33
+ python -m pip install --upgrade pip
34
+ python -m pip install .
35
+
36
+ # Run formatter
37
+ python -m pip install isort black
38
+ isort .
39
+ black .
40
+
41
+ # Run lint
42
+ python -m pip install flake8 ruff
43
+ flake8 .
44
+ ruff .
45
+
46
+ # Run tests
47
+ python -m pip install pytest
48
+ pytest
49
+
50
+ # Run demo
51
+ python src/demo.py --help
52
+ # To output debug logs to a file:
53
+ python src/demo.py --verbose 2> out.txt
54
+
55
+ # Build package
56
+ python -m pip install build
57
+ python -m build
58
+ ```
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.cfg
5
+ src/demo.py
6
+ src/opower/__init__.py
7
+ src/opower/opower.py
8
+ src/opower.egg-info/PKG-INFO
9
+ src/opower.egg-info/SOURCES.txt
10
+ src/opower.egg-info/dependency_links.txt
11
+ src/opower.egg-info/requires.txt
12
+ src/opower.egg-info/top_level.txt
13
+ src/opower/utilities/__init__.py
14
+ src/opower/utilities/base.py
15
+ src/opower/utilities/pge.py
16
+ tests/test_opower.py
@@ -0,0 +1,2 @@
1
+ aiohttp>=3.8
2
+ asyncio>=3.4.3
@@ -0,0 +1,2 @@
1
+ demo
2
+ opower
@@ -0,0 +1,6 @@
1
+ """Tests for Opower."""
2
+
3
+
4
+ def test_dummy():
5
+ """Test dummy."""
6
+ assert True