Coverage for src/signalk_cli/history/_time.py: 98%

87 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-22 09:25 +0000

1"""Time ranges for History API requests.""" 

2 

3from __future__ import annotations 

4 

5import logging 

6import re 

7from dataclasses import dataclass 

8from datetime import UTC, datetime, timedelta 

9from typing import Any 

10 

11logger = logging.getLogger("signalk_cli") 

12 

13_TIMESTAMP_FMT = "%Y-%m-%dT%H:%M:%SZ" 

14 

15_DURATION_RE = re.compile( 

16 r"^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?" 

17 r"(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$" 

18) 

19 

20 

21def _has_date_parts(duration: str) -> bool: 

22 m = _DURATION_RE.match(duration) 

23 return bool(m and any(m.group(i) for i in (1, 2, 3, 4))) 

24 

25 

26def _duration_to_timedelta(duration: str) -> timedelta: 

27 m = _DURATION_RE.match(duration) 

28 if not m: 28 ↛ 29line 28 didn't jump to line 29 because the condition on line 28 was never true

29 raise ValueError(f"Cannot parse duration: {duration!r}") 

30 years, months, weeks, days, hours, minutes = ( 

31 int(m.group(i) or 0) for i in range(1, 7) 

32 ) 

33 secs = float(m.group(7) or 0) 

34 return timedelta( 

35 days=years * 365 + months * 30 + weeks * 7 + days, 

36 hours=hours, 

37 minutes=minutes, 

38 seconds=secs, 

39 ) 

40 

41 

42def normalise_duration( 

43 duration: str | None, from_: str | None, to: str | None 

44) -> tuple[str | None, str | None, str | None]: 

45 """Convert date-component durations to explicit from/to timestamps. 

46 

47 SignalK only accepts PT-prefix (time-only) durations. Durations containing 

48 Y/M/W/D are expanded to from/to pairs: 

49 from + duration → to = from + duration 

50 to + duration → from = to - duration 

51 duration alone → from = now - duration, to = now 

52 

53 Returns (from_, to, duration_or_None). 

54 """ 

55 if not duration: 

56 return from_, to, duration 

57 try: 

58 int(duration) 

59 return from_, to, duration # integer seconds, pass through 

60 except ValueError: 

61 pass 

62 if not _has_date_parts(duration): 

63 return from_, to, duration # PT-only, pass through 

64 

65 delta = _duration_to_timedelta(duration) 

66 fmt = _TIMESTAMP_FMT 

67 now = datetime.now(UTC) 

68 

69 if from_ is not None and to is not None: 

70 return from_, to, None 

71 elif from_ is not None: 

72 from_dt = datetime.fromisoformat(from_) 

73 return from_, (from_dt + delta).strftime(fmt), None 

74 elif to is not None: 

75 to_dt = datetime.fromisoformat(to) 

76 return (to_dt - delta).strftime(fmt), to, None 

77 else: 

78 return (now - delta).strftime(fmt), now.strftime(fmt), None 

79 

80 

81def apply_time_default(time_params: dict[str, Any]) -> dict[str, Any]: 

82 """If neither 'from' nor 'duration' is set, default to the hour ending at 'to' (or now).""" 

83 if "from" in time_params or "duration" in time_params: 

84 return time_params 

85 if "to" in time_params: 

86 try: 

87 to_dt = datetime.fromisoformat(time_params["to"]) 

88 except ValueError: 

89 to_dt = datetime.now(UTC) 

90 else: 

91 to_dt = datetime.now(UTC) 

92 from_dt = to_dt - timedelta(hours=1) 

93 result = { 

94 **time_params, 

95 "from": from_dt.strftime(_TIMESTAMP_FMT), 

96 "to": to_dt.strftime(_TIMESTAMP_FMT), 

97 } 

98 logger.info( 

99 "No time range specified — defaulting to from=%s to=%s", 

100 result["from"], 

101 result["to"], 

102 ) 

103 return result 

104 

105 

106def _format_time(value: str | datetime | None) -> str | None: 

107 if value is None or isinstance(value, str): 

108 return value 

109 if value.tzinfo is None: 

110 value = value.replace(tzinfo=UTC) 

111 return value.astimezone(UTC).strftime(_TIMESTAMP_FMT) 

112 

113 

114def _format_duration(value: str | int | timedelta | None) -> str | None: 

115 if value is None or isinstance(value, str): 

116 return value 

117 if isinstance(value, timedelta): 

118 seconds = value.total_seconds() 

119 return str(int(seconds)) if seconds.is_integer() else f"PT{seconds}S" 

120 return str(value) 

121 

122 

123@dataclass(frozen=True) 

124class TimeRange: 

125 """The time window for a History API request. 

126 

127 Any combination of start, end and duration may be given, as 

128 the History API allows. Timestamps may be ISO 8601 strings or datetimes 

129 (naive datetimes are taken as UTC). Durations may be ISO 8601 strings 

130 (PT15M, P1D), integer seconds, or timedeltas. 

131 

132 Examples: 

133 ```python 

134 last_hour = TimeRange(duration="PT1H") 

135 one_day = TimeRange(start="2026-05-27T00:00:00Z", duration="P1D") 

136 ``` 

137 """ 

138 

139 start: str | datetime | None = None 

140 end: str | datetime | None = None 

141 duration: str | int | timedelta | None = None 

142 

143 def resolved(self) -> TimeRange: 

144 """Return an equivalent range the server accepts, with all values as strings. 

145 

146 The server only accepts time-only durations (PT...), so durations 

147 with date parts (P1D, P1W) are expanded to explicit start and 

148 end timestamps. With no start and no duration, the range defaults to 

149 the hour ending at end, or now. 

150 """ 

151 start, end, duration = normalise_duration( 

152 _format_duration(self.duration), 

153 _format_time(self.start), 

154 _format_time(self.end), 

155 ) 

156 params = apply_time_default(_params(start, end, duration)) 

157 return TimeRange( 

158 start=params.get("from"), 

159 end=params.get("to"), 

160 duration=params.get("duration"), 

161 ) 

162 

163 def params(self) -> dict[str, str]: 

164 """Return the from/to/duration query parameters for this range, as given.""" 

165 return _params( 

166 _format_time(self.start), 

167 _format_time(self.end), 

168 _format_duration(self.duration), 

169 ) 

170 

171 

172def _params(start: str | None, end: str | None, duration: str | None) -> dict[str, str]: 

173 p: dict[str, str] = {} 

174 if start: 

175 p["from"] = start 

176 if end: 

177 p["to"] = end 

178 if duration: 

179 p["duration"] = duration 

180 return p