pax_global_header00006660000000000000000000000064146133042230014510gustar00rootroot0000000000000052 comment=40affe10550fb4530d0c9490d5ad9a04f49c2f6e grahamwetzler-smart-meter-texas-7365b80/000077500000000000000000000000001461330422300202245ustar00rootroot00000000000000grahamwetzler-smart-meter-texas-7365b80/.editorconfig000066400000000000000000000004441461330422300227030ustar00rootroot00000000000000# http://editorconfig.org root = true [*] indent_style = space indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true charset = utf-8 end_of_line = lf [*.bat] indent_style = tab end_of_line = crlf [LICENSE] insert_final_newline = false [Makefile] indent_style = tab grahamwetzler-smart-meter-texas-7365b80/.flake8000066400000000000000000000000351461330422300213750ustar00rootroot00000000000000[flake8] max-line-length = 88grahamwetzler-smart-meter-texas-7365b80/.github/000077500000000000000000000000001461330422300215645ustar00rootroot00000000000000grahamwetzler-smart-meter-texas-7365b80/.github/ISSUE_TEMPLATE.md000066400000000000000000000005101461330422300242650ustar00rootroot00000000000000* Smart Meter Texas version: * Python version: * Operating System: ### Description Describe what you were trying to get done. Tell us what happened, what went wrong, and what you expected to happen. ### What I Did ``` Paste the command(s) you ran and the output. If there was a crash, please include the traceback here. ``` grahamwetzler-smart-meter-texas-7365b80/.github/workflows/000077500000000000000000000000001461330422300236215ustar00rootroot00000000000000grahamwetzler-smart-meter-texas-7365b80/.github/workflows/ci.yml000066400000000000000000000007411461330422300247410ustar00rootroot00000000000000name: CI on: - push - pull_request jobs: run-linters: name: Run linters runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2.4.0 - name: python-isort uses: isort/isort-action@v0.1.0 with: configuration: --check-only --diff --profile black - name: python-black uses: lgeiger/black-action@4379f39aa4b6a3bb1cceb46a7665b9c26647d82d with: args: ". --check" grahamwetzler-smart-meter-texas-7365b80/.github/workflows/python-publish.yml000066400000000000000000000020441461330422300273310ustar00rootroot00000000000000# This workflow will upload a Python Package using Twine when a release is created # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries # This workflow uses actions that are not certified by GitHub. # They are provided by a third-party and are governed by # separate terms of service, privacy policy, and support # documentation. name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build - name: Build package run: python -m build - name: Publish package uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }} grahamwetzler-smart-meter-texas-7365b80/.gitignore000066400000000000000000000022541461330422300222170ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # IDE settings .vscode/grahamwetzler-smart-meter-texas-7365b80/AUTHORS.rst000066400000000000000000000002361461330422300221040ustar00rootroot00000000000000======= Credits ======= Development Lead ---------------- * Graham Wetzler Contributors ------------ None yet. Why not be the first? grahamwetzler-smart-meter-texas-7365b80/CONTRIBUTING.rst000066400000000000000000000070661461330422300226760ustar00rootroot00000000000000.. highlight:: shell ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/grahamwetzler/smart_meter_texas/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ Smart Meter Texas could always use more documentation, whether as part of the official Smart Meter Texas docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/grahamwetzler/smart_meter_texas/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `smart_meter_texas` for local development. 1. Fork the `smart_meter_texas` repo on GitHub. 2. Clone your fork locally:: $ git clone git@github.com:your_name_here/smart_meter_texas.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv smart_meter_texas $ cd smart_meter_texas/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 smart_meter_texas tests $ python setup.py test or pytest $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 3.6, 3.7 and 3.8, and for PyPy. Check https://travis-ci.com/grahamwetzler/smart_meter_texas/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ pytest tests.test_smart_meter_texas Deploying --------- A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst). Then run:: $ bump2version patch # possible: major / minor / patch $ git push $ git push --tags Travis will then deploy to PyPI if tests pass. grahamwetzler-smart-meter-texas-7365b80/HISTORY.rst000066400000000000000000000001311461330422300221120ustar00rootroot00000000000000======= History ======= 0.1.0 (2020-07-07) ------------------ * First release on PyPI. grahamwetzler-smart-meter-texas-7365b80/LICENSE000066400000000000000000000020611461330422300212300ustar00rootroot00000000000000MIT License Copyright (c) 2020, Graham Wetzler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. grahamwetzler-smart-meter-texas-7365b80/MANIFEST.in000066400000000000000000000004061461330422300217620ustar00rootroot00000000000000include AUTHORS.rst include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif grahamwetzler-smart-meter-texas-7365b80/Makefile000066400000000000000000000043161461330422300216700ustar00rootroot00000000000000.PHONY: clean clean-test clean-pyc clean-build docs help .DEFAULT_GOAL := help define BROWSER_PYSCRIPT import os import sys import webbrowser from urllib.request import pathname2url webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) endef export BROWSER_PYSCRIPT define PRINT_HELP_PYSCRIPT import re import sys for line in sys.stdin: match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) if match: target, help = match.groups() print("%-20s %s" % (target, help)) endef export PRINT_HELP_PYSCRIPT BROWSER := python -c "$$BROWSER_PYSCRIPT" help: @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts clean-build: ## remove build artifacts rm -fr build/ rm -fr dist/ rm -fr .eggs/ find . -name '*.egg-info' -exec rm -fr {} + find . -name '*.egg' -exec rm -f {} + clean-pyc: ## remove Python file artifacts find . -name '*.pyc' -exec rm -f {} + find . -name '*.pyo' -exec rm -f {} + find . -name '*~' -exec rm -f {} + find . -name '__pycache__' -exec rm -fr {} + clean-test: ## remove test and coverage artifacts rm -fr .tox/ rm -f .coverage rm -fr htmlcov/ rm -fr .pytest_cache lint: ## check style with flake8 flake8 smart_meter_texas tests test: ## run tests quickly with the default Python pytest test-all: ## run tests on every Python version with tox tox coverage: ## check code coverage quickly with the default Python coverage run --source smart_meter_texas -m pytest coverage report -m coverage html $(BROWSER) htmlcov/index.html docs: ## generate Sphinx HTML documentation, including API docs rm -f docs/smart_meter_texas.rst rm -f docs/modules.rst sphinx-apidoc -o docs/ smart_meter_texas $(MAKE) -C docs clean $(MAKE) -C docs html $(BROWSER) docs/_build/html/index.html servedocs: docs ## compile the docs watching for changes watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . release: dist ## package and upload a release twine upload dist/* dist: clean ## builds source and wheel package python setup.py sdist python setup.py bdist_wheel ls -l dist install: clean ## install the package to the active Python's site-packages python setup.py install grahamwetzler-smart-meter-texas-7365b80/README.rst000066400000000000000000000021031461330422300217070ustar00rootroot00000000000000================= Smart Meter Texas ================= .. image:: https://img.shields.io/pypi/v/smart_meter_texas.svg :target: https://pypi.python.org/pypi/smart_meter_texas .. image:: https://img.shields.io/travis/grahamwetzler/smart-meter-texas.svg :target: https://travis-ci.com/grahamwetzler/smart-meter-texas Package to asynchronously connect to and retrieve data from the unofficial Smart Meter Texas API using aiohttp. Currently only obtaining the dashboard and current meter reading are implemented. There are serval other API endpoints that are not implemented in this package. * Free software: MIT license Install -------- To install: .. code-block:: bash $ pip install smart-meter-texas Example ------- Please see the examples for an idea of how to get started using the package. Credits ------- This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. .. _Cookiecutter: https://github.com/audreyr/cookiecutter .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage grahamwetzler-smart-meter-texas-7365b80/docs/000077500000000000000000000000001461330422300211545ustar00rootroot00000000000000grahamwetzler-smart-meter-texas-7365b80/docs/Makefile000066400000000000000000000011521461330422300226130ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = python -msphinx SPHINXPROJ = smart_meter_texas SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) grahamwetzler-smart-meter-texas-7365b80/docs/authors.rst000066400000000000000000000000341461330422300233700ustar00rootroot00000000000000.. include:: ../AUTHORS.rst grahamwetzler-smart-meter-texas-7365b80/docs/conf.py000077500000000000000000000115561461330422300224660ustar00rootroot00000000000000#!/usr/bin/env python # # smart_meter_texas documentation build configuration file, created by # sphinx-quickstart on Fri Jun 9 13:47:02 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath("..")) import smart_meter_texas # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "Smart Meter Texas" copyright = "2020, Graham Wetzler" author = "Graham Wetzler" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = smart_meter_texas.__version__ # The full version, including alpha/beta/rc tags. release = smart_meter_texas.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # -- Options for HTMLHelp output --------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "smart_meter_texasdoc" # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto, manual, or own class]). latex_documents = [ ( master_doc, "smart_meter_texas.tex", "Smart Meter Texas Documentation", "Graham Wetzler", "manual", ), ] # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, "smart_meter_texas", "Smart Meter Texas Documentation", [author], 1) ] # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "smart_meter_texas", "Smart Meter Texas Documentation", author, "smart_meter_texas", "One line description of project.", "Miscellaneous", ), ] grahamwetzler-smart-meter-texas-7365b80/docs/contributing.rst000066400000000000000000000000411461330422300244100ustar00rootroot00000000000000.. include:: ../CONTRIBUTING.rst grahamwetzler-smart-meter-texas-7365b80/docs/history.rst000066400000000000000000000000341461330422300234040ustar00rootroot00000000000000.. include:: ../HISTORY.rst grahamwetzler-smart-meter-texas-7365b80/docs/index.rst000066400000000000000000000005011461330422300230110ustar00rootroot00000000000000Welcome to Smart Meter Texas's documentation! ============================================= .. toctree:: :maxdepth: 2 :caption: Contents: readme installation usage modules contributing authors history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` grahamwetzler-smart-meter-texas-7365b80/docs/installation.rst000066400000000000000000000022761461330422300244160ustar00rootroot00000000000000.. highlight:: shell ============ Installation ============ Stable release -------------- To install Smart Meter Texas, run this command in your terminal: .. code-block:: console $ pip install smart_meter_texas This is the preferred method to install Smart Meter Texas, as it will always install the most recent stable release. If you don't have `pip`_ installed, this `Python installation guide`_ can guide you through the process. .. _pip: https://pip.pypa.io .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ From sources ------------ The sources for Smart Meter Texas can be downloaded from the `Github repo`_. You can either clone the public repository: .. code-block:: console $ git clone git://github.com/grahamwetzler/smart_meter_texas Or download the `tarball`_: .. code-block:: console $ curl -OJL https://github.com/grahamwetzler/smart_meter_texas/tarball/master Once you have a copy of the source, you can install it with: .. code-block:: console $ python setup.py install .. _Github repo: https://github.com/grahamwetzler/smart_meter_texas .. _tarball: https://github.com/grahamwetzler/smart_meter_texas/tarball/master grahamwetzler-smart-meter-texas-7365b80/docs/make.bat000066400000000000000000000014131461330422300225600ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=python -msphinx ) set SOURCEDIR=. set BUILDDIR=_build set SPHINXPROJ=smart_meter_texas if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The Sphinx module was not found. Make sure you have Sphinx installed, echo.then set the SPHINXBUILD environment variable to point to the full echo.path of the 'sphinx-build' executable. Alternatively you may add the echo.Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd grahamwetzler-smart-meter-texas-7365b80/docs/modules.rst000066400000000000000000000001301461330422300233500ustar00rootroot00000000000000smart_meter_texas ================= .. toctree:: :maxdepth: 4 smart_meter_texas grahamwetzler-smart-meter-texas-7365b80/docs/readme.rst000066400000000000000000000000331461330422300231370ustar00rootroot00000000000000.. include:: ../README.rst grahamwetzler-smart-meter-texas-7365b80/docs/smart_meter_texas.rst000066400000000000000000000005721461330422300254400ustar00rootroot00000000000000smart\_meter\_texas package =========================== Submodules ---------- smart\_meter\_texas.async\_api module ------------------------------------- .. automodule:: smart_meter_texas.async_api :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: smart_meter_texas :members: :undoc-members: :show-inheritance: grahamwetzler-smart-meter-texas-7365b80/docs/usage.rst000066400000000000000000000001311461330422300230050ustar00rootroot00000000000000===== Usage ===== To use Smart Meter Texas in a project:: import smart_meter_texas grahamwetzler-smart-meter-texas-7365b80/examples/000077500000000000000000000000001461330422300220425ustar00rootroot00000000000000grahamwetzler-smart-meter-texas-7365b80/examples/get_meter_reading.py000066400000000000000000000021731461330422300260630ustar00rootroot00000000000000"""Example to show how to read each meter associated with a user's account.""" import asyncio import logging import os import sys import aiohttp import pytz from smart_meter_texas import Account, Client, ClientSSLContext logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) username = os.environ["SMTUSER"] password = os.environ["SMTPW"] timezone = pytz.timezone("America/Chicago") async def main(): client_ssl_ctx = ClientSSLContext() ssl_context = await client_ssl_ctx.get_ssl_context() async with aiohttp.ClientSession() as websession: account = Account(username, password) client = Client(websession, account, ssl_context) print("Authenticating...") await client.authenticate() meters = await account.fetch_meters(client) for meter in meters: print("Reading meter...") await meter.read_meter(client) localized_time = meter.reading_datetime.astimezone(timezone) print(f"{meter.reading:,.0f} kW @ {localized_time}") if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) grahamwetzler-smart-meter-texas-7365b80/examples/get_meters.py000066400000000000000000000020041461330422300245460ustar00rootroot00000000000000"""Example to show how to fetch all meters associated with a user's account.""" import asyncio import logging import os import sys import aiohttp from smart_meter_texas import Account, Client, ClientSSLContext logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) username = os.environ["SMTUSER"] password = os.environ["SMTPW"] async def main(): client_ssl_ctx = ClientSSLContext() ssl_context = await client_ssl_ctx.get_ssl_context() async with aiohttp.ClientSession() as websession: account = Account(username, password) client = Client(websession, account, ssl_context) await client.authenticate() meters = await account.fetch_meters(client) for i, meter in enumerate(meters, 1): print(f"Meter {i}:") print(f" Meter:\t{meter.meter}") print(f" ESIID:\t{meter.esiid}") print(f" Address:\t{meter.address}\n") if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) grahamwetzler-smart-meter-texas-7365b80/requirements.txt000066400000000000000000000001671461330422300235140ustar00rootroot00000000000000aiohttp>=3.7.4,<4 asn1>=2.4.1 certifi>=2021.5.30 pyOpenSSL>=20.0.1 python-dateutil>=2.8.1 pytz>=2021.1 tenacity>=8.0.1 grahamwetzler-smart-meter-texas-7365b80/setup.cfg000066400000000000000000000005601461330422300220460ustar00rootroot00000000000000[bumpversion] current_version = 0.5.5 commit = True tag = True [bumpversion:file:setup.py] search = {current_version} replace = {new_version} [bumpversion:file:smart_meter_texas/__init__.py] search = {current_version} replace = {new_version} [bdist_wheel] universal = 1 [flake8] exclude = docs [aliases] test = pytest [tool:pytest] collect_ignore = ['setup.py'] grahamwetzler-smart-meter-texas-7365b80/setup.py000066400000000000000000000026341461330422300217430ustar00rootroot00000000000000#!/usr/bin/env python """The setup script.""" from setuptools import find_packages, setup with open("README.rst") as readme_file: readme = readme_file.read() requirements = [ "aiohttp>=3.7.4,<4", "asn1>=2.4.1", "python-dateutil>=2.8.1", "tenacity>=8.0.1", ] setup_requirements = ["pytest-runner"] test_requirements = ["pytest>=3"] setup( author="Graham Wetzler", author_email="graham@wetzler.dev", python_requires=">=3.6", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], description="Package to connect to and retrieve data from the unofficial \ Smart Meter Texas API", install_requires=requirements, license="MIT license", long_description=readme, include_package_data=True, keywords="smart_meter_texas", name="smart_meter_texas", packages=find_packages(include=["smart_meter_texas", "smart_meter_texas.*"]), setup_requires=setup_requirements, test_suite="tests", tests_require=test_requirements, url="https://github.com/grahamwetzler/smart-meter-texas", version="0.5.5", zip_safe=False, ) grahamwetzler-smart-meter-texas-7365b80/smart_meter_texas/000077500000000000000000000000001461330422300237525ustar00rootroot00000000000000grahamwetzler-smart-meter-texas-7365b80/smart_meter_texas/__init__.py000066400000000000000000000401551461330422300260700ustar00rootroot00000000000000from __future__ import annotations import asyncio import binascii import datetime import logging import socket import ssl import sys from random import randrange import asn1 import certifi import dateutil.parser import OpenSSL.crypto as crypto from aiohttp import ClientSession from dateutil.tz import gettz from tenacity import retry, retry_if_exception_type from .const import ( AUTH_ENDPOINT, BASE_ENDPOINT, BASE_HOSTNAME, CLIENT_HEADERS, INTERVAL_SYNCH, LATEST_OD_READ_ENDPOINT, METER_ENDPOINT, OD_READ_ENDPOINT, OD_READ_RETRY_TIME, TOKEN_EXPRIATION, USER_AGENT_TEMPLATE, ) from .exceptions import ( SmartMeterTexasAPIDateError, SmartMeterTexasAPIError, SmartMeterTexasAuthError, SmartMeterTexasAuthExpired, SmartMeterTexasRateLimitError, ) __author__ = "Graham Wetzler" __email__ = "graham@wetzler.dev" __version__ = "0.5.5" _LOGGER = logging.getLogger(__name__) class Meter: def __init__(self, meter: str, esiid: str, address: str): self.meter = meter self.esiid = esiid self.address = address self.reading_data = None self.interval = None async def read_meter(self, client: Client): """Triggers an on-demand meter read and returns it when complete.""" _LOGGER.debug("Requesting meter reading") # Trigger an on-demand meter read. await client.request( OD_READ_ENDPOINT, json={"ESIID": self.esiid, "MeterNumber": self.meter}, ) # Occasionally check to see if on-demand meter reading is complete. while True: json_response = await client.request( LATEST_OD_READ_ENDPOINT, json={"ESIID": self.esiid}, ) try: data = json_response["data"] status = data["odrstatus"] except KeyError: _LOGGER.error("Error reading meter: ", json_response) raise SmartMeterTexasAPIError( f"Error parsing response: {json_response}" ) else: if status == "COMPLETED": _LOGGER.debug("Reading completed: %s", data) self.reading_data = data return self.reading_data elif status == "PENDING": _LOGGER.debug("Meter reading %s", status) _LOGGER.debug("Sleeping for %s seconds", OD_READ_RETRY_TIME) await asyncio.sleep(OD_READ_RETRY_TIME) else: _LOGGER.error("Unknown meter reading status: %s", status) raise SmartMeterTexasAPIError(f"Unknown meter status: {status}") async def get_15min(self, client: Client, prevdays=1): """Get the interval data to parse out Surplus Generation""" retry = 1 prevdays = int(prevdays) if prevdays == 1: yesterday = (datetime.date.today() - datetime.timedelta(days=1)).strftime( "%m/%d/%Y" ) else: yesterday = ( datetime.date.today() - datetime.timedelta(days=prevdays) ).strftime("%m/%d/%Y") while retry < 3: _LOGGER.debug("Getting Interval data") surplus = [] json_response = await client.request( INTERVAL_SYNCH, json={ "startDate": yesterday, "endDate": yesterday, "reportFormat": "JSON", "ESIID": [self.esiid], "versionDate": None, "readDate": None, "versionNum": None, "dataType": None, }, ) try: data = json_response["data"] energy = data["energyData"] except KeyError: _LOGGER.error("Error reading data: ", json_response) if data["errorCode"] == "1": tdsp = "TDSP" in data["errorMessage"] if tdsp: retry += 1 yesterday = ( datetime.date.today() - datetime.timedelta(days=retry) ).strftime("%m/%d/%Y") if retry < 3: continue else: raise SmartMeterTexasAPIDateError( "Unable to get data from SMT using the date" ) else: raise SmartMeterTexasAPIError( f"Error parsing response: {json_response}" ) else: hour = -1 minute_check = 0 for entry in energy: if entry["RT"] == "G": readdata = entry["RD"].split(",") for generated in readdata: if generated != "": if minute_check % 4 == 0: hour += 1 minute = "00" elif minute_check % 4 == 1: minute = "15" elif minute_check % 4 == 2: minute = 30 elif minute_check % 4 == 3: minute = 45 minute_check += 1 num = generated.split("-")[0] surplus.append([f"{yesterday} {hour}:{minute}", num]) self.interval = surplus return self.interval @property def reading(self): """Returns the latest meter reading in kWh.""" return float(self.reading_data["odrread"]) @property def reading_datetime(self): """Returns the UTC datetime of the latest reading. 'odrdate' is returned from the SMT API in America/Chicago timezone.""" date = dateutil.parser.parse(self.reading_data["odrdate"]).replace( tzinfo=gettz("America/Chicago") ) date_as_utc = date.astimezone(datetime.timezone.utc) return date_as_utc @property def read_15min(self): """Returns the list of date/times and the consumption rate""" return self.interval class Account: def __init__(self, username: str, password: str): self.username = username self.password = password async def fetch_meters(self, client: "Client"): """Returns a list of the meters associated with the account""" json_response = await client.request(METER_ENDPOINT, json={"esiid": "*"}) meters = [] for meter_data in json_response["data"]: address = meter_data["address"] meter = meter_data["meterNumber"] esiid = meter_data["esiid"] meter = Meter(meter, esiid, address) meters.append(meter) return meters class Client: def __init__( self, websession: ClientSession, account: "Account", ssl_context: ssl.SSLContext ): self.websession = websession self.account = account self.token = None self.authenticated = False self.token_expiration = datetime.datetime.now() self.user_agent = None self.ssl_context = ssl_context def _init_ssl_context(self): if self.ssl_context == None: new_ssl_context = ssl.create_default_context(capath=certifi.where()) new_ssl_context.check_hostname = True new_ssl_context.verify_mode = ssl.CERT_REQUIRED if sys.version_info >= (3, 7): new_ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 else: new_ssl_context.options |= ( ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_SSLv3 | ssl.OP_NO_SSLv2 ) self.ssl_context = new_ssl_context def _agent_headers(self): """Build the user agent header.""" if not self.user_agent: self.user_agent = USER_AGENT_TEMPLATE.format( BUILD=randrange(1001, 9999), REV=randrange(12, 999) ) return {"User-Agent": self.user_agent} def _update_token_expiration(self): self.token_expiration = datetime.datetime.now() + TOKEN_EXPRIATION @retry(retry=retry_if_exception_type(SmartMeterTexasAuthExpired)) async def request( self, path: str, method: str = "post", **kwargs, ): """Helper method to make API calls against the SMT API.""" await self.authenticate() resp = await self.websession.request( method, f"{BASE_ENDPOINT}{path}", headers=self.headers, **kwargs, ssl=self.ssl_context, ) if resp.status == 401: _LOGGER.debug("Authentication token expired; requesting new token") self.authenticated = False await self.authenticate() raise SmartMeterTexasAuthExpired # Since API call did not return a 400 code, update the token_expiration. self._update_token_expiration() json_response = await resp.json() return json_response async def authenticate(self): if not self.token_valid: _LOGGER.debug("Requesting login token") resp = await self.websession.request( "POST", AUTH_ENDPOINT, json={ "username": self.account.username, "password": self.account.password, "rememberMe": "true", }, headers=self.headers, ssl=self.ssl_context, ) if resp.status == 400: raise SmartMeterTexasAuthError("Username or password was not accepted") if resp.status == 403: raise SmartMeterTexasRateLimitError( "Reached ratelimit or brute force protection" ) json_response = await resp.json() try: self.token = json_response["token"] except KeyError: raise SmartMeterTexasAPIError( "API returned unknown login json: %s", json_response ) self._update_token_expiration() self.authenticated = True _LOGGER.debug("Successfully retrieved login token") @property def headers(self): headers = {**self._agent_headers(), **CLIENT_HEADERS} if self.token: headers["Authorization"] = f"Bearer {self.token}" return headers @property def token_valid(self): if self.authenticated or (datetime.datetime.now() < self.token_expiration): return True return False class ClientSSLContext: def _asn1_value_to_string(self, tag_number, value): """Retrieves the ASN.1 value as a string value""" if tag_number == asn1.Numbers.ObjectIdentifier: return value elif isinstance(value, bytes): return "0x" + str(binascii.hexlify(value).upper()) elif isinstance(value, str): return value else: return repr(value) def _find_ca_issuers_uri(self, input_stream, tag_ca_issuers_uri_found=False): """Lookup the CA Issuers - URI Object and return the value.""" ca_issuers_uri = None while not input_stream.eof() and not ca_issuers_uri: tag = input_stream.peek() if tag.typ == asn1.Types.Primitive: tag, value = input_stream.read() if tag_ca_issuers_uri_found: str_value = self._asn1_value_to_string(tag.nr, value) if str_value: ca_issuers_uri = str_value.decode("utf-8") tag_ca_issuers_uri_found = False break else: tag_ca_issuers_uri_found = False elif self._asn1_value_to_string(tag.nr, value) == "1.3.6.1.5.5.7.48.2": tag_ca_issuers_uri_found = True elif tag.typ == asn1.Types.Constructed: input_stream.enter() ca_issuers_uri = self._find_ca_issuers_uri( input_stream, tag_ca_issuers_uri_found ) input_stream.leave() return ca_issuers_uri def get_ca_issuers_uri(self): """Retrieves the CA Issuers URI value""" ca_issuers_uri = None ssl_context = None try: ssl_context = ssl.create_default_context(capath=certifi.where()) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE with ssl_context.wrap_socket( socket.socket(), server_hostname=BASE_HOSTNAME ) as s: try: s.connect((BASE_HOSTNAME, 443)) cert_bin = s.getpeercert(True) x509 = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_bin) for idx in range(x509.get_extension_count()): ext = x509.get_extension(idx) short_name = ext.get_short_name() if short_name == b"authorityInfoAccess": decoder = asn1.Decoder() data = ext.get_data() decoder.start(data) ca_issuers_uri = self._find_ca_issuers_uri(decoder, False) finally: s.close() except Exception as error: _LOGGER.error("Failed to lookup CA Issuers URI value") ca_issuers_uri = None finally: if ca_issuers_uri: _LOGGER.debug("Found CA Issuers URI value: " + ca_issuers_uri) return ca_issuers_uri async def get_issuers_certificate(self, ca_issuers_uri: str): """Downloads the CA Issuers Certificate file and returns the binary data""" certificate = None try: if ca_issuers_uri != None: async with ClientSession() as client: async with await client.get(ca_issuers_uri) as resp: if resp.status == 200: certificate = await resp.read() except Exception as error: _LOGGER.error("Failed to retrieve CA Issuers URI certificate file") certificate = None return certificate def create_ssl_context(self, certificate: bin = None): """Creates the SSL Context using the CA Issuers binary data""" ssl_context = ssl.create_default_context(capath=certifi.where()) try: if certificate: ssl_context.load_verify_locations( cafile=certifi.where(), cadata=certificate ) _LOGGER.debug("Loaded certificate file into SSL Context") except Exception as error: _LOGGER.error("Error loading certificate file into SSL Context") ssl_context = ssl.create_default_context(capath=certifi.where()) # Enable strict checking ssl_context.check_hostname = True ssl_context.verify_mode = ssl.CERT_REQUIRED if sys.version_info >= (3, 7): ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2 else: ssl_context.options |= ( ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_SSLv3 | ssl.OP_NO_SSLv2 ) return ssl_context async def get_ssl_context(self): """Returns the default SSL Context""" ssl_context = None try: loop = asyncio.get_event_loop() ca_issuers_uri = await loop.run_in_executor(None, self.get_ca_issuers_uri) ca_certificate = await self.get_issuers_certificate(ca_issuers_uri) ssl_context = self.create_ssl_context(ca_certificate) except: ssl_context = None return ssl_context grahamwetzler-smart-meter-texas-7365b80/smart_meter_texas/const.py000066400000000000000000000022761461330422300254610ustar00rootroot00000000000000import datetime BASE_HOSTNAME = "www.smartmetertexas.com" BASE_URL = "https://" + BASE_HOSTNAME + "/" BASE_ENDPOINT = BASE_URL + "api" AUTH_ENDPOINT = BASE_URL + "/commonapi/user/authenticate" LATEST_OD_READ_ENDPOINT = "/usage/latestodrread" METER_ENDPOINT = "/meter" OD_READ_ENDPOINT = "/ondemandread" INTERVAL_SYNCH = "/adhoc/intervalsynch" USER_AGENT_TEMPLATE = ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/123.0.{BUILD}.{REV} Safari/537.36" ) CLIENT_HEADERS = { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9", "cache-control": "no-cache", "content-type": "application/json", "origin": "https://www.smartmetertexas.com", "pragma": "no-cache", "referer": "https://www.smartmetertexas.com/home", } API_ERROR_KEY = "errormessage" TOKEN_EXPIRED_KEY = "message" TOKEN_EXPIRED_VALUE = "Invalid Token" API_ERROR_RESPONSES = { "ERR-USR-USERNOTFOUND": "user not found", "ERR-USR-INVALIDPASSWORDERROR": "password is not correct", } API_DATE_ERROR = "No Energy Data received from the respective TDSP" OD_READ_RETRY_TIME = 15 TOKEN_EXPRIATION = datetime.timedelta(minutes=15) grahamwetzler-smart-meter-texas-7365b80/smart_meter_texas/exceptions.py000066400000000000000000000015071461330422300265100ustar00rootroot00000000000000class SmartMeterTexasException(Exception): """Base exception for more specific exceptions to inherit from.""" ... class SmartMeterTexasAuthError(SmartMeterTexasException): """Exception for authentication failures. Either wrong username or wrong password.""" ... class SmartMeterTexasRateLimitError(SmartMeterTexasException): """Exception for reaching the ratelimit. Either too many login attempts or too many requests.""" ... class SmartMeterTexasAuthExpired(SmartMeterTexasException): """Exception for when a token is no longer valid.""" ... class SmartMeterTexasAPIError(SmartMeterTexasException): """General exception for unknown API responses.""" ... class SmartMeterTexasAPIDateError(SmartMeterTexasException): """Exception for no data for specified date""" ... grahamwetzler-smart-meter-texas-7365b80/tox.ini000066400000000000000000000010441461330422300215360ustar00rootroot00000000000000[tox] envlist = py36, py37, py38, flake8 [travis] python = 3.8: py38 3.7: py37 3.6: py36 [testenv:flake8] basepython = python deps = flake8 commands = flake8 smart_meter_texas tests [testenv] setenv = PYTHONPATH = {toxinidir} deps = -r{toxinidir}/requirements_dev.txt ; If you want to make tox run the tests with the same versions, create a ; requirements.txt with the pinned versions and uncomment the following line: ; -r{toxinidir}/requirements.txt commands = pip install -U pip pytest --basetemp={envtmpdir}