Compare commits

..

No commits in common. "main" and "improve-actions" have entirely different histories.

30 changed files with 733 additions and 395 deletions

15
.coveragerc Normal file
View file

@ -0,0 +1,15 @@
# SPDX-FileCopyrightText: 2021-2024 Jeff Epler
#
# SPDX-License-Identifier: GPL-3.0-only
[report]
exclude_also =
def __repr__
if self.debug:
if settings.DEBUG
raise AssertionError
raise NotImplementedError
if 0:
if __name__ == .__main__.:
if TYPE_CHECKING:
class .*\bProtocol\):
@(abc\.)?abstractmethod

49
.github/workflows/codeql.yml vendored Normal file
View file

@ -0,0 +1,49 @@
# SPDX-FileCopyrightText: 2022-2024 Jeff Epler
#
# SPDX-License-Identifier: CC0-1.0
name: "CodeQL"
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: "53 3 * * 5"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ python ]
steps:
- name: Checkout
uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install Dependencies (python)
run: pip3 install -r requirements-dev.txt
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: +security-and-quality
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"

View file

@ -11,7 +11,7 @@ on:
jobs:
update-dut1:
runs-on: ubuntu-24.04
runs-on: ubuntu-20.04
if: startswith(github.repository, 'jepler/')
steps:

View file

@ -11,7 +11,7 @@ on:
jobs:
release:
runs-on: ubuntu-24.04
runs-on: ubuntu-20.04
steps:
- name: Dump GitHub context
env:

View file

@ -31,42 +31,6 @@ jobs:
- name: Build HTML docs
run: make html
typing:
strategy:
fail-fast: false
matrix:
python-version:
- '3.13'
os-version:
- 'ubuntu-latest'
runs-on: ${{ matrix.os-version }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install deps
run: |
python -mpip install wheel
python -mpip install -r requirements-dev.txt
- name: Check stubs with mypy
if: (! startsWith(matrix.python-version, 'pypy-'))
run: make mypy PYTHON=python
- name: Check stubs with pyrefly
if: (! startsWith(matrix.python-version, 'pypy-'))
run: make pyrefly PYTHON=python
- name: Check stubs with pyright
if: (! startsWith(matrix.python-version, 'pypy-'))
run: make pyright PYTHON=python
test:
strategy:
fail-fast: false
@ -76,8 +40,7 @@ jobs:
- '3.10'
- '3.11'
- '3.12'
- '3.13'
- '3.14.0-alpha.0 - 3.14'
- '3.13.0-alpha.0 - 3.13'
os-version:
- 'ubuntu-latest'
include:
@ -104,6 +67,10 @@ jobs:
python -mpip install wheel
python -mpip install -r requirements-dev.txt
- name: Check stubs
if: (! startsWith(matrix.python-version, 'pypy-'))
run: make mypy PYTHON=python
- name: Coverage
run: make coverage PYTHON=python

View file

@ -8,7 +8,7 @@ default_language_version:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
rev: v5.0.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
@ -16,21 +16,15 @@ repos:
- id: trailing-whitespace
exclude: test/wwvbgen_testcases
- repo: https://github.com/fsfe/reuse-tool
rev: v5.0.2
rev: v4.0.3
hooks:
- id: reuse
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.12.10
rev: v0.7.1
hooks:
# Run the linter.
- id: ruff-check
- id: ruff
args: [ --fix ]
# Run the formatter.
- id: ruff-format
- repo: https://github.com/asottile/pyupgrade
rev: v3.20.0
hooks:
- id: pyupgrade
args: [ --py39-plus ]
exclude: src/uwwvb.py # CircuitPython prevaling standard!

View file

@ -1,17 +0,0 @@
# SPDX-FileCopyrightText: 2024 Jeff Epler
#
# SPDX-License-Identifier: GPL-3.0-only
version: 2
build:
os: ubuntu-lts-latest
tools:
python: "3"
sphinx:
configuration: doc/conf.py
python:
install:
- requirements: requirements-dev.txt

73
LICENSES/Apache-2.0.txt Normal file
View file

@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -24,13 +24,13 @@ ENVPYTHON ?= _env/bin/python3
endif
.PHONY: default
default: coverage mypy pyright pyrefly
default: coverage mypy
COVERAGE_INCLUDE=--include "src/**/*.py"
.PHONY: coverage
coverage:
$(Q)$(PYTHON) -mcoverage erase
$(Q)env PYTHONPATH=src $(PYTHON) -mcoverage run -p -m unittest discover -s test
$(Q)env PYTHONPATH=src $(PYTHON) -mcoverage run --branch -p -m unittest discover -s test
$(Q)$(PYTHON) -mcoverage combine -q
$(Q)$(PYTHON) -mcoverage html $(COVERAGE_INCLUDE)
$(Q)$(PYTHON) -mcoverage xml $(COVERAGE_INCLUDE)
@ -44,16 +44,7 @@ test_venv:
.PHONY: mypy
mypy:
$(Q)mypy --strict --no-warn-unused-ignores src test
.PHONY: pyright
pyright:
$(Q)pyright src test
.PHONY: pyrefly
pyrefly:
$(Q)pyrefly check src test
$(Q)mypy --strict --no-warn-unused-ignores src
.PHONY: update
update:

View file

@ -4,13 +4,16 @@ SPDX-FileCopyrightText: 2021-2024 Jeff Epler
SPDX-License-Identifier: GPL-3.0-only
-->
[![Test wwvbgen](https://github.com/jepler/wwvbpy/actions/workflows/test.yml/badge.svg)](https://github.com/jepler/wwvbpy/actions/workflows/test.yml)
[![codecov](https://codecov.io/gh/jepler/wwvbpy/branch/main/graph/badge.svg?token=Exx0c3Gp65)](https://codecov.io/gh/jepler/wwvbpy)
[![Update DUT1 data](https://github.com/jepler/wwvbpy/actions/workflows/cron.yml/badge.svg)](https://github.com/jepler/wwvbpy/actions/workflows/cron.yml)
[![PyPI](https://img.shields.io/pypi/v/wwvb)](https://pypi.org/project/wwvb)
[![CodeQL](https://github.com/jepler/wwvbpy/actions/workflows/codeql.yml/badge.svg)](https://github.com/jepler/wwvbpy/actions/workflows/codeql.yml)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/jepler/wwvbpy/main.svg)](https://results.pre-commit.ci/latest/github/jepler/wwvbpy/main)
# Purpose
Python package and command line programs for interacting with WWVB timecodes.
wwvbpy generates WWVB timecodes for any desired time. These timecodes
may be useful in testing WWVB decoder software.
Where possible, wwvbpy uses existing facilities for calendar and time
manipulation (datetime and dateutil).
@ -36,7 +39,7 @@ The package includes:
# Development status
The author ([@jepler](https://github.com/jepler)) occasionally develops and maintains this project, but
The author (@jepler) occasionally develops and maintains this project, but
issues are not likely to be acted on. They would be interested in adding
co-maintainer(s).
@ -64,7 +67,7 @@ channel.
# Usage
~~~~
Usage: wwvbgen [OPTIONS] [TIMESPEC]...
Usage: python -m wwvb.gen [OPTIONS] [TIMESPEC]...
Generate WWVB timecodes
@ -94,7 +97,7 @@ Options:
For example, to display the leap second that occurred at the end of 1998,
~~~~
$ wwvbgen -m 7 1998 365 23 56
$ python wwvbgen.py -m 7 1998 365 23 56
WWVB timecode: year=98 days=365 hour=23 min=56 dst=0 ut1=-300 ly=0 ls=1
'98+365 23:56 210100110200100001120011001102010100010200110100121000001002
'98+365 23:57 210100111200100001120011001102010100010200110100121000001002
@ -116,7 +119,7 @@ The letters `a` through `u` represent offsets of -1.0s through +1.0s
in 0.1s increments; `k` represents 0s. (In practice, only a smaller range
of values, typically -0.7s to +0.8s, is seen)
For 2001 through 2024, NIST has published the actual DUT1 values broadcast,
For 2001 through 2019, NIST has published the actual DUT1 values broadcast,
and the date of each change, though it in the format of an HTML
table and not designed for machine readability:

416
adafruit_datetime.pyi Normal file
View file

@ -0,0 +1,416 @@
# SPDX-FileCopyrightText: 2015-2021 Jukka Lehtosalo and contributors
# SPDX-FileCopyrightText: 2021-2024 Jeff Epler
#
# SPDX-License-Identifier: Apache-2.0
# ruff: noqa
import sys
from time import struct_time
from typing import (
AnyStr,
ClassVar,
NamedTuple,
Optional,
SupportsAbs,
Tuple,
Type,
TypeVar,
overload,
)
_S = TypeVar("_S")
MINYEAR: int
MAXYEAR: int
class tzinfo:
def tzname(self, dt: Optional[datetime]) -> Optional[str]: ...
def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ...
def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ...
def fromutc(self, dt: datetime) -> datetime: ...
class timezone(tzinfo):
utc: ClassVar[timezone]
min: ClassVar[timezone]
max: ClassVar[timezone]
def __init__(self, offset: timedelta, name: str = ...) -> None: ...
def __hash__(self) -> int: ...
class _IsoCalendarDate(NamedTuple):
year: int
week: int
weekday: int
_tzinfo = tzinfo
class date:
min: ClassVar[date]
max: ClassVar[date]
resolution: ClassVar[timedelta]
def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ...
@classmethod
def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ...
@classmethod
def today(cls: Type[_S]) -> _S: ...
@classmethod
def fromordinal(cls: Type[_S], n: int) -> _S: ...
if sys.version_info >= (3, 7):
@classmethod
def fromisoformat(cls: Type[_S], date_string: str) -> _S: ...
if sys.version_info >= (3, 8):
@classmethod
def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ...
@property
def year(self) -> int: ...
@property
def month(self) -> int: ...
@property
def day(self) -> int: ...
def ctime(self) -> str: ...
def strftime(self, fmt: str) -> str: ...
if sys.version_info >= (3,):
def __format__(self, fmt: str) -> str: ...
else:
def __format__(self, fmt: AnyStr) -> AnyStr: ...
def isoformat(self) -> str: ...
def timetuple(self) -> struct_time: ...
def toordinal(self) -> int: ...
def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ...
def __le__(self, other: date) -> bool: ...
def __lt__(self, other: date) -> bool: ...
def __ge__(self, other: date) -> bool: ...
def __gt__(self, other: date) -> bool: ...
if sys.version_info >= (3, 8):
def __add__(self: _S, other: timedelta) -> _S: ...
def __radd__(self: _S, other: timedelta) -> _S: ...
else:
def __add__(self, other: timedelta) -> date: ...
def __radd__(self, other: timedelta) -> date: ...
@overload
def __sub__(self, other: timedelta) -> date: ...
@overload
def __sub__(self, other: date) -> timedelta: ...
def __hash__(self) -> int: ...
def weekday(self) -> int: ...
def isoweekday(self) -> int: ...
def isocalendar(self) -> _IsoCalendarDate: ...
class time:
min: ClassVar[time]
max: ClassVar[time]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __init__(
self,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> None: ...
else:
def __init__(
self,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> None: ...
@property
def hour(self) -> int: ...
@property
def minute(self) -> int: ...
@property
def second(self) -> int: ...
@property
def microsecond(self) -> int: ...
@property
def tzinfo(self) -> Optional[_tzinfo]: ...
if sys.version_info >= (3, 6):
@property
def fold(self) -> int: ...
def __le__(self, other: time) -> bool: ...
def __lt__(self, other: time) -> bool: ...
def __ge__(self, other: time) -> bool: ...
def __gt__(self, other: time) -> bool: ...
def __hash__(self) -> int: ...
if sys.version_info >= (3, 6):
def isoformat(self, timespec: str = ...) -> str: ...
else:
def isoformat(self) -> str: ...
if sys.version_info >= (3, 7):
@classmethod
def fromisoformat(cls: Type[_S], time_string: str) -> _S: ...
def strftime(self, fmt: str) -> str: ...
if sys.version_info >= (3,):
def __format__(self, fmt: str) -> str: ...
else:
def __format__(self, fmt: AnyStr) -> AnyStr: ...
def utcoffset(self) -> Optional[timedelta]: ...
def tzname(self) -> Optional[str]: ...
def dst(self) -> Optional[timedelta]: ...
if sys.version_info >= (3, 6):
def replace(
self,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> time: ...
else:
def replace(
self,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> time: ...
_date = date
_time = time
class timedelta(SupportsAbs["timedelta"]):
min: ClassVar[timedelta]
max: ClassVar[timedelta]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __init__(
self,
days: float = ...,
seconds: float = ...,
microseconds: float = ...,
milliseconds: float = ...,
minutes: float = ...,
hours: float = ...,
weeks: float = ...,
*,
fold: int = ...,
) -> None: ...
else:
def __init__(
self,
days: float = ...,
seconds: float = ...,
microseconds: float = ...,
milliseconds: float = ...,
minutes: float = ...,
hours: float = ...,
weeks: float = ...,
) -> None: ...
@property
def days(self) -> int: ...
@property
def seconds(self) -> int: ...
@property
def microseconds(self) -> int: ...
def total_seconds(self) -> float: ...
def __add__(self, other: timedelta) -> timedelta: ...
def __radd__(self, other: timedelta) -> timedelta: ...
def __sub__(self, other: timedelta) -> timedelta: ...
def __rsub__(self, other: timedelta) -> timedelta: ...
def __neg__(self) -> timedelta: ...
def __pos__(self) -> timedelta: ...
def __abs__(self) -> timedelta: ...
def __mul__(self, other: float) -> timedelta: ...
def __rmul__(self, other: float) -> timedelta: ...
@overload
def __floordiv__(self, other: timedelta) -> int: ...
@overload
def __floordiv__(self, other: int) -> timedelta: ...
if sys.version_info >= (3,):
@overload
def __truediv__(self, other: timedelta) -> float: ...
@overload
def __truediv__(self, other: float) -> timedelta: ...
def __mod__(self, other: timedelta) -> timedelta: ...
def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ...
else:
@overload
def __div__(self, other: timedelta) -> float: ...
@overload
def __div__(self, other: float) -> timedelta: ...
def __le__(self, other: timedelta) -> bool: ...
def __lt__(self, other: timedelta) -> bool: ...
def __ge__(self, other: timedelta) -> bool: ...
def __gt__(self, other: timedelta) -> bool: ...
def __hash__(self) -> int: ...
class datetime(date):
min: ClassVar[datetime]
max: ClassVar[datetime]
resolution: ClassVar[timedelta]
if sys.version_info >= (3, 6):
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> _S: ...
else:
def __new__(
cls: Type[_S],
year: int,
month: int,
day: int,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> _S: ...
@property
def year(self) -> int: ...
@property
def month(self) -> int: ...
@property
def day(self) -> int: ...
@property
def hour(self) -> int: ...
@property
def minute(self) -> int: ...
@property
def second(self) -> int: ...
@property
def microsecond(self) -> int: ...
@property
def tzinfo(self) -> Optional[_tzinfo]: ...
if sys.version_info >= (3, 6):
@property
def fold(self) -> int: ...
@classmethod
def fromtimestamp(cls: Type[_S], t: float, tz: Optional[_tzinfo] = ...) -> _S: ...
@classmethod
def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ...
@classmethod
def today(cls: Type[_S]) -> _S: ...
@classmethod
def fromordinal(cls: Type[_S], n: int) -> _S: ...
if sys.version_info >= (3, 8):
@classmethod
def now(cls: Type[_S], tz: Optional[_tzinfo] = ...) -> _S: ...
else:
@overload
@classmethod
def now(cls: Type[_S], tz: None = ...) -> _S: ...
@overload
@classmethod
def now(cls, tz: _tzinfo) -> datetime: ...
@classmethod
def utcnow(cls: Type[_S]) -> _S: ...
if sys.version_info >= (3, 6):
@classmethod
def combine(cls, date: _date, time: _time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ...
else:
@classmethod
def combine(cls, date: _date, time: _time) -> datetime: ...
if sys.version_info >= (3, 7):
@classmethod
def fromisoformat(cls: Type[_S], date_string: str) -> _S: ...
def strftime(self, fmt: str) -> str: ...
if sys.version_info >= (3,):
def __format__(self, fmt: str) -> str: ...
else:
def __format__(self, fmt: AnyStr) -> AnyStr: ...
def toordinal(self) -> int: ...
def timetuple(self) -> struct_time: ...
if sys.version_info >= (3, 3):
def timestamp(self) -> float: ...
def utctimetuple(self) -> struct_time: ...
def date(self) -> _date: ...
def time(self) -> _time: ...
def timetz(self) -> _time: ...
if sys.version_info >= (3, 6):
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
*,
fold: int = ...,
) -> datetime: ...
else:
def replace(
self,
year: int = ...,
month: int = ...,
day: int = ...,
hour: int = ...,
minute: int = ...,
second: int = ...,
microsecond: int = ...,
tzinfo: Optional[_tzinfo] = ...,
) -> datetime: ...
if sys.version_info >= (3, 8):
def astimezone(self: _S, tz: Optional[_tzinfo] = ...) -> _S: ...
elif sys.version_info >= (3, 3):
def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ...
else:
def astimezone(self, tz: _tzinfo) -> datetime: ...
def ctime(self) -> str: ...
if sys.version_info >= (3, 6):
def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ...
else:
def isoformat(self, sep: str = ...) -> str: ...
@classmethod
def strptime(cls, date_string: str, format: str) -> datetime: ...
def utcoffset(self) -> Optional[timedelta]: ...
def tzname(self) -> Optional[str]: ...
def dst(self) -> Optional[timedelta]: ...
def __le__(self, other: datetime) -> bool: ... # type: ignore
def __lt__(self, other: datetime) -> bool: ... # type: ignore
def __ge__(self, other: datetime) -> bool: ... # type: ignore
def __gt__(self, other: datetime) -> bool: ... # type: ignore
if sys.version_info >= (3, 8):
def __add__(self: _S, other: timedelta) -> _S: ...
def __radd__(self: _S, other: timedelta) -> _S: ...
else:
def __add__(self, other: timedelta) -> datetime: ...
def __radd__(self, other: timedelta) -> datetime: ...
@overload # type: ignore
def __sub__(self, other: datetime) -> timedelta: ...
@overload
def __sub__(self, other: timedelta) -> datetime: ...
def __hash__(self) -> int: ...
def weekday(self) -> int: ...
def isoweekday(self) -> int: ...
def isocalendar(self) -> _IsoCalendarDate: ...

0
codecov.yml Normal file
View file

View file

@ -56,7 +56,6 @@ version = release = final_version
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx_mdinclude",
]
# Add any paths that contain templates here, relative to this directory.
@ -83,10 +82,6 @@ html_static_path = ["_static"]
autodoc_typehints = "description"
autodoc_class_signature = "separated"
default_role = "any"
intersphinx_mapping = {'py': ('https://docs.python.org/3', None)}
# SPDX-FileCopyrightText: 2021-2024 Jeff Epler
#
# SPDX-License-Identifier: GPL-3.0-only

View file

@ -2,10 +2,17 @@
..
.. SPDX-License-Identifier: GPL-3.0-only
wwvbpy |version|
================
wwvbpy
======
.. image:: https://github.com/jepler/wwvbpy/actions/workflows/test.yml/badge.svg
:target: https://github.com/jepler/wwvbpy/actions/workflows/test.yml
:alt: Test wwvbpy
.. image:: https://img.shields.io/pypi/v/wwvb
:target: https://pypi.org/project/wwvb
:alt: PyPI
.. mdinclude:: ../README.md
.. toctree::
:maxdepth: 2

View file

@ -19,7 +19,7 @@ dependencies = {file = "requirements.txt"}
write_to = "src/wwvb/__version__.py"
[tool.ruff.lint]
select = ["E", "F", "D", "I", "N", "UP", "YTT", "BLE", "B", "FBT", "A", "COM", "C4", "DTZ", "FA", "ISC", "ICN", "PIE", "PYI", "Q", "RET", "SIM", "TID", "TCH", "ARG", "PTH", "C", "R", "W", "FLY", "RUF", "PL"]
ignore = ["D203", "D213", "D400", "D415", "ISC001", "E741", "C901", "PLR0911", "PLR2004", "PLR0913", "COM812"]
ignore = ["D203", "D213", "D400", "D415", "ISC001", "E741", "C901", "PLR0911", "PLR2004", "PLR0913"]
[tool.ruff]
line-length = 120
[project]
@ -48,9 +48,3 @@ dut1table = "wwvb.dut1table:main"
updateiers = "wwvb.updateiers:main"
[project.gui-scripts]
wwvbtk = "wwvb.wwvbtk:main"
[[tool.mypy.overrides]]
module = ["adafruit_datetime"]
follow_untyped_imports = true
[tool.coverage.run]
patch=["subprocess"]
branch=true

View file

@ -5,10 +5,8 @@ adafruit-circuitpython-datetime
beautifulsoup4
build
click
coverage >= 7.10.3
coverage
mypy; implementation_name=="cpython"
pyright; implementation_name=="cpython"
pyrefly; implementation_name=="cpython"
click>=8.1.5; implementation_name=="cpython"
leapseconddata
platformdirs
@ -16,14 +14,12 @@ pre-commit
python-dateutil
requests; implementation_name=="cpython"
setuptools>=68; implementation_name=="cpython"
sphinx
sphinx>=7,<8
sphinx-autodoc-typehints
sphinx-rtd-theme
sphinx-mdinclude
twine; implementation_name=="cpython"
types-beautifulsoup4; implementation_name=="cpython"
types-python-dateutil; implementation_name=="cpython"
types-requests; implementation_name=="cpython"
typing-extensions; implementation_name=="cpython"
tzdata
wheel

View file

@ -2,12 +2,9 @@
#
# SPDX-License-Identifier: GPL-3.0-only
# ruff: noqa: C405, PYI024, FBT001, FBT002
# ruff: noqa: C405 PYI024 PLR2004 FBT001 FBT002
"""Implementation of a WWVB state machine & decoder for resource-constrained systems
This version is intended for use with MicroPython & CircuitPython.
"""
"""Implementation of a WWVB state machine & decoder for resource-constrained systems"""
from __future__ import annotations

View file

@ -1,13 +1,5 @@
#!/usr/bin/python3
"""A package and CLI for WWVB timecodes
This is the full featured library suitable for use on 'real computers'.
For a reduced version suitable for use on MicroPython & CircuitPython,
see `uwwvb`.
This package also includes the commandline programs listed above,
perhaps most importantly ``wwvbgen`` for generating WWVB timecodes.
"""
"""A library for WWVB timecodes"""
# SPDX-FileCopyrightText: 2011-2024 Jeff Epler
#
@ -19,36 +11,29 @@ import datetime
import enum
import json
import warnings
from dataclasses import dataclass
from typing import ClassVar, Literal
from typing import TYPE_CHECKING, Any, NamedTuple, TextIO, TypeVar
from . import iersdata
from .tz import Mountain
WWVBChannel = Literal["amplitude", "phase", "both"]
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Generator
from typing import NotRequired, Self, TextIO, TypedDict, TypeVar
class JsonMinute(TypedDict):
"""Implementation detail
This is the Python object type that is serialized by `print_timecodes_json`
"""
year: int
days: int
hour: int
minute: int
amplitude: NotRequired[str]
phase: NotRequired[str]
T = TypeVar("T")
HOUR = datetime.timedelta(seconds=3600)
SECOND = datetime.timedelta(seconds=1)
T = TypeVar("T")
def _require(x: T | None) -> T:
"""Check an Optional item is not None."""
assert x is not None
return x
def _removeprefix(s: str, p: str) -> str:
if s.startswith(p):
return s[len(p) :]
return s
def _date(dt: datetime.date) -> datetime.date:
@ -64,6 +49,7 @@ def _maybe_warn_update(dt: datetime.date, stacklevel: int = 1) -> None:
# If the date is less than 300 days after today, there should be (possibly)
# prospective available now.
today = datetime.datetime.now(tz=datetime.timezone.utc).date()
print(f"_mwu {today=!r} {dt=!r} {iersdata.end=!r}")
if _date(dt) < today + datetime.timedelta(days=330):
warnings.warn(
"Note: Running `updateiers` may provide better DUT1 and LS information",
@ -338,26 +324,10 @@ _dst_ls_lut = [
]
@enum.unique
class DstStatus(enum.IntEnum):
"""Constants that describe the DST status of a minute"""
DST_NOT_IN_EFFECT = 0b00
"""DST not in effect today"""
DST_STARTS_TODAY = 0b01
"""DST starts today at 0200 local standard time"""
DST_ENDS_TODAY = 0b10
"""DST ends today at 0200 local standard time"""
DST_IN_EFFECT = 0b11
"""DST in effect all day today"""
@dataclass(frozen=True)
class WWVBMinute:
class _WWVBMinute(NamedTuple):
"""Uniquely identifies a minute of time in the WWVB system.
To use ``ut1`` and ``ls`` information from IERS, create a `WWVBMinuteIERS`
object instead.
To use ut1 and ls information from IERS, create a WWVBMinuteIERS value instead.
"""
year: int
@ -369,10 +339,10 @@ class WWVBMinute:
hour: int
"""UTC hour of day"""
minute: int
min: int
"""Minute of hour"""
dst: DstStatus
dst: int
"""2-bit DST code """
ut1: int
@ -384,50 +354,39 @@ class WWVBMinute:
ly: bool
"""Leap year flag"""
epoch: ClassVar[int] = 1970
def __init__(
self,
class WWVBMinute(_WWVBMinute):
"""Uniquely identifies a minute of time in the WWVB system.
To use ut1 and ls information from IERS, create a WWVBMinuteIERS value instead.
"""
epoch: int = 1970
def __new__( # noqa: PYI034
cls,
year: int,
days: int,
hour: int,
minute: int,
dst: DstStatus | int | None = None,
dst: int | None = None,
ut1: int | None = None,
*,
ls: bool | None = None,
ly: bool | None = None,
) -> None:
"""Construct a WWVBMinute
:param year: The 2- or 4-digit year. This parameter is converted by the `full_year` method.
:param days: 1-based day of year
:param hour: UTC hour of day
:param minute: Minute of hour
:param dst: 2-bit DST code
:param ut1: UT1 offset in units of 100ms, range -900 to +900ms
:param ls: Leap second warning flag
:param ly: Leap year flag
"""
dst = self.get_dst(year, days) if dst is None else DstStatus(dst)
) -> WWVBMinute:
"""Construct a WWVBMinute"""
if dst is None:
dst = cls.get_dst(year, days)
if dst not in (0, 1, 2, 3):
raise ValueError("dst value should be 0..3")
if ut1 is None and ls is None:
ut1, ls = self._get_dut1_info(year, days)
ut1, ls = cls._get_dut1_info(year, days)
elif ut1 is None or ls is None:
raise ValueError("sepecify both ut1 and ls or neither one")
year = self.full_year(year)
year = cls.full_year(year)
if ly is None:
ly = isly(year)
super().__setattr__("year", year)
super().__setattr__("days", days)
super().__setattr__("hour", hour)
super().__setattr__("minute", minute)
super().__setattr__("dst", dst)
super().__setattr__("ut1", ut1)
super().__setattr__("ls", ls)
super().__setattr__("ly", ly)
return _WWVBMinute.__new__(cls, year, days, hour, minute, dst, ut1, ls, ly)
@classmethod
def full_year(cls, year: int) -> int:
@ -449,29 +408,26 @@ class WWVBMinute:
return year
@staticmethod
def get_dst(year: int, days: int) -> DstStatus:
def get_dst(year: int, days: int) -> int:
"""Get the 2-bit WWVB DST value for the given day"""
d0 = datetime.datetime(year, 1, 1, tzinfo=datetime.timezone.utc) + datetime.timedelta(days - 1)
d1 = d0 + datetime.timedelta(1)
dst0 = isdst(d0)
dst1 = isdst(d1)
return DstStatus(dst1 * 2 + dst0)
return dst1 * 2 + dst0
def __str__(self) -> str:
"""Implement str()"""
return (
f"year={self.year:4d} days={self.days:03d} hour={self.hour:02d} "
f"min={self.minute:02d} dst={self.dst} ut1={self.ut1} ly={int(self.ly)} "
f"min={self.min:02d} dst={self.dst} ut1={self.ut1} ly={int(self.ly)} "
f"ls={int(self.ls)}"
)
def as_datetime_utc(self) -> datetime.datetime:
"""Convert to a UTC datetime
The returned object has ``tzinfo=datetime.timezone.utc``.
"""
"""Convert to a UTC datetime"""
d = datetime.datetime(self.year, 1, 1, tzinfo=datetime.timezone.utc)
d += datetime.timedelta(self.days - 1, self.hour * 3600 + self.minute * 60)
d += datetime.timedelta(self.days - 1, self.hour * 3600 + self.min * 60)
return d
as_datetime = as_datetime_utc
@ -482,18 +438,7 @@ class WWVBMinute:
*,
dst_observed: bool = True,
) -> datetime.datetime:
"""Convert to a local datetime according to the DST bits
The returned object has ``tz=datetime.timezone(computed_offset)``.
:param standard_time_offset: The UTC offset of local standard time, in seconds west of UTC.
The default value, ``7 * 3600``, is for Colorado, the source of the WWVB broadcast.
:param dst_observed: If ``True`` then the locale observes DST, and a
one hour offset is applied according to WWVB rules. If ``False``, then
the standard time offset is used at all times.
"""
"""Convert to a local datetime according to the DST bits"""
u = self.as_datetime_utc()
offset = datetime.timedelta(seconds=-standard_time_offset)
d = u - datetime.timedelta(seconds=standard_time_offset)
@ -525,7 +470,7 @@ class WWVBMinute:
return 60
if not self._is_end_of_month():
return 60
if self.hour != 23 or self.minute != 59:
if self.hour != 23 or self.min != 59:
return 60
if self.ut1 > 0:
return 59
@ -569,7 +514,7 @@ class WWVBMinute:
t.am[60] = AmplitudeModulation.MARK
for i in [4, 10, 11, 14, 20, 21, 24, 34, 35, 44, 54]:
t.am[i] = AmplitudeModulation.ZERO
t._put_am_bcd(self.minute, 1, 2, 3, 5, 6, 7, 8)
t._put_am_bcd(self.min, 1, 2, 3, 5, 6, 7, 8)
t._put_am_bcd(self.hour, 12, 13, 15, 16, 17, 18)
t._put_am_bcd(self.days, 22, 23, 25, 26, 27, 28, 30, 31, 32, 33)
ut1_sign = self.ut1 >= 0
@ -583,14 +528,14 @@ class WWVBMinute:
def _fill_pm_timecode_extended(self, t: WWVBTimecode) -> None:
"""During minutes 10..15 and 40..45, the amplitude signal holds 'extended information'"""
assert 10 <= self.minute < 16 or 40 <= self.minute < 46
minno = self.minute % 10
assert 10 <= self.min < 16 or 40 <= self.min < 46
minno = self.min % 10
assert minno < 6
dst = self.dst
# Note that these are 1 different than Table 11
# because our LFSR sequence is zero-based
seqno = (self.minute // 30) * 2
seqno = (self.min // 30) * 2
if dst == 0:
pass
elif dst == 3:
@ -673,20 +618,20 @@ class WWVBMinute:
def _fill_pm_timecode(self, t: WWVBTimecode) -> None:
"""Fill the phase portion of a timecode object"""
if 10 <= self.minute < 16 or 40 <= self.minute < 46:
if 10 <= self.min < 16 or 40 <= self.min < 46:
self._fill_pm_timecode_extended(t)
else:
self._fill_pm_timecode_regular(t)
def next_minute(self, *, newut1: int | None = None, newls: bool | None = None) -> Self:
def next_minute(self, newut1: int | None = None, newls: bool | None = None) -> WWVBMinute:
"""Return an object representing the next minute"""
d = self.as_datetime() + datetime.timedelta(minutes=1)
return self.from_datetime(d, newut1=newut1, newls=newls, old_time=self)
return self.from_datetime(d, newut1, newls, self)
def previous_minute(self, *, newut1: int | None = None, newls: bool | None = None) -> Self:
def previous_minute(self, newut1: int | None = None, newls: bool | None = None) -> WWVBMinute:
"""Return an object representing the previous minute"""
d = self.as_datetime() - datetime.timedelta(minutes=1)
return self.from_datetime(d, newut1=newut1, newls=newls, old_time=self)
return self.from_datetime(d, newut1, newls, self)
@classmethod
def _get_dut1_info(cls: type, year: int, days: int, old_time: WWVBMinute | None = None) -> tuple[int, bool]: # noqa: ARG003
@ -702,9 +647,9 @@ class WWVBMinute:
return 0, False
@classmethod
def fromstring(cls, s: str) -> Self:
def fromstring(cls, s: str) -> WWVBMinute:
"""Construct a WWVBMinute from a string representation created by print_timecodes"""
s = s.removeprefix("WWVB timecode: ")
s = _removeprefix(s, "WWVB timecode: ")
d: dict[str, int] = {}
for part in s.split():
k, v = part.split("=")
@ -715,23 +660,22 @@ class WWVBMinute:
days = d.pop("days")
hour = d.pop("hour")
minute = d.pop("minute")
dst = d.pop("dst", None)
ut1 = d.pop("ut1", None)
dst: int | None = d.pop("dst", None)
ut1: int | None = d.pop("ut1", None)
ls = d.pop("ls", None)
d.pop("ly", None) # Always use calculated ly flag
d.pop("ly", None)
if d:
raise ValueError(f"Invalid options: {d}")
return cls(year, days, hour, minute, dst, ut1=ut1, ls=None if ls is None else bool(ls))
return cls(year, days, hour, minute, dst, ut1, None if ls is None else bool(ls))
@classmethod
def from_datetime(
cls,
d: datetime.datetime,
*,
newut1: int | None = None,
newls: bool | None = None,
old_time: WWVBMinute | None = None,
) -> Self:
) -> WWVBMinute:
"""Construct a WWVBMinute from a datetime, possibly specifying ut1/ls data or propagating it from an old time"""
u = d.utctimetuple()
if newls is None and newut1 is None:
@ -739,7 +683,7 @@ class WWVBMinute:
return cls(u.tm_year, u.tm_yday, u.tm_hour, u.tm_min, ut1=newut1, ls=newls)
@classmethod
def from_timecode_am(cls, t: WWVBTimecode) -> Self | None: # noqa: PLR0912
def from_timecode_am(cls, t: WWVBTimecode) -> WWVBMinute | None:
"""Construct a WWVBMinute from a WWVBTimecode"""
for i in (0, 9, 19, 29, 39, 49, 59):
if t.am[i] != AmplitudeModulation.MARK:
@ -754,13 +698,9 @@ class WWVBMinute:
minute = t._get_am_bcd(1, 2, 3, 5, 6, 7, 8)
if minute is None:
return None
if minute >= 60:
return None
hour = t._get_am_bcd(12, 13, 15, 16, 17, 18)
if hour is None:
return None
if hour >= 24:
return None
days = t._get_am_bcd(22, 23, 25, 26, 27, 28, 30, 31, 32, 33)
if days is None:
return None
@ -777,19 +717,8 @@ class WWVBMinute:
if days > 366 or (not ly and days > 365):
return None
ls = bool(t.am[56])
dst = t._get_am_bcd(57, 58)
if dst is None:
return None
return cls(year, days, hour, minute, dst, ut1, ls=ls, ly=ly)
@property
def min(self) -> int:
"""Deprecated alias for `WWVBMinute.minute`
Update your code to use the `minute` property instead of the `min` property.
"""
warnings.warn("WWVBMinute.min property is deprecated", category=DeprecationWarning, stacklevel=1)
return self.minute
dst = _require(t._get_am_bcd(57, 58))
return cls(year, days, hour, minute, dst, ut1, ls, ly)
class WWVBMinuteIERS(WWVBMinute):
@ -798,10 +727,10 @@ class WWVBMinuteIERS(WWVBMinute):
@classmethod
def _get_dut1_info(cls, year: int, days: int, old_time: WWVBMinute | None = None) -> tuple[int, bool]: # noqa: ARG003
d = datetime.datetime(year, 1, 1, tzinfo=datetime.timezone.utc) + datetime.timedelta(days - 1)
return round(get_dut1(d) * 10) * 100, isls(d)
return int(round(get_dut1(d) * 10)) * 100, isls(d)
def _bcd_bits(n: int) -> Generator[bool]:
def _bcd_bits(n: int) -> Generator[bool, None, None]:
"""Return the bcd representation of n, starting with the least significant bit"""
while True:
d = n % 10
@ -815,13 +744,9 @@ class AmplitudeModulation(enum.IntEnum):
"""Constants that describe an Amplitude Modulation value"""
ZERO = 0
"""A zero bit (reduced carrier during the first 200ms of the second)"""
ONE = 1
"""A one bit (reduced carrier during the first 500ms of the second)"""
MARK = 2
"""A mark bit (reduced carrier during the first 800ms of the second)"""
UNSET = -1
"""An unset or unknown amplitude modulation value"""
@enum.unique
@ -829,11 +754,8 @@ class PhaseModulation(enum.IntEnum):
"""Constants that describe a Phase Modulation value"""
ZERO = 0
"""A one bit (180° phase shift during the second)"""
ONE = 1
"""A zero bit (No phase shift during the second)"""
UNSET = -1
"""An unset or unknown phase modulation value"""
class WWVBTimecode:
@ -856,10 +778,7 @@ class WWVBTimecode:
The the bits ``self.am[poslist[i]]`` in MSB order are converted from
BCD to integer
"""
pos = list(poslist)[::-1]
for p in pos:
if self.am[p] not in {AmplitudeModulation.ZERO, AmplitudeModulation.ONE}:
return None
pos = reversed(poslist)
val = [bool(self.am[p]) for p in pos]
result = 0
base = 1
@ -887,7 +806,7 @@ class WWVBTimecode:
else:
self.am[p] = AmplitudeModulation.ZERO
def _put_pm_bit(self, i: int, v: PhaseModulation | int) -> None:
def _put_pm_bit(self, i: int, v: PhaseModulation | int | bool) -> None:
"""Update a bit of the Phase Modulation signal"""
self.phase[i] = PhaseModulation(v)
@ -942,7 +861,7 @@ styles = {
def print_timecodes(
w: WWVBMinute,
minutes: int,
channel: WWVBChannel,
channel: str,
style: str,
file: TextIO,
*,
@ -961,7 +880,7 @@ def print_timecodes(
print(file=file)
print(f"WWVB timecode: {w!s}{channel_text}{style_text}", file=file)
first = False
pfx = f"{w.year:04d}-{w.days:03d} {w.hour:02d}:{w.minute:02d} "
pfx = f"{w.year:04d}-{w.days:03d} {w.hour:02d}:{w.min:02d} "
tc = w.as_timecode()
if len(style_chars) == 6:
print(f"{pfx} {tc.to_both_string(style_chars)}", file=file)
@ -979,7 +898,7 @@ def print_timecodes(
def print_timecodes_json(
w: WWVBMinute,
minutes: int,
channel: WWVBChannel,
channel: str,
file: TextIO,
) -> None:
"""Print a range of timecodes in JSON format.
@ -999,11 +918,11 @@ def print_timecodes_json(
"""
result = []
for _ in range(minutes):
data: JsonMinute = {
data: dict[str, Any] = {
"year": w.year,
"days": w.days,
"hour": w.hour,
"minute": w.minute,
"minute": w.min,
}
tc = w.as_timecode()

View file

@ -6,10 +6,10 @@
from __future__ import annotations
import sys
from typing import TYPE_CHECKING
import wwvb
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Generator

View file

@ -9,18 +9,15 @@ from __future__ import annotations
import datetime
import sys
from typing import Any
import click
import dateutil.parser
from . import WWVBMinute, WWVBMinuteIERS, print_timecodes, print_timecodes_json, styles
TYPE_CHECKING = False
if TYPE_CHECKING:
from . import WWVBChannel
def parse_timespec(ctx: click.Context, param: click.Parameter, value: list[str]) -> datetime.datetime: # noqa: ARG001
def parse_timespec(ctx: Any, param: Any, value: list[str]) -> datetime.datetime: # noqa: ARG001
"""Parse a time specifier from the commandline"""
try:
if len(value) == 5:
@ -98,7 +95,7 @@ def main(
dut1: int,
minutes: int,
style: str,
channel: WWVBChannel,
channel: str,
all_timecodes: bool,
timespec: datetime.datetime,
) -> None:

View file

@ -1 +1 @@
{"START": "1972-01-01", "OFFSETS_GZ": "H4sIAOvijWgC/+2aa3LDMAiEL5uHLTuxnN5/pn/aTmfSSiAWhGy+E2SWZQE58zwiH/1YivB/96vMXiIX2Io8CTyIrDSWGqlMRdrpDa6aJFnr0m4wYZkCE2UmSF0V+13vBveStK6JTfQyW3O86HLJf0RvDgy5u4FCI+WVKTsVoUdHzsrRoWRfYHIItZ5EEgu0Beu58EgEpMpO9zf4/s3iNO4y7/hqEwOZIPu3+PuO2T7Ic5E8GxsnZHvUYOtELxW1WP+0yx/caFxpyAooq6lq06UEr+UkLeXOIDPZ6EBrqb5K8Tvu6/B9CdnZqFQL05s2KauWy/IeF/tJGAisjK9MgGyDuUkRq4G1gRE+VjA30uZNPsdantkgMq58QO4fw+sqzj+A2/16mmvnyy9UzDvMktDgKYlnkFeB2rx+wNANG40aA4OgsY03AWoDCVs/XMmkyQ0+0jWaUqPdwA0m/MRuccGjCwirHToWzbcs8P7U1nZZLSYdHapWu5HqVg1YjK2fPEwvPZPzLPUF848tyid2u7dh8B7h+wVQ923Q+kqxZe3JclSSB+YTM3nnHrjgFth/vzgZzw6cbOMYa4bHFPU/DR3mp/ubKM4cgwMnHZW4GFxFprOVcevAKGva6oExn1MOmyGDJQPm0rpU8bjqdOo993O6Xz9ofToZela5vwrWoTn4l4o5CIIaKejCEgSnJv784V+zUyyvbb/gE8h8bi3oTQAA"}
{"START": "1972-01-01", "OFFSETS_GZ": "H4sIAD/5JWcC/+2aa3LDMAiEL5uHLDuxnN5/pn/aTGbcSiAWhGx9J8gsywJypqlHvtoxZ+H/7leeLUfKsGZ5EngQWWjMJWKegrRhB1dNkqxlaVeYsEyBiTITpC6Kvde7wr0krUtiE73M1hwvulzyt+jVgSF3N1BopLwyZUMWenSkpBwdSvYFJodQ6yCSWKAtWM+ZRyQgVTbcd/D9m8Rp3GTe8dUmBjJB9l/xtw2zfZDnInk2Vk7I+qjB1oleKmqx/mmXP7jRuNKQFVBWU9WmixFeyyAt5cYgMVnpQGupvkrxO+7n8H0J2dioVAvTmzYpq5bL8h4X+0kYCKyML0yAZIO5SRGrgbWBET5WMDfS5lU+x1qe2SAyrnxA7u/D6yrOP4Db/Xqaa+fLByrm7WZJqPCUxDPIq0BtXj9g6IaNRo2BQVDZxqsAtYGErR+uZNLkBh/pGk2p0W7gBhN+Yre44NEFhNUOHYvmWxZ4f6pru6QWk44OVavdSHWrBizG1k8eppeeyXkW24L5xxblE7vd2zB4j/D9Aqj7Nmh9pdiytGQ+KtED04kJ3rkPXHAb2H+/OBnPBpxs4+hrho8p6n8aOsxP9zfROHMMDpx4VMbF4Coyna2MawN6WdMWD/T5nHLYDOksGTCX1qWIx1WnUe+5n9Pt+kHr00nXs8r9VbB0zcG/VEyDwaBEHDRhHgxOjcmG0//O5GRb/AY1IGd710wAAA=="}

View file

@ -13,7 +13,7 @@ import json
import platformdirs
__all__ = ["DUT1_DATA_START", "DUT1_OFFSETS", "end", "span", "start"]
__all__ = ["DUT1_DATA_START", "DUT1_OFFSETS", "start", "span", "end"]
content: dict[str, str] = {"START": "1970-01-01", "OFFSETS_GZ": "H4sIAFNx1mYC/wMAAAAAAAAAAAA="}

View file

@ -47,13 +47,12 @@ def update_iersdata( # noqa: PLR0915
"""Update iersdata.py"""
offsets: list[int] = []
iersdata_text = _get_text(IERS_URL)
table_start: datetime.date | None = None
for r in csv.DictReader(io.StringIO(iersdata_text), delimiter=";"):
jd = float(r["MJD"])
offs_str = r["UT1-UTC"]
if not offs_str:
break
offs = round(float(offs_str) * 10)
offs = int(round(float(offs_str) * 10))
if not offsets:
table_start = datetime.date(1858, 11, 17) + datetime.timedelta(jd)
@ -80,8 +79,6 @@ def update_iersdata( # noqa: PLR0915
offsets.append(offs)
assert table_start is not None
wwvb_text = _get_text(NIST_URL)
wwvb_data = bs4.BeautifulSoup(wwvb_text, features="html.parser")
wwvb_dut1_table = wwvb_data.findAll("table")[2]
@ -91,7 +88,6 @@ def update_iersdata( # noqa: PLR0915
wwvb_data_stamp = datetime.datetime.fromisoformat(meta.attrs["content"]).replace(tzinfo=None).date()
def patch(patch_start: datetime.date, patch_end: datetime.date, val: int) -> None:
assert table_start is not None
off_start = (patch_start - table_start).days
off_end = (patch_end - table_start).days
offsets[off_start:off_end] = [val] * (off_end - off_start)
@ -102,7 +98,7 @@ def update_iersdata( # noqa: PLR0915
cells = row.findAll("td")
when = datetime.datetime.strptime(cells[0].text + "+0000", "%Y-%m-%d%z").date()
dut1 = cells[2].text.replace("s", "").replace(" ", "")
dut1 = round(float(dut1) * 10)
dut1 = int(round(float(dut1) * 10))
if wwvb_dut1 is not None:
assert wwvb_start is not None
patch(wwvb_start, when, wwvb_dut1)

View file

@ -6,15 +6,16 @@
# SPDX-License-Identifier: GPL-3.0-only
from __future__ import annotations
import datetime
import functools
from tkinter import Canvas, Event, TclError, Tk
import threading
import time
from tkinter import Canvas, TclError, Tk
from typing import TYPE_CHECKING, Any
import click
import wwvb
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Generator
@ -25,12 +26,12 @@ def _app() -> Tk:
return Tk()
def validate_colors(ctx: click.Context, param: click.Parameter, value: str) -> list[str]: # noqa: ARG001
def validate_colors(ctx: Any, param: Any, value: str) -> list[str]: # noqa: ARG001
"""Check that all colors in a string are valid, splitting it to a list"""
app = _app()
colors = value.split()
if len(colors) not in (2, 3, 4, 6):
raise click.BadParameter(f"Give 2, 3, 4 or 6 colors (not {len(colors)})")
raise click.BadParameter(f"Give 2, 3, 4 or 6 colors (not {len(colors)}")
for c in colors:
try:
app.winfo_rgb(c)
@ -52,36 +53,33 @@ DEFAULT_COLORS = "#3c3c3c #3c3c3c #3c3c3c #cc3c3c #88883c #3ccc3c"
@click.command
@click.option(
"--colors",
callback=validate_colors,
default=DEFAULT_COLORS,
metavar="COLORS",
help="2, 3, 4, or 6 Tk color values",
)
@click.option("--size", default=48, help="initial size in pixels")
@click.option("--min-size", default=None, type=int, help="minimum size in pixels (default: same as initial size)")
@click.option("--colors", callback=validate_colors, default=DEFAULT_COLORS)
@click.option("--size", default=48)
@click.option("--min-size", default=None)
def main(colors: list[str], size: int, min_size: int | None) -> None: # noqa: PLR0915
"""Visualize the WWVB signal in realtime"""
if min_size is None:
min_size = size
def deadline_ms(deadline: datetime.datetime) -> int:
"""Compute the number of ms until a deadline"""
now = datetime.datetime.now(datetime.timezone.utc)
return int(max(0.0, (deadline - now).total_seconds()) * 1000)
def sleep_deadline(deadline: float) -> None:
"""Sleep until a deadline"""
now = time.time()
if deadline > now:
time.sleep(deadline - now)
def wwvbtick() -> Generator[tuple[datetime.datetime, wwvb.AmplitudeModulation]]:
def wwvbtick() -> Generator[tuple[float, wwvb.AmplitudeModulation], None, None]:
"""Yield consecutive values of the WWVB amplitude signal, going from minute to minute"""
timestamp = datetime.datetime.now(datetime.timezone.utc).replace(second=0, microsecond=0)
timestamp = time.time() // 60 * 60
while True:
timecode = wwvb.WWVBMinuteIERS.from_datetime(timestamp).as_timecode()
tt = time.gmtime(timestamp)
key = tt.tm_year, tt.tm_yday, tt.tm_hour, tt.tm_min
timecode = wwvb.WWVBMinuteIERS(*key).as_timecode()
for i, code in enumerate(timecode.am):
yield timestamp + datetime.timedelta(seconds=i), code
timestamp = timestamp + datetime.timedelta(seconds=60)
yield timestamp + i, code
timestamp = timestamp + 60
def wwvbsmarttick() -> Generator[tuple[datetime.datetime, wwvb.AmplitudeModulation]]:
def wwvbsmarttick() -> Generator[tuple[float, wwvb.AmplitudeModulation], None, None]:
"""Yield consecutive values of the WWVB amplitude signal
.. but deal with time progressing unexpectedly, such as when the
@ -92,10 +90,10 @@ def main(colors: list[str], size: int, min_size: int | None) -> None: # noqa: P
"""
while True:
for stamp, code in wwvbtick():
now = datetime.datetime.now(datetime.timezone.utc)
if stamp < now - datetime.timedelta(seconds=60):
now = time.time()
if stamp < now - 60:
break
if stamp < now - datetime.timedelta(seconds=1):
if stamp < now - 1:
continue
yield stamp, code
@ -106,7 +104,7 @@ def main(colors: list[str], size: int, min_size: int | None) -> None: # noqa: P
canvas.pack(fill="both", expand=True)
app.wm_deiconify()
def resize_canvas(event: Event) -> None:
def resize_canvas(event: Any) -> None:
"""Keep the circle filling the window when it is resized"""
sz = min(event.width, event.height) - 8
if sz < 0:
@ -129,25 +127,18 @@ def main(colors: list[str], size: int, min_size: int | None) -> None: # noqa: P
"""Turn the canvas's virtual LED off"""
canvas.itemconfigure(circle, fill=colors[i])
def controller_func() -> Generator[int]:
"""Update the canvas virtual LED, yielding the number of ms until the next change"""
def thread_func() -> None:
"""Update the canvas virtual LED"""
for stamp, code in wwvbsmarttick():
yield deadline_ms(stamp)
sleep_deadline(stamp)
led_on(code)
app.update()
yield deadline_ms(stamp + datetime.timedelta(seconds=0.2 + 0.3 * int(code)))
sleep_deadline(stamp + 0.2 + 0.3 * int(code))
led_off(code)
app.update()
controller = controller_func().__next__
# pyrefly: ignore # bad-assignment
def after_func() -> None:
"""Repeatedly run the controller after the desired interval"""
app.after(controller(), after_func)
# pyrefly: ignore # bad-argument-type
app.after_idle(after_func)
thread = threading.Thread(target=thread_func, daemon=True)
thread.start()
app.mainloop()

View file

@ -1,5 +1,4 @@
#!/usr/bin/python3
"""Test most wwvblib commandline programs"""
# ruff: noqa: N802 D102
@ -7,27 +6,15 @@
#
# SPDX-License-Identifier: GPL-3.0-only
from __future__ import annotations
import json
import os
import subprocess
import sys
import unittest
from collections.abc import Sequence
from typing import Any
# These imports must remain, even though the module contents are not used directly!
import wwvb.dut1table
import wwvb.gen
# The asserts below are to help prevent their removal by a linter.
assert wwvb.dut1table.__name__ == "wwvb.dut1table"
assert wwvb.gen.__name__ == "wwvb.gen"
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Sequence
from wwvb import JsonMinute
coverage_add = ("-m", "coverage", "run", "--branch", "-p") if "COVERAGE_RUN" in os.environ else ()
class CLITestCase(unittest.TestCase):
@ -39,10 +26,10 @@ class CLITestCase(unittest.TestCase):
return subprocess.check_output(args, stdin=subprocess.DEVNULL, encoding="utf-8", env=env)
def moduleArgs(self, *args: str) -> Sequence[str]:
return (sys.executable, "-m", *args)
return (sys.executable, *coverage_add, "-m", *args)
def moduleOutput(self, *args: str) -> str:
return self.programOutput(sys.executable, "-m", *args)
return self.programOutput(sys.executable, *coverage_add, "-m", *args)
def assertProgramOutput(self, expected: str, *args: str) -> None:
"""Check the output from invoking a program matches the expected"""
@ -62,10 +49,9 @@ class CLITestCase(unittest.TestCase):
def assertStarts(self, expected: str, actual: str, *args: str) -> None:
self.assertMultiLineEqual(expected, actual[: len(expected)], f"args={args}")
def assertModuleJson(self, expected: list[JsonMinute], *args: str) -> None:
def assertModuleJson(self, expected: Any, *args: str) -> None:
"""Check the output from invoking a `python -m modulename` program matches the expected"""
actual = self.moduleOutput(*args)
# Note: in mypy, revealed type of json.loads is typing.Any!
self.assertEqual(json.loads(actual), expected)
def assertModuleOutputStarts(self, expected: str, *args: str) -> None:

View file

@ -56,3 +56,7 @@ class TestLeapSecond(unittest.TestCase):
assert not our_is_ls
d = datetime.datetime.combine(nm, datetime.time(), tzinfo=datetime.timezone.utc)
self.assertEqual(leap, bench)
if __name__ == "__main__":
unittest.main()

View file

@ -27,3 +27,7 @@ class TestPhaseModulation(unittest.TestCase):
self.assertEqual(ref_am, test_am)
self.assertEqual(ref_pm, test_pm)
if __name__ == "__main__":
unittest.main()

View file

@ -4,7 +4,7 @@
#
# SPDX-License-Identifier: GPL-3.0-only
# ruff: noqa: N802
# ruff: noqa: N802 D102
import datetime
import random
import sys
@ -47,7 +47,7 @@ class WWVBRoundtrip(unittest.TestCase):
any_leap_second = False
for _ in range(20):
timecode = minute.as_timecode()
decoded: uwwvb.WWVBMinute | None = None
decoded = None
if len(timecode.am) == 61:
any_leap_second = True
for code in timecode.am:
@ -215,3 +215,7 @@ class WWVBRoundtrip(unittest.TestCase):
datetime.datetime(2020, 12, 31, 17, 00, tzinfo=zoneinfo.ZoneInfo("America/Denver")), # Mountain time!
uwwvb.as_datetime_local(decoded),
)
if __name__ == "__main__":
unittest.main()

View file

@ -1,4 +1,5 @@
#!/usr/bin/python3
# ruff: noqa: E501
"""Test most wwvblib functionality"""
@ -18,7 +19,7 @@ import unittest
import uwwvb
import wwvb
from wwvb import WWVBChannel, decode, iersdata, tz
from wwvb import decode, iersdata, tz
class WWVBMinute2k(wwvb.WWVBMinute):
@ -44,15 +45,11 @@ class WWVBTestCase(unittest.TestCase):
header = lines[0].split()
timestamp = " ".join(header[:10])
options = header[10:]
channel: WWVBChannel = "amplitude"
channel = "amplitude"
style = "default"
for o in options:
if o == "--channel=both":
channel = "both"
elif o == "--channel=amplitude":
channel = "amplitude"
elif o == "--channel=phase":
channel = "phase"
if o.startswith("--channel="):
channel = o[10:]
elif o.startswith("--style="):
style = o[8:]
else:
@ -310,11 +307,6 @@ class WWVBRoundtrip(unittest.TestCase):
wwvb._maybe_warn_update(datetime.date(1970, 1, 1))
wwvb._maybe_warn_update(datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc))
def test_deprecated_min(self) -> None:
"""Ensure that the 'maybe_warn_update' function is covered"""
with self.assertWarnsRegex(DeprecationWarning, "min property"):
self.assertEqual(wwvb.WWVBMinute(2021, 1, 1, 1).min, wwvb.WWVBMinute(2021, 1, 1, 1).minute)
def test_undefined(self) -> None:
"""Ensure that the check for unset elements in am works"""
with self.assertWarnsRegex(Warning, "is unset"):
@ -403,34 +395,6 @@ class WWVBRoundtrip(unittest.TestCase):
self.assertEqual(WWVBMinute2k(2070, 1, 1, 0, 0).year, 2070)
self.assertEqual(WWVBMinute2k(2099, 1, 1, 0, 0).year, 2099)
def test_invalid_minute(self) -> None:
"""Check that minute 61 is not valid in an AM timecode"""
base_minute = wwvb.WWVBMinute(2021, 1, 1, 0, 0)
minute = base_minute.as_timecode()
minute._put_am_bcd(61, 1, 2, 3, 5, 6, 7, 8) # valid BCD, invalid minute
decoded_minute = wwvb.WWVBMinute.from_timecode_am(minute)
assert decoded_minute is None
def test_invalid_hour(self) -> None:
"""Check that hour 25 is not valid in an AM timecode"""
base_minute = wwvb.WWVBMinute(2021, 1, 1, 0, 0)
minute = base_minute.as_timecode()
minute._put_am_bcd(29, 12, 13, 15, 16, 17, 18) # valid BCD, invalid hour
decoded_minute = wwvb.WWVBMinute.from_timecode_am(minute)
assert decoded_minute is None
def test_invalid_bcd_day(self) -> None:
"""Check that invalid BCD is detected in AM timecode"""
base_minute = wwvb.WWVBMinute(2021, 1, 1, 0, 0)
minute = base_minute.as_timecode()
minute.am[30:34] = [wwvb.AmplitudeModulation.ONE] * 4 # invalid BCD 0xf
decoded_minute = wwvb.WWVBMinute.from_timecode_am(minute)
assert decoded_minute is None
def test_invalid_mark(self) -> None:
"""Check that invalid presence of MARK in a data field is detected"""
base_minute = wwvb.WWVBMinute(2021, 1, 1, 0, 0)
minute = base_minute.as_timecode()
minute.am[57] = wwvb.AmplitudeModulation.MARK
decoded_minute = wwvb.WWVBMinute.from_timecode_am(minute)
assert decoded_minute is None
if __name__ == "__main__":
unittest.main()

View file

@ -1,14 +1,7 @@
# SPDX-FileCopyrightText: 2021 Jeff Epler
#
# SPDX-License-Identifier: CC0-1.0
#
# "For six minutes each half hour, from 1016 and 4046 minutes past each hour,
# one-minute frames are replaced by a special extended time frame. Rather than
# transmitting 35 bits of information in one minute, this transmits 7 bits
# (time of day and DST status only) over 6 minutes, giving 30 times as much
# energy per transmitted bit, a 14.8 dB improvement in the link budget compared
# to the standard one-minute time code." (wikipedia)
#
WWVB timecode: year=2021 days=311 hour=08 min=10 dst=1 ut1=-100 ly=0 ls=0 --channel=phase
2021-311 08:10 010000110100000111110110000001010110111111100110110101010001
2021-311 08:11 001001100111100011101110101111010010110010100111001000110001