Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion art_frames/analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
SAMPLE_FIELDS = ("ts", "answered", "latency_ms", "power", "art_mode", "playing",
"brightness", "sensor", "color_temperature", "content_id")
WAKE_TEXT = (("Wake confirmed", "confirmed"), ("Wake not confirmed", "late"),
("Wake was attempted", "failed"), ("Wake skipped", "skipped"))
("Wake was attempted", "failed"), ("Wake skipped", "skipped"), ("Wake ended in TV mode", "tv-mode"))
# The only setting events stored, as "field:outcome".
SETTING_FIELDS = frozenset(OPTION_SETTERS)
SETTING_OUTCOMES = frozenset({"done", "not-done", "busy", "failed", "unpaired", "not-art-mode", "rejected",
Expand Down
26 changes: 22 additions & 4 deletions art_frames/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@
from .rotation import Hold, Rotation, held_plan, hold_until_next_change, screen_off
from .site import art_day as art_day
from .site_service import WebsitePending
from .television import MOTION_TIMER_CHOICES, DemoTelevision, DisplayError, Readback, Television, black_jpeg
from .television import (
MOTION_TIMER_CHOICES,
DemoTelevision,
DisplayError,
Readback,
Television,
WakeError,
black_jpeg,
)
from .tv_recovery import AddressRecovery

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -869,10 +877,20 @@ def _wake(self, tv, status, now, device, cfg):
self.library.delete_state("render_backoff")
woke = None
try:
# A retry sends one burst and checks briefly, so other TVs and web actions are not held up.
woke = tv.wake(checks=1) if retry else tv.wake()
self._wake_result("Wake confirmed at " + now.strftime("%H:%M") if woke else "Wake skipped because a TV programme was in progress")
# A retry sends one burst and checks briefly, so other TVs and web actions are not held up. Only the
# first try switches a TV that the wake turned on in TV mode to Art Mode (Television.wake).
woke = tv.wake(checks=1) if retry else tv.wake(switch_tv_mode=True)
if woke and "switched" in (getattr(tv, "phases", None) or {}):
self._wake_result("Wake confirmed at " + now.strftime("%H:%M") + " after a switch from TV mode")
else:
self._wake_result("Wake confirmed at " + now.strftime("%H:%M") if woke else "Wake skipped because a TV programme was in progress")
except Exception as error:
if isinstance(error, WakeError) and str(error) == "tv-mode":
# Art Frames' own wake turned the TV on in TV mode, and the one Art Mode request did not take.
# No retry: a retry must never send another wake to a TV that is on.
self._wake_result("Wake ended in TV mode at " + now.strftime("%H:%M")
+ ": the TV came on in TV mode and did not switch to Art Mode")
return tv.status()
self.library.set_state("wake_missed:" + device, today)
if self.recovery:
self.recovery.wake_failed(cfg, error) # the TV may answer at a new address
Expand Down
140 changes: 125 additions & 15 deletions art_frames/television.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ class ScreenOn(NamedTuple):
SCREEN_ON_WAIT = 30
# After the key, check for Art Mode every FAST_POLL seconds for the first FAST_SECONDS, then every second.
FAST_POLL, FAST_SECONDS = 0.5, 5
# Art Frames' own wake turned on a TV that was off, and it reads "power on, Art Mode off": the wake landed in TV
# mode. Before the one Art Mode request, the TV must read TV mode TV_MODE_READINGS more times, TV_MODE_GAP seconds
# apart, within TV_MODE_WINDOW seconds: a Frame that is still starting up often reaches Art Mode by itself. After
# the request, wait up to ART_SWITCH_WAIT seconds for Art Mode.
TV_MODE_READINGS, TV_MODE_GAP, TV_MODE_WINDOW = 2, 10, 60
ART_SWITCH_WAIT = 15
OFF_RECHECK = 3 # seconds between the two pre-wake reads of a TV that does not answer
BRIGHTNESS_RANGE = (0, 50) # used when the TV does not report its own limits
# Art Mode options. samsungtvws 3.0.6 sends these values as strings ("off", "5", "1" ...).
MOTION_TIMER_CHOICES = ("off", "5", "15", "30", "60", "120", "240") # Sleep After, in minutes
Expand Down Expand Up @@ -921,11 +928,23 @@ def check(art, steps):
outcome = {"skipped": "turned-on", "sent": "selected"}.get(steps["selected"], "no-reply")
return {**result, "outcome": outcome, "power": steps["power"], "power_after": steps["power_after"]}

def wake(self, *, checks=6):
"""Send Wake-on-LAN and confirm Art Mode; a retry passes fewer checks to bound its time."""
def wake(self, *, checks=6, switch_tv_mode=False):
"""Send Wake-on-LAN and confirm Art Mode; a retry passes fewer checks to bound its time.

Returns True for Art Mode and False when a TV programme plays. With switch_tv_mode=True (only the
scheduled wake's first try), a TV that was off before the packet (see _off_before_wake) and then
reads "power on, Art Mode off", or stays in an unknown state, is the wake landing in TV mode, not
someone watching: it gets one Art Mode request (_art_mode_after_wake), and this raises
WakeError("tv-mode") when it stays in TV mode. Without it, or for a TV that was on or in an
unknown state before the packet, TV mode is left alone.
"""
self.phases.pop("switched", None)
status = self.status(timeout=2)
if not status["paired"]:
raise WakeError("unpaired")
was_off = False
if switch_tv_mode:
status, was_off = self._off_before_wake(status)
if status["playing"]:
return False # preserve an active TV programme even at the scheduled wake time
if not self.cfg.mac:
Expand All @@ -936,19 +955,19 @@ def wake(self, *, checks=6):
# Bounded startup retries belong to this one wake event, never to the
# ordinary image-update loop. Later inactivity sleep is respected.
for _ in range(checks):
status = self.status(timeout=2)
self._mark_wake(status)
if status["playing"]:
return self._woke_in_tv_mode(was_off)
if status["known"] and status["awake"]:
return True
if not status["known"]:
# A TV in deep standby is off the network; a single burst can be lost.
self._send_magic()
time.sleep(2)
continue
art = None
try:
status = self.status(timeout=2)
self._mark_wake(status)
if status["playing"]:
return False
if status["known"] and status["awake"]:
return True
if not status["known"]:
# A TV in deep standby is off the network; a single burst can be lost.
self._send_magic()
time.sleep(2)
continue
# A confirmed standby state may be explicitly moved into Art Mode.
# Ambiguous replies never authorize a mode change.
art = self.remote(timeout=2).art(seconds=ART_SECONDS)
Expand All @@ -965,11 +984,102 @@ def wake(self, *, checks=6):
status = self.status(timeout=2)
self._mark_wake(status)
if status["playing"]:
return False
return self._woke_in_tv_mode(was_off)
if status["known"] and status["awake"]:
return True
if was_off and not status["known"] and status.get("answered"):
# It answers but its state is not clear yet: a slow start. _art_mode_after_wake waits for it.
return self._woke_in_tv_mode(was_off)
raise WakeError("state-unknown" if not status["known"] else "not-confirmed")

def _off_before_wake(self, status):
"""(The state to act on, whether the TV was off before the wake packet).

Off means confirmed standby or off, or no REST answer on two reads OFF_RECHECK seconds apart: one
missed reply can be a network blip on a TV that someone watches. A TV that answers with an
unknown state is not off.
"""
if status["known"]:
return status, not status["awake"] and not status["playing"]
if status.get("answered") is not False:
return status, False
time.sleep(OFF_RECHECK)
again = self.status(timeout=2)
if again["known"]:
return again, not again["awake"] and not again["playing"]
return again, again.get("answered") is False

def _woke_in_tv_mode(self, was_off):
"""wake() read TV mode. Someone watches unless the TV was off before the packet (see wake)."""
if not was_off:
return False
outcome = self._art_mode_after_wake()
if outcome in {"art-mode", "switched"}:
self._mark_wake({"known": True, "awake": True})
return True
raise WakeError(outcome) # "tv-mode" or "not-confirmed"

def _art_mode_after_wake(self):
"""The scheduled wake turned on a TV that was off (see _off_before_wake), and the TV now reads
"power on, Art Mode off" or an unclear state. That is the wake landing in TV mode, not someone
watching. Callers must check the state before their wake.

It reads the state until it sees TV mode TV_MODE_READINGS times, TV_MODE_GAP seconds apart, within
TV_MODE_WINDOW seconds; unclear readings do not count. A Frame that is still starting up often
reaches Art Mode by itself, and then nothing is sent. Then it reads power and Art Mode again on one
connection and, while they still read "on" and "off", calls set_artmode(True) once, and waits up to
ART_SWITCH_WAIT seconds for Art Mode. It never sends a key; an unknown or standby reading never
permits the request. Sets self.phases["switched"] when the request was sent.

Returns "art-mode" (it reached Art Mode by itself), "switched", "tv-mode" (it stayed in TV mode)
or "not-confirmed" (it went back to standby, or its state stayed unknown).
"""
self.phases.pop("switched", None)
end = time.monotonic() + TV_MODE_WINDOW
seen = 0
while seen < TV_MODE_READINGS:
if time.monotonic() >= end:
return "not-confirmed"
time.sleep(TV_MODE_GAP)
status = self.status(timeout=2)
if status["known"] and status["awake"]:
return "art-mode"
if status["playing"]:
seen += 1
elif status["known"]:
return "not-confirmed" # back in standby
device = art = None
try:
# Read power and Art Mode again on this connection, just before the change.
device = self.remote(timeout=DISPLAY_TIMEOUT)
power = str(device.rest_device_info().get("device", {}).get("PowerState", "")).strip().lower()
art = device.art(seconds=ART_SECONDS)
mode = art.get_artmode()
if power == "on" and mode == "on":
return "art-mode"
if power != "on" or mode != "off":
return "not-confirmed"
self.phases["switched"] = time.monotonic()
art.set_artmode(True)
except Exception:
if "switched" not in self.phases:
return "not-confirmed" # no answer before the request: an unknown state never permits it
# A request with a lost reply can still have worked: check below.
finally:
for connection in (art, device):
if connection:
try:
connection.close()
except Exception:
pass
end = time.monotonic() + ART_SWITCH_WAIT
while time.monotonic() < end:
time.sleep(1)
status = self.status(timeout=2)
if status["known"] and status["awake"]:
return "switched"
return "tv-mode"

def _mark_wake(self, status):
"""Record when the TV first answered after the wake packet, and when it confirmed Art Mode."""
if status["known"] or status.get("answered"):
Expand Down Expand Up @@ -1229,7 +1339,7 @@ def status(self, **kwargs):
def pair(self):
return None

def wake(self, *, checks=6):
def wake(self, *, checks=6, switch_tv_mode=False):
return True

def publish(self, image, owned_ids, record_upload, keep=()):
Expand Down
7 changes: 7 additions & 0 deletions art_frames/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,13 @@ def wake_check(text, cfg):
if text.startswith("Wake was attempted"):
return {"id": "wake", "tone": PROBLEM, "title": "Last turn-on did not reach Art Mode",
"detail": "Check the TV's MAC address, and turn on Power On with Mobile on the TV.", "fixes": ["connection"]}
if text.startswith("Wake ended in TV mode"):
title = f"Last turn-on at {times[0]} ended in TV mode, not Art Mode" if times else (
"Last turn-on ended in TV mode, not Art Mode")
return {"id": "wake", "tone": INFO, "title": title,
"detail": "Art Frames turned the TV on, but it came on in TV mode and stayed there after one request "
"to switch. To show art, press the power button on the TV's remote once: it switches the "
"TV to Art Mode."}
if "programme" in text:
return {"id": "wake", "tone": INFO, "title": "Last turn-on was skipped because someone was watching TV"}
if "room is dark" in text:
Expand Down
6 changes: 3 additions & 3 deletions tests/test_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self):
def status(self):
return {"awake": self.awake, "playing": self.playing, "paired": True, "known": True}

def wake(self, *, checks=6):
def wake(self, *, checks=6, switch_tv_mode=False):
self.wakes += 1
self.awake = True
return True
Expand Down Expand Up @@ -388,7 +388,7 @@ def status():

screen.checks = []

def wake(*, checks=6):
def wake(*, checks=6, switch_tv_mode=False):
screen.wakes += 1
screen.checks.append(checks)
raise ValueError("state-unknown")
Expand Down Expand Up @@ -550,7 +550,7 @@ def counted_status():
screen.reads += 1
return status()

def timed_wake(*, checks=6):
def timed_wake(*, checks=6, switch_tv_mode=False):
screen.phases.update(packet=100.0, answered=106.5, art_mode=108.0)
return wake(checks=checks)

Expand Down
2 changes: 1 addition & 1 deletion tests/test_prewake.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def status(self):
return {"awake": False, "playing": False, "paired": True, "known": True, "answered": True}
return {"awake": not self.playing, "playing": self.playing, "paired": True, "known": True, "answered": True}

def wake(self, *, checks=6):
def wake(self, *, checks=6, switch_tv_mode=False):
self.calls.append("wake")
if self.playing:
return False
Expand Down
4 changes: 2 additions & 2 deletions tests/test_tv_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ class WakeFails:
def status(self):
return OFFLINE

def wake(self, *, checks=6):
def wake(self, *, checks=6, switch_tv_mode=False):
raise RuntimeError("no answer")


Expand Down Expand Up @@ -789,7 +789,7 @@ def test_only_a_wake_with_no_answer_requests_a_search(configs, library, code, se
finder = recovery(configs, library, [], Clock())

class Fails(WakeFails):
def wake(self, *, checks=6):
def wake(self, *, checks=6, switch_tv_mode=False):
raise WakeError(code)

controller = Controller(configs, library, tv_factory=lambda cfg: Fails(), capture=lambda *a, **k: b"",
Expand Down
2 changes: 1 addition & 1 deletion tests/test_wake_brightness.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def undo_blank(self, content_id, brightness):
self.calls.append(("undo-blank", brightness))
return super(PowerTV, self).undo_blank(content_id, brightness)

def wake(self, *, checks=6):
def wake(self, *, checks=6, switch_tv_mode=False):
self.calls.append(("scheduled-wake", None))
self.display["power"] = "on"
return True
Expand Down
Loading