-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1418 lines (1235 loc) · 52.2 KB
/
main.py
File metadata and controls
1418 lines (1235 loc) · 52.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import subprocess
import sys
import time
import json
import shutil
import yaml
import paho.mqtt.client as mqtt
import logging
import signal
import socket
import threading
import queue
import numpy as np
import pyaudio
import ctypes
# Suppress noisy ALSA errors from PyAudio hardware probing (they spam stderr with
# "Expression 'ret' failed in pa_linux_alsa.c" during device enumeration)
try:
_alsa_lib = ctypes.cdll.LoadLibrary('libasound.so.2')
_alsa_err_handler = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int,
ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p)
@_alsa_err_handler
def _alsa_noop_handler(filename, line, function, err, fmt):
pass
_alsa_lib.snd_lib_error_set_handler(_alsa_noop_handler)
except Exception:
pass # Not on Linux or libasound not available — no-op
# Load configuration
config_path = os.path.join(os.path.dirname(__file__), "config.yaml")
if not os.path.exists(config_path):
logging.error(
"config.yaml not found. Copy config.example.yaml to config.yaml and fill in your settings."
)
sys.exit(1)
with open(config_path, "r") as file:
config = yaml.safe_load(file)
# Configure logging based on debug setting
DEBUG_MODE = config.get("debug", False)
logging.basicConfig(
level=logging.DEBUG if DEBUG_MODE else logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)
if DEBUG_MODE:
os.environ["SMARTFRAME_DEBUG"] = "1"
logging.debug("DEBUG MODE ENABLED: Subprocess output will be visible.")
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
mqtt_config = config.get("mqtt", {})
MQTT_BROKER = mqtt_config.get("broker", "[MQTT_SERVER_IP_ADDRESS]")
MQTT_PORT = mqtt_config.get("port", 1883)
MQTT_COMMAND_TOPIC = mqtt_config.get("topic", "smartframe/set_mode")
MQTT_STATE_TOPIC = mqtt_config.get("state_topic", "smartframe/mode_state")
MQTT_STATUS_TOPIC = mqtt_config.get("status_topic", "smartframe/status")
MQTT_AVAILABLE_MODES_TOPIC = mqtt_config.get(
"available_modes_topic", "smartframe/modes_available"
)
MQTT_DISCOVERY_PREFIX = mqtt_config.get("discovery_prefix", "homeassistant")
MQTT_BRIGHTNESS_COMMAND_TOPIC = mqtt_config.get(
"brightness_topic", "smartframe/set_brightness"
)
MQTT_BRIGHTNESS_STATE_TOPIC = mqtt_config.get(
"brightness_state_topic", "smartframe/brightness_state"
)
MQTT_CONTRAST_COMMAND_TOPIC = mqtt_config.get(
"contrast_topic", "smartframe/set_contrast"
)
MQTT_CONTRAST_STATE_TOPIC = mqtt_config.get(
"contrast_state_topic", "smartframe/contrast_state"
)
MQTT_COLOR_PRESET_COMMAND_TOPIC = mqtt_config.get(
"color_preset_topic", "smartframe/set_color_preset"
)
MQTT_COLOR_PRESET_STATE_TOPIC = mqtt_config.get(
"color_preset_state_topic", "smartframe/color_preset_state"
)
MQTT_INPUT_SOURCE_COMMAND_TOPIC = mqtt_config.get(
"input_source_topic", "smartframe/set_input_source"
)
MQTT_INPUT_SOURCE_STATE_TOPIC = mqtt_config.get(
"input_source_state_topic", "smartframe/input_source_state"
)
MQTT_DBA_STATE_TOPIC = mqtt_config.get("dba_state_topic", "smartframe/audio/dba")
MQTT_USER = mqtt_config.get("username")
MQTT_PASS = mqtt_config.get("password")
MODES_DIR = os.path.join(os.path.dirname(__file__), "modes")
# Globals for state management
current_process = None
current_mode = "off"
mqtt_client = None
labwc_config_dir = None
_labwc_process = None # Persistent labwc compositor (reused across mode switches)
_labwc_wayland_display = None # WAYLAND_DISPLAY name for the persistent labwc session
audio_monitor_thread = None
command_queue = queue.Queue()
# Discovery cache to avoid repeated slow subprocess calls
CACHE_FILE = os.path.join(os.path.dirname(__file__), ".smartframe_cache")
CHROMIUM_PROFILE_DIR = os.path.join(os.path.dirname(__file__), ".chromium_profile")
_working_methods = {
"session_type": None,
"hdmi_output": None,
"labwc_path": None,
"hardware": [],
"brightness": 100,
"contrast": 50,
"color_preset": "6500 K",
"input_source": "HDMI-1",
"audio_device": None,
}
available_modes_cache = []
def get_available_modes():
"""List all available mode names from the modes directory (with memory caching)."""
global available_modes_cache
if available_modes_cache:
return available_modes_cache
modes = ["off"]
if os.path.exists(MODES_DIR):
for f in os.listdir(MODES_DIR):
if f.endswith("_mode.py") or f.endswith("_mode.sh"):
mode_name = f.replace("_mode.py", "").replace("_mode.sh", "")
if mode_name not in modes:
modes.append(mode_name)
available_modes_cache = sorted(modes)
return available_modes_cache
def _discover_audio_device():
"""Finds the best audio input device once and caches it (saves 1-2s of hardware probing)."""
global _working_methods
if _working_methods.get("audio_device") is not None:
return _working_methods["audio_device"]
try:
import pyaudio
p = pyaudio.PyAudio()
found_index = None
# Priority 1: Specifically look for the I2S hardware
device_count = p.get_device_count()
logging.debug(f"Probing {device_count} audio devices for I2S hardware...")
for i in range(device_count):
try:
info = p.get_device_info_by_index(i)
name = info.get('name', '').lower()
max_in = info.get('maxInputChannels', 0)
logging.debug(f"Testing device {i}: '{name}' (Max Inputs: {max_in})")
if max_in > 0:
if any(x in name for x in ['i2s', 'googlevoicehat', 'mono', 'inmp']):
found_index = i
logging.info(f"Discovered and matched I2S hardware: {info.get('name')} at index {i}.")
break
else:
logging.debug(f" - Device '{name}' does not match I2S keywords. Skipping.")
else:
logging.debug(f" - Device '{name}' has no input channels. Skipping.")
except Exception as e:
logging.debug(f" - Error probing device {i}: {e}")
continue
# Priority 2: Fallback to default input
if found_index is None:
logging.debug("No direct I2S match found. Attempting to use system default input...")
try:
default_info = p.get_default_input_device_info()
found_index = default_info.get('index')
logging.info(f"Falling back to system default audio input: {default_info.get('name')} (index {found_index})")
except Exception as e:
logging.debug(f"Default input acquisition failed: {e}")
pass
p.terminate()
if found_index is not None:
_working_methods["audio_device"] = found_index
_save_cache()
return found_index
except ImportError:
pass
except Exception as e:
logging.debug(f"Audio discovery failed: {e}")
return None
class AudioMonitor(threading.Thread):
"""Background thread that monitors ambient dB levels and reports to MQTT."""
def __init__(self, config, mq_client):
super().__init__(daemon=True)
self.config = config
self.mqtt_client = mq_client
self.running = True
self.chunk = 4096
self.rate = 48000
self.audio_config = config.get("audio", {})
self.dba_topic = config.get("mqtt", {}).get(
"dba_state_topic", "smartframe/audio/dba"
)
self.calibration_offset = self.audio_config.get("calibration_offset_db", 0)
self.last_publish = 0
def _get_a_weighting_gains(self, rate, chunk):
freqs = np.fft.rfftfreq(chunk, 1.0 / rate)
valid_freqs = np.where(freqs == 0, 1e-10, freqs)
f_sq = valid_freqs**2
const = (12194**2) * (f_sq**2)
den = (
(f_sq + 20.6**2)
* np.sqrt((f_sq + 107.7**2) * (f_sq + 737.9**2))
* (f_sq + 12194**2)
)
w = const / den
w *= 1.2589
w[0] = 0.0
return w
def run(self):
logging.info("Audio Monitor background thread started.")
p = pyaudio.PyAudio()
stream = None
bridge_file = "/tmp/smartframe_dba"
a_gains = self._get_a_weighting_gains(self.rate, self.chunk)
ema_a = 0.0
alpha = 1.0 - np.exp(-(self.chunk / self.rate) / 0.125) # Fast integration
while self.running:
# 1. First, check if Audio Mode is writing the value to our IPC bridge
use_bridge = False
db_a = None
if os.path.exists(bridge_file):
try:
# Check if the file is recent (less than 5 seconds old)
if time.time() - os.path.getmtime(bridge_file) < 5.0:
with open(bridge_file, "r") as f:
val = f.read().strip()
if val:
db_a = float(val)
use_bridge = True
# If we were using the mic, close it to free resources for audio_mode
if stream:
try:
stream.stop_stream()
stream.close()
except:
pass
stream = None
except Exception as e:
logging.debug(f"Monitor: Bridge file read failed: {e}")
if not use_bridge:
# 2. No bridge file. Check if Audio Mode is active.
# If Audio Mode is starting/running, we MUST NOT hold the mic.
if current_mode == "audio":
if stream:
try:
stream.stop_stream()
stream.close()
except:
pass
stream = None
# Wait for Audio Mode to start and create the bridge file
time.sleep(0.2)
continue
# 3. Try to use the microphone directly.
if not stream:
try:
idx = _discover_audio_device()
if idx is not None:
stream = p.open(
format=pyaudio.paInt16,
channels=1,
rate=self.rate,
input=True,
input_device_index=idx,
frames_per_buffer=self.chunk,
)
else:
time.sleep(5)
continue
except Exception as e:
logging.debug(f"Monitor: Failed to open device (busy?): {e}")
time.sleep(5)
continue
try:
raw_data = stream.read(self.chunk, exception_on_overflow=False)
data = np.frombuffer(raw_data, dtype=np.int16).astype(np.float32)
fft_complex = np.fft.rfft(data)
fft_aw = fft_complex * a_gains
data_aw = np.fft.irfft(fft_aw)
rms_a = np.sqrt(np.mean(data_aw**2))
if ema_a == 0:
ema_a = rms_a
else:
ema_a += alpha * (rms_a - ema_a)
db_a = (20 * np.log10(max(1e-9, ema_a))) + self.calibration_offset
if db_a < 45:
correction = 8.0 * (1.0 - (max(30, db_a) - 30) / 15)
db_a -= correction
except Exception as e:
logging.debug(f"Monitor Mic Loop Error: {e}")
if stream:
try:
stream.stop_stream()
stream.close()
except:
pass
stream = None
time.sleep(2)
continue
# 3. Publish result to MQTT (throttled to 1s for better responsiveness)
now = time.time()
if now - self.last_publish >= 1.0 and db_a is not None:
if self.mqtt_client and self.mqtt_client.is_connected():
try:
self.mqtt_client.publish(
self.dba_topic, f"{db_a:.1f}", retain=False
)
self.last_publish = now
except Exception:
pass
# Simple sleep to reduce CPU usage if we're not waiting on audio stream read
if use_bridge:
time.sleep(0.5)
if stream:
try:
stream.stop_stream()
stream.close()
except:
pass
p.terminate()
# Cleanup bridge file on exit
if os.path.exists(bridge_file):
try:
os.remove(bridge_file)
except:
pass
def _load_cache():
global _working_methods
if os.path.exists(CACHE_FILE):
try:
with open(CACHE_FILE, "r") as f:
data = json.load(f)
if isinstance(data, dict):
_working_methods.update(data)
logging.debug("Loaded display discovery cache.")
except Exception:
pass
def _save_cache():
try:
with open(CACHE_FILE, "w") as f:
json.dump(_working_methods, f)
except Exception:
pass
# Load discovery cache at startup (avoids disk reads on first mode transition)
_load_cache()
_display_env_detected = False
def _is_wayland_reachable(display_name):
"""Check if a Wayland socket is actually listening."""
runtime_dir = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
socket_path = os.path.join(runtime_dir, display_name)
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
s.settimeout(0.1)
s.connect(socket_path)
return True
except Exception:
return False
def setup_display_env(force=False):
"""Detect and validate the current display environment (Wayland/X11)."""
global _display_env_detected
if _display_env_detected and not force:
return
_load_cache()
# Ensure a persistent chromium profile exists for speed
if not os.path.exists(CHROMIUM_PROFILE_DIR):
os.makedirs(CHROMIUM_PROFILE_DIR, exist_ok=True)
logging.info(f"Created persistent Chromium profile at: {CHROMIUM_PROFILE_DIR}")
uid = os.getuid()
needs_save = False
def is_x11_active():
"""Check if X server is running by looking for the process."""
for pattern in ["Xorg", "X"]:
if (
subprocess.run(
["pgrep", "-u", str(uid), "-x", pattern], capture_output=True
).returncode
== 0
):
return True
return False
# 1. Validate environment
if "WAYLAND_DISPLAY" in os.environ:
if not _is_wayland_reachable(os.environ["WAYLAND_DISPLAY"]):
del os.environ["WAYLAND_DISPLAY"]
_working_methods["session_type"] = None
needs_save = True
if "DISPLAY" in os.environ:
if not is_x11_active():
del os.environ["DISPLAY"]
_working_methods["session_type"] = None
needs_save = True
# 2. Force default XDG_RUNTIME_DIR if missing
if "XDG_RUNTIME_DIR" not in os.environ:
os.environ["XDG_RUNTIME_DIR"] = f"/run/user/{uid}"
# 3. Auto-detection using cached session_type hint
if "WAYLAND_DISPLAY" not in os.environ and "DISPLAY" not in os.environ:
if _working_methods["session_type"] != "X11":
for i in range(2):
name = f"wayland-{i}"
if _is_wayland_reachable(name):
os.environ["WAYLAND_DISPLAY"] = name
if _working_methods["session_type"] != "Wayland":
_working_methods["session_type"] = "Wayland"
needs_save = True
_display_env_detected = True
if needs_save:
_save_cache()
return
if is_x11_active() and os.path.exists("/tmp/.X11-unix/X0"):
os.environ["DISPLAY"] = ":0"
if _working_methods["session_type"] != "X11":
_working_methods["session_type"] = "X11"
needs_save = True
if needs_save:
_save_cache()
_display_env_detected = True
def _get_hdmi_output_name():
global _working_methods
# 1. Use memory cache first
if getattr(_get_hdmi_output_name, "cached", None):
return _get_hdmi_output_name.cached
# 2. Use persistent cache second
if _working_methods.get("hdmi_output"):
_get_hdmi_output_name.cached = _working_methods["hdmi_output"]
return _working_methods["hdmi_output"]
try:
# 3. Slow discovery if nothing is cached
output = subprocess.check_output(
["wlr-randr"], stderr=subprocess.DEVNULL, timeout=1.5
).decode()
for line in output.split("\n"):
if "HDMI" in line and (line.strip() and not line.startswith(" ")):
name = line.split(" ")[0]
_get_hdmi_output_name.cached = name
_working_methods["hdmi_output"] = name
_save_cache()
return name
except Exception:
pass
return "HDMI-A-1" # Fallback
def set_display_power(state: bool):
"""Sets display power using discovered strategies, optimizing for speed and reliability."""
global _working_methods
target = "ON" if state else "OFF"
setup_display_env()
output_name = _get_hdmi_output_name()
# Strategy Definitions
session_strategies = [
(
"Wayland (wlr-randr)",
["wlr-randr", "--output", output_name, "--on" if state else "--off"],
lambda: "WAYLAND_DISPLAY" in os.environ,
),
(
"X11 (xset)",
["xset", "dpms", "force", "on" if state else "off"],
lambda: "DISPLAY" in os.environ,
),
]
hardware_strategies = [
(
"DDC/CI (Fast Off)",
["sudo", "ddcutil", "setvcp", "D6", "0x01" if state else "0x04"],
lambda: True,
),
(
"HDMI-CEC",
[
"sh",
"-c",
f'echo "{"on 0" if state else "standby 0"}" | cec-client -s -d 1',
],
lambda: True,
),
(
"Legacy (vcgencmd)",
["vcgencmd", "display_power", "1" if state else "0"],
lambda: True,
),
(
"FB Blanking",
[
"sudo",
"sh",
"-c",
f"echo {'0' if state else '1'} > /sys/class/graphics/fb0/blank",
],
lambda: os.path.exists("/sys/class/graphics/fb0/blank"),
),
]
def run_strategy(name, cmd):
try:
# Short timeout for cached methods, longer for discovery (3.5s is safe for Pi Zero I2C)
timeout = 3.5
res = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
if res.returncode != 0:
err = res.stderr.strip()
if "bus" in err.lower() and (
"busy" in err.lower() or "error" in err.lower()
):
logging.debug(
f"Display method '{name}' failed (Bus Busy/Error): {err}"
)
else:
logging.debug(
f"Display method '{name}' failed with code {res.returncode}: {err}"
)
return res.returncode == 0
except subprocess.TimeoutExpired:
logging.debug(f"Display method '{name}' timed out after {timeout}s")
return False
except Exception as e:
logging.debug(f"Display method '{name}' Exception: {e}")
return False
success_count = 0
needs_save = False
# 1. Execute Session Layer
if _working_methods.get("session_type"):
# Map cached session type to a specific strategy name
s_name = (
"Wayland (wlr-randr)"
if _working_methods["session_type"] == "Wayland"
else "X11 (xset)"
)
name, cmd_base, condition = next(
(s for s in session_strategies if s[0] == s_name), (None, None, None)
)
if name and condition() and run_strategy(name, cmd_base):
success_count += 1
else:
_working_methods["session_type"] = None
needs_save = True
if not success_count:
for name, cmd, condition in session_strategies:
if condition() and run_strategy(name, cmd):
_working_methods["session_type"] = (
"Wayland" if "Wayland" in name else "X11"
)
success_count += 1
needs_save = True
break
# 2. Execute Hardware Layer
hardware_success = False
# Try any previously working hardware methods from cache
if _working_methods["hardware"]:
for name in list(_working_methods["hardware"]):
name_check, cmd, _ = next(
(s for s in hardware_strategies if s[0] == name), (None, None, None)
)
if name_check and run_strategy(name_check, cmd):
success_count += 1
hardware_success = True
else:
logging.warning(
f"Cached display method '{name}' failed, removing from cache."
)
_working_methods["hardware"].remove(name)
needs_save = True
# If no cached hardware methods worked, try discovering and executing ALL possible hardware strategies
if not hardware_success:
for name, cmd, condition in hardware_strategies:
# Skip strategies we *just* tried and failed in the cached block
if name in _working_methods["hardware"]:
continue
if condition() and run_strategy(name, cmd):
logging.info(f"Discovered new display control strategy: {name}")
_working_methods["hardware"].append(name)
success_count += 1
hardware_success = True
needs_save = True
# Break early only for premium methods (DDC/CI or CEC) to avoid double-processing
if name in ["DDC/CI (Fast Off)", "HDMI-CEC"]:
break
if needs_save:
_save_cache()
if success_count == 0:
logging.error(f"Failed to set display power to {target}.")
else:
logging.info(f"Display set to {target} (Methods: {success_count})")
# If turned ON, restore all last known settings
if state:
set_display_brightness(_working_methods.get("brightness", 100), force=True)
set_display_contrast(_working_methods.get("contrast", 50), force=True)
set_display_color_preset(
_working_methods.get("color_preset", "Natural (6500 K)")
)
def set_display_brightness(value: int, force=False):
"""Sets display brightness using ddcutil with caching."""
global _working_methods
value = max(0, min(100, int(value)))
if not force and _working_methods.get("brightness") == value:
return True
logging.info(f"Setting display brightness to {value}%...")
if _run_vcp_command("10", str(value)):
_working_methods["brightness"] = value
_save_cache()
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_BRIGHTNESS_STATE_TOPIC, str(value), retain=True)
return True
return False
def set_display_contrast(value: int, force=False):
"""Sets display contrast using ddcutil (VCP 12)."""
global _working_methods
value = max(0, min(100, int(value)))
if not force and _working_methods.get("contrast") == value:
return True
logging.info(f"Setting display contrast to {value}%...")
if _run_vcp_command("12", str(value)):
_working_methods["contrast"] = value
_save_cache()
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_CONTRAST_STATE_TOPIC, str(value), retain=True)
return True
return False
def set_display_color_preset(preset_name: str):
"""Sets display color preset (VCP 14)."""
global _working_methods
presets = {
"sRGB": "01",
"Natural (6500 K)": "05",
"Warm (5000 K)": "04",
"Cool (9300 K)": "08",
}
hex_val = presets.get(preset_name)
if not hex_val:
return False
logging.info(f"Setting display color preset to {preset_name} ({hex_val})...")
if _run_vcp_command("14", "0x" + hex_val):
_working_methods["color_preset"] = preset_name
_save_cache()
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_COLOR_PRESET_STATE_TOPIC, preset_name, retain=True)
return True
return False
def set_display_input_source(source_name: str):
"""Sets display input source (VCP 60)."""
global _working_methods
sources = {"HDMI-1": "11", "HDMI-2": "12", "DisplayPort-1": "0f", "VGA": "01"}
hex_val = sources.get(source_name)
if not hex_val:
return False
logging.info(f"Switching input source to {source_name} ({hex_val})...")
if _run_vcp_command("60", "0x" + hex_val):
_working_methods["input_source"] = source_name
_save_cache()
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_INPUT_SOURCE_STATE_TOPIC, source_name, retain=True)
return True
return False
def _run_vcp_command(vcp_code, value):
"""Helper to run a ddcutil setvcp command."""
cmd = ["sudo", "ddcutil", "setvcp", vcp_code, value]
try:
res = subprocess.run(cmd, capture_output=True, timeout=3.5)
return res.returncode == 0
except Exception as e:
logging.debug(f"ddcutil VCP {vcp_code} failed: {e}")
return False
def stop_current_mode():
"""Stop the current mode's client process. The labwc compositor is kept alive for fast switching."""
global current_process
if current_process:
logging.info("Stopping current mode process...")
try:
os.killpg(os.getpgid(current_process.pid), signal.SIGTERM)
current_process.wait(timeout=2)
except (subprocess.TimeoutExpired, ProcessLookupError, PermissionError):
try:
os.killpg(os.getpgid(current_process.pid), signal.SIGKILL)
except Exception:
pass
current_process = None
# Kill orphaned browser processes (NOT labwc — it's reused)
for proc_name in ["chromium", "chromium-browser", "cog"]:
try:
subprocess.run(
["pkill", "-f", proc_name],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2
)
except Exception:
pass
# Brief settle for the client process to release Wayland resources
time.sleep(0.1)
def _get_labwc_config():
"""Create a temporary labwc config to hide the cursor and optimize for kiosk mode."""
config_dir = (
subprocess.check_output(["mktemp", "-d", "/tmp/labwc-orchestrator-XXXXXX"])
.decode()
.strip()
)
# Using XDG_CONFIG_HOME expects a /labwc subfolder
os.makedirs(os.path.join(config_dir, "labwc"), exist_ok=True)
rc_xml = os.path.join(config_dir, "labwc", "rc.xml")
with open(rc_xml, "w") as f:
f.write(
"<labwc_config>\n"
" <windowRules>\n"
' <windowRule identifier="*">\n'
' <action name="Maximize" />\n'
" </windowRule>\n"
" </windowRules>\n"
"</labwc_config>"
)
return config_dir
def _ensure_labwc():
"""Start a persistent labwc compositor if not already running. Returns env dict for clients."""
global _labwc_process, _labwc_wayland_display, labwc_config_dir, _display_env_detected
# Check if existing labwc is still alive and its socket reachable
if _labwc_process and _labwc_process.poll() is None:
if _labwc_wayland_display and _is_wayland_reachable(_labwc_wayland_display):
logging.debug("Reusing persistent labwc compositor.")
return _labwc_wayland_display
# Process alive but socket dead — tear down
logging.warning("labwc process alive but socket unreachable, restarting.")
_stop_labwc()
# Find labwc binary (cached)
labwc_bin = _working_methods.get("labwc_path")
if not labwc_bin:
labwc_bin = subprocess.check_output(["which", "labwc"]).decode().strip()
_working_methods["labwc_path"] = labwc_bin
_save_cache()
# Create config directory (reuse if still exists)
if not labwc_config_dir or not os.path.exists(labwc_config_dir):
labwc_config_dir = _get_labwc_config()
env = os.environ.copy()
env["XDG_CONFIG_HOME"] = labwc_config_dir
env["XCURSOR_SIZE"] = "0"
env["COG_PLATFORM_FDO_SHOW_CURSOR"] = "0"
# Clean up stale wayland sockets so labwc can claim wayland-0 cleanly.
# On Pi Zero 2, stale socket files from previous crashed sessions block labwc from
# creating its own socket (name collision), causing the socket detection to time out.
runtime_dir = os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
try:
for f in os.listdir(runtime_dir):
if f.startswith("wayland-") and not f.endswith(".lock"):
if not _is_wayland_reachable(f):
stale = os.path.join(runtime_dir, f)
try:
os.remove(stale)
logging.debug(f"Removed stale Wayland socket: {stale}")
except OSError:
pass
# Also remove the companion .lock file
lock = stale + ".lock"
if os.path.exists(lock):
try:
os.remove(lock)
except OSError:
pass
except OSError:
pass
# Launch labwc with a long-lived no-op startup command.
# labwc requires -s to fully initialize its Wayland socket on DRM/KMS backends (Pi Zero 2).
# "sleep infinity" keeps labwc alive as a bare compositor ready to accept client connections.
_labwc_process = subprocess.Popen(
[labwc_bin, "-s", "sleep infinity"], env=env, start_new_session=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
logging.info(f"Started persistent labwc compositor (PID {_labwc_process.pid}).")
# Wait for labwc's Wayland socket to become reachable (max ~10s).
# First cold-start on Pi Zero 2 can take 6-8s (shared libs, DRM init, shader compile).
# Subsequent starts are ~2s thanks to warm page cache.
for attempt in range(100):
if _labwc_process.poll() is not None:
rc = _labwc_process.returncode
_labwc_process = None
raise RuntimeError(f"labwc exited during startup with code {rc}")
for name in ["wayland-0", "wayland-1", "wayland-2"]:
if _is_wayland_reachable(name):
_labwc_wayland_display = name
os.environ["WAYLAND_DISPLAY"] = name
_display_env_detected = True
logging.info(f"labwc Wayland socket ready: {name} (after {(attempt+1)*0.1:.1f}s)")
threading.Thread(target=_labwc_hide_cursor, daemon=True).start()
return name
if attempt % 10 == 9:
logging.debug(f"labwc socket poll #{attempt+1}: still waiting...")
time.sleep(0.1)
raise RuntimeError("labwc started but no Wayland socket detected within 10s")
def _labwc_hide_cursor():
"""Tell the persistent labwc to hide its cursor (fire-and-forget, best-effort)."""
try:
subprocess.run(
["labwc-msg", "action", "HideCursor"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2,
)
except Exception:
pass
def _stop_labwc():
"""Tear down the persistent labwc compositor (only called for 'off' mode or error recovery)."""
global _labwc_process, _labwc_wayland_display, labwc_config_dir, _display_env_detected
if _labwc_process:
logging.info("Stopping persistent labwc compositor.")
try:
os.killpg(os.getpgid(_labwc_process.pid), signal.SIGTERM)
_labwc_process.wait(timeout=2)
except (subprocess.TimeoutExpired, ProcessLookupError, PermissionError):
try:
os.killpg(os.getpgid(_labwc_process.pid), signal.SIGKILL)
except Exception:
pass
_labwc_process = None
_labwc_wayland_display = None
if labwc_config_dir and os.path.exists(labwc_config_dir):
try:
shutil.rmtree(labwc_config_dir)
except Exception:
pass
labwc_config_dir = None
# Kill any orphaned labwc processes
try:
subprocess.run(["pkill", "-f", "labwc"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2)
except Exception:
pass
if "WAYLAND_DISPLAY" in os.environ:
del os.environ["WAYLAND_DISPLAY"]
if "DISPLAY" in os.environ:
del os.environ["DISPLAY"]
_display_env_detected = False
time.sleep(0.3) # Brief settle for DRM/kernel resource release
def start_mode(mode):
global current_process, current_mode, mqtt_client
mode = mode.lower()
if mode == current_mode:
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_STATE_TOPIC, current_mode, retain=True)
return
previous_mode = current_mode
logging.info(f"Transitioning mode: {previous_mode} -> {mode}")
# 1. Publish intent IMMEDIATELY so HA sees the change instantly.
current_mode = mode
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_STATE_TOPIC, current_mode, retain=True)
# 2. Stop the current mode's client process (labwc compositor stays alive).
stop_current_mode()
if mode == "off":
logging.info("Ensuring display power is OFF.")
_stop_labwc() # Tear down compositor when going fully off
set_display_power(False)
return
# 3. Start display power ON and labwc compositor IN PARALLEL.
# On Pi Zero 2 cold boot, labwc takes 6-8s to create its Wayland socket.
# Overlapping with display power-on (~3s) hides most of that latency.
display_thread = None
if previous_mode == "off":
display_thread = threading.Thread(target=set_display_power, args=(True,), daemon=True)
display_thread.start()
setup_display_env()
labwc_thread = None
_labwc_start_error = [None] # Mutable container for thread result
if _labwc_process is not None or (
not os.environ.get("WAYLAND_DISPLAY") and not os.environ.get("DISPLAY")
):
def _start_labwc_parallel():
try:
_ensure_labwc()
except Exception as e:
_labwc_start_error[0] = e
labwc_thread = threading.Thread(target=_start_labwc_parallel, daemon=True)
labwc_thread.start()
# 4. Resolve mode script (runs while display + labwc warm up).
modes_dir = os.path.join(os.path.dirname(__file__), "modes")
py_script = os.path.join(modes_dir, f"{mode}_mode.py")
sh_script = os.path.join(modes_dir, f"{mode}_mode.sh")
base_cmd = []
if os.path.exists(sh_script):
base_cmd = ["bash", sh_script]
elif os.path.exists(py_script):
base_cmd = [sys.executable, py_script]
else:
available = get_available_modes()
logging.warning(f"Unknown mode: {mode}. Available modes: {available}")
current_mode = "off"
_stop_labwc()
set_display_power(False)
if mqtt_client and mqtt_client.is_connected():
mqtt_client.publish(MQTT_STATE_TOPIC, current_mode, retain=True)
return