pax_global_header 0000666 0000000 0000000 00000000064 14734324616 0014524 g ustar 00root root 0000000 0000000 52 comment=d5418829b103631ed35c9e2a4ec635f53512e72f
aiopegelonline-0.1.1/ 0000775 0000000 0000000 00000000000 14734324616 0014515 5 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/.devcontainer/ 0000775 0000000 0000000 00000000000 14734324616 0017254 5 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/.devcontainer/Dockerfile 0000664 0000000 0000000 00000000473 14734324616 0021252 0 ustar 00root root 0000000 0000000 FROM mcr.microsoft.com/vscode/devcontainers/python:0-3.9
# install test requirements
COPY requirements*.txt /tmp/pip-tmp/
RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements_dev.txt \
&& rm -rf /tmp/pip-tmp
# Set the default shell to bash instead of sh
ENV SHELL /bin/bash
aiopegelonline-0.1.1/.devcontainer/devcontainer.json 0000664 0000000 0000000 00000002160 14734324616 0022627 0 ustar 00root root 0000000 0000000 {
"name": "aiopegelonline Dev",
"context": "..",
"dockerFile": "Dockerfile",
"containerEnv": {
"DEVCONTAINER": "1"
},
"runArgs": [
"-e",
"GIT_EDITOR=code --wait"
],
"postCreateCommand": "pre-commit install",
"customizations": {
"vscode": {
"extensions": [
"ms-python.black-formatter",
"ms-python.vscode-pylance",
"ms-python.pylint"
],
"settings": {
"python.pythonPath": "/usr/local/bin/python",
"python.formatting.blackPath": "/usr/local/bin/black",
"python.formatting.provider": "black",
"python.testing.pytestArgs": [
"--no-cov",
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"files.trimTrailingWhitespace": true,
"terminal.integrated.profiles.linux": {
"zsh": {
"path": "/usr/bin/zsh"
}
},
"terminal.integrated.defaultProfile.linux": "zsh"
}
}
}
}
aiopegelonline-0.1.1/.github/ 0000775 0000000 0000000 00000000000 14734324616 0016055 5 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/.github/FUNDING.yml 0000664 0000000 0000000 00000000055 14734324616 0017672 0 ustar 00root root 0000000 0000000 custom: https://www.buymeacoffee.com/mib1185
aiopegelonline-0.1.1/.github/dependabot.yml 0000664 0000000 0000000 00000000471 14734324616 0020707 0 ustar 00root root 0000000 0000000 version: 2
updates:
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: monthly
groups:
gh-actions:
patterns: ["*"]
- package-ecosystem: pip
directory: "/"
schedule:
interval: monthly
groups:
pip-dependencies:
patterns: ["*"]
aiopegelonline-0.1.1/.github/release-drafter.yml 0000664 0000000 0000000 00000000660 14734324616 0021647 0 ustar 00root root 0000000 0000000 categories:
- title: "⚠ Breaking Changes"
labels:
- "breaking-change"
- title: "⬆️ Dependencies"
collapse-after: 1
labels:
- "dependencies"
template: |
## What's Changed
$CHANGES
---
You like my work?
aiopegelonline-0.1.1/.github/workflows/ 0000775 0000000 0000000 00000000000 14734324616 0020112 5 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/.github/workflows/release.yaml 0000664 0000000 0000000 00000004126 14734324616 0022421 0 ustar 00root root 0000000 0000000 name: Release
on:
push:
branches:
- main
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Check out the repository
uses: actions/checkout@v4.2.2
with:
fetch-depth: 2
- name: Set up Python
uses: actions/setup-python@v5.3.0
with:
python-version: "3.9"
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel build
- name: Check if there is a parent commit
id: check-parent-commit
run: |
echo "sha=$(git rev-parse --verify --quiet HEAD^)" >> $GITHUB_OUTPUT
- name: Check workspace
run: |
pwd ; ls -la
- name: Detect and tag new version
id: check-version
if: steps.check-parent-commit.outputs.sha
uses: salsify/action-detect-and-tag-new-version@v2.0.3
with:
version-command: |
sed -n 's/version = \"\(.*\)\"/\1/p' pyproject.toml
- name: Bump version for developmental release
if: "! steps.check-version.outputs.tag"
run: |
sed "s/version = \"\(.*\)\"/version = \"\1\.dev\.`date +%Y%m%d%H%M%S`\"/" -i pyproject.toml
- name: Build package
run: |
python -m build . --wheel
- name: Publish package on PyPI
if: steps.check-version.outputs.tag
uses: pypa/gh-action-pypi-publish@v1.12.2
with:
user: __token__
password: ${{ secrets.PYPI_TOKEN }}
- name: Publish package on TestPyPI
if: "! steps.check-version.outputs.tag"
uses: pypa/gh-action-pypi-publish@v1.12.2
with:
user: __token__
password: ${{ secrets.TEST_PYPI_TOKEN }}
repository_url: https://test.pypi.org/legacy/
- name: Publish release notes
uses: release-drafter/release-drafter@v6.0.0
with:
publish: ${{ steps.check-version.outputs.tag != '' }}
tag: ${{ steps.check-version.outputs.tag }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
aiopegelonline-0.1.1/.github/workflows/test.yml 0000664 0000000 0000000 00000004710 14734324616 0021616 0 ustar 00root root 0000000 0000000 # This workflow will install Python dependencies, run tests and lint
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
name: Test
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- name: Check out the repository
uses: actions/checkout@v4.2.2
- name: Set up Python 3.13
uses: actions/setup-python@v5.3.0
with:
python-version: "3.13"
- name: Install dependencies
run: |
python -m venv venv
. venv/bin/activate
python --version
pip install uv
uv pip install -r requirements_dev.txt -e .
- name: Run pre-commit
run: |
. venv/bin/activate
pre-commit run --all-files --show-diff-on-failure
pytest:
name: pytest ${{ matrix.python-version }}
runs-on: ubuntu-20.04
needs: pre-commit
strategy:
fail-fast: false
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
steps:
- name: Check out the repository
uses: actions/checkout@v4.2.2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5.3.0
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m venv venv
. venv/bin/activate
python --version
pip install uv
uv pip install -r requirements_dev.txt -e .
- name: Run tests
run: |
. venv/bin/activate
pytest tests --cov=aiopegelonline --cov-report=xml
codecov:
name: codecov
runs-on: ubuntu-20.04
needs: pytest
steps:
- name: Check out the repository
uses: actions/checkout@v4.2.2
- name: Set up Python 3.13
uses: actions/setup-python@v5.3.0
with:
python-version: "3.13"
- name: Install dependencies
run: |
python -m venv venv
. venv/bin/activate
python --version
pip install uv
uv pip install -r requirements_dev.txt -e .
- name: Run tests
run: |
. venv/bin/activate
pytest tests --cov=aiopegelonline --cov-report=xml
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
aiopegelonline-0.1.1/.gitignore 0000664 0000000 0000000 00000000055 14734324616 0016505 0 ustar 00root root 0000000 0000000 __pycache__/
*.egg
*.egg-info
.coverage
venv
aiopegelonline-0.1.1/.pre-commit-config.yaml 0000664 0000000 0000000 00000001616 14734324616 0021002 0 ustar 00root root 0000000 0000000 repos:
- repo: https://github.com/ambv/black
rev: 23.1.0
hooks:
- id: black
language_version: python3
args:
- --safe
- --quiet
files: ^(aiopegelonline|tests)/.+\.py$
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-docstring-first
- repo: https://github.com/PyCQA/pydocstyle
rev: 6.3.0
hooks:
- id: pydocstyle
files: ^(aiopegelonline|tests)/.+\.py$
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.7.1
hooks:
- id: prettier
stages: [manual]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v0.991"
hooks:
- id: mypy
files: ^(aiopegelonline|tests)/.+\.py$
aiopegelonline-0.1.1/LICENSE 0000664 0000000 0000000 00000026135 14734324616 0015531 0 ustar 00root root 0000000 0000000 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 [yyyy] [name of copyright owner]
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.
aiopegelonline-0.1.1/README.md 0000664 0000000 0000000 00000005111 14734324616 0015772 0 ustar 00root root 0000000 0000000 [](https://github.com/mib1185/aiopegelonline/actions/workflows/test.yml)
[](https://codecov.io/gh/mib1185/aiopegelonline)
[](https://codeclimate.com/github/mib1185/aiopegelonline/maintainability)
[](https://pypi.org/project/aiopegelonline)
[](https://pypi.org/project/aiopegelonline)
[](https://pypi.org/project/aiopegelonline)
[](https://github.com/psf/black)
# aiopegelonline
Asynchronous library to retrieve data from [PEGELONLINE](https://www.pegelonline.wsv.de/).
:warning: **this is in early development state** :warning:
breaking changes may occure at every time
## Requirements
- Python >= 3.9
- aiohttp
## Installation
```bash
pip install aiopegelonline
```
## Examples
### Get all available measurement stations
```python
import asyncio
import aiohttp
from aiopegelonline import PegelOnline
async def main():
async with aiohttp.ClientSession() as session:
pegelonline = PegelOnline(session)
stations = await pegelonline.async_get_all_stations()
for uuid, station in stations.items():
print(f"uuid: {uuid} name: {station.name}")
if __name__ == "__main__":
asyncio.run(main())
```
### Get current measurement
```python
import asyncio
import aiohttp
from aiopegelonline import PegelOnline
async def main():
async with aiohttp.ClientSession() as session:
pegelonline = PegelOnline(session)
measurements = await pegelonline.async_get_station_measurements("70272185-b2b3-4178-96b8-43bea330dcae")
for name, data in measurements.as_dict().items():
if data is None:
print(f"{name} not provided by measurement station")
else:
print(f"{name}: {data.value} {data.uom}")
if __name__ == "__main__":
asyncio.run(main())
```
## References
- [PEGELONLINE api reference (German)](https://www.pegelonline.wsv.de/webservice/dokuRestapi)
---
You like my work?
aiopegelonline-0.1.1/aiopegelonline/ 0000775 0000000 0000000 00000000000 14734324616 0017507 5 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/aiopegelonline/__init__.py 0000664 0000000 0000000 00000007706 14734324616 0021632 0 ustar 00root root 0000000 0000000 """Pegelonline library."""
from __future__ import annotations
import json
from aiohttp.client import ClientSession
from .const import BASE_URL, CONNECT_ERRORS, LOGGER
from .exceptions import PegelonlineDataError
from .models import CacheEntry, Station, StationMeasurements
class PegelOnline:
"""Pegelonline api."""
def __init__(self, aiohttp_session: ClientSession) -> None:
"""Pegelonline api init."""
self.session: ClientSession = aiohttp_session
self.cache: dict[str, CacheEntry] = {}
async def _async_do_request(self, url: str, params: dict):
"""Perform an async request."""
cache_key = f"{url}_{params}"
if cache_key not in self.cache:
self.cache[cache_key] = CacheEntry(None, None)
cache_entry = self.cache[cache_key]
headers = {}
if (etag := cache_entry.etag) is not None:
headers = {"If-None-Match": etag}
LOGGER.debug("REQUEST url: %s params: %s headers: %s", url, params, headers)
try:
async with self.session.get(url, params=params, headers=headers) as resp:
result = await resp.text()
LOGGER.debug("RESPONSE status: %s text: %s", resp.status, result)
if resp.status == 304: # 304 = not modified
return cache_entry.result
if cache_entry.etag is None:
cache_entry.etag = resp.headers.get("Etag")
result = json.loads(result)
cache_entry.result = result
if resp.status != 200:
raise PegelonlineDataError(
result.get("status"), result.get("message")
)
except CONNECT_ERRORS as err:
LOGGER.debug("connection error", exc_info=True)
LOGGER.error(
"Error while getting data: %s: %s",
err.__class__.__name__,
err.__class__.__cause__,
)
raise err
return result
async def async_get_all_stations(self) -> dict[str, Station]:
"""Get all stations."""
stations = await self._async_do_request(
f"{BASE_URL}/stations.json", {"prettyprint": "false"}
)
result = {}
for station in stations:
result[station["uuid"]] = Station(station)
LOGGER.debug("all stations: %s", result)
return result
async def async_get_nearby_stations(
self, latitude: float, longitude: float, radius: int
) -> dict[str, Station]:
"""Get stations within defined radius at given position."""
stations = await self._async_do_request(
f"{BASE_URL}/stations.json",
{
"prettyprint": "false",
"latitude": latitude,
"longitude": longitude,
"radius": radius,
},
)
result = {}
for station in stations:
result[station["uuid"]] = Station(station)
LOGGER.debug("nearby stations: %s", result)
return result
async def async_get_station_details(self, uuid: str) -> Station:
"""Get station details."""
station = await self._async_do_request(
f"{BASE_URL}/stations/{uuid}.json", {"prettyprint": "false"}
)
result = Station(station)
LOGGER.debug("station %s details: %s", uuid, result)
return result
async def async_get_station_measurements(self, uuid: str) -> StationMeasurements:
"""Get all current measurements of a station."""
station = await self._async_do_request(
f"{BASE_URL}/stations/{uuid}.json",
{
"prettyprint": "false",
"includeTimeseries": "true",
"includeCurrentMeasurement": "true",
},
)
result = StationMeasurements(station["timeseries"])
LOGGER.debug("station %s measurements: %s", uuid, result)
return result
aiopegelonline-0.1.1/aiopegelonline/const.py 0000664 0000000 0000000 00000000426 14734324616 0021211 0 ustar 00root root 0000000 0000000 """Constants for aiopegelonline."""
import asyncio
import logging
import aiohttp
LOGGER = logging.getLogger(__package__)
BASE_URL = "https://www.pegelonline.wsv.de/webservices/rest-api/v2"
CONNECT_ERRORS = (
aiohttp.ClientError,
asyncio.TimeoutError,
OSError,
)
aiopegelonline-0.1.1/aiopegelonline/exceptions.py 0000664 0000000 0000000 00000000662 14734324616 0022246 0 ustar 00root root 0000000 0000000 """aiopegelonline exceptions."""
from __future__ import annotations
class PegelonlineError(Exception):
"""Base class for pegelonline errors."""
class PegelonlineDataError(PegelonlineError):
"""Raised to indicate invalid data."""
def __init__(self, code: int, message: str = ""):
"""Initialize JSON RPC errors."""
self.code = code
self.message = message
super().__init__(code, message)
aiopegelonline-0.1.1/aiopegelonline/models.py 0000664 0000000 0000000 00000007515 14734324616 0021354 0 ustar 00root root 0000000 0000000 """aiopegelonline models."""
from __future__ import annotations
from dataclasses import dataclass
class Station:
"""Representation of a station."""
def __init__(self, data: dict) -> None:
"""Initialize station class."""
self.uuid: str = data["uuid"]
self.name: str = data["longname"]
self.agency: str = data["agency"]
self.river_kilometer: float | None = data.get("km")
self.longitude: float | None = data.get("longitude")
self.latitude: float | None = data.get("latitude")
self.water_name: str = data["water"]["longname"]
self.base_data_url: str = (
f"https://www.pegelonline.wsv.de/gast/stammdaten?pegelnr={data['number']}"
)
def as_dict(self) -> dict[str, str | float | None]:
"""Return data das dict."""
return {
"uuid": self.uuid,
"name": self.name,
"agency": self.agency,
"river_kilometer": self.river_kilometer,
"longitude": self.longitude,
"latitude": self.latitude,
"water_name": self.water_name,
"base_data_url": self.base_data_url,
}
class CurrentMeasurement:
"""Representation of a current measurement."""
def __init__(self, data: dict) -> None:
"""Initialize current measurment class."""
self.uom: str = data["unit"]
self.value: float = data["currentMeasurement"]["value"]
def as_dict(self) -> dict[str, str | float]:
"""Return data das dict."""
return {
"uom": self.uom,
"value": self.value,
}
class StationMeasurements:
"""Representation of station measurements."""
def __init__(self, data: list[dict]) -> None:
"""Initialize station measurments class."""
self.air_temperature: CurrentMeasurement | None = None
self.clearance_height: CurrentMeasurement | None = None
self.oxygen_level: CurrentMeasurement | None = None
self.ph_value: CurrentMeasurement | None = None
self.water_speed: CurrentMeasurement | None = None
self.water_flow: CurrentMeasurement | None = None
self.water_level: CurrentMeasurement | None = None
self.water_temperature: CurrentMeasurement | None = None
for measurement in data:
if measurement["shortname"] == "DFH":
self.clearance_height = CurrentMeasurement(measurement)
elif measurement["shortname"] == "LT":
self.air_temperature = CurrentMeasurement(measurement)
elif measurement["shortname"] == "O2":
self.oxygen_level = CurrentMeasurement(measurement)
elif measurement["shortname"] == "PH":
self.ph_value = CurrentMeasurement(measurement)
elif measurement["shortname"] == "Q":
self.water_flow = CurrentMeasurement(measurement)
elif measurement["shortname"] == "VA":
self.water_speed = CurrentMeasurement(measurement)
elif measurement["shortname"] == "W":
self.water_level = CurrentMeasurement(measurement)
elif measurement["shortname"] == "WT":
self.water_temperature = CurrentMeasurement(measurement)
def as_dict(self) -> dict[str, CurrentMeasurement | None]:
"""Return data das dict."""
return {
"air_temperature": self.air_temperature,
"clearance_height": self.clearance_height,
"oxygen_level": self.oxygen_level,
"ph_value": self.ph_value,
"water_speed": self.water_speed,
"water_flow": self.water_flow,
"water_level": self.water_level,
"water_temperature": self.water_temperature,
}
@dataclass
class CacheEntry:
"""Representation of response cache entry."""
etag: str | None
result: dict | None
aiopegelonline-0.1.1/aiopegelonline/py.typed 0000664 0000000 0000000 00000000000 14734324616 0021174 0 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/pyproject.toml 0000664 0000000 0000000 00000002363 14734324616 0017435 0 ustar 00root root 0000000 0000000 [build-system]
requires = ["setuptools==75.6.0"]
build-backend = "setuptools.build_meta"
[project]
name = "aiopegelonline"
version = "0.1.1"
description = "Asynchronous library to retrieve data from PEGELONLINE."
authors = [{ name = "mib1185" }]
readme = "README.md"
license.text = "Apache-2.0"
requires-python = '>=3.9'
dependencies = ["aiohttp"]
classifiers = [
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Software Development :: Libraries :: Python Modules",
]
[project.urls]
homepage = 'https://github.com/mib1185/aiopegelonline'
repository = 'https://github.com/mib1185/aiopegelonline'
[tool.setuptools]
package-data = { "aiopegelonline" = ["py.typed"] }
platforms = ["any"]
packages = ["aiopegelonline"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
[tool.isort]
profile = "black"
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
line_length = 88
aiopegelonline-0.1.1/requirements.txt 0000664 0000000 0000000 00000000010 14734324616 0017770 0 ustar 00root root 0000000 0000000 aiohttp
aiopegelonline-0.1.1/requirements_dev.txt 0000664 0000000 0000000 00000000322 14734324616 0020634 0 ustar 00root root 0000000 0000000 -r requirements.txt
aioresponses==0.7.7
black==24.10.0
mypy==1.13.0
pre-commit-hooks==5.0.0
pre-commit==4.0.1
pylint==3.3.2
pytest-asyncio==0.24.0
pytest-cov==6.0.0
pytest==8.3.4
reorder-python-imports==3.14.0
aiopegelonline-0.1.1/tests/ 0000775 0000000 0000000 00000000000 14734324616 0015657 5 ustar 00root root 0000000 0000000 aiopegelonline-0.1.1/tests/__init__.py 0000664 0000000 0000000 00000000040 14734324616 0017762 0 ustar 00root root 0000000 0000000 """Tests for aiopegelonline."""
aiopegelonline-0.1.1/tests/conftest.py 0000664 0000000 0000000 00000004142 14734324616 0020057 0 ustar 00root root 0000000 0000000 """Test config for aiopegelonline."""
from __future__ import annotations
import json
import aiohttp
import pytest
from aioresponses import CallbackResult, aioresponses
from aiopegelonline import PegelOnline
from aiopegelonline.const import BASE_URL
from .const import MOCK_DATA, MOCK_STATION_DATA_DRESDEN
@pytest.fixture
def mock_aioresponse():
"""Mock a web request and provide a response."""
with aioresponses() as m:
yield m
@pytest.fixture
async def mock_pegelonline():
"""Return PegelOnline session."""
session = aiohttp.ClientSession()
api = PegelOnline(session)
yield api
await session.close()
@pytest.fixture
def mock_pegelonline_with_data(mock_aioresponse, mock_pegelonline):
"""Comfort fixture to initialize pegelonline session."""
async def data_to_pegelonline() -> PegelOnline:
"""Initialize PegelOnline session."""
for path, data in MOCK_DATA.items():
mock_aioresponse.get(
f"{BASE_URL}/{path}",
status=data["status"],
body=json.dumps(data["body"]),
exception=data.get("exception"),
)
return mock_pegelonline
return data_to_pegelonline
@pytest.fixture
def mock_pegelonline_with_cached_data(mock_aioresponse, mock_pegelonline):
"""Comfort fixture to initialize pegelonline session with cached data."""
def cache_response(_, **kwargs) -> CallbackResult:
etag = "etag_station_dresden"
if (headers := kwargs.get("headers")) and headers.get("If-None-Match") == etag:
return CallbackResult(status=304, body="", headers={"Etag": etag})
return CallbackResult(
status=200,
body=json.dumps(MOCK_STATION_DATA_DRESDEN),
headers={"Etag": etag},
)
async def data_to_pegelonline() -> PegelOnline:
"""Initialize PegelOnline session."""
query = f"{BASE_URL}/stations/70272185-xxxx-xxxx-xxxx-43bea330dcae.json?prettyprint=false"
mock_aioresponse.get(query, callback=cache_response, repeat=True)
return mock_pegelonline
return data_to_pegelonline
aiopegelonline-0.1.1/tests/const.py 0000664 0000000 0000000 00000012360 14734324616 0017361 0 ustar 00root root 0000000 0000000 """Constants for aiopegelonline tests."""
from aiohttp import ClientError
MOCK_STATION_DATA_DRESDEN: dict = {
"uuid": "70272185-xxxx-xxxx-xxxx-43bea330dcae",
"number": "501060",
"shortname": "DRESDEN",
"longname": "DRESDEN",
"km": 55.63,
"agency": "STANDORT DRESDEN",
"longitude": 13.738831783620384,
"latitude": 51.054459765598125,
"water": {"shortname": "ELBE", "longname": "ELBE"},
}
MOCK_MEASUREMENT_DATA_HANAU_BRIDGE: dict = {
"uuid": "07374faf-xxxx-xxxx-xxxx-adc0e0784c4b",
"number": "24700347",
"shortname": "HANAU BRÜCKE DFH",
"longname": "HANAU BRÜCKE DFH",
"km": 56.398,
"agency": "ASCHAFFENBURG",
"water": {"shortname": "MAIN", "longname": "MAIN"},
"timeseries": [
{
"shortname": "DFH",
"longname": "DURCHFAHRTSHÖHE",
"unit": "cm",
"equidistance": 15,
"currentMeasurement": {
"timestamp": "2023-07-26T19:45:00+02:00",
"value": 715,
},
"gaugeZero": {
"unit": "m. ü. NHN",
"value": 106.501,
"validFrom": "2019-11-01",
},
}
],
}
MOCK_STATION_DATA_WUERZBURG: dict = {
"uuid": "915d76e1-xxxx-xxxx-xxxx-4d144cd771cc",
"number": "24300600",
"shortname": "WÜRZBURG",
"longname": "WÜRZBURG",
"km": 251.97,
"agency": "SCHWEINFURT",
"longitude": 9.925968763247354,
"latitude": 49.79620901036012,
"water": {"shortname": "MAIN", "longname": "MAIN"},
}
MOCK_MEASUREMENT_DATA_WUERZBURG: dict = {
**MOCK_STATION_DATA_WUERZBURG,
"timeseries": [
{
"shortname": "W",
"longname": "WASSERSTAND ROHDATEN",
"unit": "cm",
"equidistance": 15,
"currentMeasurement": {
"timestamp": "2023-07-26T19:15:00+02:00",
"value": 159,
"stateMnwMhw": "normal",
"stateNswHsw": "normal",
},
"gaugeZero": {
"unit": "m. ü. NHN",
"value": 164.511,
"validFrom": "2019-11-01",
},
},
{
"shortname": "LT",
"longname": "LUFTTEMPERATUR",
"unit": "°C",
"equidistance": 60,
"currentMeasurement": {
"timestamp": "2023-07-26T19:00:00+02:00",
"value": 21.2,
},
},
{
"shortname": "WT",
"longname": "WASSERTEMPERATUR",
"unit": "°C",
"equidistance": 60,
"currentMeasurement": {
"timestamp": "2023-07-26T19:00:00+02:00",
"value": 22.1,
},
},
{
"shortname": "VA",
"longname": "FLIESSGESCHWINDIGKEIT",
"unit": "m/s",
"equidistance": 15,
"currentMeasurement": {
"timestamp": "2023-07-26T19:15:00+02:00",
"value": 0.58,
},
},
{
"shortname": "O2",
"longname": "SAUERSTOFFGEHALT",
"unit": "mg/l",
"equidistance": 60,
"currentMeasurement": {
"timestamp": "2023-07-26T19:00:00+02:00",
"value": 8.4,
},
},
{
"shortname": "PH",
"longname": "PH-WERT",
"unit": "--",
"equidistance": 60,
"currentMeasurement": {
"timestamp": "2023-07-26T19:00:00+02:00",
"value": 8.1,
},
},
{
"shortname": "Q",
"longname": "ABFLUSS",
"unit": "m³/s",
"equidistance": 15,
"currentMeasurement": {
"timestamp": "2023-07-26T19:00:00+02:00",
"value": 102,
},
},
],
}
MOCK_DATA: dict = {
"stations.json?prettyprint=false": {
"status": 200,
"body": [
MOCK_STATION_DATA_DRESDEN,
MOCK_STATION_DATA_WUERZBURG,
],
},
"stations.json?prettyprint=false&latitude=13&longitude=51&radius=25": {
"status": 200,
"body": [
MOCK_STATION_DATA_DRESDEN,
],
},
"stations.json?prettyprint=false&latitude=10&longitude=45&radius=25": {
"status": 200,
"body": [],
},
"stations/70272185-xxxx-xxxx-xxxx-43bea330dcae.json?prettyprint=false": {
"status": 200,
"body": MOCK_STATION_DATA_DRESDEN,
},
"stations/INVALID_UUID.json?prettyprint=false": {
"status": 404,
"body": {
"status": 404,
"message": "station not found",
},
},
"stations/CONNECT_ERROR.json?prettyprint=false": {
"status": None,
"body": None,
"exception": ClientError,
},
"stations/915d76e1-xxxx-xxxx-xxxx-4d144cd771cc.json?prettyprint=false&includeTimeseries=true&includeCurrentMeasurement=true": {
"status": 200,
"body": MOCK_MEASUREMENT_DATA_WUERZBURG,
},
"stations/07374faf-xxxx-xxxx-xxxx-adc0e0784c4b.json?prettyprint=false&includeTimeseries=true&includeCurrentMeasurement=true": {
"status": 200,
"body": MOCK_MEASUREMENT_DATA_HANAU_BRIDGE,
},
}
aiopegelonline-0.1.1/tests/test_aiopegelonline.py 0000664 0000000 0000000 00000016037 14734324616 0022271 0 ustar 00root root 0000000 0000000 """Tests for aiopegelonline."""
from __future__ import annotations
import pytest
from aiohttp import ClientError
from aiopegelonline.exceptions import PegelonlineDataError
from aiopegelonline.models import Station, StationMeasurements
async def test_get_all_stations(mock_pegelonline_with_data):
"""Test async_get_all_stations."""
api = await mock_pegelonline_with_data()
stations = await api.async_get_all_stations()
assert len(stations) == 2
station = stations["70272185-xxxx-xxxx-xxxx-43bea330dcae"]
assert isinstance(station, Station)
assert station.as_dict() == {
"uuid": "70272185-xxxx-xxxx-xxxx-43bea330dcae",
"name": "DRESDEN",
"agency": "STANDORT DRESDEN",
"river_kilometer": 55.63,
"longitude": 13.738831783620384,
"latitude": 51.054459765598125,
"water_name": "ELBE",
"base_data_url": "https://www.pegelonline.wsv.de/gast/stammdaten?pegelnr=501060",
}
station = stations["915d76e1-xxxx-xxxx-xxxx-4d144cd771cc"]
assert isinstance(station, Station)
assert station.uuid == "915d76e1-xxxx-xxxx-xxxx-4d144cd771cc"
assert station.name == "WÜRZBURG"
assert station.agency == "SCHWEINFURT"
assert station.river_kilometer == 251.97
assert station.longitude == 9.925968763247354
assert station.latitude == 49.79620901036012
assert station.water_name == "MAIN"
assert (
station.base_data_url
== "https://www.pegelonline.wsv.de/gast/stammdaten?pegelnr=24300600"
)
async def test_get_nearby_stations(mock_pegelonline_with_data):
"""Test async_get_nearby_stations."""
api = await mock_pegelonline_with_data()
stations = await api.async_get_nearby_stations(13, 51, 25)
assert len(stations) == 1
station = stations["70272185-xxxx-xxxx-xxxx-43bea330dcae"]
assert isinstance(station, Station)
assert station.uuid == "70272185-xxxx-xxxx-xxxx-43bea330dcae"
assert station.name == "DRESDEN"
assert station.agency == "STANDORT DRESDEN"
assert station.river_kilometer == 55.63
assert station.longitude == 13.738831783620384
assert station.latitude == 51.054459765598125
assert station.water_name == "ELBE"
assert (
station.base_data_url
== "https://www.pegelonline.wsv.de/gast/stammdaten?pegelnr=501060"
)
async def test_get_nearby_stations_no_stations(mock_pegelonline_with_data):
"""Test async_get_nearby_stations."""
api = await mock_pegelonline_with_data()
stations = await api.async_get_nearby_stations(10, 45, 25)
assert len(stations) == 0
async def test_get_station_details(mock_pegelonline_with_data):
"""Test async_get_station_details."""
api = await mock_pegelonline_with_data()
station = await api.async_get_station_details(
"70272185-xxxx-xxxx-xxxx-43bea330dcae"
)
assert isinstance(station, Station)
assert station.uuid == "70272185-xxxx-xxxx-xxxx-43bea330dcae"
assert station.name == "DRESDEN"
assert station.agency == "STANDORT DRESDEN"
assert station.river_kilometer == 55.63
assert station.longitude == 13.738831783620384
assert station.latitude == 51.054459765598125
assert station.water_name == "ELBE"
assert (
station.base_data_url
== "https://www.pegelonline.wsv.de/gast/stammdaten?pegelnr=501060"
)
async def test_get_station_details_invalid(mock_pegelonline_with_data):
"""Test async_get_station_details with invalid uuid."""
api = await mock_pegelonline_with_data()
with pytest.raises(PegelonlineDataError):
await api.async_get_station_details("INVALID_UUID")
async def test_get_station_details_connection_error(mock_pegelonline_with_data):
"""Test async_get_station_details with connection error."""
api = await mock_pegelonline_with_data()
with pytest.raises(ClientError):
await api.async_get_station_details("CONNECT_ERROR")
async def test_get_station_measurements(mock_pegelonline_with_data):
"""Test async_get_station_measurements."""
api = await mock_pegelonline_with_data()
measurement = await api.async_get_station_measurements(
"915d76e1-xxxx-xxxx-xxxx-4d144cd771cc"
)
assert isinstance(measurement, StationMeasurements)
assert measurement.air_temperature is not None
assert measurement.air_temperature.uom == "°C"
assert measurement.air_temperature.value == 21.2
assert measurement.clearance_height is None
assert measurement.oxygen_level is not None
assert measurement.oxygen_level.uom == "mg/l"
assert measurement.oxygen_level.value == 8.4
assert measurement.ph_value is not None
assert measurement.ph_value.uom == "--"
assert measurement.ph_value.value == 8.1
assert measurement.water_speed is not None
assert measurement.water_speed.uom == "m/s"
assert measurement.water_speed.value == 0.58
assert measurement.water_flow is not None
assert measurement.water_flow.uom == "m³/s"
assert measurement.water_flow.value == 102
assert measurement.water_level is not None
assert measurement.water_level.uom == "cm"
assert measurement.water_level.value == 159
assert measurement.water_temperature is not None
assert measurement.water_temperature.uom == "°C"
assert measurement.water_temperature.value == 22.1
measurement = await api.async_get_station_measurements(
"07374faf-xxxx-xxxx-xxxx-adc0e0784c4b"
)
assert isinstance(measurement, StationMeasurements)
assert measurement.clearance_height is not None
assert measurement.clearance_height.uom == "cm"
assert measurement.clearance_height.value == 715
assert measurement.clearance_height.as_dict() == {
"uom": "cm",
"value": 715,
}
assert measurement.as_dict() == {
"air_temperature": None,
"clearance_height": measurement.clearance_height,
"oxygen_level": None,
"ph_value": None,
"water_speed": None,
"water_flow": None,
"water_level": None,
"water_temperature": None,
}
async def test_get_station_details_cached(mock_pegelonline_with_cached_data):
"""Test response cache."""
api = await mock_pegelonline_with_cached_data()
station = await api.async_get_station_details(
"70272185-xxxx-xxxx-xxxx-43bea330dcae"
)
assert isinstance(station, Station)
assert station.uuid == "70272185-xxxx-xxxx-xxxx-43bea330dcae"
assert station.name == "DRESDEN"
assert station.agency == "STANDORT DRESDEN"
assert station.river_kilometer == 55.63
assert station.longitude == 13.738831783620384
assert station.latitude == 51.054459765598125
assert station.water_name == "ELBE"
station = await api.async_get_station_details(
"70272185-xxxx-xxxx-xxxx-43bea330dcae"
)
assert isinstance(station, Station)
assert station.uuid == "70272185-xxxx-xxxx-xxxx-43bea330dcae"
assert station.name == "DRESDEN"
assert station.agency == "STANDORT DRESDEN"
assert station.river_kilometer == 55.63
assert station.longitude == 13.738831783620384
assert station.latitude == 51.054459765598125
assert station.water_name == "ELBE"