pax_global_header00006660000000000000000000000064147620353030014515gustar00rootroot0000000000000052 comment=87812dbdd4822fc7f2c20833612aa063bb8c58fb gios-6.0.0/000077500000000000000000000000001476203530300124615ustar00rootroot00000000000000gios-6.0.0/.github/000077500000000000000000000000001476203530300140215ustar00rootroot00000000000000gios-6.0.0/.github/FUNDING.yml000066400000000000000000000001711476203530300156350ustar00rootroot00000000000000custom: ["https://www.paypal.me/bieniu79", "https://www.buymeacoffee.com/QnLdxeaqO", "https://revolut.me/maciejbieniek"] gios-6.0.0/.github/dependabot.yml000066400000000000000000000003151476203530300166500ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" gios-6.0.0/.github/release-drafter.yml000066400000000000000000000013441476203530300176130ustar00rootroot00000000000000change-template: "- #$NUMBER $TITLE @$AUTHOR" sort-direction: ascending categories: - title: ":boom: Breaking Changes" label: "breaking-change" - title: ":sparkles: New Features" label: "new-feature" - title: ":zap: Performance" label: "performance" - title: ":recycle: Refactor" label: "refactor" - title: ":green_heart: CI" label: "ci" - title: ":bug: Bug Fixes" label: "bugfix" - title: ":white_check_mark: Tests" label: "tests" - title: ":arrow_up: Dependency Updates" label: "dependencies" collapse-after: 1 include-labels: - "breaking-change" - "performance" - "refactor" - "new-feature" - "bugfix" - "dependencies" - "tests" - "ci" template: | $CHANGES gios-6.0.0/.github/workflows/000077500000000000000000000000001476203530300160565ustar00rootroot00000000000000gios-6.0.0/.github/workflows/codeql.yml000066400000000000000000000013321476203530300200470ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [master] pull_request: branches: [master] schedule: - cron: "21 5 * * 0" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: ["python"] steps: - name: Checkout repository uses: actions/checkout@v4 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} - name: Autobuild uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 gios-6.0.0/.github/workflows/pre-commit-update.yml000066400000000000000000000015501476203530300221360ustar00rootroot00000000000000name: Pre-commit auto-update on: schedule: # Run on fridays - cron: "0 0 * * 1" jobs: auto-update: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.x" - name: Install pre-commit run: pip install pre-commit - name: Run pre-commit autoupdate run: pre-commit autoupdate - name: Create Pull Request uses: peter-evans/create-pull-request@v7 with: token: ${{ secrets.GITHUB_TOKEN }} branch: update/pre-commit-autoupdate title: Auto-update pre-commit hooks commit-message: Auto-update pre-commit hooks body: | Update versions of tools in pre-commit configs to latest version labels: dependencies gios-6.0.0/.github/workflows/publish.yml000066400000000000000000000013001476203530300202410ustar00rootroot00000000000000name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: 3.13 - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel - name: Build run: | pip install build python -m build - name: Publish release to PyPI uses: pypa/gh-action-pypi-publish@v1.12.4 with: user: __token__ password: ${{ secrets.PYPI_TOKEN }} gios-6.0.0/.github/workflows/release-drafter.yml000066400000000000000000000016211476203530300216460ustar00rootroot00000000000000name: Release Drafter on: push: branches: - master jobs: update_release_draft: runs-on: ubuntu-latest name: Release Drafter steps: - name: Set up Python 3.13 uses: actions/setup-python@v5 with: python-version: 3.13 - name: Checkout the repository uses: actions/checkout@v4 - name: Find Version id: version run: | version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])") echo Version from pyproject.toml: $version echo "version=$version" >> $GITHUB_OUTPUT - name: Run Release Drafter uses: release-drafter/release-drafter@v6 with: tag: ${{ steps.version.outputs.version }} name: Version ${{ steps.version.outputs.version }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} gios-6.0.0/.github/workflows/stale.yml000066400000000000000000000010101476203530300177010ustar00rootroot00000000000000name: Mark stale issues and pull requests on: schedule: - cron: '25 8 * * *' jobs: stale: runs-on: ubuntu-latest permissions: issues: write pull-requests: write steps: - name: Stale uses: actions/stale@v9 with: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-issue-message: 'Stale issue message' stale-pr-message: 'Stale pull request message' stale-issue-label: 'no-issue-activity' stale-pr-label: 'no-pr-activity'gios-6.0.0/.github/workflows/test.yml000066400000000000000000000012601476203530300175570ustar00rootroot00000000000000name: Test on: push: branches: [master] pull_request: branches: [master] jobs: test: name: Test with tox runs-on: ubuntu-latest strategy: matrix: python-version: - "3.12" - "3.13" steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: pip - name: Install dependencies run: | pip install uv uv pip install --system tox tox-uv - name: Test with tox run: | tox gios-6.0.0/.gitignore000066400000000000000000000022631476203530300144540ustar00rootroot00000000000000# 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/ *.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/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # 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/ gios-6.0.0/.pre-commit-config.yaml000066400000000000000000000023731476203530300167470ustar00rootroot00000000000000repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.9.9 hooks: - id: ruff args: - --fix - id: ruff-format - repo: https://github.com/codespell-project/codespell rev: v2.4.1 hooks: - id: codespell args: - --ignore-words-list=hass,alot,datas,dof,dur,ether,farenheit,hist,iff,ines,ist,lightsensor,mut,nd,pres,referer,ser,serie,te,technik,ue,uint,visability,wan,wanna,withing,iam,incomfort,ba - --skip="./.*,*.csv,*.json" - --quiet-level=2 exclude_types: [csv, json] exclude: ^tests/fixtures/ - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 hooks: - id: end-of-file-fixer - id: mixed-line-ending - id: trailing-whitespace - id: check-yaml - id: check-json - id: check-toml - id: pretty-format-json args: - --no-sort-keys - id: no-commit-to-branch args: - --branch=master - repo: https://github.com/pre-commit/mirrors-prettier rev: v4.0.0-alpha.8 hooks: - id: prettier stages: [manual] - repo: https://github.com/pre-commit/mirrors-mypy rev: "v1.15.0" hooks: - id: mypy files: ^(gios)/.+\.py$ gios-6.0.0/.vscode/000077500000000000000000000000001476203530300140225ustar00rootroot00000000000000gios-6.0.0/.vscode/launch.json000066400000000000000000000007101476203530300161650ustar00rootroot00000000000000{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Fetch data", "type": "python", "request": "launch", "program": "example.py", "console": "integratedTerminal" } ] }gios-6.0.0/.vscode/settings.json000066400000000000000000000004671476203530300165640ustar00rootroot00000000000000{ "python.pythonPath": "venv/bin/python", "python.testing.pytestArgs": [ "tests" ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "files.associations": { "*.yaml": "home-assistant" }, "python.analysis.typeCheckingMode": "basic" } gios-6.0.0/LICENSE000066400000000000000000000261201476203530300134670ustar00rootroot00000000000000 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 2025 Maciej Bieniek 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. gios-6.0.0/MANIFEST.in000066400000000000000000000001211476203530300142110ustar00rootroot00000000000000include LICENSE README.md include requirements.txt include requirements-test.txt gios-6.0.0/README.md000066400000000000000000000050161476203530300137420ustar00rootroot00000000000000[![GitHub Release][releases-shield]][releases] [![PyPI][pypi-releases-shield]][pypi-releases] [![PyPI - Downloads][pypi-downloads]][pypi-statistics] [![Buy me a coffee][buy-me-a-coffee-shield]][buy-me-a-coffee] [![PayPal_Me][paypal-me-shield]][paypal-me] [![Revolut.Me][revolut-me-shield]][revolut-me] # gios Python wrapper for getting air quality data from [GIOŚ (Główny Inspektorat Ochrony Środowiska)](http://www.gios.gov.pl/pl/stan-srodowiska/monitoring-jakosci-powietrza) ## How to find station_id - go to http://powietrze.gios.gov.pl/pjp/current - find on the map a measurement station located closest to your home - go to "More infotmation" link - look at site address, for ex. for this address https://powietrze.gios.gov.pl/pjp/current/station_details/table/10124/3/0 `station_id` is 10124 ## How to use package ```python """Example for GIOS.""" import asyncio import logging from aiohttp import ClientError, ClientSession from gios import ApiError, Gios, InvalidSensorsData, NoStationError GIOS_STATION_ID = 568 logging.basicConfig(level=logging.DEBUG) async def main() -> None: """Run main function.""" async with ClientSession() as websession: gios = Gios(GIOS_STATION_ID, websession) try: data = await gios.async_update() except (ApiError, NoStationError, InvalidSensorsData, ClientError) as error: print(error) return latitude = gios.latitude longitude = gios.longitude station_name = gios.station_name print(f"Longitude: {longitude}") print(f"Latitude: {latitude}") print(f"Station name: {station_name}") print(data) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() ``` [releases]: https://github.com/bieniu/gios/releases [releases-shield]: https://img.shields.io/github/release/bieniu/gios.svg?style=popout [pypi-releases]: https://pypi.org/project/gios/ [pypi-statistics]: https://pepy.tech/project/gios [pypi-releases-shield]: https://img.shields.io/pypi/v/gios [pypi-downloads]: https://pepy.tech/badge/gios/month [buy-me-a-coffee-shield]: https://img.shields.io/static/v1.svg?label=%20&message=Buy%20me%20a%20coffee&color=6f4e37&logo=buy%20me%20a%20coffee&logoColor=white [buy-me-a-coffee]: https://www.buymeacoffee.com/QnLdxeaqO [paypal-me-shield]: https://img.shields.io/static/v1.svg?label=%20&message=PayPal.Me&logo=paypal [paypal-me]: https://www.paypal.me/bieniu79 [revolut-me]: https://revolut.me/maciejbieniek [revolut-me-shield]: https://img.shields.io/static/v1.svg?label=%20&message=Revolut&logo=revolut gios-6.0.0/example.py000066400000000000000000000016051476203530300144700ustar00rootroot00000000000000"""Example for GIOS.""" import asyncio import logging from aiohttp import ClientError, ClientSession from gios import ApiError, Gios, InvalidSensorsDataError, NoStationError GIOS_STATION_ID = 568 logging.basicConfig(level=logging.DEBUG) async def main() -> None: """Run main function.""" async with ClientSession() as websession: try: gios = await Gios.create(websession, GIOS_STATION_ID) data = await gios.async_update() except ( ApiError, NoStationError, InvalidSensorsDataError, ClientError, ) as error: print(error) return print(f"Measurement stations: {gios.measurement_stations}") print(f"Station: {gios.station_name} ({gios.latitude}, {gios.longitude})") print(data) loop = asyncio.new_event_loop() loop.run_until_complete(main()) loop.close() gios-6.0.0/gios/000077500000000000000000000000001476203530300134225ustar00rootroot00000000000000gios-6.0.0/gios/__init__.py000066400000000000000000000153231476203530300155370ustar00rootroot00000000000000"""Python wrapper for getting air quality data from GIOS.""" import asyncio import logging from collections.abc import Generator from contextlib import suppress from http import HTTPStatus from typing import Any, Final, Self, cast from aiohttp import ClientSession from dacite import from_dict from .const import ( ATTR_AQI, ATTR_ID, ATTR_INDEX, ATTR_INDEX_LEVEL, ATTR_NAME, ATTR_VALUE, POLLUTANT_MAP, STATE_MAP, URL_INDEXES, URL_SENSOR, URL_STATION, URL_STATIONS, ) from .exceptions import ApiError, InvalidSensorsDataError, NoStationError from .model import GiosSensors, GiosStation _LOGGER: Final = logging.getLogger(__name__) class Gios: """Main class to perform GIOS API requests.""" def __init__(self, station_id: int | None, session: ClientSession) -> None: """Initialize.""" self.station_id = station_id self.latitude: float | None = None self.longitude: float | None = None self.station_name: str | None = None self._station_data: list[dict[str, Any]] = [] self._measurement_stations: dict[int, GiosStation] = {} self.session = session @classmethod async def create( cls: type[Self], session: ClientSession, station_id: int | None = None, ) -> Self: """Create a new instance.""" instance = cls(station_id, session) await instance.initialize() return instance async def initialize(self) -> None: """Initialize.""" msg = "Initializing GIOS" if self.station_id: msg += f" for station ID: {self.station_id}" _LOGGER.debug(msg) stations = await self._get_stations() self._measurement_stations = { station.id: station for station in self._parse_stations(stations) } if self.station_id is None: return if (station := self.measurement_stations.get(self.station_id)) is None: msg = f"{self.station_id} is not a valid measuring station ID" raise NoStationError(msg) self.latitude = station.latitude self.longitude = station.longitude self.station_name = station.name @property def measurement_stations(self) -> dict[int, GiosStation]: """Return measurement stations dict.""" return self._measurement_stations async def async_update(self) -> GiosSensors: """Update GIOS data.""" if self.station_id is None: msg = "Measuring station ID is not set" raise NoStationError(msg) data: dict[str, dict[str, Any]] = {} invalid_sensors: list[str] = [] if not self._station_data: self._station_data = await self._get_station() if not self._station_data: msg = "Invalid measuring station data from GIOS API" raise InvalidSensorsDataError(msg) for sensor_dict in self._station_data: data[sensor_dict["param"]["paramCode"].lower()] = { ATTR_ID: sensor_dict[ATTR_ID], ATTR_NAME: POLLUTANT_MAP[sensor_dict["param"]["paramName"]], } sensors = await self._get_all_sensors(data) # The GIOS server sends null values for sensors several minutes before # adding new data from measuring station. If the newest value is null # we take the earlier value. for sensor, sensor_data in data.items(): try: if sensors[sensor]["values"][0][ATTR_VALUE]: sensor_data[ATTR_VALUE] = sensors[sensor]["values"][0][ATTR_VALUE] elif sensors[sensor].get("values")[1][ATTR_VALUE]: sensor_data[ATTR_VALUE] = sensors[sensor]["values"][1][ATTR_VALUE] else: invalid_sensors.append(sensor) except (IndexError, KeyError, TypeError): invalid_sensors.append(sensor) if invalid_sensors: for sensor in invalid_sensors: data.pop(sensor) if not data: msg = "Invalid sensor data from GIOS API" raise InvalidSensorsDataError(msg) indexes = await self._get_indexes() for sensor, sensor_data in data.items(): with suppress(IndexError, KeyError, TypeError): index_level = ATTR_INDEX_LEVEL.format(sensor.lower().replace(".", "")) sensor_data[ATTR_INDEX] = STATE_MAP[ indexes[index_level]["indexLevelName"] ] with suppress(IndexError, KeyError, TypeError): if indexes["stIndexLevel"]["indexLevelName"]: data[ATTR_AQI.lower()] = {ATTR_NAME: ATTR_AQI} data[ATTR_AQI.lower()][ATTR_VALUE] = STATE_MAP[ indexes["stIndexLevel"]["indexLevelName"] ] if data.get("pm2.5"): data["pm25"] = data.pop("pm2.5") result: GiosSensors = from_dict(data_class=GiosSensors, data=data) return result async def _get_stations(self) -> Any: """Retrieve list of measurement stations.""" return await self._async_get(URL_STATIONS) def _parse_stations(self, stations: list[dict[str, Any]]) -> Generator[GiosStation]: """Parse stations data.""" for station in stations: yield GiosStation( cast(int, station["id"]), station["stationName"], float(station["gegrLat"]), float(station["gegrLon"]), ) async def _get_station(self) -> Any: """Retrieve measuring station data.""" url = URL_STATION.format(self.station_id) return await self._async_get(url) async def _get_all_sensors(self, sensors: dict[str, Any]) -> dict[str, Any]: """Retrieve all sensors data.""" tasks = [self._get_sensor(sensors[sensor][ATTR_ID]) for sensor in sensors] results = await asyncio.gather(*tasks) return dict(zip(sensors, results, strict=True)) async def _get_sensor(self, sensor: int) -> Any: """Retrieve sensor data.""" url = URL_SENSOR.format(sensor) return await self._async_get(url) async def _get_indexes(self) -> Any: """Retrieve indexes data.""" url = URL_INDEXES.format(self.station_id) return await self._async_get(url) async def _async_get(self, url: str) -> Any: """Retrieve data from GIOS API.""" async with self.session.get(url) as resp: _LOGGER.debug("Data retrieved from %s, status: %s", url, resp.status) if resp.status != HTTPStatus.OK.value: _LOGGER.warning("Invalid response from GIOS API: %s", resp.status) raise ApiError(str(resp.status)) return await resp.json() gios-6.0.0/gios/const.py000066400000000000000000000020641476203530300151240ustar00rootroot00000000000000"""Constants for GIOS library.""" from typing import Final ATTR_AQI: Final[str] = "AQI" ATTR_ID: Final[str] = "id" ATTR_INDEX: Final[str] = "index" ATTR_INDEX_LEVEL: Final[str] = "{}IndexLevel" ATTR_NAME: Final[str] = "name" ATTR_VALUE: Final[str] = "value" URL_INDEXES: Final[str] = "https://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{}" URL_SENSOR: Final[str] = "https://api.gios.gov.pl/pjp-api/rest/data/getData/{}" URL_STATION: Final[str] = "https://api.gios.gov.pl/pjp-api/rest/station/sensors/{}" URL_STATIONS: Final[str] = "https://api.gios.gov.pl/pjp-api/rest/station/findAll" POLLUTANT_MAP = { "benzen": "benzene", "tlenek węgla": "carbon monoxide", "dwutlenek azotu": "nitrogen dioxide", "ozon": "ozone", "pył zawieszony PM10": "particulate matter 10", "pył zawieszony PM2.5": "particulate matter 2.5", "dwutlenek siarki": "sulfur dioxide", } STATE_MAP = { "Bardzo dobry": "very_good", "Bardzo zły": "very_bad", "Dobry": "good", "Dostateczny": "sufficient", "Umiarkowany": "moderate", "Zły": "bad", } gios-6.0.0/gios/exceptions.py000066400000000000000000000007451476203530300161630ustar00rootroot00000000000000"""GIOS exceptions.""" class GiosError(Exception): """Base class for GIOS errors.""" def __init__(self, status: str) -> None: """Initialize.""" super().__init__(status) self.status = status class ApiError(GiosError): """Raised when GIOS API request ended in error.""" class InvalidSensorsDataError(GiosError): """Raised when sensors data is invalid.""" class NoStationError(GiosError): """Raised when no measuring station error.""" gios-6.0.0/gios/model.py000066400000000000000000000011651476203530300150770ustar00rootroot00000000000000"""Type definitions for GIOS.""" from dataclasses import dataclass @dataclass class Sensor: """Data class for sensor.""" name: str id: int | None index: str | None = None value: float | str | None = None @dataclass class GiosSensors: """Data class for polutants.""" aqi: Sensor | None c6h6: Sensor | None co: Sensor | None no2: Sensor | None o3: Sensor | None pm10: Sensor | None pm25: Sensor | None so2: Sensor | None @dataclass class GiosStation: """Data class for measeurement station.""" id: int name: str latitude: float longitude: float gios-6.0.0/gios/py.typed000066400000000000000000000000001476203530300151070ustar00rootroot00000000000000gios-6.0.0/pyproject.toml000066400000000000000000000057751476203530300154130ustar00rootroot00000000000000[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "gios" version = "6.0.0" license = {text = "Apache-2.0"} description = "Python wrapper for getting air quality data from GIOŚ servers." readme = "README.md" authors = [{name = "Maciej Bieniek"}] classifiers = [ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3 :: Only", "Typing :: Typed", ] requires-python = ">=3.12" dependencies = ["aiohttp>=3.9.4"] [project.urls] Homepage = "https://github.com/bieniu/gios" [tool.setuptools.packages.find] include = ["gios*"] [tool.pytest.ini_options] asyncio_default_fixture_loop_scope = "function" [tool.mypy] python_version = "3.13" show_error_codes = true follow_imports = "silent" ignore_missing_imports = true warn_incomplete_stub = true warn_redundant_casts = true warn_unused_configs = true check_untyped_defs = true disallow_incomplete_defs = true disallow_subclassing_any = true disallow_untyped_calls = true disallow_untyped_decorators = true disallow_untyped_defs = true no_implicit_optional = true strict_equality = true warn_return_any = true warn_unused_ignores = true warn_unreachable = true [tool.ruff] target-version = "py313" lint.select = ["ALL"] lint.ignore = [ "ANN401", # Dynamically typed expressions (typing.Any) are disallowed "COM812", # Trailing comma missing "D203", # 1 blank line required before class docstring "D213", # Multi-line docstring summary should start at the second line "ISC001", # Single line implicit string concatenation "PLR0912", # Too many branches ] [tool.ruff.lint.per-file-ignores] "tests/*" = [ "PLR0913", # Too many arguments in function definition "PLR2004", # Magic value used in comparison "S101", # Use of `assert` detected ] "example.py" = [ "T201", # `print` found ] [tool.ruff.lint.mccabe] max-complexity = 25 [tool.coverage.run] source = ["gios"] [tool.tox] legacy_tox_ini = """ [tox] envlist = py312, py313, lint, typing, coverage skip_missing_interpreters = True [gh-actions] python = 3.12: py312, lint, typing, coverage 3.13: py313 [testenv] commands = pytest --timeout=30 --cov=gios --cov-report=xml {posargs} --error-for-skips deps = -rrequirements.txt -rrequirements-test.txt [testenv:lint] basepython = python3 depends = py312 ignore_errors = True skip_install = True usedevelop = False commands = ruff check . ruff format --check . [testenv:typing] basepython = python3 depends = py312 ignore_errors = True skip_install = True usedevelop = False commands = mypy gios [testenv:coverage] basepython = python3 depends = py312 skip_install = True usedevelop = False commands = coverage report --fail-under=79 """ gios-6.0.0/requirements-dev.txt000066400000000000000000000001051476203530300165150ustar00rootroot00000000000000-r requirements.txt -r requirements-test.txt pre-commit==4.1.0 -e . gios-6.0.0/requirements-test.txt000066400000000000000000000002671476203530300167270ustar00rootroot00000000000000aioresponses==0.7.8 coverage==7.6.12 mypy==1.15.0 pytest-asyncio==0.25.3 pytest-cov==6.0.0 pytest-error-for-skips==2.0.2 pytest-timeout==2.3.1 pytest==8.3.5 ruff==0.9.9 syrupy==4.8.2 gios-6.0.0/requirements.txt000066400000000000000000000000351476203530300157430ustar00rootroot00000000000000aiohttp>=3.9.4 dacite>=1.7.0 gios-6.0.0/scripts/000077500000000000000000000000001476203530300141505ustar00rootroot00000000000000gios-6.0.0/scripts/setup-local-env.sh000077500000000000000000000003621476203530300175260ustar00rootroot00000000000000#!/bin/bash PYTHON_VERSION=3.13 python$PYTHON_VERSION -m pip install uv python$PYTHON_VERSION -m uv venv venv --seed --python=$PYTHON_VERSION source venv/bin/activate pip install uv uv pip install -r requirements-dev.txt pre-commit install gios-6.0.0/tests/000077500000000000000000000000001476203530300136235ustar00rootroot00000000000000gios-6.0.0/tests/__init__.py000066400000000000000000000000361476203530300157330ustar00rootroot00000000000000"""Tests for gios package.""" gios-6.0.0/tests/conftest.py000066400000000000000000000066471476203530300160370ustar00rootroot00000000000000"""Set up some common test helper things.""" import json from collections.abc import AsyncGenerator, Generator from pathlib import Path from typing import Any import aiohttp import pytest import pytest_asyncio from aioresponses import aioresponses from syrupy.assertion import SnapshotAssertion from syrupy.extensions.amber import AmberSnapshotExtension from syrupy.location import PyTestLocation BASE = "tests/fixtures/" @pytest_asyncio.fixture async def session() -> AsyncGenerator[aiohttp.ClientSession]: """Return a mock ClientSession.""" session = aiohttp.ClientSession() yield session await session.close() @pytest.fixture def session_mock() -> Generator[aioresponses]: """Create a reusable aioresponses mock.""" with aioresponses() as mock: yield mock @pytest.fixture def stations() -> list[dict[str, Any]]: """Return stations data from the fixture file.""" with Path.open(Path(f"{BASE}stations.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def station() -> list[dict[str, Any]]: """Return the station data from the fixture file.""" with Path.open(Path(f"{BASE}station.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def indexes() -> dict[str, Any]: """Return indexes data from the fixture file.""" with Path.open(Path(f"{BASE}indexes.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_658() -> dict[str, Any]: """Return sensor 658 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_658.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_660() -> dict[str, Any]: """Return sensor 660 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_660.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_665() -> dict[str, Any]: """Return sensor 665 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_665.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_667() -> dict[str, Any]: """Return sensor 667 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_667.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_670() -> dict[str, Any]: """Return sensor 670 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_670.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_672() -> dict[str, Any]: """Return sensor 672 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_672.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def sensor_14395() -> dict[str, Any]: """Return sensor 14395 data from the fixture file.""" with Path.open(Path(f"{BASE}sensor_14395.json"), encoding="utf-8") as file: return json.load(file) @pytest.fixture def snapshot(snapshot: SnapshotAssertion) -> SnapshotAssertion: """Return snapshot assertion fixture.""" return snapshot.use_extension(SnapshotExtension) class SnapshotExtension(AmberSnapshotExtension): """Extension for Syrupy.""" @classmethod def dirname(cls, *, test_location: PyTestLocation) -> str: """Return the directory for the snapshot files.""" test_dir = Path(test_location.filepath).parent return str(test_dir.joinpath("snapshots")) gios-6.0.0/tests/fixtures/000077500000000000000000000000001476203530300154745ustar00rootroot00000000000000gios-6.0.0/tests/fixtures/indexes.json000066400000000000000000000024101476203530300200230ustar00rootroot00000000000000{ "id": 117, "stCalcDate": "2020-07-31 15:10:17", "stIndexLevel": { "id": 1, "indexLevelName": "Dobry" }, "stSourceDataDate": "2020-07-31 14:00:00", "so2CalcDate": "2020-07-31 15:10:17", "so2IndexLevel": { "id": 0, "indexLevelName": "Bardzo dobry" }, "so2SourceDataDate": "2020-07-31 14:00:00", "no2CalcDate": 1596201017000, "no2IndexLevel": { "id": 0, "indexLevelName": "Bardzo dobry" }, "no2SourceDataDate": "2020-07-31 14:00:00", "coCalcDate": "2020-07-31 15:10:17", "coIndexLevel": { "id": 0, "indexLevelName": "Bardzo zły" }, "coSourceDataDate": "2020-07-31 14:00:00", "pm10CalcDate": "2020-07-31 15:10:17", "pm10IndexLevel": { "id": 0, "indexLevelName": "Umiarkowany" }, "pm10SourceDataDate": "2020-07-31 14:00:00", "pm25CalcDate": "2020-07-31 15:10:17", "pm25IndexLevel": { "id": 0, "indexLevelName": "Dostateczny" }, "pm25SourceDataDate": "2020-07-31 14:00:00", "o3CalcDate": "2020-07-31 15:10:17", "o3IndexLevel": { "id": 1, "indexLevelName": "Zły" }, "o3SourceDataDate": "2020-07-31 14:00:00", "c6h6CalcDate": "2020-07-31 15:10:17", "c6h6IndexLevel": { "id": 0, "indexLevelName": "Bardzo dobry" }, "c6h6SourceDataDate": "2020-07-31 14:00:00", "stIndexStatus": true, "stIndexCrParam": "OZON" } gios-6.0.0/tests/fixtures/sensor_14395.json000066400000000000000000000005021476203530300204420ustar00rootroot00000000000000{ "key": "PM10", "values": [ { "date": "2021-02-24 11:00:00", "value": 123.879 }, { "date": "2021-02-24 10:00:00", "value": 115.559 }, { "date": "2021-02-24 09:00:00", "value": 112.611 } ] }gios-6.0.0/tests/fixtures/sensor_658.json000066400000000000000000000005011476203530300202760ustar00rootroot00000000000000{ "key": "C6H6", "values": [ { "date": "2021-02-24 11:00:00", "value": 2.57148 }, { "date": "2021-02-24 10:00:00", "value": 3.24432 }, { "date": "2021-02-24 09:00:00", "value": 4.2696 } ] }gios-6.0.0/tests/fixtures/sensor_660.json000066400000000000000000000005001476203530300202660ustar00rootroot00000000000000{ "key": "CO", "values": [ { "date": "2021-02-24 11:00:00", "value": 786.702 }, { "date": "2021-02-24 10:00:00", "value": 1041.74 }, { "date": "2021-02-24 09:00:00", "value": 1358.99 } ] }gios-6.0.0/tests/fixtures/sensor_665.json000066400000000000000000000005011476203530300202740ustar00rootroot00000000000000{ "key": "NO2", "values": [ { "date": "2021-02-24 11:00:00", "value": 59.9545 }, { "date": "2021-02-24 10:00:00", "value": 52.6198 }, { "date": "2021-02-24 09:00:00", "value": 41.7289 } ] }gios-6.0.0/tests/fixtures/sensor_667.json000066400000000000000000000005001476203530300202750ustar00rootroot00000000000000{ "key": "O3", "values": [ { "date": "2021-02-24 11:00:00", "value": 8.63111 }, { "date": "2021-02-24 10:00:00", "value": 4.93778 }, { "date": "2021-02-24 09:00:00", "value": 3.19889 } ] }gios-6.0.0/tests/fixtures/sensor_670.json000066400000000000000000000005031476203530300202720ustar00rootroot00000000000000{ "key": "PM2.5", "values": [ { "date": "2021-02-24 11:00:00", "value": 59.9428 }, { "date": "2021-02-24 10:00:00", "value": 72.0243 }, { "date": "2021-02-24 09:00:00", "value": 84.4169 } ] }gios-6.0.0/tests/fixtures/sensor_672.json000066400000000000000000000004771476203530300203060ustar00rootroot00000000000000{ "key": "SO2", "values": [ { "date": "2021-02-24 11:00:00", "value": 11.6502 }, { "date": "2021-02-24 10:00:00", "value": 11.501 }, { "date": "2021-02-24 09:00:00", "value": 9.5032 } ] }gios-6.0.0/tests/fixtures/station.json000066400000000000000000000024561476203530300200570ustar00rootroot00000000000000[ { "id": 672, "stationId": 117, "param": { "paramName": "dwutlenek siarki", "paramFormula": "SO2", "paramCode": "SO2", "idParam": 1 } }, { "id": 658, "stationId": 117, "param": { "paramName": "benzen", "paramFormula": "C6H6", "paramCode": "C6H6", "idParam": 10 } }, { "id": 660, "stationId": 117, "param": { "paramName": "tlenek węgla", "paramFormula": "CO", "paramCode": "CO", "idParam": 8 } }, { "id": 665, "stationId": 117, "param": { "paramName": "dwutlenek azotu", "paramFormula": "NO2", "paramCode": "NO2", "idParam": 6 } }, { "id": 667, "stationId": 117, "param": { "paramName": "ozon", "paramFormula": "O3", "paramCode": "O3", "idParam": 5 } }, { "id": 670, "stationId": 117, "param": { "paramName": "pył zawieszony PM2.5", "paramFormula": "PM2.5", "paramCode": "PM2.5", "idParam": 69 } }, { "id": 14395, "stationId": 117, "param": { "paramName": "pył zawieszony PM10", "paramFormula": "PM10", "paramCode": "PM10", "idParam": 3 } } ] gios-6.0.0/tests/fixtures/stations.json000066400000000000000000000004561476203530300202400ustar00rootroot00000000000000[{ "id": 552, "stationName": "Test Name", "gegrLat": "99.99", "gegrLon": "88.88", "city": { "id": 1006, "name": "Test City", "commune": { "communeName": "Test Comune", "districtName": "Test District", "provinceName": "Test Province" } }, "addressStreet": "Foo" }]gios-6.0.0/tests/snapshots/000077500000000000000000000000001476203530300156455ustar00rootroot00000000000000gios-6.0.0/tests/snapshots/test_init.ambr000066400000000000000000000045611476203530300205200ustar00rootroot00000000000000# serializer version: 1 # name: test_init_only dict({ 552: GiosStation(id=552, name='Test Name', latitude=99.99, longitude=88.88), }) # --- # name: test_no_indexes_data dict({ 552: GiosStation(id=552, name='Test Name', latitude=99.99, longitude=88.88), }) # --- # name: test_no_indexes_data.1 GiosSensors(aqi=None, c6h6=Sensor(name='benzene', id=658, index=None, value=2.57148), co=Sensor(name='carbon monoxide', id=660, index=None, value=786.702), no2=Sensor(name='nitrogen dioxide', id=665, index=None, value=59.9545), o3=Sensor(name='ozone', id=667, index=None, value=8.63111), pm10=Sensor(name='particulate matter 10', id=14395, index=None, value=123.879), pm25=Sensor(name='particulate matter 2.5', id=670, index=None, value=59.9428), so2=Sensor(name='sulfur dioxide', id=672, index=None, value=11.6502)) # --- # name: test_valid_data_first_value dict({ 552: GiosStation(id=552, name='Test Name', latitude=99.99, longitude=88.88), }) # --- # name: test_valid_data_first_value.1 GiosSensors(aqi=Sensor(name='AQI', id=None, index=None, value='good'), c6h6=Sensor(name='benzene', id=658, index='very_good', value=2.57148), co=Sensor(name='carbon monoxide', id=660, index='very_bad', value=786.702), no2=Sensor(name='nitrogen dioxide', id=665, index='very_good', value=59.9545), o3=Sensor(name='ozone', id=667, index='bad', value=8.63111), pm10=Sensor(name='particulate matter 10', id=14395, index='moderate', value=123.879), pm25=Sensor(name='particulate matter 2.5', id=670, index='sufficient', value=59.9428), so2=Sensor(name='sulfur dioxide', id=672, index='very_good', value=11.6502)) # --- # name: test_valid_data_second_value dict({ 552: GiosStation(id=552, name='Test Name', latitude=99.99, longitude=88.88), }) # --- # name: test_valid_data_second_value.1 GiosSensors(aqi=Sensor(name='AQI', id=None, index=None, value='good'), c6h6=Sensor(name='benzene', id=658, index='very_good', value=3.24432), co=Sensor(name='carbon monoxide', id=660, index='very_bad', value=1041.74), no2=Sensor(name='nitrogen dioxide', id=665, index='very_good', value=52.6198), o3=Sensor(name='ozone', id=667, index='bad', value=4.93778), pm10=Sensor(name='particulate matter 10', id=14395, index='moderate', value=115.559), pm25=Sensor(name='particulate matter 2.5', id=670, index='sufficient', value=72.0243), so2=Sensor(name='sulfur dioxide', id=672, index='very_good', value=11.501)) # --- gios-6.0.0/tests/test_init.py000066400000000000000000000330171476203530300162030ustar00rootroot00000000000000"""Tests for gios package.""" from typing import Any import aiohttp import pytest from aioresponses import aioresponses from syrupy import SnapshotAssertion from gios import ApiError, Gios, InvalidSensorsDataError, NoStationError INVALID_STATION_ID = 0 VALID_STATION_ID = 552 VALID_STATION_NAME = "Test Name" VALID_LATITUDE = 99.99 VALID_LONGITUDE = 88.88 @pytest.mark.asyncio async def test_init_only( session: aiohttp.ClientSession, session_mock: aioresponses, snapshot: SnapshotAssertion, stations: list[dict[str, Any]], ) -> None: """Test init without station.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) gios = await Gios.create(session) with pytest.raises(NoStationError, match="Measuring station ID is not set"): await gios.async_update() assert gios.station_name is None assert gios.station_id is None assert gios.latitude is None assert gios.longitude is None assert gios.measurement_stations == snapshot @pytest.mark.asyncio async def test_valid_data_first_value( session: aiohttp.ClientSession, session_mock: aioresponses, snapshot: SnapshotAssertion, stations: list[dict[str, Any]], station: list[dict[str, Any]], indexes: dict[str, Any], sensor_658: dict[str, Any], sensor_660: dict[str, Any], sensor_665: dict[str, Any], sensor_667: dict[str, Any], sensor_670: dict[str, Any], sensor_672: dict[str, Any], sensor_14395: dict[str, Any], ) -> None: """Test with valid data and valid first sensor's value.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload=indexes, ) gios = await Gios.create(session, VALID_STATION_ID) data = await gios.async_update() assert gios.station_name == VALID_STATION_NAME assert gios.station_id == VALID_STATION_ID assert gios.latitude == VALID_LATITUDE assert gios.longitude == VALID_LONGITUDE assert gios.measurement_stations == snapshot assert data == snapshot @pytest.mark.asyncio async def test_api_error( session: aiohttp.ClientSession, session_mock: aioresponses ) -> None: """Test GIOS API error.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", status=404, ) with pytest.raises(ApiError) as excinfo: await Gios.create(session, VALID_STATION_ID) assert str(excinfo.value) == "404" @pytest.mark.asyncio async def test_valid_data_second_value( session: aiohttp.ClientSession, session_mock: aioresponses, snapshot: SnapshotAssertion, stations: list[dict[str, Any]], station: list[dict[str, Any]], indexes: dict[str, Any], sensor_658: dict[str, Any], sensor_660: dict[str, Any], sensor_665: dict[str, Any], sensor_667: dict[str, Any], sensor_670: dict[str, Any], sensor_672: dict[str, Any], sensor_14395: dict[str, Any], ) -> None: """Test with valid data and valid second sensor's value.""" sensor_658["values"][0]["value"] = None sensor_660["values"][0]["value"] = None sensor_665["values"][0]["value"] = None sensor_667["values"][0]["value"] = None sensor_670["values"][0]["value"] = None sensor_672["values"][0]["value"] = None sensor_14395["values"][0]["value"] = None session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload=indexes, ) gios = await Gios.create(session, VALID_STATION_ID) data = await gios.async_update() assert gios.station_name == VALID_STATION_NAME assert gios.station_id == VALID_STATION_ID assert gios.latitude == VALID_LATITUDE assert gios.longitude == VALID_LONGITUDE assert gios.measurement_stations == snapshot assert data == snapshot @pytest.mark.asyncio async def test_no_indexes_data( session: aiohttp.ClientSession, session_mock: aioresponses, snapshot: SnapshotAssertion, stations: list[dict[str, Any]], station: list[dict[str, Any]], sensor_658: dict[str, Any], sensor_660: dict[str, Any], sensor_665: dict[str, Any], sensor_667: dict[str, Any], sensor_670: dict[str, Any], sensor_672: dict[str, Any], sensor_14395: dict[str, Any], ) -> None: """Test with valid data.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload={}, ) gios = await Gios.create(session, VALID_STATION_ID) data = await gios.async_update() assert gios.station_name == VALID_STATION_NAME assert gios.station_id == VALID_STATION_ID assert gios.latitude == VALID_LATITUDE assert gios.longitude == VALID_LONGITUDE assert gios.measurement_stations == snapshot assert data == snapshot @pytest.mark.asyncio async def test_no_sensor_data_1( session: aiohttp.ClientSession, session_mock: aioresponses, stations: list[dict[str, Any]], station: list[dict[str, Any]], indexes: dict[str, Any], sensor_658: dict[str, Any], sensor_660: dict[str, Any], sensor_665: dict[str, Any], sensor_667: dict[str, Any], sensor_670: dict[str, Any], sensor_672: dict[str, Any], sensor_14395: dict[str, Any], ) -> None: """Test with no sensor data.""" sensor_658["values"][0]["value"] = None sensor_658["values"][1]["value"] = None sensor_660["values"][0]["value"] = None sensor_660["values"][1]["value"] = None sensor_665["values"][0]["value"] = None sensor_665["values"][1]["value"] = None sensor_667["values"][0]["value"] = None sensor_667["values"][1]["value"] = None sensor_670["values"][0]["value"] = None sensor_670["values"][1]["value"] = None sensor_672["values"][0]["value"] = None sensor_672["values"][1]["value"] = None sensor_14395["values"][0]["value"] = None sensor_14395["values"][1]["value"] = None session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload=indexes, ) gios = await Gios.create(session, VALID_STATION_ID) with pytest.raises( InvalidSensorsDataError, match="Invalid sensor data from GIOS API" ): await gios.async_update() @pytest.mark.asyncio async def test_invalid_sensor_data_2( session: aiohttp.ClientSession, session_mock: aioresponses, stations: list[dict[str, Any]], station: list[dict[str, Any]], ) -> None: """Test with invalid sensor data.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=None, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=None, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=None, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=None, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=None, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=None, ) session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=None, ) gios = await Gios.create(session, VALID_STATION_ID) with pytest.raises( InvalidSensorsDataError, match="Invalid sensor data from GIOS API" ): await gios.async_update() @pytest.mark.asyncio async def test_no_station_data( session: aiohttp.ClientSession, session_mock: aioresponses, stations: list[dict[str, Any]], ) -> None: """Test with no station data.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"https://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload={}, ) gios = await Gios.create(session, VALID_STATION_ID) with pytest.raises( InvalidSensorsDataError, match="Invalid measuring station data from GIOS API", ): await gios.async_update() @pytest.mark.asyncio async def test_no_stations_data( session: aiohttp.ClientSession, session_mock: aioresponses ) -> None: """Test with no stations data.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload={}, ) with pytest.raises(NoStationError, match="552 is not a valid measuring station ID"): await Gios.create(session, VALID_STATION_ID) @pytest.mark.asyncio async def test_invalid_station_id( session: aiohttp.ClientSession, session_mock: aioresponses, stations: list[dict[str, Any]], ) -> None: """Test with invalid station_id.""" session_mock.get( "https://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) with pytest.raises(NoStationError, match="0 is not a valid measuring station ID"): await Gios.create(session, INVALID_STATION_ID)