streamcom-scoreboard-client 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- streamcom_scoreboard/__init__.py +57 -0
- streamcom_scoreboard/_core.py +456 -0
- streamcom_scoreboard/_delay.py +67 -0
- streamcom_scoreboard/_time.py +18 -0
- streamcom_scoreboard/_version.py +1 -0
- streamcom_scoreboard/aio.py +173 -0
- streamcom_scoreboard/backoff.py +32 -0
- streamcom_scoreboard/board.py +635 -0
- streamcom_scoreboard/client.py +482 -0
- streamcom_scoreboard/clock.py +151 -0
- streamcom_scoreboard/errors.py +130 -0
- streamcom_scoreboard/py.typed +0 -0
- streamcom_scoreboard/stream.py +694 -0
- streamcom_scoreboard/stream_errors.py +109 -0
- streamcom_scoreboard/types.py +290 -0
- streamcom_scoreboard_client-2.0.0.dist-info/METADATA +237 -0
- streamcom_scoreboard_client-2.0.0.dist-info/RECORD +19 -0
- streamcom_scoreboard_client-2.0.0.dist-info/WHEEL +4 -0
- streamcom_scoreboard_client-2.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,635 @@
|
|
|
1
|
+
"""A court's board: the state the stream's board messages build, read as fields with every clock
|
|
2
|
+
resolved to the moment you read it.
|
|
3
|
+
|
|
4
|
+
The npm package's ``CourtState`` and ``CourtFields``, rule for rule, held to
|
|
5
|
+
``sdks/cases/stream.json``. Messages arrive when the board changes and rendering happens when the
|
|
6
|
+
screen refreshes; :meth:`CourtState.apply` on arrival and :meth:`CourtState.read` on render keeps
|
|
7
|
+
the two rates apart, which is what keeps a clock from stuttering.
|
|
8
|
+
|
|
9
|
+
**Three states per field**, which are not interchangeable:
|
|
10
|
+
|
|
11
|
+
- :data:`ABSENT`: this board has no such field. Lay nothing out for it.
|
|
12
|
+
- ``None``: the board has it and was not told its value. A placeholder, never a zero.
|
|
13
|
+
- a value.
|
|
14
|
+
|
|
15
|
+
``if score is ABSENT`` and ``if score is None`` tell them apart; ``ABSENT`` is falsy, so a plain
|
|
16
|
+
``if score:`` treats both as "nothing to show".
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import copy
|
|
22
|
+
import threading
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from datetime import datetime
|
|
25
|
+
from enum import Enum
|
|
26
|
+
from typing import Any, Callable, Literal, Optional, TypeVar, Union
|
|
27
|
+
|
|
28
|
+
from .clock import Clock, ClockReading, epoch_ms
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Absent(Enum):
|
|
32
|
+
"""The type of :data:`ABSENT`."""
|
|
33
|
+
|
|
34
|
+
ABSENT = "absent"
|
|
35
|
+
|
|
36
|
+
def __bool__(self) -> bool:
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
def __repr__(self) -> str:
|
|
40
|
+
return "ABSENT"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
ABSENT = Absent.ABSENT
|
|
44
|
+
"""This board has no such field."""
|
|
45
|
+
|
|
46
|
+
T = TypeVar("T")
|
|
47
|
+
Declarable = Union[T, None, Literal[Absent.ABSENT]]
|
|
48
|
+
"""A board field: a value, ``None`` (the board was not told) or :data:`ABSENT` (no such field)."""
|
|
49
|
+
|
|
50
|
+
Json = dict[str, Any]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class CourtChange:
|
|
55
|
+
"""What changed, for a consumer that repaints one cell rather than the screen.
|
|
56
|
+
|
|
57
|
+
``changed``: side-qualified paths that moved, e.g. ``teams-home-score``; empty on a snapshot.
|
|
58
|
+
``snapshot``: true when everything may have moved.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
changed: tuple[str, ...]
|
|
62
|
+
snapshot: bool
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Period:
|
|
67
|
+
"""The period the board shows: its ``number``, what the board calls it (``label``: ``"2"``,
|
|
68
|
+
``"OT"``) and its ``type`` (``quarter``, ``half``, …)."""
|
|
69
|
+
|
|
70
|
+
number: Declarable[int]
|
|
71
|
+
label: Declarable[str]
|
|
72
|
+
type: Declarable[str]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class Exclusion:
|
|
77
|
+
"""One player out, the countdown resolved on game time: the sin bin stops when the whistle
|
|
78
|
+
does, so it borrows the game clock's ``running``.
|
|
79
|
+
|
|
80
|
+
``remaining_ms`` and ``as_of`` as the board reported them; ``ms``, ``text`` and ``ticking``
|
|
81
|
+
resolved to the moment the board was read.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
cap: Declarable[int]
|
|
85
|
+
remaining_ms: int
|
|
86
|
+
as_of: str
|
|
87
|
+
ms: int
|
|
88
|
+
text: str
|
|
89
|
+
ticking: bool
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _field(source: Any, key: str, read: Callable[[Any], Optional[T]]) -> Declarable[T]:
|
|
93
|
+
if not isinstance(source, dict) or key not in source:
|
|
94
|
+
return ABSENT
|
|
95
|
+
value = source[key]
|
|
96
|
+
return None if value is None else read(value)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _int(value: Any) -> Optional[int]:
|
|
100
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _str(value: Any) -> Optional[str]:
|
|
104
|
+
return value if isinstance(value, str) else None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _bool(value: Any) -> Optional[bool]:
|
|
108
|
+
return value if isinstance(value, bool) else None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _any(value: Any) -> Any:
|
|
112
|
+
return copy.deepcopy(value)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _reading(value: Any) -> Optional[ClockReading]:
|
|
116
|
+
if not isinstance(value, dict):
|
|
117
|
+
return None
|
|
118
|
+
return ClockReading(
|
|
119
|
+
int(value.get("ms", 0)),
|
|
120
|
+
value.get("ticking") is True,
|
|
121
|
+
"streamed" if value.get("mode") == "streamed" else "anchored",
|
|
122
|
+
value.get("stale") is True,
|
|
123
|
+
value.get("display") if isinstance(value.get("display"), str) else None,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class TeamFields:
|
|
128
|
+
"""One side of the court. The sport-specific fields sit on one type, because a consumer that
|
|
129
|
+
renders two sports renders them from one component; a field a sport lacks is :data:`ABSENT`."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, json: Json) -> None:
|
|
132
|
+
self._json = json
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def name(self) -> Declarable[str]:
|
|
136
|
+
return _field(self._json, "name", _str)
|
|
137
|
+
|
|
138
|
+
@property
|
|
139
|
+
def short(self) -> Declarable[str]:
|
|
140
|
+
return _field(self._json, "short", _str)
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def score(self) -> Declarable[int]:
|
|
144
|
+
"""Never paint an absent or unknown score as zero."""
|
|
145
|
+
return _field(self._json, "score", _int)
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def colors(self) -> Declarable[dict[str, str]]:
|
|
149
|
+
"""``{"primary", "secondary"}``: the club's kit where the platform knows the club."""
|
|
150
|
+
return _field(self._json, "colors", lambda v: dict(v) if isinstance(v, dict) else None)
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def fouls(self) -> Declarable[int]:
|
|
154
|
+
"""Basketball."""
|
|
155
|
+
return _field(self._json, "fouls", _int)
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def bonus(self) -> Declarable[bool]:
|
|
159
|
+
"""Basketball: whether this side is in the bonus, as the bridge derives it."""
|
|
160
|
+
return _field(self._json, "bonus", _bool)
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def timeouts_remaining(self) -> Declarable[int]:
|
|
164
|
+
"""Basketball, waterpolo, korfball: time-outs left."""
|
|
165
|
+
timeouts = _field(self._json, "timeouts", lambda v: v if isinstance(v, dict) else None)
|
|
166
|
+
if not isinstance(timeouts, dict):
|
|
167
|
+
return timeouts
|
|
168
|
+
return _int(timeouts.get("remaining"))
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def timeouts_taken(self) -> Declarable[int]:
|
|
172
|
+
"""Basketball, waterpolo: time-outs called, on a board that counts them upward."""
|
|
173
|
+
return _field(self._json, "timeoutsTaken", _int)
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def exclusions(self) -> Declarable[list[Exclusion]]:
|
|
177
|
+
"""Waterpolo. ``None`` is "not told"; an empty list is "told, and there are none"."""
|
|
178
|
+
return _field(self._json, "exclusions", _exclusions)
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def penalty_corners(self) -> Declarable[int]:
|
|
182
|
+
"""Hockey."""
|
|
183
|
+
return _field(self._json, "penaltyCorners", _int)
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def cards(self) -> Declarable[list[Any]]:
|
|
187
|
+
"""Hockey: the cards as the board sends them."""
|
|
188
|
+
return _field(self._json, "cards", lambda v: _any(v) if isinstance(v, list) else None)
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def yellow_cards(self) -> Declarable[int]:
|
|
192
|
+
"""Soccer."""
|
|
193
|
+
return _field(self._json, "yellowCards", _int)
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def red_cards(self) -> Declarable[int]:
|
|
197
|
+
"""Soccer."""
|
|
198
|
+
return _field(self._json, "redCards", _int)
|
|
199
|
+
|
|
200
|
+
def to_json(self) -> Json:
|
|
201
|
+
"""This side as the npm package's ``TeamFields``: absent fields left out, unknown as
|
|
202
|
+
``None``."""
|
|
203
|
+
return copy.deepcopy(self._json)
|
|
204
|
+
|
|
205
|
+
def __repr__(self) -> str:
|
|
206
|
+
return f"TeamFields({self._json!r})"
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _exclusions(value: Any) -> Optional[list[Exclusion]]:
|
|
210
|
+
if not isinstance(value, list):
|
|
211
|
+
return None
|
|
212
|
+
return [
|
|
213
|
+
Exclusion(
|
|
214
|
+
_field(entry, "cap", _int),
|
|
215
|
+
entry["remaining_ms"],
|
|
216
|
+
entry["as_of"],
|
|
217
|
+
entry["ms"],
|
|
218
|
+
entry["text"],
|
|
219
|
+
entry["ticking"],
|
|
220
|
+
)
|
|
221
|
+
for entry in value
|
|
222
|
+
]
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class CourtFields:
|
|
226
|
+
"""One court's board, read at one moment: the scoreboard document as fields, every clock a
|
|
227
|
+
:class:`ClockReading` resolved to that moment. To animate a clock, read the board again in
|
|
228
|
+
your render loop; never tick a reading yourself.
|
|
229
|
+
|
|
230
|
+
:meth:`to_json` answers the same JSON as the npm package's ``CourtFields``, for a backend
|
|
231
|
+
that hands the board on to a page.
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
def __init__(self, json: Json) -> None:
|
|
235
|
+
self._json = json
|
|
236
|
+
self.home = TeamFields(json["home"])
|
|
237
|
+
self.away = TeamFields(json["away"])
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def court_id(self) -> str:
|
|
241
|
+
return str(self._json["courtId"])
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def board_id(self) -> Declarable[str]:
|
|
245
|
+
"""The board's own id, not the court's: a court can be fed by more than one board."""
|
|
246
|
+
return _field(self._json, "boardId", _str)
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def court(self) -> Declarable[str]:
|
|
250
|
+
"""The court's name on the board."""
|
|
251
|
+
return _field(self._json, "court", _str)
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def sport(self) -> Optional[str]:
|
|
255
|
+
sport = self._json.get("sport")
|
|
256
|
+
return sport if isinstance(sport, str) else None
|
|
257
|
+
|
|
258
|
+
@property
|
|
259
|
+
def status(self) -> str:
|
|
260
|
+
"""``live``, ``standby`` or ``offline``. Never render an offline court as live."""
|
|
261
|
+
return str(self._json["status"])
|
|
262
|
+
|
|
263
|
+
@property
|
|
264
|
+
def frozen(self) -> list[str]:
|
|
265
|
+
"""Change paths whose feeding source is not online; their values are last-known. Mark
|
|
266
|
+
them, do not blank them."""
|
|
267
|
+
return list(self._json["frozen"])
|
|
268
|
+
|
|
269
|
+
@property
|
|
270
|
+
def sequence(self) -> int:
|
|
271
|
+
"""Per court, monotonic. Advances on snapshot and update, and on nothing else."""
|
|
272
|
+
return int(self._json["sequence"])
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def connected(self) -> bool:
|
|
276
|
+
"""True while the stream is connected; apart from :attr:`status`, which is the court's."""
|
|
277
|
+
return bool(self._json["connected"])
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def clock(self) -> Declarable[ClockReading]:
|
|
281
|
+
"""The game clock: ``None``, never absent, on a board that has none."""
|
|
282
|
+
return _field(self._json, "clock", _reading)
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def shot_clock(self) -> Declarable[ClockReading]:
|
|
286
|
+
return _field(self._json, "shotClock", _reading)
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def added_time_clock(self) -> Declarable[ClockReading]:
|
|
290
|
+
"""Soccer: counts up beside a clock that may be stopped at the half length."""
|
|
291
|
+
return _field(self._json, "addedTimeClock", _reading)
|
|
292
|
+
|
|
293
|
+
@property
|
|
294
|
+
def timeout_clock(self) -> Declarable[ClockReading]:
|
|
295
|
+
"""Basketball, waterpolo, korfball: running while a time-out runs. It may count up."""
|
|
296
|
+
return _field(self._json, "timeoutClock", _reading)
|
|
297
|
+
|
|
298
|
+
@property
|
|
299
|
+
def period(self) -> Declarable[Period]:
|
|
300
|
+
return _field(
|
|
301
|
+
self._json,
|
|
302
|
+
"period",
|
|
303
|
+
lambda v: Period(
|
|
304
|
+
_field(v, "number", _int), _field(v, "label", _str), _field(v, "type", _str)
|
|
305
|
+
)
|
|
306
|
+
if isinstance(v, dict)
|
|
307
|
+
else None,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
@property
|
|
311
|
+
def buzzer(self) -> Declarable[bool]:
|
|
312
|
+
"""Momentary: true only while it sounds, so a slow consumer may miss a hit."""
|
|
313
|
+
return _field(self._json, "buzzer", _bool)
|
|
314
|
+
|
|
315
|
+
@property
|
|
316
|
+
def possession(self) -> Declarable[Literal["home", "away"]]:
|
|
317
|
+
"""Who has the ball."""
|
|
318
|
+
return _field(
|
|
319
|
+
self._json, "possession", lambda v: v if v in ("home", "away") else None
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
@property
|
|
323
|
+
def added_time_minutes(self) -> Declarable[int]:
|
|
324
|
+
"""Soccer: the fourth official's figure, in whole minutes. Announced, not counted."""
|
|
325
|
+
return _field(self._json, "addedTimeMinutes", _int)
|
|
326
|
+
|
|
327
|
+
@property
|
|
328
|
+
def format(self) -> Declarable[Json]:
|
|
329
|
+
"""The active match format, as the portal pushed it."""
|
|
330
|
+
return _field(self._json, "format", _any)
|
|
331
|
+
|
|
332
|
+
@property
|
|
333
|
+
def board_format(self) -> Declarable[Json]:
|
|
334
|
+
"""What the panel reports about its own configuration. An observation, never a target."""
|
|
335
|
+
return _field(self._json, "boardFormat", _any)
|
|
336
|
+
|
|
337
|
+
def to_json(self) -> Json:
|
|
338
|
+
"""The board as the npm package's ``CourtFields``: absent fields left out, unknown as
|
|
339
|
+
``None``."""
|
|
340
|
+
return copy.deepcopy(self._json)
|
|
341
|
+
|
|
342
|
+
def __repr__(self) -> str:
|
|
343
|
+
return f"CourtFields({self._json!r})"
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# The clock paths this library resolves: the wire's key, the `frozen` path, the field.
|
|
347
|
+
_CLOCKS = (
|
|
348
|
+
("clock", "game-clock", "clock"),
|
|
349
|
+
("shot_clock", "game-shot_clock", "shotClock"),
|
|
350
|
+
("added_time_clock", "game-added_time_clock", "addedTimeClock"),
|
|
351
|
+
("timeout_clock", "game-timeout_clock", "timeoutClock"),
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
# The wire's key and the field's name, in the order the npm package writes them.
|
|
355
|
+
_TEAM_KEYS = (
|
|
356
|
+
("name", "name"),
|
|
357
|
+
("short", "short"),
|
|
358
|
+
("score", "score"),
|
|
359
|
+
("colors", "colors"),
|
|
360
|
+
("fouls", "fouls"),
|
|
361
|
+
("bonus", "bonus"),
|
|
362
|
+
("timeouts", "timeouts"),
|
|
363
|
+
("timeouts_taken", "timeoutsTaken"),
|
|
364
|
+
("exclusions", "exclusions"),
|
|
365
|
+
("penalty_corners", "penaltyCorners"),
|
|
366
|
+
("cards", "cards"),
|
|
367
|
+
("yellow_cards", "yellowCards"),
|
|
368
|
+
("red_cards", "redCards"),
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _ms(value: Any) -> Optional[int]:
|
|
373
|
+
"""Epoch ms of an ISO moment, or ``None`` when it will not parse."""
|
|
374
|
+
if not isinstance(value, str):
|
|
375
|
+
return None
|
|
376
|
+
try:
|
|
377
|
+
return epoch_ms(datetime.fromisoformat(value))
|
|
378
|
+
except ValueError:
|
|
379
|
+
return None
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _dict(value: Any) -> Json:
|
|
383
|
+
return value if isinstance(value, dict) else {}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class CourtState:
|
|
387
|
+
"""One court's state, and the rules for moving it.
|
|
388
|
+
|
|
389
|
+
The live stream holds one per court; this is public for code that follows a court's frames
|
|
390
|
+
itself. Safe to share between threads.
|
|
391
|
+
"""
|
|
392
|
+
|
|
393
|
+
def __init__(self, court_id: str) -> None:
|
|
394
|
+
self.court_id = court_id
|
|
395
|
+
self._lock = threading.Lock()
|
|
396
|
+
self._document: Optional[Json] = None
|
|
397
|
+
self._status = "offline"
|
|
398
|
+
self._frozen: list[str] = []
|
|
399
|
+
self._sequence = -1
|
|
400
|
+
# The `as_of` of the newest anchor accepted per clock path, in epoch ms. A snapshot can be
|
|
401
|
+
# built from a board reading older than the last `court-clock` applied (the fast lane
|
|
402
|
+
# carries no sequence), and replacing the anchor would walk the clock backwards.
|
|
403
|
+
self._anchored_at: dict[str, int] = {}
|
|
404
|
+
|
|
405
|
+
@property
|
|
406
|
+
def sequence(self) -> int:
|
|
407
|
+
"""The last sequence applied, or -1 before the first."""
|
|
408
|
+
return self._sequence
|
|
409
|
+
|
|
410
|
+
@property
|
|
411
|
+
def has_state(self) -> bool:
|
|
412
|
+
"""Whether anything has arrived yet. Before it, :meth:`read` answers ``None``."""
|
|
413
|
+
return self._document is not None
|
|
414
|
+
|
|
415
|
+
def is_gap(self, next_sequence: int) -> bool:
|
|
416
|
+
"""Whether ``next_sequence`` skipped, which is answered with a ``resync``. Equal or lower
|
|
417
|
+
counts too: what is held can no longer be trusted to be complete."""
|
|
418
|
+
with self._lock:
|
|
419
|
+
return self._sequence >= 0 and next_sequence != self._sequence + 1
|
|
420
|
+
|
|
421
|
+
def apply(self, message: Json) -> Optional[CourtChange]:
|
|
422
|
+
"""Apply one board message (``court-snapshot``, ``court-update``, ``court-clock``,
|
|
423
|
+
``court-status``): what changed, or ``None`` when it moved nothing a consumer renders."""
|
|
424
|
+
with self._lock:
|
|
425
|
+
kind = message.get("type")
|
|
426
|
+
if kind == "court-snapshot":
|
|
427
|
+
self._adopt(message.get("data"))
|
|
428
|
+
self._status = str(message.get("status"))
|
|
429
|
+
self._frozen = [str(p) for p in message.get("frozen") or []]
|
|
430
|
+
self._sequence = int(message.get("sequence", -1))
|
|
431
|
+
return CourtChange((), True)
|
|
432
|
+
if kind == "court-update":
|
|
433
|
+
self._adopt(message.get("data"))
|
|
434
|
+
self._sequence = int(message.get("sequence", -1))
|
|
435
|
+
return CourtChange(tuple(str(p) for p in message.get("changed") or []), False)
|
|
436
|
+
if kind == "court-clock":
|
|
437
|
+
return self._clock(message)
|
|
438
|
+
if kind == "court-status":
|
|
439
|
+
self._status = str(message.get("status"))
|
|
440
|
+
self._frozen = [str(p) for p in message.get("frozen") or []]
|
|
441
|
+
return CourtChange(("status",), False)
|
|
442
|
+
return None
|
|
443
|
+
|
|
444
|
+
def _clock(self, message: Json) -> Optional[CourtChange]:
|
|
445
|
+
"""The fast lane: replace the clocks named, keep everything else."""
|
|
446
|
+
if self._document is None:
|
|
447
|
+
return None
|
|
448
|
+
game = dict(_dict(self._document.get("game")))
|
|
449
|
+
changed: list[str] = []
|
|
450
|
+
for key, value in _dict(_dict(message.get("data")).get("game")).items():
|
|
451
|
+
if not self._accept(key, value):
|
|
452
|
+
continue
|
|
453
|
+
game[key] = value
|
|
454
|
+
changed.append(f"game-{key}")
|
|
455
|
+
if not changed:
|
|
456
|
+
return None
|
|
457
|
+
self._document = {**self._document, "game": game}
|
|
458
|
+
return CourtChange(tuple(changed), False)
|
|
459
|
+
|
|
460
|
+
def _adopt(self, data: Any) -> None:
|
|
461
|
+
"""Take a document, keeping any clock anchor newer than the one it carries."""
|
|
462
|
+
document = copy.deepcopy(data) if isinstance(data, dict) else {}
|
|
463
|
+
game = document.get("game")
|
|
464
|
+
if isinstance(game, dict):
|
|
465
|
+
held = _dict(self._document.get("game")) if self._document else {}
|
|
466
|
+
for key, _, _ in _CLOCKS:
|
|
467
|
+
if key not in game or self._accept(key, game[key]):
|
|
468
|
+
continue
|
|
469
|
+
if key in held:
|
|
470
|
+
game[key] = held[key]
|
|
471
|
+
self._document = document
|
|
472
|
+
|
|
473
|
+
def _accept(self, key: str, value: Any) -> bool:
|
|
474
|
+
"""Whether this anchor is at least as new as the one held, recording it if so. ``None``
|
|
475
|
+
always wins: "the board no longer knows this clock" is current information."""
|
|
476
|
+
if value is None:
|
|
477
|
+
self._anchored_at.pop(key, None)
|
|
478
|
+
return True
|
|
479
|
+
at = _ms(value.get("as_of")) if isinstance(value, dict) else None
|
|
480
|
+
if at is None:
|
|
481
|
+
return True
|
|
482
|
+
held = self._anchored_at.get(key)
|
|
483
|
+
if held is not None and at < held:
|
|
484
|
+
return False
|
|
485
|
+
self._anchored_at[key] = at
|
|
486
|
+
return True
|
|
487
|
+
|
|
488
|
+
def read(self, offset_ms: int, now_ms: int, connected: bool) -> Optional[CourtFields]:
|
|
489
|
+
"""The court with every clock resolved to ``now_ms`` (epoch ms); ``offset_ms`` is the
|
|
490
|
+
source's clock minus ours. ``None`` before anything arrived. Call it from a render loop:
|
|
491
|
+
it parses nothing and holds no timers."""
|
|
492
|
+
with self._lock:
|
|
493
|
+
document = self._document
|
|
494
|
+
if document is None:
|
|
495
|
+
return None
|
|
496
|
+
game = _dict(document.get("game"))
|
|
497
|
+
board_status = document.get("status")
|
|
498
|
+
frozen = list(self._frozen)
|
|
499
|
+
|
|
500
|
+
def status_for(path: str) -> str:
|
|
501
|
+
# A path whose source is frozen reads as offline whatever the board says.
|
|
502
|
+
if path in frozen:
|
|
503
|
+
return "offline"
|
|
504
|
+
return board_status if board_status in ("online", "degraded") else "offline"
|
|
505
|
+
|
|
506
|
+
out: Json = {"courtId": self.court_id or document.get("id")}
|
|
507
|
+
if "id" in document:
|
|
508
|
+
out["boardId"] = document["id"]
|
|
509
|
+
if "court" in document:
|
|
510
|
+
out["court"] = document["court"]
|
|
511
|
+
if "sport" in document:
|
|
512
|
+
out["sport"] = document["sport"]
|
|
513
|
+
out["status"] = self._status
|
|
514
|
+
out["frozen"] = frozen
|
|
515
|
+
out["sequence"] = self._sequence
|
|
516
|
+
out["connected"] = connected
|
|
517
|
+
|
|
518
|
+
# The game clock's own `running`, which every exclusion borrows. Absent is stopped.
|
|
519
|
+
raw_clock = game.get("clock")
|
|
520
|
+
game_running = isinstance(raw_clock, dict) and raw_clock.get("running") is True
|
|
521
|
+
teams = _dict(document.get("teams"))
|
|
522
|
+
for side in ("home", "away"):
|
|
523
|
+
out[side] = _team(
|
|
524
|
+
_dict(teams.get(side)),
|
|
525
|
+
game_running,
|
|
526
|
+
offset_ms,
|
|
527
|
+
now_ms,
|
|
528
|
+
status_for(f"teams-{side}-exclusions"),
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
for key, frozen_path, name in _CLOCKS:
|
|
532
|
+
if key not in game:
|
|
533
|
+
if key == "clock":
|
|
534
|
+
out["clock"] = None
|
|
535
|
+
continue
|
|
536
|
+
out[name] = _clock_field(game[key], offset_ms, now_ms, status_for(frozen_path))
|
|
537
|
+
|
|
538
|
+
if "period" in game:
|
|
539
|
+
period = game["period"]
|
|
540
|
+
out["period"] = (
|
|
541
|
+
{k: period[k] for k in ("number", "label", "type") if k in period}
|
|
542
|
+
if isinstance(period, dict)
|
|
543
|
+
else period
|
|
544
|
+
)
|
|
545
|
+
for key, name in (
|
|
546
|
+
("buzzer", "buzzer"),
|
|
547
|
+
("possession", "possession"),
|
|
548
|
+
("added_time_minutes", "addedTimeMinutes"),
|
|
549
|
+
):
|
|
550
|
+
if key in game:
|
|
551
|
+
out[name] = game[key]
|
|
552
|
+
if "format" in document:
|
|
553
|
+
out["format"] = copy.deepcopy(document["format"])
|
|
554
|
+
if "board_format" in document:
|
|
555
|
+
out["boardFormat"] = copy.deepcopy(document["board_format"])
|
|
556
|
+
return CourtFields(out)
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def _team(
|
|
560
|
+
side: Json, game_running: bool, offset_ms: int, now_ms: int, exclusion_status: str
|
|
561
|
+
) -> Json:
|
|
562
|
+
out: Json = {}
|
|
563
|
+
for key, name in _TEAM_KEYS:
|
|
564
|
+
if key not in side:
|
|
565
|
+
continue
|
|
566
|
+
value = side[key]
|
|
567
|
+
if key != "exclusions" or value is None:
|
|
568
|
+
out[name] = copy.deepcopy(value)
|
|
569
|
+
continue
|
|
570
|
+
resolved = [
|
|
571
|
+
one
|
|
572
|
+
for entry in (value if isinstance(value, list) else [])
|
|
573
|
+
if (one := _exclusion(entry, game_running, offset_ms, now_ms, exclusion_status))
|
|
574
|
+
]
|
|
575
|
+
out["exclusions"] = resolved
|
|
576
|
+
return out
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _exclusion(
|
|
580
|
+
entry: Any, game_running: bool, offset_ms: int, now_ms: int, status: str
|
|
581
|
+
) -> Optional[Json]:
|
|
582
|
+
"""One exclusion, resolved against the game clock. An entry this cannot read is dropped
|
|
583
|
+
rather than half-rendered."""
|
|
584
|
+
if not isinstance(entry, dict):
|
|
585
|
+
return None
|
|
586
|
+
remaining = entry.get("remaining_ms")
|
|
587
|
+
as_of = entry.get("as_of")
|
|
588
|
+
if not isinstance(remaining, (int, float)) or isinstance(remaining, bool):
|
|
589
|
+
return None
|
|
590
|
+
if not isinstance(as_of, str) or _ms(as_of) is None:
|
|
591
|
+
return None
|
|
592
|
+
reading = Clock(
|
|
593
|
+
game_running, int(remaining), datetime.fromisoformat(as_of), direction="down"
|
|
594
|
+
).read_ms(now_ms, offset_ms, None, status)
|
|
595
|
+
out: Json = {}
|
|
596
|
+
cap = entry.get("cap", ABSENT)
|
|
597
|
+
if cap is None or (isinstance(cap, int) and not isinstance(cap, bool)):
|
|
598
|
+
out["cap"] = cap
|
|
599
|
+
out["remaining_ms"] = remaining
|
|
600
|
+
out["as_of"] = as_of
|
|
601
|
+
out["ms"] = reading.ms
|
|
602
|
+
out["text"] = reading.text
|
|
603
|
+
out["ticking"] = reading.ticking
|
|
604
|
+
return out
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _clock_field(value: Any, offset_ms: int, now_ms: int, status: str) -> Optional[Json]:
|
|
608
|
+
"""One clock at a moment, keeping its presence: ``None`` comes back as itself."""
|
|
609
|
+
if not isinstance(value, dict):
|
|
610
|
+
return None
|
|
611
|
+
as_of = value.get("as_of")
|
|
612
|
+
if not isinstance(as_of, str) or _ms(as_of) is None:
|
|
613
|
+
return None
|
|
614
|
+
mode = value.get("mode")
|
|
615
|
+
direction = value.get("direction")
|
|
616
|
+
display = value.get("display")
|
|
617
|
+
clock = Clock(
|
|
618
|
+
value.get("running") is True,
|
|
619
|
+
int(value.get("remaining_ms") or 0),
|
|
620
|
+
datetime.fromisoformat(as_of),
|
|
621
|
+
mode=mode if mode in ("anchored", "streamed") else None,
|
|
622
|
+
direction=direction if direction in ("down", "up") else None,
|
|
623
|
+
display=display if isinstance(display, str) else None,
|
|
624
|
+
)
|
|
625
|
+
reading = clock.read_ms(now_ms, offset_ms, None, status)
|
|
626
|
+
out: Json = {
|
|
627
|
+
"ms": reading.ms,
|
|
628
|
+
"ticking": reading.ticking,
|
|
629
|
+
"mode": reading.mode,
|
|
630
|
+
"stale": reading.stale,
|
|
631
|
+
"text": reading.text,
|
|
632
|
+
}
|
|
633
|
+
if reading.display is not None:
|
|
634
|
+
out["display"] = reading.display
|
|
635
|
+
return out
|