def main(): config = load_config_file() pir_sensor_port = config['pir_sensor_port'] pir = MotionSensor(pir_sensor_port) fade_in_duration = config.get('fade_in_duration', 1000) fade_out_duration = config.get('fade_out_duration', 1000) wake_time = config.get('wake_time', 15 * 1000) lan = LifxLAN() group_name = config.get('group', None) if group_name is not None: group = lan.get_devices_by_group(config['group']) if group is not None: watch_group(group, pir, fade_in_duration, fade_out_duration, wake_time) light_name = config.get('light', None) if light_name is not None: light = lan.get_device_by_name(light_name) if light is not None: watch_device(light, fade_in_duration, fade_out_duration, wake_time) else: print('')
def main(): num_lights = None if len(sys.argv) != 2: print( "\nDiscovery will go much faster if you provide the number of lights on your LAN:" ) print(" python {} <number of lights on LAN>\n".format(sys.argv[0])) else: num_lights = int(sys.argv[1]) # instantiate LifxLAN client, num_lights may be None (unknown). # In fact, you don't need to provide LifxLAN with the number of bulbs at all. # lifx = LifxLAN() works just as well. Knowing the number of bulbs in advance # simply makes initial bulb discovery faster. print("Discovering lights...") lifx = LifxLAN(num_lights) # get devices devices = lifx.get_devices() lights = lifx.get_lights() print("Found {} devices(s).".format(len(devices))) print("Found {} light(s):\n".format(len(lights))) cpulight = lifx.get_device_by_name("CPU") print(cpulight) workbenchlight = lifx.get_device_by_name("Workbench") print(workbenchlight) cpulight.set_color(RED, rapid=True) workbenchlight.set_color(RED, rapid=True) sleep(5) cpulight.set_waveform(is_transient=0, color=BLUE, period=55000, cycles=10000, duty_cycle=0.5, waveform=1, rapid=False) workbenchlight.set_waveform(is_transient=0, color=BLUE, period=60000, cycles=10000, duty_cycle=0.5, waveform=1, rapid=False)
def get_lights(light_names=None, group=None): num_lights = 6 # Faster discovery, when specified lan = LifxLAN(num_lights) # Select by Name(s) if group is None: lights = [] # Convert to List if type(light_names) is not list: light_names = [light_names] for light in light_names: for _ in range(5): try: light = lan.get_device_by_name(light) lights.append(light) except: print('trying again') continue else: break else: print('cannot get light: %s' % light) return lights # Select by Group else: for _ in range(5): try: lights = lan.get_devices_by_group(group).devices except: print('trying again') continue else: return lights else: print('cannot get lights')
def main(): # Definitions for the Floral Bonnet extension GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Object representation of the LAN network lan = LifxLAN() light = lan.get_device_by_name("Room") while True: input_state = GPIO.input(4) if input_state == False: try: state = light.get_power() if state == 65535: lan.set_power_all_lights(0) else: lan.set_power_all_lights(65535) except: continue
#!/usr/bin/env python # coding=utf-8 import sys # Step 1 import pickle from lifxlan import LifxLAN from pprint import pformat as pf import os print(os.getcwd()) lifx = LifxLAN(1, verbose=False) device = lifx.get_device_by_name(sys.argv[1]) print("Hardware: %s " % pf(device.get_color())) with open(sys.argv[1]+'.light', 'wb') as fileChambre: # Step 3 pickle.dump(device, fileChambre)
# init mqtt client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("128.32.171.51") client.loop_start() # populate lights lan = LifxLAN() lights = [] #lan.get_devices_by_name(selected_labels) init_color = [0, 0, 65535, 4000] for label in selected_labels: try: lights.append(lan.get_device_by_name(label)) if lights[-1] == None: raise ValueError('Failed to get device') except: print('Failed to contact ' + label) exit() print("starting baseline measurements!") # turn all lights off and get baseline light level for each for light in lights: light.set_color(init_color) #light.set_power(1) #time.sleep(1) light.set_power(0) # 10 seconds should be enough time to get messages from all motes time.sleep(10) state = 'characterizing'
import colorsys import time from datetime import datetime from lifxlan import LifxLAN, RGBtoHSBK from PIL import Image, ImageGrab from plyer import notification lifx = LifxLAN() light = lifx.get_device_by_name("Desk") #get the Light object print(f"Selected {light.get_label()}") sample_size = 1, 1 #location of our single pixel we want to grab the color from def ambient_light( light ): #function that changes the color to whatever average color my display. while True: try: screenshot = ImageGrab.grab(include_layered_windows=True) scaled = screenshot.resize(sample_size) color = scaled.getpixel((0, 0)) color = RGBtoHSBK(color, temperature=5000) color = color light.set_color(color, duration=1000) time.sleep(0.75) except Exception as e: #On error, send a notification to the OS. notification.notify( title='An error occured!', message=f'{e}', app_name='Ambient Light',
print("Starting Impression App") lifx = LifxLAN(20) while True: # get devices try: # if reconnect_to_bulbs(): devices = lifx.get_devices_by_group("Forest") # # previous_state = "default" if devices: print "Operating with {} LIFX Bulbs".format( len(devices.devices)) # These pseudo groups are used because we are unable to create new groups at the theater space single_group = [lifx.get_device_by_name(single_group_name)] for light_name in middle_light_names: middle_group.append(lifx.get_device_by_name(light_name)) active_bulbs = devices.devices setWaveformsOnGroup(active_bulbs, "starkwhite", "all") app.run(use_reloader=False) time.sleep(5) else: if retry_count > retry_attempts: print "PROBLEM FINDING LIGHTS PLEASE CHECK YOUR NETWORK, YOU MAY BE USING 5G OR GUEST NETWORK WHICH CAUSES PROBLEMS" exit() else:
class S(BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): self.devices = LifxLAN(NUM_LIGHTS) sched.add_job(self.get_lights, 'interval', minutes=2, id='get_lights', replace_existing=True) BaseHTTPRequestHandler.__init__(self, *args, **kwargs) def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def get_lights(self): lights = self.devices.get_lights() resp = "<table><tbody>" for l in lights: LIGHTS[l.get_label()] = {'mac': l.get_mac_addr(), 'ip': l.get_ip_addr(), 'colour': l.get_color()} resp += "<tr><td>" + l.get_label() + "</td>" resp += "<td>{}</td>".format(l.get_color()) resp += "<td>" + l.get_mac_addr() + "</td>" resp += "<td>" + l.get_ip_addr() + "</td></tr>" resp += '</tbody></table>' resp += "<p>POST to /lights with either mac&ip or light (with label)<br/>" resp += "no args: toggle on/off<br/>" resp += "<pre>level</pre> 'on'/'off', or 0/65535<br/>" resp += "<pre>dim</pre> 'up'/'down' or no arg to continue last dim (1/10th each time)<br/>" resp += "<pre>white</pre> 'warm'/'cool' to change kelvin level</p>" logging.debug(len(LIGHTS)) return resp 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 def do_GET(self): self._set_headers() self.wfile.write("<html><body><h1>Hi!</h1><p>Path: {path}</p>".format(path=self.path)) if self.path == '/lights': self.wfile.write(self.get_lights()) self.wfile.write("</body></html>") def do_HEAD(self): self._set_headers() def do_POST(self): ctype, pdict = cgi.parse_header(self.headers['content-type']) if ctype == 'multipart/form-data': postvars = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': length = int(self.headers['content-length']) postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) else: postvars = {} if len(postvars): i = 0 for key in sorted(postvars): logging.debug('ARG[%d] %s=%s' % (i, key, postvars[key])) i += 1 self._set_headers() self.wfile.write("<html><body><p>POST</p>") logging.debug(self.headers) if self.path.startswith('/lights'): self.wfile.write(self.set_lights(postvars)) self.wfile.write("</body></html>")
import time, threading light_pid = PID(300, 0, 50) light_pid.SetPoint = 100 hyster = 30 brightness = 0 last_seq = 0 max_achievable_lux = 150 step_size_percent = 5 duration = 5000 light_data = {} lan = LifxLAN() light = lan.get_device_by_name("Neal's light") while light is None or light.get_service() != 1: light = lan.get_device_by_name("Neal's light") light.set_power(1) brightness = light.get_color()[2] #light.set_brightness(brightness, 100) light_data['device'] = 'LIFXA19' light_data['brightness'] = '%.02f' % (brightness / 65535 * 100) light_data['id'] = light.mac_addr.replace(':', '') light_data['_meta'] = {} light_data['_meta']['device_id'] = light.mac_addr.replace(':', '') def get_brightness(): current_brightness = brightness try:
formatter = logging.Formatter(file_logging_format) handler.setFormatter(formatter) logger.addHandler(handler) logger.info("This is saved to the log") # Rclone to publish lifx.py to google drive subprocess.run('rclone sync "lifx.py" "drive:Filer/RaspberryPi" -P', shell=True) # Lifx lan environment and number of devices lan = LifxLAN(1) # Label of light to be controlled label = "Taklampa" # Get light(s) (add more by adding a list []) bulb = lan.get_device_by_name(label) logging.info("Light found: " + bulb.get_label()) # Lifx HTTP api token, deprecated TOKEN = "c6df528836417f584c1eeff650329a767ed7bd6bcd4a7adc02766bf74fcbc2eb" # Time until light turns off after no motion, defined in minutes timer = 15 # GPIO pins onboard = LED(47, active_high=False, initial_value=True) # Onboard LED pir = MotionSensor(17) # Motion sensor, physical pin: 11 b1 = Button(27) # Button 1, physical pin: 13 b2 = Button(22) # Button 2, physical pin: 15 b3 = Button(23) # Button 3, physical pin: 16 b4 = Button(24) # Button 4, physical pin: 18 # Lifx states in brightness
import time from lifxlan import LifxLAN from lifxlan import GREEN, YELLOW, RED, BLUE from color import interpolate, adjust_brightness # connect to lifx MAX_CONNECTION_RETRIES = 5 lifx = LifxLAN(1) print("Connecting...") light = None for i in range(MAX_CONNECTION_RETRIES): try: light = lifx.get_device_by_name("mini_1") #light = lifx.get_multizone_lights()[0] break except: print("Retrying...") time.sleep(1) if light is None: raise Exception("Failed to connect to LIFX device! Please try again.") print("Connected!") # set light to blue color = RED #light.set_color() light.set_color(adjust_brightness(color, 1), rapid=True)
elif "Roku" in question and "IPTV" in question: try: print("Doing roku function.") tts.get_pronunciation("OK. Launching Free View Player.") app = roku['FreeView Player'] app.launch() except: print("ERROR. I don't think you are connected...") tts.get_pronunciation("Whoops! Are you sure you are connected?") elif "lifx" in question and "connect" in question: try: lanLights = LifxLAN() print("LIFX CONNECT READY.") tts.get_pronunciation("Please say the name of the device.") recogntionAudio = r.listen(source) lifxLight = lanLights.get_device_by_name(recogntionAudio) except: print("ERROR. Are you sure that device exists?") elif "lifx" in question and "on" in question: try: print("LIFX on.") lifxLight.set_power(true) except: print("ERROR. Are you sure you are connected?") elif "lifx" in question and "off" in question: try: print("LIFX off.") lifxLight.set_power(off) except: print("ERROR. Are you sure you are connected?") else: