def __init__(self, bulb_mac=None, bulb_ip=None): logging.debug("Initialising LifxController.") self.lan = LifxLAN() self.bulbs = None self.groups = None self.bulb_labels: list = [] self.group_labels: list = [] self.bulb = None self.group = None self.bulb_mac = bulb_mac self.bulb_ip = bulb_ip # Logger config self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) self.ch = logging.StreamHandler() self.ch.setLevel(logging.DEBUG) self.formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.ch.setFormatter(self.formatter) self.logger.addHandler(self.ch) # When loading config, we don't need to discover the bulb if self.bulb_mac and self.bulb_ip: from lifxlan import Light self.bulb = Light(self.bulb_mac, self.bulb_ip)
def light_to_dict(light: Light): return { 'name': light.get_label(), 'power': bool(light.get_power()), 'color': light.get_color(), 'macAddress': light.get_mac_addr() }
def get(self, name): if (name == "test"): light = Light("d0:73:d5:26:91:07", "10.10.1.146") light.set_color(BLUE, rapid=True) #toggle_light_color(light, 0.2) return "test activated", 200 return "Scene not found", 404
def state(self, device): bulbRef = Light(device['mac'], device['ip']) hsbk = bulbRef.get_color() dev = Device(device['mac'], device['ip'], bulbRef.get_power(), hsbk[0], hsbk[1], hsbk[2], hsbk[3]) return json.dumps(dev.__dict__)
def power_status(mac, ip): try: light = Light(mac, ip) power_state = light.get_power() return power_state except Exception as e: print(e)
def __init__(self, mac = None, ip = None): self.bulb = None if mac != None and ip != None: self.bulb = Light(mac, ip) # put a try block in here later elif self.bulb == None: #put this in the catch block later lights = LifxLAN(1) self.bulb = lights.get_lights()[0] # just get whatever light you find else: lights = LifxLAN(1) self.bulb = lights.get_lights()[0] self.color = 0 #self.colors = [BLUE, CYAN, GREEN, ORANGE, PINK, PURPLE, RED, YELLOW, WHITE] self.colors = [BLUE, GREEN, RED, WHITE]
def toggle_device_power(device: lifxlan.Light, interval=.5, num_cycles=3): original_power_state = device.get_power() device.set_power("off") rapid = True if interval < 1 else False for i in range(num_cycles): device.set_power("on", rapid) sleep(interval) device.set_power("off", rapid) sleep(interval) device.set_power(original_power_state)
def set_brightness(self, br): br = br * 65535 try: for x in self.lifx_lights: mac, ip = x[0], x[1] light = Light(mac, ip) current_hue, current_sat, current_br, current_ke = light.get_color( ) light.set_color([current_hue, current_sat, br, current_ke], duration=.1 * 1000, rapid=False) except Exception as e: print(e)
def Main(): while True: i = GPIO.input(23) if i == 0: #When output from motion sensor is LOW now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "No Motion Detected. Pin reads", i while True: try: powerstatus = Light.get_power(doorlight) except: now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "Couldn't get powerstatus while no motion is detected. Return is", powerstatus continue break now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "Before no motion power check", powerstatus if powerstatus != 0: #Check if lights are currently turned on now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "After power check inside no motion", powerstatus officelights.set_power(0) #Turn lights off time.sleep(10) elif i == 1: #When output from motion sensor is HIGH now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "Motion Detected. Pin reads", i while True: try: powerstatus = Light.get_power(doorlight) except: now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "Couldn't get powerstatus while motion is detected. Return is", powerstatus continue break now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "Motion detected powerstatus", powerstatus if powerstatus == 0: #Check if lights are currently turned off now = datetime.now() dt_string = now.strftime("%m/%d/%Y %H:%M:%S") print dt_string, "After power check inside motion detected", powerstatus officelights.set_power(65535) #Turn lights on full time.sleep(600)
def _update_light(light: Light, midi_message: MidiMessage): # TODO: Probably need to fiddle with these and see what happens. They could become parameters. MIN_BRIGHTNESS = 500 # 0 - 65535 BRIGHTNESS_INCREASE_SPEED = 100 # 0-? BRIGHTNESS_DROP_SPEED = 200 # 0-? in ms, so 1000 is 1s velocity = midi_message.getVelocity() mapped_velocity = _map_value_to_range(value=velocity, from_min=MIDI_VALUE_MIN, from_max=MIDI_VALUE_MAX, to_min=LIFX_VALUE_MIN, to_max=LIFX_VALUE_MAX) ######## # TODO: We should try some different stuff here, but I'm making something up that I think will be interesting? ######## # Set the color to w/e the velocity is. This could be really erratic, so maybe add duration # which transitions to the given color over the # of ms. Just not sure if it blocks execution. light.set_hue(hue=mapped_velocity, rapid=True) # Push the brightness up by some function of the velocity. Will need to mess with this. def _new_brightness(current_brightness: int): return current_brightness + BRIGHTNESS_INCREASE_SPEED light.set_brightness(brightness=_new_brightness(current_brightness=light.get_color()[2]), rapid=True) # Then start to lower the brightness to some min level slowly light.set_brightness(brightness=MIN_BRIGHTNESS, duration=BRIGHTNESS_DROP_SPEED, rapid=True)
def toggle_light_color(light: lifxlan.Light, interval=0.5, num_cycles=3): original_color = light.get_color() rapid = True if interval < 1 else False for i in range(num_cycles): light.set_color(lifxlan.BLUE, rapid=rapid) sleep(interval) light.set_color(lifxlan.GREEN, rapid=rapid) sleep(interval) light.set_color(original_color)
async def get_light_color(name: str, light: lifx.Light): try: return ( name, light.get_color(), ) except lifx.WorkflowException as e: logging.exception("Failed to communicate with lights") return ( name, None, )
def assign_light_group(lifx, group, singles): lights = [] if singles is not None: for light in singles: if type(light) is list: lights.append(Light(light[0], light[1])) else: lights.append( lifx.get_devices_by_name(light).get_device_list()) if group is not None: lights = lights + lifx.get_devices_by_group(group).get_device_list() return Group(lights)
class Lifx(Block): version = VersionProperty('0.1.0') mac = StringProperty(title='MAC address', default='[[LIFX_MAC]]') ip = StringProperty(title='IP Address', default='[[LIFX_IP]]') power = IntProperty(title='1 for on 0 for off', default=0) hue = IntProperty(title='Hue (0-65535)', default=0) sat = IntProperty(title='Saturation (0-65535)', default=0) bri = IntProperty(title='Brightness (0-65535)', default=65535) kelvin = IntProperty(title='Kelvin (2500-9000)', default=3500) kill_switch = BoolProperty(title='Turn off Light at Service Stop?', default=True, advanced=True) def configure(self, context): super().configure(context) self.bulb = Light(self.mac(), self.ip()) def process_signals(self, signals): for signal in signals: if self.power(signal) == 0: brightness = 0 else: brightness = self.bri(signal) self.bulb.set_power(True) self.bulb.set_color([self.hue(signal), self.sat(signal), brightness, self.kelvin(signal)]) pass self.notify_signals(signals) def stop(self): if self.kill_switch(): self.bulb.set_power(False) super().stop()
async def set_light_color(name: str, light: lifx.Light, new_color: dict): try: orig_color = light.get_color() color = list(orig_color) for i, param in enumerate(["hue", "saturation", "brightness", "kelvin"]): if param in new_color: color[i] = new_color[param] if tuple(color) != orig_color: light.set_color(color, 500) return ( name, color, ) except lifx.WorkflowException as e: logging.exception("Failed to communicate with lights") return ( name, None, )
class LifxOutputDevice(OutputDevice): _light: Light _brightness: int def __init__(self, mac_address: str, ip_address: str): self._light = Light(mac_addr=mac_address, ip_addr=ip_address) def on(self, color: RGBColor): self._light.set_power("off") # type: ignore self._light.set_power("on") # type: ignore self._light.set_color( color=color.to_lifx_colors(HIGH_BRIGHTNESS)) # type: ignore self._light.set_waveform( # type: ignore is_transient=1, color=color.to_lifx_colors(LOW_BRIGHTNESS), period=2000, cycles=INFINITE_CYCLES, duty_cycle=0.5, waveform=1, rapid=True, ) def off(self): self._light.set_power("off") # type: ignore
def __init__(self, no_blink=False, use_light_list=True): light_macs = json.load(open('light_macs.json', 'r')).get('lights') lan = LifxLAN() if light_macs is None or not use_light_list: self.lights = lan.get_lights() else: self.lights = [Light(mac['mac'], mac['ip']) for mac in light_macs] #self.lights = filter(lambda x: x.mac_addr in [mac['mac'] for mac in light_macs], lan.get_lights()) self.prev_light_power_color = self.store_power_color() if not no_blink: print "Blink lights" for light in self.lights: power = light.get_power() light.set_power(0) light.set_power(power)
class LifxLightBulb(LightBulb): def __init__(self, ip_addr, mac_addr): _LOGGER.info('creating ip_addr=%s mac_addr=%s', ip_addr, mac_addr) self._device = Light(mac_addr, ip_addr) def get_power(self): _LOGGER.info('getting power') return self._device.get_power() == 65536 def turn_on(self): _LOGGER.info('turning on') self._device.set_power(True) def turn_off(self): _LOGGER.info('turning off') self._device.set_power(False) def set_color(self, color): _LOGGER.debug('setting color=%s', color) self._device.set_color(to_hsbk(color), rapid=True)
def lifx_lights(): single_zone_lights = [{ "mac_addr": "12:34:56:78:9a:bc", "ip_addr": "192.168.0.2" }, { "mac_addr": "12:45:56:99:9a:bc", "ip_addr": "192.168.0.3" }] multi_zone_lights = [{ "mac_addr": "23:45:67:89:ab:cd", "ip_addr": "192.168.0.4" }] light_objects = [] for light in single_zone_lights: light_objects.append(Light(light["mac_addr"], light["ip_addr"])) for light in multi_zone_lights: light_objects.append( MultiZoneLight(light["mac_addr"], light["ip_addr"])) return light_objects
class LightController: def __init__(self, mac = None, ip = None): self.bulb = None if mac != None and ip != None: self.bulb = Light(mac, ip) # put a try block in here later elif self.bulb == None: #put this in the catch block later lights = LifxLAN(1) self.bulb = lights.get_lights()[0] # just get whatever light you find else: lights = LifxLAN(1) self.bulb = lights.get_lights()[0] self.color = 0 #self.colors = [BLUE, CYAN, GREEN, ORANGE, PINK, PURPLE, RED, YELLOW, WHITE] self.colors = [BLUE, GREEN, RED, WHITE] def shiftColor(self): self.color = (1 + self.color) % len(self.colors) self.bulb.set_color(self.colors[self.color]) def togglePower(self): if self.bulb.get_power() == 65535: self.bulb.set_power(0) else: self.bulb.set_power(65535)
import json from lifxlan import Light, Group, WorkflowException from retrying import retry # Discover all lights on LAN and create a LifxLAN object # lifx = LifxLAN() ## Get all devices, a list of Device objects #devices = lifx.get_devices() # #for i in devices: # print(i) # Create all the objects p = json.loads(os.environ['PARENT']) parent_light = Light(p['mac'], p['ip']) c1 = json.loads(os.environ['CHILD1']) child1_light = Light(c1['mac'], c1['ip']) c2 = json.loads(os.environ['CHILD2']) child2_light = Light(c2['mac'], c2['ip']) # create the groups g = Group([child1_light, child2_light]) full_group = Group([parent_light, child1_light, child2_light]) def get_power_state(l): state = "off" # default try: if l.get_power() > 0:
import pyaudio import wave import numpy as np import serial from lifxlan import Light # import matplotlib.pyplot as plt bulb = Light("d0:73:d5:28:0b:4a", "10.0.0.16") FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 CHUNK = 1024 RECORD_SECONDS = 5 WAVE_OUTPUT_FILENAME = "file.wav" # s = serial.Serial(port='/dev/cu.usbmodem1411', baudrate=9600) audio = pyaudio.PyAudio() # start Recording stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print "recording..." frames = [] amplitudes = [] max = 10000 # for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
def apply(self, device_profile): duration = device_profile['duration'] #milliseconds dev = Light(device_profile['mac'], device_profile['ip']) dev.set_power(device_profile['power'], duration) #range [0,65535] dev.set_hue(device_profile['hue'], duration) #range [0-65535] dev.set_saturation(device_profile['saturation'], duration) #range [0-65535] dev.set_brightness(device_profile['brightness'], duration) #range [0-65535] dev.set_colortemp(device_profile['temperature'], duration) #range [2500-9000]
def configure(self, context): super().configure(context) self.bulb = Light(self.mac(), self.ip())
def __init__(self, ip, mac, multizone=False): self.rapid = False if multizone: self.bulb = MultiZoneLight(mac, ip) else: self.bulb = Light(mac, ip)
def set_lights(self, postvars={}): sched.pause() resp = 'no post data found' l = None if any(postvars): resp = 'vars!' mac = postvars.get('mac', None) if mac: ip = postvars.get('ip', None) if ip: l = Light(mac[0], ip[0]) light = postvars.get('light', None) if light: logging.debug(light) if light[0] in LIGHTS: logging.debug('found {}'.format(light[0])) light = LIGHTS.get(light[0]) mac = light.get('mac') ip = light.get('ip') colour = light.get('colour') l = Light(mac, ip) else: logging.debug(LIGHTS) l = self.devices.get_device_by_name(light[0]) if l: colour = l.get_color() if l: level = postvars.get('level', None) dim = postvars.get('dim', None) white = postvars.get('white', None) if level is not None: try: if (level[0] == 'full'): h, s, b, k = colour b = 65535 l.set_power('on') l.set_color([h, s, b, k], 300) else: l.set_power(level[0]) resp = 'set power {}'.format(level) except Exception as e: resp = 'err... {}'.format(repr(e)) elif dim is not None: switch_after_dim = False try: h, s, b, k = colour if l.get_power() == 0: switch_after_dim = True b = 0 dim = dim[0] if dim not in ('up', 'down'): dim = LIGHTS[l.get_label()].get('last_dim', None) if dim is None or b in (0, 65535): if b > 32000: dim = 'down' else: dim = 'up' if dim == 'down': b -= 6554 if dim == 'up': b += 6554 if b < 0: b = 0 if b > 65535: b = 65535 l.set_color([h, s, b, k], 600) if LIGHTS.get(l.get_label(), None) is None: LIGHTS[l.get_label()] = {'mac': l.get_mac_addr(), 'ip': l.get_ip_addr(), 'colour': l.get_color(), 'last_dim': dim} else: LIGHTS[l.get_label()]['colour'] = [h, s, b, k] LIGHTS[l.get_label()]['last_dim'] = dim if switch_after_dim is True: l.set_power('on') resp = 'set brightness {}'.format(b) except Exception as e: resp = 'dim... {}'.format(repr(e)) elif white is not None: try: h, s, b, k = colour white = white[0] if white not in ('warm', 'cool'): k = int(white) if white == 'warm': k -= 500 if white == 'cool': k += 500 if k < 2500: k = 2500 if k > 9000: k = 9000 l.set_color([h, s, b, k], 500) if LIGHTS.get(l.get_label(), None) is None: LIGHTS[l.get_label()] = {'mac': l.get_mac_addr(), 'ip': l.get_ip_addr(), 'colour': l.get_color()} else: LIGHTS[l.get_label()]['colour'] = [h, s, b, k] resp = 'set white level {}'.format(k) except Exception as e: resp = 'white... {}'.format(repr(e)) else: try: if l.get_power() > 0: l.set_power(0) else: l.set_power('on') except: resp = 'nope...' else: resp = "<p>Light not found ):</p>" sched.resume() return resp
from lifxlan import Light import sys #Living Room Lights L1 = Light("MAC", "IP") L2 = Light("MAC", "IP") L3 = Light("MAC", "IP") L4 = Light("MAC", "IP") L = (L1, L2, L3, L4) #Kitchen Lights K1 = Light("MAC", "IP") K2 = Light("MAC", "IP") K3 = Light("MAC", "IP") K4 = Light("MAC", "IP") K5 = Light("MAC", "IP") K6 = Light("MAC", "IP") K = (K1, K2, K3, K4) Kalt = (K1, K2, K3, K4, K5, K6) #Bedroom Lights B1 = Light("MAC", "IP") B2 = Light("MAC", "IP") B = (B1, B2) D = (K4, L1, L4) All = (L1, L2, L3, L4, K1, K2, K3, K4, K5, K6, B1, B2) def power_on(group):
class Bulb(object): def __init__(self, ip, mac, multizone=False): self.rapid = False if multizone: self.bulb = MultiZoneLight(mac, ip) else: self.bulb = Light(mac, ip) def supports_multizone(self): return self.bulb.supports_multizone() def get_color_zones(self): return self.bulb.get_color_zones() def set_zone_color(self, startZone, endZone, color, duration=5): return self.bulb.set_zone_color(startZone, endZone, color, duration=duration, rapid=self.rapid) def set_zone_colors(self, colors, duration=5): return self.bulb.set_zone_colors(colors, duration=duration, rapid=self.rapid) def set_power(self, power, duration=5): if duration: self.bulb.set_power(power, duration=duration, rapid=self.rapid) else: self.bulb.set_power(power) def get_power(self): return self.bulb.get_power() def set_color(self, color, duration=5): if duration: self.bulb.set_color(color, duration=duration, rapid=self.rapid) else: self.bulb.set_color(color) def get_color(self): return self.bulb.get_color() def get_label(self): return self.bulb.get_label() def get_brightness(self): return self.bulb.get_color()[2] def set_brightness(self, brightness, duration=5): return self.bulb.set_brightness(brightness, duration, rapid=self.rapid) def fast_mode(self, hostIP=None): self.rapid = True def slow_mode(self): self.rapid = False
def main(): bulb = Light("d0:73:d5:28:0b:4a", "10.0.0.16") print("Selected {}".format(bulb.get_label())) # get original state original_power = bulb.get_power() original_color = bulb.get_color() bulb.set_power("on") sleep(0.2) # to look pretty print("Toggling power...") toggle_device_power(bulb, 0.2) print("Toggling color...") toggle_light_color(bulb, 0.2) # restore original color # color can be restored after the power is turned off as well print("Restoring original color and power...") bulb.set_color(original_color) sleep(1) # to look pretty. # restore original power bulb.set_power(original_power)
import cv2 import math import numpy as np import imutils from collections import deque from imutils.video import VideoStream from lifxlan import Light def scaleValue(unscaled, to_min, to_max, from_min, from_max): return int((to_max - to_min) * (unscaled - from_min) / (from_max - from_min) + to_min) light = Light("d0:73:d5:13:f4:17", "10.52.242.195") brightness_Deque = deque(maxlen=10) hue_angleDeque = deque(maxlen=10) saturation_lineDeque = deque(maxlen=10) vs = VideoStream(src=1).start() state = 'OFF' brightness = 0 prev_brightness = 0 current_brightness = 0 # greenCenter = (0,0) yellowCenter = (-300, -300) while True: image = vs.read()