pax_global_header00006660000000000000000000000064145310667500014521gustar00rootroot0000000000000052 comment=4ab1f9ebb5345162addf32779047ccc8464b13bd bieniu-gios-4ab1f9e/000077500000000000000000000000001453106675000144305ustar00rootroot00000000000000bieniu-gios-4ab1f9e/.github/000077500000000000000000000000001453106675000157705ustar00rootroot00000000000000bieniu-gios-4ab1f9e/.github/FUNDING.yml000066400000000000000000000001261453106675000176040ustar00rootroot00000000000000custom: ['https://www.paypal.me/bieniu79', 'https://www.buymeacoffee.com/QnLdxeaqO'] bieniu-gios-4ab1f9e/.github/dependabot.yml000066400000000000000000000003151453106675000206170ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" bieniu-gios-4ab1f9e/.github/release-drafter.yml000066400000000000000000000013411453106675000215570ustar00rootroot00000000000000change-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: Test" label: "test" - title: ":arrow_up: Dependency Updates" label: "dependencies" collapse-after: 1 include-labels: - "breaking-change" - "performance" - "refactor" - "new-feature" - "bugfix" - "dependencies" - "test" - "ci" template: | $CHANGES bieniu-gios-4ab1f9e/.github/workflows/000077500000000000000000000000001453106675000200255ustar00rootroot00000000000000bieniu-gios-4ab1f9e/.github/workflows/codeql.yml000066400000000000000000000013361453106675000220220ustar00rootroot00000000000000name: "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.1.1 - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} - name: Autobuild uses: github/codeql-action/autobuild@v2 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 bieniu-gios-4ab1f9e/.github/workflows/pre-commit-update.yml000066400000000000000000000015651453106675000241130ustar00rootroot00000000000000name: Pre-commit auto-update on: schedule: # Run on fridays - cron: "0 0 * * 5" jobs: auto-update: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4.1.1 - name: Set up Python uses: actions/setup-python@v4.5.0 with: python-version: "3.10" - 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@v5.0.2 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 bieniu-gios-4ab1f9e/.github/workflows/publish.yml000066400000000000000000000012411453106675000222140ustar00rootroot00000000000000name: Upload Python Package on: release: types: [published] jobs: deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4.1.1 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.x' - name: Install dependencies run: | python -m pip install --upgrade pip pip install setuptools wheel twine - name: Build and publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | python setup.py sdist bdist_wheel twine upload dist/* bieniu-gios-4ab1f9e/.github/workflows/release-drafter.yml000066400000000000000000000014321453106675000236150ustar00rootroot00000000000000name: Release Drafter on: push: branches: - master jobs: update_release_draft: runs-on: ubuntu-latest name: Release Drafter steps: - name: Checkout the repository uses: actions/checkout@v4.1.1 with: fetch-depth: 0 - name: Find Version id: version run: | declare -i newpost version=$(python setup.py --version) echo Version from setup.py: $version echo "::set-output name=version::$version" - name: Run Release Drafter uses: release-drafter/release-drafter@v5.25.0 with: tag: ${{ steps.version.outputs.version }} name: Version ${{ steps.version.outputs.version }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} bieniu-gios-4ab1f9e/.github/workflows/stale.yml000066400000000000000000000010101453106675000216500ustar00rootroot00000000000000name: 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@v8 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'bieniu-gios-4ab1f9e/.github/workflows/test.yml000066400000000000000000000013071453106675000215300ustar00rootroot00000000000000name: Test on: push: branches: [master] pull_request: branches: [master] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-version: - "3.10" - "3.11" - "3.12" steps: - name: Check out repository uses: actions/checkout@v4.1.1 with: fetch-depth: 2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip pip install tox tox-gh-actions - name: Test with tox run: tox bieniu-gios-4ab1f9e/.gitignore000066400000000000000000000022631453106675000164230ustar00rootroot00000000000000# 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/ bieniu-gios-4ab1f9e/.pre-commit-config.yaml000066400000000000000000000022161453106675000207120ustar00rootroot00000000000000repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.1.6 hooks: - id: ruff args: - --fix - id: ruff-format - repo: https://github.com/codespell-project/codespell rev: v2.2.6 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: v4.5.0 hooks: - id: end-of-file-fixer - id: no-commit-to-branch args: - --branch=master - repo: https://github.com/adrienverge/yamllint.git rev: v1.33.0 hooks: - id: yamllint - repo: https://github.com/pre-commit/mirrors-prettier rev: v3.1.0 hooks: - id: prettier stages: [manual] - repo: https://github.com/pre-commit/mirrors-mypy rev: "v1.7.1" hooks: - id: mypy files: ^(gios)/.+\.py$ bieniu-gios-4ab1f9e/.vscode/000077500000000000000000000000001453106675000157715ustar00rootroot00000000000000bieniu-gios-4ab1f9e/.vscode/launch.json000066400000000000000000000007101453106675000201340ustar00rootroot00000000000000{ // 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" } ] }bieniu-gios-4ab1f9e/.vscode/settings.json000066400000000000000000000004051453106675000205230ustar00rootroot00000000000000{ "python.pythonPath": "venv/bin/python", "python.testing.pytestArgs": [ "tests" ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "files.associations": { "*.yaml": "home-assistant" } }bieniu-gios-4ab1f9e/.yamllint000066400000000000000000000021741453106675000162660ustar00rootroot00000000000000rules: braces: level: error min-spaces-inside: 0 max-spaces-inside: 1 min-spaces-inside-empty: -1 max-spaces-inside-empty: -1 brackets: level: error min-spaces-inside: 0 max-spaces-inside: 0 min-spaces-inside-empty: -1 max-spaces-inside-empty: -1 colons: level: error max-spaces-before: 0 max-spaces-after: 1 commas: level: error max-spaces-before: 0 min-spaces-after: 1 max-spaces-after: 1 comments: level: error require-starting-space: true min-spaces-from-content: 2 comments-indentation: level: error document-end: level: error present: false document-start: level: error present: false empty-lines: level: error max: 1 max-start: 0 max-end: 1 hyphens: level: error max-spaces-after: 1 indentation: level: error spaces: 2 indent-sequences: true check-multi-line-strings: false key-duplicates: level: error line-length: disable new-line-at-end-of-file: level: error new-lines: level: error type: unix trailing-spaces: level: error truthy: disable bieniu-gios-4ab1f9e/LICENSE000066400000000000000000000261201453106675000154360ustar00rootroot00000000000000 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 2023 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. bieniu-gios-4ab1f9e/MANIFEST.in000066400000000000000000000001211453106675000161600ustar00rootroot00000000000000include LICENSE README.md include requirements.txt include requirements-test.txt bieniu-gios-4ab1f9e/README.md000066400000000000000000000045171453106675000157160ustar00rootroot00000000000000[![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] # 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 bieniu-gios-4ab1f9e/example.py000066400000000000000000000015631453106675000164420ustar00rootroot00000000000000"""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() bieniu-gios-4ab1f9e/gios/000077500000000000000000000000001453106675000153715ustar00rootroot00000000000000bieniu-gios-4ab1f9e/gios/__init__.py000066400000000000000000000130431453106675000175030ustar00rootroot00000000000000"""Python wrapper for getting air quality data from GIOS.""" import logging from contextlib import suppress from http import HTTPStatus from typing import Any, Final 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 _LOGGER: Final = logging.getLogger(__name__) class Gios: """Main class to perform GIOS API requests.""" def __init__(self, station_id: int, 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.session = session _LOGGER.info("Initializing GIOS for station ID: %s", self.station_id) async def async_update(self) -> GiosSensors: """Update GIOS data.""" data: dict[str, dict[str, Any]] = {} invalid_sensors: list[str] = [] if not self.station_name: if not (stations := await self._get_stations()): raise ApiError("Invalid measuring stations list from GIOS API") for station in stations: if station[ATTR_ID] == self.station_id: self.latitude = float(station["gegrLat"]) self.longitude = float(station["gegrLon"]) self.station_name = station["stationName"] if not self.station_name: raise NoStationError( f"{self.station_id} is not a valid measuring station ID" ) self._station_data = await self._get_station() if not self._station_data: raise InvalidSensorsDataError( "Invalid measuring station data from GIOS API" ) 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 a 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: raise InvalidSensorsDataError("Invalid sensor data from GIOS API") 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 measuring stations.""" return await self._async_get(URL_STATIONS) 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.""" data: dict[str, Any] = {} for sensor in sensors: sensor_data = await self._get_sensor(sensors[sensor][ATTR_ID]) data[sensor] = sensor_data return data 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() bieniu-gios-4ab1f9e/gios/const.py000066400000000000000000000020571453106675000170750ustar00rootroot00000000000000"""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] = "http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{}" URL_SENSOR: Final[str] = "http://api.gios.gov.pl/pjp-api/rest/data/getData/{}" URL_STATION: Final[str] = "http://api.gios.gov.pl/pjp-api/rest/station/sensors/{}" URL_STATIONS: Final[str] = "http://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", } bieniu-gios-4ab1f9e/gios/exceptions.py000066400000000000000000000007451453106675000201320ustar00rootroot00000000000000"""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.""" bieniu-gios-4ab1f9e/gios/model.py000066400000000000000000000007571453106675000170540ustar00rootroot00000000000000"""Type definitions for GIOS.""" from dataclasses import dataclass @dataclass class Sensor: """Data class for sensor.""" name: str id: int | None # noqa: A003 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 bieniu-gios-4ab1f9e/gios/py.typed000066400000000000000000000000001453106675000170560ustar00rootroot00000000000000bieniu-gios-4ab1f9e/pyproject.toml000066400000000000000000000056161453106675000173540ustar00rootroot00000000000000[tool.pytest.ini_options] asyncio_mode = "strict" [tool.mypy] python_version = "3.10" 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 = "py310" select = [ "A", # flake8-builtins "ARG", # flake8-unused-arguments "B", # flake8-bugbear "BLE", # flake8-blind-except "C", # complexity "C4", # flake8-comprehensions "C90", # mccabe "D", # docstrings "DJ", # flake8-django "DTZ", # flake8-datetimez "E", # pycodestyle "ERA", # eradicate "EXE", # flake8-executable "F", # pyflakes/autoflake "FBT", # flake8-boolean-trap "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions "INP", # flake8-no-pep420 "ISC", # flake8-implicit-str-concat "N", # pep8-naming "NPY", # NumPy-specific rules "PD", # pandas-vet "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # Pylint "PT", # flake8-pytest-style "PYI", # flake8-pyi "Q", # flake8-quotes "RET", # flake8-return "RSE", # flake8-raise "RUF", # Ruff-specific rules "S", # flake8-bandit "SIM", # flake8-simplify "SLF", # flake8-self "T10", # flake8-debugger "T20", # flake8-print "TID", # flake8-tidy-imports "TRY", # tryceratops "UP", # pyupgrade "W", # pycodestyle "YTT", # flake8-2020 ] ignore = [ "D203", # 1 blank line required before class docstring "D213", # Multi-line docstring summary should start at the second line "D404", # First word of the docstring should not be This "D406", # Section name should end with a newline "D407", # Section name underlining "D411", # Missing blank line before section "E731", # Do not assign a lambda expression, use a def "ISC001", # Single line implicit string concatenation "PLR0912", # Too many branches "PLR0915", # Too many statements "PT023", # Use `@pytest.mark.asyncio()` over `@pytest.mark.asyncio` "TRY003", # Avoid specifying long messages outside the exception class ] [tool.ruff.per-file-ignores] "tests/*" = [ "PLR2004", # Magic value used in comparison "S101", # Use of `assert` detected ] "example.py" = [ "T201", # `print` found ] [tool.ruff.mccabe] max-complexity = 25 [tool.coverage.run] source = ["gios"] bieniu-gios-4ab1f9e/requirements-dev.txt000066400000000000000000000001051453106675000204640ustar00rootroot00000000000000-r requirements.txt -r requirements-test.txt pre-commit==3.5.0 -e . bieniu-gios-4ab1f9e/requirements-test.txt000066400000000000000000000002471453106675000206740ustar00rootroot00000000000000aioresponses==0.7.6 coverage==7.3.2 mypy==1.7.1 pytest-asyncio==0.21.1 pytest-cov==4.1.0 pytest-error-for-skips==2.0.2 pytest-timeout==2.2.0 pytest==7.4.3 ruff==0.1.6 bieniu-gios-4ab1f9e/requirements.txt000066400000000000000000000000351453106675000177120ustar00rootroot00000000000000aiohttp>=3.7.0 dacite>=1.7.0 bieniu-gios-4ab1f9e/scripts/000077500000000000000000000000001453106675000161175ustar00rootroot00000000000000bieniu-gios-4ab1f9e/scripts/setup-local-env.sh000077500000000000000000000002421453106675000214720ustar00rootroot00000000000000#!/bin/bash python3.10 -m venv venv source venv/bin/activate pip3 install --upgrade pip setuptools wheel pip3 install -r requirements-dev.txt pre-commit install bieniu-gios-4ab1f9e/setup.py000066400000000000000000000023161453106675000161440ustar00rootroot00000000000000"""Setup module for gios.""" from pathlib import Path from setuptools import setup PROJECT_DIR = Path(__file__).parent.resolve() README_FILE = PROJECT_DIR / "README.md" VERSION = "3.2.2" setup( name="gios", version=VERSION, author="Maciej Bieniek", description="Python wrapper for getting air quality data from GIOŚ servers.", long_description=README_FILE.read_text(encoding="utf-8"), long_description_content_type="text/markdown", include_package_data=True, url="https://github.com/bieniu/gios", license="Apache-2.0 License", packages=["gios"], package_data={"gios": ["py.typed"]}, python_requires=">=3.10", install_requires=["aiohttp>=3.7.0", "dacite>=1.7.0"], 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.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3 :: Only", "Typing :: Typed", ], ) bieniu-gios-4ab1f9e/tests/000077500000000000000000000000001453106675000155725ustar00rootroot00000000000000bieniu-gios-4ab1f9e/tests/__init__.py000066400000000000000000000000361453106675000177020ustar00rootroot00000000000000"""Tests for gios package.""" bieniu-gios-4ab1f9e/tests/fixtures/000077500000000000000000000000001453106675000174435ustar00rootroot00000000000000bieniu-gios-4ab1f9e/tests/fixtures/indexes.json000066400000000000000000000024101453106675000217720ustar00rootroot00000000000000{ "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" } bieniu-gios-4ab1f9e/tests/fixtures/sensor_14395.json000066400000000000000000000005021453106675000224110ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/sensor_658.json000066400000000000000000000005011453106675000222450ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/sensor_660.json000066400000000000000000000005001453106675000222350ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/sensor_665.json000066400000000000000000000005011453106675000222430ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/sensor_667.json000066400000000000000000000005001453106675000222440ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/sensor_670.json000066400000000000000000000005031453106675000222410ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/sensor_672.json000066400000000000000000000004771453106675000222550ustar00rootroot00000000000000{ "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 } ] }bieniu-gios-4ab1f9e/tests/fixtures/station.json000066400000000000000000000024561453106675000220260ustar00rootroot00000000000000[ { "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 } } ] bieniu-gios-4ab1f9e/tests/fixtures/stations.json000066400000000000000000000004561453106675000222070ustar00rootroot00000000000000[{ "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" }]bieniu-gios-4ab1f9e/tests/test_init.py000066400000000000000000000445211453106675000201540ustar00rootroot00000000000000"""Tests for gios package.""" import json import aiohttp import pytest from aioresponses import aioresponses 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_valid_data_first_value(): """Test with valid data and valid first sensor's value.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) with open("tests/fixtures/station.json", encoding="utf-8") as file: station = json.load(file) with open("tests/fixtures/sensor_658.json", encoding="utf-8") as file: sensor_658 = json.load(file) with open("tests/fixtures/sensor_660.json", encoding="utf-8") as file: sensor_660 = json.load(file) with open("tests/fixtures/sensor_665.json", encoding="utf-8") as file: sensor_665 = json.load(file) with open("tests/fixtures/sensor_667.json", encoding="utf-8") as file: sensor_667 = json.load(file) with open("tests/fixtures/sensor_670.json", encoding="utf-8") as file: sensor_670 = json.load(file) with open("tests/fixtures/sensor_672.json", encoding="utf-8") as file: sensor_672 = json.load(file) with open("tests/fixtures/sensor_14395.json", encoding="utf-8") as file: sensor_14395 = json.load(file) with open("tests/fixtures/indexes.json", encoding="utf-8") as file: indexes = json.load(file) session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload=indexes, ) gios = Gios(VALID_STATION_ID, session) data = await gios.async_update() await session.close() 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 data.so2.value == 11.6502 assert data.so2.index == "very_good" assert data.c6h6.value == 2.57148 assert data.c6h6.index == "very_good" assert data.co.value == 786.702 assert data.co.index == "very_bad" assert data.no2.value == 59.9545 assert data.no2.index == "very_good" assert data.o3.value == 8.63111 assert data.o3.index == "bad" assert data.pm25.value == 59.9428 assert data.pm25.index == "sufficient" assert data.pm10.value == 123.879 assert data.pm10.index == "moderate" assert data.aqi.value == "good" @pytest.mark.asyncio async def test_api_error(): """Test GIOS API error.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", status=404, ) gios = Gios(VALID_STATION_ID, session) with pytest.raises(ApiError) as excinfo: await gios.async_update() assert str(excinfo.value) == "404" await session.close() @pytest.mark.asyncio async def test_valid_data_second_value(): """Test with valid data and valid second sensor's value.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) with open("tests/fixtures/station.json", encoding="utf-8") as file: station = json.load(file) with open("tests/fixtures/sensor_658.json", encoding="utf-8") as file: sensor_658 = json.load(file) with open("tests/fixtures/sensor_660.json", encoding="utf-8") as file: sensor_660 = json.load(file) with open("tests/fixtures/sensor_665.json", encoding="utf-8") as file: sensor_665 = json.load(file) with open("tests/fixtures/sensor_667.json", encoding="utf-8") as file: sensor_667 = json.load(file) with open("tests/fixtures/sensor_670.json", encoding="utf-8") as file: sensor_670 = json.load(file) with open("tests/fixtures/sensor_672.json", encoding="utf-8") as file: sensor_672 = json.load(file) with open("tests/fixtures/sensor_14395.json", encoding="utf-8") as file: sensor_14395 = json.load(file) with open("tests/fixtures/indexes.json", encoding="utf-8") as file: indexes = json.load(file) 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 = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload=indexes, ) gios = Gios(VALID_STATION_ID, session) data = await gios.async_update() await session.close() 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 data.so2.value == 11.501 assert data.so2.index == "very_good" assert data.c6h6.value == 3.24432 assert data.c6h6.index == "very_good" assert data.co.value == 1041.74 assert data.co.index == "very_bad" assert data.no2.value == 52.6198 assert data.no2.index == "very_good" assert data.o3.value == 4.93778 assert data.o3.index == "bad" assert data.pm25.value == 72.0243 assert data.pm25.index == "sufficient" assert data.pm10.value == 115.559 assert data.pm10.index == "moderate" assert data.aqi.value == "good" @pytest.mark.asyncio async def test_no_indexes_data(): """Test with valid data.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) with open("tests/fixtures/station.json", encoding="utf-8") as file: station = json.load(file) with open("tests/fixtures/sensor_658.json", encoding="utf-8") as file: sensor_658 = json.load(file) with open("tests/fixtures/sensor_660.json", encoding="utf-8") as file: sensor_660 = json.load(file) with open("tests/fixtures/sensor_665.json", encoding="utf-8") as file: sensor_665 = json.load(file) with open("tests/fixtures/sensor_667.json", encoding="utf-8") as file: sensor_667 = json.load(file) with open("tests/fixtures/sensor_670.json", encoding="utf-8") as file: sensor_670 = json.load(file) with open("tests/fixtures/sensor_672.json", encoding="utf-8") as file: sensor_672 = json.load(file) with open("tests/fixtures/sensor_14395.json", encoding="utf-8") as file: sensor_14395 = json.load(file) session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload={}, ) gios = Gios(VALID_STATION_ID, session) data = await gios.async_update() await session.close() 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 data.so2.value == 11.6502 assert data.so2.index is None assert data.c6h6.value == 2.57148 assert data.c6h6.index is None assert data.co.value == 786.702 assert data.co.index is None assert data.no2.value == 59.9545 assert data.no2.index is None assert data.o3.value == 8.63111 assert data.o3.index is None assert data.pm25.value == 59.9428 assert data.pm25.index is None assert data.pm10.value == 123.879 assert data.pm10.index is None assert data.aqi is None @pytest.mark.asyncio async def test_no_sensor_data_1(): """Test with no sensor data.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) with open("tests/fixtures/station.json", encoding="utf-8") as file: station = json.load(file) with open("tests/fixtures/sensor_658.json", encoding="utf-8") as file: sensor_658 = json.load(file) with open("tests/fixtures/sensor_660.json", encoding="utf-8") as file: sensor_660 = json.load(file) with open("tests/fixtures/sensor_665.json", encoding="utf-8") as file: sensor_665 = json.load(file) with open("tests/fixtures/sensor_667.json", encoding="utf-8") as file: sensor_667 = json.load(file) with open("tests/fixtures/sensor_670.json", encoding="utf-8") as file: sensor_670 = json.load(file) with open("tests/fixtures/sensor_672.json", encoding="utf-8") as file: sensor_672 = json.load(file) with open("tests/fixtures/sensor_14395.json", encoding="utf-8") as file: sensor_14395 = json.load(file) with open("tests/fixtures/indexes.json", encoding="utf-8") as file: indexes = json.load(file) 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 = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=sensor_672, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=sensor_658, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=sensor_660, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=sensor_665, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=sensor_667, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=sensor_670, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=sensor_14395, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/aqindex/getIndex/{VALID_STATION_ID}", payload=indexes, ) gios = Gios(VALID_STATION_ID, session) with pytest.raises(InvalidSensorsDataError): await gios.async_update() await session.close() @pytest.mark.asyncio async def test_invalid_sensor_data_2(): """Test with invalid sensor data.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) with open("tests/fixtures/station.json", encoding="utf-8") as file: station = json.load(file) session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload=station, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/672", payload=None, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/658", payload=None, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/660", payload=None, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/665", payload=None, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/667", payload=None, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/670", payload=None, ) session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/data/getData/14395", payload=None, ) gios = Gios(VALID_STATION_ID, session) with pytest.raises(InvalidSensorsDataError): await gios.async_update() await session.close() @pytest.mark.asyncio async def test_no_station_data(): """Test with no station data.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) session_mock.get( f"http://api.gios.gov.pl/pjp-api/rest/station/sensors/{VALID_STATION_ID}", payload={}, ) gios = Gios(VALID_STATION_ID, session) with pytest.raises(InvalidSensorsDataError): await gios.async_update() await session.close() @pytest.mark.asyncio async def test_no_stations_data(): """Test with no stations data.""" session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload={}, ) gios = Gios(VALID_STATION_ID, session) with pytest.raises(ApiError): await gios.async_update() await session.close() @pytest.mark.asyncio async def test_invalid_station_id(): """Test with invalid station_id.""" with open("tests/fixtures/stations.json", encoding="utf-8") as file: stations = json.load(file) session = aiohttp.ClientSession() with aioresponses() as session_mock: session_mock.get( "http://api.gios.gov.pl/pjp-api/rest/station/findAll", payload=stations, ) gios = Gios(INVALID_STATION_ID, session) with pytest.raises(NoStationError) as excinfo: await gios.async_update() assert str(excinfo.value) == "0 is not a valid measuring station ID" await session.close() bieniu-gios-4ab1f9e/tox.ini000066400000000000000000000013641453106675000157470ustar00rootroot00000000000000[tox] envlist = py310, py311, py312, lint, typing, coverage skip_missing_interpreters = True [gh-actions] python = 3.10: py310, lint, typing, coverage 3.11: py311 3.12: py312 [testenv] commands = pytest --timeout=30 --cov=gios --cov-report=xml {posargs} --error-for-skips deps = -rrequirements.txt -rrequirements-test.txt [testenv:lint] basepython = python3 ignore_errors = True commands = ruff check . ruff format --check . deps = -rrequirements.txt -rrequirements-test.txt [testenv:typing] basepython = python3 ignore_errors = True commands = mypy gios deps = -rrequirements.txt -rrequirements-test.txt [testenv:coverage] deps = -rrequirements.txt -rrequirements-test.txt commands = coverage report --fail-under=79