e-note-ion 2.1.1__tar.gz → 2.2.0__tar.gz

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.
Files changed (48) hide show
  1. {e_note_ion-2.1.1/e_note_ion.egg-info → e_note_ion-2.2.0}/PKG-INFO +2 -2
  2. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/README.md +1 -1
  3. {e_note_ion-2.1.1 → e_note_ion-2.2.0/e_note_ion.egg-info}/PKG-INFO +2 -2
  4. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/health.py +30 -1
  5. e_note_ion-2.2.0/integrations/scheduler.py +80 -0
  6. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/pyproject.toml +1 -1
  7. e_note_ion-2.2.0/quiet.py +278 -0
  8. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/scheduler.py +8 -0
  9. e_note_ion-2.1.1/integrations/scheduler.py +0 -46
  10. e_note_ion-2.1.1/quiet.py +0 -96
  11. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/LICENSE.txt +0 -0
  12. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/MANIFEST.in +0 -0
  13. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/config.py +0 -0
  14. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/e_note_ion.egg-info/SOURCES.txt +0 -0
  15. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/e_note_ion.egg-info/dependency_links.txt +0 -0
  16. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/e_note_ion.egg-info/entry_points.txt +0 -0
  17. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/e_note_ion.egg-info/requires.txt +0 -0
  18. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/e_note_ion.egg-info/top_level.txt +0 -0
  19. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/exceptions.py +0 -0
  20. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/healthalert.py +0 -0
  21. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/homebridge.py +0 -0
  22. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/__init__.py +0 -0
  23. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/bart.py +0 -0
  24. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/calendar.py +0 -0
  25. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/calendar_schedule.py +0 -0
  26. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/color.py +0 -0
  27. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/discogs.py +0 -0
  28. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/diving.py +0 -0
  29. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/google.py +0 -0
  30. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/http.py +0 -0
  31. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/media.py +0 -0
  32. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/message.py +0 -0
  33. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/moon.py +0 -0
  34. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/morning.py +0 -0
  35. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/notion.py +0 -0
  36. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/parcel.py +0 -0
  37. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/plex.py +0 -0
  38. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/qbittorrent.py +0 -0
  39. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/tmdb.py +0 -0
  40. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/trakt.py +0 -0
  41. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/unraid.py +0 -0
  42. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/uptimerobot.py +0 -0
  43. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/vestaboard.py +0 -0
  44. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/weather.py +0 -0
  45. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/ynab.py +0 -0
  46. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/integrations/youtube.py +0 -0
  47. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/public.py +0 -0
  48. {e_note_ion-2.1.1 → e_note_ion-2.2.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: e-note-ion
3
- Version: 2.1.1
3
+ Version: 2.2.0
4
4
  Summary: Automation for Vestaboard displays — with emotion
5
5
  Author-email: Jason Puglisi <jason@pugli.si>
6
6
  Maintainer-email: Jason Puglisi <jason@pugli.si>
@@ -168,7 +168,7 @@ Key `[scheduler]` settings:
168
168
  | `content_enabled` | _(absent)_ | Content filter for cron-scheduled templates in both `user/` and `contrib/`: absent = all user loads, no contrib; `["*"]` = all user + all contrib; `["bart", "my_quotes"]` = only matching stems from either directory. **Webhook-only integrations (`plex`, `message`, `notion`) are unaffected — their webhooks fire regardless of this setting.** |
169
169
  | `timezone` | system TZ | IANA timezone for cron job scheduling (e.g. `"America/Los_Angeles"`) |
170
170
  | `log_level` | `"INFO"` | Logging level: `"DEBUG"`, `"INFO"`, `"WARNING"`, `"ERROR"`, `"CRITICAL"`. `"DEBUG"` shows per-integration cache hits, retry attempts, and state transitions |
171
- | `quiet` | `false` | When `true`, render content to virtual state instead of sending it to the board. Normally written by `POST /webhook/scheduler` with `{"action": "quiet"}` / `{"action": "wake"}`, but can be set manually before startup |
171
+ | `quiet` | `false` | When `true`, render content to virtual state instead of sending it to the board. Normally written by `POST /webhook/scheduler` with `{"action": "quiet"}` / `{"action": "wake"}` (optionally `"delay": <seconds>`; see [`scheduler.md`](content/contrib/scheduler.md)), but can be set manually before startup |
172
172
  | `min_hold` | `60` | Minimum seconds any message stays on display before a high-priority (≥8) queued message can interrupt it. Set to `0` to disable (not recommended for physical displays). |
173
173
 
174
174
  ### Calendar-driven gating
@@ -138,7 +138,7 @@ Key `[scheduler]` settings:
138
138
  | `content_enabled` | _(absent)_ | Content filter for cron-scheduled templates in both `user/` and `contrib/`: absent = all user loads, no contrib; `["*"]` = all user + all contrib; `["bart", "my_quotes"]` = only matching stems from either directory. **Webhook-only integrations (`plex`, `message`, `notion`) are unaffected — their webhooks fire regardless of this setting.** |
139
139
  | `timezone` | system TZ | IANA timezone for cron job scheduling (e.g. `"America/Los_Angeles"`) |
140
140
  | `log_level` | `"INFO"` | Logging level: `"DEBUG"`, `"INFO"`, `"WARNING"`, `"ERROR"`, `"CRITICAL"`. `"DEBUG"` shows per-integration cache hits, retry attempts, and state transitions |
141
- | `quiet` | `false` | When `true`, render content to virtual state instead of sending it to the board. Normally written by `POST /webhook/scheduler` with `{"action": "quiet"}` / `{"action": "wake"}`, but can be set manually before startup |
141
+ | `quiet` | `false` | When `true`, render content to virtual state instead of sending it to the board. Normally written by `POST /webhook/scheduler` with `{"action": "quiet"}` / `{"action": "wake"}` (optionally `"delay": <seconds>`; see [`scheduler.md`](content/contrib/scheduler.md)), but can be set manually before startup |
142
142
  | `min_hold` | `60` | Minimum seconds any message stays on display before a high-priority (≥8) queued message can interrupt it. Set to `0` to disable (not recommended for physical displays). |
143
143
 
144
144
  ### Calendar-driven gating
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: e-note-ion
3
- Version: 2.1.1
3
+ Version: 2.2.0
4
4
  Summary: Automation for Vestaboard displays — with emotion
5
5
  Author-email: Jason Puglisi <jason@pugli.si>
6
6
  Maintainer-email: Jason Puglisi <jason@pugli.si>
@@ -168,7 +168,7 @@ Key `[scheduler]` settings:
168
168
  | `content_enabled` | _(absent)_ | Content filter for cron-scheduled templates in both `user/` and `contrib/`: absent = all user loads, no contrib; `["*"]` = all user + all contrib; `["bart", "my_quotes"]` = only matching stems from either directory. **Webhook-only integrations (`plex`, `message`, `notion`) are unaffected — their webhooks fire regardless of this setting.** |
169
169
  | `timezone` | system TZ | IANA timezone for cron job scheduling (e.g. `"America/Los_Angeles"`) |
170
170
  | `log_level` | `"INFO"` | Logging level: `"DEBUG"`, `"INFO"`, `"WARNING"`, `"ERROR"`, `"CRITICAL"`. `"DEBUG"` shows per-integration cache hits, retry attempts, and state transitions |
171
- | `quiet` | `false` | When `true`, render content to virtual state instead of sending it to the board. Normally written by `POST /webhook/scheduler` with `{"action": "quiet"}` / `{"action": "wake"}`, but can be set manually before startup |
171
+ | `quiet` | `false` | When `true`, render content to virtual state instead of sending it to the board. Normally written by `POST /webhook/scheduler` with `{"action": "quiet"}` / `{"action": "wake"}` (optionally `"delay": <seconds>`; see [`scheduler.md`](content/contrib/scheduler.md)), but can be set manually before startup |
172
172
  | `min_hold` | `60` | Minimum seconds any message stays on display before a high-priority (≥8) queued message can interrupt it. Set to `0` to disable (not recommended for physical displays). |
173
173
 
174
174
  ### Calendar-driven gating
@@ -103,6 +103,9 @@ class _TargetState:
103
103
  # webhook-only targets, which fire on external events with no predictable
104
104
  # interval and are therefore never overdue.
105
105
  expected_interval: float | None = None
106
+ # When this integration was last *scheduled*, which is not the same as when it
107
+ # last produced an event — see note_scheduled().
108
+ last_scheduled: float = 0.0
106
109
 
107
110
 
108
111
  # Reserved target name for the Vestaboard send path. Registered implicitly
@@ -284,6 +287,30 @@ def set_expected_interval(name: str, seconds: float) -> None:
284
287
  state.expected_interval = seconds
285
288
 
286
289
 
290
+ def note_scheduled(name: str) -> None:
291
+ """Record that *name* was enqueued, whatever becomes of the message.
292
+
293
+ Overdue detection asks "has this integration stopped firing". Health events
294
+ cannot answer that on their own, because an event is only recorded once the
295
+ worker pops the message and calls the integration — and a message that loses
296
+ priority contention is discarded before that ever happens.
297
+
298
+ A Plex now-playing card holds the board indefinitely, so during a film
299
+ contrib.uptimerobot.status is enqueued every 5 minutes and discarded 2
300
+ minutes later, never reaching the integration. Nothing is wrong: #600 already
301
+ classifies exactly that discard as expected. Without this, overdue flagged it
302
+ anyway and /health went red for the length of the film.
303
+
304
+ Deliberately not a HealthEvent: this says the scheduler fired, not that the
305
+ integration succeeded, and folding it into the event deque would corrupt the
306
+ success-rate calculation.
307
+ """
308
+ with _lock:
309
+ state = _targets.get(name)
310
+ if state is not None:
311
+ state.last_scheduled = time.time()
312
+
313
+
287
314
  def _is_overdue(state: _TargetState, now: float) -> bool:
288
315
  """Return True if *state* has gone too long without firing. Caller holds _lock."""
289
316
  if state.expected_interval is None:
@@ -299,7 +326,9 @@ def _is_overdue(state: _TargetState, now: float) -> bool:
299
326
  # timestamp, and register() leaves an existing target alone. So a restored
300
327
  # target carries an old registered_at too.
301
328
  last = state.events[-1].timestamp if state.events else state.registered_at
302
- reference = max(last, _started_at)
329
+ # Being scheduled counts as alive even when the message never reached the
330
+ # integration, so a long hold on the board cannot look like a stalled cron.
331
+ reference = max(last, _started_at, state.last_scheduled)
303
332
  return (now - reference) > state.expected_interval * _OVERDUE_INTERVAL_MULTIPLIER
304
333
 
305
334
 
@@ -0,0 +1,80 @@
1
+ # integrations/scheduler.py
2
+ #
3
+ # Webhook handler for scheduler control actions (quiet mode, public mode).
4
+ # Unlike other integrations, this module does not produce display content —
5
+ # it modifies scheduler behaviour via the quiet and public modules.
6
+
7
+ import logging
8
+ import math
9
+ from typing import Any
10
+
11
+ import public as _public_mod
12
+ import quiet as _quiet_mod
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ _VALID_ACTIONS = frozenset({'quiet', 'wake', 'public', 'private'})
17
+
18
+
19
+ def _parse_delay(raw: Any) -> float:
20
+ """Validate a wake delay in seconds.
21
+
22
+ Accepts a JSON number or a numeric string (iOS Shortcuts makes it easy to
23
+ send the Text type by mistake). Rejects booleans, which are ints in Python.
24
+ The raw value is never echoed back — it is untrusted input.
25
+ """
26
+ value: float | None = None
27
+ if isinstance(raw, str):
28
+ try:
29
+ value = float(raw.strip())
30
+ except ValueError:
31
+ value = None
32
+ elif isinstance(raw, (int, float)) and not isinstance(raw, bool):
33
+ value = float(raw)
34
+ if value is None or not math.isfinite(value) or not 0 <= value <= _quiet_mod.MAX_WAKE_DELAY:
35
+ raise ValueError(f'Invalid wake delay — expected a number of seconds from 0 to {_quiet_mod.MAX_WAKE_DELAY}')
36
+ return value
37
+
38
+
39
+ def handle_webhook(
40
+ payload: dict[str, Any],
41
+ *,
42
+ credential_name: str | None = None,
43
+ ) -> None:
44
+ """Handle a scheduler control webhook.
45
+
46
+ Payload:
47
+ {"action": "quiet"} — enable quiet mode
48
+ {"action": "wake"} — disable quiet mode
49
+ {"action": "wake", "delay": 300} — disable quiet mode after 300 seconds
50
+ {"action": "public"} — enable public mode (hide private content)
51
+ {"action": "private"} — disable public mode (show all content)
52
+
53
+ The most recent command wins: quiet or an immediate wake cancels a pending
54
+ delayed wake, and a new delayed wake replaces it.
55
+
56
+ Returns None (no display message to enqueue).
57
+ """
58
+ action = payload.get('action', '')
59
+ if action not in _VALID_ACTIONS:
60
+ raise ValueError(f'Invalid scheduler action: {action!r} — expected one of {sorted(_VALID_ACTIONS)}')
61
+
62
+ delay = 0.0
63
+ if 'delay' in payload:
64
+ if action != 'wake':
65
+ raise ValueError(f'delay is only supported for the wake action, not {action!r}')
66
+ delay = _parse_delay(payload['delay'])
67
+
68
+ if action == 'quiet':
69
+ _quiet_mod.set_quiet(True)
70
+ elif action == 'wake':
71
+ if delay > 0:
72
+ _quiet_mod.schedule_wake(delay)
73
+ else:
74
+ _quiet_mod.set_quiet(False)
75
+ elif action == 'public':
76
+ _public_mod.set_public(True)
77
+ elif action == 'private':
78
+ _public_mod.set_public(False)
79
+
80
+ return None
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "e-note-ion"
3
- version = "2.1.1"
3
+ version = "2.2.0"
4
4
  description = "Automation for Vestaboard displays — with emotion"
5
5
  keywords = ["vestaboard", "note", "flagship", "automation", "schedule", "scheduling"]
6
6
  authors = [
@@ -0,0 +1,278 @@
1
+ # quiet.py
2
+ #
3
+ # Software-side quiet mode for the Vestaboard display. When active, the
4
+ # worker renders content normally but stores the result as virtual state
5
+ # instead of sending it to the board. On wake, the virtual state is sent
6
+ # immediately so the board shows contextually relevant content.
7
+ #
8
+ # State is persisted to [scheduler].quiet in config.toml so quiet mode
9
+ # survives restarts (including Docker container recreates).
10
+ #
11
+ # A wake can also be deferred (schedule_wake) so the board stays quiet for a
12
+ # few minutes after e.g. a morning alarm. The pending wake is persisted to
13
+ # data/quiet.json so it survives a restart inside the delay window. The most
14
+ # recent command wins: any set_quiet() call cancels a pending wake, and a new
15
+ # schedule_wake() replaces it. A pending wake only ever exists while quiet.
16
+ #
17
+ # Thread-safe: all state is behind a single lock.
18
+
19
+ import json
20
+ import logging
21
+ import math
22
+ import os
23
+ import threading
24
+ import time
25
+ from pathlib import Path
26
+
27
+ import config as _config_mod
28
+ import homebridge as _homebridge_mod
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+ # Upper bound on a deferred wake, so a typo cannot leave the board dark all day.
33
+ MAX_WAKE_DELAY = 3600
34
+
35
+ # Runtime state directory (Docker VOLUME /app/data), shared with health.py.
36
+ _DATA_DIR = Path('data')
37
+ _WAKE_PATH = _DATA_DIR / 'quiet.json'
38
+
39
+ _lock = threading.Lock()
40
+ _active: bool = False
41
+ _virtual_state: list[list[int]] | None = None
42
+
43
+ # Pending deferred wake. _wake_generation increments on every arm so a timer
44
+ # callback that was already running when it got cancelled or replaced (and is
45
+ # blocked on _lock) can tell it is stale — Timer.cancel() cannot stop it.
46
+ _pending_wake: threading.Timer | None = None
47
+ _pending_wake_at: float | None = None
48
+ _wake_generation: int = 0
49
+
50
+ # Set by set_quiet() so the worker can detect transitions without polling.
51
+ # The worker should wait on this event (with a timeout) in its main loop.
52
+ _changed = threading.Event()
53
+
54
+
55
+ def init() -> None:
56
+ """Load persisted quiet state from config.toml and any pending wake.
57
+
58
+ Must be called after config.load_config() and before the worker starts.
59
+ A pending wake whose deadline passed while the scheduler was stopped wakes
60
+ the board immediately; one still in the future is re-armed.
61
+ """
62
+ global _active
63
+ expired = False
64
+ with _lock:
65
+ _active = _config_mod.get_optional_bool('scheduler', 'quiet', default=False)
66
+ if _active:
67
+ logger.info('Quiet mode restored from config (board is quiet)')
68
+ wake_at = _read_wake_at()
69
+ if wake_at is not None:
70
+ if not _active:
71
+ # Quiet was cleared by hand (or the wake landed just before the file
72
+ # was removed); nothing left to wake.
73
+ logger.info('Discarding persisted pending wake — quiet mode is not active')
74
+ _remove_wake_file()
75
+ else:
76
+ remaining = wake_at - time.time()
77
+ if remaining <= 0:
78
+ expired = True
79
+ else:
80
+ # Clamp in case the wall clock moved backwards while stopped.
81
+ _arm_wake_locked(min(remaining, MAX_WAKE_DELAY))
82
+ logger.info('Pending wake restored (in %ds)', round(remaining))
83
+ if expired:
84
+ logger.info('Pending wake came due while stopped — waking now')
85
+ set_quiet(False)
86
+ # No timer was armed, so set_quiet() had nothing to cancel. Removed only
87
+ # after the wake is persisted, for the same reason as _fire_pending_wake.
88
+ # Safe outside the lock above: init() runs before the webhook server starts.
89
+ with _lock:
90
+ _remove_wake_file()
91
+
92
+
93
+ def set_quiet(value: bool) -> None:
94
+ """Set quiet mode and persist to config.toml.
95
+
96
+ Always cancels a pending deferred wake, even when the mode is unchanged:
97
+ quiet while already quiet means "keep sleeping", which must not leave the
98
+ earlier wake armed.
99
+
100
+ When transitioning to inactive, virtual state is preserved for the worker
101
+ to retrieve via pop_virtual_state() and send to the board.
102
+ """
103
+ with _lock:
104
+ if _cancel_wake_locked():
105
+ logger.info('Pending wake cancelled by %s', 'quiet' if value else 'immediate wake')
106
+ changed = _set_active_locked(value)
107
+ # Notify HomeBridge outside the lock (network I/O) and only on a real
108
+ # transition (not the no-op case).
109
+ if changed:
110
+ _homebridge_mod.notify_mode_change('quiet', value)
111
+
112
+
113
+ def schedule_wake(delay: float) -> None:
114
+ """Wake the board after *delay* seconds, replacing any pending wake.
115
+
116
+ No-op when quiet mode is not active — the board is already awake.
117
+ """
118
+ if not 0 < delay <= MAX_WAKE_DELAY:
119
+ raise ValueError(f'wake delay must be in (0, {MAX_WAKE_DELAY}] seconds')
120
+ with _lock:
121
+ if not _active:
122
+ logger.debug('Delayed wake ignored — quiet mode is not active')
123
+ return
124
+ replaced = _cancel_wake_locked()
125
+ _arm_wake_locked(delay)
126
+ _write_wake_file(time.time() + delay)
127
+ logger.info('Wake scheduled in %ds%s', round(delay), ' (replaced pending wake)' if replaced else '')
128
+
129
+
130
+ def cancel_pending_wake() -> bool:
131
+ """Cancel a pending deferred wake without changing quiet mode.
132
+
133
+ Returns whether one was pending.
134
+ """
135
+ with _lock:
136
+ return _cancel_wake_locked()
137
+
138
+
139
+ def pending_wake_at() -> float | None:
140
+ """Return the epoch time of the pending wake, or None."""
141
+ with _lock:
142
+ return _pending_wake_at
143
+
144
+
145
+ def _set_active_locked(value: bool) -> bool:
146
+ """Apply a quiet transition. Caller holds _lock. Returns whether it changed."""
147
+ global _active
148
+ if _active == value:
149
+ logger.debug('Quiet mode already %s', 'active' if value else 'inactive')
150
+ return False
151
+ _active = value
152
+ _config_mod.write_config_section('scheduler', {'quiet': value})
153
+ logger.info('Quiet mode %s', 'activated' if value else 'deactivated')
154
+ _changed.set()
155
+ return True
156
+
157
+
158
+ def _arm_wake_locked(delay: float) -> None:
159
+ """Start the wake timer. Caller holds _lock and has cancelled any prior one."""
160
+ global _pending_wake, _pending_wake_at, _wake_generation
161
+ _wake_generation += 1
162
+ timer = threading.Timer(delay, _fire_pending_wake, args=(_wake_generation,))
163
+ timer.daemon = True
164
+ _pending_wake = timer
165
+ _pending_wake_at = time.time() + delay
166
+ timer.start()
167
+
168
+
169
+ def _cancel_wake_locked() -> bool:
170
+ """Cancel the pending wake, if any. Caller holds _lock."""
171
+ global _pending_wake, _pending_wake_at
172
+ if _pending_wake is None:
173
+ return False
174
+ _pending_wake.cancel()
175
+ _pending_wake = None
176
+ _pending_wake_at = None
177
+ _remove_wake_file()
178
+ return True
179
+
180
+
181
+ def _fire_pending_wake(generation: int) -> None:
182
+ """Timer callback: wake the board if this timer is still the pending one."""
183
+ global _pending_wake, _pending_wake_at
184
+ try:
185
+ with _lock:
186
+ if _pending_wake is None or generation != _wake_generation:
187
+ return
188
+ _pending_wake = None
189
+ _pending_wake_at = None
190
+ logger.info('Delayed wake firing')
191
+ changed = _set_active_locked(False)
192
+ # Removed after the transition: if persisting quiet=false fails, the
193
+ # file survives and the next startup still wakes the board.
194
+ _remove_wake_file()
195
+ if changed:
196
+ _homebridge_mod.notify_mode_change('quiet', False)
197
+ except Exception:
198
+ logger.exception('Delayed wake failed')
199
+
200
+
201
+ def _read_wake_at() -> float | None:
202
+ """Return the persisted wake deadline, or None. Caller holds _lock."""
203
+ try:
204
+ raw = _WAKE_PATH.read_text()
205
+ except FileNotFoundError:
206
+ return None
207
+ except OSError as e:
208
+ logger.warning('Quiet: could not read %s — %s', _WAKE_PATH, e)
209
+ return None
210
+ try:
211
+ wake_at = json.loads(raw)['wake_at']
212
+ if isinstance(wake_at, bool) or not isinstance(wake_at, (int, float)) or not math.isfinite(wake_at):
213
+ raise ValueError('wake_at is not a finite number')
214
+ except (ValueError, KeyError, TypeError) as e:
215
+ logger.warning('Quiet: ignoring malformed %s — %s', _WAKE_PATH, e)
216
+ _remove_wake_file()
217
+ return None
218
+ return float(wake_at)
219
+
220
+
221
+ def _write_wake_file(wake_at: float) -> None:
222
+ """Persist the wake deadline atomically. Caller holds _lock.
223
+
224
+ Best-effort: on failure the in-memory timer still fires, the wake just
225
+ does not survive a restart.
226
+ """
227
+ tmp = _WAKE_PATH.with_suffix('.json.tmp')
228
+ try:
229
+ _DATA_DIR.mkdir(parents=True, exist_ok=True)
230
+ tmp.write_text(json.dumps({'wake_at': wake_at}))
231
+ os.replace(tmp, _WAKE_PATH)
232
+ except OSError as e:
233
+ logger.warning('Quiet: could not write %s — %s', _WAKE_PATH, e)
234
+
235
+
236
+ def _remove_wake_file() -> None:
237
+ """Delete the persisted wake deadline. Caller holds _lock."""
238
+ try:
239
+ _WAKE_PATH.unlink(missing_ok=True)
240
+ except OSError as e:
241
+ logger.warning('Quiet: could not remove %s — %s', _WAKE_PATH, e)
242
+
243
+
244
+ def is_quiet() -> bool:
245
+ """Return whether quiet mode is currently active."""
246
+ with _lock:
247
+ return _active
248
+
249
+
250
+ def set_virtual_state(characters: list[list[int]]) -> None:
251
+ """Store rendered character codes as the virtual board state."""
252
+ global _virtual_state
253
+ with _lock:
254
+ _virtual_state = characters
255
+
256
+
257
+ def get_virtual_state() -> list[list[int]] | None:
258
+ """Return the current virtual state without clearing it."""
259
+ with _lock:
260
+ return _virtual_state
261
+
262
+
263
+ def pop_virtual_state() -> list[list[int]] | None:
264
+ """Return and clear the virtual state.
265
+
266
+ Called by the worker on quiet→wake transition to send the virtual state
267
+ to the real board.
268
+ """
269
+ global _virtual_state
270
+ with _lock:
271
+ state = _virtual_state
272
+ _virtual_state = None
273
+ return state
274
+
275
+
276
+ def changed_event() -> threading.Event:
277
+ """Return the event that signals quiet state transitions."""
278
+ return _changed
@@ -201,6 +201,14 @@ def enqueue(
201
201
  seq = _counter
202
202
  _counter += 1
203
203
 
204
+ # An enqueue means the cron fired, which is what overdue detection actually
205
+ # cares about. Recorded here rather than at send time because a message that
206
+ # loses priority contention is discarded before the integration is ever
207
+ # called — see health.note_scheduled(). (#502)
208
+ integration = data.get('integration')
209
+ if integration:
210
+ _health_mod.note_scheduled(integration)
211
+
204
212
  msg = QueuedMessage(
205
213
  priority=priority,
206
214
  seq=seq,
@@ -1,46 +0,0 @@
1
- # integrations/scheduler.py
2
- #
3
- # Webhook handler for scheduler control actions (quiet mode, public mode).
4
- # Unlike other integrations, this module does not produce display content —
5
- # it modifies scheduler behaviour via the quiet and public modules.
6
-
7
- import logging
8
- from typing import Any
9
-
10
- import public as _public_mod
11
- import quiet as _quiet_mod
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- _VALID_ACTIONS = frozenset({'quiet', 'wake', 'public', 'private'})
16
-
17
-
18
- def handle_webhook(
19
- payload: dict[str, Any],
20
- *,
21
- credential_name: str | None = None,
22
- ) -> None:
23
- """Handle a scheduler control webhook.
24
-
25
- Payload:
26
- {"action": "quiet"} — enable quiet mode
27
- {"action": "wake"} — disable quiet mode
28
- {"action": "public"} — enable public mode (hide private content)
29
- {"action": "private"} — disable public mode (show all content)
30
-
31
- Returns None (no display message to enqueue).
32
- """
33
- action = payload.get('action', '')
34
- if action not in _VALID_ACTIONS:
35
- raise ValueError(f'Invalid scheduler action: {action!r} — expected one of {sorted(_VALID_ACTIONS)}')
36
-
37
- if action == 'quiet':
38
- _quiet_mod.set_quiet(True)
39
- elif action == 'wake':
40
- _quiet_mod.set_quiet(False)
41
- elif action == 'public':
42
- _public_mod.set_public(True)
43
- elif action == 'private':
44
- _public_mod.set_public(False)
45
-
46
- return None
e_note_ion-2.1.1/quiet.py DELETED
@@ -1,96 +0,0 @@
1
- # quiet.py
2
- #
3
- # Software-side quiet mode for the Vestaboard display. When active, the
4
- # worker renders content normally but stores the result as virtual state
5
- # instead of sending it to the board. On wake, the virtual state is sent
6
- # immediately so the board shows contextually relevant content.
7
- #
8
- # State is persisted to [scheduler].quiet in config.toml so quiet mode
9
- # survives restarts (including Docker container recreates).
10
- #
11
- # Thread-safe: all state is behind a single lock.
12
-
13
- import logging
14
- import threading
15
-
16
- import config as _config_mod
17
- import homebridge as _homebridge_mod
18
-
19
- logger = logging.getLogger(__name__)
20
-
21
- _lock = threading.Lock()
22
- _active: bool = False
23
- _virtual_state: list[list[int]] | None = None
24
-
25
- # Set by set_quiet() so the worker can detect transitions without polling.
26
- # The worker should wait on this event (with a timeout) in its main loop.
27
- _changed = threading.Event()
28
-
29
-
30
- def init() -> None:
31
- """Load persisted quiet state from config.toml.
32
-
33
- Must be called after config.load_config() and before the worker starts.
34
- """
35
- global _active
36
- with _lock:
37
- _active = _config_mod.get_optional_bool('scheduler', 'quiet', default=False)
38
- if _active:
39
- logger.info('Quiet mode restored from config (board is quiet)')
40
-
41
-
42
- def set_quiet(value: bool) -> None:
43
- """Set quiet mode and persist to config.toml.
44
-
45
- When transitioning to inactive, virtual state is preserved for the worker
46
- to retrieve via pop_virtual_state() and send to the board.
47
- """
48
- global _active
49
- with _lock:
50
- if _active == value:
51
- logger.debug('Quiet mode already %s', 'active' if value else 'inactive')
52
- return
53
- _active = value
54
- _config_mod.write_config_section('scheduler', {'quiet': value})
55
- logger.info('Quiet mode %s', 'activated' if value else 'deactivated')
56
- _changed.set()
57
- # Notify HomeBridge outside the lock (network I/O) and only on a real
58
- # transition (the no-op case returned above).
59
- _homebridge_mod.notify_mode_change('quiet', value)
60
-
61
-
62
- def is_quiet() -> bool:
63
- """Return whether quiet mode is currently active."""
64
- with _lock:
65
- return _active
66
-
67
-
68
- def set_virtual_state(characters: list[list[int]]) -> None:
69
- """Store rendered character codes as the virtual board state."""
70
- global _virtual_state
71
- with _lock:
72
- _virtual_state = characters
73
-
74
-
75
- def get_virtual_state() -> list[list[int]] | None:
76
- """Return the current virtual state without clearing it."""
77
- with _lock:
78
- return _virtual_state
79
-
80
-
81
- def pop_virtual_state() -> list[list[int]] | None:
82
- """Return and clear the virtual state.
83
-
84
- Called by the worker on quiet→wake transition to send the virtual state
85
- to the real board.
86
- """
87
- global _virtual_state
88
- with _lock:
89
- state = _virtual_state
90
- _virtual_state = None
91
- return state
92
-
93
-
94
- def changed_event() -> threading.Event:
95
- """Return the event that signals quiet state transitions."""
96
- return _changed
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes