def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='command') power_parser = subparsers.add_parser( 'power', help='set lights to on or off state' ) power_parser.add_argument('state', choices=('on', 'off')) bri_parser = subparsers.add_parser('bri', help='Set brightness level') bri_parser.add_argument('brightness', type=int) subparsers.add_parser('list', help='list available bulbs') parser.add_argument('--light', type=int) bridge_addr = get_bridge_ip_addr() bridge = Bridge(bridge_addr) bridge.connect() args = parser.parse_args() if args.command == 'power': set_light_attribute(bridge, args.light, 'on', args.state == 'on') elif args.command == 'bri': set_light_attribute(bridge, args.light, 'bri', args.brightness) elif args.command == 'list': list_lights(bridge)
class HueAPIClient(object): def __init__(self): pass def find_bridge(self): import hue.bridge_scanner as bridge_scanner while True: self.ip = bridge_scanner.get_bridge_ips()[0] if 0 < len(self.ip): break print('Bridge found ' + self.ip) self.bridge = Bridge(self.ip) def connect(self): self.bridge.connect() def on(self): lights = self.bridge.get_light_objects() for light in lights: light.on = True def off(self): lights = self.bridge.get_light_objects() for light in lights: light.on = False
class PhillipsHue(HAInterface): VERSION = '1.3' valid_commands = ('bri','hue','sat','ct','rgb','tr','eft') def __init__(self, *args, **kwargs): super(PhillipsHue, self).__init__(None, *args, **kwargs) # Instance should be hue = PhillipsHue(address = '192.168.0.2', poll=10) def _init(self, *args, **kwargs): super(PhillipsHue, self)._init(*args, **kwargs) self._iteration = 0 self._poll_secs = kwargs.get('poll', 60) self.last_status = {} # get the ip address and connect to the bridge self._ip = kwargs.get('address', None) print "Phillips HUE Bridge address -> {0}".format(self._ip) try: self.interface = Bridge(self._ip) self.interface.connect() self._logger.debug("[Hue] Connected to interface at {0}...\n".format(self._ip)) except Exception, 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()
class LightService: on = {'on': True, 'bri': 254, 'transitiontime': 0} off = {'on': False, 'bri': 0, 'transitiontime': 0} on_no_bri = {'on': True, 'bri': 0, 'transitiontime': 0} # off = {'on': False, 'transitiontime': 0} pink = {'on': True, 'transitiontime': 0, 'bri': 254, 'xy': [0.4149, 0.1776]} pink_end = {'on': True, 'transitiontime': 30, 'bri': 1, 'xy': [0.4149, 0.1776]} white = {'on': True, 'transitiontime': 0, 'bri': 254, 'xy': [0.3227,0.329]} red = {'on': True, 'transitiontime': 0, 'bri': 254, 'xy': [0.7, 0.2986]} red_dark = {'on': True, 'transitiontime': 0, 'bri': 20, 'xy': [0.7, 0.2986]} green_start = {'on': True, 'transitiontime': 0, 'bri': 1, 'xy': [0.214, 0.709]} green = {'on': True, 'transitiontime': 10, 'bri': 254, 'xy': [0.214, 0.709]} def __init__(self): self.bridge = Bridge('10.59.6.13') # 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.bridge.connect() # Get the bridge state (This returns the full dictionary that you can explore) #print b.get_api() @postpone def game_start(self): c = 0 # preset the color before we turn things on self.bridge.set_light([3,4], self.pink) self.bridge.set_light([3,4], self.on) while c < 8: self.bridge.set_light([3,4], self.pink) time.sleep(.5) self.bridge.set_light([3,4], self.white) time.sleep(.5) c += 1 self.bridge.set_light([3,4], self.off) @postpone def correct(self): self.bridge.set_light([3,4], self.green_start) self.bridge.set_light([3,4], self.green) time.sleep(2) self.bridge.set_light([3,4], self.off) @postpone def incorrect(self): c = 0 while c < 5: self.bridge.set_light([3,4], self.red) # self.bridge.set_light([3,4], self.on) time.sleep(.3) self.bridge.set_light([3,4], self.red_dark) time.sleep(.3) c += 1 self.bridge.set_light([3,4], self.off) @postpone def game_end(self): self.bridge.set_light([3,4], self.pink) self.bridge.set_light([3,4], self.pink_end) time.sleep(3) self.bridge.set_light([3,4], self.off)
def set_all_light(self): global FAILURES_COUNT b = Bridge(IP_BRIDGE) try: b.connect() lights = b.lights for light in lights: xy_delta = self.get_xy_delta(light) threshold = self.is_start_pattern(light) if xy_delta > 10 and threshold < MATCHING_THRESHOLD: logger.warning("The light in the {0} has been switched !".format(light.name)) #self.send_mail(EMAIL_SUBJECT, "The light in the {0} has been switched !".format(light.name)) print 'light connected' light.brightness = 207 light.colortemp = 459 light.colortemp_k = 2179 light.saturation = 209 light.saturation = 100 light.xy = OPTIMAL_XY except PhueRequestTimeout: logger.warning("PhueRequestTimeout - Could not connect with Bridge !!!") self.send_mail(EMAIL_SUBJECT, "No connection with bridge [{0}]".format(IP_BRIDGE) ) self.createConfig()
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)
def handle(text, mic, profile): bridgeip = profile['bridgeip'] b = Bridge(bridgeip) b.connect() lights = b.lights global message message = "" if "on" in text.lower(): for l in lights: l.on = True l.brightness = 254 message = "All Lights have been turned on" elif "off" in text.lower(): for l in lights: l.on = False message = "All Lights have been turned off." now = datetime.now() now_time = now.time() if now_time >= time(21,30) and now_time <= time(02,00): message += "Good Night"
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'))
def build(self): b = Bridge('192.168.0.100') b.connect() lights = b.lights root = GridLayout(cols=3) for i in lights: root.add_widget(Light(i)) return(root)
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()
class Hue(DriverBase): def __init__(self, num, ip, nameMap=None, **kwds): super().__init__(num, **kwds) if nameMap and len(nameMap) != self.numLEDs: raise ValueError( "nameMap must have the same number of entries as the number of LEDs.") self._bridge = Bridge(ip) self._bridge.connect() self._transitionTime = 0 if nameMap: self._lights = self._bridge.get_light_objects('name') self._ids = nameMap else: self._lights = self._bridge.get_light_objects('id') self._ids = [l for l in self._lights] if len(self._lights) < self.numLEDs: raise ValueError( "More LEDs were specified than there are available Hue lights.") self.setTransitionTime(0) # start with no transition time def setTransitionTime(self, time): if time < 0.0 or time > 30.0: raise ValueError( "Transition time must be between 0.0 and 30.0 seconds.") self._transitionTime = int(time * 10) def _mapRange(self, value, minFrom, maxFrom, minTo, maxTo): return minTo + (maxTo - minTo) * ((value - minFrom) / (maxFrom - minFrom)) def _rgb2hs(self, rgb): r = rgb[0] / 255.0 g = rgb[1] / 255.0 b = rgb[2] / 255.0 h, s, v = colorsys.rgb_to_hsv(r, g, b) h = int(self._mapRange(h, 0.0, 1.0, 0, 65535)) s = int(self._mapRange(s, 0.0, 1.0, 0, 254)) return (h, s) def _send_packet(self): for i in range(len(self._ids)): h, s = self._rgb2hs(self._colors[i + self._pos]) bri = min(254, self._brightness) if s == 0: bri = 0 cmd = {'on': s != 0, 'bri': bri, 'hue': h, 'saturation': s, 'transitiontime': self._transitionTime} self._bridge.set_light(self._ids[i], cmd)
def main(): parser = argparse.ArgumentParser(description='get a domain name') parser.add_argument('--bridge', help='ip/hostname of bridge', default='hue-bridge.lan', dest="br") parser.add_argument('--lids', "-l", help='light numbers', default=False, dest="ls", type=int, nargs='+') parser.add_argument('--lnams', "-n", help='light names', default=False, dest="lns", type=int, nargs='+') parser.add_argument('--on', "-1", help='turn on', action="store_true", default=False, dest="on") parser.add_argument('--off', "-0", help='turn off', action="store_true", default=False, dest="off") parser.add_argument('--colour', "-c", help='change colour', default='blue', dest="c") parser.add_argument('--brightness', "-b", help='change brightness', default='0', dest="b", type=int) parser.add_argument('--discover', "-d", help='show what lights there are', action="store_true", default=False, dest="p") args = parser.parse_args() b = Bridge(args.br) b.connect() if args.p: #print(json.dumps(b.get_light_objects('id') , sort_keys=True,indent=4, separators=(',', ': '))) pp = pprint.PrettyPrinter(indent=4) pp.pprint(b.get_light_objects('id') ) exit() #print b.get_api() lids = b.get_light_objects('id') lnams = b.get_light_objects('id') if args.off and args.on: exit("On and off are mutally exclusive") if args.ls and args.lns: exit("Names and ids are mutally exclusive") if args.off: print "turning lights", ', '.join(str(e) for e in args.ls), "off\n" if args.ls: for l in args.ls: lids[l].on = False if args.lns: for l in args.lns: lnams[l].on = False if args.on: print "turning lights", ', '.join(str(e) for e in args.ls), "on\n" if args.ls: for l in args.ls: lids[l].on = True if args.lns: for l in args.lns: lnams[l].on = True if args.c: print "c\n" if args.b: print "b\n" if args.ls: print "l:", args.ls
def hue_connect(): not_connected = True while(not_connected): try: bridge = Bridge('4908hue.eecs.umich.edu') bridge.connect() not_connected = False except: print("\nGo push the button on the hub to authorize this program. I'll wait.\n") raw_input("Hit enter when you're done. ") all_lights = bridge.get_light_objects() return all_lights
def initUI(self): global b b = Bridge("192.168.0.17") b.connect() count = 0 for l in b.lights: self.show_controls(l.name, l.brightness, l.hue, l.saturation, count) count += 1 self.statusBar() self.setGeometry(100, 400, 320, 185) self.setWindowTitle('hueqt') self.show()
def hue_connect(addr): bridge = None not_connected = True while(not_connected): try: bridge = Bridge(addr) bridge.connect() not_connected = False except: print("\nGo push the button on the hub to authorize this program. I'll wait.\n") raw_input("Hit enter when you're done. ") return bridge
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')
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 print_lamps(ip): b = Bridge(ip) b.connect() print '\033[1mName\t\tState\t\tBrightness\033[0m' print '---------------------------------------------------------' lights = b.lights for l in lights: if len(l.name) < 5: print l.name + '\t\t' + check_state_reverse(l.on) + "\t\t" + str(l.brightness) elif len(l.name) > 5 and len(l.name) < 10: print l.name + '\t' + check_state_reverse(l.on) + "\t\t" + str(l.brightness) elif len(l.name) >= 10: print l.name + '\t' + check_state_reverse(l.on) + "\t\t" + str(l.brightness)
class LightSkill(object): def __init__(self): self.bridge = Bridge('192.168.1.10') self.bridge.connect() self.intent = 'lightIntent' # define vocabulary self.light_keyword = [ "allume", "éteint", "baisse", "diminue", "augmente", "luminosité" ] self.room_keyword = [ "salon", "cuisine" ] # structure intent self.light_intent = IntentBuilder(self.intent)\ .require("LightKeyword")\ .require("RoomKeyword")\ .optionally("NumericValue")\ .build() def register(self, engine): for wk in self.light_keyword: engine.register_entity(wk, "LightKeyword") for wk in self.room_keyword: engine.register_entity(wk, "RoomKeyword") engine.register_regex_entity("(?P<NumericValue>\d+)") engine.register_intent_parser(self.light_intent) def process(self, json): room = json.get('RoomKeyword') if json.get('LightKeyword') == "allume": self.bridge.set_light(room, 'on', True) return "J'allume '%s'" % room if json.get('LightKeyword') == "éteint": self.bridge.set_light(room, 'on', False) return "J'éteins '%s'" % room if json.get('LightKeyword') == "baisse": bri = self.bridge.get_light(room).get('state').get('bri') self.bridge.set_light(room, 'bri', bri-20) return "J'ai diminué la lumière dans le '%s'" % room
def _get_bridge(): bridge = clique.context('bridge') if not bridge: bridge = Bridge() bridge.get_ip_address(set_result=True) try: bridge.connect() except: logging.exception("Failed to connect bridge.") return clique.context('bridge', bridge) return bridge
def main(): print "Push button on Bridge Now" #Check if there is already a config file createconfigs = os.path.exists("backendhue.conf") print createconfigs #DEBUG if createconfigs == True: #run main script with default configs print "True-Config File is present" #DEBUG #Add option to delete and reconfigure if createconfigs == False: #need to create configs and load to file hueaddress = raw_input("IP Address of your Phillips Hue Bridge:") b = Bridge(ip=hueaddress) # Enter bridge IP here. b.connect() #connect and pair to hub CreateConfiguration(hueaddress,b) print "False" #DEBUG
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') print(lights) if self.lightsOn(lights) == True: bridge.set_light([1,2,3,5], 'on', False) print('OFF') else: bridge.set_light([1,2,3,5], 'on', True) bridge.set_light([1,2,3,5], 'xy', [0.3227,0.329]) bridge.set_light([1,2,3,5], 'bri', 160) print('ON')
def init_bridge(ip=None, username=None): if ip == None: bridges = req.get('https://www.meethue.com/api/nupnp').json() selected = [x for x in bridges if '273a83' in x['id']][0] ip = selected['internalipaddress'] print(selected) b = Bridge(ip, username) # Enter bridge IP here. # If running for the first time, press button on bridge and run with b.connect() uncommented b.connect() try: lights = b.lights except: lights = b.lights_by_name return b
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 Hue(threading.Thread): def __init__(self, ip, dispatcher): threading.Thread.__init__(self) self.bridge = Bridge(ip) self.bridge.connect() self.dispatcher = dispatcher self.process = threading.Event() self.running = True self.commands = [] self.dispatcher.addRoute("hue", self.do) def run(self): while self._dispatch(): self.process.wait() def stop(self): self.running = False self.process.set() def do(self, command): self.commands.insert(0, command) self.process.set() def RGB2CIE(self, r, g, b): x = 0.4124*r + 0.3576*g + 0.1805*b y = 0.2126*r + 0.7152*g + 0.0722*b z = 0.0193*r + 0.1192*g + 0.9505*b return [x / (x + y + z), y / (x + y + z)] def _dispatch(self): while len(self.commands) > 0 and self.running: command = self.commands.pop() light = command.get('light') cmd = command.get('cmd') val = command.get('val') if cmd == 'xy' and isinstance(val, list) and len(val) == 3: val = self.RGB2CIE(val[0], val[1], val[2]) self.bridge.set_light(light, cmd, val) self.process.clear() return self.running
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 __init__(self, frame_listener): def lamp_controller(): while True: time.sleep(0.1) if self.frame_listener.get_confidence() > 0.1: hand_angle = self.frame_listener.get_hand_angle() prev_lamp = self.current_lamp if self.current_lamp == self.LEFT_LAMP_NBR and hand_angle > np.pi/2.0 + np.pi/8.0: self.current_lamp = self.RIGHT_LAMP_NBR elif self.current_lamp == self.RIGHT_LAMP_NBR and hand_angle < np.pi/2.0 - np.pi/8.0: self.current_lamp = self.LEFT_LAMP_NBR if prev_lamp != self.current_lamp: xy = b.get_light(prev_lamp, 'xy') b.set_light(prev_lamp, 'on', False) b.set_light(self.current_lamp, 'on', True) b.set_light(self.current_lamp, 'xy', xy) bri = self.get_current_brightness() lamp_on = b.get_light(self.current_lamp, 'on') if bri == 0: if lamp_on: b.set_light(self.current_lamp, 'on', False) else: if not lamp_on: b.set_light(self.current_lamp, 'on', True) b.set_light(self.current_lamp, 'bri', bri) new_finger_down = self.frame_listener.pop_new_finger_down_if_any() if not new_finger_down is None: b.lights[self.current_lamp - 1].xy = ColorHelper().getXYPointFromRGB(*self.colors[new_finger_down]) self.current_lamp = self.RIGHT_LAMP_NBR self.frame_listener = frame_listener b = Bridge(self.BRIDGE_IP) b.connect() b.set_light(self.LEFT_LAMP_NBR, 'on', False) b.set_light(self.RIGHT_LAMP_NBR, 'on', False) self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)] Thread(target=lamp_controller).start()
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] hyperionPath = config["hyperionPath"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') if self.lightsOn(lights) == True: bridge.set_light([1,2,3,5], 'on', False) print('OFF') else: bridge.set_light([1,2,3,5], 'on', True) bridge.set_light([1,2,3,5], 'xy', [0.139,0.081]) bridge.set_light([1,2], 'bri', 5) bridge.set_light([3,5], 'bri', 100) subprocess.call(hyperionPath, shell=True) print('ON')
def init(): 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
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)
class Hue: def __init__(self, ip): self.b = Bridge(ip) self.b.connect() self.RIGHT = RIGHT_LIGHT self.LEFT = LEFT_LIGHT self.TRANSITION_TIME = TRANSITION_TIME self.b.lights[self.LEFT].transitiontime = self.TRANSITION_TIME self.b.lights[self.RIGHT].transitiontime = self.TRANSITION_TIME self.blink(self.LEFT) self.blink(self.RIGHT) self.debug() def debug(self): for i, light in enumerate(self.b.lights): print(light) def off(self, light): self.b.set_light(light, 'on', False) def on(self, light): self.b.set_light(light, 'on', True) def set_color_hsv(self, light, color): h, s, v = color command = {'hue': (h), 'sat': (s), 'bri': (v)} self.b.set_light(light, command) def set_color_rgb(self, light, color): self.set_color_hsv(light, rgb2hsv(color)) def blink(self, light, times=1): for i in range(times): self.off(light) time.sleep(0.5) self.on(light) time.sleep(0.5)
def controllerlight(lightID, data): b = Bridge('192.168.0.19') b.connect() lights = b.lights lightID = int(lightID) for i in range(len(data)): if 'check' in data[i]: if data[i].split('=')[1] == 'on': lights[lightID - 1].on = True elif data[i].split('=')[1] == 'off': lights[lightID - 1].on = False elif 'brightness' in data[i]: bri = int(data[i].split('=')[1]) if bri != -1: lights[lightID - 1].brightness = bri elif 'color' in data[i] and 'color' in data[i + 1]: x = data[i].split('=')[1] y = data[i + 1].split('=')[1] if x is not '' and y is not '': lights[lightID - 1].xy = [float(x), float(y)] return
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 PhillipsHue: MAX_HUE = 65535 MAX_SAT = 254 MIN_HUE = 0 MIN_SAT = 0 b = None light_name_list = None def __init__(self): self.b = Bridge(IP) self.b.connect() self.light_name_list = self.b.get_light_objects('name') def increase_hue(self): for light in self.light_name_list: if self.light_name_list[light].hue + 1000 > self.MAX_HUE: self.light_name_list[light].hue = self.MAX_HUE else: self.light_name_list[light].hue += 1000 def increase_sat(self): for light in self.light_name_list: if self.light_name_list[light].saturation + 200 > self.MAX_SAT: self.light_name_list[light].saturation = self.MAX_SAT else: self.light_name_list[light].saturation += 10 def decrease_hue(self): for light in self.light_name_list: if self.light_name_list[light].hue - 1000 < self.MIN_HUE: self.light_name_list[light].hue = self.MIN_HUE else: self.light_name_list[light].hue -= 1000 def decrease_sat(self): for light in self.light_name_list: if self.light_name_list[light].saturation - 115 < self.MIN_SAT: self.light_name_list[light].saturation = self.MIN_SAT else: self.light_name_list[light].saturation -= 50 def reset_vals(self): for light in self.light_name_list: self.light_name_list[light].hue = 10 self.light_name_list[light].saturation = 120 def make_colour(self, hue, sat): for light in self.light_name_list: self.light_name_list[light].hue = hue self.light_name_list[light].saturation = sat def turn_lamps_on(self): light: Light for light in self.b.lights: print(light) light.on = True def change_scene(self, scene_str: str): scenes = self.b.scenes print(self.b.get_group(1)) for scene in scenes: if scene_str in scene.name.lower(): self.b.run_scene("Habitación", scene.name) def turn_lamps_off(self): light: Light for light in self.b.lights: light.on = False
def hue(shared): last_state = shared.state # Connect to bridge b = Bridge('192.168.1.65') # 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() # Set the default color range shared.r = shared.ranges[shared.state] # Set all lights to on print "Lights in the house:" for l in b.lights: print l.light_id, ":", l.name, "-", ("On" if l.on else "Off"), "- Colormode =", l.colormode l.on = True l.transitiontime = shared.fadein l.brightness = shared.brightness l.xy = [ 0.33, 0.33 ] # CIE 1931 print "" # Light fading function def fade(): last_state = shared.state while True: # Generate random varibles for this iteration speed = random.randint(1, shared.speed) # between lights fade = random.randint(speed, shared.fade) # per light # brightness = random.randint(0, 254) color = [ random.uniform(shared.r[0][0], shared.r[1][0]), random.uniform(shared.r[0][1], shared.r[1][1]) ] for number in shared.order: l = b.lights[number - 1] # Check for light mode change from app control if l.colormode != 'xy' or l.on != True: return # Check for state change if shared.state != last_state: shared.r = shared.ranges[shared.state] last_state = shared.state if shared.state == 'none': print "Turning all lights off..." for l in b.lights: l.transitiontime = shared.fadeout # l.brightness = 1 l.on = False return else: print "Color scheme changed to:", shared.state break # Fade light l.transitiontime = fade # l.brightness = brightness l.xy = color time.sleep(speed/10) while True: time.sleep(1) if shared.state != last_state: if shared.state != 'none' and last_state == 'none': print "Starting fade with light state", shared.state shared.r = shared.ranges[shared.state] for l in b.lights: l.on = True l.transitiontime = shared.fadein l.brightness = shared.brightness l.xy = [ 0.33, 0.33 ] fade() print "Fading paused because light was turned off or mode changed by the app..." else: last_state = shared.state
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 ShotsAlarmHueControl: def __init__(self, configFileName, logger): #print (os.path.abspath(os.curdir)) f = open(configFileName) self.config = json.load(f) self.lights = self.config["lights"] self.groups = self.config["groups"] self.bridgeIP = self.config["bridgeIp"] 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.colors = [ self.red, self.magenta, self.blue, self.lblue, self.green, self.yellow, self.orange ] self.currentColor = 0 self.connected = False try: self.b = Bridge(self.bridgeIP) self.b.connect() self.b.get_api() self.status = ("Connected", 0) self.connected = True except phue.PhueRegistrationException: self.status = ("Hue Err: Push the bridge button", 1) self.connected = False except phue.PhueRequestTimeout: self.status = ("Hue Err: No Bridge at " + str(self.bridgeIP), 1) self.connected = False except Exception as e: self.status = ("Hue ERR:/var/tmp/Shots_Alarm.log", 1) logger.error(e) self.connected = False self.flash = False self.fade = True def connect(self): if not self.connected: while not self.connected: try: self.b = Bridge(self.bridgeIP) self.b.connect() self.b.get_api() self.connected = True self.status = ("Connected", 0) except phue.PhueRegistrationException or OSError as e: print(e) self.status = ("Hue Err: Push the bridge button", 1) time.sleep(20) self.connected = False def getStatus(self): return self.status def flashLights(self, color, delay, seconds, color2=None, seconds2=None): if self.connected: self.flash = True currentSeconds = 1 while currentSeconds < seconds and self.flash: for light in self.lights: if light["enabled"]: if (light["type"] == "color"): command = { 'xy': color, "alert": "select", 'bri': self.fIntensity } else: command = { "alert": "select", 'bri': self.fIntensity } self.b.set_light(light["name"], command) currentSeconds += 1 time.sleep(delay) if color2: currentSeconds = 0 while currentSeconds < seconds2 and self.flash: for light in self.lights: if light["enabled"]: if (light["type"] == "color"): command = { 'xy': color2, "alert": "select", 'bri': self.fIntensity } else: command = { "alert": "select", 'bri': self.fIntensity } self.b.set_light(light["name"], command) currentSeconds += 1 time.sleep(delay) self.flash = False # def colorFade(self, enable): if self.connected: self.fade = enable while self.fade and not self.flash: self.advanceAsOne(5) time.sleep(6) def cancelFlash(self): self.flash = False def advanceAsOne(self, tTime): for light in self.lights: if light["enabled"] and light["type"] == "color": self.currentColor += 1 command = { 'transitiontime': tTime, 'xy': self.colors[self.currentColor % len(self.colors) - 1], 'bri': self.nIntensity } self.b.set_light(light["name"], command) if light["enabled"] and light["type"] == "white": command = {'transitiontime': tTime, 'bri': self.nIntensity} self.b.set_light(light["name"], command)
#pip install phue #Check Ip address for Hue Bridge: https://www.meethue.com/api/nupnp from phue import Bridge myBridge = Bridge('192.168.1.94') myBridge.connect() #print(myBridge.get_api()) lights = myBridge.lights for l in lights: #if l.name == "Hue color lamp 1": # l.on = False print(l.name) l.on = True
#!/usr/bin/env python3 from subprocess import Popen, PIPE from datetime import datetime from phue import Bridge import logging import nmap import time import re logging.basicConfig() # allows output to monitor/log file IPcheck = -1 # starting position for loop update = 0 # starting position for parsing results myList = '' b = Bridge('192.168.0.113') # assign hue bridge b.connect() # connect to bridge b.get_api() lights = b.lights b.get_group() run_time = time.time() + 60 * 15 # 60 * <desired minutes to run the program> def scan(): global myList nm = nmap.PortScanner() # assign scan function nm.scan(hosts='192.168.0.*/24', arguments='-n -sn -PE') # scan settings myList = nm.all_hosts() # scan results array def ring():
class SpotiHue(object): def __init__(self): self.hue_bridge = Bridge(credentials.hue_bridge_ip_address) self.spotify = Spotify(auth=spotipy.util.prompt_for_user_token( credentials.spotify_username, credentials.spotify_scope, credentials.spotify_client_id, credentials.spotify_client_secret, credentials.spotify_redirect_uri)) def retrieve_current_track_information(self): """Returns the current track's name, artist, and album.""" current_track = self.spotify.currently_playing() current_track_name = current_track["item"]["name"] current_track_artist = current_track["item"]["album"]["artists"][0][ "name"] current_track_album = current_track["item"]["album"]["name"] return current_track_name, current_track_artist, current_track_album def retrieve_current_track_album_artwork(self): """Returns the current track's album artwork URL.""" return self.spotify.currently_playing( )["item"]["album"]["images"][1]["url"] def download_current_track_album_artwork(self): """Downloads the current track's album artwork.""" album_artwork = self.retrieve_current_track_album_artwork() urllib.request.urlretrieve(album_artwork, "album_artwork.jpg") def resize_current_track_album_artwork(self): """Resizes the current track album artwork to 50% of the original size.""" self.download_current_track_album_artwork() album_artwork = cv2.imread("album_artwork.jpg") album_artwork = cv2.cvtColor(album_artwork, cv2.COLOR_BGR2RGB) dimensions = (int(album_artwork.shape[1] * 50 / 100), int(album_artwork.shape[0] * 50 / 100)) return cv2.resize(album_artwork, dimensions, interpolation=cv2.INTER_AREA) def convert_current_track_album_artwork_to_2D_array(self): """Converts the current track album artwork from a 3D to a 2D array.""" album_artwork_array = self.resize_current_track_album_artwork() return album_artwork_array.reshape( album_artwork_array.shape[0] * album_artwork_array.shape[1], 3) def obtain_kmeans_clusters(self): """Returns the cluster centers obtained by fitting K-Means with 3 clusters.""" album_artwork_array = self.convert_current_track_album_artwork_to_2D_array( ) kmeans = KMeans(n_clusters=3, random_state=1259) kmeans.fit(album_artwork_array) return kmeans.cluster_centers_ def check_black_clusters(self): """Returns the RGB values for white if the RGB values of a cluster are black.""" clusters = [] for cluster in self.obtain_kmeans_clusters(): if np.all(cluster == 0): cluster = np.array([255, 255, 255]) clusters.append(cluster) return clusters def standardize_rgb_values(self, cluster): """Returns the standardized RGB values between 0 and 1.""" R, G, B = (cluster / 255).T return R, G, B def apply_gamma_correction(self, cluster): """Returns RGB values after a gamma correction has been applied.""" R, G, B = self.standardize_rgb_values(cluster) R = [((R + 0.055) / (1.0 + 0.055))**2.4 if R > 0.04045 else R / 12.92 ][0] G = [((G + 0.055) / (1.0 + 0.055))**2.4 if G > 0.04045 else G / 12.92 ][0] B = [((B + 0.055) / (1.0 + 0.055))**2.4 if B > 0.04045 else B / 12.92 ][0] return R, G, B def convert_rgb_to_xyz(self, cluster): """Returns XYZ values after a RGB to XYZ conversion using the Wide RGB D65 conversion formula has been applied.""" R, G, B = self.apply_gamma_correction(cluster) X = R * 0.649926 + G * 0.103455 + B * 0.197109 Y = R * 0.234327 + G * 0.743075 + B * 0.022598 Z = R * 0.0000000 + G * 0.053077 + B * 1.035763 return X, Y, Z def convert_xyz_to_xy(self): """Returns xy values in the CIE 1931 colorspace after a XYZ to xy conversion has been applied.""" # Only using one cluster for now cluster = self.check_black_clusters()[0] X, Y, Z = self.convert_rgb_to_xyz(cluster) x = round(X / (X + Y + Z), 4) y = round(Y / (X + Y + Z), 4) return x, y def connect_hue_bridge_first_time(self): """Connects to the Hue Bridge for the first time. Ensure Hue Bridge button is pressed.""" self.hue_bridge.connect() def turn_lights_on(self): """Turns all of the lights on to half brightness.""" logging.info("Turning the lights on to half brightness") for light in self.hue_bridge.lights: light.on = True light.brightness = 127 def change_light_color_album_artwork(self): """Change all of the lights to one of the prominent colors in the current track's album artwork.""" track, artist, album = self.retrieve_current_track_information() logging.info( f"Changing the color of the lights based on the current track: {track}, {artist}, {album}" ) x, y = self.convert_xyz_to_xy() for light in self.hue_bridge.lights: light.xy = [x, y] def change_light_color_normal(self): """Change all of the lights to normal.""" logging.info(f"Changing the color of the lights to normal") for light in self.hue_bridge.lights: light.hue = 10000 light.saturation = 120 def determine_track_playing_status(self): """Returns a boolean indicating if Spotify is still playing a track or not. Changes the lights back to normal if Spotify is not playing.""" try: track_playing_status = self.spotify.currently_playing( )["is_playing"] if track_playing_status: logging.info("Spotify is still playing") else: logging.info("Spotify stopped playing") self.change_light_color_normal() return track_playing_status except: logging.info("Spotify stopped playing") self.change_light_color_normal() def sync_current_track_album_artwork_lights(self): """Syncs the current track's album artwork colors with the lights.""" self.turn_lights_on() while self.determine_track_playing_status(): self.change_light_color_album_artwork() time.sleep(5.3)
if R == 0: firstPos = 0 else: firstPos = R / total if G == 0: secondPos = 0 else: secondPos = G / total return [firstPos, secondPos] ikealicht = SmartPlug("192.168.86.155") biglight = Bridge('192.168.86.26') biglight.connect() async def Ikealicht(onoff): await ikealicht.update() if (onoff): await ikealicht.turn_on() else: await ikealicht.turn_off() async def Biglight(onoff, brightness, color): light_name = 'Deckenlicht' if (onoff): biglight.set_light(light_name, 'on', True) biglight.set_light(light_name, 'bri', brightness) biglight.set_light(light_name, 'xy', convertColor(color)) else:
class Hue: """Hue base class.""" def __init__(self, IP): """Init.""" self.IP = IP self.bridge = Bridge(self.IP) self.connect = self.bridge.connect() self.lights = self.bridge.get_light_objects('name') self.colors = {} self.generate_colors() self.current_color = self.colors['purple'] def start(self): """Run setup tasks.""" self.generate_colors() def generate_colors(self): """Fill the color bank.""" self.colors = { 'red': Color('red', hue=0, bri=150), 'orange': Color('orange', hue=5000, bri=200), 'yellow': Color('yellow', hue=11000, bri=200), 'green': Color('green', hue=23000, bri=200), 'blue': Color('blue', hue=45000, bri=230), 'pink': Color('pink', hue=59000, bri=210), 'purple': Color('purple', hue=50000) # 'white': Color('white', hue=45000, bri=75, sat=1) } async def turn_on(self, light_name): """Turn on a light.""" self.lights[light_name].on = True async def turn_off(self, light_name): """Turn off a light.""" self.lights[light_name].on = False def get_all_light_status(self): """Print the connection status of all lights.""" print('Light status') print('============') for light_name in self.lights.keys(): if self.lights[light_name].reachable: reachable = 'Connected' else: reachable = 'Disconnected' print(f'{light_name}: {reachable}') async def blink_light(self, light_name): """Blink a light once.""" light = self.lights[light_name] is_on = light.on if is_on: self.turn_off(light.name) await asyncio.sleep(1) self.turn_on(light.name) else: self.turn_on(light.name) await asyncio.sleep(1) self.turn_off(light.name) async def set_color(self, light_name, color): """Turn on a light then sets the color.""" # Turn the light on in case it isn't already. light_list = light_name if isinstance(light_name, str): light_list = [light_name] for light in light_list: light = self.lights[light] light.on = True # Check how the color was passed in. This could be either an # integer or string. if isinstance(color, str): # Color was given as a string. ex. Red. color = self.colors[color] # Set the light. self.bridge.set_light(light_name, { 'hue': color.hue, 'bri': color.bri, 'sat': color.sat }) else: self.bridge.set_light(light_name, {'hue': color.hue}) self.current_color = color async def rainbow(self, light_name): """Cycle lights through various colors.""" start_color = self.current_color for color in self.colors: await self.set_color(light_name, color) await asyncio.sleep(0.5) # Set lights to current_color. await self.set_color(light_name, start_color)
#!/usr/bin/env python import RPi.GPIO as GPIO import SimpleMFRC522 import http.server from phue import Bridge, Group import threading import random import time, datetime from queue import Queue from collections import deque import sys b = Bridge('10.0.0.80') b.connect() #Comment out after first run group = Group(b, "Office") if(len(sys.argv) > 1 and sys.argv[1]=="LR"): group = Group(b, "Living room") lights = group.lights print(lights) print(lights[0].hue) passive = "" default_state = None def lightning_effect(sound=False): print("lightning_effect - sound={}".format(sound)) start_state = { "hue": lights[0].hue, "saturation": lights[0].saturation, "brightness":lights[0].brightness,
def setup_hue(): global b b = Bridge(os.environ['HUE_BRIDGE_IP'], os.environ['HUE_BRIDGE_USERNAME']) b.connect()
def main(): global subs global player global bridge global SRT_FILENAME, AUDIO_FILENAME, MAX_BRIGHTNESS, TICK_TIME, HUE_IP_ADDRESS parser = argparse.ArgumentParser(description="LushRoom sound and light command-line player") # group = parser.add_mutually_exclusive_group() # group.add_argument("-v", "--verbose", action="store_true") # group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("-s","--srt", default=SRT_FILENAME, help=".srt file name for lighting events") parser.add_argument("-a","--audio", default=AUDIO_FILENAME, help="audio file for sound stream") parser.add_argument("-b","--brightness", default=MAX_BRIGHTNESS, help="maximum brightness") parser.add_argument("-t","--time", default=TICK_TIME, help="time between events") parser.add_argument("--hue", default=HUE_IP_ADDRESS, help="Philips Hue bridge IP address") args = parser.parse_args() print(args) if PLAY_AUDIO: player = vlc.MediaPlayer(AUDIO_FILENAME) event_manager = player.event_manager() event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, end_callback) if PLAY_HUE: # b = Bridge('lushroom-hue.local') bridge = Bridge(HUE_IP_ADDRESS, config_file_path="/media/usb/python_hue") # 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) bridge.connect() # Get the bridge state (This returns the full dictionary that you can explore) bridge.get_api() lights = bridge.lights # Print light names for l in lights: print(l.name) #print(dir(l)) # Set brightness of each light to 10 for l in lights: l.brightness = 1 # Get a dictionary with the light name as the key light_names = bridge.get_light_objects('name') print("Light names:", light_names) subs = srtopen(SRT_FILENAME) print("Number of lighting events",len(subs)) scheduler = BackgroundScheduler() scheduler.add_job(tick, 'interval', seconds=TICK_TIME) # scheduler.start(paused=True) if PLAY_AUDIO: player.play() scheduler.start(paused=False) try: # This is here to simulate application activity (which keeps the main thread alive). while True: sleep(0.01) try: if keyboard.is_pressed('p'): # pause scheduler.pause() player.pause() elif keyboard.is_pressed('r'): # resume scheduler.resume() player.play() # elif keyboard.is_pressed('s'): # stop # scheduler.shutdown() # player.stop() # exit(0) except: pass except (KeyboardInterrupt, SystemExit): # Not strictly necessary if daemonic mode is enabled but should be done if possible scheduler.shutdown() player.stop()
#!/usr/bin/python from phue import Bridge import os import logging HUEBRIDGEIP = "192.168.178.97" LIGHTNAME = "OnAir" # OnAir # Buro logging.basicConfig() # lgging Bridge = Bridge(HUEBRIDGEIP) # Get bridge Bridge.connect() # 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) Bridge.get_api() # Get the bridge state (This returns the full dictionary that you can explore) light_names = Bridge.get_light_objects('name') # Get a dictionary with the light name as the key LAMP = light_names[LIGHTNAME] # Get light object LAMP.on = $STATE$ # True # $STATE$
'LLM001': { 'name': 'Color Light Module', 'gamut': 'A' }, 'LLC020': { 'name': 'Hue Go', 'gamut': 'C' }, 'LST002': { 'name': 'Hue LightStrips Plus', 'gamut': 'C' }, } HUE = Bridge('philips-hue') HUE.connect() HUE_API = HUE.get_api() HUE_LIGHTS = HUE.get_light_objects('name') GAMUT_A_CONVERTER = Converter(GamutA) GAMUT_B_CONVERTER = Converter(GamutB) GAMUT_C_CONVERTER = Converter(GamutC) LOW_THRESHOLD = 10 MID_THRESHOLD = 40 HIGH_THRESHOLD = 240 def get_gamut(modelid): return GAMUTS[modelid]['gamut']
USERS = ('user1', 'user2', 'user3', 'user4') ROOMS = ('room1', 'room2', 'room3', 'room4') DEVICES = { 'camera1': { 'room': 'room1', 'ip': 'ip1' }, 'camera2': { 'room': 'room2', 'ip': 'ip2' }, 'camera3': { 'room': 'room3', 'ip': 'ip3' }, 'camera4': { 'room': 'room4', 'ip': 'ip4' }, } HUE_BRIDGE_IP = '192.168.' if HUE_BRIDGE_IP is not None: from phue import Bridge HUE_BRIDGE = Bridge(HUE_BRIDGE_IP) HUE_BRIDGE.connect() else: HUE_BRIDGE = None
def connect_bridge(): bridge = Bridge(HUE_BRIDGE_IP) bridge.connect() return bridge
#!/usr/bin/python3 import time import json import random import paho.mqtt.client as mqtt from phue import Bridge bridge_ip = '0.0.0.0' mqtt_ip = '127.0.0.1' bridge = Bridge(bridge_ip) bridge.connect() def on_connect(client, user_data, flags, rc): print('Connected with result code ' + str(rc)) client.subscribe('mcctrl/cmd/lights/on') client.subscribe('mcctrl/cmd/lights/+/bri') client.subscribe('mcctrl/cmd/lights/+/on') client.subscribe('mcctrl/cmd/lights/+/clr') def on_message(client, userdata, msg): print(msg.topic + ' ' + str(msg.payload)) if (msg.topic == 'mcctrl/cmd/lights/on'): bridge.set_group(1, 'on', True if msg.payload == b'True' else False) if (msg.topic == 'mcctrl/cmd/lights/1/bri'): bridge.set_light(1, 'bri', int(msg.payload)) if (msg.topic == 'mcctrl/cmd/lights/2/bri'): bridge.set_light(2, 'bri', int(msg.payload))
class Orb: COLORS = { 'red': [0.6679, 0.3181], 'yellow': [0.5425, 0.4196], 'orange': [0.525, 0.385], 'green': [0.41, 0.51721], 'magenta': [0.4149, 0.1776], 'blue': [0.1691, 0.0441], 'white': [0.3, 0.3], } def __init__(self, ip, bulb_id=1): self.ip = ip self.id = bulb_id self.bridge = Bridge(self.ip) # Keeps track of moving average of sentiment across # short-term memory. self.sentiment_values = [] def connect(self): self.bridge.connect() def set_color(self, xy, t=1): self.bridge.set_light(self.id, 'xy', xy, transitiontime=3) def set_brightness(self, bri): self.bridge.set_light(self.id, 'bri', int(bri)) def strobe(self): self.set_color(Orb.color_xy('magenta')) self.set_color(Orb.color_xy('blue')) def blush(self): pass def emote(self, sentiment, use_average=True): self.sentiment_values.append(sentiment) self.avg_sentiment = np.average(self.sentiment_values) if len(self.sentiment_values) > 2: self.sentiment_values.pop(0) sentiment = self.avg_sentiment if use_average else sentiment if sentiment == 0.5: color = [0.4, 0.3] if sentiment > 0.5: color = red_color(sentiment) else: color = blue_color(sentiment) self.set_color(color) def reset(self): self.num_messages = 0 self.total_sentiment = 0 self.set_color(Orb.color_xy('white')) @staticmethod def color_xy(color_name): return Orb.COLORS.get(color_name)
def __init__(self): self.read_arguments() print('reading configuration from file...') config = configparser.ConfigParser() config.read(self.config_file) #for key in config['DEFAULT']: # print(key+':', config['DEFAULT'].get(key)) settings = config['DEFAULT'] print('...configuration read successfully') logfile = open(settings.get('log_folder')+'doorbell.log', 'a',1) if self.debug == True: print('debug mode enabled') else: sys.stdout = logfile sys.stderr = logfile #Set Up Amazon and Twilio queues self.text_queue_url = settings.get('text_queue_url') self.callback_queue_url = settings.get('text_queue_url') self.account_sid = settings.get('account_sid') self.auth_token = settings.get('auth_token') self.queue_client = boto3.client('sqs') self.twilio_client = Client(self.account_sid, self.auth_token) print('Amazon and twilio queues configured successfully') #Set Up Authorized Users & Access Control try: self.access_code = settings.get('access_code') except NoOptionError: print('No access code set') self.access_code = False if settings.getboolean('auth_whitelist')==True: self.auth_whitelist=True self.auth_users_csv = settings.get('auth_users_csv') self.auth_users = {} self.default_sound_url = settings.get('default_sound') self.update_auth_users() print('Auth whitelist loaded') else: print('Auth Whitelist disabled') self.auth_whitelist=False #Set Up Hue Lights if settings.getboolean('hue_lights') == True: try: hue_bridge_ip = settings.get('hue_bridge_ip') hue_bridge_username = settings.get('hue_bridge_username') hue_light_name = settings.get('hue_light_name') self.hue_enabled = True try: hue_bridge = Bridge(hue_bridge_ip,hue_bridge_username) hue_bridge.connect() lights = hue_bridge.get_light_objects('name') self.light = lights[hue_light_name] print('Hue initialized') except: print('Error initializing Hue bridge - lights will not work') self.hue_enabled = False except NoOptionError: print('No Hue bridge config - lights will not work.') self.hue_enabled = False else: self.hue_enabled = False #Set Up Chromecast if settings.getboolean('chromecast_sounds') == True: self.sound_enabled = True self.chromecast_name=settings.get('chromecast_name') chromecasts = pychromecast.get_chromecasts() self.cast = next(cc for cc in chromecasts if cc.device.friendly_name == self.chromecast_name) print('Chromecast configured') else: print('Chromecast disabled') self.sound_enabled = False print('Startup complete')
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
def guided_setup(): # (TODO): Need to update the config file with the bridgeIP # (TODO): Need to fix formatting # (TODO): Blinking is not working as expected # intial prompt print("Hi, I'm Alfred, lets get setup. Press ENTER to continue...") input() # prompt user about Phillips Hue huePrompt = input( "Would you like me to be able to control your Phillips Hue lights (y/n)?: " ).lower() time.sleep(0.8) # run while loop if user enters incorrect answer while huePrompt != 'y' and huePrompt != 'n': print("Sorry, I didn't understand your answer...") huePrompt = input( "Would you like me to be able to control your Phillips Hue lights (y/n)?: " ) time.sleep(0.8) # if user answered yes, connect to bridge if huePrompt == 'y': # display useful tips print( "Note: Please make sure your Phillips Hue bridge is on the same network as I am running on!" ) time.sleep(0.8) # prompt for bridge IP bridgeIPPrompt = input( "Please enter the IP of your Phillips Hue bridge (instructions for locating this can be found here: https://developers.meethue.com/documentation/getting-started): " ).strip() time.sleep(0.8) print("Great, I will connect to the Bridge with IP {} (if it exists!)". format(bridgeIPPrompt)) # create bridge object b = Bridge(bridgeIPPrompt) print( "Please press the button on your Phillis Hue bridge, then within 30 seconds and press ENTER here..." ) input() # connect to bridge object b.connect() # blink lights print( "I am going to turn off all your lights, and then turn them back on to make sure things are working properly. Ready? Press ENTER to continue." ) input() lights = b.lights for l in lights: # turn lights off if they are on and on if they are off for i in range(3): l.on = not l.on time.sleep(1) # check that blink worked, if not display helpful tips blinkPrompt = input("Did your lights blink (y/n)?: ").lower() time.sleep(0.8) while blinkPrompt != 'y' and huePrompt != 'n': print("Sorry, I didn't understand your answer...") blinkPrompt = input("Did your lights blink (y/n)?: ").lower() time.sleep(0.8) if blinkPrompt == 'y': print( 'Great! I will end our setup. You can now run: python src/run_alfred.py' ) else: print('''Try running this script again. Ensure that\n - The bridge is on the same network as the computer I am running on\n - You pressed the button on the bridge when I instructed you to\n - You provided me with the correct IP address for the bridge''')
class Hue(DriverBase): """ Driver for interacting with Philips Hue lights. Provides the same parameters of :py:class:`.driver_base.DriverBase` as well as those below: :param str ip: Network hostname or IP address of the Hue base. :param list nameMap: List of names to map to each pixel index """ def __init__(self, num, ip, nameMap=None, **kwds): super().__init__(num, **kwds) if nameMap and len(nameMap) != self.numLEDs: raise ValueError( "nameMap must have the same number of entries as the number " "of LEDs.") self._bridge = Bridge(ip) self._bridge.connect() self._transitionTime = 0 if nameMap: self._lights = self._bridge.get_light_objects('name') self._ids = nameMap else: self._lights = self._bridge.get_light_objects('id') self._ids = [l for l in self._lights] if len(self._lights) < self.numLEDs: raise ValueError( "More LEDs were specified than there are available Hue lights." ) self.setTransitionTime(0) # start with no transition time def setTransitionTime(self, time): if time < 0.0 or time > 30.0: raise ValueError( "Transition time must be between 0.0 and 30.0 seconds.") self._transitionTime = int(time * 10) def _mapRange(self, value, minFrom, maxFrom, minTo, maxTo): return minTo + (maxTo - minTo) * (value - minFrom) / (maxFrom - minFrom) def _rgb2hs(self, rgb): r = rgb[0] / 255.0 g = rgb[1] / 255.0 b = rgb[2] / 255.0 h, s, v = colorsys.rgb_to_hsv(r, g, b) h = int(self._mapRange(h, 0.0, 1.0, 0, 65535)) s = int(self._mapRange(s, 0.0, 1.0, 0, 254)) return (h, s) def _send_packet(self): for i in range(len(self._ids)): h, s = self._rgb2hs(self._colors[i + self._pos]) bri = min(254, self._brightness) if s == 0: bri = 0 cmd = { 'on': s != 0, 'bri': bri, 'hue': h, 'saturation': s, 'transitiontime': self._transitionTime } self._bridge.set_light(self._ids[i], cmd)
MACs = [ '78:e1:03:f6:27:dc', '18:74:2e:25:ec:12', '18:74:2e:80:4c:c7', '68:37:e9:2e:55:4a' ] exitFlag = 0 lightpack_enabled = False # Configuration # host = '192.168.0.4' # (default) # port = 3636 # (default) # api_key = '{secret-code}' # Default is None # 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() # Connect to the Lightpack API if lightpack_enabled: lp = lightpack.Lightpack() try: lp.connect() except lightpack.CannotConnectError as e: print(repr(e)) sys.exit(1) # Lock the Lightpack so we can make changes lp.lock() else: lp = None
def main(): global subs, player, bridge, scheduler, ipcon, dmx global SRT_FILENAME, AUDIO_FILENAME, MAX_BRIGHTNESS, TICK_TIME, HUE_IP_ADDRESS, DEBUG, VERBOSE parser = argparse.ArgumentParser(description="LushRoom sound and light command-line player. \ Press Esc to exit, P to pause and R to resume.") group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true") parser.add_argument("-d", "--debug", action="store_true") parser.add_argument("-s","--srt", default=SRT_FILENAME, help=".srt file name for lighting events") parser.add_argument("-a","--audio", default=AUDIO_FILENAME, help="audio file for sound stream") parser.add_argument("-b","--brightness", default=MAX_BRIGHTNESS, help="maximum brightness") parser.add_argument("-t","--time", default=TICK_TIME, help="time between events") parser.add_argument("--hue", default=HUE_IP_ADDRESS, help="Philips Hue bridge IP address") args = parser.parse_args() MAX_BRIGHTNESS = int(args.brightness) SRT_FILENAME = args.srt AUDIO_FILENAME = args.audio TICK_TIME = float(args.time) HUE_IP_ADDRESS = args.hue VERBOSE = args.verbose DEBUG = args.debug if DEBUG: print(args) ipcon.connect(HOST, PORT) # Register Enumerate Callback ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, cb_enumerate) # Trigger Enumerate ipcon.enumerate() sleep(2) if DEBUG: print(tfIDs) dmxcount = 0 for tf in tfIDs: # try: if True: # print(len(tf[0])) if len(tf[0])<=3: # if the device UID is 3 characters it is a bricklet if tf[1] in deviceIDs: if VERBOSE: print(tf[0],tf[1], getIdentifier(tf)) if tf[1] == 285: # DMX Bricklet if dmxcount == 0: print("Registering %s as slave DMX device for capturing DMX frames" % tf[0]) dmx = BrickletDMX(tf[0], ipcon) dmx.set_dmx_mode(dmx.DMX_MODE_MASTER) # channels = int((int(MAX_BRIGHTNESS)/255.0)*ones(512,)*255) # dmx.write_frame([255,255]) sleep(1) # channels = int((int(MAX_BRIGHTNESS)/255.0)*zeros(512,)*255) # dmx.write_frame(channels) dmxcount += 1 if PLAY_AUDIO: player = vlc.MediaPlayer(AUDIO_FILENAME) event_manager = player.event_manager() event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, end_callback) if PLAY_HUE: # b = Bridge('lushroom-hue.local') bridge = Bridge(HUE_IP_ADDRESS) # 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) bridge.connect() # Get the bridge state (This returns the full dictionary that you can explore) bridge.get_api() lights = bridge.lights # Print light names for l in lights: print(l.name) #print(dir(l)) for l in lights: # print(dir(l)) l.on = False sleep(1) for l in lights: l.on = True l.brightness = MAX_BRIGHTNESS # Get a dictionary with the light name as the key light_names = bridge.get_light_objects('name') print("Light names:", light_names) subs = srtopen(SRT_FILENAME) print("Number of lighting events",len(subs)) # print("PLAY_HUE", PLAY_HUE) scheduler = BackgroundScheduler() scheduler.add_job(tick, 'interval', seconds=TICK_TIME, misfire_grace_time=10, max_instances=4096, coalesce=True) if PLAY_AUDIO: player.play() scheduler.start(paused=False) with keyboard.Listener( # on_press=on_press, on_release=on_release, suppress=False) as listener: try: listener.join() except ExitException as e: print("Exiting ...")
class HueCommand: def __init__(self, duration, states): self.b = Bridge('********') self.duration = duration self.states = states def get_states(self, ids): lights =[] for light_id in ids: is_on = self.b.get_light(light_id, 'on') bri = self.b.get_light(light_id, 'bri') hue = self.b.get_light(light_id, 'hue') lights.append({'id': light_id, 'on': is_on, 'hue': hue, 'bri': bri}) return lights def execute(self): # set hue bulbs self.b.connect() # Get a dictionary with the light ids as the key # lights = self.b.get_light_objects('id') for state in self.states: try: self.b.set_light(state.id, state.cmd) except Exception as e: print e.message continue time.sleep(self.duration)