def main(): # Look for the bulb and keep trying if it's not found. # Assume five minutes between the job being kicked off again. start = datetime.now() bulbs = discover_bulbs() while not len(bulbs): time.sleep(2) if (datetime.now() - start).total_seconds() > stop_running_after: return bulbs = discover_bulbs() logger.info(bulbs) bulb_ip = bulbs[0]['ip'] bulb = Bulb(bulb_ip) try: aqi_obj = requests.get( 'http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=94702&distance=1&API_KEY=E1C86A95-8F32-4EA5-8243-E19677A0550F' ).json() logger.info(aqi_obj) pm25 = None for item in aqi_obj: if item.get('ParameterName') == 'PM2.5': pm25 = item break if pm25 is None: pm25 = aqi_obj[1] category = pm25['Category']['Number'] except: category = 0 (r, g, b), brightness = category_colors[category] bulb.set_rgb(r, g, b) bulb.set_brightness(brightness)
def getBulb(): global bulb_connected if (len(yee.discover_bulbs())): for bulb_meta in yee.discover_bulbs(): if bulb_meta['capabilities']['id'] == bulb_id: bulb_connected = True bulb = yee.Bulb(bulb_meta['ip']) bulb.set_brightness(BRIGHTNESS) return bulb else: bulb_connected = False print("unable to connect to bulb... Retrying!..") time.sleep(10) return getBulb()
def rebuild_bulbs(self): found_bulb_ips = sorted(bulb['ip'] for bulb in yeelight.discover_bulbs(3) if bulb['ip'] in room_to_ips[self.name]) current_bulb_ips = sorted(bulb._ip for bulb in self.bulbs) if current_bulb_ips != found_bulb_ips: logger.info('Different bulbs!') logger.info('Found bulbs: %s', ', '.join(found_bulb_ips)) # Clear out the bulbs, since they don't like having multiple # connections to the same machine. del self.bulbs[:] if YEELIGHT_STATIC_REBUILD: logger.info('Statically rebuilding bulb list') self.bulbs = [ yeelight.Bulb(ip) for ip in room_to_ips[self.name] ] else: self.bulbs = [ yeelight.Bulb(found_ip) for found_ip in found_bulb_ips ] try: self.resetFromLoggedState() except Exception: logger.exception( 'Got exception when restting bulbs in rebuild_bulbs')
def __init__(self, group_name, names, loadfile=None): self.group_name = group_name self.names = names # store in case you want to reconnect or something idk self.loadfile = loadfile self.bulbs = [] bulb_dicts = yl.discover_bulbs() for bulb_dict in bulb_dicts: if bulb_dict['capabilities']['name'] in names: self.bulbs.append(Bulb(yl.Bulb(bulb_dict['ip']))) self.prev_t = time.time() if loadfile: self.load_state() else: self.loadfile = group_name + '_latest.txt' self.turn_on() self.on = True self.h = 0 self.s = 0 self.brightness = 100 self.degrees = 3800 self.r = 255 self.g = 255 self.b = 255 self.set_mode(yl.PowerMode.NORMAL)
def callback(ch, method, properties, body): print(" [x] Received %r." % body) bulbs = discover_bulbs() body_s = body.decode("utf-8") print(body) print(body_s) for bulb_raw in bulbs: bulb = Bulb(bulb_raw["ip"]) bulb.turn_on() bulb.set_brightness(100) if body_s == "error": bulb.set_rgb(255, 0, 0) # red elif body_s == "success": bulb.set_rgb(0, 255, 0) # green elif body_s == "statping_error": bulb.set_rgb(255, 51, 51) # red time.sleep(1) bulb.set_rgb(255, 128, 0) # orange time.sleep(1) bulb.set_rgb(255, 51, 51) # red # else: # bulb.set_rgb(0, 0, 255) #blue time.sleep(3) for bulb_raw in bulbs: bulb = Bulb(bulb_raw["ip"]) bulb.set_rgb(255, 255, 255) # white
def textConnect(arguments): """ INFO Setup a connection to a new yeelight USAGE {0} """ print("Discovering Lights") lightData = yeelight.discover_bulbs() if len(lightData) > 0: for i in range(len(lightData)): print(str(i + 1) + ". ", end="") if lightData[i]["capabilities"]["name"] == "": print("Unnamed Light") else: print(lightData[i]["capabilities"]["name"]) try: n = int(input("enter a light number to connect to. ")) - 1 name = input("what would you like to call it. (recommended: lights) ").lower() if n < len(lightData): YeelightSmartLight(lightData[i]["ip"], name=name) except ValueError as e: print("invalid input") else: print("No lights detected! Make sure they are on and connected to the same network.")
def __init__(self, parent=None): super(TabletSampleWindow, self).__init__(parent) self.MAX_CLICK = 10. self.MOVE_CHUNK = 40 self.BRIGHT_INC = 5 self.CT_INC = 250 self.MAX_PRESSURE = 50 self.text = "" self.pen_pressure = 0 self.max_pressure = 0 self.mode = None self.moved = False # Resizing the sample window to full desktop size: frame_rect = app.desktop().frameGeometry() width, height = frame_rect.width(), frame_rect.height() self.resize(width, height) self.move(-9, 0) self.setWindowTitle("Yeelight Control Center") self.width = width self.height = height # discover all light bulbs and setup first one bulbs = yeelight.discover_bulbs() if len(bulbs) == 0: print("No Yeelight Bulbs discovered! exiting...") sys.exit(0) self.bulb = yeelight.Bulb(ip=bulbs[0]['ip']) print(f"Connected to bulb on ip {bulbs[0]['ip']}") self.specs = self.bulb.get_model_specs() self.min_ct = self.specs['color_temp']['min'] self.max_ct = self.specs['color_temp']['max'] self.sync_bulb() schedule.every(5).minutes.do(self.sync_bulb)
def discovery_bulbs_sync(on_complete): discovered_bulbs = discover_bulbs() wrappers = [] for bulb_info in discovered_bulbs: wrappers.append(BulbWrapper(bulb_info)) idle_add(on_complete, wrappers)
def searchForBulbs(): global listOfBulbs listOfBulbs = [] results = discover_bulbs() for bulb in results: listOfBulbs.append(Bulb(bulb.get("ip"))) return listOfBulbs
def detect_lights(self): discovered_lights = discover_bulbs() for light in discovered_lights: # Check light compatibility if 'capabilities' in light and 'model' in light['capabilities'] \ and light['capabilities']['model'] not in ['mono', 'color', 'stripe', 'bslamp', 'ceiling']: continue # Check reply consistency if 'ip' not in light: continue # Set device name device_name = light['capabilities']['name'] # Check if device has a name if device_name == "": device_name = set_light_name(light['ip'], light['capabilities']['model'], light['capabilities']['id']) if device_name == "": continue # Add usable light to list self.lights[device_name] = Bulb(light['ip']) # Turn off light try: self.lights[device_name].turn_off() except: print("Communication failed with Yeelight {}, light disabled". format(device_name)) del self.lights[device_name] continue
def get_bulb(self): from yeelight import Bulb, discover_bulbs ip = self.component.ip if not ip: devices = discover_bulbs() list_devices(devices) ip = devices[0]['ip'] return Bulb(ip)
def _find_lamp_ip(self): bulbs = yeelight.discover_bulbs() if "lamp_ip" not in self.setting.keys() and len(bulbs) > 0: for b in bulbs: if "capabilities" in b.keys() and b["capabilities"][ "name"].lower() == self.setting["lamp_name"]: self.setting["lamp_ip"] = b["ip"] else: pass
async def discoverLocalBulbs() -> BulbModel: result = discover_bulbs() ip = result[0]["ip"] port = result[0]["port"] status = result[0]["capabilities"]["power"] bulbData: BulbModel = BulbModel(ip, port, status) return bulbData
def identify_bulbs(): bulbs = discover_bulbs() for b in bulbs: bulb = Bulb(b['ip']) bulb.start_flow(flow) light_name = av.ask_for( "Quel est le nom de l'ampoule qui vient de varier de couleur ?") fg.write_json(table, "name", light_name) fg.write_json_details(table, light_name, "ip", bulb['ip'])
def _initialize_lights(): logging.info('Initializing lights') lights = [] for instance in discover_bulbs(): lights.append(Bulb(instance['ip'])) logging.info('Found {} lights'.format(len(lights))) return lights
def toggle(systray): var = y.discover_bulbs() if len(var) < 1: var = "192.168.1.3" else: var = var[0]["ip"] bulb = y.Bulb(var) bulb.toggle()
def discover(self): filtered_list = [] for bulb in discover_bulbs(4): filtered_list.append({ 'ip': bulb['ip'], 'name': bulb['capabilities']['name'], 'id': bulb['capabilities']['id'] }) print('Bulbs found: ', filtered_list) return filtered_list
def refresh(): global bulb_list, bulb_list_addr bulb_list.clear() bulb_list_addr.clear() for bulb in discover_bulbs(): addr = bulb['ip'] bulb_list.append(Bulb(addr)) bulb_list_addr.append(addr)
def discoverIp(): infos = discover_bulbs() devs = [] if infos: for d in infos: dev = {d['capabilities']['id']: d['ip']} devs.append(dev) return devs else: return None
def discover_lights(): global lights_available while len(lights_available) == 0: lights_available = dict() for light in yeelight.discover_bulbs(): prefix = light["capabilities"]["name"] + '-' name = (prefix if prefix != '-' else '') + light["ip"] lights_available[name] = yeelight.Bulb( light["ip"], effect=config.lightingMode.lightTransitions) return lights_available
def find_devices(): #ipip g = discover_bulbs() #pdb.set_trace() ele = len(g) print 'size of g is: ',ele for i in range (ele): a = g[i-1] a_ip = a['ip'] a_name = a['capabilities']['name'] print a_name,a_ip check_ip(a_ip,a_name)
def assert_connect_bulbs(): infos = yeelight.discover_bulbs() bulbs = [] for info in infos: bulbs.append(yeelight.Bulb(info['ip'])) if(len(bulbs) == 0): raise yeelight.BulbException(ERROR_STR) return bulbs
def get_bulbs(timeout=0.2): 'Get a list of bulbs that are reachable' # TODO return BULBS bulbs = [ yeelight.Bulb(blb['ip']) for blb in yeelight.discover_bulbs(timeout) if blb['ip'] in BULB_IPS ] if len(bulbs) != len(BULB_IPS): logger.info('Found %d bulbs, expected %d', len(bulbs), len(BULB_IPS)) return bulbs
def control_yeelight(status): # 当前局域网存在灯设备 if len(discover_bulbs()): # 连接到yeelight bulb = Bulb(bulb_ip) dic = bulb.get_properties() # {'sat': '100', 'color_mode': '2', 'ct': '6500', 'delayoff': '0', 'power': 'on', 'rgb': '16711680', 'hue': '359', 'music_on': '0', 'bright': '82', 'name': None, 'flowing': '0'} if dic.has_key('power'): power = dic.get('power') if bulb and status == True and power == 'off': bulb.turn_on() else: print("未找到灯")
def refresh(timeout=8): global lastRefreshed, lookup from yeelight import discover_bulbs lastRefreshed = time.time() d = discover_bulbs() l = {} for i in d: if 'name' in i['capabilities']: l[i['capabilities']['name']] = i l[i['ip']] = i lookup = l
def get_bulb(): def get_parameters(bulb_dict): capabilities = bulb_dict.get('capabilities') return \ bulb_dict.get('ip'), \ bulb_dict.get('port'), \ capabilities.get('model'), \ capabilities.get('name'), \ capabilities.get('power') bulbs_discovered = yeelight.discover_bulbs() log_message = 'ip = {0}, port = {1}, model = {2}, name = {3}, power = {4}' if len(bulbs_discovered) == 1: ip, port, model, name, power = get_parameters(bulbs_discovered.pop()) logging.info('One bulb found, proceeding: ' + log_message.format(ip, port, model, name, power)) return yeelight.Bulb(ip) elif len(bulbs_discovered) == 0: raise Exception( 'No bulbs found nearby. ' 'Make sure you\'re running the script using the same local network your bulb connected to.' ) else: # more than one bulb found bulbs_found_msg = '' for index, bulb in enumerate(bulbs_discovered): ip, port, model, name, power = get_parameters(bulb) bulbs_found_msg += f'\t#{index}:\t\t{log_message.format(ip, port, model, name, power)}\n' logging.info(f'More than one bulb found:\n {bulbs_found_msg}') while True: try: chosen_index = int( input('Please input the # of the bulb you want to use ' f'(0-{len(bulbs_discovered) - 1}): ')) except ValueError: logging.error('Input must be an integer!\n') continue if chosen_index in range(len(bulbs_discovered)): ip, port, model, name, power = get_parameters( bulbs_discovered[chosen_index]) logging.info('Proceeding: ' + log_message.format(ip, port, model, name, power)) return yeelight.Bulb(ip) else: logging.error( f'The bulb # should be in range [0-{len(bulbs_discovered) - 1}]\n' )
def monitor_bulb_static(event, cond): """ Monitors for bulb connection/disconnections. Mainly for disconnections. :param event: :return: """ setprocname('Static bulbs') current_bulbs_ips = sorted( set(bulb['ip'] for bulb in yeelight.discover_bulbs())) while True: try: found_bulbs_ip = sorted( set(bulb['ip'] for bulb in yeelight.discover_bulbs(1))) if current_bulbs_ips != found_bulbs_ip: # Retry 3 times. Sometimes a bulb doesn't respond for whatever reason. for _ in range(3): tmp_found_bulbs_ip = sorted( set(bulb['ip'] for bulb in yeelight.discover_bulbs(0.8))) if tmp_found_bulbs_ip == current_bulbs_ips: break else: new_ips = set(found_bulbs_ip) - set(current_bulbs_ips) missing_ips = set(current_bulbs_ips) - set(found_bulbs_ip) for new_ip in new_ips: logger.info('Found new bulb at ip addr: %s', new_ip) for missing_ip in missing_ips: logger.info('Missing bulb at ip addr: %s', missing_ip) current_bulbs_ips = found_bulbs_ip event.set() with cond: logger.info("Static bulb") cond.notify() time.sleep(60) except: logger.exception("Got exception in static bulb")
def check_ip_change(): lights = yee.discover_bulbs() changes = False for i in range(0, len(lights)): for j in range(0, len(saved_lights)): if lights[i]["capabilities"]["id"] == saved_lights[j]["id"]: if lights[i]["ip"] != saved_lights[j]["ip"]: saved_lights[j]["ip"] = lights[i]["ip"] print("Just for debug") changes = True if changes: del_file() for l in saved_lights: add_light(l, True)
def bulb(): for i in range(10): try: bulb_list = yeelight.discover_bulbs() bulb_ip = bulb_list[0]['ip'] bulb = Bulb(bulb_ip) print('bulb info got') return bulb except BulbException as e: print(e) sleep(2) except IndexError as e: print('No bulb detected') sleep(5)
def __init__(self, rms_th=300, monitor_type='Live', *args, **kwargs): print('Search for light bulb...') self.conf_rms_threshold = rms_th self.monitor_type = monitor_type print('conf_rms_threshold set as: "' + str(self.conf_rms_threshold) + '"') bulbs_data = discover_bulbs() print(bulbs_data) ip = bulbs_data[0]["ip"] print(ip) self.bulb = Bulb(ip, effect="smooth", duration=1000) self.bulb.turn_on() self.bulb.set_rgb(255, 255, 255) super(Monitor, self).__init__(*args, **kwargs)
def _init_bulbs(self, bulbs): discover_bulbs(timeout=2, interface=False) for idx, light in enumerate(bulbs): yeelight = light yeelight.get_properties() if yeelight.last_properties.get("power") == "off": yeelight.toggle(effect="sudden") self._settings["bulbs"][idx]["state"][ "power"] = yeelight.last_properties.get("power") rgb = int(yeelight.last_properties.get("rgb")) blue = rgb & 0xff green = (rgb >> 8) & 0xff red = (rgb >> 16) & 0xff self._settings["bulbs"][idx]["state"]["colors"]["r"] = red self._settings["bulbs"][idx]["state"]["colors"]["g"] = green self._settings["bulbs"][idx]["state"]["colors"]["b"] = blue yeelight.start_music() self._settings["bulbs"][idx]["state"]["music_mode"] = 1