<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Engineering Dispatches]]></title><description><![CDATA[Technical field notes on systems programming, local-first software, defensive automation, and open-source architecture by Aditya Chavan.]]></description><link>https://aditya8242.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6afffbde83c1bd0db6134fa9/4cbc2e4e-0140-4907-b460-08d8199a808e.png</url><title>Engineering Dispatches</title><link>https://aditya8242.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 22 Nov 2026 14:56:42 GMT</lastBuildDate><atom:link href="https://aditya8242.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Why Modern Screen Time is Mathematically Flawed: Building a Local-First Cross-Device Interval Engine in Python and Kotlin]]></title><description><![CDATA[How existing trackers double-count screen time, and how I built a local-first cross-device interval union engine in Python and Kotlin using SQLite WAL]]></description><link>https://aditya8242.hashnode.dev/why-modern-screen-time-is-mathematically-flawed-building-a-local-first-cross-device-interval-engine-in-python-and-kotlin</link><guid isPermaLink="true">https://aditya8242.hashnode.dev/why-modern-screen-time-is-mathematically-flawed-building-a-local-first-cross-device-interval-engine-in-python-and-kotlin</guid><category><![CDATA[Open Source]]></category><category><![CDATA[Python]]></category><category><![CDATA[Android]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Aditya]]></dc:creator><pubDate>Fri, 20 Nov 2026 08:32:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afffbde83c1bd0db6134fa9/27c3de06-331d-4a9b-96ca-5e0471a9d538.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most screen time tools suffer from a fundamental mathematical flaw: they compute total screen exposure by summing independent device scalars rather than calculating the union of overlapping time intervals.</p>
<p>If you spend two hours working on a laptop while occasionally responding to messages on your phone for 30 minutes, standard digital wellbeing trackers report 2 hours and 30 minutes of screen time. Your biological eyes were exposed to displays for exactly 2 hours, with 30 minutes spent in a state of multi-device fragmentation ("second-screening").</p>
<p>To solve this, I built <strong>OmniScreen</strong>: an open-source, local-first engine for Windows and Android that synchronizes active screen sessions over your local Wi-Fi network and computes the mathematical interval union with zero cloud servers and zero telemetry.</p>
<p>Here is a breakdown of the mathematics, the local-first architecture, and the systems engineering behind it.</p>
<hr />
<h2>1. The Mathematical Problem: Scalar Sum vs. Interval Union</h2>
<p>Every operating system measures screen activity as discrete active sessions:</p>
<pre><code class="language-text">Session S = [t_start, t_end]
</code></pre>
<p>When aggregating screen time across multiple devices, existing digital wellbeing dashboards compute the naive sum:</p>
<pre><code class="language-text">Raw Exposure = Duration(Device 1) + Duration(Device 2) + ... + Duration(Device N)
</code></pre>
<p>When multiple devices are active simultaneously (for example, your laptop display is active while you check notifications on your phone), this naive scalar addition double-counts the overlapping period.</p>
<h3>The Correct Formulation: Interval Union</h3>
<p>True screen exposure is the measure of the mathematical union of all session intervals across all devices along a single real timeline:</p>
<pre><code class="language-text">True Exposure = Measure( Union of all [t_start, t_end] across Device 1 .. N )
</code></pre>
<p>Where overlapping intervals are merged into continuous spans so that 1 minute of real wall-clock time never counts as more than 1 minute of physical screen exposure.</p>
<p>From this, we can derive the exact duration of concurrent multi-screening:</p>
<pre><code class="language-text">Second-Screening Duration = Raw Exposure - True Exposure
</code></pre>
<p>We also compute an <strong>Attention Fragmentation Index</strong> (or Second-Screening Index, SSI):</p>
<pre><code class="language-text">Attention Fragmentation Index (SSI) = ( Second-Screening Duration / True Exposure ) * 100%
</code></pre>
<p>A high SSI indicates fragmented cognitive attention, where your focus was repeatedly split across multiple glowing displays simultaneously.</p>
<hr />
<h2>2. Implementing the Interval Union in O(N log N)</h2>
<p>To compute the interval union efficiently on a low-power local background daemon, we use a sorted sweep-line interval merge algorithm:</p>
<pre><code class="language-python">def calculate_interval_union(sessions: list[tuple[float, float]]) -&gt; float:
    """
    Computes the total non-overlapping duration from a list of [start_ts, end_ts] intervals.
    Time Complexity: O(N log N) due to sorting.
    Space Complexity: O(N) to store merged intervals.
    """
    if not sessions:
        return 0.0

    # 1. Sort intervals by start timestamp
    sorted_intervals = sorted(sessions, key=lambda x: x[0])

    merged = []
    current_start, current_end = sorted_intervals[0]

    for start, end in sorted_intervals[1:]:
        if start &lt;= current_end:
            # Overlapping or contiguous interval: extend the current boundary
            current_end = max(current_end, end)
        else:
            # Disjoint interval: commit previous interval and advance
            merged.append((current_start, current_end))
            current_start, current_end = start, end

    merged.append((current_start, current_end))

    # 2. Sum the durations of disjoint merged intervals
    return sum(end - start for start, end in merged)
</code></pre>
<p>Running this on thousands of raw session intervals takes less than 2 milliseconds on standard hardware, eliminating any CPU overhead on the host machine.</p>
<hr />
<h2>3. System Architecture: Local-First with SQLite WAL</h2>
<p>Screen time data is among the most sensitive personal telemetry possible: it records the exact minute you wake up, every application you switch to, and when you go to bed. Storing this on third-party cloud servers poses unacceptable privacy risks.</p>
<p>OmniScreen is architected strictly as a <strong>local-first system</strong>:</p>
<pre><code class="language-text">+-------------------------------------------------------------+
|                      Local Wi-Fi Network                    |
|                                                             |
|   +-------------------+              +------------------+   |
|   |   Android Agent   |  UDP Probe   |  Windows PC Hub  |   |
|   |  (Kotlin Sensor)  | -----------&gt; | (FastAPI+SQLite) |   |
|   |                   | &lt;----------- |                  |   |
|   |                   |  HTTP Sync   |                  |   |
|   +-------------------+              +------------------+   |
|                                                |            |
|                                                v            |
|                                         +--------------+    |
|                                         | SQLite (WAL) |    |
|                                         | Local Storage|    |
|                                         +--------------+    |
+-------------------------------------------------------------+
</code></pre>
<h3>Database Concurrency</h3>
<p>The local PC hub uses SQLite with <strong>Write-Ahead Logging (WAL)</strong> enabled:</p>
<pre><code class="language-python">conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA busy_timeout=15000")
</code></pre>
<ul>
<li>WAL mode allows concurrent readers (such as the web dashboard querying metrics) while background agent syncs write incoming sessions without locking the database file.</li>
<li>All administrative and mutating endpoints (<code>/api/device/delete</code>, <code>/api/device/rename</code>, <code>/api/tv/add</code>) enforce loopback checks (<code>require_localhost</code>), ensuring external network requests cannot modify device records even on an open Wi-Fi network.</li>
</ul>
<hr />
<h2>4. Native Device Sensors</h2>
<h3>Windows Win32 Agent</h3>
<p>The desktop background agent runs quietly in the Windows System Tray with zero terminal windows:</p>
<ul>
<li>Uses <code>ctypes</code> to call Win32 APIs: <code>GetForegroundWindow()</code>, <code>GetWindowTextW()</code>, and <code>GetWindowThreadProcessId()</code>.</li>
<li>Implements tick-gap detection: rather than assuming continuous usage, the polling loop calculates elapsed wall-clock time between iterations. If the system sleeps, hibernates, or locks, the gap is automatically detected and excluded from active session recording.</li>
</ul>
<h3>Android Companion Sensor</h3>
<p>On Android, query polling drains battery. Instead, OmniScreen uses native Kotlin with <code>UsageStatsManager.queryEvents()</code>:</p>
<ul>
<li>Queries raw OS events (<code>UsageEvents.Event.ACTIVITY_RESUMED</code> and <code>UsageEvents.Event.ACTIVITY_PAUSED</code>).</li>
<li>Clamps event boundaries strictly to local midnight (<code>00:00:00</code>) to prevent multi-day leakage.</li>
<li>Filters out system launchers and navigation overlays, tracking only genuine foreground applications.</li>
</ul>
<hr />
<h2>5. Local Wi-Fi Auto-Discovery: Eliminating Cloud Relays</h2>
<p>To allow the Android app to communicate with the PC hub without requiring static IP configurations or central accounts, OmniScreen implements a dual-discovery protocol:</p>
<ol>
<li><strong>UDP Broadcast Auto-Discovery:</strong><ul>
<li>The Android client broadcasts a lightweight discovery payload over UDP port <code>8766</code>.</li>
<li>The PC hub listens on <code>0.0.0.0:8766</code> and responds with its local LAN IP address and HTTP port (<code>8765</code>).</li>
<li>The Android client parses the response and initiates automated local syncing.</li>
</ul>
</li>
<li><strong>1-Tap QR Fallback:</strong><ul>
<li>The desktop dashboard generates a local QR code encoding <code>omniscreen://pair?host=&lt;LAN_IP&gt;:8765</code>.</li>
<li>Scanning the QR code with the phone camera deep-links directly into the Android app and establishes pairing in less than 2 seconds.</li>
</ul>
</li>
</ol>
<hr />
<h2>6. Open Source &amp; Key Takeaways</h2>
<p>Building OmniScreen reinforced several systems engineering principles:</p>
<ol>
<li><strong>Always question basic domain math:</strong> The double-counting error in digital wellbeing metrics had existed unchallenged simply because naive summation is easier to compute than interval unions.</li>
<li><strong>Local-first is performant and viable:</strong> Complex multi-device synchronization does not require cloud infrastructure or subscriptions. Local networks and SQLite WAL handle modern workloads effortlessly with zero latency.</li>
<li><strong>Security through minimal surface area:</strong> By refusing external cloud relays, all data remains on your physical hardware under your control.</li>
</ol>
<p>OmniScreen is 100% free and open source under the <strong>GNU General Public License v3.0 (GPL-3.0)</strong>.</p>
<ul>
<li><strong>GitHub Repository:</strong> <a href="https://github.com/aditya8242/omniscreen-agent">https://github.com/aditya8242/omniscreen-agent</a></li>
<li><strong>Windows &amp; Android Release:</strong> <a href="https://github.com/aditya8242/omniscreen-agent/releases/tag/v0.9-beta">v0.9-beta Releases</a></li>
</ul>
<p>Contributions, feedback on the interval math, and hardware compatibility reports are welcome on the GitHub issue tracker.</p>
]]></content:encoded></item></channel></rss>