class Bridge: bridge_ip = '192.168.1.65' def __init__(self): self.bridge = HueBridge(self.bridge_ip) self.bridge.get_api() self.names = [i for i in self.bridge.get_light_objects('name')] self.lights = self.bridge.get_light_objects('name') def brightness(self, bri): for light in self.names: self.bridge.set_light(light, 'bri', bri) def saturation(self, sat): for light in self.names: self.lights[light].saturation = sat def hue(self, hue): for light in self.names: self.lights[light].hue = hue def execute(self, hue, bri, sat): for light in self.names: self.lights[light].hue = hue self.bridge.set_light(light, 'bri', bri) self.lights[light].saturation = sat
def connect_to_hue_bridge(config): """ function to establish a connection to the hue bridge """ logger.info("Connecting to hue bridge") bridge = None max_connect_tries = 3 for i in range(max_connect_tries): try: #get the dridge bridge = Bridge(config['hue_bridge_ip'], config_file_path=config['hue_config_file']) # actually do an api request to check whether the connection was succesfull bridge.get_light_objects() logger.info("Connected to hue bridge") # self.connected = True # self.is_on = True break except PhueRegistrationException: print( "\npush the button on the hue bridge, waiting 15 sec for {}:th attempt out of {}\n" .format(i + 1, max_connect_tries)) time.sleep(15) except PhueRequestTimeout: #actually cannot timeout because initialising bridge does not check whether hue bridge is available print("[ ERROR ] Cannot connect to HUE bridge") bridge = None break return bridge
class HueController: def __init__(self, ip): self.b = Bridge(ip) def turnRoomsOff(self, rooms): for room in rooms: self.b.set_group(room, 'on', False) def normalizeRooms(self, rooms): lightIds = [] for room in rooms: lightIds = lightIds + self.b.get_group(room, 'lights') print(lightIds) lights = self.b.get_light_objects('id') print(lights) for id in lightIds: id = int(id) lights[id].on = True lights[id].brightness = 254 lights[id].hue = 8597 lights[id].saturation = 121 pass def nightlight(self, rooms): lightIds = [] for room in rooms: lightIds = lightIds + self.b.get_group(room, 'lights') lights = self.b.get_light_objects('id') for id in lightIds: id = int(id) lights[id].on = True lights[id].brightness = 40 lights[id].hue = 6291 lights[id].saturation = 251 pass
class HueAPIClient(object): def __init__(self): pass def find_bridge(self): import hue.bridge_scanner as bridge_scanner while True: self.ip = bridge_scanner.get_bridge_ips()[0] if 0 < len(self.ip): break print('Bridge found ' + self.ip) self.bridge = Bridge(self.ip) def connect(self): self.bridge.connect() def on(self): lights = self.bridge.get_light_objects() for light in lights: light.on = True def off(self): lights = self.bridge.get_light_objects() for light in lights: light.on = False
class Hue(DriverBase): def __init__(self, num, ip, nameMap=None, **kwds): super().__init__(num, **kwds) if nameMap and len(nameMap) != self.numLEDs: raise ValueError( "nameMap must have the same number of entries as the number of LEDs.") self._bridge = Bridge(ip) self._bridge.connect() self._transitionTime = 0 if nameMap: self._lights = self._bridge.get_light_objects('name') self._ids = nameMap else: self._lights = self._bridge.get_light_objects('id') self._ids = [l for l in self._lights] if len(self._lights) < self.numLEDs: raise ValueError( "More LEDs were specified than there are available Hue lights.") self.setTransitionTime(0) # start with no transition time def setTransitionTime(self, time): if time < 0.0 or time > 30.0: raise ValueError( "Transition time must be between 0.0 and 30.0 seconds.") self._transitionTime = int(time * 10) def _mapRange(self, value, minFrom, maxFrom, minTo, maxTo): return minTo + (maxTo - minTo) * ((value - minFrom) / (maxFrom - minFrom)) def _rgb2hs(self, rgb): r = rgb[0] / 255.0 g = rgb[1] / 255.0 b = rgb[2] / 255.0 h, s, v = colorsys.rgb_to_hsv(r, g, b) h = int(self._mapRange(h, 0.0, 1.0, 0, 65535)) s = int(self._mapRange(s, 0.0, 1.0, 0, 254)) return (h, s) def _send_packet(self): for i in range(len(self._ids)): h, s = self._rgb2hs(self._colors[i + self._pos]) bri = min(254, self._brightness) if s == 0: bri = 0 cmd = {'on': s != 0, 'bri': bri, 'hue': h, 'saturation': s, 'transitiontime': self._transitionTime} self._bridge.set_light(self._ids[i], cmd)
def main(): parser = argparse.ArgumentParser(description='get a domain name') parser.add_argument('--bridge', help='ip/hostname of bridge', default='hue-bridge.lan', dest="br") parser.add_argument('--lids', "-l", help='light numbers', default=False, dest="ls", type=int, nargs='+') parser.add_argument('--lnams', "-n", help='light names', default=False, dest="lns", type=int, nargs='+') parser.add_argument('--on', "-1", help='turn on', action="store_true", default=False, dest="on") parser.add_argument('--off', "-0", help='turn off', action="store_true", default=False, dest="off") parser.add_argument('--colour', "-c", help='change colour', default='blue', dest="c") parser.add_argument('--brightness', "-b", help='change brightness', default='0', dest="b", type=int) parser.add_argument('--discover', "-d", help='show what lights there are', action="store_true", default=False, dest="p") args = parser.parse_args() b = Bridge(args.br) b.connect() if args.p: #print(json.dumps(b.get_light_objects('id') , sort_keys=True,indent=4, separators=(',', ': '))) pp = pprint.PrettyPrinter(indent=4) pp.pprint(b.get_light_objects('id') ) exit() #print b.get_api() lids = b.get_light_objects('id') lnams = b.get_light_objects('id') if args.off and args.on: exit("On and off are mutally exclusive") if args.ls and args.lns: exit("Names and ids are mutally exclusive") if args.off: print "turning lights", ', '.join(str(e) for e in args.ls), "off\n" if args.ls: for l in args.ls: lids[l].on = False if args.lns: for l in args.lns: lnams[l].on = False if args.on: print "turning lights", ', '.join(str(e) for e in args.ls), "on\n" if args.ls: for l in args.ls: lids[l].on = True if args.lns: for l in args.lns: lnams[l].on = True if args.c: print "c\n" if args.b: print "b\n" if args.ls: print "l:", args.ls
class Hue(Command): def __init__(self): self.bridge = Bridge(ip=settings.HUE_IP_ADDRESS, username=settings.HUE_USER) def on(self, device): light = str(closest_match(device, self.bridge.get_light_objects('name').keys())) self.bridge.set_light(light, 'on', True) def off(self, device): light = str(closest_match(device, self.bridge.get_light_objects('name').keys())) self.bridge.set_light(light, 'on', False)
def main(): config = {} try: config_file = os.path.join(expanduser("~"), ".arehuebusy.yml") with open(config_file, 'r') as f: config = yaml.load(f) except Exception as e: print "Error loading config.yml" print e sys.exit(2) valid_status = config["status"].keys() if len(sys.argv) < 2 or sys.argv[1] not in valid_status: print "Missing or invalid status" print "Usage: arehuebusy <%s>" % (','.join(valid_status)) sys.exit(2) status = sys.argv[1] logging.basicConfig() b = Bridge(config["bridge_ip"]) b.connect() status_config = config["status"][status] print status_config["color"] print "Setting %s to %s, brightness %s . . ." % ( config["light"], status_config["color"], status_config["brightness"]) converter = Converter(GamutC) x, y = converter.hex_to_xy(status_config["color"]) busy_light = b.get_light_objects('name')[config["light"]] busy_light.xy = [x, y] busy_light.brightness = status_config["brightness"]
class HueManager: def __init__(self, ip): try: self._bridge = Bridge(ip) except PhueRegistrationException: raise RegistrationException @staticmethod def get_bridge_list(): bridges = discoverhue.find_bridges() return list( map( lambda bridge: { 'id': bridge, 'value': urlparse(bridges[bridge]).hostname }, bridges)) def get_light_list(self): results = [] lights = self._bridge.get_light_objects('id') for k in lights: results.append({'id': lights[k].light_id, 'value': lights[k].name}) return results def set_light(self, light_id, parameter, value=None, transition_time=None): self._bridge.set_light(light_id, parameter, value, transition_time)
def blink_lights(): # Define lights to blink alert_lights = ['Kitchen', 'Living Room', 'Living Room 2'] # Hue bridge IP b = Bridge('192.168.2.4') # If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single time) b.connect() # Get the bridge state (This returns the full dictionary that you can explore) b.get_api() # Get all the Hue lights lights = b.get_light_objects('id') store_settings = {} for id in lights: if lights[id].name in alert_lights: state = {"on" : lights[id].on, 'hue': lights[id].hue, 'saturation': lights[id].saturation, 'brightness': lights[id].brightness} if store_settings.get(id) is None: store_settings[id] = state set_alert_state(lights, store_settings) # wait time.sleep(0.01) set_original_state(lights, store_settings)
def main(): if len(sys.argv) != 2: print "Usage: pants.py <config.yaml>" sys.exit(1) config = yaml.load(open(sys.argv[1])) if not 'lights' in config: print "Config must contain a 'lights' array" sys.exit(1) if not 'device' in config: print "Config must contain a 'device'" sys.exit(1) b = None while b == None: try: b = Bridge("10.0.0.31") except phue.PhueRegistrationException as e: print str(e) sleep(5) lights = b.get_light_objects('name') xbee = subprocess.Popen(["./xbsh2", config['device']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) line = xbee.stdout.readline() p = re.compile('AD3:\s+(\d+)') while line != None: m = p.search(line) if m: value = int(m.group(1)) print value saturation = 254 hue = 65000 if value > 1000: # pants all the way down brightness = 90 elif value > 900: # pants 3/4 down brightness = 130 elif value > 700: # pants halfway down brightness = 170 elif value > 400: # pants 1/4 down brightness = 210 else: # pants up brightness = 254 saturation = 0 for light in config['lights']: l = lights[light] l.on = True l.saturation = saturation l.hue = hue l.brightness = brightness line = xbee.stdout.readline()
def read_bridge_info (): global bridge_bureau global lights_diction global group_diction global group_dic_name_lights global sensor_diction global scene_diction global scene_dic_name_lights global bridge_bureau_ip global laptop_username global iphone_bart # bridge_bureau is an object of type Bridge bridge_bureau = Bridge(ip = bridge_bureau_ip, username = iphone_bart) # make a Diction of all lights by names lights_diction = bridge_bureau.get_light_objects(mode="name") # make a Diction of all groups by key= name and value = [lights] group_diction = bridge_bureau.get_group() group_dic_name_lights = {} # make a diction of all sensors sensor_diction = bridge_bureau.get_sensor() for x in sensor_diction : if sensor_diction[x]["name"]=="Hal kamer Gust" : print (sensor_diction[x]["config"]) # make a diction of all scenes scene_diction = bridge_bureau.get_scene() scene_dic_name_lights = {} return
def rgb_set(self, rgb): red = rgb[0] green = rgb[1] blue = rgb[2] b = Bridge('192.168.1.3') # If the app is not registered and the button is not pressed, press the button # and call connect() (this only needs to be run a single time) b.connect() # Get the bridge state (This returns the full dictionary that you can explore) b.get_api() point = self.convert_rgb(red, green, blue) # aquamarine = convert_rgb(0.498039, 1, 0.831373,) # midnight_blue = convert_rgb(0.0980392, 0.0980392, 0.439216) # light_slate_gray = convert_rgb(0.466667, 0.533333, 0.6) # lavender = convert_rgb(0.901961, 0.901961, 0.980392) # point = lavender x = point[0] y = point[1] lights = b.get_light_objects() for light in lights: light.xy = [x, y]
def bridgeip(): contents = Ipe.get() print("connected to: " + Ipe.get()) global b b = Bridge(Ipe.get()) lights = b.get_light_objects() b.connect()
def light_control(message, action, light): b = Bridge(settings.HUE_BRIDGE_IP, username=settings.HUE_USERNAME) lights = b.get_light_objects('name') fuzzy_lights = {l.lower(): l for l in lights.keys()} # key search found_key = '' if light.lower() in fuzzy_lights.keys(): found_key = fuzzy_lights[light.lower()] else: possible = difflib.get_close_matches(light.lower(), fuzzy_lights.keys()) if len(possible) > 0: found_key = fuzzy_lights[possible[0]] # control action if action == "off" and found_key in lights: lights[found_key].on = False message.react('bulbout') elif action == "on" and found_key in lights: lights[found_key].on = True message.react('bulb') else: message.react('bulbunknown')
def access_lights(): #Get bridge object b = Bridge(bridge_ip_address) #Get lights list light_list = b.get_light_objects('id') return light_list
def flash(): b = Bridge("10.0.1.2") # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented #b.connect() lights = b.get_light_objects() color_list = [25653, 41613, 63155] rnd_color = random.randrange(0,2+1) light_settings = {'bri' : 254, 'hue' : color_list[rnd_color], 'on' : True, 'transitiontime' : 0} last_light = 1 for x in range(0, 10): rnd_light = random.randrange(1,3+1) b.set_light(rnd_light, light_settings) b.set_light(last_light, 'on', False, transitiontime=0) last_light = rnd_light for z in range(0, 3): b.set_light([1, 2, 3], 'on', False, transitiontime=0) print rnd_color return "OK"
def lights_phue_random(): b = Bridge("192.168.10.196") # Enter bridge IP here. # If running for the first time, press button on bridge and run with b.connect() uncommented #b.connect() lights = b.get_light_objects() for light in lights: light.brightness = 254 light.xy = [random.random(), random.random()] return redirect(url_for('lights_phue'))
def main(): parser = argparse.ArgumentParser(description="Hue to Spacebrew bridge") parser.add_argument("-s", "--server", help="Spacebrew server", default="sandbox.spacebrew.cc") parser.add_argument("-p", "--port", help="Spacebrew port", type=int, default=9000) parser.add_argument("-b", "--bridge", help="Hue bridge") args = parser.parse_args() print("Connecting to Spacebrew server: %s port %d"%(args.server, args.port)) brew = Spacebrew("Hue Bridge", server=args.server, port=args.port) if args.bridge is None: info = urllib.urlopen('http://www.meethue.com/api/nupnp').read() info = json.loads(info) if len(info) > 0: args.bridge = info[0][u'internalipaddress'] else: print("ERROR: Could not auto-detect Hue bridge IP") print(" Please specify --bridge manually") sys.exit(1) print("Connecting to Hue bridge at: %s" % args.bridge) bridge = None while bridge == None: try: bridge = Bridge(args.bridge) except phue.PhueRegistrationException as e: print(str(e)) sleep(5) lights = bridge.get_light_objects('name') brew_lights = [] print("Lights:") for name in lights: print(" - %s"%(name)) brew_lights.append(HueBulb(brew, name, lights[name])) print("Starting Spacebrew") brew.start() sleep(5) try: while True: for light in brew_lights: light.poll() # chill out man sleep(0.33) finally: brew.stop()
def set_hue_color(): hue = settings.BRIDGE_IP goldenrod = [0.5136, 0.4444] bridge = Bridge(hue) lights = bridge.get_light_objects(mode='id').values() for light in lights: light.xy = goldenrod
def main(): global started # Get config + setup HUE client with open(f"{cwd}/config.json", "r") as f: config = json.load(f) # Get users config for his HUE ip = config['ip'] username = config["username"] # If user has no IP setup get him to input one if ip == "": emit_socket( "Please enter in your HUE's IP. Found here: https://discovery.meethue.com/" ) print( "Please enter in your HUE's IP. Found here: https://discovery.meethue.com/" ) time.sleep(10) # Return and check if user entered return main() # Connect to user's HUE try: hue = Bridge(ip) hue.connect() print("HUE connected") emit_socket("HUE connected") except: print("Please connect HUE") emit_socket("Please connect HUE") time.sleep(5) return main() # Update lights available and define the hue light lights = hue.get_light_objects('id') lights_object = [] for light in lights: lights_object.append({"name": lights[light].name, "id": light}) config["lights"] = lights_object utilities.write_json(f"{cwd}/config.json", config) # Stop this loop when a video capture starts up while started == False: try: print("Waiting for video") time.sleep(3) # Get current inputs inputs = get_inputs() if len(inputs) > 0: # Start watching video / input started = True listen_video(0, lights) break else: print("No input available") emit_socket("No input available") except Exception as e: print(f"Error waiting for video: {e}") emit_socket(f"Error waiting for video: {e}")
def main(argv): bridgeIP = "0" check_interval = 60 try: opts, args = getopt.getopt(argv, "b:", ["bridge="]) except getopt.GetoptError: optUsage() sys.exit(2) except ValueError: print("ULS: Incorrect option usage!") sys.exit(2) for opt, arg in opts: if opt in ("-b", "--bridge"): bridgeIP = arg #elif opt in ("-i", "--interval"): #check_interval = float(arg) #print("ULS: Bridge IP Address: %s" % bridgeIP) try: bridge = Bridge(bridgeIP) except: print("ULS: Woah there, and error appeared!") while True: try: lights_list = bridge.get_light_objects('list') #print "Got list of lights" lights_file = open("off.lights", 'w') #print "Opened off.lights" lights_file.truncate() #print "Truncated off.lights" lights_file.write(datestamp()) #print "Wrote datestamp to file" lights_file.write("\n") #print "Wrote newline" lights_file.write(bridgeIP) #print "Wrote BridgeIP" lights_file.write("\n") # Store list of lights that are currently off #off_lights = [i] for light in lights_list: if not light.on: #off_lights.append(light) lights_file.write(light.name) lights_file.write("\n") lights_file.close() except Exception as e: # Exception! print("%s: ULS: An exception has appeared... %s" % (datestamp(), str(e))) bridge.get_api() time.sleep(check_interval)
class LightController: def __init__(self, config): self.config = config self.bridge = Bridge(config.get('ip')) self.bridge.connect() self._lights = self.bridge.get_light_objects('id') self.brightness = tk.IntVar self._lights_on = self.are_all_lights_on() def set_all_lights_on(self, on=True): new_light_state = { 'transitiontime': 10, 'on': on, 'bri': 254, 'sat': 0 } self.bridge.set_light(self._lights, new_light_state) self._lights_on = True def set_all_lights_brightness(self, brightness): bri = round(int(float(brightness))) if bri < 1: self.set_all_lights_on(False) self.brightness = 0 return False new_light_state = {'transitiontime': 0, 'on': True, 'bri': bri} self.bridge.set_light(self._lights, new_light_state) self.brightness = brightness return True def get_all_lights(self): return self._lights def are_all_lights_on(self): for light in self.bridge.get_light_objects(): if not light.on: return False return True def sync(self): self._lights_on = self.are_all_lights_on()
def lights_off(): b = Bridge("192.168.10.196") # Enter bridge IP here. # If running for the first time, press button on bridge and run with b.connect() uncommented #b.connect() lights = b.get_light_objects() for light in lights: if light.on == True: light.on = False else: light.on = False return redirect(url_for('lights_phue'))
def hue_connect(): not_connected = True while(not_connected): try: bridge = Bridge('4908hue.eecs.umich.edu') bridge.connect() not_connected = False except: print("\nGo push the button on the hub to authorize this program. I'll wait.\n") raw_input("Hit enter when you're done. ") all_lights = bridge.get_light_objects() return all_lights
def main(): from phue import Bridge import argparse # user-specific settings lights_in_play = [ 'Office Lamp 1A' # 'Front Porch', # 'Entryway', 'Foyer', # 'TV', 'Ledge 1', 'Ledge 2', 'Ledge 3', 'Ledge 4', # 'Office', 'Office Lamp 1A', 'Office Lamp 1B', 'Office Lamp 2A', 'Office Lamp 2B', # 'Bedroom 1', 'Bedroom 2' ] print('SetBulbXY') # command-line argument parser parser = argparse.ArgumentParser( prog = 'SetBulbXY', prefix_chars = '-/', description = """This program assigns settings to a list of bulbs (list is currently coded into the .py file).""") parser.add_argument('-v', '--verbose', help='Increase output verbosity', action="store_true") parser.add_argument('-xy', help='An XY pair to define the bulb color (0.0-1.0, 0.0-1.0)', type=float, nargs=2, default=[0.5, 0.5]) parser.add_argument('-t', '--timing', help='Set bulb transition time (seconds)', type=float, default=0) parser.add_argument('-b', '--brightness', help='Set bulb brightness (0 - 254)', type=int, default=254) # TODO: add option to specify bulb names # TODO: add option to specify light IDs # TODO: add option to print list of bulb name/ID combos # TODO: add option to print list of 'legal' named colors (green, red, energize) # TODO: add option to specify colors as names # TODO: add option to specify bridge IP args = parser.parse_args() x, y = args.xy[0], args.xy[1] transitiontime = int(args.timing * 10) # API uses 10ths of seconds bri = args.brightness b = Bridge() lights = b.get_light_objects('name') light_ids_in_play = [] for name in lights_in_play: light_ids_in_play.append(int(b.get_light_id_by_name(name))) if args.verbose: print('Verbosity set to ON') print('Bulbs to be set: ' + str(light_ids_in_play)) print('XY color set to X = {0}, Y = {0}'.format(x, y)) print('Transition speed set to ' + str(abs(args.timing)) + ' seconds.') print('Brightness set to ' + str(args.brightness)) # issue commands via the hub command = {'on' : True, 'transitiontime' : transitiontime, 'xy' : [x, y], 'bri' : bri} result = b.set_light(light_ids_in_play, command) print('-- lights set, exiting program --')
def ams_sethuecolor(rBulbNumber, rColor, rBlink): # Usage ams_sethuecolor(1,"blue",0) # Colors Supported: off, white, red, green, purple, pink, blue, yellow b = Bridge(myHueIP) lights = b.get_light_objects('id') # Moved off setting above light turn on so that the bulb does not # flicker if it is off and another off command comes across if rColor == "off": lights[rBulbNumber].on = False else: if (lights[rBulbNumber].on == False): lights[rBulbNumber].on = True if rColor == "white": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 14922 lights[rBulbNumber].saturation = 144 lights[rBulbNumber].xy = [0.4595, 0.4105] if rColor == "white50": lights[rBulbNumber].brightness = 125 lights[rBulbNumber].hue = 14922 lights[rBulbNumber].saturation = 144 lights[rBulbNumber].xy = [0.4595, 0.4105] if rColor == "red": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 49746 lights[rBulbNumber].saturation = 235 lights[rBulbNumber].xy = [0.6449, 0.0329] if rColor == "purple": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 46033 lights[rBulbNumber].saturation = 228 lights[rBulbNumber].xy = [0.2336, 0.1129] if rColor == "pink": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 47793 lights[rBulbNumber].saturation = 211 lights[rBulbNumber].xy = [0.3627, 0.1807] if rColor == "yellow": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 19886 lights[rBulbNumber].saturation = 254 lights[rBulbNumber].xy = [0.4304, 0.5023] if rColor == "blue": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 47108 lights[rBulbNumber].saturation = 254 lights[rBulbNumber].xy = [0.167, 0.04] if rColor == "green": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 23543 lights[rBulbNumber].saturation = 254 lights[rBulbNumber].xy = [0.3919, 0.484]
class AutoHomeHue: hue = None def __init__(self): self.hue = Bridge(ip='10.90.0.106', config_file_path="/var/lib/hue/hue.conf") def lights(self): return self.hue.lights def lights_name(self): return self.hue.get_light_objects('name') def is_locked(self, lamp): return os.path.isfile("/var/lib/hue/locks/{}".format(lamp.light_id)) def lock(self, lamp): open("/var/lib/hue/locks/{}".format(lamp.light_id), 'a').close() def unlock(self, lamp): os.remove("/var/lib/hue/locks/{}".format(lamp.light_id)) def brightness(self, lamp, value, time=100): lamp.on = True self.hue.set_light(lamp.light_id, 'bri', value, transitiontime=time) def color(self, lamp, hue=None, sat=None, xy=None): lamp.on = True if hue: lamp.hue = hue if sat: lamp.sat = sat if xy: lamp.xy = xy def time_based_white(self, light): if not self.hue.get_light(light.name, 'on'): return False if not self.hue.get_light(light.name, 'reachable'): return False hour = datetime.datetime.now().hour # Be nice, show a nice warm light # between 00:00 - 08:00 if hour < 8: hour = 24 ct = 154 + ((500-154)/24) * hour if light.light_id != 13 and light.colortemp != ct: self.hue.set_light(light.name, 'ct', ct) return True return False
def initHue(): global pbridge, v_things, lights, contexts # Connection with Hue Bridge while True: try: pbridge = Bridge(bridgeIP + ":" + bridgePort, config_file_path=".huecfg") break except Exception as ex: print(ex) time.sleep(5) continue # If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single time) i = 1 while True: print("Connection attempt with Hue bridge n." + str(i)) try: print("Hue bridge connection attempt..." + str(i)) pbridge.connect() if pbridge.username == None: time.sleep(5) i += 1 continue print("Hue bridge connected...") break except Exception as ex: print(ex) time.sleep(5) i += 1 continue # Get connected lights and builds lights = pbridge.get_light_objects('id') v_things = dict() for light_id in lights: tid = "light" + str(light_id) light = lights[light_id] v_thing_ID = thing_visor_ID + "/" + tid description = light.type label = light.name id_LD = "urn:ngsi-ld:" + v_thing_ID.replace("/", ":") v_things[id_LD] = { "vThing": { "label": label, "id": v_thing_ID, "description": description, "type": "actuator" }, "light_id": light_id, "ld_type": description, "topic": v_thing_prefix + "/" + v_thing_ID }
class LightController: def __init__(self, bridgeAddress): self.bridge = Bridge(bridgeAddress) self.lights = self.bridge.get_light_objects('name') self.converter = Converter() def setLight(self, light, r, g, b): try: xy = self.converter.rgb_to_xy(r, g, b) except ZeroDivisionError: xy = [1 / 3, 1 / 3] finally: self.lights[light].xy = xy
def main(): bridge = Bridge(BRIDGE_IP) bridge.connect() # Get the bridge state (This returns the full dictionary that you can explore) bridge.get_api() lights = bridge.get_light_objects('id') is_on = True while True: for light_id in LIGHTS: print('turning {} {}'.format(light_id, is_on)) lights[light_id].on = is_on is_on = not is_on time.sleep(2)
def hue_connect(): not_connected = True while (not_connected): try: bridge = Bridge('4908hue.eecs.umich.edu') bridge.connect() not_connected = False except: print( "\nGo push the button on the hub to authorize this program. I'll wait.\n" ) raw_input("Hit enter when you're done. ") all_lights = bridge.get_light_objects() return all_lights
def lights(message): b = Bridge(settings.HUE_BRIDGE_IP, username=settings.HUE_USERNAME) # If the app is not registered and the button is not pressed, press the # button and call connect() (this only needs to be run a single time) lights = b.get_light_objects('id') light_status = { light.name: cmn.lightbool(light.on) for light in lights.values() } res = cmn.codeblock( cmn.convert_to_table(light_status, headers=["Light", "Status"])) message.reply(res)
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') if self.lightsOn(lights) == True: bridge.set_light([4, 6], 'on', False) print('OFF') else: bridge.set_light([4, 6], 'on', True) bridge.set_light([4, 6], 'xy', [0.3227, 0.329]) bridge.set_light([4, 6], 'bri', 160) print('ON')
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') print(lights) if self.lightsOn(lights) == True: bridge.set_light([1,2,3,5], 'on', False) print('OFF') else: bridge.set_light([1,2,3,5], 'on', True) bridge.set_light([1,2,3,5], 'xy', [0.3227,0.329]) bridge.set_light([1,2,3,5], 'bri', 160) print('ON')
def main(self): default_temp = 366 ideal_temp = 240 # Enter the desired colour temp here. bridge_ip = '192.168.86.22' # Enter bridge IP here. room_name = 'Upstairs' b = Bridge(bridge_ip) # If running for the first time, press button on bridge and run with b.connect() uncommented b.connect() lights = b.get_light_objects() while True: for light in lights: if room_name in str(light.name): if light.on: if light.colortemp == default_temp: print('Fixing: ', light.name) light.colortemp = ideal_temp time.sleep(0.5)
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] hyperionPath = config["hyperionPath"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') if self.lightsOn(lights) == True: bridge.set_light([1, 2, 3, 5], 'on', False) print('OFF') else: bridge.set_light([1, 2, 3, 5], 'on', True) bridge.set_light([1, 2, 3, 5], 'xy', [0.139, 0.081]) bridge.set_light([1, 2], 'bri', 5) bridge.set_light([3, 5], 'bri', 100) subprocess.call(hyperionPath, shell=True) print('ON')
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] hyperionPath = config["hyperionPath"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') if self.lightsOn(lights) == True: bridge.set_light([1,2,3,5], 'on', False) print('OFF') else: bridge.set_light([1,2,3,5], 'on', True) bridge.set_light([1,2,3,5], 'xy', [0.139,0.081]) bridge.set_light([1,2], 'bri', 5) bridge.set_light([3,5], 'bri', 100) subprocess.call(hyperionPath, shell=True) print('ON')
class HueBulbSource(PollingSource): def __init__(self): super(HueBulbSource, self).__init__() self.bridge_addr = self.params['bridge_addr'] self.bulb_name = str(self.params['bulb_name']) self.poll_rate_secs = self.params[ 'poll_rate'] if 'poll_rate' in self.params else 2 self.bridge = Bridge(self.bridge_addr) light_objects_dict = self.bridge.get_light_objects('name') try: self.bulb = light_objects_dict[self.bulb_name] except KeyError: print( "Unknown bulb name. Here is the list of available bulbs at bridge " + self.bridge_addr + ":") print(light_objects_dict.keys()) # self.bulb_id = self.bulb.light_id self.start_polling( ) #must call begin polling at end of polling source init function def poll(self): state = {'bridge': self.bridge_addr, 'name': self.bulb_name} state['on'] = self.bulb.on state['hue'] = self.bulb.hue state['saturation'] = self.bulb.saturation state['brightness'] = self.bulb.brightness state['transitiontime'] = self.bulb.transitiontime state['colormode'] = self.bulb.colormode state['xy'] = self.bulb.xy state['alert'] = self.bulb.alert state['transitiontime'] = self.bulb.transitiontime try: state['colortemp'] = self.bulb.colortemp except KeyError: pass # lightstrips have no colortemp msg = state msg["type"] = "status" self.send(msg) return self.poll_rate_secs
class HueController: def __init__(self): self.name = "Hue Controller Object" self.b = Bridge(ip="10.0.1.16", username="******") # self.bri = 254 self.command = {'transitiontime': 100, 'on': True, 'bri': 127} self.lights = self.b.get_light_objects() try: self.b.connect() except Exception as e: print(e) def randomize(self): # for light in self.lights: # light.brightness = 113 # light.xy = [random.random(), random.random()] for i in range(1, 100): print(i) for light in self.lights: light.brightness = random.randint(1, 254) light.xy = [random.random(), random.random()] # sleep(0.50) def state(self, state=None): if state == 'on': print("set lights on") # self.b.set_light( [1, 2, 3], 'on', True) self.b.set_light(3, self.command) elif state == 'off': print("Set lights OFF") self.b.set_light([1, 2, 3], 'on', False) else: print("Dont understand")
class HueController: def __init__(self): self.name = "Hue Controller Object" self.b = Bridge(ip="10.0.1.16", username="******") # self.bri = 254 self.command = {"transitiontime": 100, "on": True, "bri": 127} self.lights = self.b.get_light_objects() try: self.b.connect() except Exception as e: print(e) def randomize(self): # for light in self.lights: # light.brightness = 113 # light.xy = [random.random(), random.random()] for i in range(1, 100): print(i) for light in self.lights: light.brightness = random.randint(1, 254) light.xy = [random.random(), random.random()] # sleep(0.50) def state(self, state=None): if state == "on": print("set lights on") # self.b.set_light( [1, 2, 3], 'on', True) self.b.set_light(3, self.command) elif state == "off": print("Set lights OFF") self.b.set_light([1, 2, 3], "on", False) else: print("Dont understand")
class my_hue(object): def __init__(self): self.b = Bridge('192.168.1.53') # Enter bridge IP here. #print b.get_api() #If running for the first time, press button on bridge and run with b.connect() uncommented #self.b.connect() self.lights = self.b.get_light_objects() print self.lights def set(self, name, **kwargs): for key, value in kwargs.iteritems(): for light in self.lights: if name == 'all' or light.name == name: setattr(light,key,value) def on(self, name='all'): self.set(name,on=True) def off(self, name='all'): self.set(name,on=False) def status(self,name='all'): status = [] for light in self.lights: if light.name == name: return light.on else: status.append(light.on) if all(status): return True if not any(status): return False else: return 'unknown' def fade_in(self,name='all'): self.set(name,on=True,brightness=0) for i in range(0,255): self.set(name,brightness=i) time.sleep(0.1)
class HueController(Resource): def __init__(self): self._BRIDGE_IP = "10.1.1.20" self._bridge = Bridge(self._BRIDGE_IP) self._lights = self._bridge.get_light_objects('name') def __hex2rgb(self, hex): return tuple(int(hex[i:i + 2], 16) for i in (0, 2, 4)) def _execute_recipe(self, light, recipe): if light in self._lights: l = self._lights[light] l.on = recipe["on"] l.brightness = recipe["brightness"] or l.brightness # set colour r = recipe['rgb'] if recipe['rgb'] is not None else None if r is not None: rgb = self.__hex2rgb(r) h, s, v = colorsys.rgb_to_hsv(*rgb) l.hue = h * 65535 l.sat = s * 255 l.bri = v
def find_a_light(): """Finds an appropriate light and returns it.""" hue = Bridge('192.168.1.11') # If running for the first time: # press button on bridge and run with b.connect() uncommented # b.connect() lights = hue.get_light_objects('name') # reachable is supposed to be an option but isn't..? # if lights['Bedroom ceiling'].reachable: if (hue.get_light('Bedroom ceiling')['state']['reachable'] and hue.get_light('Bedroom ceiling')['state']['on']): alert_light = lights['Bedroom ceiling'] elif (hue.get_light('Bedroom bed')['state']['reachable'] and hue.get_light('Bedroom bed')['state']['on']): alert_light = lights['Bedroom bed'] elif hue.get_light('Bedroom desk')['state']['reachable']: alert_light = lights['Bedroom desk'] return alert_light
# Load some config. The hue_config.json must contain a username that's whitelisted # on the specified bridge. See https://github.com/studioimaginaire/phue this_dir = os.path.dirname(os.path.realpath(__file__)) hue_config_file_path = os.path.join(this_dir, 'hue_config.json') nitelite_config_path = os.path.join(this_dir, 'nitelite.yml') with open(hue_config_file_path, 'r') as f: hue_config = json.loads(f.read()) with open(nitelite_config_path, 'r') as f: nitelite_config = yaml.safe_load(f.read()) bridge = Bridge(hue_config['hue']['address'], config_file_path=hue_config_file_path) # Use the phue API to get a dictionary with the light id as the key lights = bridge.get_light_objects('id') def set_state(state_name): """ Apply each property found in the named state. States are defined for each light in nitelite.yml. """ # For every light defined in nitelite.yml... for light_config in nitelite_config: # ...get the Hue object we are going to operate on... hue_light = lights[light_config['id']] # ...and the dict of properties that we are going to apply to it. desired_state = light_config[state_name] # Now set 'em all.
def main(): import random as random random.seed() from time import sleep from time import time import re import sys from phue import Bridge # b = Bridge() b = Bridge('192.168.1.110') # b.connect() # command-line argument parser import argparse parser = argparse.ArgumentParser( prog = 'ColorCycle', prefix_chars = '-/', description = """This program takes a series of color and brightness inputs and changes bulb charateristics accordingly. It assumes that lights that are on will be used. Lights are tested for 'on' status every transition.""") timinggroup = parser.add_mutually_exclusive_group() timinggroup.add_argument('-t', '--timing', help='Set tempo in seconds, decimal values allowed; positive values produce gradual changes, ' + 'negative values produce flash transitions', type=float) timinggroup.add_argument('-r', '--bpm', '--rate', help='Set tempo as beats per minute, decimal values allowed; positive values produce gradual changes, ' + 'negative values produce flash transitions', type=float) parser.add_argument('-w', '--wait', help='Set wait time separately from transition time (bpm or seconds)', type=float, default=0.0) parser.add_argument('-c', '--hues', '--colors', help='A list of color values the lights will cycle through (0 - 65535)', type=int, nargs='+', default=[-1]) parser.add_argument('-b', '--brightness', help='Set bulb brightness (0 - 254, can be a list)', type=int, nargs='+', default=[254]) parser.add_argument('-s', '--saturation', help='Set bulb color saturation (0 - 254)', type=int, nargs='+', default=[254]) parser.add_argument('-m', '--monochrome', help='Cycle through color list with all lights the same color', action="store_true", default=False) parser.add_argument('-o', '--ordered', help='Cycle through color list in order (do not randomize); apparent ' + 'color "chase" order will be in reverse bulb order', action="store_true", default=False) selectiongroup = parser.add_mutually_exclusive_group() selectiongroup.add_argument('-n', '--names', help='A list of bulb names to cycle through; regex OK; bulbs will be turned on', nargs='+') selectiongroup.add_argument('-i', '--ids', help='A list of bulb id values to cycle through; bulbs will be turned on', type=int, nargs='+') selectiongroup.add_argument('-nx', '--excludednames', help='Cycle through all bulbs except these; regex OK; bulbs will be turned on', nargs='+') selectiongroup.add_argument('-ix', '--excludedids', help='Cycle through all bulbs except these id values; bulbs will be turned on', type=int, nargs='+') parser.add_argument('-d', '--duration', help='Duration for which the pattern should repeat (minutes)', type=float) #, default = 0.0) parser.add_argument('-v', '--verbose', help='Increase output verbosity', action="store_true") parser.add_argument('-x', '--exit', help='Exit by turning bulbs off', action="store_true") # TODO: add option to print list of bulb name/ID combos (with additional option to sort by ID# or name? -d, -di, -dn for 'directory, by id, by name'?) # TODO: add option to print list of 'legal' named colors (green, red, energize) # TODO: add option to specify colors as names # TODO: consider using the data from this page to write color names corresponding to hues: http://en.wikipedia.org/wiki/List_of_colors_(compact) # TODO: add option to specify bridge IP # TODO: design a GUI with checkboxes, etc. for options (Kivy?) # TODO: add option to specify colors (and more?) as ranges, e.g. hues = [0-1000, 5000-6800, 40000-41000] would assign three colors chosen from those ranges (-cr, -br, -sr, -wr, -tr) # TODO: add an option that increases hue/brightness/etc. by an increment of X for each time Y -- this is a maybe # TODO: set up a series of testing comand lines (e.g. 0, 1, 5 bulbs, 0, 1, 5 colors, bad parameter values) args = parser.parse_args() if args.verbose: print('Verbosity set to ON') if args.timing is not None: if args.timing >= 0: print('Transition timing is set to ' + str(abs(args.timing)) + ' seconds with a wait time of ' + str(abs(args.wait)) + ' seconds') if args.timing < 0 and args.wait > 0.0: print('Transition timing is set to 0.0 seconds with a wait time of ' + str(abs(args.wait) + abs(args.timing)) + ' seconds') if args.timing == 0: print('Lights will be set once and program will exit') if args.timing >= 0: print('Transitions will be gradual') else: print('Transitions will be instant') if args.bpm is not None: # For bpm time specification, assume that sum(bpm, wait) = intended total bpm. # So for bpm=10 and wait=20, transitions should begin at a rate of 30 bpm (every 2.0 seconds) netbpm = abs(args.bpm) + abs(args.wait) print('Timing is set to ' + str(netbpm) + ' bpm with a transition/wait split of ' + str(round(abs(args.bpm) / netbpm, 0)) + '/' + str(round(abs(args.wait) / netbpm, 0)) + '%') if args.bpm == 0: print('Lights will be set once and program will exit') if args.bpm >= 0: print('Transitions will be gradual') else: print('Transitions will be instant') print('Hues that will be cycled through: ' + str(args.hues)) if args.ids is not None: print('Bulbs that will be cycled through: ' + str(args.ids)) if args.ordered: print('Colors and lamps will be cycled in the specified order') else: print('Colors and lamps will be cycled in random order') print('Color saturation set to: ' + str(args.saturation)) print('Brightness set to: ' + str(args.brightness)) if args.duration is not None: print('Pattern will be repeated for ' + str(args.duration) + ' minute(s)') # Convert timing/frequency to integer tenths of seconds (transitiontime). # Wait times are handled by sleep(), so wait time is in actual seconds. if args.timing is not None: # Frequency is in seconds if args.timing >= 0: transitiontime = int(round(args.timing * 10, 0)) waittime = args.wait else: # use negative timing to specify flash transitions transitiontime = 0 waittime = -args.timing + args.wait # This arrangement allows a benign but nonsensical combination # (e.g. flash transition of -10 seconds with a wait of 5 seconds). # If a negative timing and a wait time are specified, # the timing and wait times will be added together. # This way, flipping a negative sign does not change the # observed rate of changes. if args.bpm is not None: # Frequency is in bpm; netbpm is the sum of transition and wait values if args.bpm >= 0: transitiontime = int(round(60 / (args.bpm / netbpm) * 10, 0)) waittime = 60 / (args.wait / netbpm) else: # use negative bpm to specify flash transitions transitiontime = 0 waittime = 60 / netbpm if args.timing is None and args.bpm is None: transitiontime = 0 waittime = 0 # Get light names and ID numbers, and choose which lights will be active # Note: Bulb changes are transmitted using ID number. lights_in_play = b.get_light_objects('name') light_ids_in_play = [] for name in lights_in_play: light_ids_in_play.append(int(b.get_light_id_by_name(name))) # Use a selection method: ID #s, names, exclude by #, exclude by name, default = all bulbs if args.ids is not None: # Set bulbs using ID numbers # Filter lights in use so that only specified bulbs are used. # Turn specified bulbs on. light_ids_in_play = [id_ for id_ in light_ids_in_play if id_ in args.ids] b.set_light(light_ids_in_play, 'on', True) lights_in_play = [] for id_ in light_ids_in_play: lights_in_play.append(b.get_light(id_, 'name')) elif args.excludedids is not None: # Exclude bulbs using ID numbers # Filter lights in use so that only specified bulbs are used. # Turn specified bulbs on. light_ids_in_play = [id_ for id_ in light_ids_in_play if id_ not in args.excludedids] b.set_light(light_ids_in_play, 'on', True) lights_in_play = [] for id_ in light_ids_in_play: lights_in_play.append(b.get_light(id_, 'name')) elif args.names is not None: # Set bulbs using names # Filter lights in use so that only specified bulbs are used. # Turn specified bulbs on. regex = re.compile('|'.join(args.names), re.IGNORECASE) # names joined with OR '|' connector # Usage note: '.*' is equivalent to DOS '*', '.' is equivalent to DOS '?' lights_in_play = [a for a in lights_in_play if re.search(regex, a)] light_ids_in_play = [] for name in lights_in_play: light_ids_in_play.append(int(b.get_light_id_by_name(name))) b.set_light(light_ids_in_play, 'on', True) elif args.excludednames is not None: # Exclude bulbs using names # Filter lights in use so that only specified bulbs are used. # Turn specified bulbs on. regex = re.compile('|'.join(args.excludednames), re.IGNORECASE) # names joined with OR '|' connector # Usage note: '.*' is equivalent to DOS '*', '.' is equivalent to DOS '?' lights_in_play = [a for a in lights_in_play if not re.search(regex, a)] light_ids_in_play = [] for name in lights_in_play: light_ids_in_play.append(int(b.get_light_id_by_name(name))) b.set_light(light_ids_in_play, 'on', True) else: pass # All lights will be adjusted as specified, but will not be switched on # randomly assign colors to lights and issue the commands via the hub try: if args.monochrome: # Set all bulbs to the same color; cycle through colors light_ids_on = [] huenum = -1 brinum = -1 satnum = -1 start = time() while True: loopstart = time() if args.duration is not None: if args.duration < (time() - start) / 60: break if args.ordered: # This results in each bulb moving through the parameter list in order. huenum = (huenum + 1) % len(args.hues) brinum = (brinum + 1) % len(args.brightness) satnum = (satnum + 1) % len(args.saturation) hue = args.hues[huenum] bri = args.brightness[brinum] sat = args.saturation[satnum] else: hue = random.choice(args.hues) bri = random.choice(args.brightness) sat = random.choice(args.saturation) hue_verbose = hue # used only for verbose printing if hue == -1: # flag for white sat = 0 # 0 to 254 hue = random.choice([i for i in args.hues if i >= 0]) # choose from non-white values if hue == -2: # flag for black (off) # get light 'on' status and build a list of lights that are on; build fresh every time for id_ in light_ids_in_play: if b.get_light(id_, 'on'): light_ids_on.append(id_) command = {'transitiontime' : transitiontime, 'on' : False} result = b.set_light(light_ids_in_play, command) else: # Set bulbs if len(light_ids_on) > 0: # If any bulbs are in the list, turn them on command = {'on' : True, 'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri} result = b.set_light(light_ids_on, command) else: # empty list command = {'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri} result = b.set_light(light_ids_in_play, command) if args.verbose: if len(light_ids_in_play) > 0: # print('Hue Bulb(s) ' + str(light_ids_in_play) + ' set to hue = ' + str(hue) + ', sat = ' + str(sat) + ', bri = ' + str(bri)) print('Bulb(s) {light_id} set to hue = {hue:>5}, sat = {sat:>3}, bri = {bri:>3}'.format(light_id=light_ids_in_play, hue=hue_verbose, sat=sat, bri=bri)) print('-- pass complete, waiting ' + str(transitiontime / 10 + waittime) + ' seconds --') if args.duration is not None: elapsed = time() - start print('-- ' + str(int(args.duration - elapsed/60)) + ' minutes ' + str(round(max((args.duration*60 - elapsed), 0) % 60, 1)) + ' seconds remaining --') if transitiontime + waittime == 0.0: if args.verbose: print('-- lights set, bpm = 0.0, exiting program --') break # end program else: loopelapsed = time() - loopstart sleep(max(transitiontime / 10 + waittime - loopelapsed, 0)) if len(args.hues) == 1 and len(args.brightness) == 1 and len(args.saturation) == 1: if args.verbose: print('-- only one color to cycle, exiting program --') # only one color, no reason to keep changing it break else: # Set bulbs to random colors; wait; repeat light_ids_on = [] huenum = -1 brinum = -1 satnum = -1 start = time() while True: loopstart = time() if args.duration is not None: if args.duration < (time() - start) / 60: break # sat = args.saturation # 0 to 254 if args.ordered: huenum = (huenum + 1) % len(args.hues) brinum = (brinum + 1) % len(args.brightness) satnum = (satnum + 1) % len(args.saturation) else: random.shuffle(light_ids_in_play) for light_index, light_id in enumerate(light_ids_in_play): if args.ordered: # Each bulb is assigned hues in the user-specified order. # The intial hue is set by cycling through the color list in order. # Visual note: the apparent "chase" direction of colors is the reverse # of the order of lights. hue = args.hues[(light_index + huenum) % len(args.hues)] bri = args.brightness[(light_index + brinum) % len(args.brightness)] sat = args.saturation[(light_index + satnum) % len(args.saturation)] else: hue = random.choice(args.hues) bri = random.choice(args.brightness) sat = random.choice(args.saturation) hue_verbose = hue # used only for verbose printing if hue == -1: # flag for white sat = 0 # 0 to 254 if len([i for i in args.hues if i >= 0]) > 0: hue = random.choice([i for i in args.hues if i >= 0]) # choose from non-white/black values else: hue = 0 # no colors available to choose, assume red elif hue == -2: # flag for black light_ids_on.append(light_id) hue = random.choice([i for i in args.hues if i >= 0]) # choose from non-white/black values command = {'on' : False, 'transitiontime' : transitiontime} if hue_verbose != -2: # if not black # Set bulbs if light_id in light_ids_on: command = {'on' : True, 'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri} light_ids_on.remove(light_id) else: command = {'transitiontime' : transitiontime, 'hue' : hue, 'sat' : sat, 'bri' : bri} result = b.set_light(light_id, command) if args.verbose: if light_id in light_ids_in_play: print('Bulb {light_id:>2} set to hue = {hue:>5}, sat = {sat:>3}, bri = {bri:>3}'.format(light_id=light_id, hue=hue_verbose, sat=sat, bri=bri)) sat = args.saturation # 0 to 254 if args.verbose: print('-- pass complete, waiting ' + str(transitiontime / 10 + waittime) + ' seconds --') if args.duration is not None: elapsed = time() - start # the following command could use some analysis for the max portion. # the following command, with max removed, will result in an incorrect "59.9 seconds remaining" message at the end # c:\python32\python ColorCycle.py -v -t 3.0 -b 1 -c 0 500 1000 1500 2000 63000 63500 64000 64500 65000 65535 -i10 12 15 19 -d 0.2 -s 254 250 245 240 -x # print('-- ' + str(int(args.duration - elapsed/60)) + ' minutes ' + str(round(max((args.duration*60 - elapsed), 0) % 60, 1)) + ' seconds remaining --') if transitiontime + waittime == 0.0: if args.verbose: print('-- lights set, bpm = 0.0, exiting program --') break # end program else: loopelapsed = time() - loopstart len_text = 0 while (transitiontime / 10 + waittime - loopelapsed) > 0: loopelapsed = time() - loopstart elapsed = time() - start len_text = underwrite('-- ' + str(int(args.duration - elapsed/60)) + ' minutes ' + str(round(max((args.duration*60 - elapsed), 0) % 60, 1)) + ' seconds remaining --', len_text) sleep(min(1, max(0, transitiontime / 10 + waittime - loopelapsed))) if args.exit: command = {'transitiontime' : transitiontime, 'on' : False} result = b.set_light(light_ids_in_play, command) print('-- lights off, exiting program --') except KeyboardInterrupt: # Quit if we get a CTRL-C from the user if args.verbose: print('-- CTRL-C received, exiting program --') sys.exit()
def main(): parser = argparse.ArgumentParser(description="Hue to Yun bridge") parser.add_argument("-b", "--bridge", help="Hue bridge") parser.add_argument("lights", nargs="+") args = parser.parse_args() if args.bridge is None: info = urllib.urlopen('http://www.meethue.com/api/nupnp').read() info = json.loads(info) if len(info) > 0: args.bridge = info[0][u'internalipaddress'] else: log("ERROR: Could not auto-detect Hue bridge IP\n") log(" Please specify --bridge manually\n") out.close() sys.exit(1) bridge = None while bridge == None: try: bridge = Bridge(args.bridge) except phue.PhueRegistrationException as e: sleep(5) lights = [] log("Lights:\n") for name, light in bridge.get_light_objects('name').iteritems(): if name in args.lights: log(" - Found %s\n"%(name)) lights.append(HueBulb(name, light)) try: while True: rlist, wlist, elist = select.select([sys.stdin], [], [], 0) i = None while rlist: i = raw_input() i = i.strip() log("Got %s\n" % (repr(i)) ) rlist, wlist, elist = select.select([sys.stdin], [], [], 0) if i is not None: log("Processing %s\n" % (repr(i)) ) if i == "T": log("Toggle\n") # toggle normal = True for light in lights: if not light.is_normal(): normal = False for light in lights: if normal: light.off() else: light.reset() else: try: v = int(i) if v < 0: v = 0 if v > 255: v = 255 log("%d\n"%(v)) for light in lights: light.brightness(v) except: pass for light in lights: light.poll() # chill out man sleep(0.33) except KeyboardInterrupt: # try to exit quietly pass finally: out.close()
#!/usr/bin/python # light.py Landing on|off import sys from phue import Bridge b = Bridge('192.168.1.73') b.connect() lights = b.get_light_objects('name') if sys.argv[1] not in lights: print 'No light called %s' % sys.argv[1] print ' Known lights: %s' % ' '.join(lights.keys()) sys.exit(1) light = lights[sys.argv[1]] if sys.argv[2] == 'on': light.on = True elif sys.argv[2] == 'off': light.on = False else: print 'Usage: light.py <lightname> on|off (not %s)' % sys.argv[2] print ' Known lights: %s' % ' '.join(lights.keys()) sys.exit(1)
from apscheduler.scheduler import Scheduler import logging # need to log to stdout things from apscheduler #start logging for apscheduler logging.basicConfig() ''' Main Script- Set Light Alarms ''' config = ConfigObj("backendhue.conf") hueaddress = config['BridgeIP'] b = Bridge(ip=hueaddress) # Enter bridge IP here. # Get a dictionary with the light name as the key; configuration file is unneeded at this stage. it is for future developments light_names = b.get_light_objects('name') # light_names is now the library of lights and ID's lights = b.get_light_objects('id') #function to blackout lights def blackout(): for light in light_names: light_names[light].on = False # Begin to setup window root = Tk() root.title("Alarm Settings") root.grid() horizontal_frame = Frame(root) horizontal_frame.pack()
from phue import Bridge ''' This example creates 3 sliders for the first 3 lights and shows the name of the light under each slider. There is also a checkbox to toggle the light. ''' b = Bridge() # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented #b.connect() root = Tk() lights = b.get_light_objects('id') light_selection = [] def curry(fn, *cargs, **ckwargs): def call_fn(*fargs, **fkwargs): d = ckwargs.copy() d.update(fkwargs) return fn(*(cargs + fargs), **d) return call_fn def hue_command(x): if len(light_selection) > 0: b.set_light(light_selection, 'hue', int(x)) def sat_command(x): if len(light_selection) > 0:
sys.exit() elif opt in ("-l", "--lid"): LightId=int(arg) elif opt in ("-h", "--hue"): LightHue=int(arg) elif opt in ("-i", "--int"): LightIntensity=int(arg) elif opt in ("-s", "--sat"): LightSaturation=int(arg) elif opt in ("-d", "--del"): LightDelay=int(arg) b=Bridge('192.168.44.171') # Get a flat list of the light objects lights=b.get_light_objects('list') light1=lights[0] light2=lights[1] hue1=randint(1,65534) hue2=randint(1,65534) light1.on=False light2.on=False light1.on=True light2.on=True sleep(1) light1.transitiontime=1 light2.transitiontime=1 light1.brightness=LightIntensity light2.brightness=LightIntensity
from phue import Bridge import random b = Bridge('10.10.0.115') # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented #b.connect() """ lights = b.get_light_objects() for light in lights: light.brightness = 254 light.xy = [random.random(),random.random()] """ lamp1, lamp2, lamp3 = b.get_light_objects() """ lamp1.brightness = 254 lamp2.brightness = 254 lamp3.brightness = 254 """ normal = [1,1] red = [0.75,0.25] purple = [0.45,0.25] skyblue = [0.15,0.25] blue = [0.15,0.05] yellow = [0.45,0.51] green = [0.09,0.81] lightgreen = [0.3,0.5]
This example creates 3 sliders for the first 3 lights and shows the name of the light under each slider. There is also a checkbox to toggle the light. """ b = Bridge() # Enter bridge IP here. # If running for the first time, press button on bridge and run with b.connect() uncommented # b.connect() root = Tk() horizontal_frame = Frame(root) horizontal_frame.pack() lights = b.get_light_objects("id") for light_id in lights: channel_frame = Frame(horizontal_frame) channel_frame.pack(side=LEFT) scale_command = lambda x, light_id=light_id: b.set_light(light_id, {"bri": int(x), "transitiontime": 1}) scale = Scale(channel_frame, from_=254, to=0, command=scale_command, length=200, showvalue=0) scale.set(b.get_light(light_id, "bri")) scale.pack() button_var = BooleanVar() button_var.set(b.get_light(light_id, "on")) button_command = lambda button_var=button_var, light_id=light_id: b.set_light(light_id, "on", button_var.get()) button = Checkbutton(channel_frame, variable=button_var, command=button_command) button.pack()
class Occupancy(object): """This is to turn the Hue light on in the master bath when the PIR sensor detects motion""" BULB_NUMBER=3 def __init__(self,bridge_ip,duration=180): self._Timer_thread = None self.bridge_ip = bridge_ip self._bridge_connect() self._duration = duration self._button_override = False def _bridge_connect(self): self._b = Bridge(self.bridge_ip) # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented self._b.connect() def _hue_for_given_time(self): """This sets the color hue of the light for the time of day""" hour = datetime.datetime.now().hour if hour >= 23 or hour <= 7: return 47125 #hue blue elif hour >= 8 and hour <= 22: return 14910 #hue white def _sat_for_given_time(self): """This sets the saturation of the light for the time of day""" hour = datetime.datetime.now().hour if hour >= 23 or hour <= 7: return 253 #sat elif hour >= 8 and hour <= 22: return 144 #sat def _bri_for_given_time(self): """This sets the brightness of the light for the time of day""" hour = datetime.datetime.now().hour if hour >= 23 or hour <=7: return 7 #bri 5 percent elif hour >= 8 and hour <= 22: return 254 #bri 100 percent def trigger(self, state): """Handles the trigger event of the PIR sensor""" if state == 1: if self._button_override == True: pass else: self.reset_counter() self.motion_on() def button(self, state): """Handles the button press event""" if state == 1: self._button_override = True self.reset_counter(600)#seconds self.motion_on() def reset_counter(self, duration=None): """Resets timer if motion is detected""" if duration is None: duration = self._duration if self._Timer_thread is not None: self._Timer_thread.cancel() self._Timer_thread=None self._Timer_thread = threading.Timer(duration, self.motion_off) self._Timer_thread.start() def motion_on(self): """Sets light brightness and color according to button press or PIR state""" lights = self._b.get_light_objects() if self._button_override == True: self._b.set_light(self.BULB_NUMBER, 'on', True, transitiontime=20) time.sleep(.02) self._b.set_light(self.BULB_NUMBER, 'bri', 254 , transitiontime=20) time.sleep(.02) self._b.set_light(self.BULB_NUMBER, 'hue', 14910 , transitiontime=20) time.sleep(.02) self._b.set_light(self.BULB_NUMBER, 'sat', 144 , transitiontime=20) time.sleep(.02) else: self._b.set_light(self.BULB_NUMBER, 'on', True, transitiontime=20) time.sleep(.02) self._b.set_light(self.BULB_NUMBER, 'bri', self._bri_for_given_time(), transitiontime=20) time.sleep(.02) self._b.set_light(self.BULB_NUMBER, 'hue', self._hue_for_given_time(), transitiontime=20) time.sleep(.02) self._b.set_light(self.BULB_NUMBER, 'sat', self._sat_for_given_time(), transitiontime=20) time.sleep(.02) def motion_off(self): lights = self._b.get_light_objects() self._button_override = False self._b.set_light(self.BULB_NUMBER, 'on', False, transitiontime=30)
last_state = None clicks = 0 realClicks = 0 # Import stuff for Hue Lifx from phue import Bridge ##The Hue Api import lifx ##The LIFX Api # Make Connections to and pool Hue / lifx # Create LIFX Connection xLights = lifx.Lifx() #Create Hue Connection b = Bridge('192.168.0.45') hLights = b.get_light_objects() hGroups = b.get_group() #Do this stuff, for like, forever... while True: delta = encoder.get_delta() if delta!=0: # print ("rotate %d " % delta) clicks += delta # print (clicks) # print (clicks % 4) if clicks % 4 == 0: # print ("DERP, THAT'S ONE CLICK REALLY!!") print (clicks / 4)
class DriverHue(DriverBase): def __init__(self, num, ip, nameMap=None): super(DriverHue, self).__init__(num) if nameMap and len(nameMap) != self.numLEDs: raise ValueError( "nameMap must have the same number of entries as the number of LEDs.") self._bridge = Bridge(ip) self._bridge.connect() self._transitionTime = 0 self._brightness = 254 if nameMap: self._lights = self._bridge.get_light_objects('name') self._ids = nameMap else: self._lights = self._bridge.get_light_objects('id') self._ids = [l for l in self._lights] if len(self._lights) < self.numLEDs: raise ValueError( "More LEDs were specified than there are available Hue lights.") self.setTransitionTime(0) # start with no transition time def setMasterBrightness(self, brightness): if brightness < 0 or brightness > 255: raise ValueError("Brightness value must be between 0 and 255") self._brightness = brightness return True def setTransitionTime(self, time): if time < 0.0 or time > 30.0: raise ValueError( "Transition time must be between 0.0 and 30.0 seconds.") self._transitionTime = int(time * 10) def _mapRange(self, value, minFrom, maxFrom, minTo, maxTo): return minTo + (maxTo - minTo) * ((value - minFrom) / (maxFrom - minFrom)) def _rgb2hs(self, rgb): r = rgb[0] / 255.0 g = rgb[1] / 255.0 b = rgb[2] / 255.0 h, s, v = colorsys.rgb_to_hsv(r, g, b) h = int(self._mapRange(h, 0.0, 1.0, 0, 65535)) s = int(self._mapRange(s, 0.0, 1.0, 0, 254)) return (h, s) def update(self, data): pixels = [tuple(data[(p * 3):(p * 3) + 3]) for p in range(len(data) / 3)] for i in range(len(self._ids)): h, s = self._rgb2hs(pixels[i]) bri = self._brightness if s == 0: bri = 0 cmd = {'on': s != 0, 'bri': bri, 'hue': h, 'saturation': s, 'transitiontime': self._transitionTime} self._bridge.set_light(self._ids[i], cmd)
# Lock the Lightpack so we can make changes lp.lock() else: lp = None ################################ pygame.init() pygame.fastevent.init() pygame.midi.init() event_get = pygame.fastevent.get event_post = pygame.fastevent.post input_id = pygame.midi.get_default_input_id() light = b.get_light_objects('name') [r, g, bl] = [0, 0, 0] colored_lights = [ 'living room 1', 'living room 2', 'living room 3', 'bedroom 1', 'bedroom 2' ] bnw_lights = [ 'dressing room', 'bathroom 1', 'bathroom 2', 'bathroom 3', 'bathroom 4', 'entryway 1' ] lightpack = ['lightpack'] lights = b.get_light_objects('id') f = 'weatherScenes.csv' #point it towards CSV
#!/usr/bin/python from AppKit import NSWorkspace from AppKit import NSWindow import Quartz.CoreGraphics as CG from time import sleep from phue import Bridge b = Bridge('YOUR.IP.ADDRESS.HERE') # Get a dictionary with individual light numbers as the key (1,2,3,etc.) lights = b.get_light_objects('id') # Get a dictionary with the each light's name as the key (Kitchen, Bedroom, etc.) light_names = b.get_light_objects('name') # Get a flat list of the light objects light_list = b.get_light_objects('list') # Will turn on all lights in system def all_on(): b.set_light(lights,'on',True) # Will turn off all lights in system def all_off(): b.set_light(lights,'on',False) is_on = 1 while True: windlst = CG.CGWindowListCopyWindowInfo(CG.kCGWindowListOptionAll, CG.kCGNullWindowID)