Compare commits

...

102 commits
patch ... main

Author SHA1 Message Date
Anne Barela
c11c7d417b
Merge pull request #117 from adafruit/TheKitty-patch-1
Update gps_simpletest.py for Raspberry Pi Pico
2025-07-23 12:33:22 -04:00
Anne Barela
e9b3b6ebe7
Update gps_simpletest.py
Add comments for use of GP4 and GP5 for Raspberry Pi Pico per guide feedback and forum post
2025-07-23 12:30:18 -04:00
foamyguy
0cccfbaecd update rtd.yml file
Signed-off-by: foamyguy <foamyguy@gmail.com>
2025-06-17 10:26:27 -05:00
foamyguy
ee938efc56
Merge pull request #116 from adafruit/use_ruff
change to ruff
2025-05-14 11:19:55 -05:00
foamyguy
dd02ced33b change to ruff 2025-05-14 16:16:14 +00:00
foamyguy
2671a7f644 add sphinx configuration to rtd.yaml
Signed-off-by: foamyguy <foamyguy@gmail.com>
2025-01-16 09:16:22 -06:00
Scott Shawcroft
01785202c7
Merge pull request #113 from snkYmkrct/main
Added VTG sentence parse for the km/h speed value
2024-10-08 12:30:40 -07:00
Snakey Maker Cat =^.^=
0466e451f6
Merge branch 'adafruit:main' into main 2024-10-07 23:07:05 +02:00
foamyguy
70298f4a28 remove deprecated get_html_theme_path() call
Signed-off-by: foamyguy <foamyguy@gmail.com>
2024-10-07 14:49:03 -05:00
snkYmkrct
dffaebcc23 Add NMEA VTG sentence parse for the km/h speed value 2024-10-07 18:13:16 +02:00
foamyguy
3e13731cae
Merge pull request #112 from snkYmkrct/main
Add displayio example
2024-10-03 18:45:04 -05:00
snkYmkrct
d43cdabb32 Add displayio example 2024-10-03 17:09:17 +02:00
Scott Shawcroft
ea37df37cb
Merge pull request #108 from adafruit/dhalbert-patch-1
Fix typo in _parse_gil()
2024-03-22 09:59:40 -07:00
Dan Halbert
41f15963f7
Fix typo in _parse_gil() 2024-03-22 11:54:01 -04:00
Alec Delaney
ab6b33a57c
Merge pull request #102 from jkittner/minutes_fix
fix minute parsing
2024-03-21 12:39:42 -04:00
Jonas Kittner
35f4904de3 replace partition with split
partition is not available on all boards
2024-01-19 17:27:52 +01:00
Jonas Kittner
f89329a981 remove tox 2024-01-18 17:02:39 +01:00
Jonas Kittner
500559b0d8 fix typo 2024-01-18 17:01:45 +01:00
Jonas Kittner
01bcf65ece fix float formatters in example with longitude_degrees being always ints 2024-01-18 16:58:33 +01:00
Jonas Kittner
42dd755047 fix minute parsing 2024-01-18 16:58:33 +01:00
Alec Delaney
9fd82a7b77 Reorganize imports 2024-01-18 16:58:33 +01:00
Alec Delaney
ae0019d714 Fix format specifier 2024-01-18 16:58:33 +01:00
Melissa LeBlanc-Williams
84a835f7aa
Merge pull request #106 from adafruit/docs_req_fixes
unpin sphinx and add sphinx-rtd-theme to docs reqs
2023-12-04 15:08:53 -08:00
foamyguy
e7b04f733f unpin sphinx and add sphinx-rtd-theme to docs reqs 2023-12-04 14:03:40 -06:00
Scott Shawcroft
e3e845bcb7
Merge pull request #104 from adafruit/fix_rtd_theme
fix rtd theme
2023-09-20 10:11:47 -07:00
foamyguy
337fafd283 fix rtd theme 2023-09-19 18:47:33 -05:00
Dan Halbert
c8dd225699
Merge pull request #100 from adafruit/dev/fix-pylint-jquery
Update .pylintrc, fix jQuery for docs
2023-05-23 23:22:10 -04:00
Alec Delaney
5e21680f41
Update .pylintrc, fix jQuery for docs 2023-05-23 23:07:13 -04:00
Alec Delaney
4b53a07978
Merge pull request #98 from awordforthat/issue82/update-gps-docs-amend
include key as well as value when iterating over satellite dictionary
2023-05-19 15:02:12 -04:00
Emily Charles
b75667f5b9 move dev requirements to optional requirements 2023-05-18 21:48:20 -04:00
Emily Charles
6971e892fb include key as well as value when iterating over satellite dictionary 2023-05-18 20:29:07 -04:00
Alec Delaney
99f1cc5309
Merge pull request #97 from awordforthat/issue82/update-gps-docs-amend
use values for satellite dict access instead of items
2023-05-18 20:01:37 -04:00
Emily Charles
a310747c2b use values for satellite dict access instead of items 2023-05-18 19:53:44 -04:00
Tekktrik
57a402adc7 Run pre-commit 2023-05-10 22:33:52 -04:00
Tekktrik
1e8ec15b8b Update pre-commit hooks
Signed-off-by: Tekktrik <tekktrik@gmail.com>
2023-05-10 15:29:10 -04:00
Scott Shawcroft
803c981df2
Merge pull request #96 from awordforthat/issue82/update-gps-docs
add docstrings to GPS class attrs
2023-04-26 10:11:08 -07:00
Emily Charles
a9d9a1160e use pylint rule name instead of code 2023-04-25 20:39:58 -04:00
Emily Charles
a46021a761 fixing pylint errors 2023-04-24 19:38:07 -04:00
Emily Charles
224bf57cff remove unused vars 2023-04-24 19:28:05 -04:00
Emily Charles
5282286ea3 linter fixes 2023-04-24 19:27:45 -04:00
Emily Charles
df8c75e21e add docstrings to GPS class attrs 2023-04-24 17:59:54 -04:00
Alec Delaney
f25a987200 Add upload url to release action
Signed-off-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com>
2023-01-19 23:54:46 -05:00
Alec Delaney
4b82d0593e Add .venv to .gitignore
Signed-off-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com>
2022-11-30 19:42:59 -05:00
Eva Herrada
e255f1acfb
Merge pull request #92 from adafruit/stemma_i2c
Added commented out board.STEMMA_I2C with explanation
2022-11-28 12:24:05 -05:00
dherrada
ec3f7a188a Merge branch 'main' of https://github.com/adafruit/Adafruit_CircuitPython_GPS into stemma_i2c 2022-11-18 15:12:46 -05:00
dherrada
ceb1d743e1 Added commented out board.STEMMA_I2C with explanation 2022-11-18 13:05:24 -05:00
Alec Delaney
9c43ee37c2 Update .pylintrc for v2.15.5 2022-11-04 18:34:32 -04:00
Alec Delaney
91e5ba04ba Fix release CI files 2022-11-04 09:12:43 -04:00
Alec Delaney
501207a777 Update pylint to 2.15.5 2022-11-04 08:15:19 -04:00
Alec Delaney
21963113a1 Updated pylint version to 2.13.0 2022-11-04 00:46:59 -04:00
Alec Delaney
2f6015e254 Switching to composite actions 2022-11-04 00:02:49 -04:00
Mark
04417ed2ca
Merge pull request #90 from tekktrik/dev/fix-example-import
Add commented out busio import
2022-10-06 17:54:03 -05:00
Alec Delaney
5c1bf71f34
Add commented out busio import 2022-10-06 17:12:45 -04:00
foamyguy
d8fdb0b09f
Merge pull request #86 from tekktrik/doc/add-typing
Add type annotations
2022-10-03 10:11:16 -05:00
Alec Delaney
4e2c583e2a
Fix annotation for _read_int_degrees() 2022-09-16 14:56:09 -04:00
Alec Delaney
6542aa5dc1
Change timeout default value to float 2022-09-16 14:54:08 -04:00
Alec Delaney
ceb92a6121
Remove comment regarding string type 2022-09-16 14:51:24 -04:00
Alec Delaney
dd1d40194d
Merge pull request #87 from zeerakb1/optional_text
added missing optional requirement
2022-08-31 10:49:32 -04:00
Zeerak Babar
6dacd0970a
Update optional_requirements.txt
Co-authored-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com>
2022-08-31 19:24:49 +05:00
Zeerak Babar
2849319d6d
Update optional_requirements.txt
Co-authored-by: Alec Delaney <89490472+tekktrik@users.noreply.github.com>
2022-08-31 15:50:03 +05:00
imzeerak
f6d7623454 added missing optional requirement 2022-08-31 00:42:06 +05:00
Alec Delaney
f98cd66f5a Add type annotations 2022-08-30 11:52:13 -04:00
Alec Delaney
f67f0e7820 Use year duration range for copyright attribution 2022-08-23 17:26:20 -04:00
Alec Delaney
caf51e53d1 Fix copyright string 2022-08-22 21:56:11 -04:00
Alec Delaney
05f5213d7a Keep copyright up to date in documentation 2022-08-22 21:36:30 -04:00
Alec Delaney
262826891e Fix version strings in workflow files 2022-08-16 21:09:13 -04:00
Alec Delaney
ad5b067e92 Update version string 2022-08-16 18:09:13 -04:00
Alec Delaney
d5881c725d Add setuptools-scm to build system requirements
Signed-off-by: Alec Delaney <tekktrik@gmail.com>
2022-08-09 13:35:31 -04:00
Alec Delaney
cca0f0f859 Switched to pyproject.toml 2022-08-08 22:05:52 -04:00
evaherrada
8e98eedc83
Added Black formatting badge 2022-08-02 17:00:37 -04:00
evaherrada
361f7994b7
Changed .env to .venv in README.rst 2022-07-22 13:58:49 -04:00
Dan Halbert
583fbd01ef
Merge pull request #80 from gamblor21/precision
Add handling with extra precision in lat/long
2022-06-16 22:44:31 -04:00
gamblor21
872ce6e4d5 Spelling mistake, comment 2022-06-16 18:19:09 -05:00
Dan Halbert
3e9b741416
Merge pull request #81 from adafruit/sdcardio
Changed code to use sdcardio as preferred method
2022-06-16 18:31:58 -04:00
evaherrada
41be1c34c3
Example auto chooses to use sd and what sd lib to use 2022-06-16 14:25:20 -04:00
Eva Herrada
2cab6bd262
Changed code to use sdcardio as preferred method 2022-06-15 17:43:07 -04:00
gamblor21
9f90c48e17 Refactor for mpy-cross 2022-06-13 22:47:12 -05:00
gamblor21
4ccc6b9630 Changed tests as internal representation of degrees changed 2022-06-13 22:31:18 -05:00
gamblor21
d22cc67f5c Fix to handle other nmea data string lengths 2022-06-13 22:30:35 -05:00
gamblor21
28b2d2543f Add handling with extra precision in lat/long 2022-06-13 16:36:16 -05:00
evaherrada
b0a4b6c1ca
Added cp.org link to index.rst 2022-06-07 15:34:24 -04:00
Alec Delaney
40b74abb7b Set language to "en" for documentation
Signed-off-by: Alec Delaney <tekktrik@gmail.com>
2022-05-30 17:41:10 -04:00
Alec Delaney
a24fa7e210 Increase min lines similarity
Signed-off-by: Alec Delaney <tekktrik@gmail.com>
2022-05-25 19:31:41 -04:00
Dan Halbert
af5ee59e5a
Merge pull request #79 from caternuson/iss74
Switch decode to str for small board support
2022-05-25 15:59:03 -04:00
caternuson
c4d9dd1660 black says double quotes please 2022-05-25 12:45:42 -07:00
caternuson
d25f2ec187 switch decode to str 2022-05-25 12:36:07 -07:00
Alec Delaney
2b4cdefe1d Patch .pre-commit-config.yaml 2022-05-15 12:47:55 -04:00
foamyguy
e233afd3d0 change discord badge 2022-04-24 13:51:55 -05:00
evaherrada
8050aee545
Patch: Replaced discord badge image 2022-04-22 15:58:43 -04:00
Eva Herrada
57ecffd3a5
Update .gitignore 2022-04-21 18:37:58 -04:00
Kattni Rembor
44c3fbec4a Update Black to latest.
Signed-off-by: Kattni Rembor <kattni@adafruit.com>
2022-03-28 18:06:36 -04:00
dherrada
83b2ff439d Fixed readthedocs build
Signed-off-by: dherrada <dylan.herrada@adafruit.com>
2022-02-15 11:50:53 -05:00
Alec Delaney
2590a68317 Consolidate Documentation sections of README 2022-02-09 12:58:29 -05:00
dherrada
e17c63eb1a Updated docs link, updated python docs link, updated setup.py 2022-01-24 16:46:16 -05:00
dherrada
3e41e4494d First part of patch
Signed-off-by: dherrada <dylan.herrada@adafruit.com>
2022-01-19 13:52:39 -05:00
Scott Shawcroft
98d505a4db
Merge pull request #76 from mrdalgaard/main
Enhanced parsing of timestamp_utc
2021-12-10 09:50:39 -08:00
root
ef300a2edb Added leading 0 to date string since it is no longer int and to follow NMEA sentence format of DDMMYY 2021-12-09 18:07:28 +01:00
root
10142fd0d9 Learning about formatting and black 2021-12-09 17:50:41 +01:00
root
bf26b17d90 Updated timestamp tests for new type format 2021-12-09 16:51:49 +01:00
root
41a4adff44 Enhanced parsing of timestamp_utc 2021-12-08 21:41:28 +01:00
foamyguy
b9e06e93f2 update rtd py version 2021-11-23 13:02:04 -06:00
Kattni
aaff06ddd8
Merge pull request #73 from adafruit/patch
Pylint and RTD update patch, and other fixes
2021-11-11 19:32:07 -05:00
29 changed files with 755 additions and 956 deletions

11
.gitattributes vendored Normal file
View file

@ -0,0 +1,11 @@
# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
.py text eol=lf
.rst text eol=lf
.txt text eol=lf
.yaml text eol=lf
.toml text eol=lf
.license text eol=lf
.md text eol=lf

View file

@ -4,7 +4,7 @@
Thank you for contributing! Before you submit a pull request, please read the following. Thank you for contributing! Before you submit a pull request, please read the following.
Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://circuitpython.readthedocs.io/en/latest/docs/design_guide.html Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html
If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs

View file

@ -10,75 +10,5 @@ jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Dump GitHub context - name: Run Build CI workflow
env: uses: adafruit/workflows-circuitpython-libs/build@main
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Translate Repo Name For Build Tools filename_prefix
id: repo-name
run: |
echo ::set-output name=repo-name::$(
echo ${{ github.repository }} |
awk -F '\/' '{ print tolower($2) }' |
tr '_' '-'
)
- name: Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: Versions
run: |
python3 --version
- name: Checkout Current Repo
uses: actions/checkout@v1
with:
submodules: true
- name: Checkout tools repo
uses: actions/checkout@v2
with:
repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci
- name: Install dependencies
# (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.)
run: |
source actions-ci/install.sh
- name: Pip install Sphinx, pre-commit
run: |
pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit
- name: Library version
run: git describe --dirty --always --tags
- name: Pre-commit hooks
run: |
pre-commit run --all-files
- name: run tests
run: |
pip install --upgrade tox
tox -e py
- name: Build assets
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- name: Archive bundles
uses: actions/upload-artifact@v2
with:
name: bundles
path: ${{ github.workspace }}/bundles/
- name: Check For docs folder
id: need-docs
run: |
echo ::set-output name=docs::$( find . -wholename './docs' )
- name: Build docs
if: contains(steps.need-docs.outputs.docs, 'docs')
working-directory: docs
run: sphinx-build -E -W -b html . _build/html
- name: Check For setup.py
id: need-pypi
run: |
echo ::set-output name=setup-py::$( find . -wholename './setup.py' )
- name: Build Python package
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
run: |
pip install --upgrade setuptools wheel twine readme_renderer testresources
python setup.py sdist
python setup.py bdist_wheel --universal
twine check dist/*
- name: Setup problem matchers
uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1

View file

@ -1,85 +0,0 @@
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
name: Release Actions
on:
release:
types: [published]
jobs:
upload-release-assets:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- name: Translate Repo Name For Build Tools filename_prefix
id: repo-name
run: |
echo ::set-output name=repo-name::$(
echo ${{ github.repository }} |
awk -F '\/' '{ print tolower($2) }' |
tr '_' '-'
)
- name: Set up Python 3.6
uses: actions/setup-python@v1
with:
python-version: 3.6
- name: Versions
run: |
python3 --version
- name: Checkout Current Repo
uses: actions/checkout@v1
with:
submodules: true
- name: Checkout tools repo
uses: actions/checkout@v2
with:
repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci
- name: Install deps
run: |
source actions-ci/install.sh
- name: Build assets
run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location .
- name: Upload Release Assets
# the 'official' actions version does not yet support dynamically
# supplying asset names to upload. @csexton's version chosen based on
# discussion in the issue below, as its the simplest to implement and
# allows for selecting files with a pattern.
# https://github.com/actions/upload-release-asset/issues/4
#uses: actions/upload-release-asset@v1.0.1
uses: csexton/release-asset-action@master
with:
pattern: "bundles/*"
github-token: ${{ secrets.GITHUB_TOKEN }}
upload-pypi:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Check For setup.py
id: need-pypi
run: |
echo ::set-output name=setup-py::$( find . -wholename './setup.py' )
- name: Set up Python
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Install dependencies
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Build and publish
if: contains(steps.need-pypi.outputs.setup-py, 'setup.py')
env:
TWINE_USERNAME: ${{ secrets.pypi_username }}
TWINE_PASSWORD: ${{ secrets.pypi_password }}
run: |
python setup.py sdist
twine upload dist/*

19
.github/workflows/release_gh.yml vendored Normal file
View file

@ -0,0 +1,19 @@
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
name: GitHub Release Actions
on:
release:
types: [published]
jobs:
upload-release-assets:
runs-on: ubuntu-latest
steps:
- name: Run GitHub Release CI workflow
uses: adafruit/workflows-circuitpython-libs/release-gh@main
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
upload-url: ${{ github.event.release.upload_url }}

19
.github/workflows/release_pypi.yml vendored Normal file
View file

@ -0,0 +1,19 @@
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
name: PyPI Release Actions
on:
release:
types: [published]
jobs:
upload-release-assets:
runs-on: ubuntu-latest
steps:
- name: Run PyPI Release CI workflow
uses: adafruit/workflows-circuitpython-libs/release-pypi@main
with:
pypi-username: ${{ secrets.pypi_username }}
pypi-password: ${{ secrets.pypi_password }}

51
.gitignore vendored
View file

@ -1,17 +1,48 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: MIT
# Do not include files and directories created by your personal work environment, such as the IDE
# you use, except for those already listed here. Pull requests including changes to this file will
# not be accepted.
# This .gitignore file contains rules for files generated by working with CircuitPython libraries,
# including building Sphinx, testing with pip, and creating a virual environment, as well as the
# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs.
# If you find that there are files being generated on your machine that should not be included in
# your git commit, you should create a .gitignore_global file on your computer to include the
# files created by your personal setup. To do so, follow the two steps below.
# First, create a file called .gitignore_global somewhere convenient for you, and add rules for
# the files you want to exclude from git commits.
# Second, configure Git to use the exclude file for all Git repositories by running the
# following via commandline, replacing "path/to/your/" with the actual path to your newly created
# .gitignore_global file:
# git config --global core.excludesfile path/to/your/.gitignore_global
# CircuitPython-specific files
*.mpy *.mpy
.idea
# Python-specific files
__pycache__ __pycache__
_build
*.pyc *.pyc
# Sphinx build-specific files
_build
# This file results from running `pip -e install .` in a local repository
*.egg-info
# Virtual environment-specific files
.env .env
bundles .venv
# MacOS-specific files
*.DS_Store *.DS_Store
.eggs
dist # IDE-specific files
**/*.egg-info .idea
.tox .vscode
.coverage *~

View file

@ -1,42 +1,21 @@
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò # SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
repos: repos:
- repo: https://github.com/python/black
rev: 20.8b1
hooks:
- id: black
- repo: https://github.com/fsfe/reuse-tool
rev: v0.12.1
hooks:
- id: reuse
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0 rev: v4.5.0
hooks: hooks:
- id: check-yaml - id: check-yaml
- id: end-of-file-fixer - id: end-of-file-fixer
- id: trailing-whitespace - id: trailing-whitespace
- repo: https://github.com/pycqa/pylint - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v2.11.1 rev: v0.3.4
hooks: hooks:
- id: pylint - id: ruff-format
name: pylint (library code) - id: ruff
types: [python] args: ["--fix"]
args: - repo: https://github.com/fsfe/reuse-tool
- --disable=consider-using-f-string rev: v3.0.1
exclude: "^(docs/|examples/|tests/|setup.py$)" hooks:
- id: pylint - id: reuse
name: pylint (example code)
description: Run pylint rules on "examples/*.py" files
types: [python]
files: "^examples/"
args:
- --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code
- id: pylint
name: pylint (test code)
description: Run pylint rules on "tests/*.py" files
types: [python]
files: "^tests/"
args:
- --disable=missing-docstring,consider-using-f-string,duplicate-code

436
.pylintrc
View file

@ -1,436 +0,0 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
[MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=
# Add files or directories to the ignore-list. They should be base names, not
# paths.
ignore=CVS
# Add files or directories matching the regex patterns to the ignore-list. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint.
jobs=1
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Specify a configuration file.
#rcfile=
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,pointless-string-statement,unspecified-encoding
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=
[REPORTS]
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio).You can also give a reporter class, eg
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
[LOGGING]
# Logging modules to check that the string format arguments are in logging
# function parameter format
logging-modules=logging
[SPELLING]
# Spelling dictionary name. Available dictionaries: none. To make it working
# install python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to indicated private dictionary in
# --spelling-private-dict-file option instead of raising a message.
spelling-store-unknown-words=no
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
# notes=FIXME,XXX,TODO
notes=FIXME,XXX
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=board
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid to define new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,_cb
# A regular expression matching the name of dummy variables (i.e. expectedly
# not used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,future.builtins
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
# expected-line-ending-format=
expected-line-ending-format=LF
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=yes
# Minimum lines number of a similarity.
min-similarity-lines=4
[BASIC]
# Naming hint for argument names
argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct argument names
argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Naming hint for attribute names
attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct attribute names
attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Bad variable names which should always be refused, separated by a comma
bad-names=foo,bar,baz,toto,tutu,tata
# Naming hint for class attribute names
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Regular expression matching correct class attribute names
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
# Naming hint for class names
# class-name-hint=[A-Z_][a-zA-Z0-9]+$
class-name-hint=[A-Z_][a-zA-Z0-9_]+$
# Regular expression matching correct class names
# class-rgx=[A-Z_][a-zA-Z0-9]+$
class-rgx=[A-Z_][a-zA-Z0-9_]+$
# Naming hint for constant names
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Regular expression matching correct constant names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming hint for function names
function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct function names
function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Good variable names which should always be accepted, separated by a comma
# good-names=i,j,k,ex,Run,_
good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_
# Include a hint for the correct naming format with invalid-name
include-naming-hint=no
# Naming hint for inline iteration names
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
# Regular expression matching correct inline iteration names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
# Naming hint for method names
method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct method names
method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Naming hint for module names
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Regular expression matching correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
property-classes=abc.abstractproperty
# Naming hint for variable names
variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
# Regular expression matching correct variable names
variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$
[IMPORTS]
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled)
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled)
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled)
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,__new__,setUp
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs
[DESIGN]
# Maximum number of arguments for function / method
max-args=5
# Maximum number of attributes for a class (see R0902).
# max-attributes=7
max-attributes=11
# Maximum number of boolean expressions in a if statement
max-bool-expr=5
# Maximum number of branch for function / method body
max-branches=12
# Maximum number of locals for function / method body
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body
max-returns=6
# Maximum number of statements in function / method body
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=1
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception

View file

@ -8,8 +8,15 @@
# Required # Required
version: 2 version: 2
sphinx:
configuration: docs/conf.py
build:
os: ubuntu-lts-latest
tools:
python: "3"
python: python:
version: "3.6"
install: install:
- requirements: docs/requirements.txt - requirements: docs/requirements.txt
- requirements: requirements.txt - requirements: requirements.txt

View file

@ -2,10 +2,10 @@ Introduction
============ ============
.. image:: https://readthedocs.org/projects/adafruit-circuitpython-gps/badge/?version=latest .. image:: https://readthedocs.org/projects/adafruit-circuitpython-gps/badge/?version=latest
:target: https://circuitpython.readthedocs.io/projects/gps/en/latest/ :target: https://docs.circuitpython.org/projects/gps/en/latest/
:alt: Documentation Status :alt: Documentation Status
.. image :: https://img.shields.io/discord/327254708534116352.svg .. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg
:target: https://adafru.it/discord :target: https://adafru.it/discord
:alt: Discord :alt: Discord
@ -13,6 +13,10 @@ Introduction
:target: https://github.com/adafruit/Adafruit_CircuitPython_GPS/actions/ :target: https://github.com/adafruit/Adafruit_CircuitPython_GPS/actions/
:alt: Build Status :alt: Build Status
.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
:target: https://github.com/astral-sh/ruff
:alt: Code Style: Ruff
GPS parsing module. Can send commands to, and parse simple NMEA data sentences GPS parsing module. Can send commands to, and parse simple NMEA data sentences
from serial and I2C GPS modules to read latitude, longitude, and more. from serial and I2C GPS modules to read latitude, longitude, and more.
@ -48,8 +52,8 @@ To install in a virtual environment in your current project:
.. code-block:: shell .. code-block:: shell
mkdir project-name && cd project-name mkdir project-name && cd project-name
python3 -m venv .env python3 -m venv .venv
source .env/bin/activate source .venv/bin/activate
pip3 install adafruit-circuitpython-gps pip3 install adafruit-circuitpython-gps
Usage Example Usage Example
@ -122,7 +126,9 @@ should fix this.
Documentation Documentation
============= =============
API documentation for this library can be found on `Read the Docs <https://circuitpython.readthedocs.io/projects/gps/en/latest/>`_. API documentation for this library can be found on `Read the Docs <https://docs.circuitpython.org/projects/gps/en/latest/>`_.
For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.
Contributing Contributing
============ ============
@ -130,8 +136,3 @@ Contributing
Contributions are welcome! Please read our `Code of Conduct Contributions are welcome! Please read our `Code of Conduct
<https://github.com/adafruit/Adafruit_CircuitPython_gps/blob/main/CODE_OF_CONDUCT.md>`_ <https://github.com/adafruit/Adafruit_CircuitPython_gps/blob/main/CODE_OF_CONDUCT.md>`_
before contributing to help this project stay welcoming. before contributing to help this project stay welcoming.
Documentation
=============
For information on building library documentation, please check out `this guide <https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/sharing-our-docs-on-readthedocs#sphinx-5-1>`_.

View file

@ -26,10 +26,21 @@ Implementation Notes
https://github.com/adafruit/circuitpython/releases https://github.com/adafruit/circuitpython/releases
""" """
import time import time
from micropython import const from micropython import const
__version__ = "0.0.0-auto.0" try:
from typing import List, Optional, Tuple
from busio import I2C, UART
from circuitpython_typing import ReadableBuffer
from typing_extensions import Literal
except ImportError:
pass
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_GPS.git" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_GPS.git"
@ -45,16 +56,17 @@ _GSV11 = 6
_GSV15 = 7 _GSV15 = 7
_GSV19 = 8 _GSV19 = 8
_RMC_4_1 = 9 _RMC_4_1 = 9
_VTG = 10
_ST_MIN = _GLL _ST_MIN = _GLL
_ST_MAX = _RMC_4_1 _ST_MAX = _VTG
_SENTENCE_PARAMS = ( _SENTENCE_PARAMS = (
# 0 - _GLL # 0 - _GLL
"dcdcfcC", "dcdcscC",
# 1 - _RMC # 1 - _RMC
"fcdcdcffiDCC", "scdcdcffsDCC",
# 2 - _GGA # 2 - _GGA
"fdcdciiffsfsIS", "sdcdciiffsfsIS",
# 3 - _GSA # 3 - _GSA
"ciIIIIIIIIIIIIfff", "ciIIIIIIIIIIIIfff",
# 4 - _GSA_4_11 # 4 - _GSA_4_11
@ -68,50 +80,80 @@ _SENTENCE_PARAMS = (
# 8 - _GSV19 # 8 - _GSV19
"iiiiiiIiiiIiiiIiiiI", "iiiiiiIiiiIiiiIiiiI",
# 9 - _RMC_4_1 # 9 - _RMC_4_1
"fcdcdcffiDCCC", "scdcdcffsDCCC",
# 10 - _VTG
"fcFCfcfcC",
) )
# Internal helper parsing functions. # Internal helper parsing functions.
# These handle input that might be none or null and return none instead of # These handle input that might be none or null and return none instead of
# throwing errors. # throwing errors.
def _parse_degrees(nmea_data): def _parse_degrees(nmea_data: str) -> int:
# Parse a NMEA lat/long data pair 'dddmm.mmmm' into a pure degrees value. # Parse a NMEA lat/long data pair 'dddmm.mmmm' into a pure degrees value.
# Where ddd is the degrees, mm.mmmm is the minutes. # Where ddd is the degrees, mm.mmmm is the minutes.
if nmea_data is None or len(nmea_data) < 3: if nmea_data is None or len(nmea_data) < 3:
return None return None
raw = float(nmea_data) # To avoid losing precision handle degrees and minutes separately
deg = raw // 100 # Return the final value as an integer. Further functions can parse
minutes = raw % 100 # this into a float or separate parts to retain the precision
return deg + minutes / 60 raw = nmea_data.split(".")
degrees = int(raw[0]) // 100 * 1000000 # the ddd
minutes = int(raw[0]) % 100 # the mm.
minutes += int(f"{raw[1][:4]:0<4}") / 10000
minutes = int((minutes * 1000000) / 60)
return degrees + minutes
def _parse_int(nmea_data): def _parse_int(nmea_data: str) -> int:
if nmea_data is None or nmea_data == "": if nmea_data is None or not nmea_data:
return None return None
return int(nmea_data) return int(nmea_data)
def _parse_float(nmea_data): def _parse_float(nmea_data: str) -> float:
if nmea_data is None or nmea_data == "": if nmea_data is None or not nmea_data:
return None return None
return float(nmea_data) return float(nmea_data)
def _parse_str(nmea_data): def _parse_str(nmea_data: str) -> str:
if nmea_data is None or nmea_data == "": if nmea_data is None or not nmea_data:
return None return None
return str(nmea_data) return str(nmea_data)
def _read_degrees(data, index, neg): def _read_degrees(data: List[float], index: int, neg: str) -> float:
x = data[index] # This function loses precision with float32
x = data[index] / 1000000
if data[index + 1].lower() == neg: if data[index + 1].lower() == neg:
x *= -1.0 x *= -1.0
return x return x
def _parse_talker(data_type): def _read_deg_mins(data: List[str], index: int, neg: str) -> Tuple[int, float]:
# the degrees come in different formats and vary between latitudes and
# longitudes, which makes parsing tricky:
# for latitudes: ddmm,mmmm (0 - 7 decimal places, not zero padded)
# for longitudes: dddmm,mmmm (0 - 7 decimal places, not zero padded)
if "." in data[index]:
int_part, minutes_decimal = data[index].split(".")
else:
int_part, minutes_decimal = data[index], 0
# we need to parse from right to left, minutes can only have 2 digits
minutes_int = int_part[-2:]
# the rest must be degrees which are either 2 or 3 digits
deg = int(int_part[:-2])
# combine the parts of the minutes, this also works when there are no
# decimal places specified in the sentence
minutes = float(f"{minutes_int}.{minutes_decimal}")
if data[index + 1].lower() == neg:
deg *= -1
return deg, minutes
def _parse_talker(data_type: bytes) -> Tuple[bytes, bytes]:
# Split the data_type into talker and sentence_type # Split the data_type into talker and sentence_type
if data_type[:1] == b"P": # Proprietary codes if data_type[:1] == b"P": # Proprietary codes
return (data_type[:1], data_type[1:]) return (data_type[:1], data_type[1:])
@ -119,11 +161,10 @@ def _parse_talker(data_type):
return (data_type[:2], data_type[2:]) return (data_type[:2], data_type[2:])
def _parse_data(sentence_type, data): def _parse_data(sentence_type: int, data: List[str]) -> Optional[List]:
"""Parse sentence data for the specified sentence type and """Parse sentence data for the specified sentence type and
return a list of parameters in the correct format, or return None. return a list of parameters in the correct format, or return None.
""" """
# pylint: disable=too-many-branches
if not _ST_MIN <= sentence_type <= _ST_MAX: if not _ST_MIN <= sentence_type <= _ST_MAX:
# The sentence_type is unknown # The sentence_type is unknown
@ -166,6 +207,12 @@ def _parse_data(sentence_type, data):
elif pti == "f": elif pti == "f":
# A floating point number # A floating point number
params.append(_parse_float(dti)) params.append(_parse_float(dti))
elif pti == "F":
# A floating point number or Nothing
if nothing:
params.append(None)
else:
params.append(_parse_float(dti))
elif pti == "i": elif pti == "i":
# An integer # An integer
params.append(_parse_int(dti)) params.append(_parse_int(dti))
@ -194,48 +241,97 @@ def _parse_data(sentence_type, data):
return params return params
# lint warning about too many attributes disabled
# pylint: disable-msg=R0902
class GPS: class GPS:
"""GPS parsing module. Can parse simple NMEA data sentences from serial """GPS parsing module. Can parse simple NMEA data sentences from serial
GPS modules to read latitude, longitude, and more. GPS modules to read latitude, longitude, and more.
""" """
def __init__(self, uart, debug=False): def __init__(self, uart: UART, debug: bool = False) -> None:
self._uart = uart self._uart = uart
# Initialize null starting values for GPS attributes. # Initialize null starting values for GPS attributes.
self.timestamp_utc = None self.timestamp_utc = None
"""Timestamp in UTC"""
self.latitude = None self.latitude = None
"""Degrees latitude"""
self.latitude_degrees = None
"""Degrees component of latitude measurement"""
self.latitude_minutes = None # Use for full precision minutes
"""Minutes component of latitude measurement"""
self.longitude = None self.longitude = None
"""Degrees longitude"""
self.longitude_degrees = None
"""Degrees component of longitude measurement"""
self.longitude_minutes = None # Use for full precision minutes
"""Minutes component of longitude measurement"""
self.fix_quality = 0 self.fix_quality = 0
"""
GPS quality indicator
| 0 - fix not available
| 1 - GPS fix
| 2 - Differential GPS fix (values above 2 are 2.3 features)
| 3 - PPS fix
| 4 - Real Time Kinematic
| 5 - Float RTK
| 6 - estimated (dead reckoning)
| 7 - Manual input mode
| 8 - Simulation mode
"""
self.fix_quality_3d = 0 self.fix_quality_3d = 0
"""
The type of fix for a reading
| 1 - no fix
| 2 - 2D fix
| 3 - 3D fix
"""
self.satellites = None self.satellites = None
"""The number of satellites in use, 0 - 12"""
self.satellites_prev = None self.satellites_prev = None
"""The number of satellites in use from the previous data point, 0 - 12"""
self.horizontal_dilution = None self.horizontal_dilution = None
"""Horizontal dilution of precision (GGA)"""
self.altitude_m = None self.altitude_m = None
"""Antenna altitude relative to mean sea level"""
self.height_geoid = None self.height_geoid = None
"""Geoidal separation relative to WGS 84"""
self.speed_knots = None self.speed_knots = None
"""Ground speed in knots"""
self.speed_kmh = None
"""Ground speed in km/h"""
self.track_angle_deg = None self.track_angle_deg = None
"""Track angle in degrees"""
self._sats = None # Temporary holder for information from GSV messages self._sats = None # Temporary holder for information from GSV messages
self.sats = None # Completed information from GSV messages self.sats = None
"""Information from GSV messages"""
self.isactivedata = None self.isactivedata = None
self.true_track = None """Status Valid(A) or Invalid(V)"""
self.mag_track = None
self.sat_prns = None self.sat_prns = None
"""Satellite pseudorandom noise code"""
self.sel_mode = None self.sel_mode = None
"""
Selection mode
| 'M' - manual
| 'A' - automatic
"""
self.pdop = None self.pdop = None
"""Dilution of precision"""
self.hdop = None self.hdop = None
"""Horizontal dilution of precision (GSA)"""
self.vdop = None self.vdop = None
"""Vertical dilution of precision"""
self.total_mess_num = None self.total_mess_num = None
"""Number of messages"""
self.mess_num = None self.mess_num = None
"""Message number"""
self._raw_sentence = None self._raw_sentence = None
self._mode_indicator = None self._mode_indicator = None
self._magnetic_variation = None self._magnetic_variation = None
self.debug = debug self.debug = debug
"""Toggles debug mode. When True, prints the incoming data sentence to the console"""
def update(self): def update(self) -> bool:
"""Check for updated data from the GPS module and process it """Check for updated data from the GPS module and process it
accordingly. Returns True if new data was processed, and False if accordingly. Returns True if new data was processed, and False if
nothing new was received. nothing new was received.
@ -265,7 +361,7 @@ class GPS:
# GP - GPS # GP - GPS
# GQ - QZSS # GQ - QZSS
# GN - GNSS / More than one of the above # GN - GNSS / More than one of the above
if talker not in (b"GA", b"GB", b"GI", b"GL", b"GP", b"GQ", b"GN"): if talker not in {b"GA", b"GB", b"GI", b"GL", b"GP", b"GQ", b"GN"}:
# It's not a known GNSS source of data # It's not a known GNSS source of data
# Assume it's a valid packet anyway # Assume it's a valid packet anyway
return True return True
@ -282,10 +378,12 @@ class GPS:
result = self._parse_gsv(talker, args) result = self._parse_gsv(talker, args)
elif sentence_type == b"GSA": # GPS DOP and active satellites elif sentence_type == b"GSA": # GPS DOP and active satellites
result = self._parse_gsa(talker, args) result = self._parse_gsa(talker, args)
elif sentence_type == b"VTG": # Ground speed
result = self._parse_vtg(args)
return result return result
def send_command(self, command, add_checksum=True): def send_command(self, command: bytes, add_checksum: bool = True) -> None:
"""Send a command string to the GPS. If add_checksum is True (the """Send a command string to the GPS. If add_checksum is True (the
default) a NMEA checksum will automatically be computed and added. default) a NMEA checksum will automatically be computed and added.
Note you should NOT add the leading $ and trailing * to the command Note you should NOT add the leading $ and trailing * to the command
@ -298,54 +396,53 @@ class GPS:
for char in command: for char in command:
checksum ^= char checksum ^= char
self.write(b"*") self.write(b"*")
self.write(bytes("{:02x}".format(checksum).upper(), "ascii")) self.write(bytes(f"{checksum:02x}".upper(), "ascii"))
self.write(b"\r\n") self.write(b"\r\n")
@property @property
def has_fix(self): def has_fix(self) -> bool:
"""True if a current fix for location information is available.""" """True if a current fix for location information is available."""
return self.fix_quality is not None and self.fix_quality >= 1 return self.fix_quality is not None and self.fix_quality >= 1
@property @property
def has_3d_fix(self): def has_3d_fix(self) -> bool:
"""Returns true if there is a 3d fix available. """Returns true if there is a 3d fix available.
use has_fix to determine if a 2d fix is available, use has_fix to determine if a 2d fix is available,
passing it the same data""" passing it the same data"""
return self.fix_quality_3d is not None and self.fix_quality_3d >= 2 return self.fix_quality_3d is not None and self.fix_quality_3d >= 2
@property @property
def datetime(self): def datetime(self) -> Optional[time.struct_time]:
"""Return struct_time object to feed rtc.set_time_source() function""" """Return struct_time object to feed rtc.set_time_source() function"""
return self.timestamp_utc return self.timestamp_utc
@property @property
def nmea_sentence(self): def nmea_sentence(self) -> Optional[str]:
"""Return raw_sentence which is the raw NMEA sentence read from the GPS""" """Return raw_sentence which is the raw NMEA sentence read from the GPS"""
return self._raw_sentence return self._raw_sentence
def read(self, num_bytes): def read(self, num_bytes: Optional[int]) -> Optional[bytes]:
"""Read up to num_bytes of data from the GPS directly, without parsing. """Read up to num_bytes of data from the GPS directly, without parsing.
Returns a bytearray with up to num_bytes or None if nothing was read""" Returns a bytestring with up to num_bytes or None if nothing was read"""
return self._uart.read(num_bytes) return self._uart.read(num_bytes)
def write(self, bytestr): def write(self, bytestr: ReadableBuffer) -> Optional[int]:
"""Write a bytestring data to the GPS directly, without parsing """Write a bytestring data to the GPS directly, without parsing
or checksums""" or checksums"""
return self._uart.write(bytestr) return self._uart.write(bytestr)
@property @property
def in_waiting(self): def in_waiting(self) -> int:
"""Returns number of bytes available in UART read buffer""" """Returns number of bytes available in UART read buffer"""
return self._uart.in_waiting return self._uart.in_waiting
def readline(self): def readline(self) -> Optional[bytes]:
"""Returns a newline terminated bytearray, must have timeout set for """Returns a newline terminated bytestring, must have timeout set for
the underlying UART or this will block forever!""" the underlying UART or this will block forever!"""
return self._uart.readline() return self._uart.readline()
def _read_sentence(self): def _read_sentence(self) -> Optional[str]:
# Parse any NMEA sentence that is available. # Parse any NMEA sentence that is available.
# pylint: disable=len-as-condition
# This needs to be refactored when it can be tested. # This needs to be refactored when it can be tested.
# Only continue if we have at least 11 bytes in the input buffer # Only continue if we have at least 11 bytes in the input buffer
@ -376,7 +473,7 @@ class GPS:
# At this point we don't have a valid sentence # At this point we don't have a valid sentence
return None return None
def _parse_sentence(self): def _parse_sentence(self) -> Optional[Tuple[str, str]]:
sentence = self._read_sentence() sentence = self._read_sentence()
# sentence is a valid NMEA with a valid checksum # sentence is a valid NMEA with a valid checksum
@ -393,10 +490,10 @@ class GPS:
data_type = sentence[1:delimiter] data_type = sentence[1:delimiter]
return (data_type, sentence[delimiter + 1 :]) return (data_type, sentence[delimiter + 1 :])
def _update_timestamp_utc(self, time_utc, date=None): def _update_timestamp_utc(self, time_utc: str, date: Optional[str] = None) -> None:
hours = time_utc // 10000 hours = int(time_utc[0:2])
mins = (time_utc // 100) % 100 mins = int(time_utc[2:4])
secs = time_utc % 100 secs = int(time_utc[4:6])
if date is None: if date is None:
if self.timestamp_utc is None: if self.timestamp_utc is None:
day, month, year = 0, 0, 0 day, month, year = 0, 0, 0
@ -405,127 +502,146 @@ class GPS:
month = self.timestamp_utc.tm_mon month = self.timestamp_utc.tm_mon
year = self.timestamp_utc.tm_year year = self.timestamp_utc.tm_year
else: else:
day = date // 10000 day = int(date[0:2])
month = (date // 100) % 100 month = int(date[2:4])
year = 2000 + date % 100 year = 2000 + int(date[4:6])
self.timestamp_utc = time.struct_time( self.timestamp_utc = time.struct_time((year, month, day, hours, mins, secs, 0, 0, -1))
(year, month, day, hours, mins, secs, 0, 0, -1)
)
def _parse_gll(self, data): def _parse_vtg(self, data: List[str]) -> bool:
# VTG - Course Over Ground and Ground Speed
if data is None or len(data) != 9:
return False # Unexpected number of params
parsed_data = _parse_data(_VTG, data)
if parsed_data is None:
return False # Params didn't parse
# Track made good, degrees true
self.track_angle_deg = parsed_data[0]
# Speed over ground, knots
self.speed_knots = parsed_data[4]
# Speed over ground, kilometers / hour
self.speed_kmh = parsed_data[6]
# Parse FAA mode indicator
self._mode_indicator = parsed_data[8]
return True
def _parse_gll(self, data: List[str]) -> bool:
# GLL - Geographic Position - Latitude/Longitude # GLL - Geographic Position - Latitude/Longitude
if data is None or len(data) != 7: if data is None or len(data) != 7:
return False # Unexpected number of params. return False # Unexpected number of params.
data = _parse_data(_GLL, data) parsed_data = _parse_data(_GLL, data)
if data is None: if parsed_data is None:
return False # Params didn't parse return False # Params didn't parse
# Latitude # Latitude
self.latitude = _read_degrees(data, 0, "s") self.latitude = _read_degrees(parsed_data, 0, "s")
self.latitude_degrees, self.latitude_minutes = _read_deg_mins(data=data, index=0, neg="s")
# Longitude # Longitude
self.longitude = _read_degrees(data, 2, "w") self.longitude = _read_degrees(parsed_data, 2, "w")
self.longitude_degrees, self.longitude_minutes = _read_deg_mins(data=data, index=2, neg="w")
# UTC time of position # UTC time of position
self._update_timestamp_utc(int(data[4])) self._update_timestamp_utc(parsed_data[4])
# Status Valid(A) or Invalid(V) # Status Valid(A) or Invalid(V)
self.isactivedata = data[5] self.isactivedata = parsed_data[5]
# Parse FAA mode indicator # Parse FAA mode indicator
self._mode_indicator = data[6] self._mode_indicator = parsed_data[6]
return True return True
def _parse_rmc(self, data): def _parse_rmc(self, data: List[str]) -> bool:
# RMC - Recommended Minimum Navigation Information # RMC - Recommended Minimum Navigation Information
if data is None or len(data) not in (12, 13): if data is None or len(data) not in {12, 13}:
return False # Unexpected number of params. return False # Unexpected number of params.
data = _parse_data({12: _RMC, 13: _RMC_4_1}[len(data)], data) parsed_data = _parse_data({12: _RMC, 13: _RMC_4_1}[len(data)], data)
if data is None: if parsed_data is None:
self.fix_quality = 0 self.fix_quality = 0
return False # Params didn't parse return False # Params didn't parse
# UTC time of position and date # UTC time of position and date
self._update_timestamp_utc(int(data[0]), data[8]) self._update_timestamp_utc(parsed_data[0], parsed_data[8])
# Status Valid(A) or Invalid(V) # Status Valid(A) or Invalid(V)
self.isactivedata = data[1] self.isactivedata = parsed_data[1]
if data[1].lower() == "a": if parsed_data[1].lower() == "a":
if self.fix_quality == 0: if self.fix_quality == 0:
self.fix_quality = 1 self.fix_quality = 1
else: else:
self.fix_quality = 0 self.fix_quality = 0
# Latitude # Latitude
self.latitude = _read_degrees(data, 2, "s") self.latitude = _read_degrees(parsed_data, 2, "s")
self.latitude_degrees, self.latitude_minutes = _read_deg_mins(data=data, index=2, neg="s")
# Longitude # Longitude
self.longitude = _read_degrees(data, 4, "w") self.longitude = _read_degrees(parsed_data, 4, "w")
self.longitude_degrees, self.longitude_minutes = _read_deg_mins(data=data, index=4, neg="w")
# Speed over ground, knots # Speed over ground, knots
self.speed_knots = data[6] self.speed_knots = parsed_data[6]
# Track made good, degrees true # Track made good, degrees true
self.track_angle_deg = data[7] self.track_angle_deg = parsed_data[7]
# Magnetic variation # Magnetic variation
if data[9] is None or data[10] is None: if parsed_data[9] is None or parsed_data[10] is None:
self._magnetic_variation = None self._magnetic_variation = None
else: else:
self._magnetic_variation = _read_degrees(data, 9, "w") self._magnetic_variation = _read_degrees(parsed_data, 9, "w")
# Parse FAA mode indicator # Parse FAA mode indicator
self._mode_indicator = data[11] self._mode_indicator = parsed_data[11]
return True return True
def _parse_gga(self, data): def _parse_gga(self, data: List[str]) -> bool:
# GGA - Global Positioning System Fix Data # GGA - Global Positioning System Fix Data
if data is None or len(data) != 14: if data is None or len(data) != 14:
return False # Unexpected number of params. return False # Unexpected number of params.
data = _parse_data(_GGA, data) parsed_data = _parse_data(_GGA, data)
if data is None: if parsed_data is None:
self.fix_quality = 0 self.fix_quality = 0
return False # Params didn't parse return False # Params didn't parse
# UTC time of position # UTC time of position
self._update_timestamp_utc(int(data[0])) self._update_timestamp_utc(parsed_data[0])
# Latitude # Latitude
self.latitude = _read_degrees(data, 1, "s") self.latitude = _read_degrees(parsed_data, 1, "s")
self.longitude_degrees, self.longitude_minutes = _read_deg_mins(data=data, index=3, neg="w")
# Longitude # Longitude
self.longitude = _read_degrees(data, 3, "w") self.longitude = _read_degrees(parsed_data, 3, "w")
self.latitude_degrees, self.latitude_minutes = _read_deg_mins(data=data, index=1, neg="s")
# GPS quality indicator # GPS quality indicator
# 0 - fix not available, self.fix_quality = parsed_data[5]
# 1 - GPS fix,
# 2 - Differential GPS fix (values above 2 are 2.3 features)
# 3 - PPS fix
# 4 - Real Time Kinematic
# 5 - Float RTK
# 6 - estimated (dead reckoning)
# 7 - Manual input mode
# 8 - Simulation mode
self.fix_quality = data[5]
# Number of satellites in use, 0 - 12 # Number of satellites in use, 0 - 12
self.satellites = data[6] self.satellites = parsed_data[6]
# Horizontal dilution of precision # Horizontal dilution of precision
self.horizontal_dilution = data[7] self.horizontal_dilution = parsed_data[7]
# Antenna altitude relative to mean sea level # Antenna altitude relative to mean sea level
self.altitude_m = _parse_float(data[8]) self.altitude_m = _parse_float(parsed_data[8])
# data[9] - antenna altitude unit, always 'M' ??? # data[9] - antenna altitude unit, always 'M' ???
# Geoidal separation relative to WGS 84 # Geoidal separation relative to WGS 84
self.height_geoid = _parse_float(data[10]) self.height_geoid = _parse_float(parsed_data[10])
# data[11] - geoidal separation unit, always 'M' ??? # data[11] - geoidal separation unit, always 'M' ???
# data[12] - Age of differential GPS data, can be null # data[12] - Age of differential GPS data, can be null
@ -533,10 +649,10 @@ class GPS:
return True return True
def _parse_gsa(self, talker, data): def _parse_gsa(self, talker: bytes, data: List[str]) -> bool:
# GSA - GPS DOP and active satellites # GSA - GPS DOP and active satellites
if data is None or len(data) not in (17, 18): if data is None or len(data) not in {17, 18}:
return False # Unexpected number of params. return False # Unexpected number of params.
if len(data) == 17: if len(data) == 17:
data = _parse_data(_GSA, data) data = _parse_data(_GSA, data)
@ -546,7 +662,7 @@ class GPS:
self.fix_quality_3d = 0 self.fix_quality_3d = 0
return False # Params didn't parse return False # Params didn't parse
talker = talker.decode("ascii") talker = str(talker, "ascii")
# Selection mode: 'M' - manual, 'A' - automatic # Selection mode: 'M' - manual, 'A' - automatic
self.sel_mode = data[0] self.sel_mode = data[0]
@ -557,7 +673,7 @@ class GPS:
satlist = list(filter(None, data[2:-4])) satlist = list(filter(None, data[2:-4]))
self.sat_prns = [] self.sat_prns = []
for sat in satlist: for sat in satlist:
self.sat_prns.append("{}{}".format(talker, sat)) self.sat_prns.append(f"{talker}{sat}")
# PDOP, dilution of precision # PDOP, dilution of precision
self.pdop = _parse_float(data[14]) self.pdop = _parse_float(data[14])
@ -572,11 +688,10 @@ class GPS:
return True return True
def _parse_gsv(self, talker, data): def _parse_gsv(self, talker: bytes, data: List[str]) -> bool:
# GSV - Satellites in view # GSV - Satellites in view
# pylint: disable=too-many-branches
if data is None or len(data) not in (7, 11, 15, 19): if data is None or len(data) not in {7, 11, 15, 19}:
return False # Unexpected number of params. return False # Unexpected number of params.
data = _parse_data( data = _parse_data(
{7: _GSV7, 11: _GSV11, 15: _GSV15, 19: _GSV19}[len(data)], {7: _GSV7, 11: _GSV11, 15: _GSV15, 19: _GSV19}[len(data)],
@ -585,7 +700,7 @@ class GPS:
if data is None: if data is None:
return False # Params didn't parse return False # Params didn't parse
talker = talker.decode("ascii") talker = str(talker, "ascii")
# Number of messages # Number of messages
self.total_mess_num = data[0] self.total_mess_num = data[0]
@ -602,7 +717,7 @@ class GPS:
j = i * 4 j = i * 4
value = ( value = (
# Satellite number # Satellite number
"{}{}".format(talker, sat_tup[0 + j]), f"{talker}{sat_tup[0 + j]}",
# Elevation in degrees # Elevation in degrees
sat_tup[1 + j], sat_tup[1 + j],
# Azimuth in degrees # Azimuth in degrees
@ -630,10 +745,9 @@ class GPS:
# been seen for 30 seconds # been seen for 30 seconds
timestamp = time.monotonic() timestamp = time.monotonic()
old = [] old = []
for i in self.sats: for sat_id, sat_data in self.sats.items():
sat = self.sats[i] if (timestamp - sat_data[4]) > 30:
if (timestamp - sat[4]) > 30: old.append(sat_id)
old.append(i)
for i in old: for i in old:
self.sats.pop(i) self.sats.pop(i)
for sat in self._sats: for sat in self._sats:
@ -651,11 +765,14 @@ class GPS_GtopI2C(GPS):
""" """
def __init__( def __init__(
self, i2c_bus, *, address=_GPSI2C_DEFAULT_ADDRESS, debug=False, timeout=5 self,
): i2c_bus: I2C,
from adafruit_bus_device import ( # pylint: disable=import-outside-toplevel *,
i2c_device, address: int = _GPSI2C_DEFAULT_ADDRESS,
) debug: bool = False,
timeout: float = 5.0,
) -> None:
from adafruit_bus_device import i2c_device # noqa: PLC0415
super().__init__(None, debug) # init the parent with no UART super().__init__(None, debug) # init the parent with no UART
self._i2c = i2c_device.I2CDevice(i2c_bus, address) self._i2c = i2c_device.I2CDevice(i2c_bus, address)
@ -664,7 +781,7 @@ class GPS_GtopI2C(GPS):
self._internalbuffer = [] self._internalbuffer = []
self._timeout = timeout self._timeout = timeout
def read(self, num_bytes=1): def read(self, num_bytes: int = 1) -> bytearray:
"""Read up to num_bytes of data from the GPS directly, without parsing. """Read up to num_bytes of data from the GPS directly, without parsing.
Returns a bytearray with up to num_bytes or None if nothing was read""" Returns a bytearray with up to num_bytes or None if nothing was read"""
result = [] result = []
@ -680,19 +797,19 @@ class GPS_GtopI2C(GPS):
self._lastbyte = char # keep track of the last character approved self._lastbyte = char # keep track of the last character approved
return bytearray(result) return bytearray(result)
def write(self, bytestr): def write(self, bytestr: ReadableBuffer) -> None:
"""Write a bytestring data to the GPS directly, without parsing """Write a bytestring data to the GPS directly, without parsing
or checksums""" or checksums"""
with self._i2c as i2c: with self._i2c as i2c:
i2c.write(bytestr) i2c.write(bytestr)
@property @property
def in_waiting(self): def in_waiting(self) -> Literal[16]:
"""Returns number of bytes available in UART read buffer, always 16 """Returns number of bytes available in UART read buffer, always 16
since I2C does not have the ability to know how much data is available""" since I2C does not have the ability to know how much data is available"""
return 16 return 16
def readline(self): def readline(self) -> Optional[bytearray]:
"""Returns a newline terminated bytearray, must have timeout set for """Returns a newline terminated bytearray, must have timeout set for
the underlying UART or this will block forever!""" the underlying UART or this will block forever!"""
timeout = time.monotonic() + self._timeout timeout = time.monotonic() + self._timeout

View file

@ -1,5 +1,11 @@
.. If you created a package, create one automodule per module in the package. .. If you created a package, create one automodule per module in the package.
.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py)
.. use this format as the module name: "adafruit_foo.foo"
API Reference
#############
.. automodule:: adafruit_gps .. automodule:: adafruit_gps
:members: :members:

View file

@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# #
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
import datetime
import os import os
import sys import sys
@ -16,13 +15,14 @@ sys.path.insert(0, os.path.abspath(".."))
# ones. # ones.
extensions = [ extensions = [
"sphinx.ext.autodoc", "sphinx.ext.autodoc",
"sphinxcontrib.jquery",
"sphinx.ext.intersphinx", "sphinx.ext.intersphinx",
"sphinx.ext.viewcode", "sphinx.ext.viewcode",
] ]
intersphinx_mapping = { intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None), "python": ("https://docs.python.org/3", None),
"CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None),
} }
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
@ -35,7 +35,12 @@ master_doc = "index"
# General information about the project. # General information about the project.
project = "Adafruit GPS Library" project = "Adafruit GPS Library"
copyright = "2017 Tony DiCola, 2021 James Carr" creation_year = "2017"
current_year = str(datetime.datetime.now().year)
year_duration = (
current_year if current_year == creation_year else creation_year + " - " + current_year
)
copyright = year_duration + " Tony DiCola, James Carr"
author = "Tony DiCola, James Carr" author = "Tony DiCola, James Carr"
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
@ -52,7 +57,7 @@ release = "1.0"
# #
# This is also used if you do content translation via gettext catalogs. # This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases. # Usually you set "language" from the command line for these cases.
language = None language = "en"
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
@ -83,19 +88,9 @@ todo_emit_warnings = True
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # a list of builtin themes.
# #
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally
try:
import sphinx_rtd_theme import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme" html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except:
html_theme = "default"
html_theme_path = ["."]
else:
html_theme_path = ["."]
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,

View file

@ -39,8 +39,9 @@ Table of Contents
.. toctree:: .. toctree::
:caption: Other Links :caption: Other Links
Download <https://github.com/adafruit/Adafruit_CircuitPython_GPS/releases/latest> Download from GitHub <https://github.com/adafruit/Adafruit_CircuitPython_GPS/releases/latest>
CircuitPython Reference Documentation <https://circuitpython.readthedocs.io> Download Library Bundle <https://circuitpython.org/libraries>
CircuitPython Reference Documentation <https://docs.circuitpython.org>
CircuitPython Support Forum <https://forums.adafruit.com/viewforum.php?f=60> CircuitPython Support Forum <https://forums.adafruit.com/viewforum.php?f=60>
Discord Chat <https://adafru.it/discord> Discord Chat <https://adafru.it/discord>
Adafruit Learning System <https://learn.adafruit.com> Adafruit Learning System <https://learn.adafruit.com>

View file

@ -2,4 +2,6 @@
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
sphinx>=4.0.0 sphinx
sphinxcontrib-jquery
sphinx-rtd-theme

View file

@ -10,8 +10,11 @@
# MUST carefully follow the steps in this guide to enable writes to the # MUST carefully follow the steps in this guide to enable writes to the
# internal filesystem: # internal filesystem:
# https://learn.adafruit.com/adafruit-ultimate-gps-featherwing/circuitpython-library # https://learn.adafruit.com/adafruit-ultimate-gps-featherwing/circuitpython-library
import sys
import board import board
import busio import busio
import adafruit_gps import adafruit_gps
# Path to the file to log GPS data. By default this will be appended to # Path to the file to log GPS data. By default this will be appended to
@ -25,22 +28,29 @@ LOG_FILE = "gps.txt" # Example for writing to internal path gps.txt
# like to erase the file and start clean each time use the value 'wb' instead. # like to erase the file and start clean each time use the value 'wb' instead.
LOG_MODE = "ab" LOG_MODE = "ab"
# If writing to SD card on a microcontroller customize and uncomment these # sdcardio and adafruit_sdcard are NOT supported on blinka. If you are using a
# lines to import the necessary library and initialize the SD card: # Raspberry Pi or other single-board linux computer, the code will save the
# NOT for use with a single board computer like Raspberry Pi! # output to the path defined in LOG_FILE above.
""" if sys.platform != "linux":
import adafruit_sdcard
import digitalio
import storage import storage
SD_CS_PIN = board.D10 # CS for SD card using Adalogger Featherwing SD_CS_PIN = board.D10 # CS for SD card using Adalogger Featherwing
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) try:
sd_cs = digitalio.DigitalInOut(SD_CS_PIN) import sdcardio
sdcard = adafruit_sdcard.SDCard(spi, sd_cs)
sdcard = sdcardio.SDCard(board.SPI, SD_CS_PIN)
except ImportError:
import adafruit_sdcard
import digitalio
sdcard = adafruit_sdcard.SDCard(
board.SPI(),
digitalio.DigitalInOut(SD_CS_PIN),
)
vfs = storage.VfsFat(sdcard) vfs = storage.VfsFat(sdcard)
storage.mount(vfs, '/sd') # Mount SD card under '/sd' path in filesystem. storage.mount(vfs, "/sd") # Mount SD card under '/sd' path in filesystem.
LOG_FILE = '/sd/gps.txt' # Example for writing to SD card path /sd/gps.txt LOG_FILE = "/sd/gps.txt" # Example for writing to SD card path /sd/gps.txt
"""
# Create a serial connection for the GPS connection using default speed and # Create a serial connection for the GPS connection using default speed and
# a slightly higher timeout (GPS modules typically update once a second). # a slightly higher timeout (GPS modules typically update once a second).
@ -54,7 +64,8 @@ uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)
# uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10)
# If using I2C, we'll create an I2C interface to talk to using default pins # If using I2C, we'll create an I2C interface to talk to using default pins
# i2c = board.I2C() # i2c = board.I2C() # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
# Create a GPS module instance. # Create a GPS module instance.
gps = adafruit_gps.GPS(uart) # Use UART/pyserial gps = adafruit_gps.GPS(uart) # Use UART/pyserial

View file

@ -0,0 +1,71 @@
# SPDX-FileCopyrightText: 2024
# SPDX-License-Identifier: MIT
import time
import board
from adafruit_display_text.label import Label
from displayio import Group
from terminalio import FONT
import adafruit_gps
# import busio
# uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)
i2c = board.I2C() # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector
# Create a GPS module instance.
# gps = adafruit_gps.GPS(uart, debug=False) # Use UART
gps = adafruit_gps.GPS_GtopI2C(i2c, debug=False) # Use I2C interface
# Turn on the basic GGA and RMC info (what you typically want)
gps.send_command(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0")
# Set update rate to once a second 1hz (what you typically want)
gps.send_command(b"PMTK220,1000")
# Example written for boards with built-in displays
display = board.DISPLAY
# Create a main_group to hold anything we want to show on the display.
main_group = Group()
# Create a Label to show the readings. If you have a very small
# display you may need to change to scale=1.
display_output_label = Label(FONT, text="", scale=2)
# Place the label near the top left corner with anchored positioning
display_output_label.anchor_point = (0, 0)
display_output_label.anchored_position = (4, 4)
# Add the label to the main_group
main_group.append(display_output_label)
# Set the main_group as the root_group of the display
display.root_group = main_group
last_print = time.monotonic()
# Begin main loop
while True:
gps.update()
current = time.monotonic()
# Update display data every second
if current - last_print >= 1.0:
last_print = current
if not gps.has_fix:
# Try again if we don't have a fix yet.
display_output_label.text = "Waiting for fix..."
continue
# We have a fix! (gps.has_fix is true)
t = gps.timestamp_utc
# Update the label.text property to change the text on the display
display_output_label.text = f"Timestamp (UTC): \
\n{t.tm_mday}/{t.tm_mon}/{t.tm_year} {t.tm_hour}:{t.tm_min:02}:{t.tm_sec:02}\
\nLat: {gps.latitude:.6f}\
\nLong: {gps.longitude:.6f}"

View file

@ -5,6 +5,7 @@
# Will print NMEA sentences received from the GPS, great for testing connection # Will print NMEA sentences received from the GPS, great for testing connection
# Uses the GPS to send some commands, then reads directly from the GPS # Uses the GPS to send some commands, then reads directly from the GPS
import time import time
import board import board
import busio import busio
@ -21,7 +22,8 @@ uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)
# uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10)
# If using I2C, we'll create an I2C interface to talk to using default pins # If using I2C, we'll create an I2C interface to talk to using default pins
# i2c = board.I2C() # i2c = board.I2C() # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
# Create a GPS module instance. # Create a GPS module instance.
gps = adafruit_gps.GPS(uart) # Use UART/pyserial gps = adafruit_gps.GPS(uart) # Use UART/pyserial

View file

@ -7,6 +7,7 @@
# * GSV - Satellites in view # * GSV - Satellites in view
import time import time
import board import board
import adafruit_gps import adafruit_gps
@ -15,6 +16,7 @@ import adafruit_gps
# a slightly higher timeout (GPS modules typically update once a second). # a slightly higher timeout (GPS modules typically update once a second).
# These are the defaults you should use for the GPS FeatherWing. # These are the defaults you should use for the GPS FeatherWing.
# For other boards set RX = GPS module TX, and TX = GPS module RX pins. # For other boards set RX = GPS module TX, and TX = GPS module RX pins.
# import busio
# uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10) # uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)
# for a computer, use the pyserial library for uart access # for a computer, use the pyserial library for uart access
@ -22,7 +24,8 @@ import adafruit_gps
# uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10)
# If using I2C, we'll create an I2C interface to talk to using default pins # If using I2C, we'll create an I2C interface to talk to using default pins
i2c = board.I2C() i2c = board.I2C() # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
# Create a GPS module instance. # Create a GPS module instance.
# gps = adafruit_gps.GPS(uart, debug=False) # Use UART/pyserial # gps = adafruit_gps.GPS(uart, debug=False) # Use UART/pyserial

View file

@ -5,6 +5,7 @@
# Will wait for a fix and print a message every second with the current location # Will wait for a fix and print a message every second with the current location
# and other details. # and other details.
import time import time
import board import board
import busio import busio
@ -14,14 +15,17 @@ import adafruit_gps
# a slightly higher timeout (GPS modules typically update once a second). # a slightly higher timeout (GPS modules typically update once a second).
# These are the defaults you should use for the GPS FeatherWing. # These are the defaults you should use for the GPS FeatherWing.
# For other boards set RX = GPS module TX, and TX = GPS module RX pins. # For other boards set RX = GPS module TX, and TX = GPS module RX pins.
uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10) rx = board.RX # Change to board.GP4 for Raspberry Pi Pico boards
tx = board.TX # Change to board.GP5 for Raspberry Pi Pico boards
uart = busio.UART(rx, tx, baudrate=9600, timeout=10)
# for a computer, use the pyserial library for uart access # for a computer, use the pyserial library for uart access
# import serial # import serial
# uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10) # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10)
# If using I2C, we'll create an I2C interface to talk to using default pins # If using I2C, we'll create an I2C interface to talk to using default pins
# i2c = board.I2C() # i2c = board.I2C() # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
# Create a GPS module instance. # Create a GPS module instance.
gps = adafruit_gps.GPS(uart, debug=False) # Use UART/pyserial gps = adafruit_gps.GPS(uart, debug=False) # Use UART/pyserial
@ -35,6 +39,8 @@ gps = adafruit_gps.GPS(uart, debug=False) # Use UART/pyserial
# Turn on the basic GGA and RMC info (what you typically want) # Turn on the basic GGA and RMC info (what you typically want)
gps.send_command(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") gps.send_command(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0")
# Turn on the basic GGA and RMC info + VTG for speed in km/h
# gps.send_command(b"PMTK314,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0")
# Turn on just minimum info (RMC only, location): # Turn on just minimum info (RMC only, location):
# gps.send_command(b'PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') # gps.send_command(b'PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0')
# Turn off everything: # Turn off everything:
@ -71,7 +77,7 @@ while True:
# Print out details about the fix like location, date, etc. # Print out details about the fix like location, date, etc.
print("=" * 40) # Print a separator line. print("=" * 40) # Print a separator line.
print( print(
"Fix timestamp: {}/{}/{} {:02}:{:02}:{:02}".format( "Fix timestamp: {}/{}/{} {:02}:{:02}:{:02}".format( # noqa: UP032
gps.timestamp_utc.tm_mon, # Grab parts of the time from the gps.timestamp_utc.tm_mon, # Grab parts of the time from the
gps.timestamp_utc.tm_mday, # struct_time object that holds gps.timestamp_utc.tm_mday, # struct_time object that holds
gps.timestamp_utc.tm_year, # the fix time. Note you might gps.timestamp_utc.tm_year, # the fix time. Note you might
@ -80,20 +86,24 @@ while True:
gps.timestamp_utc.tm_sec, gps.timestamp_utc.tm_sec,
) )
) )
print("Latitude: {0:.6f} degrees".format(gps.latitude)) print(f"Latitude: {gps.latitude:.6f} degrees")
print("Longitude: {0:.6f} degrees".format(gps.longitude)) print(f"Longitude: {gps.longitude:.6f} degrees")
print("Fix quality: {}".format(gps.fix_quality)) print(f"Precise Latitude: {gps.latitude_degrees} degs, {gps.latitude_minutes:2.4f} mins")
print(f"Precise Longitude: {gps.longitude_degrees} degs, {gps.longitude_minutes:2.4f} mins")
print(f"Fix quality: {gps.fix_quality}")
# Some attributes beyond latitude, longitude and timestamp are optional # Some attributes beyond latitude, longitude and timestamp are optional
# and might not be present. Check if they're None before trying to use! # and might not be present. Check if they're None before trying to use!
if gps.satellites is not None: if gps.satellites is not None:
print("# satellites: {}".format(gps.satellites)) print(f"# satellites: {gps.satellites}")
if gps.altitude_m is not None: if gps.altitude_m is not None:
print("Altitude: {} meters".format(gps.altitude_m)) print(f"Altitude: {gps.altitude_m} meters")
if gps.speed_knots is not None: if gps.speed_knots is not None:
print("Speed: {} knots".format(gps.speed_knots)) print(f"Speed: {gps.speed_knots} knots")
if gps.speed_kmh is not None:
print(f"Speed: {gps.speed_kmh} km/h")
if gps.track_angle_deg is not None: if gps.track_angle_deg is not None:
print("Track angle: {} degrees".format(gps.track_angle_deg)) print(f"Track angle: {gps.track_angle_deg} degrees")
if gps.horizontal_dilution is not None: if gps.horizontal_dilution is not None:
print("Horizontal dilution: {}".format(gps.horizontal_dilution)) print(f"Horizontal dilution: {gps.horizontal_dilution}")
if gps.height_geoid is not None: if gps.height_geoid is not None:
print("Height geoid: {} meters".format(gps.height_geoid)) print(f"Height geoid: {gps.height_geoid} meters")

View file

@ -6,9 +6,11 @@
# time while there is powersource (ie coin cell battery) # time while there is powersource (ie coin cell battery)
import time import time
import board import board
import busio import busio
import rtc import rtc
import adafruit_gps import adafruit_gps
uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10) uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=10)
@ -26,19 +28,13 @@ the_rtc = rtc.RTC()
def _format_datetime(datetime): def _format_datetime(datetime):
return "{:02}/{:02}/{} {:02}:{:02}:{:02}".format( date_part = f"{datetime.tm_mon:02}/{datetime.tm_mday:02}/{datetime.tm_year}"
datetime.tm_mon, time_part = f"{datetime.tm_hour:02}:{datetime.tm_min:02}:{datetime.tm_sec:02}"
datetime.tm_mday, return f"{date_part} {time_part}"
datetime.tm_year,
datetime.tm_hour,
datetime.tm_min,
datetime.tm_sec,
)
last_print = time.monotonic() last_print = time.monotonic()
while True: while True:
gps.update() gps.update()
# Every second print out current time from GPS, RTC and time.localtime() # Every second print out current time from GPS, RTC and time.localtime()
current = time.monotonic() current = time.monotonic()
@ -48,12 +44,12 @@ while True:
print("No time data from GPS yet") print("No time data from GPS yet")
continue continue
# Time & date from GPS informations # Time & date from GPS informations
print("Fix timestamp: {}".format(_format_datetime(gps.timestamp_utc))) print(f"Fix timestamp: {_format_datetime(gps.timestamp_utc)}")
# Time & date from internal RTC # Time & date from internal RTC
print("RTC timestamp: {}".format(_format_datetime(the_rtc.datetime))) print(f"RTC timestamp: {_format_datetime(the_rtc.datetime)}")
# Time & date from time.localtime() function # Time & date from time.localtime() function
local_time = time.localtime() local_time = time.localtime()
print("Local time: {}".format(_format_datetime(local_time))) print(f"Local time: {_format_datetime(local_time)}")

View file

@ -1,6 +1,9 @@
# SPDX-FileCopyrightText: 2021 Jonas Kittner # SPDX-FileCopyrightText: 2021 Jonas Kittner
# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
adafruit-circuitpython-sd
covdefaults covdefaults
coverage coverage
freezegun freezegun

48
pyproject.toml Normal file
View file

@ -0,0 +1,48 @@
# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries
#
# SPDX-License-Identifier: MIT
[build-system]
requires = [
"setuptools",
"wheel",
"setuptools-scm",
]
[project]
name = "adafruit-circuitpython-gps"
description = "CircuitPython library for GPS modules."
version = "0.0.0+auto.0"
readme = "README.rst"
authors = [
{name = "Adafruit Industries", email = "circuitpython@adafruit.com"}
]
urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_GPS"}
keywords = [
"adafruit",
"gps",
"module",
"latitude",
"longitude",
"breakout",
"hardware",
"micropython",
"circuitpython",
]
license = {text = "MIT"}
classifiers = [
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Embedded Systems",
"Topic :: System :: Hardware",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
]
dynamic = ["dependencies", "optional-dependencies"]
[tool.setuptools]
py-modules = ["adafruit_gps"]
[tool.setuptools.dynamic]
dependencies = {file = ["requirements.txt"]}
optional-dependencies = {optional = {file = ["optional_requirements.txt"]}}

View file

@ -1,7 +1,9 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries
# #
# SPDX-License-Identifier: Unlicense # SPDX-License-Identifier: Unlicense
Adafruit-Blinka Adafruit-Blinka
pyserial
adafruit-circuitpython-busdevice adafruit-circuitpython-busdevice
pyserial
adafruit-circuitpython-typing
typing-extensions~=4.0

108
ruff.toml Normal file
View file

@ -0,0 +1,108 @@
# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
target-version = "py38"
line-length = 100
[lint]
preview = true
select = ["I", "PL", "UP"]
extend-select = [
"D419", # empty-docstring
"E501", # line-too-long
"W291", # trailing-whitespace
"PLC0414", # useless-import-alias
"PLC2401", # non-ascii-name
"PLC2801", # unnecessary-dunder-call
"PLC3002", # unnecessary-direct-lambda-call
"E999", # syntax-error
"PLE0101", # return-in-init
"F706", # return-outside-function
"F704", # yield-outside-function
"PLE0116", # continue-in-finally
"PLE0117", # nonlocal-without-binding
"PLE0241", # duplicate-bases
"PLE0302", # unexpected-special-method-signature
"PLE0604", # invalid-all-object
"PLE0605", # invalid-all-format
"PLE0643", # potential-index-error
"PLE0704", # misplaced-bare-raise
"PLE1141", # dict-iter-missing-items
"PLE1142", # await-outside-async
"PLE1205", # logging-too-many-args
"PLE1206", # logging-too-few-args
"PLE1307", # bad-string-format-type
"PLE1310", # bad-str-strip-call
"PLE1507", # invalid-envvar-value
"PLE2502", # bidirectional-unicode
"PLE2510", # invalid-character-backspace
"PLE2512", # invalid-character-sub
"PLE2513", # invalid-character-esc
"PLE2514", # invalid-character-nul
"PLE2515", # invalid-character-zero-width-space
"PLR0124", # comparison-with-itself
"PLR0202", # no-classmethod-decorator
"PLR0203", # no-staticmethod-decorator
"UP004", # useless-object-inheritance
"PLR0206", # property-with-parameters
"PLR0904", # too-many-public-methods
"PLR0911", # too-many-return-statements
"PLR0912", # too-many-branches
"PLR0913", # too-many-arguments
"PLR0914", # too-many-locals
"PLR0915", # too-many-statements
"PLR0916", # too-many-boolean-expressions
"PLR1702", # too-many-nested-blocks
"PLR1704", # redefined-argument-from-local
"PLR1711", # useless-return
"C416", # unnecessary-comprehension
"PLR1733", # unnecessary-dict-index-lookup
"PLR1736", # unnecessary-list-index-lookup
# ruff reports this rule is unstable
#"PLR6301", # no-self-use
"PLW0108", # unnecessary-lambda
"PLW0120", # useless-else-on-loop
"PLW0127", # self-assigning-variable
"PLW0129", # assert-on-string-literal
"B033", # duplicate-value
"PLW0131", # named-expr-without-context
"PLW0245", # super-without-brackets
"PLW0406", # import-self
"PLW0602", # global-variable-not-assigned
"PLW0603", # global-statement
"PLW0604", # global-at-module-level
# fails on the try: import typing used by libraries
#"F401", # unused-import
"F841", # unused-variable
"E722", # bare-except
"PLW0711", # binary-op-exception
"PLW1501", # bad-open-mode
"PLW1508", # invalid-envvar-default
"PLW1509", # subprocess-popen-preexec-fn
"PLW2101", # useless-with-lock
"PLW3301", # nested-min-max
]
ignore = [
"PLR2004", # magic-value-comparison
"UP030", # format literals
"PLW1514", # unspecified-encoding
"PLR0913", # too-many-arguments
"PLR0915", # too-many-statements
"PLR0917", # too-many-positional-arguments
"PLR0904", # too-many-public-methods
"PLR0912", # too-many-branches
"PLR0916", # too-many-boolean-expressions
]
[lint.per-file-ignores]
"tests/adafruit_gps_test.py" = ["PLC2701"]
[format]
line-ending = "lf"

View file

@ -1,60 +0,0 @@
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="adafruit-circuitpython-gps",
use_scm_version=True,
setup_requires=["setuptools_scm"],
description="CircuitPython library for GPS modules.",
long_description=long_description,
long_description_content_type="text/x-rst",
# The project's main homepage.
url="https://github.com/adafruit/Adafruit_CircuitPython_GPS",
# Author details
author="Adafruit Industries",
author_email="circuitpython@adafruit.com",
install_requires=[
"pyserial",
"Adafruit-Blinka",
"adafruit-circuitpython-busdevice",
],
# Choose your license
license="MIT",
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"Topic :: System :: Hardware",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
# What does your project relate to?
keywords="adafruit gps module latitude longitude breakout hardware micropython circuitpython",
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
py_modules=["adafruit_gps"],
)

View file

@ -1,29 +1,31 @@
# pylint: disable=missing-function-docstring,missing-module-docstring,invalid-name,protected-access,no-self-use,missing-class-docstring
# SPDX-FileCopyrightText: 2021 Jonas Kittner # SPDX-FileCopyrightText: 2021 Jonas Kittner
# #
# SPDX-License-Identifier: MIT # SPDX-License-Identifier: MIT
import time import time
from unittest import mock from unittest import mock
from freezegun import freeze_time
import pytest
from adafruit_gps import _parse_degrees import pytest
from adafruit_gps import _parse_int from freezegun import freeze_time
from adafruit_gps import _parse_float
from adafruit_gps import _parse_str from adafruit_gps import (
from adafruit_gps import _read_degrees GPS,
from adafruit_gps import _parse_talker _parse_data,
from adafruit_gps import _parse_data _parse_degrees,
from adafruit_gps import GPS _parse_float,
_parse_int,
_parse_str,
_parse_talker,
_read_deg_mins,
_read_degrees,
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
("val", "exp"), ("val", "exp"),
( (
pytest.param("0023.456", 0.390933, id="leading zero"), pytest.param("0023.456", 390933, id="leading zero"),
pytest.param("6413.9369", 64.23228, id="regular value"), pytest.param("6413.9369", 64232281, id="regular value"),
pytest.param("2747.416122087989", 27.79027, id="long value"), pytest.param("2747.416122087989", 27790268, id="long value"),
), ),
) )
def test_parse_degrees(val, exp): def test_parse_degrees(val, exp):
@ -61,10 +63,10 @@ def test_parse_float_invalid(val):
@pytest.mark.parametrize( @pytest.mark.parametrize(
("data", "neg", "exp"), ("data", "neg", "exp"),
( (
pytest.param([27.79027, "S"], "s", -27.79027, id="south negative"), pytest.param([27790270, "S"], "s", -27.79027, id="south negative"),
pytest.param([64.23228, "N"], "s", 64.23228, id="north not negative"), pytest.param([64232280, "N"], "s", 64.23228, id="north not negative"),
pytest.param([123.4567, "W"], "w", -123.4567, id="west negative"), pytest.param([123456700, "W"], "w", -123.4567, id="west negative"),
pytest.param([10.7891, "E"], "w", 10.7891, id="east not negative"), pytest.param([10789100, "E"], "w", 10.7891, id="east not negative"),
), ),
) )
def test_read_degrees(data, neg, exp): def test_read_degrees(data, neg, exp):
@ -114,7 +116,7 @@ def test_parse_data_unexpected_parameter_type():
class UartMock: class UartMock:
"""mocking the UART connection an its methods""" """mocking the UART connection an its methods"""
def write(self, bytestr): def write(self, bytestr): # noqa: PLR6301
print(bytestr, end="") print(bytestr, end="")
@property @property
@ -140,14 +142,14 @@ def test_GPS_update_timestamp_UTC_date_None():
assert gps.datetime is None assert gps.datetime is None
assert gps.timestamp_utc is None assert gps.timestamp_utc is None
exp_struct = time.struct_time((0, 0, 0, 22, 14, 11, 0, 0, -1)) exp_struct = time.struct_time((0, 0, 0, 22, 14, 11, 0, 0, -1))
gps._update_timestamp_utc(time_utc=221411) gps._update_timestamp_utc(time_utc="221411")
assert gps.timestamp_utc == exp_struct assert gps.timestamp_utc == exp_struct
def test_GPS_update_timestamp_UTC_date_not_None(): def test_GPS_update_timestamp_UTC_date_not_None():
gps = GPS(uart=UartMock()) gps = GPS(uart=UartMock())
exp_struct = time.struct_time((2021, 10, 2, 22, 14, 11, 0, 0, -1)) exp_struct = time.struct_time((2021, 10, 2, 22, 14, 11, 0, 0, -1))
gps._update_timestamp_utc(time_utc=221411, date=21021) gps._update_timestamp_utc(time_utc="221411", date="021021")
assert gps.timestamp_utc == exp_struct assert gps.timestamp_utc == exp_struct
@ -157,7 +159,7 @@ def test_GPS_update_timestamp_timestamp_utc_was_not_none_new_date_none():
gps.timestamp_utc = time.struct_time((2021, 10, 2, 22, 10, 11, 0, 0, -1)) gps.timestamp_utc = time.struct_time((2021, 10, 2, 22, 10, 11, 0, 0, -1))
exp_struct = time.struct_time((2021, 10, 2, 22, 14, 11, 0, 0, -1)) exp_struct = time.struct_time((2021, 10, 2, 22, 14, 11, 0, 0, -1))
# update the timestamp # update the timestamp
gps._update_timestamp_utc(time_utc=221411) gps._update_timestamp_utc(time_utc="221411")
assert gps.timestamp_utc == exp_struct assert gps.timestamp_utc == exp_struct
@ -177,6 +179,10 @@ def test_GPS_update_rmc_no_magnetic_variation():
assert gps.timestamp_utc == exp_time assert gps.timestamp_utc == exp_time
assert gps.latitude == pytest.approx(12.57613) assert gps.latitude == pytest.approx(12.57613)
assert gps.longitude == pytest.approx(1.385391) assert gps.longitude == pytest.approx(1.385391)
assert gps.latitude_degrees == 12
assert gps.longitude_degrees == 1
assert gps.latitude_minutes == 34.5678
assert gps.longitude_minutes == 23.12345
assert gps.fix_quality == 1 assert gps.fix_quality == 1
assert gps.fix_quality_3d == 0 assert gps.fix_quality_3d == 0
assert gps.speed_knots == 0.45 assert gps.speed_knots == 0.45
@ -197,12 +203,8 @@ def test_GPS_update_rmc_no_magnetic_variation():
def test_GPS_update_rmc_fix_is_set(): def test_GPS_update_rmc_fix_is_set():
r_valid = ( r_valid = b"$GPRMC,215032.086,A,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A*6A\r\n"
b"$GPRMC,215032.086,A,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A*6A\r\n" r_invalid = b"$GPRMC,215032.086,V,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A*7D\r\n"
)
r_invalid = (
b"$GPRMC,215032.086,V,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A*7D\r\n"
)
with mock.patch.object(GPS, "readline", return_value=r_valid): with mock.patch.object(GPS, "readline", return_value=r_valid):
gps = GPS(uart=UartMock()) gps = GPS(uart=UartMock())
assert gps.update() assert gps.update()
@ -216,9 +218,7 @@ def test_GPS_update_rmc_fix_is_set():
def test_GPS_update_rmc_fix_is_set_new(): def test_GPS_update_rmc_fix_is_set_new():
r_valid = ( r_valid = b"$GPRMC,215032.086,A,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A*6A\r\n"
b"$GPRMC,215032.086,A,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A*6A\r\n"
)
r_invalid = b"$GPRMC,215032.086,V,ABC,N,00123.12345,E,0.45,56.35,021021,,,A*1B\r\n" r_invalid = b"$GPRMC,215032.086,V,ABC,N,00123.12345,E,0.45,56.35,021021,,,A*1B\r\n"
with mock.patch.object(GPS, "readline", return_value=r_valid): with mock.patch.object(GPS, "readline", return_value=r_valid):
gps = GPS(uart=UartMock()) gps = GPS(uart=UartMock())
@ -285,11 +285,8 @@ def test_GPS_update_rmc_debug_shows_sentence(capsys):
gps = GPS(uart=UartMock(), debug=True) gps = GPS(uart=UartMock(), debug=True)
assert gps.update() assert gps.update()
out, err = capsys.readouterr() out, err = capsys.readouterr()
assert err == "" assert not err
assert ( assert out == "('GPRMC', '215032.086,A,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A')\n"
out
== "('GPRMC', '215032.086,A,1234.5678,N,00123.12345,E,0.45,56.35,021021,,,A')\n"
)
def test_GPS_update_data_type_too_short(): def test_GPS_update_data_type_too_short():
@ -303,7 +300,7 @@ def test_GPS_send_command_with_checksum(capsys):
gps = GPS(uart=UartMock()) gps = GPS(uart=UartMock())
gps.send_command(command=b"$PMTK001,314,3\r\n", add_checksum=True) gps.send_command(command=b"$PMTK001,314,3\r\n", add_checksum=True)
out, err = capsys.readouterr() out, err = capsys.readouterr()
assert err == "" assert not err
assert out == ("b'$'" "b'$PMTK001,314,3\\r\\n'" "b'*'" "b'15'" "b'\\r\\n'") assert out == ("b'$'" "b'$PMTK001,314,3\\r\\n'" "b'*'" "b'15'" "b'\\r\\n'")
@ -311,7 +308,7 @@ def test_GPS_send_command_without_checksum(capsys):
gps = GPS(uart=UartMock()) gps = GPS(uart=UartMock())
gps.send_command(command=b"$PMTK001,314,3\r\n", add_checksum=False) gps.send_command(command=b"$PMTK001,314,3\r\n", add_checksum=False)
out, err = capsys.readouterr() out, err = capsys.readouterr()
assert err == "" assert not err
assert out == ("b'$'" "b'$PMTK001,314,3\\r\\n'" "b'\\r\\n'") assert out == ("b'$'" "b'$PMTK001,314,3\\r\\n'" "b'\\r\\n'")
@ -324,6 +321,10 @@ def test_GPS_update_from_GLL():
assert gps.timestamp_utc == exp_time assert gps.timestamp_utc == exp_time
assert gps.latitude == pytest.approx(49.27417) assert gps.latitude == pytest.approx(49.27417)
assert gps.longitude == pytest.approx(-123.1853) assert gps.longitude == pytest.approx(-123.1853)
assert gps.latitude_degrees == 49
assert gps.longitude_degrees == -123
assert gps.latitude_minutes == 16.45
assert gps.longitude_minutes == 11.12
assert gps.isactivedata == "A" assert gps.isactivedata == "A"
assert gps._mode_indicator == "A" assert gps._mode_indicator == "A"
assert gps.fix_quality == 0 assert gps.fix_quality == 0
@ -335,7 +336,7 @@ def test_GPS_update_from_GLL():
def test_GPS_update_from_RMC(): def test_GPS_update_from_RMC():
r = b"$GNRMC,001031.00,A,4404.13993,N,12118.86023,W,0.146,084.4,100117,,,A*5d\r\n" r = b"$GNRMC,001031.00,A,4404.1399,N,12118.8602,W,0.146,084.4,100117,,,A*5d\r\n"
# TODO: length 13 and 14 version # TODO: length 13 and 14 version
with mock.patch.object(GPS, "readline", return_value=r): with mock.patch.object(GPS, "readline", return_value=r):
gps = GPS(uart=UartMock()) gps = GPS(uart=UartMock())
@ -349,6 +350,10 @@ def test_GPS_update_from_RMC():
assert gps.has_3d_fix is False assert gps.has_3d_fix is False
assert gps.latitude == pytest.approx(44.069) assert gps.latitude == pytest.approx(44.069)
assert gps.longitude == pytest.approx(-121.3143) assert gps.longitude == pytest.approx(-121.3143)
assert gps.latitude_degrees == 44
assert gps.longitude_degrees == -121
assert gps.latitude_minutes == 4.1399
assert gps.longitude_minutes == 18.8602
assert gps.speed_knots == 0.146 assert gps.speed_knots == 0.146
assert gps.track_angle_deg == 84.4 assert gps.track_angle_deg == 84.4
assert gps._magnetic_variation is None assert gps._magnetic_variation is None
@ -364,6 +369,10 @@ def test_GPS_update_from_GGA():
assert gps.timestamp_utc == exp_time assert gps.timestamp_utc == exp_time
assert gps.latitude == pytest.approx(48.1173) assert gps.latitude == pytest.approx(48.1173)
assert gps.longitude == pytest.approx(11.51667) assert gps.longitude == pytest.approx(11.51667)
assert gps.latitude_degrees == 48
assert gps.longitude_degrees == 11
assert gps.latitude_minutes == 7.038
assert gps.longitude_minutes == 31.000
assert gps.fix_quality == 1 assert gps.fix_quality == 1
assert gps.fix_quality_3d == 0 assert gps.fix_quality_3d == 0
assert gps.satellites == 8 assert gps.satellites == 8
@ -374,21 +383,17 @@ def test_GPS_update_from_GGA():
assert gps.has_3d_fix is False assert gps.has_3d_fix is False
assert gps.datetime == exp_time assert gps.datetime == exp_time
assert ( assert (
gps._raw_sentence gps._raw_sentence == "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"
== "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"
) )
assert ( assert (
gps.nmea_sentence gps.nmea_sentence == "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"
== "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"
) )
@pytest.mark.parametrize( @pytest.mark.parametrize(
"r", "r",
( (
pytest.param( pytest.param(b"$GPGSA,A,3,15,18,14,,,31,,,23,,,,04.5,02.1,04.0*0f\r\n", id="smaller v4.1"),
b"$GPGSA,A,3,15,18,14,,,31,,,23,,,,04.5,02.1,04.0*0f\r\n", id="smaller v4.1"
),
pytest.param( pytest.param(
b"$GPGSA,A,3,15,18,14,,,31,,,23,,,,04.5,02.1,04.0,3*10\r\n", b"$GPGSA,A,3,15,18,14,,,31,,,23,,,,04.5,02.1,04.0,3*10\r\n",
id="greater v4.1", id="greater v4.1",
@ -467,3 +472,19 @@ def test_GPS_update_from_GSV_both_parts_sats_are_removed():
assert gps.update() assert gps.update()
assert gps.satellites == 2 assert gps.satellites == 2
assert set(gps.sats.keys()) == {"GP12", "GP14", "GP13", "GP15"} assert set(gps.sats.keys()) == {"GP12", "GP14", "GP13", "GP15"}
@pytest.mark.parametrize(
("input_str", "exp", "neg"),
(
(["3723.2475", "n"], (37, 23.2475), "s"),
(["3723.2475", "s"], (-37, 23.2475), "s"),
(["00123.1234", "e"], (1, 23.1234), "w"),
(["00123", "e"], (1, 23), "w"),
(["1234.5678", "e"], (12, 34.5678), "w"),
(["3723.2475123", "n"], (37, 23.2475123), "s"),
(["3723", "n"], (37, 23), "s"),
),
)
def test_read_min_secs(input_str, exp, neg):
assert _read_deg_mins(data=input_str, index=0, neg=neg) == exp

13
tox.ini
View file

@ -1,13 +0,0 @@
# SPDX-FileCopyrightText: 2021 Jonas Kittner
#
# SPDX-License-Identifier: Unlicense
[tox]
envlist = py37
[testenv]
deps = -rrequirements-dev.txt
commands =
coverage erase
coverage run -m pytest tests/
coverage report