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
class WhiteBulb: def __init__(self, ip): self.bulb = Bulb(ip) def power_on(self): self.bulb.turn_on() print("Turning the light on...") def power_off(self): self.bulb.turn_off() print("Turning the light off...") def power_toggle(self): self.bulb.toggle() print("Toggling the light...") def set_brightness(self, bright): self.bulb.set_brightness(bright) print("Setting the brightness to ", bright, "%...") def set_temperature(self, temp): self.bulb.set_color_temp(temp) print("Setting the temperature to ", temp, "K...") def get_status(self): status = self.bulb.get_properties() power = status['power'] bright = status['bright'] temp = status['ct'] rgb = status['rgb'] r, g, b = [rgb[i:i + 3] for i in range(0, len(rgb), 3)] rgb = "(" + r + ", " + g + ", " + b + ")" print("Power: {}\nBrighness: {}%\nTemperature: {}K\nRGB: {}".format( power, bright, temp, rgb))
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)
class YeetBulb: def __init__(self, name, ip): self.name = name self.ip = ip self.bulb = Bulb(self.ip, effect="smooth", duration=750, auto_on=True) self.properties = self.bulb.get_properties() def __getitem__(self, key): return getattr(self, key) def turnoff(self): self.bulb.turn_off() def turnon(self): self.bulb.turn_on() def toggle(self): self.bulb.toggle() def loadPreset(self, preset): if os.path.isfile(preset): with open(preset, 'r') as f: config = json.load(f) if 'preset' in config: preset = config['preset'] if ('rgb' in preset): try: self.bulb.set_rgb(preset['rgb'][0], preset['rgb'][1], preset['rgb'][2]) except: print('not supported by bulb') if ('hsv' in preset): try: self.bulb.set_hsv(preset['hsv'][0], preset['hsv'][1], preset['hsv'][2]) except: print('not supported by bulb') if ('color_temp' in preset): try: self.bulb.set_color_temp(preset['color_temp']) except: print('not supported by bulb') if ('brightness' in preset): try: self.bulb.set_brightness(preset['brightness']) except: print('not supported by bulb') if ('color_temp' in preset): try: self.bulb.set_color_temp(preset['color_temp']) except: print('not supported by bulb') else: print('File not found: ' + preset) def updateProperties(self): self.properties = self.bulb.get_properties()
class YeelightBulb(object): def __init__(self, name, ip, support, model, power): self.name = name self.ip = ip self.support = support self.model = model self.power = power self.bulb = Bulb(self.ip, auto_on=True) def set_power(self, mode): answer = ('%s is now %s' % (self.name, mode)) if mode == "on" and self.power != "on": self.bulb.turn_on() self.power = mode elif mode == "off" and self.power != "off": self.bulb.turn_off() self.power = mode elif mode == "toggle": self.bulb.toggle() if self.power == "on": self.power = "off" else: self.power = "on" else: answer = ('%s is already %s' % (self.name, self.power)) return answer def set_brightness(self, value): self.bulb.set_brightness(value) answer = ('%s brightness value set' % self.name) return answer def set_rgb(self, color, color_name): if "set_rgb" in self.support: self.bulb.set_rgb(color[0],color[1],color[2]) answer = ('%s color set to %s' % (self.name, color_name)) else: answer = ('%s doesn\'t support RGB color mode' % self.name) return answer def set_color_temp(self, temp): if "set_ct_abx" in self.support: if 1700 <= temp <= 6500: self.bulb.set_color_temp(temp) answer = ('%s color temperature set' % self.name) else: answer = 'Color temperature must be between 1700 and 6500 degrees' else: answer = ('%s doesn\'t support color temperature adjustment' % self.name) return answer
def set_light_name(ip, light_model, light_id): print("Name not defined for Yeelight {}, ID: {}".format(light_model, light_id)) # Identify light for user try: bulb = Bulb(ip) bulb.turn_off() bulb.effect = "sudden" bulb.turn_on() bulb.set_brightness(100) bulb.set_rgb(0, 0, 255) bulb.effect = "smooth" bulb.duration = 10000 bulb.set_rgb(255, 0, 0) except: print( "Communication failed with Yeelight {}, ID: {}".format( light_model, light_id ) ) return "" # Get user input for light name print("This device will change color from blue to red over 10 seconds.") print("Enter name for this device or press enter to skip it:") input_char = input() if input_char == "": try: bulb.turn_off() except: print( "Communication failed with Yeelight {}, ID: {}".format( light_model, light_id ) ) return "" return "" # Set light name device_name = input_char try: bulb.set_name(device_name) except: print( "Communication failed with Yeelight {}, ID: {}".format( light_model, light_id ) ) return "" return device_name
def start_dawn(duration: timedelta, bulb: Bulb): steps = duration // STEP logger.info('Starting dawn in %s steps...', steps) bulb.turn_on() for step in range(steps): temperature = get_value(MIN_TEMPERATURE, MAX_TEMPERATURE, steps, step) brightness = get_value(MIN_BRIGHTNESS, MAX_BRIGHTNESS, steps, step) logger.debug( 'Setting up temperature to %s and brightness to %s on %s step', temperature, brightness, step) bulb.set_color_temp(temperature) bulb.set_brightness(brightness) sleep(STEP.seconds) logger.info('Rise and shine!')
def lightup_bulb(bulb: Bulb, ip: str, color: List[int], brightness: int): """ This method is used to, surprise surprise, light up a bulb with selected color :param bulb: Bulb object from yeelight lib :param ip: bulb's ip as str :param color: list with colors as [r, g, b] :param brightness: int with brightness level (0-100) :return: None """ bulb._ip = ip bulb.turn_on() bulb.set_rgb(color[0], color[1], color[2]) bulb.set_brightness(int(brightness))
def brightness(): if ip is None: return jsonify({'status': 'error', 'message': 'no bulb found'}) bulb = Bulb(ip) try: bulb.set_brightness(10) except: return jsonify({'status': 'error', 'message': 'could not adjust brightness'}) return jsonify({'status': 'OK'})
class BulbContainer: def __init__(self, ip): self.bulb = Bulb(ip, duration=1000) def blink(self, duration, retry=10): try: self.bulb.turn_on(duration=1000) self.bulb.set_color_temp(6500) self.bulb.set_brightness(100) sleep(duration) self.bulb.turn_off(duration=10000) except Exception as ex: log(f"Blink error: {ex}") if retry > 0: log(f'Retrying... ({retry} more time)') self.blink(duration, retry=retry - 1)
def user_homepage(request): bulb = Bulb("10.3.3.144") if request.GET.get('connect'): print(request.GET.get('connect')) print("Discovering") print(discover_bulbs()) elif request.GET.get('turnon'): print(request.GET.get('turnon')) print("Turning On") bulb.turn_on() elif request.GET.get('turnoff'): print(request.GET.get('turnoff')) print("Turning Off") bulb.turn_off() elif request.GET.get('dimming'): print(request.GET.get('dimming')) print("Dimming") bulb.set_brightness(100) elif request.GET.get('color'): print(request.GET.get('color')) print("Setting Color") bulb.set_color_temp(2000) elif request.GET.get('lecrepecafe'): print(request.GET.get('lecrepecafe')) print("Clicked Le Crepe Cafe") bulb.turn_on() bulb.set_color_temp(6500) elif request.GET.get('starbucks'): print(request.GET.get('starbucks')) print("Clicked Starbucks") bulb.turn_on() bulb.set_color_temp(1500) elif request.GET.get('jamba'): print(request.GET.get('jamba')) print("Clicked Jamba") bulb.turn_on() bulb.set_color_temp(1500) elif request.GET.get('panda'): print(request.GET.get('panda')) print("Clicked Panda") bulb.turn_on() bulb.set_color_temp(6500) return render(request, 'users/userhome.html')
def flash(): bulbs_data = discover_bulbs() print(bulbs_data) ip = bulbs_data[0]["ip"] print(ip) bulb = Bulb(ip, effect="smooth", duration=1000) bulb.turn_on() bulb.set_rgb(255, 255, 255) bulb.set_brightness(100) try: for flash_count in range(0, 17): bulb.set_rgb(30, 144, 255) time.sleep(0.6) bulb.set_rgb(220, 20, 60) time.sleep(0.6) bulb.set_brightness(30) bulb.set_rgb(255, 255, 255) except (RuntimeError, BulbException): print("error")
def upd(self, progress=None, retry=3): """ update the current bulb colour and brightness :param progress: :param retry: :return: """ try: _progress = progress or min( max((self.now - self.sunset).seconds, 0) / (self.dusk - self.sunset).seconds, 1) bulb = Bulb(self.bulb) bulb.set_rgb(*self.grad[min(int(_progress * len(self.grad)), len(self.grad) - 1)]) bulb.set_brightness(self.brightness[min( int(_progress * len(self.brightness)), len(self.grad) - 1)]) except BulbException: time.sleep(10) if retry > 0: return self.upd(progress, retry - 1)
def index(request): bulb = Bulb("10.3.3.144") if request.GET.get('connect'): print(request.GET.get('connect')) print("Discovering") print(discover_bulbs()) elif request.GET.get('turnon'): print(request.GET.get('turnon')) print("Turning On") bulb.turn_on() elif request.GET.get('turnoff'): print(request.GET.get('turnoff')) print("Turning Off") bulb.turn_off() elif request.GET.get('dimming'): print(request.GET.get('dimming')) print("Dimming") bulb.set_brightness(1) elif request.GET.get('color'): print(request.GET.get('color')) print("Setting Color") bulb.set_color_temp(2000) return render(request, 'index.html')
def room_handler(): post_dict = request.query.decode() if 'ct' in post_dict and 'bri' in post_dict: ct = int(post_dict['ct']) bri = int(float(post_dict['bri']) * 100) for (currentbulb, maxtemp, mintemp) in zip(bulbs, maxtemps, mintemps): if currentbulb != '': print('Sending command to Yeelight at', currentbulb) bulb = Bulb(currentbulb) if static_brightness is False: bulb.set_brightness(bri) print('Brightness set to', bri, 'percent') if int(mintemp) < ct < int(maxtemp): bulb.set_color_temp(ct) print('Color temperature set to', ct, 'Kelvin') else: if ct > int(maxtemp): bulb.set_color_temp(int(maxtemp)) print('Reached highest color temperature of', maxtemp, 'Kelvin') if ct < int(mintemp): bulb.set_color_temp(int(mintemp)) print('Reached lowest color temperature of', mintemp, 'Kelvin')
def activate_light(): global t_end bulb = Bulb('[BULB IP ADDRESS]', effect='smooth', duration=1500) bulb.start_music() bulb.set_rgb(255, 0, 0) bulb.set_brightness(10) bulb.turn_on() t_end = time.time() + 60 # Fade light while time.time() < t_end: bulb.set_brightness(75) time.sleep(2) bulb.set_brightness(10) time.sleep(2) bulb.turn_off()
def main(): print('Welcome to fluxee by davidramiro') print('Reading config...') config = configparser.ConfigParser() config.read('config.ini') global static_brightness bulb_count = int(config.get('general', 'LampCount')) check_state = config.getboolean('general', 'CheckLampState') static_brightness = config.getboolean('general', 'StaticBrightness') default_brightness = int(config.get('general', 'BrightnessValue')) for n in range(1, (bulb_count + 1)): bulbs.append(config.get(str(n), 'ip')) if config.get(str(n), 'MaxColorTemperature') == '': maxtemps.append(6500) else: maxtemps.append(config.get(str(n), 'MaxColorTemperature')) if config.get(str(n), 'MinColorTemperature') == '': mintemps.append(1700) else: mintemps.append(config.get(str(n), 'MinColorTemperature')) print('Initializing...') for init_bulb in bulbs: if init_bulb != '': print('Initializing Yeelight at %s' % init_bulb) bulb = Bulb(init_bulb) if check_state is True: state = bulb.get_properties(requested_properties=['power']) if 'off' in state['power']: print('Powered off. Ignoring Yeelight at %s' % init_bulb) elif static_brightness is True: print('Changing brightness of', init_bulb) bulb.set_brightness(default_brightness) else: print('Turning on Yeelight at %s' % init_bulb) bulb.turn_on() if static_brightness is True: bulb.set_brightness(default_brightness) else: bulb.set_brightness(100) run(host='127.0.0.1', port=8080) print('Thank you for using fluxee. Have a good one!')
while (correct_date): curr_time = datetime.datetime.now().time() correct_time = (curr_time > dusk) & (curr_time < dusk_plus) sysRandom = random.SystemRandom() print('correct date') #heartbeat if (correct_time): print(f'correct_time {curr_time}') #just for debug purpose if (not bulb_turned): bulbR.turn_on() bulbL.turn_on() bulb_turned = True #I want to change brightness more often bulbL.set_brightness(sysRandom.randint(0, 70)) sleep(0.5) bulbR.set_brightness(sysRandom.randint(0, 70)) sleep(0.5) sleep(sysRandom.randint(1, 3)) bulbL.set_brightness(sysRandom.randint(0, 70)) sleep(0.5) bulbR.set_brightness(sysRandom.randint(0, 70)) sleep(0.5) sleep(sysRandom.randint(1, 3)) #once a while new set of colors bulbL.set_rgb(sysRandom.randint(0, 255), sysRandom.randint(0, 255),
timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) exit(0) bulb.turn_on() bulb.set_brightness(50) print("Ready - go check me out!") time.sleep(10) # Act #dance(bulb) setFree(bulb) time.sleep(5) setMeeting(bulb) time.sleep(5) setDND(bulb) time.sleep(5) # Turn off bulb.turn_off()
class App: def __init__(self): self.window = tk.Tk() self.window.configure(bg='black') self.window.title("Xiaomi led Bulb control") self.window.geometry("1000x580") self.insertIp() self.window.mainloop() def insertIp(self): self.ipText = tk.Label(master=self.window, text='Enter your xiaomi yeelight ip', fg='white', bg='black', font=('Helvetica', 12, 'bold')) self.ipText.grid(row=0, column=0, sticky=tk.N, pady=(15, 0), padx=(10, 0)) self.ipEntry = tk.Entry(master=self.window, width=30, bg='black', fg='white', font=('Helvetica', 12, 'bold')) self.ipEntry.grid(row=0, column=1, sticky=tk.N, pady=(15, 0), padx=(10, 0)) self.confirmIp = tk.Button(master=self.window, width=30, bg='white', fg='black', text="Confirm", command=self.showPanel) self.confirmIp.grid(row=0, column=2, sticky=tk.N, pady=(15, 0), padx=(10, 0)) bulbs_list = discover_bulbs() if len(bulbs_list) > 0: self.ipEntry.delete(0, tk.END) self.ipEntry.insert(0, bulbs_list[0]['ip']) def showPanel(self): self.bulb = Bulb(self.ipEntry.get(), effect="smooth", duration=1000) self.confirmIp.destroy() self.ipEntry.destroy() self.ipText.destroy() # -------------------------------------| RGB FRAME |--------------------------------------------- self.rgb_handler = tk.Frame(master=self.window, bg='black') self.rgb_handler.grid(row=0, column=0, sticky=tk.N, pady=(15, 0), padx=(50, 0)) self.redLabel = tk.Label(master=self.rgb_handler, text="Red", bg="red", fg='white') self.greenLabel = tk.Label(master=self.rgb_handler, text="Green", bg="green", fg='white') self.blueLabel = tk.Label(master=self.rgb_handler, text="Blue", bg="blue", fg='white') self.redLabel.grid(row=0, column=0, sticky=tk.S, pady=(12, 2)) self.greenLabel.grid(row=0, column=1, sticky=tk.S, pady=(12, 2)) self.blueLabel.grid(row=0, column=2, sticky=tk.S, pady=(12, 2)) self.redSlider = tk.Scale(master=self.rgb_handler, from_=1, to=255, tickinterval=60, orient=tk.VERTICAL, bg="red", fg='white', command=self.setRedText) self.greenSlider = tk.Scale(master=self.rgb_handler, from_=1, to=255, tickinterval=60, orient=tk.VERTICAL, bg="green", fg='white', command=self.setGreenText) self.blueSlider = tk.Scale(master=self.rgb_handler, from_=1, to=255, tickinterval=60, orient=tk.VERTICAL, bg="blue", fg='white', command=self.setBlueText) self.redSlider.grid(row=1, column=0, sticky=tk.W, padx=(10, 10), pady=10) self.greenSlider.grid(row=1, column=1, sticky=tk.W, padx=(10, 10)) self.blueSlider.grid(row=1, column=2, sticky=tk.W, padx=(10, 10)) self.redInput = tk.Entry(master=self.rgb_handler, width=5, bg='red', fg='white') self.greenInput = tk.Entry(master=self.rgb_handler, width=5, bg='green', fg='white') self.blueInput = tk.Entry(master=self.rgb_handler, width=5, bg='blue', fg='white') self.redInput.insert(tk.END, 1) self.greenInput.insert(tk.END, 1) self.blueInput.insert(tk.END, 1) self.redInput.grid(row=2, column=0, sticky=tk.N, padx=(10, 10)) self.greenInput.grid(row=2, column=1, sticky=tk.N, padx=(10, 10)) self.blueInput.grid(row=2, column=2, sticky=tk.N, padx=(10, 10)) self.colorFrame = tk.Frame(master=self.rgb_handler, bg="black", width=40, height=40, relief=tk.RIDGE, borderwidth=2) self.colorFrame.grid(row=3, column=1, sticky=tk.S, padx=(10, 10), pady=(10, 15)) self.applyButton = tk.Button(master=self.rgb_handler, command=self.setColors, text="Apply Color") self.applyButton.grid(row=4, column=1, sticky=tk.S) # ---------------------------------| POWER FRAME |---------------------------------------- self.power_handler = tk.Frame(master=self.window, bg='black') self.power_handler.grid(row=0, column=1, sticky=tk.N, padx=(60, 60), pady=20) self.title = tk.Label(master=self.power_handler, text='Xiaomi led Bulb remote control', fg='white', bg='black', font=('Helvetica', 14, 'bold')) self.title.grid(row=0, column=1, sticky=tk.N) self.buttonsHandler = tk.Frame(master=self.power_handler, bg='black') self.buttonsHandler.grid(row=1, column=1, sticky=tk.N, pady=10) self.turnOnButton = tk.Button(master=self.buttonsHandler, text="ON", width=15, command=self.turnOnBulb, padx=5) self.turnOnButton.grid(row=0, column=0, sticky=tk.N, padx=5) self.turnOffButton = tk.Button(master=self.buttonsHandler, text="OFF", width=15, command=self.turnOffBulb) self.turnOffButton.grid(row=0, column=1, sticky=tk.N, padx=5) self.title = tk.Label(master=self.power_handler, text='Brightness', fg='white', bg='black', font=('Helvetica', 12, 'bold')) self.title.grid(row=2, column=1, sticky=tk.N, pady=(20, 5)) self.brightnessSlider = tk.Scale(master=self.power_handler, from_=0, to=100, tickinterval=20, orient=tk.HORIZONTAL, bg="#FFFFFF", fg='#000000', length=200) self.brightnessSlider.set(80) self.brightnessSlider.grid(row=3, column=1, sticky=tk.N, pady=10) self.applyBrightnessButton = tk.Button(master=self.power_handler, text="Apply Brightness", width=15, command=self.setBrightness) self.applyBrightnessButton.grid(row=4, column=1, sticky=tk.N, pady=10) # ---------------------------| MODES FRAME |---------------------------------- self.modes_handler = tk.Frame(master=self.window, bg='black') self.modes_handler.grid(row=0, column=2, sticky=tk.N, padx=30, pady=50) self.mode_1 = tk.Button(master=self.modes_handler, text="Flow 1 (smooth)", width=15, command=lambda: self.showFlow([ RGBTransition(20, 255, 20, 2000), RGBTransition(255, 20, 20, 2000), RGBTransition(20, 20, 255, 2000), RGBTransition(255, 255, 20, 2000), RGBTransition(255, 20, 255, 2000), RGBTransition(20, 255, 255, 2000) ], 10)) self.mode_1.grid(column=0, row=0, pady=(0, 15)) self.mode_2 = tk.Button(master=self.modes_handler, text="Flow 2 (speed)", width=15, command=lambda: self.showFlow([ RGBTransition(20, 255, 20, 100), RGBTransition(255, 20, 20, 100), RGBTransition(20, 20, 255, 100), RGBTransition(255, 255, 20, 100), RGBTransition(255, 20, 255, 100), RGBTransition(20, 255, 255, 100) ], 30)) self.mode_2.grid(column=0, row=1, pady=(0, 15)) self.mode_3 = tk.Button(master=self.modes_handler, text="Flow 3 (temp)", width=15, command=lambda: self.showFlow([ TemperatureTransition(6500, 1000), TemperatureTransition(5200, 1000), TemperatureTransition(4000, 1000), TemperatureTransition(2800, 1000), TemperatureTransition(1700, 1000) ], 5)) self.mode_3.grid(column=0, row=2, pady=(0, 15)) self.mode_4 = tk.Button(master=self.modes_handler, text="Flow 4 (disco)", width=15, command=lambda: self.showFlow(disco(), 5)) self.mode_4.grid(column=0, row=3, pady=(0, 15)) self.mode_5 = tk.Button(master=self.modes_handler, text="Flow 5 (strobe)", width=15, command=lambda: self.showFlow(strobe(), 20)) self.mode_5.grid(column=0, row=4, pady=(0, 15)) self.mode_6 = tk.Button(master=self.modes_handler, text="Flow 6 (alarm)", width=15, command=lambda: self.showFlow(alarm(), 5)) self.mode_6.grid(column=0, row=5, pady=(0, 15)) self.mode_7 = tk.Button(master=self.modes_handler, text="Flow 7 (police)", width=15, command=lambda: self.showFlow(police(), 10)) self.mode_7.grid(column=0, row=6, pady=(0, 15)) self.mode_8 = tk.Button(master=self.modes_handler, text="Flow 8 (smooth)", width=15, command=lambda: self.showFlow(lsd(), 5)) self.mode_8.grid(column=0, row=7, pady=(0, 15)) self.mode_9 = tk.Button(master=self.modes_handler, text="Flow 9 (christmas)", width=15, command=lambda: self.showFlow(christmas(), 5)) self.mode_9.grid(column=0, row=8, pady=(0, 15)) self.mode_10 = tk.Button( master=self.modes_handler, text="Flow 10 (random)", width=15, command=lambda: self.showFlow(random_loop(), 5)) self.mode_10.grid(column=0, row=9, pady=(0, 15)) self.quitBT = tk.Button(master=self.window, text="Quit", font=('Helvetica', 12, 'bold'), command=self.quit) self.quitBT.grid(column=1, row=1, pady=(0, 15)) def turnOnBulb(self): try: self.bulb.turn_on() except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def turnOffBulb(self): try: self.bulb.turn_off() except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def setBrightness(self): try: self.bulb.set_brightness(int(self.brightnessSlider.get())) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def setColors(self): try: self.bulb.set_rgb(int(self.redInput.get()), int(self.greenInput.get()), int(self.blueInput.get())) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def setRedText(self, val): try: self.redInput.delete(0, tk.END) self.redInput.insert(0, val) self.setFrameColor(int(self.redInput.get()), int(self.greenInput.get()), int(self.blueInput.get())) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def setGreenText(self, val): try: self.greenInput.delete(0, tk.END) self.greenInput.insert(0, val) self.setFrameColor(int(self.redInput.get()), int(self.greenInput.get()), int(self.blueInput.get())) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def setBlueText(self, val): try: self.blueInput.delete(0, tk.END) self.blueInput.insert(0, val) self.setFrameColor(int(self.redInput.get()), int(self.greenInput.get()), int(self.blueInput.get())) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def setFrameColor(self, r, g, b): try: rgb_color = "#%02x%02x%02x" % (r, g, b) self.colorFrame.configure(background=rgb_color) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def showFlow(self, transactions, count): try: flow = Flow(count=count, action=Flow.actions.recover, transitions=transactions) self.bulb.start_flow(flow) except: self.showAlert( "Warning", "Your bulb is probably turn off from internet or your ip is badly formatted" ) def quit(self): self.window.destroy() @staticmethod def showAlert(title, message): tk.messagebox.showwarning(title, message)
class LedLightYeeLight(LedLight): def __init__(self, name, ipAddrOrName=None): if ipAddrOrName is None: ipAddrOrName = name self.bulb = Bulb(ipAddrOrName) self.name = name try: self.bulb.set_name(name) except Exception as exc: print "Caught exception socket.error : %s" % exc # Send an RGB message def sendRGB(self, red, green, blue): try: self.bulb.set_rgb(red, green, blue) except Exception as exc: print "Caught exception socket.error : %s" % exc # Send a white message def sendWhite(self, white): try: self.bulb.set_color_temp(5000) self.bulb.set_brightness(white) except Exception as exc: print "Caught exception socket.error : %s" % exc def turnOff(self): try: return self.bulb.turn_off() except Exception as exc: print "Caught exception socket.error : %s" % exc def turnOn(self): try: self.bulb.turn_on() except Exception as exc: print "Caught exception socket.error : %s" % exc def isOn(self): try: return self.bulb.get_properties()['power'] == 'on' except Exception as exc: print "Caught exception socket.error : %s" % exc def getWhite(self): try: properties = self.bulb.get_properties() if (properties['color_mode'] == '2'): return int(properties['bright']) else: return -1 except Exception as exc: print "Caught exception socket.error : %s" % exc # comment def getRGB(self): try: properties = self.bulb.get_properties() if (properties['color_mode'] == '1'): rgb = int(properties['rgb']) return [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255] else: return -1 except Exception as exc: print "Caught exception socket.error : %s" % exc
bulbR.turn_on() bulbL.turn_on() print("FREEZE!\n\n") sleep(1) print("Put your hand's in the air!\n") for i in range(0, 4): player.play() bulbL.set_rgb(0, 0, 255) bulbR.set_rgb(255, 0, 0) bulbL.set_brightness(0) bulbR.set_brightness(100) sleep(interval) bulbR.set_brightness(0) bulbL.set_brightness(100) bulbR.set_rgb(0, 0, 255) sleep(interval) bulbL.set_rgb(255, 0, 0) bulbL.set_brightness(0) bulbR.set_brightness(100)
def set_rgb_bright(r, g, b, l): bulb = Bulb("192.168.1.14") bulb.set_brightness(l) bulb.set_rgb(r, g, b)
class Yeetlight(commands.Cog): def __init__(self, client): self.client = client self.bulb = Bulb("192.168.1.9") self.acceptInput = True self.isTimeout = False @commands.command(hidden=True, aliases=['yeeac']) async def accept_input(self, ctx, boolAccept=True): print(boolAccept) author = ctx.message.author if str(author) == 'YABOI#2205': if boolAccept: self.acceptInput = boolAccept else: self.acceptInput = boolAccept print("boolaccept: " + str(boolAccept)) @commands.command(aliases=['lamp']) async def lampu(self, ctx, command, arg1=None): if command == 'isAccepting' or command == 'isAcceptingCommands': if self.acceptInput: await ctx.send('yes') else: await ctx.send('no') elif command == 'info': embd = discord.Embed(title='Info pake lampu', description='', color=0xb63b24) embd.add_field(name='`.lampu info`', value='gimana cara make command lampu', inline=False) embd.add_field( name='`.lampu isAcceptingCommands`', value= 'buat ngecek bot nya pengen di ganggu untuk ganti lampu atau engga', inline=False) embd.add_field(name='`.lampu isTimeout`', value='buat ngecek masih capek atau engga bot nya', inline=False) embd.add_field( name='`.lampu toggle`', value= 'mati/nyala lampu, tidak sembarang orang bisa ngejalanin ini', inline=False) embd.add_field( name='`.lampu setColor [warna]`', value= 'ganti warna, untuk `[warna]` nya bisa pake kode hex # atau warna premade', inline=False) embd.add_field(name='`.lampu preColor`', value='list warna yg premade', inline=False) embd.add_field( name='`.lampu setBright [level]`', value= 'nambah/ngurang terang, untuk `[level]` nya harus antara 0 sama 100', inline=False) await ctx.send(embed=embd) elif command == 'preColor': embd = discord.Embed( title='warna pre', description='red green blue turqoise yellow orange pink') await ctx.send(embed=embd) elif command == 'isTimeout': if self.isTimeout: await ctx.send('yes') else: await ctx.send('no') elif command == 'toggle': print('masuk toggle') author = ctx.message.author # if str(author) == 'YABOI#2205': self.bulb.toggle() elif command == 'setColor': preColors = [['red', 255, 0, 0], ['green', 0, 255, 0], ['blue', 0, 0, 255], ['turqoise', 175, 238, 238], ['yellow', 255, 224, 93], ['orange', 255, 150, 66], ['pink', 255, 224, 93]] valid = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' ] if self.acceptInput: if len(arg1) == 7 and arg1[0] == '#' and all(char in valid for char in arg1): print('masuk setColor hex') if self.isTimeout == False: self.isTimeout = True red = int(arg1[1] + arg1[2], 16) green = int(arg1[3] + arg1[4], 16) blue = int(arg1[5] + arg1[6], 16) if red <= 0 and green <= 0 and blue <= 0: print('no item') return self.bulb.set_rgb(red, green, blue) await asyncio.sleep(1) await ctx.send( f'warna lampu berhasil diganti menjadi warna **{arg1}**' ) self.isTimeout = False else: await ctx.send('timeout tunggu beberapa detik') elif any(arg1 in color for color in preColors): print('masuk setColor premade ') colorC = next(c for c in preColors if c[0] == arg1) print(colorC) # print(arg1 + colorC[1] + colorC[2] + colorC[3]) if self.isTimeout == False: self.isTimeout = True self.bulb.set_rgb(colorC[1], colorC[2], colorC[3]) await asyncio.sleep(1) await ctx.send( f'warna lampu berhasil diganti menjadi warna **{arg1}**' ) self.isTimeout = False else: await ctx.send('timeout tunggu beberapa detik') else: await ctx.send('warna tidak ditemukannnn') else: await ctx.send('lampu sedang tidak menerima input') elif command == 'setBrightness' or command == 'setBright': bright_level = int(arg1) if self.acceptInput: if bright_level >= 0 and bright_level <= 100: if self.isTimeout == False: self.isTimeout = True self.bulb.set_brightness(bright_level) await asyncio.sleep(1) self.isTimeout = False await ctx.send( f'brightness lampu berhasil diubah menjadi **{bright_level}%**' ) else: await ctx.send('timeout tunggu beberapa detik') else: await ctx.send('brightness harus 0<=n<=100') else: await ctx.send('lampu sedang tidak menerima input') else: await ctx.send('command tak dikenal :(')
class Device(BaseDevice): typesDevice = ["light"] name = DEVICE_NAME addConfig = AddDevice( fields=False, description= "1. Through the original application, you must enable device management over the local network.\n2. Enter the ip-address of the device (it can be viewed in the same application)." ) editConfig = EditDevice(address=True, fields=EditField(icon=True)) def __init__(self, *args, **kwargs): super().__init__(**kwargs) self.device = Bulb(self.coreAddress) try: values = self.device.get_properties() self.minmaxValue = self.device.get_model_specs() if (not look_for_param(self.values, "state") and "power" in values): val = "0" if (values["power"] == "on"): val = "1" self.values.append( DeviceElement(name="state", systemName=self.systemName, control=True, high=1, low=0, type="binary", icon="fas fa-power-off", value=val)) if (not look_for_param(self.values, "brightness") and "current_brightness" in values): self.values.append( DeviceElement(name="brightness", systemName=self.systemName, control=True, high=100, low=0, type="number", icon="far fa-sun", value=values["current_brightness"])) if (not look_for_param(self.values, "night_light") and self.minmaxValue["night_light"] != False): self.values.append( DeviceElement(name="night_light", systemName=self.systemName, control=True, high="1", low=0, type="binary", icon="fab fa-moon", value=values["active_mode"])) if (not look_for_param(self.values, "color") and values["hue"] != None): self.values.append( DeviceElement(name="color", systemName=self.systemName, control=True, high=360, low=0, type="number", icon="fab fa-medium-m", value=values["hue"])) if (not look_for_param(self.values, "saturation") and values["sat"] != None): self.values.append( DeviceElement(name="saturation", systemName=self.systemName, control=True, high=100, low=0, type="number", icon="fab fa-medium-m", value=values["sat"])) if (not look_for_param(self.values, "temp") and "ct" in values): self.values.append( DeviceElement(name="temp", systemName=self.systemName, control=True, high=self.minmaxValue["color_temp"]["max"], low=self.minmaxValue["color_temp"]["min"], type="number", icon="fas fa-adjust", value=values["ct"])) super().save() except Exception as e: logger.warning(f"yeelight initialize error. {e}") self.device = None def update_value(self, *args, **kwargs): values = self.device.get_properties() state = look_for_param(self.values, "state") if (state and "power" in values): val = "0" if (values["power"] == "on"): val = "1" saveNewDate(state, val) brightness = look_for_param(self.values, "brightness") if (brightness and "current_brightness" in values): saveNewDate(brightness, values["current_brightness"]) mode = look_for_param(self.values, "night_light") if (mode and "active_mode" in values): saveNewDate(mode, values["active_mode"]) temp = look_for_param(self.values, "temp") if (temp and "ct" in values): saveNewDate(temp, values["ct"]) color = look_for_param(self.values, "color") if (color and "hue" in values): saveNewDate(color, values["hue"]) saturation = look_for_param(self.values, "saturation") if (saturation and "sat" in values): saveNewDate(saturation, values["sat"]) def get_value(self, name): self.update_value() return super().get_value(name) def get_values(self): self.update_value() return super().get_values() def set_value(self, name, status): status = super().set_value(name, status) if (name == "state"): if (int(status) == 1): self.device.turn_on() else: self.device.turn_off() if (name == "brightness"): self.device.set_brightness(int(status)) if (name == "temp"): self.device.set_power_mode(PowerMode.NORMAL) self.device.set_color_temp(int(status)) if (name == "night_light"): if (int(status) == 1): self.device.set_power_mode(PowerMode.MOONLIGHT) if (int(status) == 0): self.device.set_power_mode(PowerMode.NORMAL) if (name == "color"): self.device.set_power_mode(PowerMode.HSV) saturation = look_for_param(self.values, "saturation") self.device.set_hsv(int(status), int(saturation.get())) if (name == "saturation"): self.device.set_power_mode(PowerMode.HSV) color = look_for_param(self.values, "color") self.device.set_hsv(int(color.get()), int(status)) def get_All_Info(self): self.update_value() return super().get_All_Info()
from yeelight import Bulb, HSVTransition, Flow, TemperatureTransition, SleepTransition, RGBTransition import sys ip = sys.argv[1] ip2 = sys.argv[2] ip3 = sys.argv[3] bulb = Bulb(ip) bulb2 = Bulb(ip2) bulb3 = Bulb(ip3) bulb.turn_on() bulb2.turn_on() bulb3.turn_off() bulb.set_brightness(10) bulb2.set_brightness(10) bulb.set_rgb(255, 255, 255) bulb2.set_rgb(255, 255, 255)
class NoiseMonitor(Monitor): # rms_list = [] conf_max_sample = 200 conf_rms_threshold = 0 conf_rms_over_threshold = 5 conf_max_flash_count = 25 average_q_size = 5 is_playing_sound = False is_flashing_light = False bulb = None meterr = None interval = 5 monitor_type = 'Live' warning_level = deque([]) rms_average = deque([]) red_light = False first_sound = False wait_until = datetime.datetime.now() + datetime.timedelta(seconds=5) no_alert_until = datetime.datetime.now() 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 monitor(self, rms): rms_avg = int(round(self.get_rms_average(rms))) print('CURRENT RMS: ' + str(rms) + '; AVERAGE RMS: ' + str(rms_avg)) if self.monitor_type == 'Live': # Convert from 1 to rms threshold, to 1-100 bright = int(round(rms_avg / self.conf_rms_threshold * 100)) if bright > 100: bright = 100 # Check alert per 5 seconds if self.wait_until < datetime.datetime.now(): if bright > 99: if self.no_alert_until < datetime.datetime.now(): self.warning_level.append(1) # Call alert method print('CURRENT LEVEL SUM: ' + str(sum(self.warning_level))) self.trigger_warning(sum(self.warning_level)) elif bright < 100: # Clear all warnings level self.warning_level.clear() # Set to default - White light with low brightness self.bulb.set_rgb(255, 255, 255) print("DEBUG: SET WHITE") self.bulb.set_brightness(bright) print("DEBUG: BRIGHTNESS: " + str(bright) + "; TIME: " + str(datetime.datetime.now().time())) self.wait_until = datetime.datetime.now() + datetime.timedelta( seconds=self.interval) def trigger_warning(self, warning_level=0): if self.no_alert_until < datetime.datetime.now(): if warning_level == 1: self.trigger_alert(sound=None, brightness=100, color_R=0, color_G=255, color_B=0) # self.trigger_alert(sound=None, brightness=100, color_R=255, color_G=165, color_B=0) elif warning_level == 2: self.trigger_alert(sound=None, brightness=100, color_R=0, color_G=0, color_B=255) elif warning_level == 3: self.trigger_alert(sound='Shush_Short.mp3', brightness=100, color_R=255, color_G=0, color_B=0) elif warning_level == 4: self.trigger_alert(sound='shush.mp3', brightness=100, color_R=255, color_G=0, color_B=0) elif warning_level == 5: self.trigger_voice_and_blink() elif warning_level > 5: self.trigger_alert(sound=None, brightness=100, color_R=255, color_G=0, color_B=0) #sleep for 1 mintute self.no_alert_until = datetime.datetime.now( ) + datetime.timedelta(seconds=60) # Clear all warnings level self.warning_level.clear() else: print("DEBUG: Unhandled level: '" + str(warning_level) + "'") def trigger_alert(self, sound, brightness, color_R, color_G, color_B): """ Alert - play sound + flash light """ _thread.start_new_thread(self.playsound, (sound, )) _thread.start_new_thread(self.set_light, ( brightness, color_R, color_G, color_B, )) print("DEBUG: trigger_alert: sound=" + str(sound) + "; brightness=" + str(brightness) + "; color_R=" + str(color_R) + "; color_G=" + str(color_G) + "; color_B=" + str(color_B)) def set_light(self, brightness=None, color_R=None, color_G=None, color_B=None): if color_R != None and color_G != None and color_B != None: self.bulb.set_rgb(color_R, color_G, color_B) if brightness != None: self.bulb.set_brightness(brightness) def playsound(self, sound=None): try: if sound != None: if not self.is_playing_sound: self.is_playing_sound = True playsound('./mp3/' + str(sound)) self.is_playing_sound = False except Exception: pass def get_rms_average(self, rms, queue_size=average_q_size): if len(self.rms_average) > queue_size: self.rms_average.popleft() self.rms_average.append(rms) return sum(self.rms_average) / len(self.rms_average) def return_rms_average(self): return str(sum(self.rms_average)) def trigger_voice_and_blink(self): _thread.start_new_thread(self.playsound, ('silence_pleae_esp.wav', )) _thread.start_new_thread(self.flashlight, (2, )) # def trigger_siren(self): # """ Alert - play sound + flash light """ # _thread.start_new_thread(self.playsound, ('siren.mp3',)) # _thread.start_new_thread(self.flashlight, ()) def flashlight(self, flash_count): if not self.is_flashing_light: self.is_flashing_light = True # self.bulb.turn_on() self.bulb.set_brightness(100) try: for flash_count in range(0, flash_count): self.bulb.set_rgb(30, 144, 255) time.sleep(0.6) self.bulb.set_rgb(220, 20, 60) time.sleep(0.6) self.bulb.set_brightness(100) self.bulb.set_rgb(255, 0, 0) except (RuntimeError, BulbException): print("error") # self.bulb.turn_off() self.is_flashing_light = False else: print("light already flashing")
parser.add_argument('-b', '--brightness', help='set the brightness', type=int) onoff = parser.add_mutually_exclusive_group() onoff.add_argument('--on', help='turn on the light', action="store_true") onoff.add_argument('--off', help='turn off the light', action="store_true") colors = parser.add_mutually_exclusive_group() colors.add_argument('-t', '--temp', help='set the white color temp', type=int) colors.add_argument('-c', '--color', help='set the rgb color', type=valid_color) args = parser.parse_args() for bulbaddr in args.bulbs: bulb = Bulb(bulbaddr) if args.switch: status = bulb.get_properties() if status['power'] == "off": bulb.turn_on() else: bulb.turn_off() if args.on: bulb.turn_on() elif args.off: bulb.turn_off() if args.brightness is not None: bulb.set_brightness(args.brightness) if args.temp is not None: bulb.set_color_temp(args.temp) elif args.color is not None: bulb.set_rgb(args.color[0], args.color[1], args.color[2])
from yeelight import Bulb import sys ip = sys.argv[1] brightness = sys.argv[2] bulb = Bulb(ip) result = bulb.set_brightness(int(brightness)) print(result)
elif event == '-SLIDER B-': value_b = values['-SLIDER B-'] elif event == '-SEND RGB-' and value_r.isnumeric( ) and value_g.isnumeric() and value_b.isnumeric(): value_r_i = int(value_r) value_g_i = int(value_g) value_b_i = int(value_b) zero_list = [0, 0, 0] value_rgb_list = [value_r_i, value_g_i, value_b_i] if value_rgb_list != zero_list: temp_bulb_obj.set_rgb(value_r_i, value_g_i, value_b_i) elif event == '-SEND BRIGHT-': slider = window[event] slider_brightness = int(values['-BRIGHT-']) temp_bulb_obj.set_brightness(slider_brightness) elif event == '-SEND TEMP-': slider = window[event] slider_temp = int(values['-TEMP-']) temp_bulb_obj.set_color_temp(slider_temp) temp_bulb_obj = None