pax_global_header00006660000000000000000000000064147620502130014512gustar00rootroot0000000000000052 comment=a72869af45a76e2bd01edf9bdef76f2bc297161d aioecowitt-2025.3.1/000077500000000000000000000000001476205021300141135ustar00rootroot00000000000000aioecowitt-2025.3.1/.devcontainer/000077500000000000000000000000001476205021300166525ustar00rootroot00000000000000aioecowitt-2025.3.1/.devcontainer/Dockerfile000066400000000000000000000025331476205021300206470ustar00rootroot00000000000000# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.241.1/containers/python-3/.devcontainer/base.Dockerfile # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster ARG VARIANT="3.10-bullseye" FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 ARG NODE_VERSION="none" RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. # COPY requirements.txt /tmp/pip-tmp/ # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ # && rm -rf /tmp/pip-tmp # [Optional] Uncomment this section to install additional OS packages. # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ # && apt-get -y install --no-install-recommends # [Optional] Uncomment this line to install global node packages. # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1aioecowitt-2025.3.1/.devcontainer/devcontainer.json000066400000000000000000000024551476205021300222340ustar00rootroot00000000000000 { "name": "EcoWitt Test", "build": { "dockerfile": "Dockerfile", "context": ".." }, "postCreateCommand": "pip3 install -e .", "runArgs": ["-e", "GIT_EDITOR=code --wait", "--privileged"], "extensions": [ "ms-python.python", "ms-python.vscode-pylance", "visualstudioexptteam.vscodeintellicode", "esbenp.prettier-vscode" ], "mounts": [ "type=volume,target=/var/lib/docker" ], "settings": { "terminal.integrated.profiles.linux": { "zsh": { "path": "/usr/bin/zsh" } }, "terminal.integrated.defaultProfile.linux": "zsh", "editor.formatOnPaste": false, "editor.formatOnSave": true, "editor.formatOnType": true, "files.trimTrailingWhitespace": true, "python.pythonPath": "/usr/local/bin/python3", "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.formatting.provider": "black", "python.formatting.blackArgs": ["--target-version", "py39"], "python.formatting.blackPath": "/usr/local/bin/black", "python.linting.banditPath": "/usr/local/bin/bandit", "python.linting.flake8Path": "/usr/local/bin/flake8", "python.linting.mypyPath": "/usr/local/bin/mypy", "python.linting.pylintPath": "/usr/local/bin/pylint", "python.linting.pydocstylePath": "/usr/local/bin/pydocstyle" } } aioecowitt-2025.3.1/.github/000077500000000000000000000000001476205021300154535ustar00rootroot00000000000000aioecowitt-2025.3.1/.github/FUNDING.yml000066400000000000000000000000771476205021300172740ustar00rootroot00000000000000# These are supported funding model platforms github: pvizeli aioecowitt-2025.3.1/.github/dependabot.yml000066400000000000000000000004071476205021300203040ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: daily open-pull-requests-limit: 10 - package-ecosystem: pip directory: "/" schedule: interval: daily open-pull-requests-limit: 10 aioecowitt-2025.3.1/.github/release-drafter.yml000066400000000000000000000004161476205021300212440ustar00rootroot00000000000000change-template: "- #$NUMBER - $TITLE (@$AUTHOR)" categories: - title: "⚠ Breaking Changes" labels: - "breaking-change" - title: "⬆️ Dependencies" collapse-after: 1 labels: - "dependencies" template: | ## What’s Changed $CHANGES aioecowitt-2025.3.1/.github/workflows/000077500000000000000000000000001476205021300175105ustar00rootroot00000000000000aioecowitt-2025.3.1/.github/workflows/pythonpublish.yml000066400000000000000000000015251476205021300231460ustar00rootroot00000000000000# 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: [published] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4.2.2 - name: Set up Python uses: actions/setup-python@v5.4.0 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | python setup.py sdist bdist_wheel twine upload dist/* aioecowitt-2025.3.1/.github/workflows/release-drafter.yml000066400000000000000000000005121476205021300232760ustar00rootroot00000000000000name: Release Drafter on: push: branches: - main jobs: update_release_draft: runs-on: ubuntu-latest steps: # Drafts your next Release notes as Pull Requests are merged into "master" - uses: release-drafter/release-drafter@v6.1.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} aioecowitt-2025.3.1/.github/workflows/test.yml000066400000000000000000000012121476205021300212060ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Run Tests on: push: branches: [main] pull_request: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4.2.2 - name: Set up Python 3.9 uses: actions/setup-python@v5.4.0 with: python-version: 3.9 - name: Install dependencies run: | pip install tox - name: Run Tox run: | tox aioecowitt-2025.3.1/.gitignore000066400000000000000000000034071476205021300161070ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # 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/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ aioecowitt-2025.3.1/LICENSE000066400000000000000000000261671476205021300151340ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2021 root@garbled.net Copyright 2022 pvizeli@syshack.ch Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. aioecowitt-2025.3.1/README.md000066400000000000000000000001421476205021300153670ustar00rootroot00000000000000# aioEcoWitt Simple python library for the EcoWitt Protocol Inspired by pyecowit & ecowitt2mqtt aioecowitt-2025.3.1/aioecowitt/000077500000000000000000000000001476205021300162625ustar00rootroot00000000000000aioecowitt-2025.3.1/aioecowitt/__init__.py000066400000000000000000000002351476205021300203730ustar00rootroot00000000000000"""aioEcoWitt API wrapper.""" from .server import EcoWittListener from .sensor import EcoWittSensor, EcoWittSensorTypes from .station import EcoWittStation aioecowitt-2025.3.1/aioecowitt/__main__.py000066400000000000000000000020361476205021300203550ustar00rootroot00000000000000"""Run local Test server.""" from __future__ import annotations import asyncio import sys from aioecowitt import EcoWittListener, EcoWittSensor def usage(): """Print usage of the CLI.""" print(f"Usage: {sys.argv[0]} port") async def my_handler(sensor: EcoWittSensor) -> None: """Callback handler for printing data.""" print("In my handler") print(f"{str(sensor)}") async def run_server(ecowitt_ws: EcoWittListener) -> None: """Run server in endless mode.""" await ecowitt_ws.start() while True: await asyncio.sleep(100000) def main() -> None: """Run main.""" if len(sys.argv) < 2: usage() sys.exit(1) print(f"Firing up webserver to listen on port {sys.argv[1]}") ecowitt_server = EcoWittListener(port=sys.argv[1]) ecowitt_server.new_sensor_cb.append(my_handler) try: asyncio.run(run_server(ecowitt_server)) except Exception as err: # pylint: disable=broad-except print(str(err)) print("Exiting") if __name__ == "__main__": main() aioecowitt-2025.3.1/aioecowitt/calc.py000066400000000000000000000230431476205021300175400ustar00rootroot00000000000000"""Weather datapoint calculator.""" from __future__ import annotations import datetime as dt import meteocalc from .sensor import SENSOR_MAP, EcoWittSensorTypes def _ftoc(fahrenheit: float | str) -> float: """Convert f to c.""" return round(meteocalc.Temp(fahrenheit, "F").c, 1) def _timestamp_to_datetime(timestamp: int) -> dt.datetime: return dt.datetime.fromtimestamp(timestamp, dt.timezone.utc) def weather_datapoints( data: dict[str, str], ) -> dict[str, str | int | float | dt.datetime | None]: """Calculate and convert weather data.""" mph_kmh = 1.60934 in_hpa = 33.86 in_mm = 25.4 km_mi = 0.6213712 wm_lux = 0.0079 # basic conversions if "humidityin" in data: data["humidityin"] = int(data["humidityin"]) if "humidity" in data: data["humidity"] = int(data["humidity"]) if "winddir" in data: data["winddir"] = int(data["winddir"]) if "winddir_avg10m" in data: data["winddir_avg10m"] = int(data["winddir_avg10m"]) if "uv" in data: data["uv"] = int(data["uv"]) if "solarradiation" in data: data["solarradiation"] = float(data["solarradiation"]) data["solarradiation_lux"] = round(data["solarradiation"] / wm_lux, 1) # lightning if "lightning_time" in data: if data["lightning_time"]: data["lightning_time"] = _timestamp_to_datetime(int(data["lightning_time"])) else: data["lightning_time"] = None if "lightning_num" in data: data["lightning_num"] = int(data["lightning_num"]) if "lightning" in data: if data["lightning"]: data["lightning"] = int(data["lightning"]) data["lightning_mi"] = int(round(data["lightning"] * km_mi)) else: data["lightning"] = None # temperatures if "tempf" in data: data["tempf"] = float(data["tempf"]) data["tempc"] = _ftoc(data["tempf"]) if "tempinf" in data: data["tempinf"] = float(data["tempinf"]) data["tempinc"] = _ftoc(data["tempinf"]) # (WH45) if "tf_co2" in data: data["tf_co2"] = float(data["tf_co2"]) data["tf_co2c"] = _ftoc(data["tf_co2"]) # WN34 Soil Temperature Sensor for j in range(1, 9): wnf = f"tf_ch{j}" wnc = f"tf_ch{j}c" if wnf in data: data[wnf] = float(data[wnf]) data[wnc] = _ftoc(data[wnf]) # numbered WH31 temp/humid for j in range(1, 9): tmpf = f"temp{j}f" tmpc = f"temp{j}c" hum = f"humidity{j}" if tmpf in data: data[tmpf] = float(data[tmpf]) data[tmpc] = _ftoc(data[tmpf]) if hum in data: data[hum] = int(data[hum]) # speeds if "windspeedmph" in data: data["windspeedmph"] = float(data["windspeedmph"]) data["windspeedkmh"] = round(data["windspeedmph"] * mph_kmh, 1) if "windgustmph" in data: data["windgustmph"] = float(data["windgustmph"]) data["windgustkmh"] = round(data["windgustmph"] * mph_kmh, 1) # I assume this is MPH? if "maxdailygust" in data: data["maxdailygust"] = float(data["maxdailygust"]) data["maxdailygustkmh"] = round(data["maxdailygust"] * mph_kmh, 1) if "windspdmph_avg10m" in data: data["windspdmph_avg10m"] = float(data["windspdmph_avg10m"]) data["windspdkmh_avg10m"] = round(float(data["windspdmph_avg10m"] * mph_kmh), 1) # distances if "rainratein" in data: data["rainratein"] = float(data["rainratein"]) data["rainratemm"] = round(data["rainratein"] * in_mm, 1) if "eventrainin" in data: data["eventrainin"] = float(data["eventrainin"]) data["eventrainmm"] = round(data["eventrainin"] * in_mm, 1) if "hourlyrainin" in data: data["hourlyrainin"] = float(data["hourlyrainin"]) data["hourlyrainmm"] = round(data["hourlyrainin"] * in_mm, 1) if "dailyrainin" in data: data["dailyrainin"] = float(data["dailyrainin"]) data["dailyrainmm"] = round(data["dailyrainin"] * in_mm, 1) if "weeklyrainin" in data: data["weeklyrainin"] = float(data["weeklyrainin"]) data["weeklyrainmm"] = round(data["weeklyrainin"] * in_mm, 1) if "monthlyrainin" in data: data["monthlyrainin"] = float(data["monthlyrainin"]) data["monthlyrainmm"] = round(data["monthlyrainin"] * in_mm, 1) if "yearlyrainin" in data: data["yearlyrainin"] = float(data["yearlyrainin"]) data["yearlyrainmm"] = round(data["yearlyrainin"] * in_mm, 1) if "totalrainin" in data: data["totalrainin"] = float(data["totalrainin"]) data["totalrainmm"] = round(data["totalrainin"] * in_mm, 1) # piezo rain sensor if "rrain_piezo" in data: data["rrain_piezo"] = float(data["rrain_piezo"]) data["rrain_piezomm"] = round(data["rrain_piezo"] * in_mm, 1) if "erain_piezo" in data: data["erain_piezo"] = float(data["erain_piezo"]) data["erain_piezomm"] = round(data["erain_piezo"] * in_mm, 1) if "hrain_piezo" in data: data["hrain_piezo"] = float(data["hrain_piezo"]) data["hrain_piezomm"] = round(data["hrain_piezo"] * in_mm, 1) if "drain_piezo" in data: data["drain_piezo"] = float(data["drain_piezo"]) data["drain_piezomm"] = round(data["drain_piezo"] * in_mm, 1) if "wrain_piezo" in data: data["wrain_piezo"] = float(data["wrain_piezo"]) data["wrain_piezomm"] = round(data["wrain_piezo"] * in_mm, 1) if "mrain_piezo" in data: data["mrain_piezo"] = float(data["mrain_piezo"]) data["mrain_piezomm"] = round(data["mrain_piezo"] * in_mm, 1) if "yrain_piezo" in data: data["yrain_piezo"] = float(data["yrain_piezo"]) data["yrain_piezomm"] = round(data["yrain_piezo"] * in_mm, 1) if "srain_piezo" in data: data["srain_piezo"] = int(data["srain_piezo"]) # Pressure if "baromrelin" in data: data["baromrelin"] = float(data["baromrelin"]) data["baromrelhpa"] = round(data["baromrelin"] * in_hpa, 1) if "baromabsin" in data: data["baromabsin"] = float(data["baromabsin"]) data["baromabshpa"] = round(data["baromabsin"] * in_hpa, 1) # Wind chill if "tempf" in data and "windspeedmph" in data: try: wind_chill = meteocalc.wind_chill(data["tempf"], data["windspeedmph"]) except ValueError: data["windchillf"] = None data["windchillc"] = None else: data["windchillf"] = round(wind_chill.f, 1) data["windchillc"] = round(wind_chill.c, 1) # Dew point for j in ["", "in", "1", "2", "3", "4", "5", "6", "7", "8"]: if f"temp{j}c" in data and f"humidity{j}" in data: dewpoint = meteocalc.dew_point(data[f"temp{j}c"], data[f"humidity{j}"]) data[f"dewpoint{j}c"] = round(dewpoint.c, 1) data[f"dewpoint{j}f"] = round(dewpoint.f, 1) # Feels like if "tempf" in data and "humidity" in data and "windspeedmph" in data: feels_like = meteocalc.feels_like( data["tempf"], data["humidity"], data["windspeedmph"] ) data["tempfeelsf"] = round(feels_like.f, 1) data["tempfeelsc"] = round(feels_like.c, 1) # Soil moisture (WH51) for j in range(1, 17): name = f"soilmoisture{j}" if name in data: data[name] = int(data[name]) # PM 2.5 sensor (WH41) for j in range(1, 5): pmc = f"pm25_ch{j}" pma = f"pm25_avg_24h_ch{j}" if pmc in data: data[pmc] = float(data[pmc]) if pma in data: data[pma] = float(data[pma]) # Leak sensor (WH55) for j in range(1, 5): leak = f"leak_ch{j}" if leak in data: data[leak] = int(data[leak]) # Wetness sensor (WN35) for j in range(1, 8): leaf = f"leafwetness_ch{j}" if leaf in data: data[leaf] = int(data[leaf]) # CO2 indoor air quality (WH45) (note temp is in temps above) pm_floats = [ "pm25", "pm25_24h", "pm10", "pm10_24", ] for prefix in pm_floats: name = f"{prefix}_co2" if name in data: data[name] = float(data[name]) if "co2" in data: data["co2"] = int(data["co2"]) if "co2_24h" in data: data["co2_24h"] = int(data["co2_24h"]) if "humi_co2" in data: data["humi_co2"] = int(data["humi_co2"]) # Batteries bat_names = [ "wh25", "wh26", "wh40", "wh57", "wh65", "wh68", "wh80", "wh90", "co2_", ] for prefix in bat_names: name = f"{prefix}batt" if name in data: batt_type = SENSOR_MAP[name].stype if batt_type == EcoWittSensorTypes.BATTERY_PERCENTAGE: data[name] = int(data[name]) * 20 else: data[name] = float(data[name]) bat_range_names = [ "", # for just 'batt' "soil", "pm25", "leak", "tf_", # WN34 voltage type "leaf_", ] for r_prefix in bat_range_names: for j in range(1, 9): name = f"{r_prefix}batt{j}" if name in data: batt_type = SENSOR_MAP[name].stype if batt_type == EcoWittSensorTypes.BATTERY_PERCENTAGE: data[name] = int(data[name]) * 20 else: data[name] = float(data[name]) bat_full_names = [ "ws90cap_volt", "console_batt", ] for name in bat_full_names: if name in data: data[name] = float(data[name]) return data aioecowitt-2025.3.1/aioecowitt/py.typed000066400000000000000000000000001476205021300177470ustar00rootroot00000000000000aioecowitt-2025.3.1/aioecowitt/sensor.py000066400000000000000000000601741476205021300201550ustar00rootroot00000000000000"""Sensor and mapping data from ecowitt.""" from __future__ import annotations import datetime as dt from typing import Callable from dataclasses import dataclass, field import enum from .station import EcoWittStation @dataclass class EcoWittSensor: """An internal sensor to the ecowitt.""" name: str key: str stype: EcoWittSensorTypes station: EcoWittStation value: None | str | int | float | dt.datetime = field(default=None, init=False) last_update: float = field(default=0, init=False) last_update_m: float = field(default=0, init=False) update_cb: list[Callable[[], None]] = field(default_factory=list, init=False) def update_value( self, value: None | str | int | float | dt.datetime, last_update: float, last_update_m: float, ) -> None: """Update the value of the sensor.""" self.last_update = last_update self.last_update_m = last_update_m # Set the value if self.value == value: return self.value = value # notify listeners for callback in self.update_cb: callback() class EcoWittSensorTypes(enum.Enum): """EcoWitt sensor types.""" INTERNAL = 1 PRESSURE_HPA = 2 PRESSURE_INHG = 3 RAIN_COUNT_MM = 4 RAIN_COUNT_INCHES = 5 RAIN_RATE_MM = 6 RAIN_RATE_INCHES = 7 HUMIDITY = 8 DEGREE = 9 SPEED_KPH = 10 SPEED_MPH = 11 TEMPERATURE_C = 12 TEMPERATURE_F = 13 WATT_METERS_SQUARED = 14 UV_INDEX = 15 PM25 = 16 PM10 = 17 TIMESTAMP = 18 LIGHTNING_COUNT = 19 LIGHTNING_DISTANCE_KM = 20 LIGHTNING_DISTANCE_MILES = 21 LEAK = 22 VOLTAGE = 23 BATTERY_BINARY = 24 BATTERY_VOLTAGE = 25 BATTERY_PERCENTAGE = 26 CO2_PPM = 27 LUX = 28 PERCENTAGE = 29 SOIL_RAWADC = 30 RAIN_STATE = 31 @dataclass class EcoWittMapping: """Mapping Sensor information.""" name: str stype: EcoWittSensorTypes SENSOR_MAP: dict[str, EcoWittMapping] = { "baromabshpa": EcoWittMapping("Absolute Pressure", EcoWittSensorTypes.PRESSURE_HPA), "baromrelhpa": EcoWittMapping("Relative Pressure", EcoWittSensorTypes.PRESSURE_HPA), "baromabsin": EcoWittMapping("Absolute Pressure", EcoWittSensorTypes.PRESSURE_INHG), "baromrelin": EcoWittMapping("Relative Pressure", EcoWittSensorTypes.PRESSURE_INHG), "rainratein": EcoWittMapping("Rain Rate", EcoWittSensorTypes.RAIN_RATE_INCHES), "eventrainin": EcoWittMapping("Event Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES), "hourlyrainin": EcoWittMapping("Hourly Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES), "totalrainin": EcoWittMapping("Total Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES), "dailyrainin": EcoWittMapping("Daily Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES), "weeklyrainin": EcoWittMapping("Weekly Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES), "monthlyrainin": EcoWittMapping( "Monthly Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "yearlyrainin": EcoWittMapping("Yearly Rain", EcoWittSensorTypes.RAIN_COUNT_INCHES), "rainratemm": EcoWittMapping("Rain Rate", EcoWittSensorTypes.RAIN_RATE_MM), "eventrainmm": EcoWittMapping("Event Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "hourlyrainmm": EcoWittMapping("Hourly Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "totalrainmm": EcoWittMapping("Total Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "dailyrainmm": EcoWittMapping("Daily Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "weeklyrainmm": EcoWittMapping("Weekly Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "monthlyrainmm": EcoWittMapping("Monthly Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "yearlyrainmm": EcoWittMapping("Yearly Rain", EcoWittSensorTypes.RAIN_COUNT_MM), "humidity": EcoWittMapping("Humidity", EcoWittSensorTypes.HUMIDITY), "humidityin": EcoWittMapping("Indoor Humidity", EcoWittSensorTypes.HUMIDITY), "humidity1": EcoWittMapping("Humidity 1", EcoWittSensorTypes.HUMIDITY), "humidity2": EcoWittMapping("Humidity 2", EcoWittSensorTypes.HUMIDITY), "humidity3": EcoWittMapping("Humidity 3", EcoWittSensorTypes.HUMIDITY), "humidity4": EcoWittMapping("Humidity 4", EcoWittSensorTypes.HUMIDITY), "humidity5": EcoWittMapping("Humidity 5", EcoWittSensorTypes.HUMIDITY), "humidity6": EcoWittMapping("Humidity 6", EcoWittSensorTypes.HUMIDITY), "humidity7": EcoWittMapping("Humidity 7", EcoWittSensorTypes.HUMIDITY), "humidity8": EcoWittMapping("Humidity 8", EcoWittSensorTypes.HUMIDITY), "winddir": EcoWittMapping("Wind Direction", EcoWittSensorTypes.DEGREE), "winddir_avg10m": EcoWittMapping( "Wind Direction 10m Avg", EcoWittSensorTypes.DEGREE ), "windspeedkmh": EcoWittMapping("Wind Speed", EcoWittSensorTypes.SPEED_KPH), "windspdkmh_avg10m": EcoWittMapping( "Wind Speed 10m Avg", EcoWittSensorTypes.SPEED_KPH ), "windgustkmh": EcoWittMapping("Wind Gust", EcoWittSensorTypes.SPEED_KPH), "maxdailygustkmh": EcoWittMapping("Max Daily Gust", EcoWittSensorTypes.SPEED_KPH), "windspeedmph": EcoWittMapping("Wind Speed", EcoWittSensorTypes.SPEED_MPH), "windspdmph_avg10m": EcoWittMapping( "Wind Speed 10m Avg", EcoWittSensorTypes.SPEED_MPH ), "windgustmph": EcoWittMapping("Wind Gust", EcoWittSensorTypes.SPEED_MPH), "maxdailygust": EcoWittMapping("Max Daily Wind Gust", EcoWittSensorTypes.SPEED_MPH), "tempc": EcoWittMapping("Outdoor Temperature", EcoWittSensorTypes.TEMPERATURE_C), "tempfeelsc": EcoWittMapping( "Feels like Temperature", EcoWittSensorTypes.TEMPERATURE_C ), "tempinc": EcoWittMapping("Indoor Temperature", EcoWittSensorTypes.TEMPERATURE_C), "temp1c": EcoWittMapping("Temperature 1", EcoWittSensorTypes.TEMPERATURE_C), "temp2c": EcoWittMapping("Temperature 2", EcoWittSensorTypes.TEMPERATURE_C), "temp3c": EcoWittMapping("Temperature 3", EcoWittSensorTypes.TEMPERATURE_C), "temp4c": EcoWittMapping("Temperature 4", EcoWittSensorTypes.TEMPERATURE_C), "temp5c": EcoWittMapping("Temperature 5", EcoWittSensorTypes.TEMPERATURE_C), "temp6c": EcoWittMapping("Temperature 6", EcoWittSensorTypes.TEMPERATURE_C), "temp7c": EcoWittMapping("Temperature 7", EcoWittSensorTypes.TEMPERATURE_C), "temp8c": EcoWittMapping("Temperature 8", EcoWittSensorTypes.TEMPERATURE_C), "dewpointc": EcoWittMapping("Dewpoint", EcoWittSensorTypes.TEMPERATURE_C), "dewpointinc": EcoWittMapping("Indoor Dewpoint", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint1c": EcoWittMapping("Dewpoint 1", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint2c": EcoWittMapping("Dewpoint 2", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint3c": EcoWittMapping("Dewpoint 3", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint4c": EcoWittMapping("Dewpoint 4", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint5c": EcoWittMapping("Dewpoint 5", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint6c": EcoWittMapping("Dewpoint 6", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint7c": EcoWittMapping("Dewpoint 7", EcoWittSensorTypes.TEMPERATURE_C), "dewpoint8c": EcoWittMapping("Dewpoint 8", EcoWittSensorTypes.TEMPERATURE_C), "windchillc": EcoWittMapping("Windchill", EcoWittSensorTypes.TEMPERATURE_C), "tempf": EcoWittMapping("Outdoor Temperature", EcoWittSensorTypes.TEMPERATURE_F), "tempfeelsf": EcoWittMapping( "Feels like Temperature", EcoWittSensorTypes.TEMPERATURE_F, ), "tempinf": EcoWittMapping("Indoor Temperature", EcoWittSensorTypes.TEMPERATURE_F), "temp1f": EcoWittMapping("Temperature 1", EcoWittSensorTypes.TEMPERATURE_F), "temp2f": EcoWittMapping("Temperature 2", EcoWittSensorTypes.TEMPERATURE_F), "temp3f": EcoWittMapping("Temperature 3", EcoWittSensorTypes.TEMPERATURE_F), "temp4f": EcoWittMapping("Temperature 4", EcoWittSensorTypes.TEMPERATURE_F), "temp5f": EcoWittMapping("Temperature 5", EcoWittSensorTypes.TEMPERATURE_F), "temp6f": EcoWittMapping("Temperature 6", EcoWittSensorTypes.TEMPERATURE_F), "temp7f": EcoWittMapping("Temperature 7", EcoWittSensorTypes.TEMPERATURE_F), "temp8f": EcoWittMapping("Temperature 8", EcoWittSensorTypes.TEMPERATURE_F), "dewpointf": EcoWittMapping("Dewpoint", EcoWittSensorTypes.TEMPERATURE_F), "dewpointinf": EcoWittMapping("Indoor Dewpoint", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint1f": EcoWittMapping("Dewpoint 1", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint2f": EcoWittMapping("Dewpoint 2", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint3f": EcoWittMapping("Dewpoint 3", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint4f": EcoWittMapping("Dewpoint 4", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint5f": EcoWittMapping("Dewpoint 5", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint6f": EcoWittMapping("Dewpoint 6", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint7f": EcoWittMapping("Dewpoint 7", EcoWittSensorTypes.TEMPERATURE_F), "dewpoint8f": EcoWittMapping("Dewpoint 8", EcoWittSensorTypes.TEMPERATURE_F), "windchillf": EcoWittMapping("Windchill", EcoWittSensorTypes.TEMPERATURE_F), "solarradiation": EcoWittMapping( "Solar Radiation", EcoWittSensorTypes.WATT_METERS_SQUARED ), "solarradiation_lux": EcoWittMapping("Solar Lux", EcoWittSensorTypes.LUX), "uv": EcoWittMapping("UV Index", EcoWittSensorTypes.UV_INDEX), "soilmoisture1": EcoWittMapping("Soil Moisture 1", EcoWittSensorTypes.HUMIDITY), "soilmoisture2": EcoWittMapping("Soil Moisture 2", EcoWittSensorTypes.HUMIDITY), "soilmoisture3": EcoWittMapping("Soil Moisture 3", EcoWittSensorTypes.HUMIDITY), "soilmoisture4": EcoWittMapping("Soil Moisture 4", EcoWittSensorTypes.HUMIDITY), "soilmoisture5": EcoWittMapping("Soil Moisture 5", EcoWittSensorTypes.HUMIDITY), "soilmoisture6": EcoWittMapping("Soil Moisture 6", EcoWittSensorTypes.HUMIDITY), "soilmoisture7": EcoWittMapping("Soil Moisture 7", EcoWittSensorTypes.HUMIDITY), "soilmoisture8": EcoWittMapping("Soil Moisture 8", EcoWittSensorTypes.HUMIDITY), "soilmoisture9": EcoWittMapping("Soil Moisture 9", EcoWittSensorTypes.HUMIDITY), "soilmoisture10": EcoWittMapping("Soil Moisture 10", EcoWittSensorTypes.HUMIDITY), "soilmoisture11": EcoWittMapping("Soil Moisture 11", EcoWittSensorTypes.HUMIDITY), "soilmoisture12": EcoWittMapping("Soil Moisture 12", EcoWittSensorTypes.HUMIDITY), "soilmoisture13": EcoWittMapping("Soil Moisture 13", EcoWittSensorTypes.HUMIDITY), "soilmoisture14": EcoWittMapping("Soil Moisture 14", EcoWittSensorTypes.HUMIDITY), "soilmoisture15": EcoWittMapping("Soil Moisture 15", EcoWittSensorTypes.HUMIDITY), "soilmoisture16": EcoWittMapping("Soil Moisture 16", EcoWittSensorTypes.HUMIDITY), "soilad1": EcoWittMapping("Soil AD 1", EcoWittSensorTypes.SOIL_RAWADC), "soilad2": EcoWittMapping("Soil AD 2", EcoWittSensorTypes.SOIL_RAWADC), "soilad3": EcoWittMapping("Soil AD 3", EcoWittSensorTypes.SOIL_RAWADC), "soilad4": EcoWittMapping("Soil AD 4", EcoWittSensorTypes.SOIL_RAWADC), "soilad5": EcoWittMapping("Soil AD 5", EcoWittSensorTypes.SOIL_RAWADC), "soilad6": EcoWittMapping("Soil AD 6", EcoWittSensorTypes.SOIL_RAWADC), "soilad7": EcoWittMapping("Soil AD 7", EcoWittSensorTypes.SOIL_RAWADC), "soilad8": EcoWittMapping("Soil AD 8", EcoWittSensorTypes.SOIL_RAWADC), "soilad9": EcoWittMapping("Soil AD 9", EcoWittSensorTypes.SOIL_RAWADC), "soilad10": EcoWittMapping("Soil AD 10", EcoWittSensorTypes.SOIL_RAWADC), "soilad11": EcoWittMapping("Soil AD 11", EcoWittSensorTypes.SOIL_RAWADC), "soilad12": EcoWittMapping("Soil AD 12", EcoWittSensorTypes.SOIL_RAWADC), "soilad13": EcoWittMapping("Soil AD 13", EcoWittSensorTypes.SOIL_RAWADC), "soilad14": EcoWittMapping("Soil AD 14", EcoWittSensorTypes.SOIL_RAWADC), "soilad15": EcoWittMapping("Soil AD 15", EcoWittSensorTypes.SOIL_RAWADC), "soilad16": EcoWittMapping("Soil AD 16", EcoWittSensorTypes.SOIL_RAWADC), "pm25_ch1": EcoWittMapping("PM2.5 1", EcoWittSensorTypes.PM25), "pm25_ch2": EcoWittMapping("PM2.5 2", EcoWittSensorTypes.PM25), "pm25_ch3": EcoWittMapping("PM2.5 3", EcoWittSensorTypes.PM25), "pm25_ch4": EcoWittMapping("PM2.5 4", EcoWittSensorTypes.PM25), "pm25_avg_24h_ch1": EcoWittMapping("PM2.5 24h Average 1", EcoWittSensorTypes.PM25), "pm25_avg_24h_ch2": EcoWittMapping("PM2.5 24h Average 2", EcoWittSensorTypes.PM25), "pm25_avg_24h_ch3": EcoWittMapping("PM2.5 24h Average 3", EcoWittSensorTypes.PM25), "pm25_avg_24h_ch4": EcoWittMapping("PM2.5 24h Average 4", EcoWittSensorTypes.PM25), "lightning_time": EcoWittMapping( "Last Lightning strike", EcoWittSensorTypes.TIMESTAMP ), "lightning_num": EcoWittMapping( "Lightning strikes", EcoWittSensorTypes.LIGHTNING_COUNT ), "lightning": EcoWittMapping( "Lightning strike distance", EcoWittSensorTypes.LIGHTNING_DISTANCE_KM ), "lightning_mi": EcoWittMapping( "Lightning strike distance", EcoWittSensorTypes.LIGHTNING_DISTANCE_MILES, ), "tf_co2": EcoWittMapping("WH45 Temperature", EcoWittSensorTypes.TEMPERATURE_F), "tf_co2c": EcoWittMapping("WH45 Temperature", EcoWittSensorTypes.TEMPERATURE_C), "humi_co2": EcoWittMapping("WH45 Humidity", EcoWittSensorTypes.HUMIDITY), "pm25_co2": EcoWittMapping("WH45 PM2.5 CO2", EcoWittSensorTypes.PM25), "pm25_24h_co2": EcoWittMapping( "WH45 PM2.5 CO2 24h average", EcoWittSensorTypes.PM25 ), "pm10_co2": EcoWittMapping("WH45 PM10 CO2", EcoWittSensorTypes.PM10), "pm10_24h_co2": EcoWittMapping( "WH45 PM10 CO2 24h average", EcoWittSensorTypes.PM10 ), "co2": EcoWittMapping("WH45 CO2", EcoWittSensorTypes.CO2_PPM), "co2_24h": EcoWittMapping("WH45 CO2 24h average", EcoWittSensorTypes.CO2_PPM), "co2_batt": EcoWittMapping("WH45 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE), "leak_ch1": EcoWittMapping("Leak Detection 1", EcoWittSensorTypes.LEAK), "leak_ch2": EcoWittMapping("Leak Detection 2", EcoWittSensorTypes.LEAK), "leak_ch3": EcoWittMapping("Leak Detection 3", EcoWittSensorTypes.LEAK), "leak_ch4": EcoWittMapping("Leak Detection 4", EcoWittSensorTypes.LEAK), "wh25batt": EcoWittMapping("WH25 Battery", EcoWittSensorTypes.BATTERY_BINARY), "wh26batt": EcoWittMapping("WH26 Battery", EcoWittSensorTypes.BATTERY_BINARY), "wh40batt": EcoWittMapping("WH40 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE), "wh57batt": EcoWittMapping("WH57 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE), "wh65batt": EcoWittMapping("WH65 Battery", EcoWittSensorTypes.BATTERY_BINARY), "wh68batt": EcoWittMapping("WH68 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE), "wh80batt": EcoWittMapping("WH80 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE), "console_batt": EcoWittMapping( "Console Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "soilbatt1": EcoWittMapping("Soil Battery 1", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt2": EcoWittMapping("Soil Battery 2", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt3": EcoWittMapping("Soil Battery 3", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt4": EcoWittMapping("Soil Battery 4", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt5": EcoWittMapping("Soil Battery 5", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt6": EcoWittMapping("Soil Battery 6", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt7": EcoWittMapping("Soil Battery 7", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt8": EcoWittMapping("Soil Battery 8", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt9": EcoWittMapping("Soil Battery 9", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt10": EcoWittMapping("Soil Battery 10", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt11": EcoWittMapping("Soil Battery 11", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt12": EcoWittMapping("Soil Battery 12", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt13": EcoWittMapping("Soil Battery 13", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt14": EcoWittMapping("Soil Battery 14", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt15": EcoWittMapping("Soil Battery 15", EcoWittSensorTypes.BATTERY_VOLTAGE), "soilbatt16": EcoWittMapping("Soil Battery 16", EcoWittSensorTypes.BATTERY_VOLTAGE), "batt1": EcoWittMapping("Battery 1", EcoWittSensorTypes.BATTERY_BINARY), "batt2": EcoWittMapping("Battery 2", EcoWittSensorTypes.BATTERY_BINARY), "batt3": EcoWittMapping("Battery 3", EcoWittSensorTypes.BATTERY_BINARY), "batt4": EcoWittMapping("Battery 4", EcoWittSensorTypes.BATTERY_BINARY), "batt5": EcoWittMapping("Battery 5", EcoWittSensorTypes.BATTERY_BINARY), "batt6": EcoWittMapping("Battery 6", EcoWittSensorTypes.BATTERY_BINARY), "batt7": EcoWittMapping("Battery 7", EcoWittSensorTypes.BATTERY_BINARY), "batt8": EcoWittMapping("Battery 8", EcoWittSensorTypes.BATTERY_BINARY), "pm25batt1": EcoWittMapping( "PM2.5 1 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt2": EcoWittMapping( "PM2.5 2 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt3": EcoWittMapping( "PM2.5 3 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt4": EcoWittMapping( "PM2.5 4 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt5": EcoWittMapping( "PM2.5 5 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt6": EcoWittMapping( "PM2.5 6 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt7": EcoWittMapping( "PM2.5 7 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "pm25batt8": EcoWittMapping( "PM2.5 8 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE ), "leakbatt1": EcoWittMapping( "Leak Detection 1 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt2": EcoWittMapping( "Leak Detection 2 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt3": EcoWittMapping( "Leak Detection 3 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt4": EcoWittMapping( "Leak Detection 4 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt5": EcoWittMapping( "Leak Detection 5 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt6": EcoWittMapping( "Leak Detection 6 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt7": EcoWittMapping( "Leak Detection 7 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "leakbatt8": EcoWittMapping( "Leak Detection 8 Battery", EcoWittSensorTypes.BATTERY_PERCENTAGE, ), "tf_ch1c": EcoWittMapping("Soil Temperature 1", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch2c": EcoWittMapping("Soil Temperature 2", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch3c": EcoWittMapping("Soil Temperature 3", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch4c": EcoWittMapping("Soil Temperature 4", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch5c": EcoWittMapping("Soil Temperature 5", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch6c": EcoWittMapping("Soil Temperature 6", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch7c": EcoWittMapping("Soil Temperature 7", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch8c": EcoWittMapping("Soil Temperature 8", EcoWittSensorTypes.TEMPERATURE_C), "tf_ch1": EcoWittMapping("Soil Temperature 1", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch2": EcoWittMapping("Soil Temperature 2", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch3": EcoWittMapping("Soil Temperature 3", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch4": EcoWittMapping("Soil Temperature 4", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch5": EcoWittMapping("Soil Temperature 5", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch6": EcoWittMapping("Soil Temperature 6", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch7": EcoWittMapping("Soil Temperature 7", EcoWittSensorTypes.TEMPERATURE_F), "tf_ch8": EcoWittMapping("Soil Temperature 8", EcoWittSensorTypes.TEMPERATURE_F), "tf_batt1": EcoWittMapping( "Soil Temperature 1 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt2": EcoWittMapping( "Soil Temperature 2 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt3": EcoWittMapping( "Soil Temperature 3 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt4": EcoWittMapping( "Soil Temperature 4 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt5": EcoWittMapping( "Soil Temperature 5 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt6": EcoWittMapping( "Soil Temperature 6 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt7": EcoWittMapping( "Soil Temperature 7 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "tf_batt8": EcoWittMapping( "Soil Temperature 8 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leafwetness_ch1": EcoWittMapping("Leaf Wetness 1", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch2": EcoWittMapping("Leaf Wetness 2", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch3": EcoWittMapping("Leaf Wetness 3", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch4": EcoWittMapping("Leaf Wetness 4", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch5": EcoWittMapping("Leaf Wetness 5", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch6": EcoWittMapping("Leaf Wetness 6", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch7": EcoWittMapping("Leaf Wetness 7", EcoWittSensorTypes.PERCENTAGE), "leafwetness_ch8": EcoWittMapping("Leaf Wetness 8", EcoWittSensorTypes.PERCENTAGE), "leaf_batt1": EcoWittMapping( "Leaf Wetness 1 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt2": EcoWittMapping( "Leaf Wetness 2 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt3": EcoWittMapping( "Leaf Wetness 3 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt4": EcoWittMapping( "Leaf Wetness 4 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt5": EcoWittMapping( "Leaf Wetness 5 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt6": EcoWittMapping( "Leaf Wetness 6 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt7": EcoWittMapping( "Leaf Wetness 7 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "leaf_batt8": EcoWittMapping( "Leaf Wetness 8 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE ), "dateutc": EcoWittMapping("dateutc", EcoWittSensorTypes.INTERNAL), "fields": EcoWittMapping("field list", EcoWittSensorTypes.INTERNAL), "wh90batt": EcoWittMapping("WH90 Battery", EcoWittSensorTypes.BATTERY_VOLTAGE), "ws90cap_volt": EcoWittMapping("WH90 Capacitor", EcoWittSensorTypes.VOLTAGE), "rrain_piezo": EcoWittMapping( "Rain Rate Piezo", EcoWittSensorTypes.RAIN_RATE_INCHES ), "erain_piezo": EcoWittMapping( "Event Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "hrain_piezo": EcoWittMapping( "Hourly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "drain_piezo": EcoWittMapping( "Daily Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "wrain_piezo": EcoWittMapping( "Weekly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "mrain_piezo": EcoWittMapping( "Monthly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "yrain_piezo": EcoWittMapping( "Yearly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_INCHES ), "srain_piezo": EcoWittMapping("Rain State Piezo", EcoWittSensorTypes.RAIN_STATE), "rrain_piezomm": EcoWittMapping("Rain Rate Piezo", EcoWittSensorTypes.RAIN_RATE_MM), "erain_piezomm": EcoWittMapping( "Event Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_MM ), "hrain_piezomm": EcoWittMapping( "Hourly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_MM ), "drain_piezomm": EcoWittMapping( "Daily Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_MM ), "wrain_piezomm": EcoWittMapping( "Weekly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_MM ), "mrain_piezomm": EcoWittMapping( "Monthly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_MM ), "yrain_piezomm": EcoWittMapping( "Yearly Rain Piezo", EcoWittSensorTypes.RAIN_COUNT_MM ), "runtime": EcoWittMapping("Runtime", EcoWittSensorTypes.INTERNAL), "interval": EcoWittMapping("Interval", EcoWittSensorTypes.INTERNAL), "heap": EcoWittMapping("Memory heap", EcoWittSensorTypes.INTERNAL), } aioecowitt-2025.3.1/aioecowitt/server.py000066400000000000000000000101561476205021300201450ustar00rootroot00000000000000"""aioEcoWitt API server.""" from __future__ import annotations import logging import time from typing import Callable from aiohttp import web from .sensor import EcoWittSensor, SENSOR_MAP from .station import extract_station, EcoWittStation from .calc import weather_datapoints _LOGGER = logging.getLogger(__name__) _ECOWITT_LISTEN_PORT = 49199 class EcoWittListener: """EcoWitt Server API server.""" def __init__(self, port: int = _ECOWITT_LISTEN_PORT, path: str = None): """Initialize EcoWitt Server.""" # API Constants self.port: int = port self.path: str = path # webserver self.server: None | web.Server = None self.runner: None | web.ServerRunner = None self.site: None | web.TCPSite = None # internal data self.last_values: dict[str, dict[str, str | None]] = {} self.new_sensor_cb: list[Callable[[EcoWittSensor], None]] = [] self._warned_unknown: set[str] = set() # storage self.sensors: dict[str, EcoWittSensor] = {} self.stations: dict[str, EcoWittStation] = {} def _new_sensor_cb(self, sensor: EcoWittSensor) -> None: """Internal new sensor callback binds to self.new_sensor_cb """ for callback in self.new_sensor_cb: callback(sensor) def process_data(self, data: dict[str, str | float | int | None]) -> None: """Process data from weather station.""" data = data.copy() station = extract_station(data) weather_data = weather_datapoints(data) # add station to list if station.key not in self.stations: _LOGGER.debug("Found new station: %s", station.key) self.stations[station.key] = station else: station = self.stations[station.key] last_update = time.time() last_update_m = time.monotonic() for datapoint in weather_data.keys(): sensor_id = f"{station.key}.{datapoint}" sensor = self.sensors.get(sensor_id) if sensor is None: # we have a new sensor if datapoint not in SENSOR_MAP: if datapoint not in self._warned_unknown: self._warned_unknown.add(datapoint) _LOGGER.warning( "Unhandled sensor type %s value %s", datapoint, weather_data[datapoint], ) continue metadata = SENSOR_MAP[datapoint] sensor = EcoWittSensor( metadata.name, datapoint, metadata.stype, station ) self.sensors[sensor_id] = sensor try: self._new_sensor_cb(sensor) except Exception as err: # pylint: disable=broad-except _LOGGER.warning("EcoWitt new sensor callback error: %s", err) try: sensor.update_value(weather_data[datapoint], last_update, last_update_m) except Exception as err: # pylint: disable=broad-except _LOGGER.warning("Sensor update error: %s", err) async def handler(self, request: web.BaseRequest) -> web.Response: """AIOHTTP handler for the API.""" if request.method != "POST": return web.Response(status=405) if self.path is not None and request.path != self.path: return web.Response(status=404) data = await request.post() # data is not a dict, it's a MultiDict self.last_values[data["PASSKEY"]] = data.copy() self.last_values[data["PASSKEY"]].pop("PASSKEY") self.process_data(data) return web.Response(text="OK") async def start(self) -> None: """Listen and process.""" self.server = web.Server(self.handler) self.runner = web.ServerRunner(self.server) await self.runner.setup() self.site = web.TCPSite(self.runner, port=self.port) await self.site.start() async def stop(self) -> None: """Stop listening.""" await self.site.stop() aioecowitt-2025.3.1/aioecowitt/station.py000066400000000000000000000015341476205021300203200ustar00rootroot00000000000000"""Station mapping from ecowitt.""" from __future__ import annotations from dataclasses import dataclass, field VERSION_FIELDS = { "ws90_ver", } @dataclass class EcoWittStation: """An internal ecowitt station.""" station: str model: str frequence: str | None key: str version: None | str = field(default=None) def extract_station(data: dict[str, str]) -> EcoWittStation: """Extract station from data.""" station = data.pop("stationtype") passkey = data.pop("PASSKEY") model = data.pop("model") frequence = data.pop("freq", None) version = None for value in VERSION_FIELDS: if value not in data: continue version = data.pop(value) break return EcoWittStation( station=station, model=model, frequence=frequence, key=passkey, version=version ) aioecowitt-2025.3.1/misc/000077500000000000000000000000001476205021300150465ustar00rootroot00000000000000aioecowitt-2025.3.1/misc/example.data000066400000000000000000000042041476205021300173340ustar00rootroot00000000000000 aioecowitt-2025.3.1/misc/fake_client.py000066400000000000000000000052441476205021300176710ustar00rootroot00000000000000""" A bone-simple fake client used to test the hass integration """ import http.client import sys import urllib.parse MY_PASSKEY = "34271334ED1FADA6D8B988B14267E55D" # MY_PASSKEY = '35271334ED1FADA7D8B988B22222E22D' paramset_a = { "PASSKEY": MY_PASSKEY, "stationtype": "EasyWeatherV1.4.9", "dateutc": "2020-11-13+17:10:24", "tempinf": 76.8, "humidityin": 22, "baromrelin": 28.760, "baromabsin": 28.760, "tempf": 65.8, "humidity": 24, "winddir": 319, "windspeedmph": 0.9, "windgustmph": 1.1, "rainratein": 0.000, "eventrainin": 0.000, "dailyrainin": 0.000, "weeklyrainin": 0.024, "monthlyrainin": 0.028, "yearlyrainin": 0.843, "solarradiation": 375.53, "uv": 3, "pm25_ch1": 8.0, "pm25_avg_24h_ch1": 5.2, "freq": "915M", "model": "HP3500_V1.6.2", "leak_ch1": 0, "leakbatt1": 5, } paramset_b = { "PASSKEY": MY_PASSKEY, "stationtype": "EasyWeatherV1.5.4", "dateutc": "2020-11-16+15:30:24", "tempinf": 68.7, "humidityin": 52, "baromrelin": 29.785, "baromabsin": 29.785, "tempf": 46.4, "humidity": 94, "winddir": 260, "winddir_avg10m": 260, "windspeedmph": 0.0, "windspdmph_avg10m": 0.0, "windgustmph": 0.0, "maxdailygust": 6.9, "rainratein": 0.000, "eventrainin": 0.118, "hourlyrainin": 0.000, "dailyrainin": 0.118, "weeklyrainin": 0.118, "monthlyrainin": 0.378, "yearlyrainin": 6.268, "solarradiation": 0.00, "uv": 0, "soilmoisture1": 0, "soilad1": 120, "wh65batt": 1, "wh25batt": 0, "console_batt": 2.5, "soilbatt1": 1.5, "leak_ch1": 0, "leakbatt1": 5, "leak_ch2": 1, "leakbatt2": 3, "tf_co2": 56.7, "humi_co2": 72, "pm25_co2": 24.7, "pm25_24h_co2": 29.4, "pm10_co2": 24.7, "pm10_24h_co2": 29.9, "co2": 455, "co2_24h": 464, "co2_batt": 6, "tf_ch1": 71.1, "tf_batt1": 1.40, "freq": "868M", "model": "HP1000SE-PRO_Pro_V1.6.0", } def usage(): print("Usage: {0} host port".format(sys.argv[0])) if __name__ == "__main__": if len(sys.argv) < 3: usage() exit(1) host = sys.argv[1] port = sys.argv[2] # add a sensor if len(sys.argv) > 3 and sys.argv[3] == "add": paramset_b["humidity2"] = 21 print("Connecting to host {0} on port {0}".format(host, port)) conn = http.client.HTTPConnection(host, port) headers = {"Content-type": "application/x-www-form-urlencoded"} params = urllib.parse.urlencode(paramset_b) print(params) conn.request("POST", "", params, headers) response = conn.getresponse() print(response.status, response.reason) conn.close() aioecowitt-2025.3.1/requirements_tests.txt000066400000000000000000000002171476205021300206210ustar00rootroot00000000000000pytest==8.3.5 pytest-aiohttp==1.1.0 pytest-timeout==2.3.1 black==25.1.0 flake8==7.1.2 isort==6.0.1 mypy==1.15.0 pydocstyle==6.3.0 pylint==3.3.4aioecowitt-2025.3.1/setup.cfg000066400000000000000000000050741476205021300157420ustar00rootroot00000000000000[flake8] exclude = .venv,.git,.tox,docs,venv,bin,lib,deps,build # To work with Black max-line-length = 100 # E501: line too long # W503: Line break occurred before a binary operator # E203: Whitespace before ':' # D202 No blank lines allowed after function docstring # W504 line break after binary operator ignore = E501, W503, E203, D202, W504, E266 per-file-ignores = __init__.py:F401 [isort] profile = black multi_line_output = 3 include_trailing_comma = True force_grid_wrap = 0 use_parentheses = True line_length = 88 [mypy] python_version = 3.9 ignore_errors = true follow_imports = silent ignore_missing_imports = true warn_incomplete_stub = true warn_redundant_casts = true warn_unused_configs = true [pydocstyle] add-ignore = D202 [pylint.master] ignore=tests ignore-patterns=app_vars # Use a conservative default here; 2 should speed up most setups and not hurt # any too bad. Override on command line as appropriate. jobs=2 persistent=no suggestion-mode=yes extension-pkg-whitelist=taglib,orjson [pylint.basic] good-names=id,i,j,k,ex,Run,_,fp,T,ev [pylint.messages_control] # Reasons disabled: # format - handled by black # locally-disabled - it spams too much # duplicate-code - unavoidable # cyclic-import - doesn't test if both import on load # unused-argument - generic callbacks and setup methods create a lot of warnings # too-many-* - are not enforced for the sake of readability # too-few-* - same as too-many-* # abstract-method - with intro of async there are always methods missing # inconsistent-return-statements - doesn't handle raise # too-many-ancestors - it's too strict. # wrong-import-order - isort guards this # fixme - project is in development phase # c-extension-no-member - it was giving me headaches disable= format, abstract-method, cyclic-import, duplicate-code, inconsistent-return-statements, locally-disabled, not-context-manager, too-few-public-methods, too-many-ancestors, too-many-arguments, too-many-branches, too-many-instance-attributes, too-many-lines, too-many-locals, too-many-public-methods, too-many-return-statements, too-many-statements, too-many-boolean-expressions, unused-argument, wrong-import-order, fixme, c-extension-no-member # enable useless-suppression temporarily every now and then to clean them up enable= use-symbolic-message-instead [pylint.reports] score=no [pylint.refactoring] # Maximum number of nested blocks for function / method body max-nested-blocks=15 [pylint.typecheck] # For attrs ignored-classes=_CountingAttr [pylint.format] expected-line-ending-format=LF aioecowitt-2025.3.1/setup.py000066400000000000000000000026171476205021300156330ustar00rootroot00000000000000"""Setup module for EcoWitt.""" from pathlib import Path from setuptools import find_packages, setup PROJECT_DIR = Path(__file__).parent.resolve() README_FILE = PROJECT_DIR / "README.md" VERSION = "2025.3.1" setup( name="aioecowitt", version=VERSION, url="https://github.com/home-assistant-libs/aioecowitt", download_url="https://github.com/home-assistant-libs/aioecowitt", author="Home Assistant Team", author_email="hello@home-assistant.io", description="Python wrapper for EcoWitt Protocol", long_description=README_FILE.read_text(encoding="utf-8"), long_description_content_type="text/markdown", packages=find_packages(exclude=["tests.*", "tests", "misc"]), package_data={"aioecowitt": ["py.typed"]}, python_requires=">=3.9", install_requires=["aiohttp>3", "meteocalc>=1.1.0"], entry_points={"console_scripts": ["ecowitt-testserver = aioecowitt.__main__:main"]}, include_package_data=True, zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Home Automation", "License :: OSI Approved :: Apache Software License", ], ) aioecowitt-2025.3.1/tests/000077500000000000000000000000001476205021300152555ustar00rootroot00000000000000aioecowitt-2025.3.1/tests/__init__.py000066400000000000000000000000301476205021300173570ustar00rootroot00000000000000"""Init test folder.""" aioecowitt-2025.3.1/tests/conftest.py000066400000000000000000000007601476205021300174570ustar00rootroot00000000000000import pytest from aioecowitt import server @pytest.fixture def ecowitt_server(): """EcoWitt server fixture.""" ecowitt_server = server.EcoWittListener() yield ecowitt_server @pytest.fixture def ecowitt_http(event_loop, aiohttp_raw_server, aiohttp_client, ecowitt_server): """EcoWitt HTTP fixture.""" raw_server = event_loop.run_until_complete( aiohttp_raw_server(ecowitt_server.handler) ) return event_loop.run_until_complete(aiohttp_client(raw_server)) aioecowitt-2025.3.1/tests/const.py000066400000000000000000000046221476205021300167610ustar00rootroot00000000000000"""Constante weather data for testings.""" EASYWEATHER_DATA = { "PASSKEY": "34271334ED1FADA6D8B988B14267E55D", "stationtype": "EasyWeatherV1.4.9", "dateutc": "2020-05-04 14:34:26", "tempinf": "79.0", "humidityin": "33", "baromrelin": "28.583", "baromabsin": "28.583", "tempf": "70.3", "humidity": "32", "winddir": "200", "windspeedmph": "0.4", "windgustmph": "1.1", "rainratein": "0.000", "eventrainin": "0.000", "dailyrainin": "0.000", "weeklyrainin": "0.079", "monthlyrainin": "0.079", "yearlyrainin": "0.079", "solarradiation": "205.52", "uv": "2", "freq": "915M", "model": "HP3500_V1.6.2", } GW2000A_DATA = { "PASSKEY": "345544D8EAF42E1B8824A86D8250D5A3", "stationtype": "GW2000A_V2.1.5", "runtime": "188738", "dateutc": "2022-07-15 15:26:14", "tempinf": "78.80", "humidityin": "53", "baromrelin": "27.885", "baromabsin": "27.885", "tempf": "87.08", "humidity": "34", "winddir": "289", "windspeedmph": "2.91", "windgustmph": "3.13", "maxdailygust": "12.53", "solarradiation": "530.62", "uv": "4", "rrain_piezo": "0.000", "erain_piezo": "0.000", "hrain_piezo": "0.000", "drain_piezo": "0.000", "wrain_piezo": "0.000", "mrain_piezo": "0.000", "yrain_piezo": "0.000", "leak_ch1": "0", "leakbatt1": "5", "soilad1": "120", "leafwetness_ch1": "14", "leaf_batt1": "1.78", "ws90cap_volt": "5.4", "ws90_ver": "119", "wh90batt": "2.74", "console_batt": "2.5", "freq": "868M", "model": "GW2000A", } GW2000A_V3_DATA = { "PASSKEY": "345544D8EAF42E1B8824A86D8250D5A3", "stationtype": "GW2000A_V3.1.0", "runtime": "158060", "heap": "124256", "dateutc": "2024-02-08 10: 36: 28", "tempinf": "69.44", "humidityin": "36", "baromrelin": "26.175", "baromabsin": "26.175", "tempf": "64.76", "humidity": "48", "winddir": "293", "windspeedmph": "0.00", "windgustmph": "0.00", "maxdailygust": "1.34", "solarradiation": "3.87", "uv": "0", "rrain_piezo": "0.000", "erain_piezo": "0.000", "hrain_piezo": "0.000", "drain_piezo": "0.000", "wrain_piezo": "0.000", "mrain_piezo": "0.000", "yrain_piezo": "0.000", "ws90cap_volt": "1.3", "ws90_ver": "133", "wh90batt": "2.90", "freq": "868M", "model": "GW2000A", "interval": "60", } aioecowitt-2025.3.1/tests/test_calc.py000066400000000000000000000064221476205021300175740ustar00rootroot00000000000000"""Test for calulcated values from calc.py""" from aioecowitt import calc from .const import EASYWEATHER_DATA, GW2000A_DATA def test_gw2000a_v2(): """Test Calculated values from GW2000A_V2""" values = calc.weather_datapoints(GW2000A_DATA) assert values == { "PASSKEY": "345544D8EAF42E1B8824A86D8250D5A3", "baromabshpa": 944.2, "baromabsin": 27.885, "baromrelhpa": 944.2, "baromrelin": 27.885, "dateutc": "2022-07-15 15:26:14", "dewpointc": 13.0, "dewpointf": 55.3, "dewpointinc": 15.7, "dewpointinf": 60.2, "drain_piezo": 0.0, "drain_piezomm": 0.0, "erain_piezo": 0.0, "erain_piezomm": 0.0, "freq": "868M", "hrain_piezo": 0.0, "hrain_piezomm": 0.0, "humidity": 34, "humidityin": 53, "maxdailygust": 12.53, "maxdailygustkmh": 20.2, "model": "GW2000A", "mrain_piezo": 0.0, "mrain_piezomm": 0.0, "rrain_piezo": 0.0, "rrain_piezomm": 0.0, "runtime": "188738", "solarradiation": 530.62, "solarradiation_lux": 67167.1, "stationtype": "GW2000A_V2.1.5", "tempc": 30.6, "tempf": 87.08, "tempfeelsc": 29.7, "tempfeelsf": 85.5, "tempinc": 26.0, "tempinf": 78.8, "uv": 4, "wh90batt": 2.74, "console_batt": 2.5, "windchillc": None, "windchillf": None, "winddir": 289, "windgustkmh": 5.0, "windgustmph": 3.13, "windspeedkmh": 4.7, "windspeedmph": 2.91, "wrain_piezo": 0.0, "wrain_piezomm": 0.0, "leaf_batt1": 1.78, "leafwetness_ch1": 14, "leak_ch1": 0, "leakbatt1": 100, "soilad1": "120", "ws90_ver": "119", "ws90cap_volt": 5.4, "yrain_piezo": 0.0, "yrain_piezomm": 0.0, } def test_easyweather(): """Test EasyWeather station.""" values = calc.weather_datapoints(EASYWEATHER_DATA) assert values == { "PASSKEY": "34271334ED1FADA6D8B988B14267E55D", "baromabshpa": 967.8, "baromabsin": 28.583, "baromrelhpa": 967.8, "baromrelin": 28.583, "dailyrainin": 0.0, "dailyrainmm": 0.0, "dateutc": "2020-05-04 14:34:26", "dewpointc": 3.9, "dewpointf": 39.1, "dewpointinc": 8.6, "dewpointinf": 47.4, "eventrainin": 0.0, "eventrainmm": 0.0, "freq": "915M", "humidity": 32, "humidityin": 33, "model": "HP3500_V1.6.2", "monthlyrainin": 0.079, "monthlyrainmm": 2.0, "rainratein": 0.0, "rainratemm": 0.0, "solarradiation": 205.52, "solarradiation_lux": 26015.2, "stationtype": "EasyWeatherV1.4.9", "tempc": 21.3, "tempf": 70.3, "tempfeelsc": 21.3, "tempfeelsf": 70.3, "tempinc": 26.1, "tempinf": 79.0, "uv": 2, "weeklyrainin": 0.079, "weeklyrainmm": 2.0, "windchillc": None, "windchillf": None, "winddir": 200, "windgustkmh": 1.8, "windgustmph": 1.1, "windspeedkmh": 0.6, "windspeedmph": 0.4, "yearlyrainin": 0.079, "yearlyrainmm": 2.0, } aioecowitt-2025.3.1/tests/test_sensor.py000066400000000000000000000025011476205021300201750ustar00rootroot00000000000000"""Test ecowitt sensor module.""" import pytest from aioecowitt import server from .const import GW2000A_V3_DATA from aioecowitt import sensor def test_update_listener() -> None: """Test on change get updates from callback.""" ecowit_sensor = sensor.EcoWittSensor( "test", "test", sensor.EcoWittSensorTypes.TEMPERATURE_C, "test" ) called = False def on_change() -> None: """Test callback.""" nonlocal called called = True ecowit_sensor.update_cb.append(on_change) ecowit_sensor.update_value(10, 0, 0) assert called called = False ecowit_sensor.update_value(10, 0, 0) assert not called ecowit_sensor.update_value(11, 0, 0) assert called @pytest.mark.asyncio async def test_heap_field(ecowitt_server, ecowitt_http) -> None: """Test handling of heap field.""" heap_sensor = None def on_change(sensor: server.EcoWittSensor) -> None: """Test callback.""" if sensor.key == "heap": nonlocal heap_sensor heap_sensor = sensor ecowitt_server.new_sensor_cb.append(on_change) resp = await ecowitt_http.post("/", data=GW2000A_V3_DATA) assert resp.status == 200 text = await resp.text() assert text == "OK" assert heap_sensor assert heap_sensor.value == GW2000A_V3_DATA["heap"] aioecowitt-2025.3.1/tests/test_server.py000066400000000000000000000043431476205021300202000ustar00rootroot00000000000000"""EcoWitt server tests.""" import pytest from aioecowitt import server from .const import GW2000A_DATA, EASYWEATHER_DATA # pylint: disable=redefined-outer-name @pytest.mark.asyncio async def test_server_start(ecowitt_server, ecowitt_http) -> None: """Test server start.""" sensors = [] def on_change(sensor: server.EcoWittSensor) -> None: """Test callback.""" sensors.append(sensor) ecowitt_server.new_sensor_cb.append(on_change) resp = await ecowitt_http.post("/", data=GW2000A_DATA) assert resp.status == 200 text = await resp.text() assert text == "OK" assert len(sensors) == 52 assert len(ecowitt_server.sensors) == 52 assert len(ecowitt_server.stations) == 1 assert "PASSKEY" not in ecowitt_server.last_values[GW2000A_DATA["PASSKEY"]] @pytest.mark.asyncio async def test_server_token(ecowitt_server, ecowitt_http) -> None: """Test server start.""" sensors = [] path = "/test" ecowitt_server.path = path def on_change(sensor: server.EcoWittSensor) -> None: """Test callback.""" sensors.append(sensor) ecowitt_server.new_sensor_cb.append(on_change) resp = await ecowitt_http.post("/", data=GW2000A_DATA) assert resp.status == 404 resp = await ecowitt_http.post(path, data=GW2000A_DATA) assert resp.status == 200 text = await resp.text() assert text == "OK" assert len(sensors) == 52 assert len(ecowitt_server.sensors) == 52 assert len(ecowitt_server.stations) == 1 @pytest.mark.asyncio async def test_server_multi_stations(ecowitt_server, ecowitt_http) -> None: """Test server start and multiple stations.""" sensors = [] def on_change(sensor: server.EcoWittSensor) -> None: """Test callback.""" sensors.append(sensor) ecowitt_server.new_sensor_cb.append(on_change) resp = await ecowitt_http.post("/", data=GW2000A_DATA) assert resp.status == 200 text = await resp.text() assert text == "OK" resp = await ecowitt_http.post("/", data=EASYWEATHER_DATA) assert resp.status == 200 text = await resp.text() assert text == "OK" assert len(sensors) == 91 assert len(ecowitt_server.sensors) == 91 assert len(ecowitt_server.stations) == 2 aioecowitt-2025.3.1/tests/test_station.py000066400000000000000000000023641476205021300203540ustar00rootroot00000000000000"""Test for stations from station.py""" from aioecowitt import station from .const import EASYWEATHER_DATA, GW2000A_DATA def test_gw2000a_v2(): """Test Calculated values from GW2000A_V2""" ecowitt_station = station.extract_station(GW2000A_DATA) assert "PASSKEY" not in GW2000A_DATA assert "model" not in GW2000A_DATA assert "frequence" not in GW2000A_DATA assert "stationtype" not in GW2000A_DATA assert "ws90_ver" not in GW2000A_DATA assert ecowitt_station.station == "GW2000A_V2.1.5" assert ecowitt_station.key == "345544D8EAF42E1B8824A86D8250D5A3" assert ecowitt_station.model == "GW2000A" assert ecowitt_station.version == "119" assert ecowitt_station.frequence == "868M" def test_easyweather(): """Test EasyWeather station.""" ecowitt_station = station.extract_station(EASYWEATHER_DATA) assert "PASSKEY" not in EASYWEATHER_DATA assert "model" not in EASYWEATHER_DATA assert "frequence" not in EASYWEATHER_DATA assert "stationtype" not in EASYWEATHER_DATA assert ecowitt_station.station == "EasyWeatherV1.4.9" assert ecowitt_station.key == "34271334ED1FADA6D8B988B14267E55D" assert ecowitt_station.model == "HP3500_V1.6.2" assert ecowitt_station.frequence == "915M" aioecowitt-2025.3.1/tox.ini000066400000000000000000000005511476205021300154270ustar00rootroot00000000000000[tox] envlist = lint, black, tests [testenv] basepython = python3 deps = -r{toxinidir}/requirements_tests.txt [testenv:lint] ignore_errors = True commands = flake8 aioecowitt pylint aioecowitt [testenv:black] commands = black --target-version py39 --check aioecowitt setup.py tests [testenv:tests] commands = pytest --timeout=10 tests