14 min read

iOS-Style "Screen Time" for Sony Bravia Google TVs: ADB Polling, Per-App History Stats, and Dual Limit Alerts in Home Assistant

On an iPhone, iOS Screen Time makes digital habits crystal clear—while smart TVs are total black boxes where hours vanish. Here is how I brought Screen Time to two Sony Bravia OLEDs using Home Assistant, lightweight ADB polling, per-app history_stats, and dual alerts on iPhone and TV screen.

If you use an iPhone, you probably know the exact moment your weekly Screen Time report lands on Sunday morning.

Whether that notification brings quiet satisfaction or a jolt of guilt, it delivers something fundamental: unflinching transparency. At a single glance, iOS breaks down your digital day into crisp categories—social, entertainment, utilities—showing exactly how many hours went into each app, how many times you picked up the device, and when your daily app limits kicked in to preserve your focus.

Now contrast that with the centerpiece of almost every modern household: the living room television.

Smart TVs are no longer simple display panels plugged into coaxial cables. They are fully fledged, internet-connected computers running multi-core SoCs, Gigabit networking, and extensive app ecosystems. Yet in terms of self-awareness and usage visibility, they are complete black boxes.

You sit down in the evening after dinner with the intention of watching one 20-minute video. Before you know it, four hours have dissolved into the ether. Google TV won't tell you how long the display has been shining. Sony's firmware won't tell you how many hours went into streaming versus background music versus the screensaver. And if you have multiple displays across your home usage simply vanishes into thin air.

After stripping the telemetry and telemetry-laden stock launchers off both televisions in our earlier debloating project, I wanted to solve this black-box dilemma once and for all.

I wanted the exact iOS Screen Time experience for both Sony Bravia OLEDs inside Home Assistant: 1. Total Daily Screen Time: An accurate tally of how long each display is physically open every day (counting both active viewing and idle launcher/screensaver time). 2. Granular Per-App Breakdown: Exact daily hours accumulated in SmartTube, YouTube, Twitch, MagentaTV, Prime Video, Jellyfin, HDMI inputs, or the launcher. 3. Dedicated Lovelace Dashboard: A clean, iOS-inspired dashboard with live status cards, per-app timers, and 24-hour activity timelines. 4. Dual Screen-Time Limit Alerts: When either television crosses a configurable daily threshold (e.g., 4.0 hours), fire a push notification to our iPhones with a deep link straight to the dashboard, accompanied by an immediate on-screen Android TV banner overlaid on top of whatever is currently playing.

Here is the engineering breakdown of why the standard Google Cast approach failed, how we built lightweight ADB polling directly from inside Home Assistant without triggering USB debugging dialogs, how dumpsys handles transient UI edge cases, and how native history_stats sensors power the entire tracking engine.


Why Standard Google Cast Integration Falls Short

When integrating an Android TV or Google TV into Home Assistant, the standard recommendation is to enable the official Google Cast (cast) integration.

Google Cast relies on mDNS discovery and the Cast V2 protocol. It looks convenient on paper: Home Assistant immediately discovers media_player.bravia_65 and media_player.bravia_55. But the moment you attempt to use Cast entities for screen-time accounting, the architecture breaks down completely:

┌─────────────────────────────────────────────────────────────┐
│ Why Google Cast Fails for Screen Time Accounting            │
├─────────────────────────────────────────────────────────────┤
│ 1. Active Cast Sessions Only                                │
│    Cast only reports state when a phone or browser beams    │
│    media via the Cast receiver protocol.                    │
│                                                             │
│ 2. Total Blindness to Native Android TV Apps                │
│    When launching native apps directly on the TV remote     │
│    (SmartTube, YouTube, Twitch, Jellyfin, MagentaTV), the   │
│    Cast daemon is completely inactive.                      │
│                                                             │
│ 3. Zero Visibility Into HDMI Inputs or Launchers           │
│    Playing on a console, watching cable via HDMI, or idling │
│    on Projectivy Launcher registers as 'off' or 'idle'.     │
└─────────────────────────────────────────────────────────────┘

If someone sits down and watches three hours of live esports on native SmartTube or a film on Prime Video, media_player.cast sits blissfully in off or idle. Relying on Google Cast for screen time would miss more than 90% of actual panel operation.

What about Sony's native Bravia REST API (braviatv integration)? While it reports general display power reliably via Pre-Shared Key (PSK), it is incapable of reporting side-loaded application package names, cannot detect custom DreamService screensavers, and requires maintaining static PSK credentials on each television.

To achieve genuine Screen Time parity with iOS, we needed direct introspection into Android TV's low-level window manager and power subsystems.

We needed ADB (Android Debug Bridge).


The Architecture: Lightweight ADB Polling from the Home Assistant Container

The stock Home Assistant androidtv integration provides ADB connectivity, but anyone who has used it over network ADB knows its pitfalls: persistent background sockets that frequently desynchronize, race conditions that lock the TV's single TCP debugging slot, and occasional CPU spikes.

Instead of heavy integrations, we implemented a lean, decoupled architecture: 1. A standalone, deterministic Python monitor script (tv_adb_monitor.py) located inside the Home Assistant configuration at /config/scripts/tv_adb_monitor.py. 2. Python's native pure-Python adb_shell library—which is already pre-installed inside the official Home Assistant container image. 3. Declarative command_line sensors in configuration.yaml polling each TV every 30 seconds.

┌──────────────────────────────────────────────────────────────────────────┐
│ Home Assistant Container (raspberrypi: 192.168.1.9)                      │
│                                                                          │
│  /config/.storage/androidtv_adbkey (Authorized RSA Key Pair)             │
│                     │                                                    │
│  command_line sensor (scan_interval: 30s)                                │
│                     │                                                    │
│  python3 /config/scripts/tv_adb_monitor.py status <IP>                   │
│                     │                                                    │
└─────────────────────┼────────────────────────────────────────────────────┘
                      │ TCP Port 5555 (Connect -> Poll -> Close in <200ms)
       ┌──────────────┴──────────────┐
       ▼                             ▼
┌───────────────────────────┐ ┌───────────────────────────┐
│ Bravia 65 (XR-65A80L)     │ │ Bravia 55 (XR-55A80L)     │
│ 192.168.1.58:5555         │ │ 192.168.1.19:5555         │
│ Debloated Google TV       │ │ Debloated Google TV       │
└───────────────────────────┘ └───────────────────────────┘

Reusing Existing Keys: Zero "Allow USB Debugging" Prompts

One of our strictest anti-goals was preventing the dreaded "Allow USB debugging from this computer?" popup from appearing on the TV screens. If a living room display prompts the user with an ADB authorization modal during a movie, the automation has failed.

When Home Assistant previously initialized an Android TV device, it generated a private RSA key pair stored at /config/.storage/androidtv_adbkey. By instructing tv_adb_monitor.py to load that exact key file (or fall back to ~/.android/adbkey), every TCP handshake validates against the TV's existing adbd authorized keys list without prompting the UI.

Furthermore, each poll opens an AdbDeviceTcp session with a strict 4.0-second timeout, executes a single combined command, extracts the output, and immediately closes the socket. The television's ADB port is never held open, leaving it free for ad-hoc debugging whenever needed.


Under the Hood: Deconstructing Android TV with dumpsys

To accurately determine whether a television is on and which application is in the foreground, tv_adb_monitor.py executes a single pipelined command:

dumpsys power | grep -E "mWakefulness="; \
dumpsys dreams | grep -E "mIsDreaming=|mCurrentDream="; \
dumpsys window displays | grep -E "mCurrentFocus=|mFocusedApp="

Let's dissect what each subsystem reveals:

1. Power State (dumpsys power)

Sony Bravia OLEDs support deep standby, shallow sleep (dozing), and active awake modes. Inspecting mWakefulness gives unambiguous hardware power status: - mWakefulness=Awake: The display panel is powered and active. - mWakefulness=Dreaming: The screensaver is active. - mWakefulness=Asleep or mWakefulness=Dozing: The television is off. The script immediately returns {"is_on": false, "app": "Wyłączony"} without further parsing.

2. The Screensaver Subsystem (dumpsys dreams)

When an Android TV idles, it engages DreamService (either the stock backdrop or our Omarchy pure #000000 OLED screensaver).

While an active screensaver means no one is actively watching content, the television is still physically powered and open. In our Screen Time philosophy, idle display time must count toward total panel uptime. The monitor checks:

dream_match = re.search(r"mIsDreaming=(true|false)", output, re.IGNORECASE)
is_dreaming = dream_match.group(1).lower() == "true" if dream_match else False

if is_dreaming or wakefulness.lower() == "dreaming":
    return {
        "is_on": True,
        "wakefulness": "Dreaming",
        "package": "dream",
        "app": "Launcher / Wygaszacz",
    }

3. The Window Focus vs. Focused App Trap

Determining the active foreground application sounds simple: just query dumpsys window displays for mCurrentFocus. But real-world living-room use introduces a sneaky edge case: transient system UI.

Whenever a viewer touches the remote to change volume, mute, or switch audio output, Android TV renders a system volume bar or banner overlay (com.android.systemui). For those 2 to 3 seconds, mCurrentFocus flips from the streaming app to Window{... com.android.systemui}:

mCurrentFocus=Window{8df1cb2 u0 com.android.systemui/com.android.systemui.volume.VolumeDialogImpl}
mFocusedApp=ActivityRecord{3a41e90 u0 org.smarttube.stable/.ui.MainActivity t14}

If your monitoring script blindly trusts mCurrentFocus, your tracking registers random 30-second spikes of "System UI" or misclassifies the app as unknown.

tv_adb_monitor.py elegantly handles this with a priority fallback: 1. Extract mCurrentFocus and mFocusedApp via regex. 2. If focus_pkg is present and is not com.android.systemui, use it. 3. If focus_pkg is com.android.systemui or null, fall back to mFocusedApp (the persistent activity record running underneath). 4. If neither is available, classify the state as the launcher.

focus_pkg = focus_match.group(1) if focus_match else None
app_pkg = focused_app_match.group(1) if focused_app_match else None

if focus_pkg and focus_pkg != "com.android.systemui":
    package = focus_pkg
elif app_pkg:
    package = app_pkg
elif focus_pkg:
    package = focus_pkg
else:
    package = ""

4. The Human-Readable Package Map

Raw package identifiers like com.pl.tmobile.magentatv or com.spocky.projengmenu look terrible in a dashboard. The monitor maps package names to friendly names:

PACKAGE_APP_MAP: Dict[str, str] = {
    "org.smarttube.stable": "SmartTube",
    "com.google.android.youtube.tv": "YouTube",
    "tv.twitch.android.app": "Twitch",
    "com.pl.tmobile.magentatv": "MagentaTV",
    "com.amazon.amazonvideo.livingroom": "Prime Video",
    "org.jellyfin.androidtv": "Jellyfin",
    "pl.videostar": "Videostar",
    "com.sony.dtv.tvinput.external": "HDMI / TV",
    "com.sony.dtv.tvinput.tuner": "HDMI / TV",
    "com.sony.dtv.braviasyncmenu": "HDMI / TV",
    "com.spocky.projengmenu": "Launcher / Wygaszacz",
    "com.google.android.apps.tv.launcherx": "Launcher / Wygaszacz",
    "com.google.android.apps.tv.dreamx": "Launcher / Wygaszacz",
    "com.tvs.haomarchy": "Launcher / Wygaszacz",
    "com.android.tv.settings": "Launcher / Wygaszacz",
    "com.google.android.tungsten.setupwraith": "Launcher / Wygaszacz",
    "com.google.android.backdrop": "Launcher / Wygaszacz",
}

When called from the terminal or Home Assistant, the script outputs clean JSON:

$ python3 tv_adb_monitor.py status 192.168.1.58
{"is_on": true, "wakefulness": "Awake", "package": "org.smarttube.stable", "app": "SmartTube"}

Home Assistant Integration: Sensors, History Stats & Templates

With deterministic JSON output in hand, wire the script into Home Assistant's declarative ecosystem:

1. Command-Line Sensor (configuration.yaml)

We declare a sensor for each TV with a 30-second polling interval:

command_line:
  - sensor:
      name: "Bravia 65 – Aktywna aplikacja"
      unique_id: bravia_65_aktywna_aplikacja
      command: "python3 /config/scripts/tv_adb_monitor.py status 192.168.1.58"
      scan_interval: 30
      command_timeout: 10
      value_template: "{{ value_json.app }}"
      json_attributes:
        - is_on
        - wakefulness
        - package
      icon: mdi:television

  - sensor:
      name: "Bravia 55 – Aktywna aplikacja"
      unique_id: bravia_55_aktywna_aplikacja
      command: "python3 /config/scripts/tv_adb_monitor.py status 192.168.1.19"
      scan_interval: 30
      command_timeout: 10
      value_template: "{{ value_json.app }}"
      json_attributes:
        - is_on
        - wakefulness
        - package
      icon: mdi:television

2. Power Binary Sensor

A template binary sensor extracts the is_on attribute, giving us a clean power indicator with device_class: power:

template:
  - binary_sensor:
      - name: "Bravia 65 – Włączony"
        unique_id: bravia_65_wlaczony
        device_class: power
        state: "{{ state_attr('sensor.bravia_65_aktywna_aplikacja', 'is_on') | bool(false) }}"

      - name: "Bravia 55 – Włączony"
        unique_id: bravia_55_wlaczony
        device_class: power
        state: "{{ state_attr('sensor.bravia_55_aktywna_aplikacja', 'is_on') | bool(false) }}"

3. Accumulating Daily Time with history_stats

The true magic behind iOS Screen Time is daily accumulation that resets cleanly at midnight. Home Assistant provides this natively via the history_stats platform.

By defining start: "{{ today_at('00:00') }}" and end: "{{ now() }}", Home Assistant continuously integrates time spent in any given state across the current calendar day:

sensor:
  # Total Screen Time Today (Tracks when TV power is on)
  - platform: history_stats
    name: "Bravia 65 – Czas dzisiaj"
    unique_id: bravia_65_czas_dzis
    entity_id: binary_sensor.bravia_65_wlaczony
    state: "on"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: "Bravia 55 – Czas dzisiaj"
    unique_id: bravia_55_czas_dzis
    entity_id: binary_sensor.bravia_55_wlaczony
    state: "on"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

  # Per-App History Stats for Bravia 65
  - platform: history_stats
    name: "Bravia 65 – SmartTube"
    unique_id: bravia_65_czas_smarttube
    entity_id: sensor.bravia_65_aktywna_aplikacja
    state: "SmartTube"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: "Bravia 65 – YouTube"
    unique_id: bravia_65_czas_youtube
    entity_id: sensor.bravia_65_aktywna_aplikacja
    state: "YouTube"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: "Bravia 65 – Twitch"
    unique_id: bravia_65_czas_twitch
    entity_id: sensor.bravia_65_aktywna_aplikacja
    state: "Twitch"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: "Bravia 65 – Prime Video"
    unique_id: bravia_65_czas_prime_video
    entity_id: sensor.bravia_65_aktywna_aplikacja
    state: "Prime Video"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: "Bravia 65 – Launcher / Wygaszacz"
    unique_id: bravia_65_czas_launcher
    entity_id: sensor.bravia_65_aktywna_aplikacja
    state: "Launcher / Wygaszacz"
    type: time
    start: "{{ today_at('00:00') }}"
    end: "{{ now() }}"

Each sensor outputs exact decimal hours (e.g. 2.45 h) and automatically resets to 0.0 at 00:00:00 every single night.


The Lovelace "Telewizory" Screen Time Dashboard

To visualize this data, we built a dedicated dashboard (tv_dashboard.yaml) registered in the sidebar as Telewizory (mdi:television-shimmer).

The dashboard layout features four key elements: 1. Live Status Grid: Tile cards displaying real-time power state, active foreground application, cumulative daily hours, and limit status for each TV. 2. Per-App Time Breakdown: Clean entity lists showing how many hours were spent in each app today. 3. 24-Hour Activity Timeline (history-graph): A colored timeline showing application switches throughout the day. 4. Daily Threshold Slider: An input_number entity allowing on-the-fly adjustment of the notification threshold.

title: Telewizory
views:
  - title: Przegląd
    path: telewizory
    icon: mdi:television-shimmer
    cards:
      # Live Status: Bravia 65
      - type: grid
        title: Bravia 65 – Salon
        columns: 2
        square: false
        cards:
          - type: tile
            entity: binary_sensor.bravia_65_wlaczony
            name: Zasilanie
            icon: mdi:television
          - type: tile
            entity: sensor.bravia_65_aktywna_aplikacja
            name: Aktywna aplikacja
            icon: mdi:apps
          - type: tile
            entity: sensor.bravia_65_czas_dzisiaj
            name: Czas dzisiaj
            icon: mdi:clock-outline
            color: blue
          - type: tile
            entity: binary_sensor.bravia_65_limit_4h
            name: Status limitu
            icon: mdi:timer-alert
            color: amber

      # Live Status: Bravia 55
      - type: grid
        title: Bravia 55 – Salon
        columns: 2
        square: false
        cards:
          - type: tile
            entity: binary_sensor.bravia_55_wlaczony
            name: Zasilanie
            icon: mdi:television
          - type: tile
            entity: sensor.bravia_55_aktywna_aplikacja
            name: Aktywna aplikacja
            icon: mdi:apps
          - type: tile
            entity: sensor.bravia_55_czas_dzisiaj
            name: Czas dzisiaj
            icon: mdi:clock-outline
            color: purple
          - type: tile
            entity: binary_sensor.bravia_55_limit_4h
            name: Status limitu
            icon: mdi:timer-alert
            color: amber

      # Per-App Breakdown Cards
      - type: grid
        title: Czas wg aplikacji dzisiaj
        columns: 2
        square: false
        cards:
          - type: entities
            title: Bravia 65
            show_header_toggle: false
            entities:
              - entity: sensor.bravia_65_smarttube
                name: SmartTube
                icon: mdi:youtube
              - entity: sensor.bravia_65_youtube
                name: YouTube
                icon: mdi:youtube
              - entity: sensor.bravia_65_twitch
                name: Twitch
                icon: mdi:twitch
              - entity: sensor.bravia_65_magentatv
                name: MagentaTV
                icon: mdi:television-classic
              - entity: sensor.bravia_65_prime_video
                name: Prime Video
                icon: mdi:video-vintage
              - entity: sensor.bravia_65_jellyfin
                name: Jellyfin
                icon: mdi:filmstrip
              - entity: sensor.bravia_65_hdmi_tv
                name: HDMI / TV
                icon: mdi:video-input-hdmi
              - entity: sensor.bravia_65_launcher_wygaszacz
                name: Launcher / Wygaszacz
                icon: mdi:view-dashboard-outline

          - type: entities
            title: Bravia 55
            show_header_toggle: false
            entities:
              - entity: sensor.bravia_55_smarttube
                name: SmartTube
                icon: mdi:youtube
              - entity: sensor.bravia_55_youtube
                name: YouTube
                icon: mdi:youtube
              - entity: sensor.bravia_55_magentatv
                name: MagentaTV
                icon: mdi:television-classic
              - entity: sensor.bravia_55_prime_video
                name: Prime Video
                icon: mdi:video-vintage
              - entity: sensor.bravia_55_jellyfin
                name: Jellyfin
                icon: mdi:filmstrip
              - entity: sensor.bravia_55_videostar
                name: Videostar
                icon: mdi:play-box-multiple
              - entity: sensor.bravia_55_hdmi_tv
                name: HDMI / TV
                icon: mdi:video-input-hdmi
              - entity: sensor.bravia_55_launcher_wygaszacz
                name: Launcher / Wygaszacz
                icon: mdi:view-dashboard-outline

      # 24-Hour Visual Activity History
      - type: history-graph
        title: Aktywność aplikacji (ostatnie 24h)
        hours_to_show: 24
        entities:
          - entity: sensor.bravia_65_aktywna_aplikacja
            name: Bravia 65
          - entity: sensor.bravia_55_aktywna_aplikacja
            name: Bravia 55

      # Daily Limit Configuration Slider
      - type: entities
        title: Ustawienia limitu
        show_header_toggle: false
        entities:
          - entity: input_number.prog_czas_tv_dziennie
            name: Dzienny próg powiadomienia (godziny)

Dual Screen-Time Limit Alerts: iPhone Push + On-Screen TV Toast

Visibility is great, but true iOS Screen Time enforces intentionality with App Limits. When you exceed your chosen time, you get an explicit nudge.

We established a daily 4.0-hour threshold via an input_number helper:

input_number:
  prog_czas_tv_dziennie:
    name: "Dzienny próg czasu TV"
    min: 1.0
    max: 10.0
    step: 0.5
    unit_of_measurement: "h"
    icon: mdi:timer-alert

A template binary sensor monitors when daily time crosses this value:

template:
  - binary_sensor:
      - name: "Bravia 65 – Limit 4h"
        unique_id: bravia_65_limit_4h
        device_class: problem
        state: >-
          {{ states('sensor.bravia_65_czas_dzisiaj') | float(0) >= states('input_number.prog_czas_tv_dziennie') | float(4.0) }}

When this sensor trips to on, an automation fires a synchronized dual alert:

- id: "tv_bravia_65_limit_4h"
  alias: "Telewizory – Bravia 65 limit czasu 4h"
  description: "Wysyła powiadomienie na iPhone i ekran TV po przekroczeniu limitu czasu (raz dziennie)"
  trigger:
    - platform: state
      entity_id: binary_sensor.bravia_65_limit_4h
      to: "on"
  condition:
    - condition: template
      value_template: >-
        {{ this.attributes.last_triggered is none or this.attributes.last_triggered.date() < now().date() }}
  action:
    # 1. iPhone Push Notification with Deep Link to Dashboard
    - service: notify.mobile_app_iphone
      data:
        title: "Limit czasu TV – Bravia 65 (4h)"
        message: "Telewizor Bravia 65 działa dzisiaj już ponad 4 godziny."
        data:
          url: "/tv-dashboard/telewizory"

    # 2. On-Screen Android TV Notification Banner
    - service: shell_command.tv_notify_bravia_65

Let's examine why both notification channels are crucial:

1. The iPhone Push Notification with Deep Linking

Via Home Assistant Companion (notify.mobile_app_iphone), the alert immediately reaches our phones. By providing url: "/tv-dashboard/telewizory", tapping the push banner opens the Home Assistant iOS app directly into the Telewizory dashboard. You don't have to navigate menus; you instantly see the app breakdown and timeline for why the alert triggered.

The condition this.attributes.last_triggered.date() < now().date() guarantees the notification fires strictly once per calendar day per television, preventing repetitive nagging.

2. Native On-Screen Android TV Banners over ADB

Sending a phone alert is helpful if you're in another room, but if you are sitting on the couch engrossed in a movie, you won't check your pocket. You need an on-screen prompt.

Most smart home setups rely on third-party Android TV notification apps (such as Notifications for Android TV / NFATV), which require side-loading an APK, keeping a background service running, and opening custom ports.

We bypassed third-party apps entirely by using Android's native command-line notification manager:

cmd notification post -S bigtext -t "Limit czasu TV (4h)" tv_limit_4h "Telewizor Bravia 65 działa już dzisiaj ponad 4 godziny."

In tv_adb_monitor.py, the notify subcommand connects via AdbDeviceTcp, executes cmd notification post, and disconnects:

def send_tv_notification(ip: str, title: str, message: str, timeout_s: float = 4.0) -> bool:
    """Send an on-screen notification to the TV via adb_shell."""
    from adb_shell.adb_device import AdbDeviceTcp

    signer = _get_adb_signer()
    if not signer:
        return False

    device = None
    try:
        device = AdbDeviceTcp(ip, 5555, default_transport_timeout_s=timeout_s)
        device.connect(rsa_keys=[signer], auth_timeout_s=timeout_s)
        cmd = f"cmd notification post -S bigtext -t {shlex.quote(title)} tv_limit_4h {shlex.quote(message)}"
        device.shell(cmd, transport_timeout_s=timeout_s, read_timeout_s=timeout_s)
        return True
    except Exception:
        return False
    finally:
        if device:
            try:
                device.close()
            except Exception:
                pass

And Home Assistant invokes it via a simple shell_command:

shell_command:
  tv_notify_bravia_65: 'python3 /config/scripts/tv_adb_monitor.py notify 192.168.1.58 "Limit czasu TV (4h)" "Telewizor Bravia 65 działa już dzisiaj ponad 4 godziny."'
  tv_notify_bravia_55: 'python3 /config/scripts/tv_adb_monitor.py notify 192.168.1.19 "Limit czasu TV (4h)" "Telewizor Bravia 55 działa już dzisiaj ponad 4 godziny."'

Because cmd notification post is a core Android OS binary, the notification displays as an elegant, non-intrusive heads-up banner in the top-right corner of the television. It overlays cleanly across any active app—even 4K HDR playback in SmartTube or Prime Video—without interrupting audio or dropping video frames.


The Reality Check: What the Data Revealed

After running the Screen Time monitoring engine across both Bravia OLEDs for a full week, the resulting data yielded fascinating insights into household screen habits:

  1. The "Passive Screen" Phenomenon: On average, nearly 35% of daily "TV on" time was not active video streaming, but the television idling on Projectivy Launcher or the screensaver while someone stepped away to cook or read. By capturing both active apps and the launcher/screensaver state, our total uptime metric provided an honest appraisal of actual display usage.
  2. Streaming App Distribution: Rather than generic "TV time", having exact per-app hours showed clear patterns—SmartTube accounted for the vast majority of weekday evening viewing, while streaming services dominated weekend afternoons.
  3. The Power of the On-Screen Toast: An iPhone notification is easy to swipe away and ignore. But an on-screen toast appearing directly over the television screen at the 4-hour mark is remarkably effective at prompting someone to hit the power button and head outside.

Summary & Takeaways

By stepping outside standard smart home abstractions and treating Android TV like the full Linux/Android system it is, we brought true iOS-style Screen Time to our living room displays:

  • Zero Cloud or Cast Dependencies: Lightweight ADB polling over local LAN via pure-Python adb_shell.
  • Zero Annoying Prompts: Reusing existing RSA key pairs to connect silently without triggering debugging dialogs.
  • Robust State Engine: Handling screensavers and transient volume bar focus with dumpsys power, dumpsys dreams, and dumpsys window displays.
  • Declarative Home Assistant Architecture: history_stats sensors automatically managing daily resets at midnight, paired with a dedicated YAML Lovelace dashboard.
  • Actionable Dual Alerts: Deep-linked iPhone push notifications paired with native on-screen Android TV banners.

If you have an Android TV or Google TV in your home and want to demystify where your evening hours go, you don't need proprietary cloud subscriptions or invasive surveillance software. A few lines of Python and Home Assistant's native history sensors are all it takes to take back control of your screen time.


The AI-SDLC Blueprint (How This Was Engineered)

Every project on this blog is built using a deterministic, spec-driven AI Software Development Life Cycle (SDLC) — turning autonomous coding agents into disciplined production engineering pipelines with zero architectural drift.

  • Production Footprint: Python ADB foreground-app monitor + Home Assistant history_stats & dual-alert automations
  • Verification & Quality Gate: Automated unit test suite (test_tv_adb_monitor.py) + live ADB state-transition verification
  • Spec-First Governance: 1 design specs & 1 step-by-step TDD implementation plans written before code
  • Agentic Stack: Gemini 4 Argon (High) orchestrated in AGY
  • Spec-first design solved Android TV's lack of native Screen Time APIs by combining lightweight ADB window-focus polling with Home Assistant history_stats sensors.
  • TDD unit suite (test_tv_adb_monitor.py) verified dumpsys window parsing edge cases across YouTube, Netflix, PS5 HDMI inputs, and standby states before deployment.
  • Dual-channel enforcement delivers both mobile push notifications and on-screen TV toast overlays when daily app budgets are exceeded.

Proof of Work (Specs, Plans & Source Code): Explore the complete case study repository on GitHub →

Authorship & Proof-of-Work Disclosure (An Amplifier of Intent, Not a Source of Ideas): The prose and implementation code on this blog are generated by AI agents operating as hyper-literal contractors with encyclopedic memory and zero agency—while 100% of the problem selection, creative direction, architectural boundaries, and verification gates originate from my mind. As Sean Goedecke argues in Writing Is No Longer Proof of Work, real engineering proof of work is system effectiveness and verifiable outcomes, not hours spent manually wordsmithing sentences. Read the full AI-SDLC Authorship Manifesto →