Debian Codegraph @

flux_led/fluxled.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """
3 This is a utility for controlling stand-alone Flux WiFi LED light bulbs.
4
5 The protocol was reverse-engineered by studying packet captures between a
6 bulb and the controlling "Magic Home" mobile app. The code here dealing
7
8 with the network protocol is littered with magic numbers, and ain't so pretty.
9 But it does seem to work!
10
11 So far most of the functionality of the apps is available here via the CLI
12 and/or programmatically.
13
14 The classes in this project could very easily be used as an API, and incorporated into a GUI app written
15 in PyQt, Kivy, or some other framework.
16
17 ##### Available:
18 * Discovering bulbs on LAN
19 * Turning on/off bulb
20 * Get state information
21 * Setting "warm white" mode
22 * Setting single color mode
23 * Setting preset pattern mode
24 * Setting custom pattern mode
25 * Reading timers
26 * Setting timers
27
28 ##### Some missing pieces:
29 * Initial administration to set up WiFi SSID and passphrase/key.
30 * Remote access administration
31 * Music-relating pulsing. This feature isn't so impressive on the Magic Home app,
32 and looks like it might be a bit of work.
33
34 ##### Cool feature:
35 * Specify colors with names or web hex values. Requires that python "webcolors"
36 package is installed. (Easily done via pip, easy_install, or apt-get, etc.)
37 See the following for valid color names: http://www.w3schools.com/html/html_colornames.asp
38
39 """
40
41 from __future__ import annotations
42
43 import asyncio
44 import datetime
45 import logging
46 import sys
47 from optparse import OptionGroup, OptionParser, Values
48 from typing import Any
49
50 from .aio import AIOWifiLedBulb
51 from .aioscanner import AIOBulbScanner
52 from .const import ATTR_ID, ATTR_IPADDR
53 from .pattern import PresetPattern
54 from .scanner import FluxLEDDiscovery
55 from .timer import LedTimer
56 from .utils import utils
57
58 _LOGGER = logging.getLogger(__name__)
59
60
61 # =======================================================================
62 def showUsageExamples() -> None:
63 example_text = """
64 Examples:
65
66 Scan network:
67 %prog% -s
68
69 Scan network and show info about all:
70 %prog% -sSti
71
72 Turn on:
73 %prog% 192.168.1.100 --on
74 %prog% 192.168.1.100 -192.168.1.101 -1
75
76 Turn on all bulbs on LAN:
77 %prog% -sS --on
78
79 Turn off:
80 %prog% 192.168.1.100 --off
81 %prog% 192.168.1.100 --0
82 %prog% -sS --off
83
84 Set warm white, 75%
85 %prog% 192.168.1.100 -w 75
86
87 Set cold white, 55%
88 %prog% 192.168.1.100 -d 55
89
90 Set CCT, 3500 85%
91 %prog% 192.168.1.100 -k 3500 85
92
93 Set fixed color red :
94 %prog% 192.168.1.100 -c Red
95 %prog% 192.168.1.100 -c 255,0,0
96 %prog% 192.168.1.100 -c "#FF0000"
97
98 Set RGBW 25 100 200 50:
99 %prog% 192.168.1.100 -c 25,100,200,50
100
101 Set RGBWW 25 100 200 50 30:
102 %prog% 192.168.1.100 -c 25,100,200,50,30
103
104 Set preset pattern #35 with 40% speed:
105 %prog% 192.168.1.100 -p 35 40
106
107 Set custom pattern 25% speed, red/green/blue, gradual change:
108 %prog% 192.168.1.100 -C gradual 25 "red green (0,0,255)"
109
110 Sync all bulb's clocks with this computer's:
111 %prog% -sS --setclock
112
113 Set timer #1 to turn on red at 5:30pm on weekdays:
114 %prog% 192.168.1.100 -T 1 color "time:1730;repeat:12345;color:red"
115
116 Deactivate timer #4:
117 %prog% 192.168.1.100 -T 4 inactive ""
118
119 Use --timerhelp for more details on setting timers
120 """
121
122 print(example_text.replace("%prog%", sys.argv[0]))
123
124
125 def showTimerHelp() -> None:
126 timerhelp_text = """
127 There are 6 timers available for each bulb.
128
129 Mode Details:
130 inactive: timer is inactive and unused
131 poweroff: turns off the light
132 default: turns on the light in default mode
133 color: turns on the light with specified color
134 preset: turns on the light with specified preset and speed
135 warmwhite: turns on the light with warm white at specified brightness
136
137 Settings available for each mode:
138 Timer Mode | Settings
139 --------------------------------------------
140 inactive: [none]
141 poweroff: time, (repeat | date)
142 default: time, (repeat | date)
143 color: time, (repeat | date), color
144 preset: time, (repeat | date), code, speed
145 warmwhite: time, (repeat | date), level
146 sunrise: time, (repeat | date), startBrightness, endBrightness, duration
147 sunset: time, (repeat | date), startBrightness, endBrightness, duration
148
149 Setting Details:
150
151 time: 4 digit string with zeros, no colons
152 e.g:
153 "1000" - for 10:00am
154 "2312" - for 11:23pm
155 "0315" - for 3:15am
156
157 repeat: Days of the week that the timer should repeat
158 (Mutually exclusive with date)
159 0=Sun, 1=Mon, 2=Tue, 3=Wed, 4=Thu, 5=Fri, 6=Sat
160 e.g:
161 "0123456" - everyday
162 "06" - weekends
163 "12345" - weekdays
164 "2" - only Tuesday
165
166 date: Date that the one-time timer should fire
167 (Mutually exclusive with repeat)
168 e.g:
169 "2015-09-13"
170 "2016-12-03"
171
172 color: Color name, hex code, or rgb triple
173
174 level: Level of the warm while light (0-100)
175
176 code: Code of the preset pattern (use -l to list them)
177
178 speed: Speed of the preset pattern transitions (0-100)
179
180 startBrightness: starting brightness of warmlight (0-100)
181
182 endBrightness: ending brightness of warmlight (0-100)
183
184 duration: transition time in minutes
185
186 Example setting strings:
187 "time:2130;repeat:0123456"
188 "time:2130;date:2015-08-11"
189 "time:1245;repeat:12345;color:123,345,23"
190 "time:1245;repeat:12345;color:green"
191 "time:1245;repeat:06;code:50;speed:30"
192 "time:0345;date:2015-08-11;level:100"
193 """
194
195 print(timerhelp_text)
196
197
198 def processSetTimerArgs(parser: OptionParser, args: Any) -> LedTimer:
199 mode = args[1]
200 num = args[0]
201 settings = args[2]
202
203 if not num.isdigit() or int(num) > 6 or int(num) < 1:
204 parser.error("Timer number must be between 1 and 6")
205
206 # create a dict from the settings string
207 settings_list = settings.split(";")
208 settings_dict = {}
209 for s in settings_list:
210 pair = s.split(":")
211 key = pair[0].strip().lower()
212 val = ""
213 if len(pair) > 1:
214 val = pair[1].strip().lower()
215 settings_dict[key] = val
216
217 keys = list(settings_dict.keys())
218 timer = LedTimer()
219
220 if mode == "inactive":
221 # no setting needed
222 timer.setActive(False)
223
224 elif mode in [
225 "poweroff",
226 "default",
227 "color",
228 "preset",
229 "warmwhite",
230 "sunrise",
231 "sunset",
232 ]:
233 timer.setActive(True)
234
235 if "time" not in keys:
236 parser.error(f"This mode needs a time: {mode}")
237 if "repeat" in keys and "date" in keys:
238 parser.error(f"This mode only a repeat or a date, not both: {mode}")
239
240 # validate time format
241 if len(settings_dict["time"]) != 4 or not settings_dict["time"].isdigit():
242 parser.error("time must be a 4 digits")
243 hour = int(settings_dict["time"][0:2:])
244 minute = int(settings_dict["time"][2:4:])
245 if hour > 23:
246 parser.error("timer hour can't be greater than 23")
247 if minute > 59:
248 parser.error("timer minute can't be greater than 59")
249
250 timer.setTime(hour, minute)
251
252 # validate date format
253 if "repeat" not in keys and "date" not in keys:
254 # Generate date for next occurance of time
255 print("No time or repeat given. Defaulting to next occurance of time")
256 now = datetime.datetime.now()
257 dt = now.replace(hour=hour, minute=minute)
258 if utils.date_has_passed(dt):
259 dt = dt + datetime.timedelta(days=1)
260 # settings_dict["date"] = date
261 timer.setDate(dt.year, dt.month, dt.day)
262 elif "date" in keys:
263 try:
264 dt = datetime.datetime.strptime(settings_dict["date"], "%Y-%m-%d")
265 timer.setDate(dt.year, dt.month, dt.day)
266 except ValueError:
267 parser.error("date is not properly formatted: YYYY-MM-DD")
268
269 # validate repeat format
270 if "repeat" in keys:
271 if len(settings_dict["repeat"]) == 0:
272 parser.error("Must specify days to repeat")
273 days = set()
274 for c in list(settings_dict["repeat"]):
275 if c not in ["0", "1", "2", "3", "4", "5", "6"]:
276 parser.error("repeat can only contain digits 0-6")
277 days.add(int(c))
278
279 repeat = 0
280 if 0 in days:
281 repeat |= LedTimer.Su
282 if 1 in days:
283 repeat |= LedTimer.Mo
284 if 2 in days:
285 repeat |= LedTimer.Tu
286 if 3 in days:
287 repeat |= LedTimer.We
288 if 4 in days:
289 repeat |= LedTimer.Th
290 if 5 in days:
291 repeat |= LedTimer.Fr
292 if 6 in days:
293 repeat |= LedTimer.Sa
294 timer.setRepeatMask(repeat)
295
296 if mode == "default":
297 timer.setModeDefault()
298
299 if mode == "poweroff":
300 timer.setModeTurnOff()
301
302 if mode == "color":
303 if "color" not in keys:
304 parser.error("color mode needs a color setting")
305 # validate color val
306 c = utils.color_object_to_tuple(settings_dict["color"]) # type: ignore
307 if c is None:
308 parser.error("Invalid color value: {}".format(settings_dict["color"]))
309 assert c is not None
310 timer.setModeColor(c[0], c[1], c[2]) # type: ignore
311
312 if mode == "preset":
313 if "code" not in keys:
314 parser.error(f"preset mode needs a code: {mode}")
315 if "speed" not in keys:
316 parser.error(f"preset mode needs a speed: {mode}")
317 code = settings_dict["code"]
318 speed = settings_dict["speed"]
319 if not speed.isdigit() or int(speed) > 100:
320 parser.error("preset speed must be a percentage (0-100)")
321 if not code.isdigit() or not PresetPattern.valid(int(code)):
322 parser.error("preset code must be in valid range")
323 timer.setModePresetPattern(int(code), int(speed))
324
325 if mode == "warmwhite":
326 if "level" not in keys:
327 parser.error(f"warmwhite mode needs a level: {mode}")
328 level = settings_dict["level"]
329 if not level.isdigit() or int(level) > 100:
330 parser.error("warmwhite level must be a percentage (0-100)")
331 timer.setModeWarmWhite(int(level))
332
333 if mode == "sunrise" or mode == "sunset":
334 if "startbrightness" not in keys:
335 parser.error(f"{mode} mode needs a startBrightness (0% -> 100%)")
336 startBrightness = int(settings_dict["startbrightness"])
337
338 if "endbrightness" not in keys:
339 parser.error(f"{mode} mode needs an endBrightness (0% -> 100%)")
340 endBrightness = int(settings_dict["endbrightness"])
341
342 if "duration" not in keys:
343 parser.error(f"{mode} mode needs a duration (minutes)")
344 duration = int(settings_dict["duration"])
345
346 if mode == "sunrise":
347 timer.setModeSunrise(startBrightness, endBrightness, duration)
348
349 elif mode == "sunset":
350 timer.setModeSunset(startBrightness, endBrightness, duration)
351
352 else:
353 parser.error(f"Not a valid timer mode: {mode}")
354
355 return timer
356
357
358 def processCustomArgs(
359 parser: OptionParser, args: Any
360 ) -> tuple[Any, int, list[tuple[int, ...]]] | None:
361 if args[0] not in ["gradual", "jump", "strobe"]:
362 parser.error(f"bad pattern type: {args[0]}")
363 return None
364
365 speed = int(args[1])
366
367 # convert the string to a list of RGB tuples
368 # it should have space separated items of either
369 # color names, hex values, or byte triples
370 try:
371 color_list_str = args[2].strip()
372 str_list = color_list_str.split(" ")
373 color_list = []
374 for s in str_list:
375 c = utils.color_object_to_tuple(s)
376 if c is not None:
377 color_list.append(c)
378 else:
379 raise Exception
380
381 except Exception:
382 parser.error(
383 "COLORLIST isn't formatted right. It should be a space separated list of RGB tuples, color names or web hex values"
384 )
385
386 return args[0], speed, color_list
387
388
389 def parseArgs() -> tuple[Values, Any]:
390 parser = OptionParser()
391
392 parser.description = "A utility to control Flux WiFi LED Bulbs. "
393 # parser.description += ""
394 # parser.description += "."
395 power_group = OptionGroup(parser, "Power options (mutually exclusive)")
396 mode_group = OptionGroup(parser, "Mode options (mutually exclusive)")
397 info_group = OptionGroup(parser, "Program help and information option")
398 other_group = OptionGroup(parser, "Other options")
399
400 parser.add_option_group(info_group)
401 info_group.add_option(
402 "--debug",
403 action="store_true",
404 dest="debug",
405 default=False,
406 help="Enable debug logging",
407 )
408 info_group.add_option(
409 "-e",
410 "--examples",
411 action="store_true",
412 dest="showexamples",
413 default=False,
414 help="Show usage examples",
415 )
416 info_group.add_option(
417 "",
418 "--timerhelp",
419 action="store_true",
420 dest="timerhelp",
421 default=False,
422 help="Show detailed help for setting timers",
423 )
424 info_group.add_option(
425 "-l",
426 "--listpresets",
427 action="store_true",
428 dest="listpresets",
429 default=False,
430 help="List preset codes",
431 )
432 info_group.add_option(
433 "--listcolors",
434 action="store_true",
435 dest="listcolors",
436 default=False,
437 help="List color names",
438 )
439
440 parser.add_option(
441 "-s",
442 "--scan",
443 action="store_true",
444 dest="scan",
445 default=False,
446 help="Search for bulbs on local network",
447 )
448 parser.add_option(
449 "-S",
450 "--scanresults",
451 action="store_true",
452 dest="scanresults",
453 default=False,
454 help="Operate on scan results instead of arg list",
455 )
456 power_group.add_option(
457 "-1",
458 "--on",
459 action="store_true",
460 dest="on",
461 default=False,
462 help="Turn on specified bulb(s)",
463 )
464 power_group.add_option(
465 "-0",
466 "--off",
467 action="store_true",
468 dest="off",
469 default=False,
470 help="Turn off specified bulb(s)",
471 )
472 parser.add_option_group(power_group)
473
474 mode_group.add_option(
475 "-c",
476 "--color",
477 dest="color",
478 default=None,
479 help="""For setting a single color mode. Can be either color name, web hex, or comma-separated RGB triple.
480 For setting an RGBW can be a comma-seperated RGBW list
481 For setting an RGBWW can be a comma-seperated RGBWW list""",
482 metavar="COLOR",
483 )
484 mode_group.add_option(
485 "-w",
486 "--warmwhite",
487 dest="ww",
488 default=None,
489 help="Set warm white mode (LEVELWW is percent)",
490 metavar="LEVELWW",
491 type="int",
492 )
493 mode_group.add_option(
494 "-d",
495 "--coldwhite",
496 dest="cw",
497 default=None,
498 help="Set cold white mode (LEVELCW is percent)",
499 metavar="LEVELCW",
500 type="int",
501 )
502 mode_group.add_option(
503 "-k",
504 "--CCT",
505 dest="cct",
506 default=None,
507 help="Temperture and brightness (CCT Kelvin, brightness percent)",
508 metavar="LEVELCCT",
509 type="int",
510 nargs=2,
511 )
512 mode_group.add_option(
513 "-p",
514 "--preset",
515 dest="preset",
516 default=None,
517 help="Set preset pattern mode (SPEED is percent)",
518 metavar="CODE SPEED",
519 type="int",
520 nargs=2,
521 )
522 mode_group.add_option(
523 "-C",
524 "--custom",
525 dest="custom",
526 metavar="TYPE SPEED COLORLIST",
527 default=None,
528 nargs=3,
529 help="Set custom pattern mode. "
530 + "TYPE should be jump, gradual, or strobe. SPEED is percent. "
531 + "COLORLIST is a space-separated list of color names, web hex values, or comma-separated RGB triples",
532 )
533 parser.add_option_group(mode_group)
534
535 parser.add_option(
536 "-i",
537 "--info",
538 action="store_true",
539 dest="info",
540 default=False,
541 help="Info about bulb(s) state",
542 )
543 parser.add_option(
544 "",
545 "--getclock",
546 action="store_true",
547 dest="getclock",
548 default=False,
549 help="Get clock",
550 )
551 parser.add_option(
552 "",
553 "--setclock",
554 action="store_true",
555 dest="setclock",
556 default=False,
557 help="Set clock to same as current time on this computer",
558 )
559 parser.add_option(
560 "-t",
561 "--timers",
562 action="store_true",
563 dest="showtimers",
564 default=False,
565 help="Show timers",
566 )
567 parser.add_option(
568 "-T",
569 "--settimer",
570 dest="settimer",
571 metavar="NUM MODE SETTINGS",
572 default=None,
573 nargs=3,
574 help="Set timer. "
575 + "NUM: number of the timer (1-6). "
576 + "MODE: inactive, poweroff, default, color, preset, or warmwhite. "
577 + "SETTINGS: a string of settings including time, repeatdays or date, "
578 + "and other mode specific settings. Use --timerhelp for more details.",
579 )
580
581 parser.add_option(
582 "--protocol",
583 dest="protocol",
584 default=None,
585 metavar="PROTOCOL",
586 help="Set the device protocol. Currently only supports LEDENET",
587 )
588
589 other_group.add_option(
590 "-v",
591 "--volatile",
592 action="store_true",
593 dest="volatile",
594 default=False,
595 help="Don't persist mode setting with hard power cycle (RGB and WW modes only).",
596 )
597 parser.add_option_group(other_group)
598
599 parser.usage = "usage: %prog [-sS10cwdkpCiltThe] [addr1 [addr2 [addr3] ...]."
600 (options, args) = parser.parse_args()
601
602 if options.debug:
603 logging.basicConfig(level=logging.DEBUG)
604
605 if options.showexamples:
606 showUsageExamples()
607 sys.exit(0)
608
609 if options.timerhelp:
610 showTimerHelp()
611 sys.exit(0)
612
613 if options.listpresets:
614 for c in range(
615 PresetPattern.seven_color_cross_fade, PresetPattern.seven_color_jumping + 1
616 ):
617 print(f"{c:2} {PresetPattern.valtostr(c)}")
618 sys.exit(0)
619
620 if options.listcolors:
621 for c in utils.get_color_names_list(): # type: ignore
622 print(f"{c}, ")
623 print()
624 sys.exit(0)
625
626 if options.settimer:
627 new_timer = processSetTimerArgs(parser, options.settimer)
628 options.new_timer = new_timer
629 else:
630 options.new_timer = None
631
632 mode_count = 0
633 if options.color:
634 mode_count += 1
635 if options.ww:
636 mode_count += 1
637 if options.cw:
638 mode_count += 1
639 if options.cct:
640 mode_count += 1
641 if options.preset:
642 mode_count += 1
643 if options.custom:
644 mode_count += 1
645 if mode_count > 1:
646 parser.error(
647 "options --color, --*white, --preset, --CCT, and --custom are mutually exclusive"
648 )
649
650 if options.on and options.off:
651 parser.error("options --on and --off are mutually exclusive")
652
653 if options.custom:
654 options.custom = processCustomArgs(parser, options.custom)
655
656 if options.color:
657 options.color = utils.color_object_to_tuple(options.color)
658 if options.color is None:
659 parser.error("bad color specification")
660
661 if options.preset:
662 if not PresetPattern.valid(options.preset[0]):
663 parser.error("Preset code is not in range")
664
665 # asking for timer info, implicitly gets the state
666 if options.showtimers:
667 options.info = True
668
669 op_count = mode_count
670 if options.on:
671 op_count += 1
672 if options.off:
673 op_count += 1
674 if options.info:
675 op_count += 1
676 if options.getclock:
677 op_count += 1
678 if options.setclock:
679 op_count += 1
680 if options.listpresets:
681 op_count += 1
682 if options.settimer:
683 op_count += 1
684
685 if (not options.scan or options.scanresults) and (op_count == 0):
686 parser.error("An operation must be specified")
687
688 # if we're not scanning, IP addresses must be specified as positional args
689 if not options.scan and not options.scanresults and not options.listpresets:
690 if len(args) == 0:
691 parser.error(
692 "You must specify at least one IP address as an argument, or use scan results"
693 )
694
695 return (options, args)
696
697
698 # -------------------------------------------
699
700
701 async def _async_run_commands(
702 bulb: AIOWifiLedBulb, info: FluxLEDDiscovery, options: Any
703 ) -> None:
704 """Run requested commands on a bulb."""
705 buffer = ""
706
707 def buf_in(str: str) -> None:
708 nonlocal buffer
709 buffer += str + "\n"
710
711 if options.getclock:
712 buf_in(
713 "{} [{}] {}".format(info["id"], info["ipaddr"], await bulb.async_get_time())
714 )
715
716 if options.setclock:
717 await bulb.async_set_time()
718
719 if options.ww is not None:
720 if options.ww > 100:
721 raise ValueError("Input can not be higher than 100%")
722 buf_in(f"Setting warm white mode, level: {options.ww}%")
723 await bulb.async_set_levels(
724 w=utils.percentToByte(options.ww), persist=not options.volatile
725 )
726
727 if options.cw is not None:
728 if options.cw > 100:
729 raise ValueError("Input can not be higher than 100%")
730 buf_in(f"Setting cold white mode, level: {options.cw}%")
731 await bulb.async_set_levels(
732 w2=utils.percentToByte(options.cw), persist=not options.volatile
733 )
734
735 if options.cct is not None:
736 if options.cct[1] > 100:
737 raise ValueError("Brightness can not be higher than 100%")
738 if options.cct[0] < 2700 or options.cct[0] > 6500:
739 buf_in("Color Temp must be between 2700 and 6500")
740 else:
741 buf_in(
742 f"Setting LED temperature {options.cct[0]}K and brightness: {options.cct[1]}%"
743 )
744 await bulb.async_set_white_temp(
745 options.cct[0], options.cct[1] * 2.55, persist=not options.volatile
746 )
747
748 if options.color is not None:
749 buf_in(
750 f"Setting color RGB:{options.color}",
751 )
752 name = utils.color_tuple_to_string(options.color)
753 if name is None:
754 buf_in("")
755 else:
756 buf_in(f"[{name}]")
757 if any(i < 0 or i > 255 for i in options.color):
758 raise ValueError("Invalid value received must be between 0-255")
759 if len(options.color) == 3:
760 await bulb.async_set_levels(
761 options.color[0],
762 options.color[1],
763 options.color[2],
764 persist=not options.volatile,
765 )
766 elif len(options.color) == 4:
767 await bulb.async_set_levels(
768 options.color[0],
769 options.color[1],
770 options.color[2],
771 options.color[3],
772 persist=not options.volatile,
773 )
774 elif len(options.color) == 5:
775 await bulb.async_set_levels(
776 options.color[0],
777 options.color[1],
778 options.color[2],
779 options.color[3],
780 options.color[4],
781 persist=not options.volatile,
782 )
783
784 elif options.custom is not None:
785 await bulb.async_set_custom_pattern(
786 options.custom[2], options.custom[1], options.custom[0]
787 )
788 buf_in(
789 f"Setting custom pattern: {options.custom[0]}, Speed={options.custom[1]}%, {options.custom[2]}"
790 )
791
792 elif options.preset is not None:
793 buf_in(
794 f"Setting preset pattern: {PresetPattern.valtostr(options.preset[0])}, Speed={options.preset[1]}%"
795 )
796 await bulb.async_set_preset_pattern(options.preset[0], options.preset[1])
797
798 if options.on:
799 buf_in(f"Turning on bulb at {bulb.ipaddr}")
800 await bulb.async_turn_on()
801 elif options.off:
802 buf_in(f"Turning off bulb at {bulb.ipaddr}")
803 await bulb.async_turn_off()
804
805 if options.info:
806 buf_in("{} [{}] {} ({})".format(info["id"], info["ipaddr"], bulb, bulb.model))
807
808 if options.settimer:
809 empty_timers: list[LedTimer] = []
810 timers = await bulb.async_get_timers() or empty_timers
811 num = int(options.settimer[0])
812 buf_in(f"New Timer ---- #{num}: {options.new_timer}")
813 if options.new_timer.isExpired():
814 buf_in("[timer is already expired, will be deactivated]")
815 timers[num - 1] = options.new_timer
816 await bulb.async_set_timers(timers)
817
818 if options.showtimers:
819 show_timers = await bulb.async_get_timers()
820 if show_timers:
821 for idx, t in enumerate(show_timers):
822 buf_in(f" Timer #{idx + 1}: {t}")
823 buf_in("")
824
825 print(buffer.rstrip("\n"))
826
827
828 async def _async_process_bulb(info: FluxLEDDiscovery, options: Any) -> None:
829 """Process a bulb."""
830 bulb = AIOWifiLedBulb(info["ipaddr"], discovery=info)
831 await bulb.async_setup(lambda *args: None)
832 try:
833 await _async_run_commands(bulb, info, options)
834 finally:
835 await bulb.async_stop()
836
837
838 async def async_main() -> None:
839 (options, args) = parseArgs()
840 scanner = AIOBulbScanner()
841
842 if options.scan:
843 await scanner.async_scan(timeout=6)
844 bulb_info_list = scanner.getBulbInfo()
845 # we have a list of buld info dicts
846 addrs = []
847 if options.scanresults and len(bulb_info_list) > 0:
848 for b in bulb_info_list:
849 addrs.append(b["ipaddr"])
850 else:
851 print(f"{len(bulb_info_list)} bulbs found")
852 for b in bulb_info_list:
853 print(" {} {}".format(b["id"], b["ipaddr"]))
854 return
855 else:
856 if options.info:
857 for addr in args:
858 await scanner.async_scan(timeout=6, address=addr)
859 bulb_info_list = scanner.getBulbInfo()
860 else:
861 bulb_info_list = []
862 found_addrs = {discovery[ATTR_IPADDR] for discovery in bulb_info_list}
863 for addr in args:
864 if addr in found_addrs:
865 continue
866 bulb_info_list.append(
867 FluxLEDDiscovery({ATTR_IPADDR: addr, ATTR_ID: "Unknown ID"}) # type: ignore[typeddict-item]
868 )
869
870 # now we have our bulb list, perform same operation on all of them
871 tasks = [_async_process_bulb(info, options) for info in bulb_info_list]
872 results = await asyncio.gather(
873 *tasks,
874 return_exceptions=True,
875 )
876 for idx, info in enumerate(bulb_info_list):
877 if isinstance(results[idx], Exception):
878 msg = str(results[idx]) or type(results[idx])
879 print(f"Error while processing {info}: {msg}")
880 return
881
882
883 def main() -> None:
884 asyncio.run(async_main())
885
886
887 if __name__ == "__main__":
888 main()
889 sys.exit(0)