pax_global_header00006660000000000000000000000064150277000600014507gustar00rootroot0000000000000052 comment=c94895e7fb5d2621b35857099e7cb89f90b476ac Danielhiversen-pyTibber-c94895e/000077500000000000000000000000001502770006000166015ustar00rootroot00000000000000Danielhiversen-pyTibber-c94895e/.coveragerc000066400000000000000000000005431502770006000207240ustar00rootroot00000000000000[run] source = Tibber [report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about missing debug-only code: def __repr__ # Don't complain if tests don't hit defensive assertion code: raise AssertionError raise NotImplementedError Danielhiversen-pyTibber-c94895e/.github/000077500000000000000000000000001502770006000201415ustar00rootroot00000000000000Danielhiversen-pyTibber-c94895e/.github/FUNDING.yml000066400000000000000000000001461502770006000217570ustar00rootroot00000000000000# These are supported funding model platforms github: Danielhiversen custom: http://paypal.me/dahoiv Danielhiversen-pyTibber-c94895e/.github/dependabot.yml000066400000000000000000000005061502770006000227720ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: weekly open-pull-requests-limit: 10 reviewers: - Danielhiversen - package-ecosystem: pip directory: "/" schedule: interval: daily time: "04:00" open-pull-requests-limit: 10 reviewers: - Danielhiversen Danielhiversen-pyTibber-c94895e/.github/main.workflow000066400000000000000000000005521502770006000226630ustar00rootroot00000000000000workflow "flake8" { on = "push" resolves = ["The Python Action"] } action "GitHub Action for Flake8" { uses = "cclauss/GitHub-Action-for-Flake8@master" args = "flake8 tibber" } action "The Python Action" { uses = "Gr1N/the-python-action@0.4.0" needs = ["GitHub Action for Flake8"] args = "tox -e lint" env = { PYTHON_VERSION = "3.11" } } Danielhiversen-pyTibber-c94895e/.github/workflows/000077500000000000000000000000001502770006000221765ustar00rootroot00000000000000Danielhiversen-pyTibber-c94895e/.github/workflows/code_checker.yml000066400000000000000000000017741502770006000253300ustar00rootroot00000000000000name: Code checker on: push: pull_request: schedule: - cron: "0 4 * * *" jobs: validate: runs-on: "ubuntu-latest" strategy: matrix: python-version: - "3.11" - "3.12" env: SRC_FOLDER: tibber steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: 'pip' - name: Install dependency run: | pip install -r requirements.txt pip install mypy pre-commit pytest pytest-asyncio pytest-cov ruff - uses: actions/cache@v4 with: path: ~/.cache/pre-commit key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }} - name: Run pre-commit run: pre-commit run --all-files --show-diff-on-failure --color=always shell: bash - name: pytest run: | pytest Danielhiversen-pyTibber-c94895e/.github/workflows/codeql.yml000066400000000000000000000013651502770006000241750ustar00rootroot00000000000000name: "CodeQL" on: push: branches: ["master"] pull_request: branches: ["master"] schedule: - cron: "3 0 * * 6" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [python] steps: - name: Checkout uses: actions/checkout@v4 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} queries: +security-and-quality - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: category: "/language:${{ matrix.language }}" Danielhiversen-pyTibber-c94895e/.github/workflows/python-publish.yml000066400000000000000000000014601502770006000257070ustar00rootroot00000000000000# This workflows 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 name: Upload Python Package on: release: types: [created] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install build twine - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | python -m build twine upload dist/* Danielhiversen-pyTibber-c94895e/.github/workflows/rebase.yml000066400000000000000000000011571502770006000241660ustar00rootroot00000000000000name: Automatic Rebase on: issue_comment: types: [created] jobs: rebase: name: Rebase if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase') && github.event.comment.author_association == 'OWNER' runs-on: ubuntu-latest steps: - name: Checkout the latest code uses: actions/checkout@v4 with: token: ${{ secrets.GITHUB_TOKEN }} fetch-depth: 0 # otherwise, you will fail to push refs to dest repo - name: Automatic Rebase uses: cirrus-actions/rebase@1.8 env: GITHUB_TOKEN: ${{ secrets.GIT }} Danielhiversen-pyTibber-c94895e/.gitignore000066400000000000000000000022321502770006000205700ustar00rootroot00000000000000# 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/ # 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/ venvs/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # IDE .idea/ Danielhiversen-pyTibber-c94895e/.pre-commit-config.yaml000066400000000000000000000007161502770006000230660ustar00rootroot00000000000000repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.1.0 hooks: - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.6.2 hooks: - id: ruff args: [--fix, --exit-non-zero-on-fix] - id: ruff-format - repo: local hooks: - id: mypy name: mypy entry: mypy language: system types: [python] files: ^(tibber|test)/.+\.py$ Danielhiversen-pyTibber-c94895e/LICENSE000066400000000000000000001045151502770006000176140ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . Danielhiversen-pyTibber-c94895e/README.md000066400000000000000000000041031502770006000200560ustar00rootroot00000000000000# pyTibber [![PyPI version](https://badge.fury.io/py/pyTibber.svg)](https://badge.fury.io/py/pyTibber) Ruff pre-commit Python3 library for [Tibber](https://tibber.com/). Get electricity price and consumption. If you have a Tibber Pulse or Watty you can see your consumption in real time. [Buy me a coffee :)](http://paypal.me/dahoiv) Go to [developer.tibber.com/](https://developer.tibber.com/) to get your API token. ## Install ``` pip3 install pyTibber ``` ## Example: ```python import tibber.const import tibber import asyncio async def start(): tibber_connection = tibber.Tibber(tibber.const.DEMO_TOKEN, user_agent="change_this") await tibber_connection.update_info() print(tibber_connection.name) home = tibber_connection.get_homes()[0] await home.fetch_consumption_data() await home.update_info() print(home.address1) await home.update_price_info() print(home.current_price_info) # await tibber_connection.close_connection() loop = asyncio.run(start()) ``` ## Example realtime data: An example of how to subscribe to realtime data (Pulse/Watty): ```python import tibber.const import asyncio import aiohttp import tibber def _callback(pkg): print(pkg) data = pkg.get("data") if data is None: return print(data.get("liveMeasurement")) async def run(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber(tibber.const.DEMO_TOKEN, websession=session, user_agent="change_this") await tibber_connection.update_info() home = tibber_connection.get_homes()[0] await home.rt_subscribe(_callback) while True: await asyncio.sleep(10) loop = asyncio.run(run()) ``` The library is used as part of Home Assistant. Danielhiversen-pyTibber-c94895e/pyproject.toml000066400000000000000000000024631502770006000215220ustar00rootroot00000000000000[build-system] build-backend = "setuptools.build_meta" requires = ["setuptools>=77.0"] [project] name = "pyTibber" license = "GPL-3.0-or-later" description = "A python3 library to communicate with Tibber" readme = "README.md" authors = [{ name = "Daniel Hjelseth Hoyer", email = "mail@dahoiv.net" }] requires-python = ">=3.11" classifiers = [ "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Home Automation", "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ "aiohttp>=3.0.6", "gql>=3.0.0", "websockets>=10.0", ] dynamic = ["version"] [project.urls] "Source code" = "https://github.com/Danielhiversen/pyTibber" [tool.setuptools.dynamic] version = { attr = "tibber.const.__version__"} [tool.setuptools.packages.find] include = ["tibber*"] [tool.mypy] disallow_incomplete_defs = true implicit_optional = true strict_optional = false [tool.ruff] line-length = 120 target-version = "py311" [tool.ruff.lint] ignore = ["D", "EM", "FBT", "PLR0913", "C901", "S101", "TRY"] select = ["ALL"] [tool.ruff.lint.isort] known-first-party = ["tibber", "test"] [tool.ruff.lint.per-file-ignores] "setup.py" = ["D100"] "test/**/*" = [ "ANN201", "PLR2004", "S101", "S106", ] Danielhiversen-pyTibber-c94895e/requirements.txt000066400000000000000000000000021502770006000220550ustar00rootroot00000000000000. Danielhiversen-pyTibber-c94895e/setup.cfg000066400000000000000000000000711502770006000204200ustar00rootroot00000000000000[flake8] max-line-length = 120 extend-ignore = S105,S110 Danielhiversen-pyTibber-c94895e/test/000077500000000000000000000000001502770006000175605ustar00rootroot00000000000000Danielhiversen-pyTibber-c94895e/test/__init__.py000066400000000000000000000000251502770006000216660ustar00rootroot00000000000000"""Provide tests.""" Danielhiversen-pyTibber-c94895e/test/test_tibber.py000066400000000000000000000152761502770006000224530ustar00rootroot00000000000000"""Tests for pyTibber.""" import asyncio import datetime as dt import logging import aiohttp import pytest import tibber from tibber.const import RESOLUTION_DAILY from tibber.exceptions import FatalHttpExceptionError, InvalidLoginError, NotForDemoUserError @pytest.mark.asyncio async def test_tibber_no_session(): tibber_connection = tibber.Tibber( user_agent="test", ) await tibber_connection.update_info() assert tibber_connection.name == "Arya Stark" @pytest.mark.asyncio async def test_tibber(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( websession=session, user_agent="test", ) await tibber_connection.update_info() assert tibber_connection.name == "Arya Stark" assert len(tibber_connection.get_homes(only_active=False)) == 1 assert tibber_connection.get_home("INVALID_KEY") is None k = 0 for home in tibber_connection.get_homes(only_active=False): await home.update_info() if home.home_id == "c70dcbe5-4485-4821-933d-a8a86452737b": k += 1 assert home.home_id == "c70dcbe5-4485-4821-933d-a8a86452737b" assert home.address1 == "Kungsgatan 8" assert home.country == "SE" assert home.price_unit == "SEK/kWh" assert home.has_real_time_consumption assert home.current_price_total is None assert home.price_total == {} assert home.current_price_info == {} await home.update_current_price_info() assert home.current_price_total > 0 assert isinstance(home.current_price_info.get("energy"), float | int) assert isinstance(home.current_price_info.get("startsAt"), str) assert isinstance(home.current_price_info.get("tax"), float | int) assert isinstance(home.current_price_info.get("total"), float | int) await home.update_price_info() for key in home.price_total: assert isinstance(key, str) assert isinstance(home.price_total[key], float | int) else: k += 1 assert home.home_id == "96a14971-525a-4420-aae9-e5aedaa129ff" assert home.address1 == "Winterfell Castle 1" assert home.country is None assert k == 1 assert len(tibber_connection.get_homes(only_active=False)) == 1 await tibber_connection.update_info() @pytest.mark.asyncio async def test_tibber_invalid_token(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( access_token="INVALID_TOKEN", websession=session, user_agent="test", ) with pytest.raises(InvalidLoginError, match="invalid token"): await tibber_connection.update_info() assert not tibber_connection.name assert tibber_connection.get_homes() == [] @pytest.mark.asyncio async def test_tibber_invalid_query(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( websession=session, user_agent="test", ) with pytest.raises(FatalHttpExceptionError, match="Syntax Error*"): await tibber_connection.execute("invalidquery") assert not tibber_connection.name assert tibber_connection.get_homes() == [] @pytest.mark.asyncio async def test_tibber_notification(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( websession=session, user_agent="test", ) with pytest.raises(NotForDemoUserError, match="operation not allowed for demo user"): await tibber_connection.send_notification("Test title", "message") @pytest.mark.asyncio async def test_tibber_token(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( access_token="d11a43897efa4cf478afd659d6c8b7117da9e33b38232fd454b0e9f28af98012", websession=session, user_agent="test", ) await tibber_connection.update_info() assert tibber_connection.name == "Daniel Høyer" assert len(tibber_connection.get_homes()) == 0 assert len(tibber_connection.get_homes(only_active=False)) == 0 @pytest.mark.asyncio async def test_tibber_current_price_rank(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( websession=session, user_agent="test", ) await tibber_connection.update_info() homes = tibber_connection.get_homes() assert len(homes) == 1, "No homes found" await homes[0].update_info_and_price_info() _, _, _, price_rank = homes[0].current_price_data() assert isinstance(price_rank, int), "Price rank was unset" assert 1 <= price_rank <= 24, "Price rank is out of range" @pytest.mark.asyncio async def test_tibber_get_historic_data(): async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( websession=session, user_agent="test", ) await tibber_connection.update_info() homes = tibber_connection.get_homes() assert len(homes) == 1, f"Expected 1 home, got '{len(homes)}'" home = homes[0] assert home is not None historic_data = await home.get_historic_data_date(dt.datetime(2024, 1, 1, tzinfo=dt.UTC), 5, RESOLUTION_DAILY) assert len(historic_data) == 5 assert historic_data[0]["from"] == "2024-01-01T00:00:00.000+01:00", "First day must be 2024-01-01" assert historic_data[4]["from"] == "2024-01-05T00:00:00.000+01:00", "Last day must be 2024-01-05" @pytest.mark.asyncio async def test_logging_rt_subscribe(caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.INFO) async with aiohttp.ClientSession() as session: tibber_connection = tibber.Tibber( websession=session, user_agent="test", ) await tibber_connection.update_info() home = tibber_connection.get_homes()[0] def _callback(_: dict) -> None: return None await home.rt_subscribe(_callback) await asyncio.sleep(1) home.rt_unsubscribe() await tibber_connection.rt_disconnect() await asyncio.sleep(10) assert "gql.transport.websockets:websockets_base.py:240" not in caplog.text, "should not show on info logging level" assert "gql.transport.websockets:websockets_base.py:218" not in caplog.text, "should not show on info logging level" Danielhiversen-pyTibber-c94895e/tibber/000077500000000000000000000000001502770006000200505ustar00rootroot00000000000000Danielhiversen-pyTibber-c94895e/tibber/__init__.py000066400000000000000000000211471502770006000221660ustar00rootroot00000000000000"""Library to handle connection with Tibber API.""" import asyncio import datetime as dt import logging from ssl import SSLContext from typing import Any import aiohttp from .const import API_ENDPOINT, DEFAULT_TIMEOUT, DEMO_TOKEN, __version__ from .exceptions import ( FatalHttpExceptionError, InvalidLoginError, RetryableHttpExceptionError, UserAgentMissingError, ) from .gql_queries import INFO, PUSH_NOTIFICATION from .home import TibberHome from .realtime import TibberRT from .response_handler import extract_response_data _LOGGER = logging.getLogger(__name__) class Tibber: """Class to communicate with the Tibber api.""" def __init__( self, access_token: str = DEMO_TOKEN, timeout: int = DEFAULT_TIMEOUT, websession: aiohttp.ClientSession | None = None, time_zone: dt.tzinfo | None = None, user_agent: str | None = None, ssl: SSLContext | bool = True, ) -> None: """Initialize the Tibber connection. :param access_token: The access token to access the Tibber API with. :param timeout: The timeout in seconds to use when communicating with the Tibber API. :param websession: The websession to use when communicating with the Tibber API. :param time_zone: The time zone to display times in and to use. :param user_agent: User agent identifier for the platform running this. Required if websession is None. :param ssl: SSLContext to use. """ if websession is None: websession = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=ssl)) elif user_agent is None: user_agent = websession.headers.get(aiohttp.hdrs.USER_AGENT) if user_agent is None: raise UserAgentMissingError("Please provide value for HTTP user agent") self._user_agent: str = f"{user_agent} pyTibber/{__version__} " self.websession = websession self.timeout: int = timeout self._access_token: str = access_token self.realtime: TibberRT = TibberRT( self._access_token, self.timeout, self._user_agent, ssl=ssl, ) self.time_zone: dt.tzinfo = time_zone or dt.UTC self._name: str = "" self._user_id: str | None = None self._active_home_ids: list[str] = [] self._all_home_ids: list[str] = [] self._homes: dict[str, TibberHome] = {} async def close_connection(self) -> None: """Close the Tibber connection. This method simply closes the websession used by the object. """ await self.websession.close() async def execute( self, document: str, variable_values: dict[Any, Any] | None = None, timeout: int | None = None, # noqa: ASYNC109 retry: int = 3, ) -> dict[Any, Any] | None: """Execute a GraphQL query and return the data. :param document: The GraphQL query to request. :param variable_values: The GraphQL variables to parse with the request. :param timeout: The timeout to use for the request. :param retry: The number of times to retry the request. """ timeout = timeout or self.timeout payload = {"query": document, "variables": variable_values or {}} try: resp = await self.websession.post( API_ENDPOINT, headers={ "Authorization": "Bearer " + self._access_token, aiohttp.hdrs.USER_AGENT: self._user_agent, }, data=payload, timeout=aiohttp.ClientTimeout(total=self.timeout), ) return (await extract_response_data(resp)).get("data") except (TimeoutError, aiohttp.ClientError) as err: if retry > 0: return await self.execute( document, variable_values, timeout, retry - 1, ) if isinstance(err, asyncio.TimeoutError): _LOGGER.error("Timed out when connecting to Tibber") else: _LOGGER.exception("Error connecting to Tibber") raise except (InvalidLoginError, FatalHttpExceptionError) as err: _LOGGER.error( "Fatal error interacting with Tibber API, HTTP status: %s. API error: %s / %s", err.status, err.extension_code, err.message, ) raise except RetryableHttpExceptionError as err: _LOGGER.warning( "Temporary failure interacting with Tibber API, HTTP status: %s. API error: %s / %s", err.status, err.extension_code, err.message, ) raise async def update_info(self) -> None: """Updates home info asynchronously.""" if (data := await self.execute(INFO)) is None: return if not (viewer := data.get("viewer")): return if sub_endpoint := viewer.get("websocketSubscriptionUrl"): _LOGGER.debug("Using websocket subscription url %s", sub_endpoint) self.realtime.sub_endpoint = sub_endpoint self._name = viewer.get("name") self._user_id = viewer.get("userId") self._active_home_ids = [] for _home in viewer.get("homes", []): if not (home_id := _home.get("id")): continue self._all_home_ids += [home_id] if not (subs := _home.get("subscriptions")): continue if subs[0].get("status") is not None and subs[0]["status"].lower() == "running": self._active_home_ids += [home_id] def get_home_ids(self, only_active: bool = True) -> list[str]: """Return list of home ids.""" if only_active: return self._active_home_ids return self._all_home_ids def get_homes(self, only_active: bool = True) -> list[TibberHome]: """Return list of Tibber homes.""" return [home for home_id in self.get_home_ids(only_active) if (home := self.get_home(home_id))] def get_home(self, home_id: str) -> TibberHome | None: """Return an instance of TibberHome for given home id.""" if home_id not in self._all_home_ids: _LOGGER.error("Could not find any Tibber home with id: %s", home_id) return None if home_id not in self._homes: self._homes[home_id] = TibberHome(home_id, self) return self._homes[home_id] async def send_notification(self, title: str, message: str) -> bool: """Sends a push notification to the Tibber app on registered devices. :param title: The title of the push notification. :param message: The message of the push notification. """ if not ( res := await self.execute( PUSH_NOTIFICATION.format( title, message, ), ) ): return False notification = res.get("sendPushNotification", {}) successful = notification.get("successful", False) pushed_to_number_of_devices = notification.get("pushedToNumberOfDevices", 0) _LOGGER.debug( "send_notification: status %s, send to %s devices", successful, pushed_to_number_of_devices, ) return successful async def fetch_consumption_data_active_homes(self) -> None: """Fetch consumption data for active homes.""" await asyncio.gather( *[tibber_home.fetch_consumption_data() for tibber_home in self.get_homes(only_active=True)], ) async def fetch_production_data_active_homes(self) -> None: """Fetch production data for active homes.""" await asyncio.gather( *[ tibber_home.fetch_production_data() for tibber_home in self.get_homes(only_active=True) if tibber_home.has_production ], ) async def rt_disconnect(self) -> None: """Stop subscription manager. This method simply calls the stop method of the SubscriptionManager if it is defined. """ return await self.realtime.disconnect() @property def user_id(self) -> str | None: """Return user id of user.""" return self._user_id @property def name(self) -> str: """Return name of user.""" return self._name @property def home_ids(self) -> list[str]: """Return list of home ids.""" return self.get_home_ids(only_active=True) Danielhiversen-pyTibber-c94895e/tibber/const.py000066400000000000000000000013121502770006000215450ustar00rootroot00000000000000"""Constants used by pyTibber""" from http import HTTPStatus from typing import Final __version__ = "0.31.6" API_ENDPOINT: Final = "https://api.tibber.com/v1-beta/gql" DEFAULT_TIMEOUT: Final = 10 DEMO_TOKEN: Final = "3A77EECF61BD445F47241A5A36202185C35AF3AF58609E19B53F3A8872AD7BE1-1" RESOLUTION_HOURLY: Final = "HOURLY" RESOLUTION_DAILY: Final = "DAILY" RESOLUTION_WEEKLY: Final = "WEEKLY" RESOLUTION_MONTHLY: Final = "MONTHLY" RESOLUTION_ANNUAL: Final = "ANNUAL" API_ERR_CODE_UNKNOWN: Final = "UNKNOWN" API_ERR_CODE_UNAUTH: Final = "UNAUTHENTICATED" HTTP_CODES_RETRIABLE: Final = [ HTTPStatus.TOO_MANY_REQUESTS, HTTPStatus.PRECONDITION_REQUIRED, ] HTTP_CODES_FATAL: Final = [HTTPStatus.BAD_REQUEST] Danielhiversen-pyTibber-c94895e/tibber/exceptions.py000066400000000000000000000023731502770006000226100ustar00rootroot00000000000000"""Exceptions""" from .const import API_ERR_CODE_UNKNOWN class SubscriptionEndpointMissingError(Exception): """Exception raised when subscription endpoint is missing""" class UserAgentMissingError(Exception): """Exception raised when user agent is missing""" class HttpExceptionError(Exception): """Exception base for HTTP errors :param status: http response code :param message: http response message if any :param extension_code: http response extension if any """ def __init__( self, status: int, message: str = "HTTP error", extension_code: str = API_ERR_CODE_UNKNOWN, ) -> None: self.status = status self.message = message self.extension_code = extension_code super().__init__(self.message) class FatalHttpExceptionError(HttpExceptionError): """Exception raised for HTTP codes that are non-retriable""" class RetryableHttpExceptionError(HttpExceptionError): """Exception raised for HTTP codes that are possible to retry""" class InvalidLoginError(FatalHttpExceptionError): """Invalid login exception.""" class NotForDemoUserError(FatalHttpExceptionError): """Exception raised when trying to use a feature not available for demo users""" Danielhiversen-pyTibber-c94895e/tibber/gql_queries.py000066400000000000000000000157661502770006000227610ustar00rootroot00000000000000"""Gql queries""" HISTORIC_DATA = """ {{ viewer {{ home(id: "{0}") {{ {1}(resolution: {2}, last: {3}, before: "{5}") {{ pageInfo {{ hasPreviousPage startCursor }} nodes {{ from unitPrice {4} {1} }} }} }} }} }} """ HISTORIC_DATA_DATE = """ {{ viewer {{ home(id: "{0}") {{ {1}(resolution: {2}, first: {3}, after: "{4}") {{ nodes {{ from to unitPrice unitPriceVAT currency {5} }} }} }} }} }} """ HISTORIC_PRICE = """ {{ viewer {{ home(id: "{0}") {{ currentSubscription {{ priceRating {{ {1} {{ entries {{ time total }} }} }} }} }} }} }} """ INFO = """ { viewer { name userId homes { id subscriptions { status } } websocketSubscriptionUrl } } """ LIVE_SUBSCRIBE = """ subscription{ liveMeasurement(homeId:"%s"){ accumulatedConsumption accumulatedConsumptionLastHour accumulatedCost accumulatedProduction accumulatedProductionLastHour accumulatedReward averagePower currency currentL1 currentL2 currentL3 lastMeterConsumption lastMeterProduction maxPower minPower power powerFactor powerProduction powerReactive signalStrength timestamp voltagePhase1 voltagePhase2 voltagePhase3 } } """ PUSH_NOTIFICATION = """ mutation{{ sendPushNotification(input: {{ title: "{}", message: "{}", }}){{ successful pushedToNumberOfDevices }} }} """ UPDATE_CURRENT_PRICE = """ { viewer { home(id: "%s") { currentSubscription { priceInfo { current { energy tax total startsAt } } } } } } """ UPDATE_INFO = """ { viewer { home(id: "%s") { appNickname features { realTimeConsumptionEnabled } currentSubscription { status } address { address1 address2 address3 city postalCode country latitude longitude } meteringPointData { consumptionEan energyTaxType estimatedAnnualConsumption gridCompany productionEan vatType } owner { name isCompany language contactInfo { email mobile } } timeZone subscriptions { id status validFrom validTo statusReason } currentSubscription { priceInfo { current { currency } } } } } } """ UPDATE_INFO_PRICE = """ { viewer { home(id: "%s") { currentSubscription { priceInfo { current { energy tax total startsAt level } today { total startsAt level } tomorrow { total startsAt level } } } appNickname features { realTimeConsumptionEnabled } currentSubscription { status } address { address1 address2 address3 city postalCode country latitude longitude } meteringPointData { consumptionEan energyTaxType estimatedAnnualConsumption gridCompany productionEan vatType } owner { name isCompany language contactInfo { email mobile } } timeZone subscriptions { id status validFrom validTo statusReason } currentSubscription { priceInfo { current { currency } } } } } } """ PRICE_INFO = """ { viewer { home(id: "%s") { currentSubscription { priceRating { hourly { currency entries { time total energy level } } } } } } } """ Danielhiversen-pyTibber-c94895e/tibber/home.py000066400000000000000000000622371502770006000213640ustar00rootroot00000000000000"""Tibber home""" from __future__ import annotations import asyncio import base64 import contextlib import datetime as dt import logging from typing import TYPE_CHECKING, Any from gql import gql from .const import RESOLUTION_HOURLY from .gql_queries import ( HISTORIC_DATA, HISTORIC_DATA_DATE, HISTORIC_PRICE, LIVE_SUBSCRIBE, PRICE_INFO, UPDATE_CURRENT_PRICE, UPDATE_INFO_PRICE, ) MIN_IN_HOUR = 60 if TYPE_CHECKING: from collections.abc import Callable from . import Tibber _LOGGER = logging.getLogger(__name__) class HourlyData: """Holds hourly data for consumption or production.""" def __init__(self, production: bool = False) -> None: self.is_production: bool = production self.month_energy: float | None = None self.month_money: float | None = None self.peak_hour: float | None = None self.peak_hour_time: dt.datetime | None = None self.last_data_timestamp: dt.datetime | None = None self.data: list[dict[Any, Any]] = [] @property def direction_name(self) -> str: """Return the direction name.""" if self.is_production: return "production" return "consumption" @property def money_name(self) -> str: """Return the money name.""" if self.is_production: return "profit" return "cost" class TibberHome: """Instance of Tibber home.""" def __init__(self, home_id: str, tibber_control: Tibber) -> None: """Initialize the Tibber home class. :param home_id: The ID of the home. :param tibber_control: The Tibber instance associated with this instance of TibberHome. """ self._tibber_control = tibber_control self._home_id: str = home_id self._current_price_total: float | None = None self._current_price_info: dict[str, float] = {} self._price_info: dict[str, float] = {} self._level_info: dict[str, str] = {} self._rt_power: list[tuple[dt.datetime, float]] = [] self.info: dict[str, dict[Any, Any]] = {} self.last_data_timestamp: dt.datetime | None = None self._hourly_consumption_data: HourlyData = HourlyData() self._hourly_production_data: HourlyData = HourlyData(production=True) self._last_rt_data_received: dt.datetime = dt.datetime.now(tz=dt.UTC) self._rt_listener: None | asyncio.Task[Any] = None self._rt_callback: Callable[..., Any] | None = None self._rt_stopped: bool = True self._has_real_time_consumption: None | bool = None self._real_time_consumption_suggested_disabled: dt.datetime | None = None async def _fetch_data(self, hourly_data: HourlyData) -> None: """Update hourly consumption or production data asynchronously.""" now = dt.datetime.now(tz=dt.UTC) local_now = now.astimezone(self._tibber_control.time_zone) n_hours = 60 * 24 if ( not hourly_data.data or hourly_data.last_data_timestamp is None or dt.datetime.fromisoformat(hourly_data.data[0]["from"]) < now - dt.timedelta(hours=n_hours + 24) ): hourly_data.data = [] else: time_diff = now - hourly_data.last_data_timestamp seconds_diff = time_diff.total_seconds() n_hours = int(seconds_diff / 3600) if n_hours < 1: return n_hours = max(2, int(n_hours)) data = await self.get_historic_data( n_hours, resolution=RESOLUTION_HOURLY, production=hourly_data.is_production, ) if not data: _LOGGER.error("Could not find %s data.", hourly_data.direction_name) return if not hourly_data.data: hourly_data.data = data else: hourly_data.data = [entry for entry in hourly_data.data if entry not in data] hourly_data.data.extend(data) _month_energy = 0 _month_money = 0 _month_hour_max_month_hour_energy = 0 _month_hour_max_month_hour: dt.datetime | None = None for node in hourly_data.data: _time = dt.datetime.fromisoformat(node["from"]) if _time.month != local_now.month or _time.year != local_now.year: continue if (energy := node.get(hourly_data.direction_name)) is None: continue if ( hourly_data.last_data_timestamp is None or _time + dt.timedelta(hours=1) > hourly_data.last_data_timestamp ): hourly_data.last_data_timestamp = _time + dt.timedelta(hours=1) if energy > _month_hour_max_month_hour_energy: _month_hour_max_month_hour_energy = energy _month_hour_max_month_hour = _time _month_energy += energy if node.get(hourly_data.money_name) is not None: _month_money += node[hourly_data.money_name] hourly_data.month_energy = round(_month_energy, 2) hourly_data.month_money = round(_month_money, 2) hourly_data.peak_hour = round(_month_hour_max_month_hour_energy, 2) hourly_data.peak_hour_time = _month_hour_max_month_hour async def fetch_consumption_data(self) -> None: """Update consumption info asynchronously.""" return await self._fetch_data(self._hourly_consumption_data) async def fetch_production_data(self) -> None: """Update consumption info asynchronously.""" return await self._fetch_data(self._hourly_production_data) @property def month_cons(self) -> float | None: """Get consumption for current month.""" return self._hourly_consumption_data.month_energy @property def month_cost(self) -> float | None: """Get total cost for current month.""" return self._hourly_consumption_data.month_money @property def peak_hour(self) -> float | None: """Get consumption during peak hour for the current month.""" return self._hourly_consumption_data.peak_hour @property def peak_hour_time(self) -> dt.datetime | None: """Get the time for the peak consumption during the current month.""" return self._hourly_consumption_data.peak_hour_time @property def last_cons_data_timestamp(self) -> dt.datetime | None: """Get last consumption data timestampt.""" return self._hourly_consumption_data.last_data_timestamp @property def hourly_consumption_data(self) -> list[dict[Any, Any]]: """Get consumption data for the last 30 days.""" return self._hourly_consumption_data.data @property def hourly_production_data(self) -> list[dict[Any, Any]]: """Get production data for the last 30 days.""" return self._hourly_production_data.data async def update_info(self) -> None: """Update home info and the current price info asynchronously.""" await self.update_info_and_price_info() async def update_info_and_price_info(self) -> None: """Update home info and all price info asynchronously.""" if data := await self._tibber_control.execute(UPDATE_INFO_PRICE % self._home_id): self.info = data self._update_has_real_time_consumption() if self.has_active_subscription: await self.update_price_info() def _update_has_real_time_consumption(self) -> None: try: _has_real_time_consumption = self.info["viewer"]["home"]["features"]["realTimeConsumptionEnabled"] except (KeyError, TypeError): self._has_real_time_consumption = None return if self._has_real_time_consumption is None: self._has_real_time_consumption = _has_real_time_consumption return if self._has_real_time_consumption is True and _has_real_time_consumption is False: now = dt.datetime.now(tz=dt.UTC) if self._real_time_consumption_suggested_disabled is None: self._real_time_consumption_suggested_disabled = now self._has_real_time_consumption = None elif now - self._real_time_consumption_suggested_disabled > dt.timedelta(hours=1): self._real_time_consumption_suggested_disabled = None self._has_real_time_consumption = False else: self._has_real_time_consumption = None return if _has_real_time_consumption is True: self._real_time_consumption_suggested_disabled = None self._has_real_time_consumption = _has_real_time_consumption async def update_current_price_info(self) -> None: """Update just the current price info asynchronously.""" query = UPDATE_CURRENT_PRICE % self.home_id price_info_temp = await self._tibber_control.execute(query) if not price_info_temp: _LOGGER.error("Could not find current price info.") return try: home = price_info_temp["viewer"]["home"] current_subscription = home["currentSubscription"] price_info = current_subscription["priceInfo"]["current"] except (KeyError, TypeError): _LOGGER.error("Could not find current price info.") return if price_info: self._current_price_info = price_info async def update_price_info(self, retry: bool = True) -> None: """Update the current price info, todays price info and tomorrows price info asynchronously. """ price_info = await self._tibber_control.execute(PRICE_INFO % self.home_id) if not price_info: if self.has_active_subscription: if retry: _LOGGER.debug("Could not find price info. Retrying...") return await self.update_price_info(retry=False) _LOGGER.error("Could not find price info.") return None data = price_info["viewer"]["home"]["currentSubscription"]["priceRating"]["hourly"]["entries"] if not data: if self.has_active_subscription: if retry: _LOGGER.debug("Could not find price info data. Retrying...") return await self.update_price_info(retry=False) _LOGGER.error("Could not find price info data. %s", price_info) return None self._price_info = {} self._level_info = {} for row in data: self._price_info[row.get("time")] = row.get("total") self._level_info[row.get("time")] = row.get("level") self.last_data_timestamp = dt.datetime.fromisoformat(data[-1]["time"]) return None @property def current_price_total(self) -> float | None: """Get current price total.""" if not self._current_price_info: return None return self._current_price_info.get("total") @property def current_price_info(self) -> dict[str, float]: """Get current price info.""" return self._current_price_info @property def price_total(self) -> dict[str, float]: """Get dictionary with price total, key is date-time as a string.""" return self._price_info @property def price_level(self) -> dict[str, str]: """Get dictionary with price level, key is date-time as a string.""" return self._level_info @property def home_id(self) -> str: """Return home id.""" return self._home_id @property def has_active_subscription(self) -> bool: """Return home id.""" try: sub = self.info["viewer"]["home"]["currentSubscription"]["status"] except (KeyError, TypeError): return False return sub in [ "running", "awaiting market", "awaiting time restriction", "awaiting termination", ] @property def has_real_time_consumption(self) -> None | bool: """Return home id.""" return self._has_real_time_consumption @property def has_production(self) -> bool: """Return true if the home has a production metering point.""" try: return bool(self.info["viewer"]["home"]["meteringPointData"]["productionEan"]) except (KeyError, TypeError): return False @property def address1(self) -> str: """Return the home adress1.""" try: return self.info["viewer"]["home"]["address"]["address1"] except (KeyError, TypeError): _LOGGER.error("Could not find address1.") return "" @property def consumption_unit(self) -> str: """Return the consumption unit.""" return "kWh" @property def currency(self) -> str: """Return the currency.""" try: return self.info["viewer"]["home"]["currentSubscription"]["priceInfo"]["current"]["currency"] except (KeyError, TypeError, IndexError): _LOGGER.error("Could not find currency.") return "" @property def country(self) -> str: """Return the country.""" try: return self.info["viewer"]["home"]["address"]["country"] except (KeyError, TypeError): _LOGGER.error("Could not find country.") return "" @property def name(self) -> str: """Return the name.""" try: return self.info["viewer"]["home"]["appNickname"] except (KeyError, TypeError): return self.info["viewer"]["home"]["address"].get("address1", "") @property def price_unit(self) -> str: """Return the price unit (e.g. NOK/kWh).""" if not self.currency or not self.consumption_unit: _LOGGER.error("Could not find price_unit.") return "" return self.currency + "/" + self.consumption_unit def current_price_rank(self, price_total: dict[str, float], price_time: dt.datetime | None) -> int | None: """Gets the rank (1-24) of how expensive the current price is compared to the other prices today.""" # No price -> no rank if price_time is None: return None # Map price_total to a list of tuples (datetime, float) price_items_typed: list[tuple[dt.datetime, float]] = [ ( dt.datetime.fromisoformat(time).astimezone(self._tibber_control.time_zone), price, ) for time, price in price_total.items() ] # Filter out prices not from today, sort by price prices_today_sorted = sorted( [item for item in price_items_typed if item[0].date() == price_time.date()], key=lambda x: x[1], ) # Find the rank of the current price try: price_rank = next(idx for idx, item in enumerate(prices_today_sorted, start=1) if item[0] == price_time) except StopIteration: price_rank = None return price_rank def current_price_data(self) -> tuple[float | None, str | None, dt.datetime | None, int | None]: """Get current price.""" now = dt.datetime.now(self._tibber_control.time_zone) for key, price_total in self.price_total.items(): price_time = dt.datetime.fromisoformat(key).astimezone(self._tibber_control.time_zone) time_diff = (now - price_time).total_seconds() / MIN_IN_HOUR if 0 <= time_diff < MIN_IN_HOUR: price_rank = self.current_price_rank(self.price_total, price_time) return round(price_total, 3), self.price_level[key], price_time, price_rank return None, None, None, None async def rt_subscribe(self, callback: Callable[..., Any]) -> None: """Connect to Tibber and subscribe to Tibber real time subscription. :param callback: The function to call when data is received. """ def _add_extra_data(data: dict[str, Any]) -> dict[str, Any]: live_data = data["data"]["liveMeasurement"] _timestamp = dt.datetime.fromisoformat(live_data["timestamp"]).astimezone(self._tibber_control.time_zone) while self._rt_power and self._rt_power[0][0] < _timestamp - dt.timedelta(minutes=5): self._rt_power.pop(0) self._rt_power.append((_timestamp, live_data["power"] / 1000)) if "lastMeterProduction" in live_data: live_data["lastMeterProduction"] = max(0, live_data["lastMeterProduction"] or 0) if ( (power_production := live_data.get("powerProduction")) and power_production > 0 and live_data.get("power") is None ): live_data["power"] = 0 if live_data.get("power", 0) > 0 and live_data.get("powerProduction") is None: live_data["powerProduction"] = 0 current_hour = live_data["accumulatedConsumptionLastHour"] if current_hour is not None: power = sum(p[1] for p in self._rt_power) / len(self._rt_power) live_data["estimatedHourConsumption"] = round( current_hour + power * (3600 - (_timestamp.minute * 60 + _timestamp.second)) / 3600, 3, ) if self._hourly_consumption_data.peak_hour and current_hour > self._hourly_consumption_data.peak_hour: self._hourly_consumption_data.peak_hour = round(current_hour, 2) self._hourly_consumption_data.peak_hour_time = _timestamp return data async def _start() -> None: """Subscribe to Tibber.""" for _ in range(30): if self._rt_stopped: _LOGGER.debug("Stopping rt_subscribe") return if self._tibber_control.realtime.subscription_running: break _LOGGER.debug("Waiting for rt_connect") await asyncio.sleep(1) else: _LOGGER.error("rt not running") return try: async for _data in self._tibber_control.realtime.sub_manager.session.subscribe( gql(LIVE_SUBSCRIBE % self.home_id), ): data = {"data": _data} with contextlib.suppress(KeyError): data = _add_extra_data(data) callback(data) self._last_rt_data_received = dt.datetime.now(tz=dt.UTC) _LOGGER.debug( "Data received for %s: %s", self.home_id, data, ) if self._rt_stopped or not self._tibber_control.realtime.subscription_running: _LOGGER.debug("Stopping rt_subscribe loop") return except Exception: _LOGGER.exception("Error in rt_subscribe") self._rt_callback = callback self._tibber_control.realtime.add_home(self) await self._tibber_control.realtime.connect() self._rt_listener = asyncio.create_task(_start()) self._rt_stopped = False async def rt_resubscribe(self) -> None: """Resubscribe to Tibber data.""" self.rt_unsubscribe() _LOGGER.debug("Resubscribe, %s", self.home_id) await asyncio.gather( *[ self.update_info(), self._tibber_control.update_info(), ], return_exceptions=False, ) if self._rt_callback is None: _LOGGER.warning("No callback set for rt_resubscribe") return await self.rt_subscribe(self._rt_callback) def rt_unsubscribe(self) -> None: """Unsubscribe to Tibber data.""" _LOGGER.debug("Unsubscribe, %s", self.home_id) self._rt_stopped = True if self._rt_listener is None: return self._rt_listener.cancel() self._rt_listener = None @property def rt_subscription_running(self) -> bool: """Is real time subscription running.""" if not self._tibber_control.realtime.subscription_running: return False return not self._last_rt_data_received < dt.datetime.now(tz=dt.UTC) - dt.timedelta(seconds=60) async def get_historic_data( self, n_data: int, resolution: str = RESOLUTION_HOURLY, production: bool = False, ) -> list[dict[str, Any]]: """Get historic data. :param n_data: The number of nodes to get from history. e.g. 5 would give 5 nodes and resolution = hourly would give the 5 last hours of historic data :param resolution: The resolution of the data. Can be HOURLY, DAILY, WEEKLY, MONTHLY or ANNUAL :param production: True to get production data instead of consumption """ cons_or_prod_str = "production" if production else "consumption" query = HISTORIC_DATA.format( self.home_id, cons_or_prod_str, resolution, n_data, "profit" if production else "totalCost cost", "", ) if not (data := await self._tibber_control.execute(query, timeout=30)): _LOGGER.error("Could not get the data.") return [] data = data["viewer"]["home"][cons_or_prod_str] if data is None: return [] return data["nodes"] async def get_historic_data_date( self, date_from: dt.datetime, n_data: int, resolution: str = RESOLUTION_HOURLY, production: bool = False, ) -> list[dict[str, Any]]: """Get historic data. :param date_from: The start-date to get the data from :param n_data: The number of nodes to get from history. e.g. 5 would give 5 nodes and resolution = hourly would give the 5 last hours of historic data. If 0 the set month-days will be calculated to the end of the month. :param resolution: The resolution of the data. Can be HOURLY, DAILY, WEEKLY, MONTHLY or ANNUAL :param production: True to get production data instead of consumption """ date_from_base64 = base64.b64encode(date_from.strftime("%Y-%m-%d").encode()).decode("utf-8") if n_data == 0: # Calculate the number of days to the end of the month from the given date n_data = (date_from.replace(day=1, month=date_from.month + 1) - date_from).days cons_or_prod_str = "production" if production else "consumption" query = HISTORIC_DATA_DATE.format( self.home_id, cons_or_prod_str, resolution, n_data, date_from_base64, "profit production productionUnit" if production else "cost consumption consumptionUnit", ) if not (data := await self._tibber_control.execute(query, timeout=30)): _LOGGER.error("Could not get the data.") return [] data = data["viewer"]["home"][cons_or_prod_str] if data is None: return [] return data["nodes"] async def get_historic_price_data( self, resolution: str = RESOLUTION_HOURLY, ) -> list[dict[Any, Any]] | None: """Get historic price data. :param resolution: The resolution of the data. Can be HOURLY, DAILY, WEEKLY, MONTHLY or ANNUAL """ resolution = resolution.lower() query = HISTORIC_PRICE.format( self.home_id, resolution, ) if not (data := await self._tibber_control.execute(query)): _LOGGER.error("Could not get the price data.") return None return data["viewer"]["home"]["currentSubscription"]["priceRating"][resolution]["entries"] def current_attributes(self) -> dict[str, float]: """Get current attributes.""" max_price = 0.0 min_price = 10000.0 sum_price = 0.0 off_peak_1 = 0.0 peak = 0.0 off_peak_2 = 0.0 num1 = 0.0 num0 = 0.0 num2 = 0.0 num = 0.0 now = dt.datetime.now(self._tibber_control.time_zone) for key, _price_total in self.price_total.items(): price_time = dt.datetime.fromisoformat(key).astimezone(self._tibber_control.time_zone) price_total = round(_price_total, 3) if now.date() == price_time.date(): max_price = max(max_price, price_total) min_price = min(min_price, price_total) if price_time.hour < 8: # noqa: PLR2004 off_peak_1 += price_total num1 += 1 elif price_time.hour < 20: # noqa: PLR2004 peak += price_total num0 += 1 else: off_peak_2 += price_total num2 += 1 num += 1 sum_price += price_total attr = {} attr["max_price"] = max_price attr["avg_price"] = round(sum_price / num, 3) if num > 0 else 0 attr["min_price"] = min_price attr["off_peak_1"] = round(off_peak_1 / num1, 3) if num1 > 0 else 0 attr["peak"] = round(peak / num0, 3) if num0 > 0 else 0 attr["off_peak_2"] = round(off_peak_2 / num2, 3) if num2 > 0 else 0 return attr Danielhiversen-pyTibber-c94895e/tibber/py.typed000066400000000000000000000000001502770006000215350ustar00rootroot00000000000000Danielhiversen-pyTibber-c94895e/tibber/realtime.py000066400000000000000000000167341502770006000222370ustar00rootroot00000000000000"""Tibber RT connection.""" import asyncio import datetime as dt import logging import random from ssl import SSLContext from typing import Any from gql import Client from gql.transport.websockets import log as websockets_logger from .exceptions import SubscriptionEndpointMissingError from .home import TibberHome from .websocket_transport import TibberWebsocketsTransport LOCK_CONNECT = asyncio.Lock() _LOGGER = logging.getLogger(__name__) websockets_logger.setLevel(logging.WARNING) class TibberRT: """Class to handle real time connection with the Tibber api.""" def __init__(self, access_token: str, timeout: int, user_agent: str, ssl: SSLContext | bool) -> None: """Initialize the Tibber connection. :param access_token: The access token to access the Tibber API with. :param timeout: The timeout in seconds to use when communicating with the Tibber API. :param user_agent: User agent identifier for the platform running this. Required if websession is None. """ self._access_token: str = access_token self._timeout: int = timeout self._user_agent: str = user_agent self._ssl_context = ssl self._sub_endpoint: str | None = None self._homes: list[TibberHome] = [] self._watchdog_runner: None | asyncio.Task[Any] = None self._watchdog_running: bool = False self.sub_manager: Client | None = None async def disconnect(self) -> None: """Stop subscription manager. This method simply calls the stop method of the SubscriptionManager if it is defined. """ _LOGGER.debug("Stopping subscription manager") if self._watchdog_runner is not None: _LOGGER.debug("Stopping watchdog") self._watchdog_running = False self._watchdog_runner.cancel() self._watchdog_runner = None for home in self._homes: home.rt_unsubscribe() if self.sub_manager is None: return try: if not hasattr(self.sub_manager, "session"): return await self.sub_manager.close_async() finally: self.sub_manager = None async def connect(self) -> None: """Start subscription manager.""" self._create_sub_manager() assert self.sub_manager is not None async with LOCK_CONNECT: if self.subscription_running: return if self._watchdog_runner is None: _LOGGER.debug("Starting watchdog") self._watchdog_running = True self._watchdog_runner = asyncio.create_task(self._watchdog()) await self.sub_manager.connect_async() def _create_sub_manager(self) -> None: if self.sub_endpoint is None: raise SubscriptionEndpointMissingError("Subscription endpoint not initialized") if self.sub_manager is not None: return self.sub_manager = Client( transport=TibberWebsocketsTransport( self.sub_endpoint, self._access_token, self._user_agent, ssl=self._ssl_context, ), ) async def _watchdog(self) -> None: """Watchdog to keep connection alive.""" assert self.sub_manager is not None assert isinstance(self.sub_manager.transport, TibberWebsocketsTransport) await asyncio.sleep(60) _retry_count = 0 next_test_all_homes_running = dt.datetime.now(tz=dt.UTC) while self._watchdog_running: await asyncio.sleep(5) if ( self.sub_manager.transport.running and self.sub_manager.transport.reconnect_at > dt.datetime.now( tz=dt.UTC, ) and dt.datetime.now(tz=dt.UTC) > next_test_all_homes_running ): is_running = True for home in self._homes: _LOGGER.debug( "Watchdog: Checking if home %s is alive, %s, %s", home.home_id, home.has_real_time_consumption, home.rt_subscription_running, ) if not home.rt_subscription_running: is_running = False next_test_all_homes_running = dt.datetime.now(tz=dt.UTC) + dt.timedelta(seconds=60) break _LOGGER.debug( "Watchdog: Home %s is alive", home.home_id, ) if is_running: _retry_count = 0 _LOGGER.debug("Watchdog: Connection is alive") continue self.sub_manager.transport.reconnect_at = dt.datetime.now(tz=dt.UTC) + dt.timedelta(seconds=self._timeout) _LOGGER.error( "Watchdog: Connection is down, %s", self.sub_manager.transport.reconnect_at, ) try: if hasattr(self.sub_manager, "session"): await self.sub_manager.close_async() except Exception: _LOGGER.exception("Error in watchdog close") if not self._watchdog_running: _LOGGER.debug("Watchdog: Stopping") return self._create_sub_manager() try: await self.sub_manager.connect_async() await self._resubscribe_homes() except Exception as err: # noqa: BLE001 delay_seconds = min( random.SystemRandom().randint(1, 30) + _retry_count**2, 5 * 60, ) _retry_count += 1 _LOGGER.error( "Error in watchdog connect, retrying in %s seconds, %s: %s", delay_seconds, _retry_count, err, exc_info=_retry_count > 1, ) await asyncio.sleep(delay_seconds) else: _LOGGER.debug("Watchdog: Reconnected successfully") await asyncio.sleep(60) async def _resubscribe_homes(self) -> None: """Resubscribe to all homes.""" _LOGGER.debug("Resubscribing to homes") await asyncio.gather(*[home.rt_resubscribe() for home in self._homes]) def add_home(self, home: TibberHome) -> bool: """Add home to real time subscription.""" if home.has_real_time_consumption is False: return False if home in self._homes: return False self._homes.append(home) return True @property def subscription_running(self) -> bool: """Is real time subscription running.""" return ( self.sub_manager is not None and isinstance(self.sub_manager.transport, TibberWebsocketsTransport) and self.sub_manager.transport.running and hasattr(self.sub_manager, "session") ) @property def sub_endpoint(self) -> str | None: """Get subscription endpoint.""" return self._sub_endpoint @sub_endpoint.setter def sub_endpoint(self, sub_endpoint: str) -> None: """Set subscription endpoint.""" self._sub_endpoint = sub_endpoint if self.sub_manager is not None and isinstance(self.sub_manager.transport, TibberWebsocketsTransport): self.sub_manager.transport.url = sub_endpoint Danielhiversen-pyTibber-c94895e/tibber/response_handler.py000066400000000000000000000056001502770006000237560ustar00rootroot00000000000000"""Tibber API response handler""" import logging from http import HTTPStatus from typing import Any from aiohttp import ClientResponse from .const import ( API_ERR_CODE_UNAUTH, API_ERR_CODE_UNKNOWN, HTTP_CODES_FATAL, HTTP_CODES_RETRIABLE, ) from .exceptions import ( FatalHttpExceptionError, InvalidLoginError, NotForDemoUserError, RetryableHttpExceptionError, ) _LOGGER = logging.getLogger(__name__) def extract_error_details(errors: list[Any], default_message: str) -> tuple[str, str]: """Tries to extract the error message and code from the provided 'errors' dictionary""" if not errors: return API_ERR_CODE_UNKNOWN, default_message return errors[0].get("extensions").get("code"), errors[0].get("message") async def extract_response_data(response: ClientResponse) -> dict[Any, Any]: """Extracts the response as JSON or throws a HttpException""" _LOGGER.debug("Response status: %s", response.status) if response.content_type != "application/json": raise RetryableHttpExceptionError( response.status, f"Unexpected content type: {response.content_type}", API_ERR_CODE_UNKNOWN, ) result: dict[str, Any] = await response.json() if response.status == HTTPStatus.OK: errors: list[dict[str, Any]] = result.get("errors", []) if not errors: return result error_code, error_message = extract_error_details(errors, str(response.content)) if error_code == "UNAUTHENTICATED": raise InvalidLoginError(response.status, error_message, error_code) if (error_code == "INTERNAL_SERVER_ERROR") & ("demo user" in error_message): raise NotForDemoUserError(response.status, error_message, error_code) raise RetryableHttpExceptionError(response.status, message=error_message, extension_code=error_code) if response.status in HTTP_CODES_RETRIABLE: error_code, error_message = extract_error_details(result.get("errors", []), str(response.content)) raise RetryableHttpExceptionError(response.status, message=error_message, extension_code=error_code) if response.status in HTTP_CODES_FATAL: error_code, error_message = extract_error_details(result.get("errors", []), "request failed") if error_code == API_ERR_CODE_UNAUTH: raise InvalidLoginError(response.status, error_message, error_code) _LOGGER.error("FatalHttpExceptionError %s %s", error_message, error_code) raise FatalHttpExceptionError(response.status, error_message, error_code) error_code, error_message = extract_error_details(result.get("errors", []), "N/A") # if reached here the HTTP response code is not currently handled _LOGGER.error("FatalHttpExceptionError %s %s", error_message, error_code) raise FatalHttpExceptionError(response.status, f"Unhandled error: {error_message}", error_code) Danielhiversen-pyTibber-c94895e/tibber/websocket_transport.py000066400000000000000000000033011502770006000245210ustar00rootroot00000000000000"""Websocket transport for Tibber.""" import asyncio import datetime as dt import logging from ssl import SSLContext from gql.transport.exceptions import TransportClosed from gql.transport.websockets import WebsocketsTransport _LOGGER = logging.getLogger(__name__) class TibberWebsocketsTransport(WebsocketsTransport): """Tibber websockets transport.""" def __init__(self, url: str, access_token: str, user_agent: str, ssl: SSLContext | bool = True) -> None: """Initialize TibberWebsocketsTransport.""" super().__init__( url=url, init_payload={"token": access_token}, headers={"User-Agent": user_agent}, ping_interval=30, ssl=ssl, ) self._user_agent: str = user_agent self._timeout: int = 90 self.reconnect_at: dt.datetime = dt.datetime.now(tz=dt.UTC) + dt.timedelta(seconds=self._timeout) @property def running(self) -> bool: """Is real time subscription running.""" return self.websocket is not None and self.websocket.open async def _receive(self) -> str: """Wait the next message from the websocket connection.""" try: msg = await asyncio.wait_for(super()._receive(), timeout=self._timeout) except TimeoutError: _LOGGER.error("No data received from Tibber for %s seconds", self._timeout) raise self.reconnect_at = dt.datetime.now(tz=dt.UTC) + dt.timedelta(seconds=self._timeout) return msg async def close(self) -> None: """Close the websocket connection.""" await self._fail(TransportClosed(f"Tibber websocket closed by {self._user_agent}")) await self.wait_closed()