-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnight-mode.py
More file actions
executable file
·181 lines (145 loc) · 5.29 KB
/
night-mode.py
File metadata and controls
executable file
·181 lines (145 loc) · 5.29 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
#!/usr/bin/env python3
"""
Night Mode Service
Manages blue light filtering with wlsunset and sends bedtime notifications.
"""
import subprocess
import sys
import signal
import time
from datetime import datetime, timedelta
from pathlib import Path
try:
import tomllib
except ImportError:
import tomli as tomllib
CONFIG_PATH = Path(__file__).parent / "config.toml"
wlsunset_process = None
def load_config():
"""Load configuration from TOML file."""
with open(CONFIG_PATH, "rb") as f:
return tomllib.load(f)
def parse_time(time_str: str) -> datetime:
"""Parse HH:MM string to datetime for today."""
hour, minute = map(int, time_str.split(":"))
now = datetime.now()
return now.replace(hour=hour, minute=minute, second=0, microsecond=0)
def send_notification(title: str, message: str, urgency: str = "normal"):
"""Send desktop notification using notify-send."""
icon = "night-light" if "blue" in title.lower() else "appointment-soon"
try:
subprocess.run([
"notify-send",
"-u", urgency,
"-i", icon,
"-a", "Night Mode",
title,
message
], check=False)
except Exception as e:
print(f"Failed to send notification: {e}", file=sys.stderr)
def start_wlsunset(config: dict):
"""Start wlsunset with configured settings."""
global wlsunset_process
schedule = config["schedule"]
temp = config["temperature"]
# Build wlsunset command
cmd = [
"wlsunset",
"-S", schedule["wake_time"], # sunrise (filter off)
"-s", schedule["blue_light_start"], # sunset (filter on)
"-t", str(temp["night"]), # low/night temperature
"-T", str(temp["day"]), # high/day temperature
"-d", str(schedule["transition_minutes"] * 60) # transition duration in seconds
]
print(f"Starting wlsunset: {' '.join(cmd)}")
wlsunset_process = subprocess.Popen(cmd)
return wlsunset_process
def notification_scheduler(config: dict):
"""Run notification scheduler loop."""
schedule = config["schedule"]
notif = config["notifications"]
if not notif["enabled"]:
print("Notifications disabled in config")
return
# Track which notifications we've sent today
sent_today = {
"blue_light": False,
"bedtime_warning": False,
"bedtime": False
}
last_date = datetime.now().date()
while True:
now = datetime.now()
# Reset tracking at midnight
if now.date() != last_date:
sent_today = {k: False for k in sent_today}
last_date = now.date()
# Parse times for today
blue_time = parse_time(schedule["blue_light_start"])
bedtime = parse_time(schedule["bedtime"])
warning_time = bedtime - timedelta(minutes=notif["bedtime_warning_minutes"])
# Check blue light notification
if not sent_today["blue_light"] and now >= blue_time:
send_notification(
"Blue Light Filter",
notif["blue_light_message"]
)
sent_today["blue_light"] = True
print(f"[{now.strftime('%H:%M')}] Sent blue light notification")
# Check bedtime warning
if (notif["bedtime_warning_minutes"] > 0 and
not sent_today["bedtime_warning"] and
now >= warning_time and now < bedtime):
minutes_left = int((bedtime - now).total_seconds() / 60)
send_notification(
"Bedtime Approaching",
f"{minutes_left} minutes until bedtime",
urgency="normal"
)
sent_today["bedtime_warning"] = True
print(f"[{now.strftime('%H:%M')}] Sent bedtime warning notification")
# Check bedtime notification
if not sent_today["bedtime"] and now >= bedtime:
send_notification(
"Bedtime",
notif["bedtime_message"],
urgency="critical"
)
sent_today["bedtime"] = True
print(f"[{now.strftime('%H:%M')}] Sent bedtime notification")
# Sleep for a minute before checking again
time.sleep(60)
def cleanup(signum, frame):
"""Clean up on exit."""
global wlsunset_process
print("\nShutting down night-mode...")
if wlsunset_process:
wlsunset_process.terminate()
wlsunset_process.wait()
sys.exit(0)
def main():
# Handle signals for clean shutdown
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGINT, cleanup)
print("Night Mode Service starting...")
# Load configuration
try:
config = load_config()
except Exception as e:
print(f"Failed to load config: {e}", file=sys.stderr)
sys.exit(1)
print(f"Config loaded:")
print(f" Blue light: {config['schedule']['blue_light_start']}")
print(f" Bedtime: {config['schedule']['bedtime']}")
print(f" Wake time: {config['schedule']['wake_time']}")
print(f" Temperature: {config['temperature']['night']}K - {config['temperature']['day']}K")
# Start wlsunset
start_wlsunset(config)
# Run notification scheduler (blocks)
try:
notification_scheduler(config)
except KeyboardInterrupt:
cleanup(None, None)
if __name__ == "__main__":
main()