Edit on GitHub

aprs.timestamp

Represent various timestamp formats

  1"""Represent various timestamp formats"""
  2
  3from datetime import UTC, datetime, timedelta, tzinfo
  4from typing import TYPE_CHECKING
  5
  6from attrs import define, field
  7
  8from .constants import TimestampFormat, timestamp_formats_map
  9
 10__author__ = "Masen Furer KF7HVM <kf7hvm@0x26.net>"
 11__copyright__ = "Copyright 2022 Masen Furer and Contributors"
 12__license__ = "Apache License, Version 2.0"
 13
 14# when receiving timestamps, consider 1 hour ahead of our clock
 15# to be "plausible" rather than adjusting the year/month/day to
 16# have the timestamp exist in the past
 17FUTURE_TIMESTAMP_THRESHOLD = timedelta(hours=1)
 18
 19
 20def utcnow_tz():
 21    return datetime.now(tz=UTC)
 22
 23
 24def _now(tz: tzinfo | None) -> datetime:
 25    """The reference time used to fill in the fields a timestamp leaves out."""
 26    return datetime.now(tz=tz)
 27
 28
 29def _fields(data: bytes, count: int) -> list[int]:
 30    """Split ``count`` 2-digit decimal fields off the front of ``data``."""
 31    digits = data[: count * 2]
 32    if len(digits) != count * 2 or not digits.isdigit():
 33        raise ValueError(f"Expecting {count * 2} ASCII digits, got {data!r}")
 34    return [int(digits[i : i + 2]) for i in range(0, count * 2, 2)]
 35
 36
 37def _months_back(year: int, month: int, n: int) -> tuple[int, int]:
 38    index = year * 12 + (month - 1) - n
 39    return index // 12, index % 12 + 1
 40
 41
 42def decode_timestamp_dhm(data: bytes) -> datetime:
 43    """
 44    Day/hours/minutes, in the current month unless that would be in the future.
 45
 46    The most recent month in which the day exists is used, so "31" received on
 47    the 1st of a 30-day month refers to the 31st two months ago, not an error.
 48    """
 49    ts_format = TimestampFormat(data[6:7])
 50    tz = None if ts_format == TimestampFormat.DayHoursMinutesLocal else UTC
 51    day, hour, minute = _fields(data, 3)
 52    if not 1 <= day <= 31:
 53        raise ValueError(f"Day out of range in {data!r}")
 54    now = _now(tz)
 55    for n in range(13):
 56        year, month = _months_back(now.year, now.month, n)
 57        try:
 58            ts = datetime(year, month, day, hour, minute, tzinfo=tz)
 59        except ValueError:
 60            if hour > 23 or minute > 59:
 61                raise
 62            continue  # day doesn't exist in that month
 63        if ts <= now + FUTURE_TIMESTAMP_THRESHOLD:
 64            return ts
 65    raise ValueError(f"Cannot place {data!r} in the past year")  # pragma: no cover
 66
 67
 68def decode_timestamp_hms(data: bytes) -> datetime:
 69    """Hours/minutes/seconds zulu, today unless that would be in the future."""
 70    hour, minute, second = _fields(data, 3)
 71    now = _now(UTC)
 72    ts = datetime(now.year, now.month, now.day, hour, minute, second, tzinfo=UTC)
 73    if ts > (now + FUTURE_TIMESTAMP_THRESHOLD):
 74        # can't have a timestamp (too far) in the future, so assume it's from yesterday
 75        return ts - timedelta(days=1)
 76    return ts
 77
 78
 79def decode_timestamp_mdhm(data: bytes) -> datetime:
 80    """Month/day/hours/minutes zulu, this year unless that would be in the future."""
 81    month, day, hour, minute = _fields(data, 4)
 82    now = _now(UTC)
 83    for year in (now.year, now.year - 1, now.year - 2, now.year - 3, now.year - 4):
 84        try:
 85            ts = datetime(year, month, day, hour, minute, tzinfo=UTC)
 86        except ValueError:
 87            if (month, day) != (2, 29):
 88                raise
 89            continue  # Feb 29 outside a leap year
 90        if ts <= now + FUTURE_TIMESTAMP_THRESHOLD:
 91            return ts
 92    raise ValueError(f"Cannot place {data!r} in the past")  # pragma: no cover
 93
 94
 95@define(frozen=True, slots=True)
 96class Timestamp:
 97    """Represents a timestamp for an APRS information field."""
 98
 99    timestamp_format: TimestampFormat = field(default=TimestampFormat.DayHoursMinutesZulu)
100    timestamp: datetime = field(factory=utcnow_tz)
101
102    @classmethod
103    def from_bytes(cls, raw: bytes) -> "Timestamp":
104        """
105        Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp.
106
107        Raises ValueError if ``raw`` does not start with a valid timestamp.
108        """
109        indicator = raw[6:7]
110        if indicator.isdigit():
111            return cls(
112                TimestampFormat.MonthDayHoursMinutesZulu, decode_timestamp_mdhm(raw)
113            )
114        ts_format = TimestampFormat(indicator)
115        if ts_format == TimestampFormat.HoursMinutesSecondsZulu:
116            return cls(ts_format, decode_timestamp_hms(raw))
117        if ts_format == TimestampFormat.MonthDayHoursMinutesZulu:
118            raise ValueError(f"Timestamp too short: {raw!r}")
119        return cls(ts_format, decode_timestamp_dhm(raw))
120
121    def __bytes__(self) -> bytes:
122        # pylint: disable=no-member
123        return (
124            self.timestamp.strftime(self.timestamp_format_string).encode("ascii")
125            + self.timestamp_format.value
126        )
127        # pylint: enable=no-member
128
129    @property
130    def timestamp_format_string(self):
131        return timestamp_formats_map[self.timestamp_format]
132
133
134class TimestampMixin:  # pylint: disable=too-few-public-methods
135    if TYPE_CHECKING:
136        # provided by the attrs class this is mixed into (read-only: frozen)
137        @property
138        def _timestamp(self) -> Timestamp | None: ...
139
140    @property
141    def timestamp(self) -> datetime | None:
142        if self._timestamp:
143            return self._timestamp.timestamp
144        return None
FUTURE_TIMESTAMP_THRESHOLD = datetime.timedelta(seconds=3600)
def utcnow_tz():
21def utcnow_tz():
22    return datetime.now(tz=UTC)
def decode_timestamp_dhm(data: bytes) -> datetime.datetime:
43def decode_timestamp_dhm(data: bytes) -> datetime:
44    """
45    Day/hours/minutes, in the current month unless that would be in the future.
46
47    The most recent month in which the day exists is used, so "31" received on
48    the 1st of a 30-day month refers to the 31st two months ago, not an error.
49    """
50    ts_format = TimestampFormat(data[6:7])
51    tz = None if ts_format == TimestampFormat.DayHoursMinutesLocal else UTC
52    day, hour, minute = _fields(data, 3)
53    if not 1 <= day <= 31:
54        raise ValueError(f"Day out of range in {data!r}")
55    now = _now(tz)
56    for n in range(13):
57        year, month = _months_back(now.year, now.month, n)
58        try:
59            ts = datetime(year, month, day, hour, minute, tzinfo=tz)
60        except ValueError:
61            if hour > 23 or minute > 59:
62                raise
63            continue  # day doesn't exist in that month
64        if ts <= now + FUTURE_TIMESTAMP_THRESHOLD:
65            return ts
66    raise ValueError(f"Cannot place {data!r} in the past year")  # pragma: no cover

Day/hours/minutes, in the current month unless that would be in the future.

The most recent month in which the day exists is used, so "31" received on the 1st of a 30-day month refers to the 31st two months ago, not an error.

def decode_timestamp_hms(data: bytes) -> datetime.datetime:
69def decode_timestamp_hms(data: bytes) -> datetime:
70    """Hours/minutes/seconds zulu, today unless that would be in the future."""
71    hour, minute, second = _fields(data, 3)
72    now = _now(UTC)
73    ts = datetime(now.year, now.month, now.day, hour, minute, second, tzinfo=UTC)
74    if ts > (now + FUTURE_TIMESTAMP_THRESHOLD):
75        # can't have a timestamp (too far) in the future, so assume it's from yesterday
76        return ts - timedelta(days=1)
77    return ts

Hours/minutes/seconds zulu, today unless that would be in the future.

def decode_timestamp_mdhm(data: bytes) -> datetime.datetime:
80def decode_timestamp_mdhm(data: bytes) -> datetime:
81    """Month/day/hours/minutes zulu, this year unless that would be in the future."""
82    month, day, hour, minute = _fields(data, 4)
83    now = _now(UTC)
84    for year in (now.year, now.year - 1, now.year - 2, now.year - 3, now.year - 4):
85        try:
86            ts = datetime(year, month, day, hour, minute, tzinfo=UTC)
87        except ValueError:
88            if (month, day) != (2, 29):
89                raise
90            continue  # Feb 29 outside a leap year
91        if ts <= now + FUTURE_TIMESTAMP_THRESHOLD:
92            return ts
93    raise ValueError(f"Cannot place {data!r} in the past")  # pragma: no cover

Month/day/hours/minutes zulu, this year unless that would be in the future.

@define(frozen=True, slots=True)
class Timestamp:
 96@define(frozen=True, slots=True)
 97class Timestamp:
 98    """Represents a timestamp for an APRS information field."""
 99
100    timestamp_format: TimestampFormat = field(default=TimestampFormat.DayHoursMinutesZulu)
101    timestamp: datetime = field(factory=utcnow_tz)
102
103    @classmethod
104    def from_bytes(cls, raw: bytes) -> "Timestamp":
105        """
106        Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp.
107
108        Raises ValueError if ``raw`` does not start with a valid timestamp.
109        """
110        indicator = raw[6:7]
111        if indicator.isdigit():
112            return cls(
113                TimestampFormat.MonthDayHoursMinutesZulu, decode_timestamp_mdhm(raw)
114            )
115        ts_format = TimestampFormat(indicator)
116        if ts_format == TimestampFormat.HoursMinutesSecondsZulu:
117            return cls(ts_format, decode_timestamp_hms(raw))
118        if ts_format == TimestampFormat.MonthDayHoursMinutesZulu:
119            raise ValueError(f"Timestamp too short: {raw!r}")
120        return cls(ts_format, decode_timestamp_dhm(raw))
121
122    def __bytes__(self) -> bytes:
123        # pylint: disable=no-member
124        return (
125            self.timestamp.strftime(self.timestamp_format_string).encode("ascii")
126            + self.timestamp_format.value
127        )
128        # pylint: enable=no-member
129
130    @property
131    def timestamp_format_string(self):
132        return timestamp_formats_map[self.timestamp_format]

Represents a timestamp for an APRS information field.

Timestamp( timestamp_format: aprs.TimestampFormat = <TimestampFormat.DayHoursMinutesZulu: b'z'>, timestamp: datetime.datetime = NOTHING)
30def __init__(self, timestamp_format=attr_dict['timestamp_format'].default, timestamp=NOTHING):
31    _setattr = _cached_setattr_get(self)
32    _setattr('timestamp_format', timestamp_format)
33    if timestamp is not NOTHING:
34        _setattr('timestamp', timestamp)
35    else:
36        _setattr('timestamp', __attr_factory_timestamp())

Method generated by attrs for class Timestamp.

timestamp_format: aprs.TimestampFormat
timestamp: datetime.datetime
@classmethod
def from_bytes(cls, raw: bytes) -> Timestamp:
103    @classmethod
104    def from_bytes(cls, raw: bytes) -> "Timestamp":
105        """
106        Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp.
107
108        Raises ValueError if ``raw`` does not start with a valid timestamp.
109        """
110        indicator = raw[6:7]
111        if indicator.isdigit():
112            return cls(
113                TimestampFormat.MonthDayHoursMinutesZulu, decode_timestamp_mdhm(raw)
114            )
115        ts_format = TimestampFormat(indicator)
116        if ts_format == TimestampFormat.HoursMinutesSecondsZulu:
117            return cls(ts_format, decode_timestamp_hms(raw))
118        if ts_format == TimestampFormat.MonthDayHoursMinutesZulu:
119            raise ValueError(f"Timestamp too short: {raw!r}")
120        return cls(ts_format, decode_timestamp_dhm(raw))

Decode a 7-byte DHM/HMS timestamp or an 8-digit MDHM timestamp.

Raises ValueError if raw does not start with a valid timestamp.

timestamp_format_string
130    @property
131    def timestamp_format_string(self):
132        return timestamp_formats_map[self.timestamp_format]
class TimestampMixin:
135class TimestampMixin:  # pylint: disable=too-few-public-methods
136    if TYPE_CHECKING:
137        # provided by the attrs class this is mixed into (read-only: frozen)
138        @property
139        def _timestamp(self) -> Timestamp | None: ...
140
141    @property
142    def timestamp(self) -> datetime | None:
143        if self._timestamp:
144            return self._timestamp.timestamp
145        return None
timestamp: datetime.datetime | None
141    @property
142    def timestamp(self) -> datetime | None:
143        if self._timestamp:
144            return self._timestamp.timestamp
145        return None