-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlights.py
More file actions
executable file
·2036 lines (1639 loc) · 62.8 KB
/
lights.py
File metadata and controls
executable file
·2036 lines (1639 loc) · 62.8 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
#!/home/pi/venvs/wiz/bin/python
import asyncio
import json
import os
import random
import signal
import socket
import subprocess
import sys
from pathlib import Path
from pywizlight import PilotBuilder, wizlight
from pywizlight.exceptions import WizLightConnectionError
# --------------------------------------------------
# CONFIG
# --------------------------------------------------
IPS = [
"192.168.86.123", # kitchen 1
"192.168.86.124", # kitchen 2
"192.168.86.133", # entryway 1
"192.168.86.134", # entryway 2
]
# Map bulb IP -> room label (used by dashboard and status output)
ROOM_BY_IP = {
"192.168.86.123": "KITCHEN",
"192.168.86.124": "KITCHEN",
"192.168.86.133": "ENTRYWAY",
"192.168.86.134": "ENTRYWAY",
}
GROUPS = {
"all": [
"192.168.86.123",
"192.168.86.124",
"192.168.86.133",
"192.168.86.134",
],
"kitchen": [
"192.168.86.123",
"192.168.86.124",
],
"entryway": [
"192.168.86.133",
"192.168.86.134",
],
}
GROUP_ALIASES = {
"kitchen": "kitchen",
"kit": "kitchen",
"k": "kitchen",
"entryway": "entryway",
"entry": "entryway",
"e": "entryway",
"all": "all",
"a": "all",
}
ACTIVE_GROUP: str | None = None
ACTIVE_IPS: list[str] | None = None
def _set_active_group(group: str | None) -> None:
global ACTIVE_GROUP, ACTIVE_IPS
if group is None or group == "all":
ACTIVE_GROUP = None
ACTIVE_IPS = None
return
if group not in GROUPS:
raise ValueError(f"Unknown group: {group}")
ACTIVE_GROUP = group
ACTIVE_IPS = list(GROUPS[group])
def active_group() -> str | None:
return ACTIVE_GROUP
def _maybe_consume_group(argv: list[str]) -> tuple[str | None, list[str]]:
if not argv:
return None, argv
tok = argv[0].lower()
group = GROUP_ALIASES.get(tok)
if group is None:
return None, argv
return group, argv[1:]
def _target_ips() -> list[str]:
return ACTIVE_IPS if ACTIVE_IPS is not None else IPS
WIZ_PORT = 38899
STATE_DIR = Path("/home/pi/.lights_state")
ALERT_PULSE_TOGGLE = STATE_DIR / "alert_pulse.toggle"
STATE_DIR.mkdir(parents=True, exist_ok=True)
SNAPSHOT_DIR = STATE_DIR / "snapshots"
SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
def _snapshot_path(name: str) -> Path:
safe = "".join(c for c in name if c.isalnum() or c in ("-", "_")).strip()
if not safe:
safe = "default"
return SNAPSHOT_DIR / f"{safe}.json"
STATE_FILE = STATE_DIR / "last_mode"
EFFECT_FILE = STATE_DIR / "effect_running"
EFFECT_BRI_FILE = STATE_DIR / "effect_bri"
CYCLE_ORDER = [
"warm",
"soft",
"cool",
"bright",
"dim",
"night",
]
BACKGROUND_EFFECTS = {
"fireplace_ambient",
"asym_static",
"embers",
"bonfire",
"aurora",
"cozy_ambient",
"candle_pair",
"breathe_soft",
"focus_wave",
"dusk_drift",
"hearth",
"abyss",
"storm_distant",
"police_siren",
}
# --------------------------------------------------
# PRESETS
# - Non-scene presets use PilotBuilder
# - Scene presets use raw UDP setPilot with sceneId
# --------------------------------------------------
PRESETS = {
"warm": {"brightness": 180, "pilot": PilotBuilder(brightness=180, colortemp=2700)},
"soft": {"brightness": 140, "pilot": PilotBuilder(brightness=140, colortemp=3000)},
"cool": {"brightness": 220, "pilot": PilotBuilder(brightness=220, colortemp=5000)},
"bright": {"brightness": 255, "pilot": PilotBuilder(brightness=255, colortemp=4000)},
"dim": {"brightness": 80, "pilot": PilotBuilder(brightness=80, colortemp=2700)},
"night": {"brightness": 30, "pilot": PilotBuilder(brightness=30, colortemp=2200)},
"red": {"brightness": 200, "pilot": PilotBuilder(brightness=200, rgb=(255, 0, 0))},
"green": {"brightness": 200, "pilot": PilotBuilder(brightness=200, rgb=(0, 255, 0))},
"blue": {"brightness": 200, "pilot": PilotBuilder(brightness=200, rgb=(0, 120, 255))},
"sunset": {"brightness": 120, "pilot": PilotBuilder(brightness=120, rgb=(255, 120, 40))},
"movie": {"brightness": 60, "pilot": PilotBuilder(brightness=60, rgb=(255, 180, 120))},
"tiffany_cream": {"brightness": 100, "pilot": PilotBuilder(brightness=100, rgb=(248, 229, 201))},
"tiffany_honey": {"brightness": 100, "pilot": PilotBuilder(brightness=100, rgb=(241, 193, 89))},
"tiffany": {"brightness": 160, "duo": ("tiffany_cream", "tiffany_honey")},
}
# --------------------------------------------------
# WiZ scenes / effects via raw sceneId
# Keep these in a separate dict, then merge into PRESETS.
# --------------------------------------------------
SCENE_PRESETS = {
"ocean": {"brightness": 140, "scene_id": 1},
"romance": {"brightness": 140, "scene_id": 2},
"sunset_scene": {"brightness": 140, "scene_id": 3},
"party": {"brightness": 140, "scene_id": 4},
"fireplace": {"brightness": 120, "scene_id": 5},
"cozy": {"brightness": 140, "scene_id": 6},
"forest": {"brightness": 140, "scene_id": 7},
"pastel_colors": {"brightness": 140, "scene_id": 8},
"wake_up": {"brightness": 140, "scene_id": 9},
"bedtime": {"brightness": 140, "scene_id": 10},
"warm_white": {"brightness": 180, "scene_id": 11},
"daylight": {"brightness": 200, "scene_id": 12},
"cool_white": {"brightness": 200, "scene_id": 13},
"night_light": {"brightness": 60, "scene_id": 14},
"focus": {"brightness": 220, "scene_id": 15},
"relax": {"brightness": 140, "scene_id": 16},
"true_colors": {"brightness": 140, "scene_id": 17},
"tv_time": {"brightness": 140, "scene_id": 18},
"plant_growth": {"brightness": 200, "scene_id": 19},
"spring": {"brightness": 140, "scene_id": 20},
"summer": {"brightness": 140, "scene_id": 21},
"fall": {"brightness": 140, "scene_id": 22},
"deep_dive": {"brightness": 140, "scene_id": 23},
"jungle": {"brightness": 140, "scene_id": 24},
"mojito": {"brightness": 140, "scene_id": 25},
"club": {"brightness": 140, "scene_id": 26},
"christmas": {"brightness": 140, "scene_id": 27},
"halloween": {"brightness": 140, "scene_id": 28},
"candlelight": {"brightness": 140, "scene_id": 29},
"golden_white": {"brightness": 160, "scene_id": 30},
"pulse": {"brightness": 140, "scene_id": 31},
"steampunk": {"brightness": 140, "scene_id": 32},
}
# Merge scenes into PRESETS so CLI + dashboard see them
PRESETS.update(SCENE_PRESETS)
# Optional: scene ID reverse map for the dashboard status line
SCENE_ID_TO_NAME = {v["scene_id"]: k for k, v in SCENE_PRESETS.items()}
# --------------------------------------------------
# UI COLOR HINTS (used by lights_dashboard.py)
# Single source of truth for preset/effect menu colors.
# --------------------------------------------------
PRESET_RGB_HINTS = {
# Whites
"warm": (255, 180, 120),
"soft": (255, 200, 150),
"dim": (255, 150, 80),
"night": (255, 110, 50),
"cool": (200, 220, 255),
"bright": (240, 240, 255),
# Solid RGB presets
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 120, 255),
"sunset": (255, 120, 40),
"movie": (255, 180, 120),
# Duo preset (dashboard alternates the two colors)
"tiffany": (241, 193, 89),
"tiffany_cream": (248, 229, 201),
"tiffany_honey": (241, 193, 89),
# Scene-ish presets
"ocean": (0, 120, 255),
"romance": (255, 0, 120),
"sunset_scene": (255, 120, 40),
"party": (255, 0, 255),
"fireplace": (255, 90, 20),
"cozy": (255, 170, 90),
"forest": (0, 170, 90),
"pastel_colors": (190, 160, 255),
"wake_up": (255, 210, 140),
"bedtime": (255, 120, 80),
"warm_white": (255, 220, 180),
"daylight": (220, 240, 255),
"cool_white": (200, 220, 255),
"night_light": (255, 90, 20),
"focus": (240, 240, 255),
"relax": (255, 180, 120),
"true_colors": (255, 255, 255),
"tv_time": (180, 140, 255),
"plant_growth": (120, 255, 120),
"spring": (140, 255, 180),
"summer": (255, 230, 120),
"fall": (255, 140, 60),
"deep_dive": (0, 80, 255),
"jungle": (0, 200, 80),
"mojito": (120, 255, 180),
"club": (255, 0, 255),
"christmas": (255, 0, 0),
"halloween": (255, 80, 0),
"candlelight": (255, 140, 60),
"golden_white": (255, 210, 140),
"pulse": (255, 0, 255),
"steampunk": (255, 170, 90),
"diwali": (255, 120, 255),
"white": (255, 255, 255),
"alarm": (255, 0, 0),
# Alert presets
"alert_white": (255, 255, 255),
"alert_red": (255, 0, 0),
"alert_blue": (0, 120, 255),
# Background effects (menu color hints)
"embers": (255, 115, 35),
"hearth": (255, 150, 70),
"fireplace_ambient": (255, 125, 45),
"storm_distant": (150, 165, 190),
"cozy_ambient": (255, 175, 95),
"candle_pair": (255, 170, 80),
"asym_static": (255, 215, 170),
"breathe_soft": (255, 145, 90),
"focus_wave": (210, 235, 255),
"dusk_drift": (255, 140, 85),
"police_siren": (255, 0, 0),
"abyss": (60, 0, 150),
}
# --------------------------------------------------
# EFFECT STATE (PID + brightness scaling) - PER GROUP
# --------------------------------------------------
def _install_signal_handlers():
loop = asyncio.get_event_loop()
async def _cancel():
clear_effect_running()
for task in asyncio.all_tasks(loop):
if task is not asyncio.current_task():
task.cancel()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, lambda: asyncio.create_task(_cancel()))
except NotImplementedError:
pass
def _pid_alive(pid: int) -> bool:
try:
os.kill(pid, 0)
return True
except Exception:
return False
def _effect_file(group: str | None) -> Path:
if group and group != "all":
return STATE_DIR / f"effect_running_{group}"
return STATE_DIR / "effect_running_all"
def _effect_bri_file(group: str | None) -> Path:
if group and group != "all":
return STATE_DIR / f"effect_bri_{group}"
return STATE_DIR / "effect_bri_all"
def effect_is_running(group: str | None = None) -> bool:
g = active_group() if group is None else group
ef = _effect_file(g)
if not ef.exists():
return False
try:
lines = ef.read_text().splitlines()
pid = int(lines[1]) if len(lines) > 1 else None
if pid and _pid_alive(pid):
return True
except Exception:
pass
ef.unlink(missing_ok=True)
return False
def set_effect_running(name: str, group: str | None = None) -> None:
g = active_group() if group is None else group
ef = _effect_file(g)
bf = _effect_bri_file(g)
ef.write_text(f"{name}\n{os.getpid()}\n")
if not bf.exists():
bf.write_text("255")
def clear_effect_running(group: str | None = None) -> None:
g = active_group() if group is None else group
_effect_file(g).unlink(missing_ok=True)
def load_effect_bri(default: int = 255, group: str | None = None) -> int:
g = active_group() if group is None else group
bf = _effect_bri_file(g)
try:
if bf.exists():
v = int(bf.read_text().strip())
return max(1, min(255, v))
except Exception:
pass
return max(1, min(255, int(default)))
def save_effect_bri(v: int, group: str | None = None) -> int:
g = active_group() if group is None else group
bf = _effect_bri_file(g)
v = max(1, min(255, int(v)))
bf.write_text(str(v))
return v
def effect_scale(group: str | None = None) -> float:
return load_effect_bri(255, group=group) / 255.0
def scale_bri(b: float, group: str | None = None) -> int:
s = effect_scale(group=group)
return max(1, min(255, int(round(float(b) * s))))
def stop_running_effect(group: str | None = None) -> None:
groups_to_stop: list[str | None]
if group is None:
groups_to_stop = [None] + [g for g in GROUPS.keys() if g != "all"]
else:
groups_to_stop = [group]
for g in groups_to_stop:
ef = _effect_file(g)
if not ef.exists():
continue
try:
lines = ef.read_text().splitlines()
pid = int(lines[1]) if len(lines) > 1 else None
if pid:
try:
os.kill(pid, signal.SIGTERM)
except Exception:
pass
except Exception:
pass
ef.unlink(missing_ok=True)
def effect_should_stop(group: str | None = None) -> bool:
g = active_group() if group is None else group
ef = _effect_file(g)
if not ef.exists():
return True
try:
lines = ef.read_text().splitlines()
pid = int(lines[1]) if len(lines) > 1 else None
if pid != os.getpid():
return True
except Exception:
return True
return False
def load_running_effect_name(group: str | None = None) -> str | None:
g = active_group() if group is None else group
if not effect_is_running(g):
return None
try:
lines = _effect_file(g).read_text().splitlines()
name = lines[0].strip() if lines else ""
return name or None
except Exception:
return None
# --------------------------------------------------
# STATE HELPERS
# --------------------------------------------------
def _last_mode_file(group: str | None) -> Path:
if group:
return STATE_DIR / f"last_mode_{group}"
return STATE_DIR / "last_mode"
def save_last_mode(mode: str, group: str | None = None) -> None:
path = _last_mode_file(group)
path.write_text(mode)
def load_last_mode(group: str | None = None) -> str | None:
path = _last_mode_file(group)
if path.exists():
return path.read_text().strip()
return None
# --------------------------------------------------
# CORE HELPERS
# --------------------------------------------------
async def get_bulbs():
ips = _target_ips()
return [wizlight(ip) for ip in ips]
async def close_all(bulbs):
for b in bulbs:
await b.async_close()
def _brightness_to_dimming_percent(brightness_0_255: int) -> int:
b = int(brightness_0_255)
b = max(0, min(255, b))
pct = int(round((b / 255) * 100))
return max(1, min(100, pct))
def send_raw_scene(ip: str, scene_id: int, brightness_0_255: int) -> None:
dimming = _brightness_to_dimming_percent(brightness_0_255)
payload = {
"id": 1,
"method": "setPilot",
"params": {
"state": True,
"sceneId": int(scene_id),
"dimming": dimming,
},
}
data = json.dumps(payload).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.sendto(data, (ip, WIZ_PORT))
finally:
sock.close()
def send_raw_rgb(ip: str, r: int, g: int, b: int, brightness_0_255: int) -> None:
dimming = _brightness_to_dimming_percent(brightness_0_255)
payload = {
"id": 1,
"method": "setPilot",
"params": {
"state": True,
"r": int(r), "g": int(g), "b": int(b),
"dimming": dimming,
},
}
data = json.dumps(payload).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.sendto(data, (ip, WIZ_PORT))
finally:
sock.close()
def send_raw_off(ip: str) -> None:
payload = {
"id": 1,
"method": "setPilot",
"params": {"state": False},
}
data = json.dumps(payload).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.sendto(data, (ip, WIZ_PORT))
finally:
sock.close()
def send_raw_dim1(ip: str) -> None:
"""Snap a bulb to 1% dimming (used before OFF to avoid slow fade)."""
payload = {
"id": 1,
"method": "setPilot",
"params": {"state": True, "dimming": 1},
}
data = json.dumps(payload).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.sendto(data, (ip, WIZ_PORT))
finally:
sock.close()
def get_pilot_raw(ip: str, timeout: float = 0.6) -> dict | None:
"""
Ask the bulb for its current state via WiZ UDP getPilot.
Returns parsed JSON dict, or None on failure/timeout.
"""
payload = {"id": 1, "method": "getPilot", "params": {}}
data = json.dumps(payload).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(float(timeout))
try:
sock.sendto(data, (ip, WIZ_PORT))
resp, _addr = sock.recvfrom(4096)
return json.loads(resp.decode("utf-8", errors="replace"))
except Exception:
return None
finally:
try:
sock.close()
except Exception:
pass
def _validate_mode(mode: str) -> None:
if mode not in PRESETS:
raise ValueError(f"Unknown preset: {mode}")
async def _apply_mode_to_bulb(bulb, mode: str) -> None:
_validate_mode(mode)
preset = PRESETS[mode]
if "scene_id" in preset:
scene_id = preset["scene_id"]
brightness = int(preset.get("brightness", 140))
send_raw_scene(bulb.ip, scene_id, brightness)
print(f"{mode.upper():<12} {bulb.ip} sceneId={scene_id}")
return
pilot = preset["pilot"]
try:
await bulb.turn_on(pilot)
print(f"{mode.upper():<12} {bulb.ip}")
except (WizLightConnectionError, asyncio.TimeoutError) as e:
print(f"FAIL {bulb.ip} ({type(e).__name__})")
def launch_background(cmd: str, group: str | None) -> None:
running = load_running_effect_name(group)
if running == cmd:
if group:
print(f"EFFECT {cmd} already running ({group}), restarting")
else:
print(f"EFFECT {cmd} already running, restarting")
stop_running_effect(group)
else:
stop_running_effect(group)
args = [sys.executable, __file__, "--bg", cmd]
if group:
args.append(group)
subprocess.Popen(
args,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
if group:
print(f"EFFECT {cmd} started ({group})")
else:
print(f"EFFECT {cmd} started")
# --------------------------------------------------
# SNAPSHOTS
# --------------------------------------------------
async def snapshot_save(name: str = "default") -> None:
bulbs = [wizlight(ip) for ip in IPS]
try:
states = await asyncio.gather(*[b.updateState() for b in bulbs])
data = {"name": name, "bulbs": []}
for b, st in zip(bulbs, states):
item = {
"ip": b.ip,
"on": bool(st.get_state()),
"bri": st.get_brightness(),
"ct": st.get_colortemp(),
"rgb": st.get_rgb(),
}
data["bulbs"].append(item)
_snapshot_path(name).write_text(json.dumps(data, indent=2))
print(f"SNAPSHOT saved {name}")
finally:
await close_all(bulbs)
async def snapshot_load(name: str = "default") -> None:
path = _snapshot_path(name)
if not path.exists():
raise SystemExit(f"No snapshot found: {name}")
data = json.loads(path.read_text())
bulbs_data = data.get("bulbs", [])
ip_to_item = {it["ip"]: it for it in bulbs_data if "ip" in it}
bulbs = [wizlight(ip) for ip in ip_to_item.keys()]
try:
tasks = []
for b in bulbs:
it = ip_to_item[b.ip]
if not it.get("on", False):
tasks.append(asyncio.to_thread(send_raw_off, b.ip))
continue
bri = it.get("bri") or 120
rgb = it.get("rgb")
ct = it.get("ct")
rgb_valid = (
isinstance(rgb, (tuple, list))
and len(rgb) == 3
and all(v is not None for v in rgb)
)
if rgb_valid:
tasks.append(b.turn_on(PilotBuilder(brightness=int(bri), rgb=tuple(rgb))))
elif ct is not None:
tasks.append(b.turn_on(PilotBuilder(brightness=int(bri), colortemp=int(ct))))
else:
tasks.append(b.turn_on(PilotBuilder(brightness=int(bri), colortemp=2700)))
if tasks:
await asyncio.gather(*tasks)
print(f"SNAPSHOT loaded {name}")
finally:
await close_all(bulbs)
def snapshot_list() -> None:
snaps = sorted(SNAPSHOT_DIR.glob("*.json"))
if not snaps:
print("SNAPSHOT (none)")
return
for p in snaps:
print(f"SNAPSHOT {p.stem}")
# --------------------------------------------------
# BASIC ACTIONS
# --------------------------------------------------
async def turn_on(mode: str) -> None:
_validate_mode(mode)
preset = PRESETS[mode]
bulbs = await get_bulbs()
try:
if "duo" in preset:
if not bulbs:
return
m1, m2 = preset["duo"]
if len(bulbs) == 1:
await _apply_mode_to_bulb(bulbs[0], m1)
return
await _apply_mode_to_bulb(bulbs[0], m1)
await _apply_mode_to_bulb(bulbs[1], m2)
return
await asyncio.gather(*[_apply_mode_to_bulb(bulb, mode) for bulb in bulbs])
finally:
await close_all(bulbs)
async def turn_on_b1(mode: str) -> None:
bulbs = await get_bulbs()
try:
if bulbs:
await _apply_mode_to_bulb(bulbs[0], mode)
finally:
await close_all(bulbs)
async def turn_on_b2(mode: str) -> None:
bulbs = await get_bulbs()
try:
if len(bulbs) < 2:
raise RuntimeError("Need at least 2 bulbs for b2")
await _apply_mode_to_bulb(bulbs[1], mode)
finally:
await close_all(bulbs)
async def turn_duo(mode_b1: str, mode_b2: str) -> None:
bulbs = await get_bulbs()
try:
if len(bulbs) < 2:
raise RuntimeError("Need at least 2 bulbs for duo")
await _apply_mode_to_bulb(bulbs[0], mode_b1)
await _apply_mode_to_bulb(bulbs[1], mode_b2)
finally:
await close_all(bulbs)
async def turn_off() -> None:
bulbs = await get_bulbs()
try:
# Group bulbs by room to keep visual timing consistent
rooms: dict[str, list] = {}
for b in bulbs:
label = ROOM_BY_IP.get(b.ip, "UNKNOWN")
rooms.setdefault(label, []).append(b)
async def _burst_off(room_bulbs: list) -> None:
# Quick OFF bursts (helps with UDP misses)
for _ in range(4):
await asyncio.gather(*[
asyncio.to_thread(send_raw_off, b.ip)
for b in room_bulbs
])
await asyncio.sleep(0.04)
async def _snap_dim_1(room_bulbs: list) -> None:
# Some bulbs do a slow fade on OFF. This "snaps" them to 1% first.
await asyncio.gather(*[
asyncio.to_thread(send_raw_dim1, b.ip)
for b in room_bulbs
])
async def _hard_off(room_bulbs: list) -> None:
# Snap then OFF bursts
await _snap_dim_1(room_bulbs)
await asyncio.sleep(0.05)
await _burst_off(room_bulbs)
# Run each room in parallel so entryway matches kitchen timing
tasks = [asyncio.create_task(_hard_off(room_bulbs)) for room_bulbs in rooms.values()]
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
finally:
await close_all(bulbs)
async def show_status() -> None:
bulbs = await get_bulbs()
try:
states = await asyncio.gather(*[b.updateState() for b in bulbs])
running = load_running_effect_name()
last = load_last_mode(active_group())
on_bris = []
for st in states:
if st.get_state():
bri = st.get_brightness()
if bri is not None:
on_bris.append(int(bri))
avg_bri = int(round(sum(on_bris) / len(on_bris))) if on_bris else None
if running:
s = load_effect_bri(255)
pct = int(round((s / 255.0) * 100))
est_raw = None
if avg_bri is not None and s > 0:
est_raw = int(round(avg_bri / (s / 255.0)))
if avg_bri is not None and est_raw is not None:
print(f"EFFECT {running} scale={s}/255 ({pct}%) avg_bri={avg_bri} est_raw={est_raw}")
else:
print(f"EFFECT {running} scale={s}/255 ({pct}%)")
else:
if last:
if last in BACKGROUND_EFFECTS:
print(f"MODE {last} (not running)")
print(f"HINT run: lights {last}")
else:
print(f"MODE {last}")
else:
print("MODE (none)")
for bulb, state in zip(bulbs, states):
if not state.get_state():
print(f"OFF {bulb.ip}")
continue
bri = state.get_brightness()
rgb = state.get_rgb()
ct = state.get_colortemp()
rgb_valid = (
isinstance(rgb, (tuple, list))
and len(rgb) == 3
and all(v is not None for v in rgb)
)
if rgb_valid:
print(f"ON {bulb.ip} bri={bri} rgb={rgb}")
elif ct is not None:
print(f"ON {bulb.ip} bri={bri} ct={ct}")
else:
print(f"ON {bulb.ip} bri={bri}")
finally:
await close_all(bulbs)
async def dim_adjust(target: str, delta: int) -> None:
bulbs = await get_bulbs()
try:
if not bulbs:
return
if target == "B1":
bulbs = bulbs[:1]
elif target == "B2":
if len(bulbs) < 2:
raise RuntimeError("Need at least 2 bulbs for B2")
bulbs = [bulbs[1]]
delta = int(delta)
for b in bulbs:
st = await b.updateState()
cur_bri = st.get_brightness() or 120
new_bri = max(1, min(255, int(cur_bri) + delta))
last = load_last_mode(active_group())
if last and last in PRESETS and "scene_id" in PRESETS[last]:
scene_id = PRESETS[last]["scene_id"]
send_raw_scene(b.ip, scene_id, new_bri)
print(f"DIM_SCENE {b.ip} sceneId={scene_id} bri={new_bri}")
continue
rgb = st.get_rgb()
ct = st.get_colortemp()
rgb_valid = (
isinstance(rgb, (tuple, list))
and len(rgb) == 3
and all(v is not None for v in rgb)
)
if rgb_valid:
pilot = PilotBuilder(brightness=new_bri, rgb=tuple(rgb))
elif ct is not None:
pilot = PilotBuilder(brightness=new_bri, colortemp=int(ct))
else:
pilot = PilotBuilder(brightness=new_bri, colortemp=2700)
await b.turn_on(pilot)
print(f"DIM {b.ip} bri={new_bri}")
finally:
await close_all(bulbs)
# --------------------------------------------------
# FADE
# --------------------------------------------------
async def fade_to(mode: str, seconds: float) -> None:
bulbs = await get_bulbs()
_validate_mode(mode)
target = PRESETS[mode]
steps = max(int(float(seconds) * 10), 1)
delay = float(seconds) / steps
loop = asyncio.get_event_loop()
start_time = loop.time()
try:
if "duo" in target:
if not bulbs:
return
m1, m2 = target["duo"]
if len(bulbs) == 1:
t1 = PRESETS[m1]
target_bri1 = int(t1.get("brightness", 140))
st1 = await bulbs[0].updateState()
start_bri1 = st1.get_brightness() or 0
for i in range(steps):
level = (i + 1) / steps
bri1 = int(start_bri1 + (target_bri1 - start_bri1) * level)
await bulbs[0].turn_on(PilotBuilder(brightness=bri1))
next_tick = start_time + (i + 1) * delay
await asyncio.sleep(max(0, next_tick - loop.time()))
await _apply_mode_to_bulb(bulbs[0], m1)
print(f"FADE {bulbs[0].ip} -> {mode}")
return
t1 = PRESETS[m1]
t2 = PRESETS[m2]
target_bri1 = int(t1.get("brightness", 140))
target_bri2 = int(t2.get("brightness", 140))
st1, st2 = await asyncio.gather(bulbs[0].updateState(), bulbs[1].updateState())
start_bri1 = st1.get_brightness() or 0
start_bri2 = st2.get_brightness() or 0
for i in range(steps):
level = (i + 1) / steps
bri1 = int(start_bri1 + (target_bri1 - start_bri1) * level)
bri2 = int(start_bri2 + (target_bri2 - start_bri2) * level)
await asyncio.gather(
bulbs[0].turn_on(PilotBuilder(brightness=bri1)),
bulbs[1].turn_on(PilotBuilder(brightness=bri2)),
)
next_tick = start_time + (i + 1) * delay
await asyncio.sleep(max(0, next_tick - loop.time()))
await _apply_mode_to_bulb(bulbs[0], m1)
await _apply_mode_to_bulb(bulbs[1], m2)
print(f"FADE {bulbs[0].ip} {bulbs[1].ip} -> {mode}")
return
if "scene_id" in target:
target_bri = int(target.get("brightness", 140))
target_scene_id = int(target["scene_id"])
else:
target_bri = int(target.get("brightness", 140))
target_scene_id = None
states = await asyncio.gather(*[bulb.updateState() for bulb in bulbs])
start_bris = [s.get_brightness() or 0 for s in states]
for i in range(steps):
level = (i + 1) / steps
tasks = []
for bulb, start_bri in zip(bulbs, start_bris):
bri = int(start_bri + (target_bri - start_bri) * level)
tasks.append(bulb.turn_on(PilotBuilder(brightness=bri)))
await asyncio.gather(*tasks)