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
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# This application is an example on how to use aiolifx
#
# Copyright (c) 2016 François Wautier
# Copyright (c) 2022 Michael Farrell <micolous+git@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
# IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import sys
import asyncio as aio
import aiolifx as alix
from time import sleep
from functools import partial
from enum import Enum
# Simple bulb control frpm console
class bulbs:
"""A simple class with a register and unregister methods"""
def __init__(self):
self.bulbs = []
self.boi = None # bulb of interest
def register(self, bulb):
bulb.get_label()
bulb.get_location()
bulb.get_version()
bulb.get_group()
bulb.get_wififirmware()
bulb.get_hostfirmware()
self.bulbs.append(bulb)
self.bulbs.sort(key=lambda x: x.label or x.mac_addr)
def unregister(self, bulb):
idx = 0
for x in list([y.mac_addr for y in self.bulbs]):
if x == bulb.mac_addr:
del self.bulbs[idx]
break
idx += 1
class BulbOptions(Enum):
BACK = 0
POWER = 1
WHITE = 2
COLOUR = 3
INFO = 4
FIRMWARE = 5
WIFI = 6
UPTIME = 7
PULSE = 8
HEV_CYCLE_OR_FIRMWARE_EFFECT = 9
HEV_CONFIGURATION_OR_FIRMWARE_EFFECT_START_STOP = 10
RELAYS = 11
BUTTON = 12
BUTTON_CONFIG = 13
REBOOT = 99
def readin():
"""Reading from stdin and displaying menu"""
selection = sys.stdin.readline().strip("\n")
MyBulbs.bulbs.sort(key=lambda x: x.label or x.mac_addr)
lov = [x for x in selection.split(" ") if x != ""]
if lov:
if MyBulbs.boi:
# try:
if True:
if int(lov[0]) == BulbOptions.BACK.value:
MyBulbs.boi = None
elif int(lov[0]) == BulbOptions.POWER.value:
if len(lov) > 1:
MyBulbs.boi.set_power(lov[1].lower() in ["1", "on", "true"])
MyBulbs.boi = None
else:
print("Error: For power you must indicate on or off\n")
elif int(lov[0]) == BulbOptions.WHITE.value:
if len(lov) > 2:
try:
MyBulbs.boi.set_color(
[
58275,
0,
int(round((float(lov[1]) * 65365.0) / 100.0)),
int(round(float(lov[2]))),
]
)
MyBulbs.boi = None
except:
print(
"Error: For white brightness (0-100) and temperature (2500-9000) must be numbers.\n"
)
else:
print(
"Error: For white you must indicate brightness (0-100) and temperature (2500-9000)\n"
)
elif int(lov[0]) == BulbOptions.COLOUR.value:
if len(lov) > 3:
try:
MyBulbs.boi.set_color(
[
int(round((float(lov[1]) * 65535.0) / 360.0)),
int(round((float(lov[2]) * 65535.0) / 100.0)),
int(round((float(lov[3]) * 65535.0) / 100.0)),
3500,
]
)
MyBulbs.boi = None
except:
print(
"Error: For colour hue (0-360), saturation (0-100) and brightness (0-100)) must be numbers.\n"
)
else:
print(
"Error: For colour you must indicate hue (0-360), saturation (0-100) and brightness (0-100))\n"
)
elif int(lov[0]) == BulbOptions.INFO.value:
print(MyBulbs.boi.device_characteristics_str(" "))
print(MyBulbs.boi.device_product_str(" "))
MyBulbs.boi = None
elif int(lov[0]) == BulbOptions.FIRMWARE.value:
print(MyBulbs.boi.device_firmware_str(" "))
MyBulbs.boi = None
elif int(lov[0]) == BulbOptions.WIFI.value:
mypartial = partial(MyBulbs.boi.device_radio_str)
MyBulbs.boi.get_wifiinfo(
callb=lambda x, y: print("\n" + mypartial(y))
)
MyBulbs.boi = None
elif int(lov[0]) == BulbOptions.UPTIME.value:
mypartial = partial(MyBulbs.boi.device_time_str)
MyBulbs.boi.get_hostinfo(
callb=lambda x, y: print("\n" + mypartial(y))
)
MyBulbs.boi = None
elif int(lov[0]) == BulbOptions.PULSE.value:
if len(lov) > 3:
try:
print(
"Sending {}".format(
[
int(round((float(lov[1]) * 65535.0) / 360.0)),
int(round((float(lov[2]) * 65535.0) / 100.0)),
int(round((float(lov[3]) * 65535.0) / 100.0)),
3500,
]
)
)
MyBulbs.boi.set_waveform(
{
"color": [
int(round((float(lov[1]) * 65535.0) / 360.0)),
int(round((float(lov[2]) * 65535.0) / 100.0)),
int(round((float(lov[3]) * 65535.0) / 100.0)),
3500,
],
"transient": 1,
"period": 100,
"cycles": 30,
"skew_ratio": 0,
"waveform": 0,
}
)
MyBulbs.boi = None
except:
print(
"Error: For pulse hue (0-360), saturation (0-100) and brightness (0-100)) must be numbers.\n"
)
else:
print(
"Error: For pulse you must indicate hue (0-360), saturation (0-100) and brightness (0-100))\n"
)
elif int(lov[0]) == BulbOptions.HEV_CYCLE_OR_FIRMWARE_EFFECT.value:
if (
alix.aiolifx.products_dict[MyBulbs.boi.product].hev is True
): # HEV cycle
if len(lov) == 1:
# Get current state
print("Getting current HEV state")
MyBulbs.boi.get_hev_cycle(
callb=lambda _, r: print(
f"\nHEV: duration={r.duration}, "
f"remaining={r.remaining}, "
f"last_power={r.last_power}"
)
)
MyBulbs.boi.get_last_hev_cycle_result(
callb=lambda _, r: print(
f"\nHEV result: {r.result_str}"
)
)
elif len(lov) == 2:
duration = int(lov[1])
enable = duration >= 0
if enable:
print(f"Running HEV cycle for {duration} second(s)")
else:
print(f"Aborting HEV cycle")
duration = 0
MyBulbs.boi.set_hev_cycle(
enable=enable,
duration=duration,
callb=lambda _, r: print(
f"\nHEV: duration={r.duration}, "
f"remaining={r.remaining}, "
f"last_power={r.last_power}"
),
)
else:
print("Error: maximum 1 argument for HEV cycle")
MyBulbs.boi = None
elif (
alix.aiolifx.products_dict[MyBulbs.boi.product].multizone
is True
): # Multizone firmware effect
print(
"Getting current firmware effect state from multizone device"
)
MyBulbs.boi.get_multizone_effect(
callb=lambda _, r: print(
f"\nCurrent effect={r.effect_str}"
f"\nSpeed={r.speed/1000 if getattr(r, 'speed', None) is not None else 0}"
f"\nDuration={r.duration/1000000000 if getattr(r, 'duration', None) is not None else 0:4f}"
f"\nDirection={r.direction_str}"
)
)
MyBulbs.boi = None
elif (
int(lov[0])
== BulbOptions.HEV_CONFIGURATION_OR_FIRMWARE_EFFECT_START_STOP.value
):
if (
alix.aiolifx.products_dict[MyBulbs.boi.product].hev is True
): # HEV cycle configuration
if len(lov) == 1:
# Get current state
print("Getting current HEV configuration")
MyBulbs.boi.get_hev_configuration(
callb=lambda _, r: print(
f"\nHEV: indication={r.indication}, "
f"duration={r.duration}"
)
)
elif len(lov) == 3:
indication = bool(int(lov[1]))
duration = int(lov[2])
print(
f"Configuring default HEV cycle with "
f"{'' if indication else 'no '}indication for "
f"{duration} second(s)"
)
MyBulbs.boi.set_hev_configuration(
indication=indication,
duration=duration,
callb=lambda _, r: print(
f"\nHEV: indication={r.indication}, "
f"duration={r.duration}"
),
)
else:
print("Error: 0 or 2 arguments for HEV config")
MyBulbs.boi = None
elif (
alix.aiolifx.products_dict[MyBulbs.boi.product].multizone
is True
): # Start/stop firmware effect
can_set = True
if len(lov) == 3:
effect = str(lov[1])
direction = str(lov[2])
if effect.lower() not in ["off", "move"]:
print("Error: effect parameter must be 'off' or 'move'")
can_set = False
if direction.lower() not in ["left", "right"]:
print(
"Error: direction parameter must be 'right' or 'left"
)
can_set = False
if can_set:
e = alix.aiolifx.MultiZoneEffectType[
effect.upper()
].value
d = alix.aiolifx.MultiZoneDirection[
direction.upper()
].value
MyBulbs.boi.set_multizone_effect(
effect=e, speed=3, direction=d
)
elif len(lov) == 2:
MyBulbs.boi.set_multizone_effect(effect=0)
else:
print(
"Error: need to provide effect and direction parameters."
)
MyBulbs.boi = None
elif int(lov[0]) == BulbOptions.RELAYS.value:
def callback(x, statePower):
return print(
f"Relay {statePower.relay_index + 1}: {'On' if statePower.level == 65535 else 'Off'}"
) # +1 to use 1-indexing
if alix.aiolifx.features_map[MyBulbs.boi.product]["relays"] is True:
# If user provides relay index as second param AND a third param off or on
if len(lov) == 3:
# -1 to use 1-indexing
relay_index = int(lov[1]) - 1
on = [True, 1, "on"]
off = [False, 0, "off"]
set_power = partial(
MyBulbs.boi.set_rpower, relay_index, callb=callback
)
if lov[2] in on:
set_power(True)
elif lov[2] in off:
set_power(False)
else:
values_list = ", ".join(
[str(x) for lst in [on, off] for x in lst]
)
print(
f"Argument not known. Use one of these values: {values_list}"
)
# User has provided a relay index but isn't trying to set the value
elif len(lov) == 2:
# -1 to use 1-indexing
relay_index = int(lov[1]) - 1
MyBulbs.boi.get_rpower(relay_index, callb=callback)
else: # User hasn't provided a relay index so wants all values
MyBulbs.boi.get_rpower(callb=callback)
else:
print(
"This device isn't a switch and therefore doesn't have relays"
)
elif int(lov[0]) == BulbOptions.BUTTON.value:
if alix.aiolifx.features_map[MyBulbs.boi.product]["relays"] is True:
def callback(x, buttonResponse):
def get_action_name(action_index):
if action_index == 0:
return "Single Press"
elif action_index == 1:
return "Double Press"
elif action_index == 2:
return "Long Press"
else:
# To present 1-indexing to users
return f"Action {action_index + 1}"
buttons_str = ""
for button_index, button in enumerate(
buttonResponse.buttons[: buttonResponse.buttons_count]
):
buttons_str += f"Button {button_index + 1}:\n"
# At the moment, LIFX app only supports single, double and long press
MAX_ACTIONS = 3
for action_index, action in enumerate(
button["button_actions"][:MAX_ACTIONS]
):
buttons_str += (
f"\t{get_action_name(action_index)}\n"
+ f"\t\tGesture: {action['button_gesture']}\n"
+ f"\t\t{action['button_target_type']}\n"
+ f"\t\t{action['button_target']}\n"
)
return print(
f"Count: {buttonResponse.count}\n"
+ f"Index: {buttonResponse.index}\n"
+ f"Buttons Count: {buttonResponse.buttons_count}\n"
+ f"Buttons:\n{buttons_str}"
)
MyBulbs.boi.get_button(callback)
elif int(lov[0]) == BulbOptions.BUTTON_CONFIG.value:
if alix.aiolifx.features_map[MyBulbs.boi.product]["relays"] is True:
def callback(x, buttonConfig):
# Switch returns the kelvin value as a byte, so we need to convert it to a kelvin value
# The kelvin value is reversed (higher byte value = lower kelvin).
# Below 10495 and above 56574 are outside the range of supported Kelvin values
def get_kelvin(byte_value):
MIN_KELVIN_VALUE = 1500
MAX_KELVIN_VALUE = 9000
KELVIN_RANGE = MAX_KELVIN_VALUE - MIN_KELVIN_VALUE
MIN_BYTE_VALUE = 10495 # 9000 Kelvin
MAX_BYTE_VALUE = 56575 # 1500 Kelvin
BYTE_RANGE = MAX_BYTE_VALUE - MIN_BYTE_VALUE
if byte_value <= MIN_BYTE_VALUE:
return MAX_KELVIN_VALUE
elif byte_value < MAX_BYTE_VALUE:
return int(
round(
MAX_KELVIN_VALUE
- (
(byte_value - MIN_BYTE_VALUE)
/ BYTE_RANGE
)
* KELVIN_RANGE
)
)
else:
return MIN_KELVIN_VALUE
backlight_on_color = {
"hue": int(
round(
360
* (
buttonConfig.backlight_on_color["hue"]
/ 65535
)
)
),
"saturation": int(
round(
100
* (
buttonConfig.backlight_on_color[
"saturation"
]
/ 65535
)
)
),
"brightness": int(
round(
100
* (
buttonConfig.backlight_on_color[
"brightness"
]
/ 65535
)
)
),
"kelvin": get_kelvin(
buttonConfig.backlight_on_color["kelvin"]
),
}
backlight_on_color_str = f"hue: {backlight_on_color['hue']}, saturation: {backlight_on_color['saturation']}, brightness: {backlight_on_color['brightness']}, kelvin: {backlight_on_color['kelvin']}"
backlight_off_color = {
"hue": int(
round(
360
* (
buttonConfig.backlight_off_color["hue"]
/ 65535
)
)
),
"saturation": int(
round(
100
* (
buttonConfig.backlight_off_color[
"saturation"
]
/ 65535
)
)
),
"brightness": int(
round(
100
* (
buttonConfig.backlight_off_color[
"brightness"
]
/ 65535
)
)
),
"kelvin": get_kelvin(
buttonConfig.backlight_off_color["kelvin"]
),
}
backlight_off_color_str = f"hue: {backlight_off_color['hue']}, saturation: {backlight_off_color['saturation']}, brightness: {backlight_off_color['brightness']}, kelvin: {backlight_off_color['kelvin']}"
return print(
f"Haptic Duration (ms): {buttonConfig.haptic_duration_ms}\nBacklight on color: {backlight_on_color_str}\nBacklight off color: {backlight_off_color_str}"
)
if len(lov) == 10:
haptic_duration_ms = int(lov[1])
# Switch accepts the actual kelvin value as the input
def get_kelvin(input):
if input < 1500 or input > 9000:
print("Kelvin must be between 1500 and 9000")
return 1500
return input
backlight_on_color = {
"hue": int(round(65535 * (int(lov[2]) / 360))),
"saturation": int(round(65535 * (int(lov[3]) / 100))),
"brightness": int(round(65535 * (int(lov[4]) / 100))),
"kelvin": get_kelvin(int(lov[5])),
}
backlight_off_color = {
"hue": int(round(65535 * (int(lov[6]) / 360))),
"saturation": int(round(65535 * (int(lov[7]) / 100))),
"brightness": int(round(65535 * (int(lov[8]) / 100))),
"kelvin": get_kelvin(int(lov[9])),
}
MyBulbs.boi.set_button_config(
haptic_duration_ms,
backlight_on_color,
backlight_off_color,
callback,
)
elif len(lov) > 1:
print(
"Error: Format should be: <haptic_duration_ms> <backlight_on_color_hue> (0-360) <backlight_on_color_saturation> (0-100) <backlight_on_color_brightness> (0-100) <backlight_on_color_kelvin> (2500-9000) <backlight_off_color_hue> (0-360) <backlight_off_color_saturation> (0-100) <backlight_off_color_brightness> (0-100) <backlight_off_color_kelvin> (2500-9000)"
)
else:
MyBulbs.boi.get_button_config(callback)
elif int(lov[0]) == 99:
# Reboot bulb
print(
"Rebooting bulb in 3 seconds. If the bulb is on, it will flicker off and back on as it reboots."
)
print(
"Hit CTRL-C within 3 seconds to to quit without rebooting the bulb."
)
sleep(3)
MyBulbs.boi.set_reboot()
print("Bulb rebooted.")
# except:
# print ("\nError: Selection must be a number.\n")
else:
try:
if int(lov[0]) > 0:
if int(lov[0]) <= len(MyBulbs.bulbs):
MyBulbs.boi = MyBulbs.bulbs[int(lov[0]) - 1]
else:
print("\nError: Not a valid selection.\n")
except:
print("\nError: Selection must be a number.\n")
if MyBulbs.boi:
print("Select Function for {}:".format(MyBulbs.boi.label))
print(f"\t[{BulbOptions.POWER.value}]\tPower (0 or 1)")
print(f"\t[{BulbOptions.WHITE.value}]\tWhite (Brightness Temperature)")
print(f"\t[{BulbOptions.COLOUR.value}]\tColour (Hue Saturation Brightness)")
print(f"\t[{BulbOptions.INFO.value}]\tInfo")
print(f"\t[{BulbOptions.FIRMWARE.value}]\tFirmware")
print(f"\t[{BulbOptions.WIFI.value}]\tWifi")
print(f"\t[{BulbOptions.UPTIME.value}]\tUptime")
print(f"\t[{BulbOptions.PULSE.value}]\tPulse")
if alix.aiolifx.products_dict[MyBulbs.boi.product].hev is True:
print(
f"\t[{BulbOptions.HEV_CYCLE_OR_FIRMWARE_EFFECT.value}]\tHEV cycle (duration, or -1 to stop)"
)
print(
f"\t[{BulbOptions.HEV_CONFIGURATION_OR_FIRMWARE_EFFECT_START_STOP.value}]\tHEV configuration (indication, duration)"
)
if alix.aiolifx.products_dict[MyBulbs.boi.product].multizone is True:
print(
f"\t[{BulbOptions.HEV_CYCLE_OR_FIRMWARE_EFFECT.value}]\tGet firmware effect status"
)
print(
f"\t[{BulbOptions.HEV_CONFIGURATION_OR_FIRMWARE_EFFECT_START_STOP.value}]\tStart or stop firmware effect ([off/move] [right|left])"
)
if alix.aiolifx.products_dict[MyBulbs.boi.product].relays is True:
print(
f"\t[{BulbOptions.RELAYS.value}]\tRelays; optionally followed by relay number (beginning at 1); optionally followed by `on` or `off` to set the value"
)
print(f"\t[{BulbOptions.BUTTON.value}]\tButton")
print(
f"\t[{BulbOptions.BUTTON_CONFIG.value}]\tButton Config. Optionally followed by <haptic_duration_ms> <backlight_on_color_hue> (0-360; if not 0, kelvin is ignored) <backlight_on_color_saturation> (0-100) <backlight_on_color_brightness> (0-100) <backlight_on_color_kelvin> (2500-9000) <backlight_off_color_hue> (0-360; if not 0, kelvin is ignored) <backlight_off_color_saturation> (0-100) <backlight_off_color_brightness> (0-100) <backlight_off_color_kelvin> (2500-9000)"
)
print(
f"\t[{BulbOptions.REBOOT.value}]\tReboot the bulb (indicated by a reboot blink)"
)
print("")
print(f"\t[{BulbOptions.BACK.value}]\tBack to bulb selection")
else:
idx = 1
print("Select Bulb:")
for x in MyBulbs.bulbs:
print("\t[{}]\t{}".format(idx, x.label or x.mac_addr))
idx += 1
print("")
print("Your choice: ", end="", flush=True)
async def scan(loop, discovery):
scanner = alix.LifxScan(loop)
ips = await scanner.scan()
print('Hit "Enter" to start')
print("Use Ctrl-C to quit")
if not ips:
print("LIFX controller not found!")
return
discovery.start(listen_ip=ips[0])
MyBulbs = bulbs()
loop = aio.get_event_loop()
discovery = alix.LifxDiscovery(loop, MyBulbs)
try:
loop.add_reader(sys.stdin, readin)
loop.create_task(scan(loop, discovery))
loop.run_forever()
except:
pass
finally:
discovery.cleanup()
loop.remove_reader(sys.stdin)
loop.close()
|