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 function_two(flag): # Initialization env = Environment() env.start() env.discover(3) b = Bridge('192.168.0.100') b.connect() lights = b.lights groups = b.groups client = MongoClient( 'mongodb://*****:*****@tmega-shard-00-00-kcfpq.mongodb.net:27017,tmega-shard-00-01-kcfpq.mongodb.net:27017,tmega-shard-00-02-kcfpq.mongodb.net:27017/user_info?ssl=true&replicaSet=tmega-shard-0&authSource=admin' ) db_website = client.website # Post button press to API temp_dict = db_website.usrname.find_one({'username': '******'}, {'button_two': ()}) new_value = int(temp_dict['button_two']) + 1 db_website.usrname.update({'username': '******'}, {'$set': { 'button_two': new_value }}, upsert=False) # Bedroom Lights (OFF) if flag == 1: b.set_light('lamp 3', 'on', False) # Kitchen Lights (OFF) if flag == 2: b.set_group('Kitchen', 'on', False) # TV (NONE) if flag == 3: print("TV 2") # Fan (OFF) if flag == 4: env.get_switch('office').off() sleep(0.3)
class lights: def __init__(self): ip = self.discover_ip() self.bridge = Bridge(ip) def discover_ip(self): response = requests.get('https://discovery.meethue.com') if response and response.status_code == 200: data = response.json() if 'internalipaddress' in data[0]: return data[0]['internalipaddress'] return None def lights_connect(self): self.bridge.connect() self.bridge.set_group(1, 'on', True) def set_light_color(self, color): converter = Converter() xy = converter.rgb_to_xy(color[0], color[1], color[2]) self.bridge.set_group(1, 'xy', color) def disconnect_lights(self): self.bridge.set_group(1, 'on', False)
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 react_to_vlc(): v = VLCTracker('','password') b = Bridge(BRIDGE_IP) b.connect() outcome = '' while True: new_outcome = v.get_state() if outcome != new_outcome: # Something changed if new_outcome == 'playing': # Turn off lights b.set_group(1, 'on', False) elif new_outcome == 'paused': # Dim lights b.set_group(1, 'on', True) else: # Restore light b.set_group(1, 'on', True) print("State changed from '" + outcome + "' to '" + new_outcome + "'") else: pass outcome = new_outcome time.sleep(0.1)
light = None # First, check if it's a group name. for group_data in b.get_group().values(): if group_data["name"] == LAMP_OR_GROUP_NAME: print("Found group with name", LAMP_OR_GROUP_NAME) is_group = True # If it's not a group, find the lamp by name. if not is_group: light_names = b.get_light_objects("name") light = light_names[LAMP_OR_GROUP_NAME] print("Found light with name", LAMP_OR_GROUP_NAME) current_brightness = None while True: x = trinkey.readline().decode("utf-8") if not x.startswith("Slider: "): continue # Convert the Slider Trinkey output value of 0-100 to 0-254. brightness_value = int((float(x.split(": ")[1]) / 100) * 254) if current_brightness is None or brightness_value != current_brightness: print("Setting brightness to:", brightness_value) if is_group: b.set_group(LAMP_OR_GROUP_NAME, {"bri": brightness_value}) else: light.brightness = brightness_value current_brightness = brightness_value
import sys import spotipy import spotipy.util as util import time from datetime import datetime from datetime import timedelta def bright(loud): return 244.94 * (1.0199 ** loud) b = Bridge('') b.connect() hue = 1 b.create_group('room',[1,2,3,4,5]) #b.set_light(2,'on',True) b.set_group(1,'on',True) uri='spotify:track:6CDzDgIUqeDY5g8ujExx2f' token = util.prompt_for_user_token(username='', scope = 'user-modify-playback-state', client_id="", client_secret="", redirect_uri="http://localhost:8080") if token: sp = spotipy.Spotify(auth=token) results = uri if results != None: #analysis = sp.audio_analysis(results["item"]["uri"]) analysis = sp.audio_analysis(results) iterator = iter(analysis['segments']) brightness=32 val = analysis['segments'][0] time_taken = 0 start_time = time.time()
class HueWrapper: def __init__(self, bridge_ip): """ :param bridge_ip: ip address of the hue bridge """ self.bridge = Bridge(bridge_ip) # first time we run, we have to press the physical button on the bridge device self.bridge.connect() lights = self.bridge.lights # Print light names print("found the following lights on bridge {}".format(bridge_ip)) for l in lights: print(l.name) def is_group_on(self, group): """ Checks whether the specified group is on. :param group: :return: True iff the specified group is on. """ return self.bridge.get_group(group, "on") def turn_group_off(self, group): """ Turns off the specified group. :param group: :return: """ self.bridge.set_group(group, "on", False) def turn_group_on(self, group): """ Turns on the specified group. :param group: :param transition_time: slow transition :return: """ self.bridge.set_group(group, "on", True) def set_light_group_brightness(self, group, brightness_pct, transition_time=None): """ Sets the brightness for the specified light group. Note that setting brightness to 0 will not turn off the light. :param group: :param brightness_pct: :return: """ self.bridge.set_group(group, 'bri', self.brightness_from_pct(brightness_pct), transition_time) '''Get or set the color temperature of the light, in units of Kelvin [2000-6500]''' def set_light_group_temp(self, group, temp, transition_time=None): mireds = int(round(1e6 / temp)) self.bridge.set_group(group, 'ct', mireds, transition_time) def set_light_brightness(self, light, brightness_pct, transition_time=None): """ Sets the brightness for the specified light. Note that setting brightness to 0 will not turn off the light. :param light: :param brightness_pct: :param transition_time: :return: """ self.bridge.set_light(light, 'bri', self.brightness_from_pct(brightness_pct), transitiontime=transition_time) def turn_light_on(self, light): self.bridge.set_light(light, 'on', True) def turn_light_off(self, light): self.bridge.set_light(light, 'on', False) @staticmethod def brightness_from_pct(brightness_pct): """ Converts an integer representing percentage into a value acceptable for hue api :param brightness_pct: :return: """ return int(float(brightness_pct) / 100 * 254)
def turnOn(): logging.basicConfig() b = Bridge(ip) b.set_group(1, 'on', True)
b.set_light(b2,'hue',13088) b.set_light(b3,'hue',13088) while (newbri <= 150): b.set_light(b2,'bri',newbri,transitiontime=300) b.set_light(b3,'bri',newbri,transitiontime=300) if newbri <=100: b.set_light(b1,'bri',newbri,transitiontime=300) b.set_light(b3,'bri',newbri,transitiontime=300) newbri = newbri + 10 sleep(30) print 'Colored Lights Done' #Turn on Lux Groups b.set_group(g1,'on',True) b.set_group(g1,'bri',0) b.set_group(g2,'on',True) b.set_group(g2,'bri',0) #Start Brightness on Lux newbri = 0 while (newbri <= 150): b.set_group(g1,'bri',newbri,transitiontime=300) if newbri <=100: b.set_group(g2,'bri',newbri,transitiontime=300) newbri = newbri + 10 sleep(30) print 'Lux Done'
light_status = "[" for light in group['lights']: light = b.get_light(int(light)) status = f"{light['state']['bri']:3}" if light['state']['on'] else "off" light_status += f"({light['name']}: {status}), " print(light_status[:-2]+"]") # print available scenes and inputs indexed_scenes = list(enumerate([scene.name for scene in b.scenes])) print("Available scenes:") pprint.pp(indexed_scenes) commands = input("Enter scene index, 'on', 'off', or -brightness value (1-255) (empty cancels): ") # handle the command(s) given for command in commands.split(): if command == "": pass elif command == 'on': b.set_group(1, 'on', True) elif command == 'off': b.set_group(1, 'on', False) elif command.isdigit(): command = int(command) if command >= 0: b.run_scene(group['name'], indexed_scenes[command][1]) else: b.set_group(1, 'bri', -command) else: print("command not recognized")
class HueModuleMain(AbstractModule): module_name = 'Phillips Hue' config_parameters = { "bridge_ip": "Enter the ip address of your Philips Hue Bridge here. Make sure, that you have" " pressed the button on the bridge before hitting enter." } bridge = None def __init__(self): super(HueModuleMain, self).__init__() self.add_submodule(HueModuleDe()) self.add_submodule(HueModuleEn()) def configure(self): try: bridge_ip = Config.get_instance().get("hue", "bridge_ip") self.bridge = Bridge(bridge_ip) except phue.PhueRegistrationException: # TODO figure out how to localize error message here raise ImpossibleActionError( "You have to press the button on your bridge first!") except Exception as e: raise ModuleError(self.module_name, str(e)) @staticmethod def scene(chosen_scene): if chosen_scene == "chillig": # the event has to be created on ifttt.com first ifttt.send_event("huescene") def off(self): try: self.bridge.set_group(1, 'on', False) except phue.PhueRequestTimeout: raise ImpossibleActionError("Connection timed out.") except Exception as e: raise ModuleError(self.module_name, str(e)) def on(self): try: self.bridge.set_group(1, 'on', True) except phue.PhueRequestTimeout: raise ImpossibleActionError("Connection timed out.") except Exception as e: raise ModuleError(self.module_name, str(e)) def fan_on(self): try: self.bridge.set_group(3, 'on', True) except phue.PhueRequestTimeout: raise ImpossibleActionError("Connection timed out.") except Exception as e: raise ModuleError(self.module_name, str(e)) def fan_off(self): try: self.bridge.set_group(3, 'on', False) except phue.PhueRequestTimeout: raise ImpossibleActionError("Connection timed out.") except Exception as e: raise ModuleError(self.module_name, str(e)) # maybe going to switch to selection of more scenes, but it is good enough for my usage right now def scene_relaxing(self): self.scene('chillig')
class PhilipsHue(HAInterface): VERSION = '2.1' valid_commands = ('bri', 'hue', 'sat', 'ct', 'rgb', 'tr', 'eft') def __init__(self, *args, **kwargs): super(PhilipsHue, self).__init__(None, *args, **kwargs) # Instance should be hue = PhilipsHue(address = '192.168.0.2', poll=10) def _init(self, *args, **kwargs): super(PhilipsHue, self)._init(*args, **kwargs) self._iteration = 0 self._poll_secs = kwargs.get('poll', 10) self.last_status = {} # get the ip address and connect to the bridge self._ip = kwargs.get('address', None) print("Philips HUE Bridge address -> {0} Poll time -> {1}".format( self._ip, self._poll_secs)) try: self.interface = Bridge(self._ip) self.interface.connect() self._logger.debug( "[Hue] Connected to interface at {0}...\n".format(self._ip)) except Exception as ex: self._logger.debug('[Hue] Could not connect to bridge: {0}'.format( str(ex))) print( "\nCouldn't connect to HUE bridge, please press the LINK button\n" ) print("on the bridge and restart Pytomation within 30 seconds...") sys.exit() # Get the initial configuration of the Bridge so we can see models of lights etc # self.bridge_config['lights']['1']['modelid'] # Eventually we will build a table of device capabilites, for example if the # light is dimmable self.bridge_config = self.interface.get_api() #devices = self._build_device_table() self.version() def _readInterface(self, lastPacketHash): # We need to dial back how often we check the bridge.. Lets not bombard it! # If status hasn't changed for N seconds, dial back polling, once status changes # reset and slowly dial back again. # We check the status here and compare with what Pytomation knows, in case a light gets changed # by one of the Huw switches, a cell phone or some other app or device. if self._iteration <= self._poll_secs: self._logger.debug('[HUE] Retrieving status from bridge.') #check to see if there is anything we need to read try: # get dictionary of lights lights = self.interface.get_light_objects('id') for d in self._devices: #print (d.address,d.state,lights[int(d.address[1:])].on) if (d.state == 'on' or 'level' in d.state) and lights[int( d.address[1:])].on == False: contact = Command.OFF self._logger.debug('Light {0} status -> {1}'.format( d.address, contact)) self._onCommand(address="{0}".format(d.address), command=contact) self._iteration = .1 elif d.state == 'off' and lights[int( d.address[1:])].on == True: bri = int( round( int(lights[int(d.address[1:])].brightness) / 255.0 * 100)) contact = (Command.LEVEL, bri) self._logger.debug('Light {0} status -> {1}'.format( d.address, contact)) self._onCommand(address="{0}".format(d.address), command=contact) self._iteration = .1 except Exception as ex: self._logger.error('Could not process data from bridge: ' + str(ex)) if self._iteration < self._poll_secs: self._iteration += .1 time.sleep(self._iteration) # print("looping", self._iteration) else: self._iteration -= .2 def on(self, address): # TODO Check the type of bulb and then command accordingly # an 'on' command always sets level to 100% and colour to white cmd = {'transitiontime': 0, 'on': True, 'bri': 255, 'ct': 370} if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error("{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return # TODO parse result def off(self, address): cmd = {'transitiontime': 0, 'on': False} if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error("{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return # Level for the HUE is capable of setting the following: # brightness : level = (int) - int is from 0 to 100 (mapped to 255) # hue : level = ('hue':int') - int is from 0 to 65535 # saturation : level = ('sat':int') - int is from 0 to 255 # hue and sat: level = ('hue':int', 'sat:int') - int is from 0 to 65535 # ct : level = ('ct':int') - int is from 153 to 500 # rgb : level = ('rgb':hex) - hex is from 000000 to ffffff # transition : level = ('tr':int') int is from 0 to 3000 in 1/10 seconds # effect : level = ('eft':colorloop|none') put bulb in colour loop # Not all RGB colours will produce a colour in the HUE lamps. # ct values are translated kelvin temperature values from 2000K to 6500K # 2000K maps to 500 and 6500K maps to 153 # If the lamp is already on don't send an on command # TODO check if bulb type can perform the selected operation def level(self, address, level, timeout=None, rate=None): cmd = {} #print level if (isinstance(level, tuple)): for i in level: if isinstance(i, int): #classic pytomation brightness i = 'bri:{0}'.format(i) cmd = dict( list(self._build_hue_command(i).items()) + list(cmd.items())) #print cmd if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error( "{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return else: if isinstance(level, int): #classic pytomation brightness level = 'bri:{0}'.format(level) if level.split(':')[0] not in self.valid_commands: self._logger.error( "{name} not a valid HUE command {level}".format( name=self.name, level=level, )) return cmd = self._build_hue_command(level) if address[:1] == 'L': result = self.interface.set_light(int(address[1:]), cmd) elif address[:1] == 'G': result = self.interface.set_group(int(address[1:]), cmd) else: self._logger.error( "{name} not a valid HUE address {addr}".format( name=self.name, addr=address, )) return def hue(self, address): pass def saturation(self, address): pass def _build_hue_command(self, level): if (isinstance(level, tuple)): pass else: huecmd = level.split(':')[0] hueval = level.split(':')[1] if huecmd == 'bri': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 100): # if level is 0 or 1 turn hue off if hueval == 0 or hueval == 1: return {'on': False} else: # make it 0 to 255 brimapped = int((int(hueval) / 100.0) * int(0xFF)) return {'on': True, huecmd: brimapped} else: return None elif huecmd == 'hue': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 65535): return {'on': True, huecmd: hueval} else: return None elif huecmd == 'sat': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 255): return {'on': True, huecmd: hueval} else: return None elif huecmd == 'ct': hueval = int(hueval) if self._check_range(huecmd, hueval, 153, 500): return {'on': True, huecmd: hueval} else: return None elif huecmd == 'tr': hueval = int(hueval) if self._check_range(huecmd, hueval, 0, 3000): return {'on': True, 'transitiontime': hueval} else: return None elif huecmd == 'rgb': if self._check_range(huecmd, int(hueval, 16), 0, 16777215): xy = () # no colour # convert the hex colour ('000000' to 'ffffff') to RGB red = int(hueval[0:2], 16) #red green = int(hueval[2:4], 16) #green blue = int(hueval[4:6], 16) #blue xy = self._rgb2xy(red, green, blue) return {'on': True, 'xy': xy} else: return None elif huecmd == 'eft': if hueval == 'colorloop' or hueval == 'none': return {'on': True, 'effect': hueval} else: return None def update_status(self): lights = self.interface.get_light_objects('id') for d in self._devices: print("Getting status for HUE -> ", d.address) if lights[int(d.address[1:])].on == True: bri = int( round( int(lights[int(d.address[1:])].brightness) / 255.0 * 100)) contact = (Command.LEVEL, bri) else: contact = Command.OFF self._logger.debug('Light L{0} status -> {1}'.format( d.address, contact)) self._onCommand(address="{0}".format(d.address), command=contact) def _check_range(self, cmd, val, minv, maxv): if val > maxv or val < minv: self._logger.error( "hue cannot set {level} beyond {mn} - {mx}".format( level=cmd, mn=minv, mx=maxv, )) return False else: return True def _rgb2xy(self, red, green, blue): # Returns xy point containing the closest available gamut colour (cie 1931) r = ((red + 0.055) / (1.0 + 0.055))**2.4 if (red > 0.04045) else (red / 12.92) g = ((green + 0.055) / (1.0 + 0.055))**2.4 if (green > 0.04045) else (green / 12.92) b = ((blue + 0.055) / (1.0 + 0.055))**2.4 if (blue > 0.04045) else (blue / 12.92) x = r * 0.4360747 + g * 0.3850649 + b * 0.0930804 y = r * 0.2225045 + g * 0.7168786 + b * 0.0406169 z = r * 0.0139322 + g * 0.0971045 + b * 0.7141733 if x + y + z == 0: cx = cy = 0 else: cx = x / (x + y + z) cy = y / (x + y + z) # Check if the given xy value is within the colour reach of our lamps. xyPoint = cx, cy, return xyPoint def version(self): self._logger.info("Philips HUE Pytomation driver version " + self.VERSION + '\n')
12.92) X = r * 0.664511 + g * 0.154324 + b * 0.162028 Y = r * 0.283881 + g * 0.668433 + b * 0.047685 Z = r * 0.000088 + g * 0.072310 + b * 0.986039 cx = X / (X + Y + Z) cy = Y / (X + Y + Z) return [cx, cy] # 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) # print(b.get_api()) lights = b.get_light_objects() print(lights) while True: b.set_group(1, 'bri', 100) b.set_group(1, 'on', True) b.set_group(1, 'xy', rgb_to_xy(255, 255, 255)) #White sleep(1) b.set_group(1, 'xy', rgb_to_xy(0, 255, 0)) # Green sleep(1) b.set_group(1, 'xy', rgb_to_xy(0, 0, 255)) # Blue sleep(1)
import time from phue import Bridge if __name__ == "__main__": hue_bridge = Bridge("192.168.0.58") dim_command = {'transitiontime' : 10, 'on' : True, 'bri' : 25} bright_command = {'transitiontime' : 40, 'on' : True, 'bri' : 230} playStatus = 0 revisionNumber = 1 while (True): newStatus = isPlaying.get_status(revisionNumber, 1) newPlayStatus = isPlaying.play_status(newStatus) oldRevisionNumber = revisionNumber revisionNumber = isPlaying.revision_number(newStatus) if (newPlayStatus != playStatus): playStatus = newPlayStatus if (playStatus == 4): hue_bridge.set_group(1, dim_command) print "playing" elif (playStatus == 3): hue_bridge.set_group(1, bright_command) print "paused" else: print "unknown: {}".format(playStatus) revisionNumber = oldRevisionNumber
class HueWrapper: def __init__(self, bridge_ip): """ :param bridge_ip: ip address of the hue bridge """ self.bridge = Bridge(bridge_ip) # first time we run, we have to press the physical button on the bridge device self.bridge.connect() lights = self.bridge.lights # Print light names print("found the following lights on bridge {}".format(bridge_ip)) for l in lights: print(l.name) @retry(wait=wait_exponential(min=1, max=6), stop=stop_after_attempt(32)) def is_group_on(self, group): """ Checks whether the specified group is on. :param group: :return: True iff the specified group is on. """ return self.bridge.get_group(group, "on") @retry(wait=wait_exponential(min=1, max=6), stop=stop_after_attempt(32)) def turn_group_off(self, group): """ Turns off the specified group. :param group: :return: """ self.bridge.set_group(group, "on", False) @retry(wait=wait_exponential(min=1, max=6), stop=stop_after_attempt(32)) def turn_group_on(self, group): """ Turns on the specified group. :param group: :return: """ self.bridge.set_group(group, "on", True) @retry(wait=wait_exponential(min=1, max=6), stop=stop_after_attempt(32)) def set_light_group_brightness(self, group, brightness_pct): """ Sets the brightness for the specified light group. Note that setting brightness to 0 will not turn off the light. :param group: :param brightness_pct: :return: """ self.bridge.set_group(group, 'bri', self.brightness_from_pct(brightness_pct)) @retry(wait=wait_exponential(min=1, max=6), stop=stop_after_attempt(32)) def set_light_brightness(self, light, brightness_pct): """ Sets the brightness for the specified light. Note that setting brightness to 0 will not turn off the light. :param light: :param brightness_pct: :return: """ self.bridge.set_light(light, 'bri', self.brightness_from_pct(brightness_pct)) @staticmethod def brightness_from_pct(brightness_pct): """ Converts an integer representing percentage into a value acceptable for hue api :param brightness_pct: :return: """ return int(float(brightness_pct) / 100 * 254)
#startColorLoop() #t.sleep(30) #stopColorLoop() #setDayScene() now = datetime.now() sunset = sun['sunset'] dusk = sun['dusk'] sunrise = sun['sunrise'] while True: now = datetime.now() if (now.hour == sunset.hour and now.minute == (sunset.minute - 15)): startColorLoop() time.sleep(60) if (now.hour == dusk.hour and now.minute == (dusk.minute - 15)): stopColorLoop() setDayScene() if (now.hour == 0 and now.minute == 1): setDayScene() if (now.hour == sunrise.hour and now.minute == (sunrise.minute + 15)): b.set_group(1, 'on', False)
class hueControl: def __init__(self): self.cIntensity = 175 self.fIntensity = 254 self.nIntensity = 128 # self.tTime = 50 self.nDelay = 5 self.red = [0.6901, 0.3076] self.magenta = [0.4343, 0.1936] self.blue = [0.1541, 0.0836] self.lblue = [0.1695, 0.3364] self.green = [0.2073, 0.6531] self.yellow = [0.4898, 0.4761] self.orange = [0.5706, 0.4078] self.b = Bridge('10.142.1.114') self.b.get_api() def updateLR(self, command): self.b.set_group(4, command) def updateDoor(self, command): self.b.set_group(5, command) def updateHW(self, command): self.b.set_group(6, command) def updateKitchen(self, command): self.b.set_group(2, command) def flashLights(self, color, delay, seconds): command = {'transitiontime': 1, 'xy': color, 'bri': self.fIntensity} self.b.set_group(0, command) for i in range(1, (seconds + 1)): command = {'transitiontime': 1, 'on': False} self.b.set_group(0, command) time.sleep(delay) command = {'transitiontime': 1, 'on': True, 'bri': self.fIntensity} self.b.set_group(0, command) time.sleep(delay) def advanceAsOne(self, tTime): lrColor = self.b.get_light(10, 'xy') if lrColor == self.red: lrCommand = { 'transitiontime': tTime, 'xy': self.magenta, 'bri': self.nIntensity } elif lrColor == self.magenta: lrCommand = { 'transitiontime': tTime, 'xy': self.blue, 'bri': self.nIntensity } elif lrColor == self.blue: lrCommand = { 'transitiontime': tTime, 'xy': self.lblue, 'bri': self.nIntensity } elif lrColor == self.lblue: lrCommand = { 'transitiontime': tTime, 'xy': self.green, 'bri': self.nIntensity } elif lrColor == self.green: lrCommand = { 'transitiontime': tTime, 'xy': self.yellow, 'bri': self.nIntensity } elif lrColor == self.yellow: lrCommand = { 'transitiontime': tTime, 'xy': self.orange, 'bri': self.nIntensity } else: lrCommand = { 'transitiontime': tTime, 'xy': self.red, 'bri': self.nIntensity } self.b.set_group(0, lrCommand) def advanceLights(self, tTime): lrColor = self.b.get_light(10, 'xy') if lrColor == self.red: lrCommand = { 'transitiontime': tTime, 'xy': self.magenta, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.blue, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.lblue, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.green, 'bri': self.nIntensity } elif lrColor == self.magenta: lrCommand = { 'transitiontime': tTime, 'xy': self.blue, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.lblue, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.green, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.yellow, 'bri': self.nIntensity } elif lrColor == self.blue: lrCommand = { 'transitiontime': tTime, 'xy': self.lblue, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.green, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.yellow, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.orange, 'bri': self.nIntensity } elif lrColor == self.lblue: lrCommand = { 'transitiontime': tTime, 'xy': self.green, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.yellow, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.orange, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.red, 'bri': self.nIntensity } elif lrColor == self.green: lrCommand = { 'transitiontime': tTime, 'xy': self.yellow, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.orange, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.red, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.magenta, 'bri': self.nIntensity } elif lrColor == self.yellow: lrCommand = { 'transitiontime': tTime, 'xy': self.orange, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.red, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.magenta, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.blue, 'bri': self.nIntensity } else: lrCommand = { 'transitiontime': tTime, 'xy': self.red, 'bri': self.nIntensity } doorCommand = { 'transitiontime': tTime, 'xy': self.magenta, 'bri': self.nIntensity } hwCommand = { 'transitiontime': tTime, 'xy': self.blue, 'bri': self.nIntensity } kitchenCommand = { 'transitiontime': tTime, 'xy': self.lblue, 'bri': self.nIntensity } self.updateLR(lrCommand) self.updateDoor(doorCommand) self.updateHW(hwCommand) self.updateKitchen(kitchenCommand)
# print( b.get_api() ) print("\n\n") # Prints if light 1 is on or not # print( b.get_light(1, 'on') ) # artery light group GROUP = 3 artery_lights = b.get_group(GROUP, 'lights') artery_lights = list(map(lambda l: int(l), artery_lights)) print(artery_lights) b.set_group(GROUP, 'on', True) red = [0.648427, 0.330856] # red: 255, 0, 0 green = [0.330853, 0.586362] # green: 65, 210, 27 while True: key = getch.getch() print(key) if key == ' ': color = (random.random(), random.random()) print('changing to') print(color) b.set_light(artery_lights[0], { 'transitiontime': 0, 'xy': color, 'bri': 254
distance = radius outer #direction left = sin(longi) cos(lat2) right = (cos(lat1) sin(lat2)) - (sin(lat1) cos(lat2) cos(longi)) direction = atan2(left, right) direction = degrees(direction) direction = (direction + 360) % 360 card = cardinalDirection(direction) print(Distance %.2f KilometersnBearing %.2f° (%s) % (distance, direction, card)) # Main def main() device = XBeeDevice(PORT, BAUD_RATE) b.connect() b.create_group('RGB', [1,2,3]) b.set_group(1, green) currentTime = time.time() targetTime = time.time() try device.open() while(True) #light reset if targetTime time.time() b.set_group(1, green) # Receive Data and Parse def data_receive_callback(xbee_message) address = xbee_message.remote_device.get_64bit_addr() message = xbee_message.data.decode() print(From %s %s % (address, message))
'transitiontime': light.transitiontime, 'on': light.on, 'effect': light.effect, 'saturation': light.saturation, 'brightness': light.brightness, 'xy': light.xy } return command bridge = Bridge(BRIDGE_IP) bridge.connect() GROUP_ID = bridge.get_group_id_by_name(GROUP_NAME) bedroom_light_ids = bridge.get_group(GROUP_NAME,'lights') lights = bridge.get_light_objects('id') print("Getting Lights") backup_lights = [] for x in bedroom_light_ids: light_id = int(x) id_command = (light_id, get_light_state(lights[light_id])) print("Backing up: " + str(light_id)) backup_lights.append(id_command) time.sleep(1) print("Turning off lights") bridge.set_group(1, 'on', False) time.sleep(3) print("Restoring lights") for id, command in backup_lights: bridge.set_light(id, command)
# assume no configured room roomnum = 0 roomnums = None if args.room: roomnum = getroomnumber(args.room) if args.rooms: print args.rooms roomnums = getroomnumbers(args.rooms) print roomnums if args.on: if roomnum > 0: b.set_group(roomnum, 'on', True) if args.brightness > 0: b.set_group(roomnum, 'bri', args.brightness) elif roomnums: for num in roomnums: b.set_group(num, 'on', True) if args.brightness > 0: b.set_group(num, 'bri', args.brightness) else: if args.brightness >= 0: b.set_group(roomnum, 'bri', args.brightness) if args.off: if roomnum > 0: b.set_group(roomnum, 'on', False)
class LightHuePlugin(LightPlugin): """ Philips Hue lights plugin. Requires: * **phue** (``pip install phue``) """ MAX_BRI = 255 MAX_SAT = 255 MAX_HUE = 65535 ANIMATION_CTRL_QUEUE_NAME = 'platypush/light/hue/AnimationCtrl' _BRIDGE_RECONNECT_SECONDS = 5 _MAX_RECONNECT_TRIES = 5 class Animation(Enum): COLOR_TRANSITION = 'color_transition' BLINK = 'blink' def __eq__(self, other): if isinstance(other, str): return self.value == other elif isinstance(other, self.__class__): return self == other def __init__(self, bridge, lights=None, groups=None): """ :param bridge: Bridge address or hostname :type bridge: str :param lights: Default lights to be controlled (default: all) :type lights: list[str] :param groups Default groups to be controlled (default: all) :type groups: list[str] """ super().__init__() self.bridge_address = bridge self.bridge = None self.logger.info('Initializing Hue lights plugin - bridge: "{}"'.format(self.bridge_address)) self.connect() self.lights = []; self.groups = [] if lights: self.lights = lights elif groups: self.groups = groups self._expand_groups() else: self.lights = [l.name for l in self.bridge.lights] self.redis = None self.animation_thread = None self.animations = {} self._init_animations() self.logger.info('Configured lights: "{}"'. format(self.lights)) def _expand_groups(self): groups = [g for g in self.bridge.groups if g.name in self.groups] for g in groups: for l in g.lights: self.lights += [l.name] def _init_animations(self): self.animations = { 'groups': {}, 'lights': {}, } for g in self.bridge.groups: self.animations['groups'][g.group_id] = None for l in self.bridge.lights: self.animations['lights'][l.light_id] = None @action def connect(self): """ Connect to the configured Hue bridge. If the device hasn't been paired yet, uncomment the ``.connect()`` and ``.get_api()`` lines and retry after clicking the pairing button on your bridge. """ # Lazy init if not self.bridge: from phue import Bridge, PhueRegistrationException success = False n_tries = 0 while not success: try: n_tries += 1 self.bridge = Bridge(self.bridge_address) success = True except PhueRegistrationException as e: self.logger.warning('Bridge registration error: {}'. format(str(e))) if n_tries >= self._MAX_RECONNECT_TRIES: self.logger.error(('Bridge registration failed after ' + '{} attempts').format(n_tries)) break time.sleep(self._BRIDGE_RECONNECT_SECONDS) self.logger.info('Bridge connected') self.get_scenes() else: self.logger.info('Bridge already connected') @action def get_scenes(self): """ Get the available scenes on the devices. :returns: The scenes configured on the bridge. Example output:: { "scene-id-1": { "name": "Scene 1", "lights": [ "1", "3" ], "owner": "owner-id", "recycle": true, "locked": false, "appdata": {}, "picture": "", "lastupdated": "2018-06-01T00:00:00", "version": 1 } } """ return self.bridge.get_scene() @action def get_lights(self): """ Get the configured lights. :returns: List of available lights as id->dict. Example:: { "1": { "state": { "on": true, "bri": 254, "hue": 1532, "sat": 215, "effect": "none", "xy": [ 0.6163, 0.3403 ], "ct": 153, "alert": "none", "colormode": "hs", "reachable": true }, "type": "Extended color light", "name": "Lightbulb 1", "modelid": "LCT001", "manufacturername": "Philips", "uniqueid": "00:11:22:33:44:55:66:77-88", "swversion": "5.105.0.21169" } } """ return self.bridge.get_light() @action def get_groups(self): """ Get the list of configured light groups. :returns: List of configured light groups as id->dict. Example:: { "1": { "name": "Living Room", "lights": [ "16", "13", "12", "11", "10", "9", "1", "3" ], "type": "Room", "state": { "all_on": true, "any_on": true }, "class": "Living room", "action": { "on": true, "bri": 241, "hue": 37947, "sat": 221, "effect": "none", "xy": [ 0.2844, 0.2609 ], "ct": 153, "alert": "none", "colormode": "hs" } } } """ return self.bridge.get_group() @action def get_animations(self): """ Get the list of running light animations. :returns: dict. Structure:: { "groups": { "id_1": { "type": "color_transition", "hue_range": [0,65535], "sat_range": [0,255], "bri_range": [0,255], "hue_step": 10, "sat_step": 10, "bri_step": 2, "transition_seconds": 2 } }, "lights": { "id_1": {} } } """ return self.animations def _exec(self, attr, *args, **kwargs): try: self.connect() self.stop_animation() except Exception as e: # Reset bridge connection self.bridge = None raise e lights = []; groups = [] if 'lights' in kwargs: lights = kwargs.pop('lights').split(',').strip() \ if isinstance(lights, str) else kwargs.pop('lights') if 'groups' in kwargs: groups = kwargs.pop('groups').split(',').strip() \ if isinstance(groups, str) else kwargs.pop('groups') if not lights and not groups: lights = self.lights groups = self.groups if not self.bridge: self.connect() try: if attr == 'scene': self.bridge.run_scene(groups[0], kwargs.pop('name')) else: if groups: self.bridge.set_group(groups, attr, *args, **kwargs) if lights: self.bridge.set_light(lights, attr, *args, **kwargs) except Exception as e: # Reset bridge connection self.bridge = None raise e @action def set_light(self, light, **kwargs): """ Set a light (or lights) property. :param light: Light or lights to set. Can be a string representing the light name, a light object, a list of string, or a list of light objects. :param kwargs: key-value list of parameters to set. Example call:: { "type": "request", "target": "hostname", "action": "light.hue.set_light", "args": { "light": "Bulb 1", "sat": 255 } } """ self.connect() self.bridge.set_light(light, **kwargs) @action def set_group(self, group, **kwargs): """ Set a group (or groups) property. :param group: Group or groups to set. Can be a string representing the group name, a group object, a list of strings, or a list of group objects. :param kwargs: key-value list of parameters to set. Example call:: { "type": "request", "target": "hostname", "action": "light.hue.set_group", "args": { "light": "Living Room", "sat": 255 } } """ self.connect() self.bridge.set_group(group, **kwargs) @action def on(self, lights=None, groups=None, **kwargs): """ Turn lights/groups on. :param lights: Lights to turn on (names or light objects). Default: plugin default lights :param groups: Groups to turn on (names or group objects). Default: plugin default groups """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('on', True, lights=lights, groups=groups, **kwargs) @action def off(self, lights=None, groups=None, **kwargs): """ Turn lights/groups off. :param lights: Lights to turn off (names or light objects). Default: plugin default lights :param groups: Groups to turn off (names or group objects). Default: plugin default groups """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('on', False, lights=lights, groups=groups, **kwargs) @action def toggle(self, lights=None, groups=None, **kwargs): """ Toggle lights/groups on/off. :param lights: Lights to turn off (names or light objects). Default: plugin default lights :param groups: Groups to turn off (names or group objects). Default: plugin default groups """ if groups is None: groups = [] if lights is None: lights = [] lights_on = [] lights_off = [] groups_on = [] groups_off = [] if groups: all_groups = self.bridge.get_group().values() groups_on = [ group['name'] for group in all_groups if group['name'] in groups and group['state']['any_on'] is True ] groups_off = [ group['name'] for group in all_groups if group['name'] in groups and group['state']['any_on'] is False ] if not groups and not lights: lights = self.lights if lights: all_lights = self.bridge.get_light().values() lights_on = [ light['name'] for light in all_lights if light['name'] in lights and light['state']['on'] is True ] lights_off = [ light['name'] for light in all_lights if light['name'] in lights and light['state']['on'] is False ] if lights_on or groups_on: self._exec('on', False, lights=lights_on, groups=groups_on, **kwargs) if lights_off or groups_off: self._exec('on', True, lights=lights_off, groups=groups_off, **kwargs) @action def bri(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups brightness. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param value: Brightness value (range: 0-255) """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('bri', int(value) % (self.MAX_BRI+1), lights=lights, groups=groups, **kwargs) @action def sat(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups saturation. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param value: Saturation value (range: 0-255) """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('sat', int(value) % (self.MAX_SAT+1), lights=lights, groups=groups, **kwargs) @action def hue(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups color hue. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param value: Hue value (range: 0-65535) """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('hue', int(value) % (self.MAX_HUE+1), lights=lights, groups=groups, **kwargs) @action def xy(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups XY colors. :param value: xY value :type value: list[float] containing the two values """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('xy', value, lights=lights, groups=groups, **kwargs) @action def ct(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups color temperature. :param value: Temperature value (range: 0-255) :type value: int """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('ct', value, lights=lights, groups=groups, **kwargs) @action def delta_bri(self, delta, lights=None, groups=None, **kwargs): """ Change lights/groups brightness by a delta [-100, 100] compared to the current state. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param delta: Brightness delta value (range: -100, 100) """ if groups is None: groups = [] if lights is None: lights = [] bri = 0 if lights: bri = statistics.mean([ light['state']['bri'] for light in self.bridge.get_light().values() if light['name'] in lights ]) elif groups: bri = statistics.mean([ group['action']['bri'] for group in self.bridge.get_group().values() if group['name'] in groups ]) else: bri = statistics.mean([ light['state']['bri'] for light in self.bridge.get_light().values() if light['name'] in self.lights ]) delta *= (self.MAX_BRI/100) if bri+delta < 0: bri = 0 elif bri+delta > self.MAX_BRI: bri = self.MAX_BRI else: bri += delta return self._exec('bri', int(bri), lights=lights, groups=groups, **kwargs) @action def delta_sat(self, delta, lights=None, groups=None, **kwargs): """ Change lights/groups saturation by a delta [-100, 100] compared to the current state. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param delta: Saturation delta value (range: -100, 100) """ if groups is None: groups = [] if lights is None: lights = [] sat = 0 if lights: sat = statistics.mean([ light['state']['sat'] for light in self.bridge.get_light().values() if light['name'] in lights ]) elif groups: sat = statistics.mean([ group['action']['sat'] for group in self.bridge.get_group().values() if group['name'] in groups ]) else: sat = statistics.mean([ light['state']['sat'] for light in self.bridge.get_light().values() if light['name'] in self.lights ]) delta *= (self.MAX_SAT/100) if sat+delta < 0: sat = 0 elif sat+delta > self.MAX_SAT: sat = self.MAX_SAT else: sat += delta return self._exec('sat', int(sat), lights=lights, groups=groups, **kwargs) @action def delta_hue(self, delta, lights=None, groups=None, **kwargs): """ Change lights/groups hue by a delta [-100, 100] compared to the current state. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param delta: Hue delta value (range: -100, 100) """ if groups is None: groups = [] if lights is None: lights = [] hue = 0 if lights: hue = statistics.mean([ light['state']['hue'] for light in self.bridge.get_light().values() if light['name'] in lights ]) elif groups: hue = statistics.mean([ group['action']['hue'] for group in self.bridge.get_group().values() if group['name'] in groups ]) else: hue = statistics.mean([ light['state']['hue'] for light in self.bridge.get_light().values() if light['name'] in self.lights ]) delta *= (self.MAX_HUE/100) if hue+delta < 0: hue = 0 elif hue+delta > self.MAX_HUE: hue = self.MAX_HUE else: hue += delta return self._exec('hue', int(hue), lights=lights, groups=groups, **kwargs) @action def scene(self, name, lights=None, groups=None, **kwargs): """ Set a scene by name. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param name: Name of the scene """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('scene', name=name, lights=lights, groups=groups, **kwargs) @action def is_animation_running(self): """ :returns: True if there is an animation running, false otherwise. """ return self.animation_thread is not None @action def stop_animation(self): """ Stop a running animation if any """ if self.animation_thread and self.animation_thread.is_alive(): redis = self._get_redis() redis.rpush(self.ANIMATION_CTRL_QUEUE_NAME, 'STOP') self._init_animations() @action def animate(self, animation, duration=None, hue_range=None, sat_range=None, bri_range=None, lights=None, groups=None, hue_step=1000, sat_step=2, bri_step=1, transition_seconds=1.0): """ Run a lights animation. :param animation: Animation name. Supported types: **color_transition** and **blink** :type animation: str :param duration: Animation duration in seconds (default: None, i.e. continue until stop) :type duration: float :param hue_range: If you selected a color color_transition.html, this will specify the hue range of your color color_transition.html. Default: [0, 65535] :type hue_range: list[int] :param sat_range: If you selected a color color_transition.html, this will specify the saturation range of your color color_transition.html. Default: [0, 255] :type sat_range: list[int] :param bri_range: If you selected a color color_transition.html, this will specify the brightness range of your color color_transition.html. Default: [254, 255] :type bri_range: list[int] :param lights: Lights to control (names, IDs or light objects). Default: plugin default lights :param groups: Groups to control (names, IDs or group objects). Default: plugin default groups :param hue_step: If you selected a color color_transition.html, this will specify by how much the color hue will change between iterations. Default: 1000 :type hue_step: int :param sat_step: If you selected a color color_transition.html, this will specify by how much the saturation will change between iterations. Default: 2 :type sat_step: int :param bri_step: If you selected a color color_transition.html, this will specify by how much the brightness will change between iterations. Default: 1 :type bri_step: int :param transition_seconds: Time between two transitions or blinks in seconds. Default: 1.0 :type transition_seconds: float """ if bri_range is None: bri_range = [self.MAX_BRI - 1, self.MAX_BRI] if sat_range is None: sat_range = [0, self.MAX_SAT] if hue_range is None: hue_range = [0, self.MAX_HUE] if groups: groups = [g for g in self.bridge.groups if g.name in groups or g.group_id in groups] lights = lights or [] for g in groups: lights.extend([l.name for l in g.lights]) elif lights: lights = [l.name for l in self.bridge.lights if l.name in lights or l.light_id in lights] else: lights = self.lights info = { 'type': animation, 'duration': duration, 'hue_range': hue_range, 'sat_range': sat_range, 'bri_range': bri_range, 'hue_step': hue_step, 'sat_step': sat_step, 'bri_step': bri_step, 'transition_seconds': transition_seconds, } if groups: for g in groups: self.animations['groups'][g.group_id] = info for l in self.bridge.lights: if l.name in lights: self.animations['lights'][l.light_id] = info def _initialize_light_attrs(lights): if animation == self.Animation.COLOR_TRANSITION: return { l: { 'hue': random.randint(hue_range[0], hue_range[1]), 'sat': random.randint(sat_range[0], sat_range[1]), 'bri': random.randint(bri_range[0], bri_range[1]), } for l in lights } elif animation == self.Animation.BLINK: return { l: { 'on': True, 'bri': self.MAX_BRI, 'transitiontime': 0, } for l in lights } def _next_light_attrs(lights): if animation == self.Animation.COLOR_TRANSITION: for (light, attrs) in lights.items(): for (attr, value) in attrs.items(): attr_range = [0,0] attr_step = 0 if attr == 'hue': attr_range = hue_range attr_step = hue_step elif attr == 'bri': attr_range = bri_range attr_step = bri_step elif attr == 'sat': attr_range = sat_range attr_step = sat_step lights[light][attr] = ((value - attr_range[0] + attr_step) % (attr_range[1]-attr_range[0]+1)) + \ attr_range[0] elif animation == self.Animation.BLINK: lights = { light: { 'on': False if attrs['on'] else True, 'bri': self.MAX_BRI, 'transitiontime': 0, } for (light, attrs) in lights.items() } return lights def _should_stop(): try: redis = self._get_redis(transition_seconds) redis.blpop(self.ANIMATION_CTRL_QUEUE_NAME) return True except QueueTimeoutError: return False def _animate_thread(lights): set_thread_name('HueAnimate') self.logger.info('Starting {} animation'.format( animation, (lights or groups))) lights = _initialize_light_attrs(lights) animation_start_time = time.time() stop_animation = False while True: if stop_animation or \ (duration and time.time() - animation_start_time > duration): break try: if animation == self.Animation.COLOR_TRANSITION: for (light, attrs) in lights.items(): self.logger.debug('Setting {} to {}'.format(light, attrs)) self.bridge.set_light(light, attrs) stop_animation = _should_stop() if stop_animation: break elif animation == self.Animation.BLINK: conf = lights[list(lights.keys())[0]] self.logger.debug('Setting lights to {}'.format(conf)) if groups: self.bridge.set_group([g.name for g in groups], conf) else: self.bridge.set_light(lights.keys(), conf) stop_animation = _should_stop() if stop_animation: break except Exception as e: self.logger.warning(e) time.sleep(2) lights = _next_light_attrs(lights) self.logger.info('Stopping animation') self.animation_thread = None self.redis = None self.stop_animation() self.animation_thread = Thread(target=_animate_thread, name='HueAnimate', args=(lights,)) self.animation_thread.start() def _get_redis(self, socket_timeout=1.0): if not self.redis: redis_args = get_backend('redis').redis_args redis_args['socket_timeout'] = socket_timeout self.redis = Redis(**redis_args) return self.redis def status(self): # TODO pass
import RPi.GPIO as GPIO import time from phue import Bridge b = Bridge('<ip of bridge here>') #b.connect() print(b.get_group(1)) b.set_group(1, 'on', False) on = False GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) button_two_clicks = 0 default_warm = 400 default_cool = 153 def set_scene(scene_number): print('Set Scene %d' % scene_number) if scene_number == 0: b.set_group(1, 'ct', default_warm) b.set_group(1, 'bri', 254) if scene_number == 1: b.set_group(1, 'ct', default_warm) b.set_group(1, 'bri', 127) if scene_number == 2: b.set_group(1, 'ct', default_warm) b.set_group(1, 'bri', 63)
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()
b.set_light(b2, 'hue', 13088) b.set_light(b3, 'hue', 13088) while (newbri <= 150): b.set_light(b2, 'bri', newbri, transitiontime=300) b.set_light(b3, 'bri', newbri, transitiontime=300) if newbri <= 100: b.set_light(b1, 'bri', newbri, transitiontime=300) b.set_light(b3, 'bri', newbri, transitiontime=300) newbri = newbri + 10 sleep(30) print 'Colored Lights Done' #Turn on Lux Groups b.set_group(g1, 'on', True) b.set_group(g1, 'bri', 0) b.set_group(g2, 'on', True) b.set_group(g2, 'bri', 0) #Start Brightness on Lux newbri = 0 while (newbri <= 150): b.set_group(g1, 'bri', newbri, transitiontime=300) if newbri <= 100: b.set_group(g2, 'bri', newbri, transitiontime=300) newbri = newbri + 10 sleep(30) print 'Lux Done'
class BridgeContainer(): def __init__(self, transitiontime=50, individual=None, ip=None, dummy=False): if dummy: self.mybridge = DummyBridge() self.individual = 1 self.transitiontime = 50 return self.mybridge = None while not self.mybridge: try: if not ip: # try to find a bridge with meethue api logging.debug("will try finding the hue bridge") print "1111" localbridge = json.loads(urlopen(' /nupnp').read()) ip = localbridge[0]["internalipaddress"] logging.info('connecting to localbridge at ' + str(ip)) print "????" self.mybridge = Bridge(ip) self.mybridge.connect() self.mybridge.get_api() except Exception as e: logging.warn( 'failed to connect to HUE server did you push the button?') self.mybridge = None sleep(10) self.transitiontime = transitiontime self.individual = None if individual: self.individual = int(individual) self.alert() def setTransitionTime(self, value): # this should be the transistion time in seconds self.transitiontime = int(10 * float(value)) def sendAll(self, **options): lamp = self.individual or 0 for k, v in options.iteritems(): if v is None: del (options[k]) if self.transitiontime >= 0: options['transitiontime'] = self.transitiontime if self.individual: self.mybridge.set_light(self.individual, options) else: self.mybridge.set_group(0, options) def getAll(self): # returns dictionary with all values # {"state": {"on":true,"bri":254,"hue":45000,"sat":253,"xy":[0.1914,0.0879],"ct":500,"alert":"select","effect":"none","colormode":"hs","reachable":true}, # "type": "Extended color light", "name": "Hue Lamp", "modelid": "LCT001", "swversion": "66009663", "pointsymbol": { "1":"none", "2":"none", "3":"none", "4":"none", "5":"none", "6":"none", "7":"none", "8":"none" }} return self.mybridge.get_light(self.individual)['state'] def setEffect(self, value): self.sendAll(effect=effect) def setHue(self, value): self.sendAll(hue=value) def setBri(self, value): self.sendAll(bri=value) def setSat(self, value): self.sendAll(sat=value) def get_state(self): if self.individual: logging.debug(str(self.mybridge.get_light(self.individual))) return self.mybridge.get_light(self.individual)['state'] def toggle(self, dummy=None): if self.individual: if self.mybridge.get_light(self.individual)['state']['on']: self.mybridge.set_light(self.individual, {'on': False}) else: self.mybridge.set_light(self.individual, {'on': True}) else: if self.mybridge.get_group(0)['action']['on']: self.mybridge.set_group(0, {'on': False}) else: self.mybridge.set_group(0, {'on': True}) def setOn(self, value): if self.individual: if value: self.mybridge.set_light(self.individual, {'on': True}) else: self.mybridge.set_light(self.individual, {'on': False}) def alert(self, dummy=None): if self.individual: self.mybridge.set_light(self.individual, {'alert': 'select'}) else: self.mybridge.set_group(0, {'alert': 'select'})
class HueController: def __init__(self): self.bridge = Bridge('192.168.1.107') # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented #bridge.connect() self.lights = self.bridge.get_light_objects() for light in self.lights: print(light.brightness) print(light.xy) self.state = 'off' self.on_off_toggle = False def set_off(self): try: self.stop_blink() self.bridge.set_group(1, 'on', False) self.state = 'off' except: pass def set_on(self): try: self.stop_blink() self.bridge.set_group(1, 'on', True) self.bridge.set_group(1, 'xy', [0.4578, 0.41]) self.bridge.set_group(1, 'brightness', 254) self.state = 'photo' except: pass def start_blink(self): try: self.keep_blinking = True self.blink_thread = threading.Thread(target=self._blink).start() except: pass def stop_blink(self): self.keep_blinking = False def _blink(self): try: while(self.keep_blinking): for light in self.lights: if self.on_off_toggle: light.transitiontime = 0 light.on = True light.xy = [random.random(),random.random()] else: light.transitiontime = 0 light.on = False time.sleep(0.05) self.on_off_toggle = not self.on_off_toggle if not self.keep_blinking: break except: pass
# sleep(2) # test_light.on = True # sleep(2) # test_light.on = False # sleep(2) print(b.groups) nb_group = b.groups #print(len(nb_group)) print(b.get_group_id_by_name('control_group')) #print(b.lights) #b.create_group('control_group', [3, 4, 5]) b.set_group(group_id='control_group', parameter='lights', value=[5]) gr0 = Group(b, 'control_group') gr0.on = True gr0.brightness = 254 gr0.colortemp_k = 3500 sleep(3) gr0.on = False b.set_group(group_id='control_group', parameter='lights', value=[3, 4]) gr0 = Group(b, 'control_group') gr0.on = True gr0.brightness = 254 gr0.colortemp_k = 3500 sleep(3) gr0.on = False
class HueController(object): def __init__(self): self.client = Client(connected_callback=self.connected) if BRIDGE_HOST: self.bridge = Bridge(ip=BRIDGE_HOST, username=BRIDGE_USERNAME) self.bridge.connect() else: self.logger.warning('Not connecting to bridge') self.arduino = Console() @property def logger(self): return logging.getLogger(__name__) def connected(self): self.logger.debug('connected to websocket') self.client.send('subscribe', { 'exchange': 'data', 'routing_key': 'zymbit.mood.#', }) def data(self, envelope): hexstr = envelope['params']['hex'] r, g, b = get_rgb_from_hex(hexstr) self.set_arduino_color(r, g, b) def handle_message(self): try: payload = self.client.recv() except WebSocketConnectionClosedException: # the connection is closed self._ws = None return if payload is None: self.logger.warning('got an empty payload') return try: data = json.loads(payload) except TypeError: self.logger.error('unable to load payload={}'.format(payload)) raise print 'data={}'.format(data) handler_fn = data.get('action') if handler_fn is None: self.logger.warning('no action in data={}'.format(data)) return handler = getattr(self, handler_fn, None) if handler is None: self.logger.warning('no handler for handler_fn={}'.format(handler_fn)) return return handler(data) @backoff.on_exception(backoff.expo, Disconnected, max_value=30) def loop(self): r, _, _ = select.select([self.client], [], [], 1.0) if self.client in r: self.handle_message() def run(self): while True: self.loop() def set_arduino_color(self, r, g, b): command = 'set_colors {} {} {}'.format(r, g, b) self.logger.debug('sending arduino command={}'.format(command)) self.arduino.send(command) def set_color(self, color): self.value = color self.bridge.set_group(1, 'hue', self.value)
'bri': roomstatus['action']['bri'], 'on': roomstatus['action']['on']}, transitiontime=0) time.sleep(defaultwaittime) def islampon(): global inalert, roomnumber result = False roomon = b.get_group(roomnumber) result = roomon['state']['any_on'] return result # ================================================================ #Main loop - keep going forever # ================================================================ while True: gesture = apds.gesture() if gesture == 0x01: b.set_group(roomnumber, 'on', True) print("on") if gesture == 0x02: b.set_group(roomnumber, 'on', False) print("off") if gesture == 0x03: if bright >= 10: bright -= 20 b.set_group(roomnumber, 'bri', bright) print(bright) print("Dimming") if gesture == 0x04: if bright <= 255: bright += 20 b.set_group(roomnumber, 'bri', bright) print (bright)
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 turnOff(): logging.basicConfig() b = Bridge(ip) b.set_group(1, 'on', False)
# For reference, the hubs are on the UW network at these IP addresses # Lab Green 172.28.219.225 # Lab Blue 172.28.219.235 # Lab Red 172.28.219.189 # Sieg Master 172.28.219.179 b = Bridge('172.28.219.225') #Lab Green # 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) #print(b.get_api()) lights = b.get_light_objects() for light in lights: print(light) light.transitiontime = 10 while True: for light in lights: light.on = True light.brightness = 255 b.set_group(1, 'hue', 10000) light.xy = [.5, .2] print(light.xy) sleep(.1) light.on = False sleep(.1)