Skip to content

Add automatic display brightness - #8025

Open
s0up4200 wants to merge 11 commits into
omacom:quattrofrom
s0up4200:feat/automatic-brightness
Open

s0up4200 wants to merge 11 commits into
omacom:quattrofrom
s0up4200:feat/automatic-brightness

Conversation

@s0up4200

@s0up4200 s0up4200 commented Aug 24, 2026 •

Copy link
Copy Markdown

What changed

  • Adds omarchy brightness auto on|off|toggle|status commands and an opt-in user service.
  • Reads ambient light from IIO sensors to adjust matching internal or external displays.
  • Controls connected Apple displays as one brightness group when they share an Apple ambient-light sensor.
  • Adds an accessible automatic-brightness toggle to the Display panel. The toggle stays visible while the feature is on, so you can turn it off after the sensor is gone.
  • Treats manual brightness changes as a new baseline, restoring that level when ambient light returns to its previous range.
  • Pauses a built-in sensor while the lid is closed. A sensor under a closed lid reads dark. In clamshell mode Omarchy disables the internal panel, and the sensor would then drive the external display toward its minimum. The lid is checked before a session starts. Closing the lid disables the panel, Hyprland sends monitorremoved, and the running session ends. The check does not affect Apple display sensors.

The service prefers the Apple display sensor for Apple Studio Display, Pro Display XDR, and supported Apple Cinema Display models. Generic sensors control the internal display or the only active display.

Polling

The service reads the light sensor from sysfs once per second, because a user service gets no change signal for that value. The IIO buffer needs root setup and allows only one reader. The Apple Silicon sensor has no buffer. iio-sensor-proxy, which GNOME and KWin use, reads the same value every 0.7 to 0.8 seconds and exposes only one sensor. Between reads, the service waits on the Hyprland event stream, and it checks the monitors only after a monitor event. A read in steady light starts no process.

Development

OpenAI GPT-5.6 Sol wrote the first version at xhigh reasoning effort under my supervision. Claude Opus 5.5 wrote the Apple display cache, the event loop, the fixes from the review, and the lid guard under my supervision. The guard is based on a patch from @cb2206.

Packaging

No package change is needed. omarchy brightness auto on installs the unit into ~/.config/systemd/user before it enables the service, and off removes it again, as omarchy-audio-tuning does for its speaker unit.

Testing

  • ./test/all (191 test files) on the first version
  • test/shell.d/brightness-auto-test.sh, test/shell.d/brightness-display-test.sh, test/shell.d/config-test.sh and test/shell.d/monitor-test.sh after the merge of quattro
  • Live tested on dual Apple Studio Displays: enable and disable, dark and bright ambient-light response, manual baseline changes, synchronized brightness, and restart stability
  • Live check of the event loop on dual Apple Studio Displays: the controller takes control, and over 6 seconds of steady light it started no child process except the event-stream reader
  • Live check of the event loop with the Studio Display sensor covered by hand: the reading fell from about 173000 to about 1500 and brightness went from 74% to 23%; after uncovering, brightness rose back to 74%
  • One brightness key step on two Apple Studio Displays takes about 0.3 s with the display cache, down from about 1 s
  • The live tests above ran before the review fixes. Those fixes change how a manual change sets the baseline.
  • test/shell.d/config-test.sh with an omarchy-pkgs checkout of 1efe4ea, so the unit check runs
  • Regression coverage for silent automatic writes during upgrades from an older display dispatcher
  • Removed test/shell.d/brightness-display-apple-cache-test.sh. It expected the old cache, which held one device, and it failed on a host with an Apple display. brightness-display-test.sh covers its checks for the new cache.
  • test/shell.d/brightness-auto-test.sh with OMARCHY_PATH unset, after the review fixes
  • Lid guard: a unit test for clamshell mode. With the lid closed, a built-in sensor starts no session. After the lid opens, it starts one. An Apple sensor starts one with the lid closed. Each case fails when its part of the check is removed. Not live tested, because this machine has only Apple display sensors.
  • Hyprland 0.56.2 source: a config reload that disables a connected monitor posts monitorremoved and monitorremovedv2 (Monitor.cpp onDisconnect), and re-enabling it posts monitoradded
  • Hyprland 0.56.2 sends no event on the event socket for a DPMS change: hl.dsp.dpms disable and enable on a headless monitor produced no event, and hyprctl reload in the same capture produced configreloaded

Copilot AI balanced review requested due to automatic review settings August 24, 2026 10:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds ambient-light-driven automatic brightness with CLI/service controls and Display panel integration.

Changes:

  • Adds sensor discovery, brightness adjustment, and service controls.
  • Integrates an accessible automatic-brightness toggle.
  • Adds locking, packaging checks, and automated tests.

Tip

If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.

Reviewed changes

Copilot reviewed 7 out of 9 changed files in this pull request and generated no comments.

Show a summary per file
File Description
bin/omarchy-brightness-auto Implements automatic brightness control.
bin/omarchy-brightness-display Adds coordinated nonblocking writes.
default/systemd/user/omarchy-brightness-auto.service Defines the opt-in user service.
shell/plugins/panels/monitor/Model.js Parses automatic-brightness status.
shell/plugins/panels/monitor/Panel.qml Adds the Display panel toggle.
test/shell.d/brightness-auto-test.sh Tests sensors, controls, and reconnects.
test/shell.d/brightness-display-test.sh Tests brightness locking behavior.
test/shell.d/config-test.sh Checks service packaging.
test/shell.d/monitor-test.sh Tests status parsing.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@cb2206

cb2206 commented Sep 30, 2026

Copy link
Copy Markdown

Tested this on a MacBook Pro 14" M1 Pro (Asahi apple,j314s, Omarchy 4.0.3rc4, Hyprland 0.56.2), where the built-in ambient light sensor is the AOP ALS (aop-sensors-als, in_illuminance_input in lux, no _raw/_scale). Ran b9e38132 locally as a user service, with the --nonblocking hunk merged into omarchy-brightness-display.

Works as-is on Apple Silicon. find_sensor picks the ALS and skips the lid-angle IIO device next to it, select_monitor picks eDP-1, and status reports supported. With the sensor fully covered, lux went 368 → 0 and the panel ramped 96 % → 21 % in about 28 s (3 %/s cap). Uncovered, it went back to 93 % in about 26 s. The manual baseline held: I run the panel at 95 % in a ~270 lx room, and it kept that level instead of pulling it down to the 33 % curve value. Panel brightness does not bias this sensor: lux stayed at 260-270 across panel 10-100 %.

Two things I changed locally, which you may want here:

  1. Pause a built-in sensor when it can't see the room. Covers the same cases Follow the T1 ambient light sensor for panel and keyboard backlight #10331 guards against on T1 Macs:

    • Internal panel DPMS-off: a blanked panel can read darker than the room, and the dim target is what you see on wake.
    • Clamshell: with the lid closed, Omarchy disables eDP-1. select_monitor then falls back to "the only active display", so a generic built-in sensor under a closed lid would drive the external monitor toward its minimum.

    The check (sensor_obscured) only applies to generic sensors, so Apple display sensors are unaffected. It asks about the lid only when no internal panel is lit, and it is also checked before a session starts. On my machine a real idle lock (with its DPMS cycle) logged paused then resumed 2 s later.

  2. Fewer forks per poll. The 1 s loop runs hyprctl, jq and three awk every second; with the guard added it measured 3.6 % of a core here. One hyprctl monitors -j per poll is now shared by the guard and select_monitor (optional JSON argument, still self-fetching when called alone). The lux of an _input channel is read with bash read (read_lux stays the fallback), and smoothing plus curve are one awk (smooth_and_curve, output checked identical to smooth_lux + curve_brightness). That brings it to 1.7 %.

Tests: test/shell.d/brightness-auto-test.sh passes with the change, plus three new cases: the guard decisions, no generic writes while the panel is off (Apple sensor still writes), and no session in clamshell mode. I checked that each new case fails with its guard removed. I did not run the full ./test/all.

Not tested: closing the lid with an external display attached on real hardware (the clamshell path is covered by the unit test only), and the Display-panel toggle (I didn't install the QML part).

Patch on top of b9e3813 (bin/omarchy-brightness-auto, test/shell.d/brightness-auto-test.sh)
diff --git i/bin/omarchy-brightness-auto w/bin/omarchy-brightness-auto
index 297538f9..bbfe806b 100755
--- i/bin/omarchy-brightness-auto
+++ w/bin/omarchy-brightness-auto
@@ -183,9 +183,9 @@ step_toward() {
 
 select_monitor() {
   local kind="$1"
-  local monitors=""
+  local monitors="${2:-}"
 
-  monitors="$(hyprctl monitors -j 2>/dev/null)" || return 1
+  [[ -n $monitors ]] || monitors="$(hyprctl monitors -j 2>/dev/null)" || return 1
   jq -er --arg kind "$kind" '
     [.[] | select(.disabled == false)] as $active
     | if $kind == "apple" then
@@ -237,6 +237,39 @@ log_state() {
   log_message "$status"
 }
 
+# A closed lid covers a built-in sensor, and a blanked panel can read darker
+# than the room (seen on T1 Macs), so either would drive a wrong target. The
+# lid is only asked about when no internal panel is lit (clamshell disables it).
+sensor_obscured() {
+  local monitors="${1:-}"
+  local internal=""
+
+  [[ -n $monitors ]] || monitors="$(hyprctl monitors -j 2>/dev/null)" || return 1
+  internal="$(jq -r '[.[] | select(.name | test("^(eDP|LVDS|DSI)-"))] | if length == 0 then "none" elif any(.dpmsStatus == false) then "off" else "on" end' <<<"$monitors" 2>/dev/null)"
+  case "$internal" in
+  on) return 1 ;;
+  off) return 0 ;;
+  esac
+  omarchy-hw-laptop-closed
+}
+
+# One awk per poll instead of two: prints the smoothed lux and its curve target.
+smooth_and_curve() {
+  awk \
+    -v old="$1" \
+    -v lux="$2" \
+    -v new_weight="$smoothing_new_weight" \
+    -v center_percent="$curve_center_percent" \
+    -v percent_per_octave="$curve_percent_per_octave" \
+    -v center_lux="$curve_center_lux" '
+      BEGIN {
+        smoothed = old * (1 - new_weight) + lux * new_weight
+        value = smoothed < 0.1 ? 0.1 : smoothed
+        printf "%.10g %d\n", smoothed, int(center_percent + percent_per_octave * log(value / center_lux) / log(2) + 0.5)
+      }
+    '
+}
+
 control_session() {
   local sensor="$1"
   local kind="$2"
@@ -250,6 +283,8 @@ control_session() {
   local offset=""
   local next=""
   local mapped_monitor=""
+  local monitors=""
+  local channel=""
   local write_status=0
 
   lux="$(read_lux "$sensor")" || {
@@ -266,8 +301,16 @@ control_session() {
   last_auto="$current"
   log_state "controlling $monitor from $sensor at $current%"
 
+  channel="$(find_illuminance_channel "$sensor")" || channel=""
+
   while sleep "$poll_seconds"; do
-    mapped_monitor="$(select_monitor "$kind")" || {
+    monitors="$(hyprctl monitors -j 2>/dev/null)" || monitors="[]"
+    if [[ $kind == generic ]] && sensor_obscured "$monitors"; then
+      log_state "paused: lid closed or internal panel off"
+      continue
+    fi
+    [[ $last_status == paused:* ]] && log_state "resumed on $monitor"
+    mapped_monitor="$(select_monitor "$kind" "$monitors")" || {
       log_state "lost display $monitor"
       return 1
     }
@@ -275,12 +318,16 @@ control_session() {
       log_state "display mapping changed from $monitor to $mapped_monitor"
       return 1
     fi
-    lux="$(read_lux "$sensor")" || {
-      log_state "lost sensor $sensor"
-      return 1
-    }
-    smoothed_lux="$(smooth_lux "$smoothed_lux" "$lux")" || return 1
-    base_target="$(curve_brightness "$smoothed_lux")" || return 1
+    # A processed channel is already lux, so read it without an awk per poll.
+    if [[ $channel == *_input ]] && read -r lux <"$channel" 2>/dev/null && [[ $lux =~ ^[0-9]+([.][0-9]*)?$ ]]; then
+      :
+    else
+      lux="$(read_lux "$sensor")" || {
+        log_state "lost sensor $sensor"
+        return 1
+      }
+    fi
+    read -r smoothed_lux base_target < <(smooth_and_curve "$smoothed_lux" "$lux") || return 1
     target="$(target_with_offset "$base_target" "$offset")"
     needs_adjustment "$target" "$last_auto" || continue
 
@@ -316,6 +363,10 @@ controller_pass() {
     log_state "no ambient light sensor found"
     return 1
   fi
+  if [[ $kind == generic ]] && sensor_obscured; then
+    log_state "paused: lid closed or internal panel off"
+    return 1
+  fi
   monitor="$(select_monitor "$kind")" || {
     log_state "no unambiguous active monitor for $sensor"
     return 1
diff --git i/test/shell.d/brightness-auto-test.sh w/test/shell.d/brightness-auto-test.sh
index d77517c6..376c16a8 100755
--- i/test/shell.d/brightness-auto-test.sh
+++ w/test/shell.d/brightness-auto-test.sh
@@ -201,6 +201,77 @@ fi
 [[ ! -s $brightness_writes ]] || fail "display loss does not write a stale brightness target"
 pass "automatic brightness remaps after display loss under steady light"
 
+(
+  lid_file="$test_tmp/lid-closed"
+  printf '0\n' >"$lid_file"
+  omarchy-hw-laptop-closed() { [[ $(<"$lid_file") == 1 ]]; }
+
+  sensor_obscured '[{"name":"eDP-1","dpmsStatus":false}]' ||
+    fail "a blanked internal panel pauses a built-in sensor"
+  sensor_obscured '[{"name":"eDP-1","dpmsStatus":true}]' &&
+    fail "a lit internal panel does not pause a built-in sensor"
+  sensor_obscured '[{"name":"DP-1","dpmsStatus":true}]' &&
+    fail "an external display with the lid open does not pause a built-in sensor"
+  printf '1\n' >"$lid_file"
+  sensor_obscured '[{"name":"DP-1","dpmsStatus":true}]' ||
+    fail "clamshell mode pauses a built-in sensor"
+  sensor_obscured '[{"name":"eDP-1","dpmsStatus":true}]' &&
+    fail "the lid is not asked while the internal panel is lit"
+  true
+)
+pass "automatic brightness knows when a built-in sensor is covered or dark"
+
+(
+  guard_writes="$test_tmp/guard-writes"
+  guard_sleeps="$test_tmp/guard-sleeps"
+  : >"$guard_writes"
+  printf '0\n' >"$guard_sleeps"
+  smoothing_new_weight=1
+  omarchy-hw-laptop-closed() { return 1; }
+  hyprctl() { printf '%s\n' '[{"name":"eDP-1","disabled":false,"dpmsStatus":false}]'; }
+  guard_reads="$test_tmp/guard-reads"
+  printf '0\n' >"$guard_reads"
+  read_lux() {
+    local count=""
+    read -r count <"$guard_reads"
+    printf '%s\n' "$(( count + 1 ))" >"$guard_reads"
+    (( count == 0 )) && printf '200\n' || printf '1\n'
+  }
+  read_brightness() { printf '80\n'; }
+  log_state() { :; }
+  sleep() {
+    local count=""
+    read -r count <"$guard_sleeps"
+    (( count < 3 )) || return 1
+    printf '%s\n' "$(( count + 1 ))" >"$guard_sleeps"
+  }
+  write_brightness() { printf '%s\n' "$2" >>"$guard_writes"; }
+
+  control_session ignored generic eDP-1 || true
+  [[ ! -s $guard_writes ]] || fail "a blanked internal panel stops generic-sensor writes" "$(cat "$guard_writes")"
+
+  printf '0\n' >"$guard_sleeps"
+  printf '0\n' >"$guard_reads"
+  control_session ignored apple eDP-1 || true
+  [[ -s $guard_writes ]] || fail "an Apple display sensor keeps working while the internal panel is off"
+)
+pass "automatic brightness pauses a built-in sensor while the internal panel is off"
+
+(
+  session_started="$test_tmp/clamshell-session"
+  : >"$session_started"
+  omarchy-hw-laptop-closed() { return 0; }
+  hyprctl() { printf '%s\n' '[{"name":"DP-1","disabled":false,"dpmsStatus":true}]'; }
+  find_sensor() { printf '%s generic\n' "$generic_sensor"; }
+  control_session() { printf 'started\n' >"$session_started"; }
+  log_state() { :; }
+
+  controller_pass && fail "clamshell mode does not start a session"
+  [[ ! -s $session_started ]] || fail "clamshell mode does not drive an external display from a covered sensor"
+  true
+)
+pass "automatic brightness does not drive an external display from a closed lid"
+
 grep -Fx 'ExecStart=/usr/bin/omarchy-brightness-auto' "$unit" >/dev/null ||
   fail "automatic brightness unit runs the package command"
 grep -Fx 'WantedBy=graphical-session.target' "$unit" >/dev/null ||

🤖 Generated with Claude Code

Detection of the Apple displays took about half a second on each
brightness key press. Cache the detected group for each set of HID
nodes, and detect again after a failed read or write. The OSD shows the
written value, so a key press does not read every display again.
@greptile-apps

greptile-apps Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The changes affect automatic brightness within the user's graphical display session.

The panel-off regression and the remaining external-sensor block should be fixed before merging.

Findings

  1. P1 Screen wakes too dim ▶
  2. P1 External sensors stop working ▶

Summary

Adds opt-in automatic display brightness using ambient-light sensors.

  • Ambient light now adjusts a display through an opt-in service.
  • Supported Apple displays now share one brightness setting.
  • The Display panel now offers an automatic-brightness switch.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Display-panel toggle or CLI] --> B[User service]
  B --> C[Choose sensor and display]
  C --> D[Read ambient light]
  D --> E[Calculate brightness]
  E --> F[Write brightness]
  F --> D
Loading

Reviews (7) · Last reviewed commit: "Pause a built-in light sensor only while..." · Reviewed by Greptile

Comment thread bin/omarchy-brightness-auto Resolved
Comment thread bin/omarchy-brightness-auto Resolved
Comment thread shell/plugins/panels/monitor/Panel.qml Resolved
@omarchybot omarchybot removed the enhancement New feature or request label Oct 17, 2026
Comment thread bin/omarchy-brightness-auto Resolved
Comment thread shell/plugins/panels/monitor/Panel.qml Resolved
Comment thread bin/omarchy-brightness-display-apple Resolved
The loop ran hyprctl, jq, three awk processes and sleep every second.
It now waits on the Hyprland event stream, checks the monitors only
after a monitor event, and skips the math while the light is steady,
so a poll in steady light starts no process.
Comment thread bin/omarchy-brightness-auto Resolved
Comment thread bin/omarchy-brightness-auto Resolved
The service is opt-in, so the command now installs its unit into the
user config before it enables it, and removes the unit when it turns the
service off. The package no longer has to ship the unit, which the unit
check from quattro requires.
Comment thread bin/omarchy-brightness-auto Resolved
A manual change during a ramp is now the baseline for the current light. If the brightness lock skips a write, the controller tries it again after the light settles. Fractional lux readings keep their precision in dim light. The Display panel shows the switch while the feature is on, so you can turn it off when the sensor is gone. Remove the Apple cache test, because it expects the old cache format.
If OMARCHY_PATH is not set, the test stopped when it sourced the command under set -u, before it ran a check. The command now builds the unit path only in the on step.
A closed lid covers a built-in sensor. When the lid closes, Omarchy disables
the internal panel. The controller then drives the only active display, which
is the external monitor. The sensor reads dark, so the external monitor goes
toward its minimum. A blanked panel can also read darker than the room, and
the user sees the dim value on wake.

The guard comes from a tester's patch on the PR. It applies only to a generic
sensor. It does not affect Apple display sensors.

Hyprland 0.56.2 sends no socket2 event when DPMS changes. A test with
hl.dsp.dpms on a headless monitor showed this. Thus the session checks the
lid and the panel only when the sensor reading changes by more than 1%. A
closed lid or a blanked panel makes the reading drop, so the check runs at
that time. In steady light, a poll still starts no process. A session does
not start while the sensor is covered.
Comment thread bin/omarchy-brightness-auto Resolved
@greptile-apps

greptile-apps Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

The previous commit also paused a built-in sensor while the internal panel
was off, and it checked the panel each time the reading changed by more than
1%. A pause from that check ended only when the reading jumped again. A
sensor that does not see its own panel, such as the M1 Pro sensor that a
tester measured, gives no jump on wake. In steady light, automatic brightness
then stayed off. No measurement shows that a blanked panel reads darker, so
this commit removes that check and the paused state.

The lid check now runs after the monitor query. When the lid closes, Omarchy
disables the internal panel, and Hyprland sends monitorremoved. A session
that maps a display before that event gets the event and ends. The next pass
sees the closed lid and starts no session. The check does not affect Apple
display sensors.
@s0up4200

Copy link
Copy Markdown
Author

thanks for testing on Apple Silicon, and for the patch 😄

the fork part landed in a different form in 086c9b4, the loop waits on the Hyprland event stream now and reads the sensor with a bash read each poll. awk only runs when the reading moves more than 1%, and monitors are only checked after a monitoradded/monitorremoved event, so steady light starts no process

the lid part is in 6c72999. with an external display connected, closing the lid makes Omarchy disable the laptop panel, Hyprland sends monitorremoved, the session ends, and the next pass sees the closed lid and doesn't start one. Apple sensors aren't affected

I left the DPMS part out. Hyprland 0.56.2 sends no event for DPMS, so it would need a check on every poll, and your M1 Pro numbers show the panel doesn't bias the sensor. if you can measure a blanked panel reading darker, post the before/after lux and I'll add it

Comment thread bin/omarchy-brightness-auto Resolved
@maxffarrell

Copy link
Copy Markdown

Tested on a Dell XPS 13 9345 (Snapdragon X Elite), with a few changes I'd like to offer.

Its light sensor sits behind the Qualcomm sensor core. It has no IIO sysfs channel and is only reachable through iio-sensor-proxy; packaging for that is in omacom/omarchy-pkgs#3364. I ran this PR against that sensor through iio-sensor-proxy, which needed three changes. A fourth fixes a problem that affects IIO sensors too.

  1. Read iio-sensor-proxy when no IIO illuminance channel exists. find_sensor falls back to the proxy when HasAmbientLight is true. A monitor-sensor --light child holds the claim, and its output is read with read -t on its descriptor, so steady light starts no process. The first real reading gets one second to replace the cached value.
  2. Claim again when the proxy restarts. iio-sensor-proxy 3.9 takes its bus name before it has found the sensor. A claim in that window, which is exactly when monitor-sensor reclaims after suspend, is never served and blocks every later claim. The upstream fix is under review in iio-sensor-proxy!415. Until then the controller drops its claim and claims again once HasAmbientLight is true, keeping the session and its offset. With the real proxy and sensor on a private bus: 0 of 3 restarts recovered before this change, and 10 of 10 after.
  3. Notice manual changes when they happen. Today a brightness-key change is only noticed at the next adjustment, and the offset is then computed against the new light. Set 30% in room light (16 lux), shine a light at the sensor, take it away, and the display ends at 1%. Reading the kernel backlight level each poll (a bash read from sysfs, no process) and taking the offset against the light the level was chosen in brings it back to 31%. This one applies to IIO sensors as well.
  4. Keep the curve within 1–100% before adding the offset. At 0.1 lux the curve gives about -52%, so a level set in the dark learned an offset of +60 and sent the display to the top once the room was lit.
Diff against 6c72999 (bin/omarchy-brightness-auto only)
--- a/bin/omarchy-brightness-auto
+++ b/bin/omarchy-brightness-auto
@@ -10,12 +10,17 @@
 change_threshold=2
 max_step=3
 poll_seconds=1
+proxy_settle_seconds=2
 retry_seconds=5
+backlight_root=${OMARCHY_AUTO_BRIGHTNESS_BACKLIGHT_ROOT:-/sys/class/backlight}
 iio_root=${OMARCHY_AUTO_BRIGHTNESS_IIO_ROOT:-/sys/bus/iio/devices}
 service=omarchy-brightness-auto.service
 unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$service"
 last_status=""
 events=""
+proxy=""
+proxy_pid=""
+proxy_lux=""
 next_tick=0
 monitors_changed=0
 
@@ -85,8 +90,83 @@
     [[ -n $fallback ]] || fallback="$sensor"
   done
 
-  [[ -n $fallback ]] || return 1
-  printf '%s generic\n' "$fallback"
+  if [[ -n $fallback ]]; then
+    printf '%s generic\n' "$fallback"
+  elif proxy_has_light; then
+    printf 'proxy generic\n'
+  else
+    return 1
+  fi
+}
+
+proxy_has_light() {
+  local value=""
+
+  value="$(busctl --system get-property net.hadess.SensorProxy /net/hadess/SensorProxy \
+    net.hadess.SensorProxy HasAmbientLight 2>/dev/null)" || return 1
+  [[ $value == "b true" ]]
+}
+
+# monitor-sensor holds the claim. It prints a cached value first, which can predate the claim, so give
+# the first real reading a second to replace it.
+open_proxy() {
+  local line=""
+
+  proxy_lux=""
+  exec {proxy}< <(exec stdbuf -oL monitor-sensor --light 2>/dev/null)
+  proxy_pid=$!
+  while IFS= read -r -t 1 -u "$proxy" line; do
+    if [[ $line =~ (value:|Light\ changed:)\ ([0-9]+(\.[0-9]+)?) ]]; then
+      proxy_lux="${BASH_REMATCH[2]}"
+    fi
+  done
+  [[ -n $proxy_lux ]]
+}
+
+close_proxy() {
+  [[ -n $proxy ]] || return 0
+  kill "$proxy_pid" 2>/dev/null
+  exec {proxy}<&-
+  proxy=""
+}
+
+# The proxy takes its bus name before it has found the sensor. A claim made
+# then is recorded without starting the sensor, and keeps every later claim
+# from starting it. monitor-sensor claims exactly then, so drop its claim and
+# make a new one once the proxy has settled. The session and the learned
+# offset carry on.
+reopen_proxy() {
+  local attempt=0
+
+  close_proxy
+  for (( attempt = 0; attempt < 15; attempt++ )); do
+    sleep "$proxy_settle_seconds"
+    if proxy_has_light; then
+      open_proxy && return 0
+      close_proxy
+    fi
+  done
+  return 1
+}
+
+# Status 2 means the proxy restarted and the claim has to be made again.
+drain_proxy() {
+  local line=""
+  local status=0
+
+  while true; do
+    if IFS= read -r -t 0.01 -u "$proxy" line; then
+      if [[ $line == *"iio-sensor-proxy appeared"* ]]; then
+        return 2
+      elif [[ $line =~ Light\ changed:\ ([0-9]+(\.[0-9]+)?) ]]; then
+        proxy_lux="${BASH_REMATCH[1]}"
+      fi
+    else
+      status=$?
+      (( status > 128 )) && return 0
+      return 2
+    fi
+  done
 }
 
 read_lux() {
@@ -97,6 +177,10 @@
   local raw=""
   local scale=1
 
+  if [[ $sensor == "proxy" ]]; then
+    printf '%s\n' "$proxy_lux"
+    return
+  fi
   channel="$(find_illuminance_channel "$sensor")" || return 1
   if [[ $channel == *_input ]]; then
     read -r input <"$channel" || return 1
@@ -142,6 +226,8 @@
         if (lux !~ /^[-+]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][-+]?[0-9]+)?$/) exit 1
         if (lux < 0.1) lux = 0.1
         target = int(center_percent + percent_per_octave * log(lux / center_lux) / log(2) + 0.5)
+        if (target < 1) target = 1
+        if (target > 100) target = 100
         print target
       }
     '
@@ -294,6 +380,18 @@
   log_message "$status"
 }
 
+# The kernel's raw levels, read without starting a process, so every poll can
+# notice the brightness keys.
+read_panel() {
+  local file=""
+  local level=""
+
+  panel=""
+  for file in "$backlight_root"/*/brightness; do
+    [[ -r $file ]] && read -r level <"$file" && panel+="$level "
+  done
+}
+
 control_session() {
   local sensor="$1"
   local kind="$2"
@@ -311,12 +409,18 @@
   local channel=""
   local raw=""
   local last_raw=""
+  local panel=""
+  local last_panel=""
 
-  channel="$(find_illuminance_channel "$sensor")" || {
-    log_state "unable to read sensor $sensor"
-    return 1
-  }
-  read -r last_raw <"$channel"
+  if [[ $sensor == "proxy" ]]; then
+    last_raw="$proxy_lux"
+  else
+    channel="$(find_illuminance_channel "$sensor")" || {
+      log_state "unable to read sensor $sensor"
+      return 1
+    }
+    read -r last_raw <"$channel"
+  fi
   lux="$(read_lux "$sensor")" || {
     log_state "unable to read sensor $sensor"
     return 1
@@ -330,6 +434,8 @@
   offset=$(( current - base_target ))
   last_auto="$current"
   target="$current"
+  read_panel
+  last_panel="$panel"
   log_state "controlling $monitor from $sensor at $current%"
 
   monitors_changed=0
@@ -346,10 +452,34 @@
         return 1
       fi
     fi
-    read -r raw <"$channel" || {
-      log_state "lost sensor $sensor"
-      return 1
-    }
+    read_panel
+    if [[ $panel != $last_panel ]]; then
+      last_panel="$panel"
+      current="$(read_brightness "$monitor")" || return 1
+      if (( current != last_auto )); then
+        # The last reading is the light the new level was chosen in.
+        smoothed_lux="$lux"
+        base_target="$(curve_brightness "$lux")" || return 1
+        offset=$(( current - base_target ))
+        last_auto="$current"
+        target="$current"
+      fi
+    fi
+    if [[ $sensor == "proxy" ]]; then
+      if ! drain_proxy; then
+        log_message "iio-sensor-proxy restarted, claiming the sensor again"
+        reopen_proxy || {
+          log_state "lost sensor $sensor"
+          return 1
+        }
+      fi
+      raw="$proxy_lux"
+    else
+      read -r raw <"$channel" || {
+        log_state "lost sensor $sensor"
+        return 1
+      }
+    fi
     # Steady light: the reading is about the same, the smoothing has settled,
     # and no write is still pending.
     if [[ $smoothed_lux == $lux ]] && ! reading_changed "$last_raw" "$raw" &&
@@ -384,6 +514,8 @@
     next="$(step_toward "$target" "$last_auto")"
     if write_brightness "$monitor" "$next"; then
       last_auto="$next"
+      read_panel
+      last_panel="$panel"
     else
       write_status=$?
       (( write_status == 75 )) && continue
@@ -419,9 +551,13 @@
   elif [[ $kind == generic ]] && omarchy-hw-laptop-closed; then
     log_state "paused: lid closed"
     status=1
+  elif [[ $sensor == "proxy" ]] && ! open_proxy; then
+    log_state "no reading from iio-sensor-proxy"
+    status=1
   else
     control_session "$sensor" "$kind" "$monitor" || status=$?
   fi
+  close_proxy
   exec {events}<&-
   return "$status"
 }

What was tested: the XPS's real sensor and backlight with the service running since 21 November, through a suspend and resume, plus stand-in tests for the cases above. Not tested: the Apple and DDC paths, or an IIO sensor with these changes. The diff keeps --nonblocking: my copy ran without it, because that part of this PR isn't in my Omarchy.

Filed by Claude Opus 5.5 via Claude Code.

@roehrbacher

Copy link
Copy Markdown

Hi, thanks for working on this! One thing I found on my Dell XPS 14 (2026, Intel ISH light sensor) that might save you some debugging.

Your 1 s poll is the right rate for this sensor. But if in_illuminance_raw is read twice less than about 0.45 s apart, the ISH firmware gets stuck returning 0 lux for a while. That shows up as random dims to dark and then back. Reading at most once a second fixed it completely for me (0 false zeros since). As far as I can see the loop here does a back-to-back double read at start and whenever the raw value moves, so it could hit exactly this on XPS machines.

I run a separate plugin that does screen and keyboard backlight together with macOS-style fades, details in #19982, code at https://github.com/roehrbacher/omarchy-auto-brightness (MIT). Take whatever is useful. cc #13148 since the keyboard side reads the same sensor.

This comment was written by Grok Bot.

@Cynnamoroll

Copy link
Copy Markdown
Contributor

I tested 6c729990 locally: 55 focused checks passed. In a simulated IIO setup with one internal panel, I manually set brightness to 45% at 200 lux, then changed the light to 3,200 lux and back to 200. Brightness settled at 16% instead of returning to 45%. This was a simulated test, not hardware validation.

I also found four content conflicts against quattro at 0d649d8d. Would you welcome help resolving them and adding a regression test for the manual brightness behavior?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants