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 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 deskLampOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() bridge.set_light('Living Room Lamp', 'on', False) return 'Hi!'
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)
class HueDriver(Driver): def setup(self, cfg): self.b = Bridge(cfg['hue_bridge']) self.b.connect() self.b.get_api() self.lights = {} for l in self.b.lights: self.lights[l.name.replace(' ', '_')] = HueLight( l, self.report, l.name.replace(" ", "_")) self._log.info("lights: {0}".format(self.b.lights)) def write(self, uri, age, msg): """ Dispatch the write to the correct object """ if msg.XBOSIoTDeviceActuation is not None: l = msg.XBOSIoTDeviceActuation.light name = uri.split('/')[-1] self.lights[name].write(uri, age, msg) def read(self, requestid=None): """ Read all sub devices and have them publish """ for light in self.lights.values(): light.report(light.read())
def turn_lights_on(): b = Bridge('192.168.0.51') b.connect() b.get_api() command = {'hue': 25500, 'on': True} b.set_light(4, command) turn_music_on()
def bedroomLightOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() bridge.set_light('Bedroom', 'on', False) return 'Hi!'
def frontHallLampOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() bridge.set_light('Front Hall', 'on', False) return 'Hi!'
def turn_on_led(led_num): ni.ifaddresses('eth0') ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr'] b = Bridge('192.168.4.50') b.connect() b.get_api() b.set_light(led_num, 'on', True)
def allLightsOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() for light in bridge.lights: bridge.set_light(light.name, 'on', False) return 'Hi!'
def initHue(): b = Bridge('192.168.178.39') # Replace with the IP of your Hue Bridge b.connect() b.get_api() lights = b.lights print("Available lights:") for l in lights: print(l) return b
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)
def present(): b = Bridge('10.0.0.11', 'pi') b.connect() b.get_api() color = None r = requests.get( 'https://iswa.gsfc.nasa.gov/IswaSystemWebApp/DatabaseDataStreamServlet?format=JSON&resource=NOAA-KP&quantity=KP&duration=1' ) entries = r.json()[-26:] x = 0 y = 0 for i in entries: x += float(i['KP']) y += 1 mean = x / y # mean = 4 if (mean < 2): color = green elif (mean >= 2 and mean < 3): color = yellow elif (mean >= 3 and mean < 4): color = orange elif (mean >= 4): color = red temp = b.get_group(1) print("Cycle every " + str(_sleep / 60) + " min ------------------") print(" Changing color to: " + str(color)) print(" The average KP is: " + str(mean)) print(" Timestamps from " + str(entries[0]['timestamp']) + " to " + str(entries[-1]['timestamp'])) print(" Defaults are as: Bri: " + str(temp['action']['bri']) + " sat: " + str(temp['action']['sat']) + " hue: " + str(temp['action']['hue'])) b.set_group(1, 'bri', 0) b.set_group(1, 'bri', 0) time.sleep(2.5) b.set_group(1, 'sat', 255) b.set_group(1, 'hue', color) #Darken for i in range(0, flash_seq): b.set_group(1, 'bri', 255) # b.set_group(1, 'bri', 255, transitiontime=5) # On time.sleep(0.6) b.set_group(1, 'bri', 0) # b.set_group(1, 'bri', 0, transitiontime=5) # off time.sleep(0.6) b.set_group(1, 'bri', temp['action']['bri']) b.set_group(1, 'hue', temp['action']['hue']) b.set_group(1, 'sat', temp['action']['sat']) # Back on # b.set_group(1, 'bri', temp['action']['bri'], transitiontime=50) # b.set_group(1, 'hue', temp['action']['hue'], transitiontime=50) # b.set_group(1, 'sat', temp['action']['sat'], transitiontime=50) # Back on time.sleep(1)
def createConfig(self): created = False logger.warning('***********************Press the button on the Hue bridge*************************') while not created: b = Bridge(IP_BRIDGE) b.connect() # Get the bridge state (This returns the full dictionary that you can explore) b.get_api() if len(b.lights)>0: created=True HueCocotte().send_mail(EMAIL_SUBJECT, "Philips HUE connected") logger.warning("Bridge connected !") self.polling()
def get_office_lights(): ''' Gets the current state of my office lights so I know what values to plug in to presets. ''' from phue import Bridge b = Bridge(settings.HUE_BRIDGE) b.connect() b.get_api() light_index = 9 print b.get_light(light_index, 'on') print b.get_light(light_index, 'hue') print b.get_light(light_index, 'sat')
class HueControl: def __init__(self, IP): self.b = Bridge(IP) # 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) # self.b.connect() self.b.register_app() # Get the bridge state (This returns the full dictionary that you can explore) self.b.get_api() def flash_blubs(self): self.b.set_light(3, 'on', False) self.b.set_light(3, 'on', True) self.b.set_light(3, 'on', False) self.b.set_light(3, 'on', True)
class PhilipsHueController: def cinemaFadeDown(self): playsound.playsound("PATHTOFILE") print("dimming down lights") self.bridge.set_group(12, "bri", 0, transitiontime=100) time.sleep(7) print("turning off lights") self.bridge.set_group(12, "on", False) def __init__(self): self.bridge = Bridge("YOURIP") self.bridge.connect() self.bridge.get_api() self.cinemaFadeDown()
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)
class Lights: kitchenLights = [1, 2, 4, 7, 13] livingRoomLights = [ 3, 5, 6, 8, 14 ] diningRoomLights = [9, 10] hallwayRoomLights = [11] lightModes = { 'tv': [ 0, 30, 0, 0, 0], 'relax': [ 60, 130, 150, 30, 15], 'normal': [150, 200, 200, 50, 16], 'reading': [150, 200, 200, 50, 25], 'bright': [255, 255, 255, 200,30], 'makeup': [255, 155, 155, 50, 16], 'off': [ 0, 0, 0, 0, 0] } hueBridge = None def setTable( self, trigger ): urllib2.urlopen( config.iftttBase % ( trigger ) ).read() def connect(self ): self.hueBridge = Bridge(config.hueBridgeIP) self.hueBridge.connect() self.hueBridge.get_api() def setLight( self, light, brightness ): self.hueBridge.set_light( light, 'bri', brightness) def setSection( self, section, brightness ): for light in section: if brightness == 0: print "setting %d off" % ( light ) self.hueBridge.set_light( light, 'on', False) else: self.hueBridge.set_light( light, 'on', True) self.hueBridge.set_light( light, 'bri', brightness) def setLights_int( self, mode ): self.setTable( "table_%d" % ( self.lightModes[mode][4]) ) self.setSection( self.livingRoomLights, self.lightModes[mode][0] ) self.setSection( self.kitchenLights, self.lightModes[mode][1] ) self.setSection( self.diningRoomLights, self.lightModes[mode][2] ) self.setSection( self.hallwayRoomLights, self.lightModes[mode][3] ) def setLights( self, mode ): print "setting lights to: " + mode for i in range(1,3): self.setLights_int( mode ) time.sleep(1) if mode == 'makeup': urllib2.urlopen( config.iftttBase % ( "hallway_72" ) ).read()
class CommonHardwareHue(object): """ Class for interfacing with hue """ def __init__(self, ip_addr): self.hue_inst = Bridge(ip_addr, config_file_path='/mediakraken/phue/phue.config') # 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) self.hue_inst.connect() def com_hardware_hue_get_api(self): # Get the bridge state (This returns the full dictionary that you can explore) return self.hue_inst.get_api() def com_hardware_hue_get_lights(self): return self.com_hardware_hue_get_api()['lights'] def com_hardware_hue_light_info(self, light_num, status_type): # 'on' - wether on/off # 'name' - name of light return self.hue_inst.get_light(light_num, status_type) def com_hardware_hue_light_set(self, light_list, function_type='on', var_value=True): # You can also control multiple lamps by sending a list as lamp_id # 'on' on/off via bool # 'bri' 1-100 value for brightness self.hue_inst.set_light(light_list, function_type, var_value)
class HueControl(): def initBridge(self, ip): self.bridge = Bridge(ip) self.bridge.connect() self.bridge.get_api() def __init__(self, jarvis, hueBridgeIP): self.initBridge(hueBridgeIP) self.jarvis = jarvis def setHue(self, hueValue): """ Set Hue from 0 to 65280 """ self.bridge.set_light(2,'hue', hueValue) def setSaturation(self, satValue): """ Set Saturation from 0 to 254 """ self.bridge.set_light(2,'sat', hueValue) def setBrightness(self, briValue): """ Set brightness from 0 to 254 """ self.bridge.set_light(2,'bri', hueValue) def setCommand(self, command): self.bridge.set_light(2, command) def setState(self, state): self.bridge.set_light(2,'on', state) def getState(self): return self.bridge.get_light(2,'on') def toggleState(self): wantedState = not self.getState() self.setState(wantedState)
def main(): from pprint import pprint from phue import Bridge print('Saving bridge state to api_end.txt.') b = Bridge('192.168.1.110') # b = Bridge() b.connect() pprint(b.get_api(), stream=open('api_end.txt','w'))
class HueControl(): def initBridge(self, ip): self.bridge = Bridge(ip) self.bridge.connect() self.bridge.get_api() def __init__(self, jarvis, hueBridgeIP): self.initBridge(hueBridgeIP) self.jarvis = jarvis def setHue(self, hueValue): """ Set Hue from 0 to 65280 """ self.bridge.set_light(2, 'hue', hueValue) def setSaturation(self, satValue): """ Set Saturation from 0 to 254 """ self.bridge.set_light(2, 'sat', hueValue) def setBrightness(self, briValue): """ Set brightness from 0 to 254 """ self.bridge.set_light(2, 'bri', hueValue) def setCommand(self, command): self.bridge.set_light(2, command) def setState(self, state): self.bridge.set_light(2, 'on', state) def getState(self): return self.bridge.get_light(2, 'on') def toggleState(self): wantedState = not self.getState() self.setState(wantedState)
def huetv(img_size=100, webcam=0, buffer_size=5, bridge_ip=''): """Function to start the read-calc-set-Loop * read a webcam-picture * calculate the most common color * set the color to all hue-lights """ CV2_QUOT_PHILIPS = 179.0 / 65280.0 # HUE API hue_bridge = Bridge(bridge_ip) hue_bridge.connect() hue_bridge.get_api() # WEBCAM API cam = cv2.VideoCapture(webcam) buf = [] while True: # Read new Webcam Image _, image = cam.read() # Resize Image image = cv2.cvtColor(cv2.resize(image, (img_size, img_size)), cv2.COLOR_BGR2HSV) # Calculate the most common color philips_hue = int(Counter(image[:,:,0].flatten().tolist()).most_common(1)[0][0] / CV2_QUOT_PHILIPS) # Add to color-buffer buf.append(philips_hue) # if buffer is full if(len(buf) == buffer_size): # calculate the mean color hue = sum(buf)/len(buf) # set the color to all hue-lights for i in range(1, len(hue_bridge.lights)): hue_bridge.set_light(i, 'hue', hue) print(hue) # reset the buffer buf = []
class Controller(CementBaseController): class Meta: label = "base" description = "Hue Dump" arguments = [ (["-b", "--bridge"], dict(action="store", help="hostname of Hue bridge")), (["-u", "--user"], dict(action="store", help="username of Hue user")), (["-t", "--template"], dict(action="store", help="template for output rendering", default="")), ] @expose(help="Dump the configuration and state of the bridge") def dump(self): self.login() self.app.log.info(self.format_json(self.api)) @expose(help="Display a summary of lights registered on the bridge") def lights(self): self.login() lights = self.sort_dict(self.api.get("lights")) rows = [[i, l.get("name"), l.get("_alias"), l.get("manufacturername"), l.get("modelid"), "ON" if l.get("state").get("on") else "", l.get("state").get("bri", ""), l.get("state").get("colormode", ""), l.get("state").get("hue", ""), l.get("state").get("sat", "") ] for i, l in lights.iteritems()] t = self.table(["#", "Name", "Alias", "Manu", "Model", "On", "Bri", "CM", "Hue", "Sat"], rows) self.app.log.info(t) @expose(help="Render state using a template") def render(self): self.login() tpl = self.template(self.app.pargs.template, self.api) print(tpl) @expose(hide=True) def login(self): host = self.app.pargs.bridge or self.app.config.get("bridge", "host") user = self.app.pargs.user or self.app.config.get("bridge", "user") self.bridge = Bridge(host, user) self.bridge.connect() try: self.api = self.bridge.get_api() except Exception, e: if e.errno == -2: self.app.log.error("Invalid bridge host") sys.exit(1) self.add_metadata()
def blink_lights(self): try: ip = requests.get('https://www.meethue.com/api/nupnp').json( )[0]['internalipaddress'] hue = Bridge(ip) hue.connect() light_group = int(list(hue.get_api()['groups'].keys())[0]) red = [0.6786, 0.3159] reading = [0.4452, 0.4068] sleep_time = 0.5 # save the original light settings, so they can be reset when the alarm is turned off lights = hue.get_api()['lights'] orig_settings = {} for light_id in lights.keys(): light = lights[light_id] xy = light['state']['xy'] bri = light['state']['bri'] on = light['state']['on'] orig_settings[light_id] = xy, bri, on print(orig_settings) hue.set_group(light_group, 'on', True) hue.set_group(light_group, 'xy', red) while self.ringing: hue.set_group(light_group, 'bri', 255) sleep(sleep_time) hue.set_group(light_group, 'bri', 0) sleep(sleep_time) # return the lights to their original settings for light_id in orig_settings.keys(): orig_setting = orig_settings[light_id] command = { 'xy': orig_setting[0], 'bri': orig_setting[1], 'on': orig_setting[2] } hue.set_light(int(light_id), command) except PhueRegistrationException: print( 'ERROR: The link button needs to be pressed to control the lights' )
def hue(power=True): # contact bridge hue = Bridge(BRIDGE_IP) # first time only hue.connect() # turn all off if requested if not power: hue.set_group(0, 'on', False) return # don't mess with lights during the day time if daytime(): return # we'll find scenes by searching rules for "Tap X.Y $str", where # X is a Tap number, Y is the tap button. First, search for Tap # numbers based on their names: tap_names = [] for num, sensor in hue.get_api().get("sensors", {}).items(): name = sensor.get("name", "") if name in TAPS: tap_names.append("Tap %s.%d" % (num, TAPS[name])) # now, determine scenes scenes = [] for _, rule in hue.get_api().get("rules", {}).items(): # pull only "Tap X.Y" from name name = rule.get("name", "") match = re.match(r"(?P<tid>Tap [0-9]\.[0-9]).*", name) if match is None: continue # see if Tap button is one of interest, recall its scene if so if match.group("tid") in tap_names: action = rule.get("actions", [{}])[0] scene = action.get("body", {}).get("scene", "") scenes.append(scene) # set all scenes for scene in scenes: hue.set_group(0, 'scene', scene)
def setLightStatus(request, username=None, light_id=None, status=False): from phue import Bridge # ip_address = '127.0.0.1:9000' ip_address = request.data.get('ip_address') b = Bridge(ip_address, username=username) b.connect() print(b.get_api()) new_status = True if status == '1' else False b.set_light(int(light_id), 'on', new_status) ctx = {'on': new_status} return Response(ctx)
def control_light(bridge_ip, key, room_name, light_id, new_state, dry_run=False): assert new_state in (True, False) logger.info("Setting light %s(%s) to %s" % (room_name, light_id, "ON" if new_state else "OFF")) if dry_run: return b = Bridge(bridge_ip, username=key) b.get_api() b.set_light(light_id, {'on': new_state}) result = b.get_light(light_id) if result['state']['on'] == new_state: logger.info(" Set light %s to %s" % (light_id, "ON" if new_state else "OFF")) else: logger.info(" Tried to set light %s to %s, but new state is %s" % (light_id, new_state, result['state']['on']))
class HueController(object): """ Hue controller """ def __init__(self, ip_address, *args, **kwargs): self.bridge = Bridge(ip_address) self.api = self.bridge.get_api() self.intensity = 0 def reset(self): """ Reset lamps to 0, white, no effect """ self.bridge.set_group(1, PARAM_TURNEDON, True) self.bridge.set_group(1, PARAM_HUE, 65535) self.bridge.set_group(1, PARAM_SATURATION, 0) self.bridge.set_group(1, PARAM_BRIGHTNESS, 0) self.bridge.set_group(1, PARAM_EFFECT, 'none') # colorloop or none supported def get_light_ids(self): lights_info = self.api['lights'] lamp_ids = [int(key) for key, value in lights_info.items()] return lamp_ids def get_light_names(self): lights_info = self.api['lights'] lamp_names = [value['name'] for key, value in lights_info.items()] return lamp_names def update_state(self): print( f'Using intensity {self.intensity} and value {round(254/100*self.intensity)}' ) self.bridge.set_group(1, PARAM_SATURATION, round(254 / 100 * self.intensity)) if (self.intensity == 100): self.bridge.set_group(1, PARAM_BRIGHTNESS, 0, transitiontime=0.5) self.bridge.set_group(1, PARAM_BRIGHTNESS, 254, transitiontime=0.5) else: self.bridge.set_group(1, PARAM_BRIGHTNESS, round(254 / 100 * self.intensity)) def increase_intensity(self): if self.intensity < 100: self.intensity = self.intensity + 5 self.update_state() def decrease_intensity(self): if self.intensity > 1: self.intensity = self.intensity - 5 self.update_state()
class Hue(): def __init__(self, bridge, lightbulb=None): self.bridgeAddress = bridge self.lightsMap = {} if lightbulb: m = re.split('\s*,\s*', lightbulb) self.lightbulbs = m if m else [lightbulb] def connect(self): self.bridge = Bridge(self.bridgeAddress) self.bridge.connect() self.bridge.get_api() for light in self.bridge.lights: self.lightsMap[light.name] = light if not hasattr(self, 'lightbulbs'): self.lightbulbs = [] for light in self.bridge.lights: self.lightbulbs.append(light.name) def setBri(self, bri): if bri == 0: for light in self.lightbulbs: self.bridge.set_light(light, 'on', False) else: for light in self.lightbulbs: if not self.bridge.get_light(light, 'on'): self.bridge.set_light(light, 'on', True) self.bridge.set_light(self.lightbulbs, 'bri', bri) def setSat(self, sat): self.bridge.set_light(self.lightbulbs, 'sat', sat) def setHue(self, hue): self.bridge.set_light(self.lightbulbs, 'hue', hue)
class HueService: def __init__(self, bridge_ip): self.connected = False try: self.bridge = Bridge(bridge_ip) self.connected = True self.bridge.connect() self.hue_info = self.bridge.get_api() self.lights = [] for light_numb in self.hue_info['lights']: light = self.hue_info['lights'][light_numb] light_obj = HueLight(self, light_numb, light) self.lights.append(light_obj) except: pass def get_lights(self): return self.lights def refresh_lights(self): print('refreshing lights') self.hue_info = self.bridge.get_api() for light_numb in range(0, len(self.lights)): self.lights[light_numb].refresh()
def turn_on_alert(led_num, alert_type): #Turns on an alert ni.ifaddresses('eth0') ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr'] b = Bridge('192.168.4.50') b.connect() b.get_api() b.set_light(led_num, 'on', True) b.set_light(led_num, 'bri', 150) if (alert_type == 1): #turns on led as bright as possible #b.set_light(led_num,'bri',254) b.set_light(led_num, 'hue', 0) time.sleep(TIME_OUT) elif (alert_type == 2): #turns on a led but less brightly b.set_light(led_num, 'hue', 25500) time.sleep(TIME_OUT) elif (alert_type == 3): #slow blink b.set_light(led_num, 'hue', 46920) time.sleep(TIME_OUT) #while(time.time()<timeout): # b.set_light(led_num,'on',False) # time.sleep(1.5) # b.set_light(led_num,'on',True) # time.sleep(1.5) elif (alert_type == 4): b.set_light(led_num, 'hue', 10000) time.sleep(TIME_OUT) #while(time.time()<timeout): #fast blink # b.set_light(led_num,'on',False) # time.sleep(0.5) # b.set_light(led_num,'on',True) # time.sleep(0.5) b.set_light(led_num, 'on', False)
class HueConnector(Connector): def __init__(self, backend, ip): super().__init__(backend) self.bridge = Bridge(ip) self.bridge.connect() api = self.bridge.get_api() self.light_indices = {} for idx, data in api["lights"].items(): self.light_indices[data["name"]] = int(idx) self.group_indices = {} for idx, data in api["groups"].items(): self.group_indices[data["name"]] = int(idx) #pprint(api) def recv(self, msg): if not isinstance(msg, RoomLightsMessage): return if isinstance(msg, SetPresetCommand): self.apply_config(msg.preset) def apply_config(self, config): for c in config: lights, preset = c for light in lights: if light.startswith("Group:"): name = light[6:] index_set = self.group_indices set_func = self.bridge.set_group else: name = light index_set = self.light_indices set_func = self.bridge.set_light idx = index_set.get(name) if idx: set_func(idx, preset.phue_dict()) else: print("Warning: Light or group with name '{}' unknown.". format(name))
class HueService(ParentService): def __init__(self, ip=None): self.ip = ip self.id = None self.bridge = Bridge(self.ip) def get_function(self, message=None): api = self.bridge.get_api() for each_light in api['lights']: if (api['lights'][each_light]['name'].lower() == message.get( "bulb_name", "none").lower()): self.id = each_light return self.toggle def toggle(self): self.bridge.connect() curr_state = self.bridge.get_light(int(self.id), 'on') if curr_state: self.bridge.set_light(int(self.id), 'on', False) else: self.bridge.set_light(int(self.id), 'on', True)
def init(): global light global b b = Bridge('192.168.0.170') b.connect() # Get the bridge state (This returns the full dictionary that you can explore) print(b.get_api()) lights = b.lights # Print light names for l in lights: if l.name == "Cal's light": light = l print("light found") break if light is None: raise Exception("no light found") light.transitiontime = 10 light.on = True
import web from phue import Bridge urls = ( '/', 'index' ) bridge = Bridge('192.168.1.42', 'e9a353626dcf16710e53f9a2ae2407b') bridge.get_api() class index: def GET(self): render = web.template.render('') lights = bridge.get_light_objects('list') return render.index(lights) if __name__ == "__main__": app = web.application(urls, globals()) app.run()
#!/usr/bin/env python from phue import Bridge import pprint import json import os bridge = Bridge('10.0.1.2') bridge.connect() pprint.pprint(bridge.get_api()) sensors = { "00:00:00:00:00:40:92:15-f2": "Bedroom Door", "00:00:00:00:00:42:06:3b-f2": "Bedroom Nightstand", "00:00:00:00:00:43:c1:9b-f2": "Office Door", "00:00:00:00:00:43:1c:9f-f2": "Front Door", } lights = { "00:17:88:01:00:b1:8a:1d-0b": "Bedroom - Alicia", "00:17:88:01:00:1c:57:ea-0b": "Bedroom - Alicia (Under)", "00:17:88:01:00:b1:91:e2-0b": "Bedroom - Tim", "00:17:88:01:00:1c:57:ae-0b": "Bedroom - Tim (Under)", "00:17:88:01:00:ba:20:96-0b": "Living Room 1", "00:17:88:01:00:bf:d8:5c-0b": "Living Room 2", "00:17:88:01:00:b6:43:01-0b": "Living Room Outer", "00:17:88:01:00:b1:bf:53-0b": "Kitchen Left", "00:17:88:01:00:b6:43:72-0b": "Kitchen Right",
b.set_light(index + 1, change_command) time.sleep(2.9) def lights_off(): off_command = {'transitiontime': 10, 'on': False} b.set_light(range(1, number_of_lights+1), off_command) b = Bridge(hue_bridge_ip) # 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() new_file = mono_only(which_file) file_data = wav_data(which_file) file_time = wav_frames(which_file) size_chunks = wav_len(file_data, file_time) the_chunks = chunks(file_data, size_chunks) find_notes = note_conversion(the_chunks) map_of_notes = notes_map(find_notes) map_of_note_counter = counter_for_note_map(map_of_notes) play_song() lights_on() note_to_color(map_of_note_counter) lights_off()
#Phillips Hue Home automation project #Allows control of Phillips Hue Bulbs from tkinter import * from tkinter import ttk import time import urllib.request import phue from phue import Bridge b = Bridge('192.168.1.151') #Replace with your Phllips Hue Hub Address try: b.connect() bridgeState = b.get_api() except: print("Failed to connect to bridge") lights = b.lights for lightBulb in lights: print(lightBulb.name) root = Tk() root.style = ttk.Style() root.style.theme_use('clam') #root.configure(background='black') frame = Frame(root) frame.grid(row=0)
class Hue(object): """ Plugin to interact with Philips Hue devices @author: Fabio "BlackLight" Manganiello <*****@*****.**> @depend: Philips Hue phue Python bridge [pip install phue] """ __hue = None __hue_lock = threading.RLock() def __init__(self, lightbulbs=None): """ bridge -- Name or IP address of the Philips Hue bridge host lightbulbs -- Lightbulbs to act on - single lightbulb name or comma separated list. In case nothing is passed, the plugin will act on all the lightbulbs connected to the bridge """ self.__config = Config.get_config() self.__logger = Logger.get_logger(__name__) self.bridge_address = self.__config.get('hue.bridge') self.lightbulbs = self.__config.get('hue.lightbulbs') self.connected = False if self.lightbulbs: m = re.split('\s*,\s*', self.lightbulbs) self.lightbulbs = m or [self.lightbulbs] self.__logger.info({ 'msg_type': 'Hue bridge started', 'bridge': self.bridge_address, 'lightbulbs': self.lightbulbs or None, }) @classmethod def get_hue(cls): """ Static helper used for rules.xml <action> tags of type Python, which are run through eval(). Thread-safe singleton to access or initialize the static default hue object """ cls.__hue_lock.acquire() try: if cls.__hue is None: cls.__hue = Hue() finally: cls.__hue_lock.release() return cls.__hue def connect(self): " Connect to the Philips Hue bridge " if self.connected: return self.__logger.info({ 'msg_type': 'Connecting to the Hue bridge', }) self.bridge = Bridge(self.bridge_address) self.bridge.connect() self.bridge.get_api() if not self.lightbulbs: self.lightbulbs = [] for light in self.bridge.lights: self.lightbulbs.append(light.name) self.__logger.info({ 'msg_type': 'Connected to the Hue bridge', 'lightbulbs': self.lightbulbs, }) self.connected = True return self def is_connected(self): " Return true if we are connected to the bridge " return self.connected def set_on(self, on): """ Set the lightbulbs on status on -- If False, turn the lights off, otherwise turn them on """ self.__logger.info({ 'msg_type': 'Set lightbulbs on', 'on': on, }) for light in self.lightbulbs: self.bridge.set_light(light, 'on', on) if on: self.bridge.set_light(light, 'bri', 255) return self def set_bri(self, bri): """ Set the lightbulbs brightness bri -- Brightness value, in range [0-255] """ self.__logger.info({ 'msg_type': 'Set lightbulbs brightness', 'brightness': bri, }) if bri == 0: for light in self.lightbulbs: self.bridge.set_light(light, 'on', False) else: for light in self.lightbulbs: if not self.bridge.get_light(light, 'on'): self.bridge.set_light(light, 'on', True) self.bridge.set_light(self.lightbulbs, 'bri', bri) return self def set_sat(self, sat): """ Set the lightbulbs saturation sat -- Saturation value, in range [0-500] """ self.__logger.info({ 'msg_type': 'Set lightbulbs saturation', 'saturation': sat, }) self.bridge.set_light(self.lightbulbs, 'sat', sat) return self def set_hue(self, hue): """ Set the lightbulbs hue hue -- Hue/tint value, in range [0-65535] """ self.__logger.info({ 'msg_type': 'Set lightbulbs hue', 'saturation': hue, }) self.bridge.set_light(self.lightbulbs, 'hue', hue) return self
class Control: nest = None bridge = None def __init__(self): global logger logger = logging.getLogger(__name__) # connect to nest try: from nest import Nest self.nest = Nest( username=settings.NEST_LOGIN, password=settings.NEST_PASS ) self.nest.login() self.nest.get_status() except: logger.error("Unable to connect to NEST.") # connect to phillips hue self.bridge = Bridge( settings.HUE_BRIDGE ) try: self.bridge.connect() self.bridge.get_api() except: logger.error("Unable to connect to Hue.") def execute_command(self, command): if command.action == 'power': light_state = (command.value == 'on') for light_index in settings.LIGHT_GROUPS[command.room]: logger.debug('Setting light %s: %s' % ( str(light_index), str(light_state) )) self.bridge.set_light(light_index, 'on', light_state) if light_state: # reset color self.bridge.set_light(light_index, 'hue', 15331) self.bridge.set_light(light_index, 'sat', 121) return True elif command.action == 'dim': for light_index in settings.LIGHT_GROUPS[command.room]: brightness = int(255 * (command.value*0.1)) logger.debug('Setting bright %s: %s' % ( str(light_index), str(brightness) )) self.bridge.set_light(light_index, 'bri', brightness) return True elif command.action == 'hue': curr_group = settings.LIGHT_GROUPS[command.room] for index, light_index in enumerate(curr_group): # iterates over each color for fades, gradients,etc value = command.value[index % len(command.value)] logger.debug('Setting hue %s: %s' % ( str(light_index), value )) self.bridge.set_light(light_index, 'on', True) self.bridge.set_light(light_index, 'hue', value) self.bridge.set_light(light_index, 'sat', 255) return True elif command.action == 'temperature': if not self.nest: logger.error('Nest thermostat not initialized.') return False if command.value: self.nest.set_temperature(command.value) return True else: logger.error('Could not determine a temperature.') return False
class HuePlugin(IPlugin): """ Abstraction of the Hue plugin. """ def __init__(self): IPlugin.__init__(self) self.command_priority = 1 self.log = logging.getLogger(__name__) self.voice = None self.bridge = None self.lights = mc.get('footman_lights') if not self.lights: self.bridge = Bridge(ip=HUE_IP_ADDRESS, username=HUE_USER) self.api_data = self.bridge.get_api() self.lights = [self.api_data['lights'][key]['name'] for key in self.api_data['lights'].keys()] mc.set('footman_lights', self.lights) self.commands = { '.*(?P<command>turn on|turn off|dim|bright|crazy).*(?P<light>' + '|'.join([l.lower() for l in self.lights]) + '|all).*light.*': [ { 'command': self.command, 'args': (None, None,), 'kwargs': {}, 'command_priority': 0, } ] } def command(self, command_dict, comm_text, light_text): """ Give the robot a command """ if comm_text: command_text = comm_text else: command_text = command_dict['command'] if light_text: light_id_text = light_text else: light_id_text = command_dict['light'] if not self.voice: self.instantiate_voice() if not self.bridge: self.bridge = Bridge(ip=HUE_IP_ADDRESS, username=HUE_USER) if light_id_text == 'all' and command_text == 'turn on': self.bridge.set_light([str(light) for light in self.lights], 'on', True) self.bridge.set_light([str(light) for light in self.lights], 'bri', 127) self.voice.say({}, 'All lights turned on') elif light_id_text == 'all' and command_text == 'turn off': self.bridge.set_light([str(light) for light in self.lights], 'on', False) self.voice.say({}, 'All lights turned off') elif light_id_text == 'all' and command_text == 'bright': self.bridge.set_light([str(light) for light in self.lights], 'on', False) self.bridge.set_light([str(light) for light in self.lights], 'bri', 254) elif light_id_text == 'all' and command_text == 'dim': self.bridge.set_light([str(light) for light in self.lights], 'on', False) self.bridge.set_light([str(light) for light in self.lights], 'bri', 25) self.voice.say({}, 'All lights dimmed') elif light_id_text == 'all' and command_text == 'crazy': self.bridge.set_light([str(light) for light in self.lights], 'on', False) self.bridge.set_light([str(light) for light in self.lights], 'effect', 'colorloop') self.voice.say({}, 'All lights rotating colors') elif command_text == 'turn on': for light in self.lights: if light.lower() == light_id_text: self.bridge.set_light(str(light), 'on', True) self.bridge.set_light(str(light), 'bri', 127) self.voice.say({}, light + ' light turned on') elif command_text == 'turn off': for light in self.lights: if light.lower() == light_id_text: self.bridge.set_light(str(light), 'on', False) self.voice.say({}, light + ' light turned off') elif command_text == 'bright': for light in self.lights: if light.lower() == light_id_text: self.bridge.set_light(str(light), 'bri', 254) self.voice.say({}, light + ' light brightened') elif command_text == 'dim': for light in self.lights: if light.lower() == light_id_text: self.bridge.set_light(str(light), 'bri', 25) self.voice.say({}, light + ' light dimmed') elif command_text == 'crazy': for light in self.lights: if light.lower() == light_id_text: self.bridge.set_light(str(light), 'effect', 'colorloop') self.voice.say({}, light + ' light rotating colors') return None def instantiate_voice(self): """ We need to separately instatiate this so yapsy doesn't get confused. """ from footman.plugins.voice import VoicePlugin self.voice = VoicePlugin() return None
#!/usr/bin/python # AutoAuroDX # hueTesting.py (some simple bits to test API behavior) # Adam J. Bauman # # Real-time Philips Hue light programming based off hue and intensity averages of PC monitor display. import datetime, time import os from phue import Bridge myBridge = Bridge('192.168.1.25') myBridge.connect() myBridge.get_api() myBridge.set_light(1, 'on', True) myBridge.set_light(1, 'bri', 127, transitiontime=0) myBridge.set_light(1, 'effect', 'colorloop', transitiontime=0) raw_input('Press any key to continue... ') myBridge.set_light(1, 'effect', 'none') print(myBridge.get_light(1, 'hue'))
__author__ = 'sander' from phue import Bridge b=Bridge(ip="192.168.2.9") #b.connect() ap = b.get_api() #grp = b.get_group(1) scn = b.get_scene(u'e07a35d7e-on-0') print scn #b.set_light("Tafel",'on',True)
#!/usr/bin/python from flask import Flask, render_template, request from phue import Bridge app = Flask(__name__) ip = '10.0.1.128' b = Bridge(ip) b.connect() b.get_api() lights = b.get_light_objects() @app.route("/") def index(): return render_template('index.html') @app.route("/changeColor") def changeColor(): h = int(request.args.get('h')) s = int(request.args.get('s')) l = int(request.args.get('l')) b.get_api() lights = b.get_light_objects() filteredLights = filter(lambda a: a.name != 'Bedside lamp', lights) for light in filteredLights: light.hue = h light.saturation = s light.brightness = l return "ayy lmao"
def run(self): b = Bridge(self.device.get_ip()) b.connect() logger.info('Bridge state: %s' % str(b.get_api())) lights = {} next_action = None while(self._in_service()): if next_action: logger.info('Changing... %s' % str(next_action)) light_id = next_action['id'] next_status = next_action['status'] if light_id in lights \ and lights[light_id]['last_status'] != next_status: logger.info('Change: %s, %s' % (light_id, next_status)) if lights[light_id]['last_status'] is None: lights[light_id]['last_status'] = {} last_status = lights[light_id]['last_status'] light = lights[light_id]['device'] if next_status['on']: last_status['on'] = next_status['on'] light.on = next_status['on'] if 'hue' in next_status: last_status['hue'] = next_status['hue'] light.hue = next_status['hue'] if 'saturation' in next_status: last_status['saturation'] = next_status['saturation'] light.saturation = next_status['saturation'] if 'brightness' in next_status: last_status['brightness'] = next_status['brightness'] light.brightness = next_status['brightness'] if 'on' in next_status and \ last_status['on'] != next_status['on']: last_status['on'] = next_status['on'] light.on = next_status['on'] else: logger.info('Ignored: %s, %s' % (light_id, next_status)) logger.debug('Retrieving status of lights...') current = {} added = [] removed = [] try: for l in b.lights: current[b.get_light_id_by_name(l.name)] = l for lid, light in current.items(): if lid not in lights: added.append(lid) for lid, light in lights.items(): if lid not in current: removed.append(lid) for lid in added: lights[lid] = {'device': current[lid], 'last_status': None} msg = {'id': lid, 'action': 'added', 'name': current[lid].name, 'topic': {'light': get_light_topic(self.device.udn, lid)}} self.mqtt_client.publish(get_light_topic(self.device.udn, lid), payload=json.dumps(msg)) for lid in removed: old = lights[lid]['device'] del lights[lid] msg = {'id': lid, 'action': 'removed', 'name': old.name, 'topic': {'light': get_light_topic(self.device.udn, lid)}} self.mqtt_client.publish(get_light_topic(self.device.udn, lid), payload=json.dumps(msg)) for lid, light_entry in lights.items(): light = light_entry['device'] status = {'on': light.on, 'saturation': light.saturation, 'hue': light.hue, 'brightness': light.brightness} if status != light_entry['last_status']: logger.debug('%s: status=%s' % (light.name, str(status))) light_entry['last_status'] = status topic = '%s/status' % get_light_topic(self.device.udn, lid) self.mqtt_client.publish(topic, payload=json.dumps(status)) except: logger.warning('Unexpected error: %s' % sys.exc_info()[0]) logger.debug('Retrieving finished') try: next_action = self.actions.get(True, self.interval) except Queue.Empty: next_action = None