def get_all_lights(): log.info("discovering LIFX devices on network...") lifx = lifxlan.LifxLAN(None) devices = lifx.get_devices() log.info("finished LIFX device discovery") log.debug("LIFX devices found: {}".format(devices)) return devices
def __init__(self): self.lan = lifxlan.LifxLAN() self.lights = [] for light in self.lan.get_lights(): if light.get_group() == "Twitch": self.lights.append(light) return
def __init__(self, **kwargs): """ Check if LifxLAN api available, small ui initialization. """ super().__init__(**kwargs) if not API_AVAIL: dialog = Gtk.MessageDialog(transient_for=self, flags=0, message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK, text="LifxLAN api not found") dialog.format_secondary_text( "Please install using pip then relaunch Ambience.") dialog.run() dialog.destroy() exit(1) self.lan = lifxlan.LifxLAN() self.edit.set_sensitive(False) self.content_stack.set_visible_child_name("empty") self.update_sidebar()
def main(): global LAN args = options() LAN = lifxlan.LifxLAN() logging.basicConfig(level=logging.INFO) app.run(debug=False, host=args.host, port=args.port, processes=50)
def discover(self, command=None): self.lifxLan = lifxlan.LifxLAN() if self.discovery_thread is not None: if self.discovery_thread.isAlive(): LOGGER.info('Discovery is still in progress') return self.discovery_thread = Thread(target=self._discovery_process) self.discovery_thread.start()
def main(): lan = lifxlan.LifxLAN() lights = lan.get_color_lights() print('----------------------') print('Found {} color light(s).'.format(len(lights))) for i, light in enumerate(lights): print('----------------------') print('Device {}'.format(i + 1)) print('----------------------') print(light) print('----------------------')
def __init__(self, verbose=True): self.lifx = lifxlan.LifxLAN() self.verbose = verbose self.devices: List[lifxlan.MultiZoneLight] = [] self.device_color_zone_counts: Dict[lifxlan.MultiZoneLight, int] = {} self.device_color_mapping: Dict[str, list] = {} # Messing with gradients based on moving average of volume self.current_gradient_colors = [] self.current_gradient_value = 0 self.device_timers: Dict[lifxlan.MultiZoneLight, Timer] = {}
def get_lights(): lan = lifx.LifxLAN() lights: List[lifx.Device] = lan.get_lights() data = [{ "ip": l.ip_addr, "mac_address": l.mac_addr, "group": l.get_group(), "label": l.get_label(), "product": lifx.product_map[l.get_product()] or "Unknown", } for l in lights] return data
def get_key_light(): lan = lifxlan.LifxLAN(6) retry = 0 while retry < 3: try: light = lan.get_device_by_name('Back Strip') if light: retry = 3 else: retry += 1 except WorkflowException as E: light = None retry += 1 return light
def main(): lifx = lifxlan.LifxLAN(1) counter = 0 while True: try: counter += 1 devices = lifx.get_multizone_lights() if len(devices) > 0: break except lifxlan.WorkflowException: pass print(f'Found {len(devices)} device(s). Took {counter} requests to find') bulb: lifxlan.Light = devices[0] bulb: lifxlan.MultiZoneLight = lifxlan.MultiZoneLight( bulb.mac_addr, bulb.ip_addr, source_id=bulb.source_id) print(f'Found device: {bulb.get_label()}') print('Getting zones') counter = 0 while True: try: counter += 1 all_zones = bulb.get_color_zones() break except lifxlan.WorkflowException: pass print(f'Took {counter} tries to get zones') all_zones[-1] = all_zones[-2] rainbow_zones = [] colors = [ lifxlan.RED, lifxlan.ORANGE, lifxlan.YELLOW, lifxlan.GREEN, lifxlan.BLUE, lifxlan.PURPLE ] colors = [x for x in colors for _ in range(len(all_zones) // len(colors))] for i, (h, s, _, k) in enumerate(all_zones): h = colors[i % len(colors)][0] rainbow_zones.append((h, s, 50000, k)) print('Attempting to set colors') counter = 0 while True: try: counter += 1 bulb.set_zone_colors(rainbow_zones) break except lifxlan.WorkflowException: pass print(f'Took {counter} tries to set zone colors')
def main(): num_bulbs = parse_args() logger.info('Searching for bulbs on network') lifx = lifxlan.LifxLAN(num_bulbs) devices = lifx.get_lights() logger.info("Found %d Bulbs" % len(devices)) monitor = BulbMonitor(logger, 2 * MILLISECONDS_PER_SECOND) bulb_states = [] for i, bulb in enumerate(devices): bulb_states.append(BulbState(bulb.get_color(), logger)) while (1): run_bulb_controller(devices, bulb_states, monitor)
def rainbow_press(name): global gExpectedBulbs global bulbs global lan #print ("len(bulbs):",len(bulbs)) try: print("Discovering lights...") lan = lifxlan.LifxLAN( int(gExpectedBulbs) if int(gExpectedBulbs) != 0 else None) if lan is None: print("Error finding bulbs") return bulbs = lan.get_lights() if len(bulbs) < 1: print("No bulbs found. Exiting.") return #print("lan:",lan,"type(lan):",type(lan)) original_colors = lan.get_color_all_lights() original_powers = lan.get_power_all_lights() print("Turning on all lights...") lan.set_power_all_lights(True) sleep(1) print("Flashy fast rainbow") rainbow(lan, 0.4) #print("Smooth slow rainbow") #rainbow(lan, 1, smooth=True) print("Restoring original color to all lights...") for light in original_colors: light.set_color(original_colors[light]) sleep(1) print("Restoring original power to all lights...") for light in original_powers: light.set_power(original_powers[light]) except Exception as e: print("Ignoring error:", str(e))
def rainbow_press(name): print("Discovering lights...") lan = lifxlan.LifxLAN(EXPECTED_BULBS) original_colors = lan.get_color_all_lights() original_powers = lan.get_power_all_lights() print("Turning on all lights...") lan.set_power_all_lights(True) sleep(1) print("Flashy fast rainbow") rainbow(lan, 0.4) #print("Smooth slow rainbow") #rainbow(lan, 1, smooth=True) print("Restoring original color to all lights...") for light in original_colors: light.set_color(original_colors[light]) sleep(1) print("Restoring original power to all lights...") for light in original_powers: light.set_power(original_powers[light])
# === OPERATING SYSTEM FUNCTIONS === # # IMPORTS FROM SYSTEM import os import socket import keyboard import subprocess from data.sqlmem import query from ctypes import windll, Structure, c_long, byref # IMPORTS FROM SMART HOME import lifxlan from pyHS100 import smartplug # IMPORTS FOR DESKTOP-PLATFORM if not socket.gethostname() == "raspberrypi": import pyscreenshot as ScreenGrab # LIFX_LAN Object lifx_controller = lifxlan.LifxLAN() # LOCAL NETWORK FUNCTIONS --------------------------: def get_local_ip(return_self=True): # Method 1: Not always compatible try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) local_ip = s.getsockname()[0] s.close() # Method 2: Not always Accurate except Exception as e: print(e, '[IP EXCEPTION] Using socket.gethostbyname() instead') try: local_ip = socket.gethostbyname(socket.gethostname())
def finder(): global bulbList global lan global gExpectedBulbs global config global lifxList global lifxDict global config bulbList.clear() bulbList.append("-Select Bulb-") try: global bulbs #print("finder().gExpectedBulbs:",gExpectedBulbs) lan = lifxlan.LifxLAN( int(gExpectedBulbs) if int(gExpectedBulbs) != 0 else None) bulbs = lan.get_lights() #print(type(bulbs)) #print(bulbs[0].label) if len(bulbs) < 1: app.errorBox( "Error", "No bulbs found. Please try again. If you switched WiFi networks, please re-start the app and try again." ) app.setLabelBg("lbl2", "red") app.setLabel("lbl2", "Found 0 bulbs") return else: app.setLabelBg("lbl2", mygreen) app.hideLabel("f1") app.setLabel("lbl2", "Found " + str(len(bulbs)) + " bulbs") app.setCheckBox("Select All") #app.setSpinBox("Expected Bulbs", str(len(bulbs))) del lifxList[:] for bulb in bulbs: #print(".get_label()",bulb.get_label()) # this gets the actual label #print(".label:",bulb.label) # this returns None label = bulb.get_label() ip = bulb.ip_addr mac = bulb.mac_addr #print (label,ip,mac) lifxDict['label'] = label lifxDict['mac'] = mac lifxDict['ip'] = ip lifxList.append(lifxDict.copy()) bulbList.append(label) app.changeOptionBox("LIFX Bulbs", bulbList, callFunction=False) app.showButton("Pick Color") #print(lifxList) #config['bulbs'] = lifxList pkl.dump(lifxList, open(PICKLE, "wb")) #this pickles #exit(0) #config.write() except Exception as e: print("Ignoring error:", str(e)) app.setLabelBg("lbl2", "gray") app.setLabel("lbl2", "Found 0 bulbs") app.errorBox( "Error", str(e) + "\n\nPlease try again. If you keep getting this error, check/toggle your WiFi, ensure that 'Expected Bulbs' is either 0 or the number of bulbs you have and finally, try restarting the app" ) # config['bulbs'] = bulbs # config.write() print("finder() Ended")
if 'Scene 3' in config: app.setEntry("Scene 3", config["Scene 3"], callFunction=False) #print("config['bulbs']:",config['bulbs']) #print("type(config['bulbs']):",type(config['bulbs'])) if os.path.exists(PICKLE): bulbPickle = pkl.load(open(PICKLE, "rb")) #this reads the pickle #print (bulbPickle) bulbList.clear() bulbList.append("-Select Bulb-") for i, bulb in enumerate(bulbPickle): #print ("mac:",bulb['mac']); light = lifxlan.Light(bulb['mac'], bulb['ip']) light.label = bulb['label'] bulbs.append(light) bulbList.append(bulb['label']) if len(bulbs) > 0: app.clearOptionBox("LIFX Bulbs", callFunction=False) app.changeOptionBox("LIFX Bulbs", bulbList, callFunction=False) app.setLabelBg("lbl2", mygreen) app.hideLabel("f1") app.setLabel("lbl2", "Recalled " + str(len(bulbs)) + " bulbs") app.setCheckBox("Select All") #light = Light("12:34:56:78:9a:bc", "192.168.1.42") #print("bulbs:",bulbs) lan = lifxlan.LifxLAN() app.go()
def __init__(self, settings): num_expected = settings.get_value('default_num_lights', None) self._lifxlan = lifxlan.LifxLAN(num_expected)
def __init__(self, *args, **kwargs): self.lifx_connector = lifxlan.LifxLAN(None) super(LIFXControl, self).__init__(*args, **kwargs)
for y in range(len(self.canvas)): self.canvas[y][index] = color else: raise Exception( "dimension must be either the string 'x' or 'y', not {}". format(str(dimension))) def ssave(self): self.power = self.TileChain.get_power() self.tilechain_colors = self.TileChain.get_tilechain_colors() def sload(self): self.TileChain.set_power(self.power) self.TileChain.set_tilechain_colors(self.tilechain_colors) # ---- script ---- if __name__ == "__main__": lifx = lifxlan.LifxLAN() tilechains = lifx.get_tilechain_lights() tilechain = tilechains[0] my_mtc = ManagedTilechain(tilechain) HSVK_list = my_mtc.read_HSVK_2D() print(HSVK_list) tilechain.set_tilechain_colors(HSVK_list, 0, rapid=True)
def __init__(self): super(LifxSkill, self).__init__(name="LifxSkill") self.lifxlan = lifxlan.LifxLAN() self.targets = {}
def __init__(self, name, groups): Thread.__init__(self) self.name = name self.lifx = lifxlan.LifxLAN() self.groups = groups
def main(test_file, no_affine, no_crop, debug, log_time, config): with open(config) as fp: factors = json.load(fp) context = { **factors, **{ 'debug': debug, 'no_affine': no_affine, 'no_crop': no_crop, 'log_time': log_time, } } stop = {'stop': False} def handler(signum, frame): stop['stop'] = True signal.signal(signal.SIGINT, handler) print('Starting capture') if test_file: class IM: def read(self): return True, cv2.imread(test_file) def release(self): pass cam = IM() context['width'] = 1920 context['height'] = 1080 context['width_float'] = 1920.0 context['height_float'] = 1080.0 else: cam = cv2.VideoCapture(0) # 0 -> index of camera cam.set(3, context['camera']['w']) cam.set(4, context['camera']['h']) cam.set(cv2.CAP_PROP_AUTOFOCUS, 0) context['width'] = int(cam.get(3)) context['height'] = int(cam.get(4)) context['width_float'] = cam.get(3) context['height_float'] = cam.get(4) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') if context['debug']: print(context['width']) print(context['height']) print(fourcc) context['out_o'] = cv2.VideoWriter( '/tmp1/cam-test-orig.avi', fourcc, 30, (context['width'], context['height'])) context['out_a'] = cv2.VideoWriter( '/tmp1/cam-test-affine.avi', fourcc, 30, (context['width'], context['height'])) context['out_m'] = cv2.VideoWriter( '/tmp1/cam-test-masked.avi', fourcc, 30, (context['width'], context['height'])) context['out_b'] = cv2.VideoWriter( '/tmp1/cam-test-bars.avi', fourcc, 30, (context['width'], context['height'])) context['out_g'] = cv2.VideoWriter( '/tmp1/cam-test-grey.avi', fourcc, 30, (context['width'], context['height'])) context['out_t'] = cv2.VideoWriter( '/tmp1/cam-test-thresh.avi', fourcc, 30, (context['width'], context['height'])) context['out_c'] = cv2.VideoWriter( '/tmp1/cam-test-countour.avi', fourcc, 30, (context['width'], context['height'])) context['out_co'] = cv2.VideoWriter( '/tmp1/cam-test-countour-overlay.avi', fourcc, 30, (context['width'], context['height'])) context['out'] = cv2.VideoWriter('/tmp1/cam-test.avi', fourcc, 30, (context['width'], context['height'])) lan = lifxlan.LifxLAN(26) bias = lan.get_device_by_name('TV Bias') bias.set_power(True) if context['debug']: print(bias) while True: try: start_time = time.time() read, img = cam.read() if not read: break if context['debug']: cv2.imwrite("/tmp1/cam-test.png", img) debug_frame(img, 'out_o', context) demo = timed('ghetto_affine', ghetto_affine, img, context) removed = timed('ghetto_crop', ghetto_crop, demo, context) removed = timed('ghetto_masks', ghetto_masks, removed, context) # shrink = cv2.resize(removed, (context['num_zones'], 1), interpolation=cv2.INTER_NEAREST) # shrink = cv2.resize(removed.row(0), (context['num_zones'], 1), interpolation=cv2.INTER_NEAREST) shrink = removed[5, 10::(context['width'] // context['num_zones'] + 1)] if context['debug']: print(shrink) print(shrink.shape) hsv = [ colorsys.rgb_to_hsv(r / 255, g / 255, b / 255) for [b, g, r] in shrink.tolist() ] lifx_hsv = [[h * 257 * 255, s * 257 * 255, v * 257 * 255, 3500] for [h, s, v] in hsv] if context['debug']: print(lifx_hsv) try: timed('set_zone_colors', bias.set_zone_colors, lifx_hsv, rapid=True) except Exception as e: print(e) if context['debug']: final = cv2.resize(np.expand_dims(shrink, axis=0), (context['width'], context['height']), interpolation=cv2.INTER_NEAREST) debug_frame(final, 'out', context) if context['log_time']: print(time.time() - start_time) except Exception as e: print(e) if stop['stop']: break time.sleep(.1) cam.release() if context['debug']: context['out'].release() context['out_o'].release() context['out_a'].release() context['out_m'].release() context['out_b'].release() context['out_g'].release() context['out_t'].release() context['out_c'].release() context['out_co'].release()
def init(config_values): global lifx, last_brightness, last_temperature last_brightness = 65535 last_temperature = 4000 lifx = lifxlan.LifxLAN()
def __init__(self, instance_label, init_mode, init_mode_args={}, group=None, shared_modules=[], pollrate=None, *args, **kwargs): super().__init__( module_name="Volux Light ({})".format(instance_label), module_attr="light_{}".format(instance_label), module_get=self.get, get_type=float, get_min=0, get_max=100, module_set=self.set, set_type=float, set_min=0, set_max=100, shared_modules=shared_modules, pollrate=pollrate, ) init_mode_options = [ "all_devices", "device", "group", ] # note: all types of labels are case-sensitive self.instance_label = instance_label self.init_mode = init_mode self.init_mode_args = init_mode_args # self.group = group # note: group labels are caps sensitive self.lifx = lifxlan.LifxLAN(None) self.devices = [] if self.init_mode not in init_mode_options: raise ValueError("invalid init_mode. options include: {}".format( init_mode_options)) else: if self.init_mode == "all_devices": self.devices = self.lifx.get_devices() elif self.init_mode == "device": if type(self.init_mode_args) == dict: if ("ip" in self.init_mode_args and "mac" in self.init_mode_args): raise NotImplementedError( ) # note: implement ip + mac option elif "label" in self.init_mode_args: self.devices.append( self.lifx.get_device_by_name( self.init_mode_args["label"])) else: raise KeyError("'label' not specified in mode_args") else: raise TypeError("init_mode_args must be of type 'dict'") elif self.init_mode == "group": if "group_label" in self.init_mode_args: devices = self.lifx.get_devices_by_group( self.init_mode_args["group_label"]).devices if len(devices) > 0: self.devices = devices else: raise Exception( "no devices found for group_label {}! Please note group_label is caps-sensitive!" .format(self.init_mode_args["group_label"])) else: raise KeyError("'group_label' not specified in mode_args") # if not self.group is None: # for device in self.devices: # if not device.get_group_label() == self.group: # device.set_power(False) # self.devices.remove(device) # print("removed '{}' from selected devices because it's not in group '{}'".format(device.get_label(),self.group)) if len(self.devices) > 0: for device in self.devices: if device is not None: device.set_power(True) else: raise Exception( "No lights with specified conditions found!") else: raise Exception("No lights with specified conditions found!") log.debug("devices: {}".format(self.devices)) self.mdevices = [ManagedDevice(device) for device in self.devices]