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()
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)
def main(): if len(sys.argv) != 2: print "Usage: pants.py <config.yaml>" sys.exit(1) config = yaml.load(open(sys.argv[1])) if not 'lights' in config: print "Config must contain a 'lights' array" sys.exit(1) if not 'device' in config: print "Config must contain a 'device'" sys.exit(1) b = None while b == None: try: b = Bridge("10.0.0.31") except phue.PhueRegistrationException as e: print str(e) sleep(5) lights = b.get_light_objects('name') xbee = subprocess.Popen(["./xbsh2", config['device']], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) line = xbee.stdout.readline() p = re.compile('AD3:\s+(\d+)') while line != None: m = p.search(line) if m: value = int(m.group(1)) print value saturation = 254 hue = 65000 if value > 1000: # pants all the way down brightness = 90 elif value > 900: # pants 3/4 down brightness = 130 elif value > 700: # pants halfway down brightness = 170 elif value > 400: # pants 1/4 down brightness = 210 else: # pants up brightness = 254 saturation = 0 for light in config['lights']: l = lights[light] l.on = True l.saturation = saturation l.hue = hue l.brightness = brightness line = xbee.stdout.readline()
def 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()
def bttn_stop(): # connect to the Sonos sonos = SoCo(SONOS_IP) # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # stop the Sonos and reset to sensible defaults queue = sonos.get_queue() sonos.clear_queue() sonos.volume = 45 sonos.play_mode = 'NORMAL' sonos.stop() # set the lights back to approximately 80% over 3 seconds command = { 'transitiontime': 30, 'on': True, 'bri': 203 } hue.set_light(1, command) return jsonify(status="success")
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 bttn_stop(): # connect to the Sonos sonos = SoCo(SONOS_IP) # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # stop the Sonos and reset to sensible defaults queue = sonos.get_queue() sonos.clear_queue() sonos.volume = STOP_VOLUME sonos.play_mode = 'NORMAL' sonos.stop() # set the lights back to a sensible default command = { 'transitiontime': (STOP_DIMMER_SECONDS * 10), 'on': True, 'bri': STOP_DIMMER_BRIGHTNESS } hue.set_light(STOP_LIGHTS, command) return jsonify(status="success")
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
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()
def main(): parser = argparse.ArgumentParser(description="Hue to Spacebrew bridge") parser.add_argument("-s", "--server", help="Spacebrew server", default="sandbox.spacebrew.cc") parser.add_argument("-p", "--port", help="Spacebrew port", type=int, default=9000) parser.add_argument("-b", "--bridge", help="Hue bridge") args = parser.parse_args() print("Connecting to Spacebrew server: %s port %d"%(args.server, args.port)) brew = Spacebrew("Hue Bridge", server=args.server, port=args.port) if args.bridge is None: info = urllib.urlopen('http://www.meethue.com/api/nupnp').read() info = json.loads(info) if len(info) > 0: args.bridge = info[0][u'internalipaddress'] else: print("ERROR: Could not auto-detect Hue bridge IP") print(" Please specify --bridge manually") sys.exit(1) print("Connecting to Hue bridge at: %s" % args.bridge) bridge = None while bridge == None: try: bridge = Bridge(args.bridge) except phue.PhueRegistrationException as e: print(str(e)) sleep(5) lights = bridge.get_light_objects('name') brew_lights = [] print("Lights:") for name in lights: print(" - %s"%(name)) brew_lights.append(HueBulb(brew, name, lights[name])) print("Starting Spacebrew") brew.start() sleep(5) try: while True: for light in brew_lights: light.poll() # chill out man sleep(0.33) finally: brew.stop()
def set_hue_color(): hue = settings.BRIDGE_IP goldenrod = [0.5136, 0.4444] bridge = Bridge(hue) lights = bridge.get_light_objects(mode='id').values() for light in lights: light.xy = goldenrod
def update_lights(config, level): """ Update the lights with the new state """ bridge = Bridge(ip=config.hostname, username=config.username) for light in config.lights: log.debug('Updating light "%s"', light) actions = config.get_actions(light, level) for act in actions: bridge.set_light(light, act)
def main(): from phue import Bridge import argparse # user-specific settings lights_in_play = [ 'Office Lamp 1A' # 'Front Porch', # 'Entryway', 'Foyer', # 'TV', 'Ledge 1', 'Ledge 2', 'Ledge 3', 'Ledge 4', # 'Office', 'Office Lamp 1A', 'Office Lamp 1B', 'Office Lamp 2A', 'Office Lamp 2B', # 'Bedroom 1', 'Bedroom 2' ] print('SetBulbXY') # command-line argument parser parser = argparse.ArgumentParser( prog = 'SetBulbXY', prefix_chars = '-/', description = """This program assigns settings to a list of bulbs (list is currently coded into the .py file).""") parser.add_argument('-v', '--verbose', help='Increase output verbosity', action="store_true") parser.add_argument('-xy', help='An XY pair to define the bulb color (0.0-1.0, 0.0-1.0)', type=float, nargs=2, default=[0.5, 0.5]) parser.add_argument('-t', '--timing', help='Set bulb transition time (seconds)', type=float, default=0) parser.add_argument('-b', '--brightness', help='Set bulb brightness (0 - 254)', type=int, default=254) # TODO: add option to specify bulb names # TODO: add option to specify light IDs # TODO: add option to print list of bulb name/ID combos # TODO: add option to print list of 'legal' named colors (green, red, energize) # TODO: add option to specify colors as names # TODO: add option to specify bridge IP args = parser.parse_args() x, y = args.xy[0], args.xy[1] transitiontime = int(args.timing * 10) # API uses 10ths of seconds bri = args.brightness b = Bridge() lights = b.get_light_objects('name') light_ids_in_play = [] for name in lights_in_play: light_ids_in_play.append(int(b.get_light_id_by_name(name))) if args.verbose: print('Verbosity set to ON') print('Bulbs to be set: ' + str(light_ids_in_play)) print('XY color set to X = {0}, Y = {0}'.format(x, y)) print('Transition speed set to ' + str(abs(args.timing)) + ' seconds.') print('Brightness set to ' + str(args.brightness)) # issue commands via the hub command = {'on' : True, 'transitiontime' : transitiontime, 'xy' : [x, y], 'bri' : bri} result = b.set_light(light_ids_in_play, command) print('-- lights set, exiting program --')
def 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 sexy_time(): # connect to the Sonos sonos = SoCo(SONOS_IP) # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # get queue queue = sonos.get_queue() # if we: # * already have a queue # * music is playing # * we are already playing a queue that begins with "Let's Get It On" # ...then skip to the next track if len(queue) > 0 and \ sonos.get_current_transport_info()['current_transport_state'] == "PLAYING" and \ queue[0].title == SEXY_TIME_FIRST_TRACK: sonos.next() # else, intitiate a fresh Sexy Time else: # clear Sonos queue sonos.clear_queue() # turn off shuffle and repeat sonos.play_mode = 'NORMAL' # set volume sonos.volume = 45 # play Sexy Time playlist playlist = get_sonos_playlist(sonos, SEXY_TIME_PLAYLIST_NAME) if playlist: sonos.add_to_queue(playlist) sonos.play() # dim the lights (bri out of 254) over the pre-defined amount of time command = { 'transitiontime': (SEXY_TIME_DIMMER_SECONDS * 10), 'on': True, 'bri': SEXY_TIME_DIMMER_BRIGHTNESS } hue.set_light(1, command) return jsonify(status="success")
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 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 ams_sethuecolor(rBulbNumber, rColor, rBlink): # Usage ams_sethuecolor(1,"blue",0) # Colors Supported: off, white, red, green, purple, pink, blue, yellow b = Bridge(myHueIP) lights = b.get_light_objects('id') # Moved off setting above light turn on so that the bulb does not # flicker if it is off and another off command comes across if rColor == "off": lights[rBulbNumber].on = False else: if (lights[rBulbNumber].on == False): lights[rBulbNumber].on = True if rColor == "white": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 14922 lights[rBulbNumber].saturation = 144 lights[rBulbNumber].xy = [0.4595, 0.4105] if rColor == "white50": lights[rBulbNumber].brightness = 125 lights[rBulbNumber].hue = 14922 lights[rBulbNumber].saturation = 144 lights[rBulbNumber].xy = [0.4595, 0.4105] if rColor == "red": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 49746 lights[rBulbNumber].saturation = 235 lights[rBulbNumber].xy = [0.6449, 0.0329] if rColor == "purple": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 46033 lights[rBulbNumber].saturation = 228 lights[rBulbNumber].xy = [0.2336, 0.1129] if rColor == "pink": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 47793 lights[rBulbNumber].saturation = 211 lights[rBulbNumber].xy = [0.3627, 0.1807] if rColor == "yellow": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 19886 lights[rBulbNumber].saturation = 254 lights[rBulbNumber].xy = [0.4304, 0.5023] if rColor == "blue": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 47108 lights[rBulbNumber].saturation = 254 lights[rBulbNumber].xy = [0.167, 0.04] if rColor == "green": lights[rBulbNumber].brightness = 250 lights[rBulbNumber].hue = 23543 lights[rBulbNumber].saturation = 254 lights[rBulbNumber].xy = [0.3919, 0.484]
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)
def createConfig(self): created = False logger.warning('***********************Press the button on the Hue bridge*************************') while not created: b = Bridge(IP_BRIDGE) b.connect() # Get the bridge state (This returns the full dictionary that you can explore) b.get_api() if len(b.lights)>0: created=True HueCocotte().send_mail(EMAIL_SUBJECT, "Philips HUE connected") logger.warning("Bridge connected !") self.polling()
def _get_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
class HueController(object): def __init__(self): self.value = 0 self.increment = 10000 self.brightness = 128 self.is_on = False self._ws = None self.bridge = Bridge(ip=BRIDGE_HOST, username=BRIDGE_USERNAME) def run(self): print self.bridge.register_app()
def flash(): b = Bridge("10.0.1.2") # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented #b.connect() lights = b.get_light_objects() color_list = [25653, 41613, 63155] rnd_color = random.randrange(0,2+1) light_settings = {'bri' : 254, 'hue' : color_list[rnd_color], 'on' : True, 'transitiontime' : 0} last_light = 1 for x in range(0, 10): rnd_light = random.randrange(1,3+1) b.set_light(rnd_light, light_settings) b.set_light(last_light, 'on', False, transitiontime=0) last_light = rnd_light for z in range(0, 3): b.set_light([1, 2, 3], 'on', False, transitiontime=0) print rnd_color return "OK"
def connect(self): " Connect to the Philips Hue bridge " if self.connected: return self.__logger.info({ 'msg_type': 'Connecting to the Hue bridge', }) self.bridge = Bridge(self.bridge_address) self.bridge.connect() self.bridge.get_api() if not self.lightbulbs: self.lightbulbs = [] for light in self.bridge.lights: self.lightbulbs.append(light.name) self.__logger.info({ 'msg_type': 'Connected to the Hue bridge', 'lightbulbs': self.lightbulbs, }) self.connected = True return self
def __init__(self): self.b = Bridge('192.168.1.53') # Enter bridge IP here. #print b.get_api() #If running for the first time, press button on bridge and run with b.connect() uncommented #self.b.connect() self.lights = self.b.get_light_objects() print self.lights
def __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 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
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): self.b = Bridge(IP) self.b.connect() self.light_name_list = self.b.get_light_objects('name')
def colorSwitch(): lColor = [1, 4000, 10200, 24000, 45000, 52000] test_light.saturation = 254 for i in lColor: test_light.hue = i sleep(2) def setBright(): vvalue = w.get() test_light.brightness = vvalue b = Bridge('192.168.1.17') lights = b.lights #listLumiere() bureau1 = Light(b, 'Sous-sol A1') bureau2 = Light(b, 'Sous-sol A2') test_light = Light(b, 'Sous-sol A1') test_light.on = False test_light.on = True test_light.brightness = 254 test_light.saturation = 254 #test_light.effect = "colorloop" #colorLoop() while (True): colorSwitch()
test_light.on = True test_light.brightness = 254 test_light.saturation = 254 test_light.transitiontime = 0 sleep(2) x = time() for i in range(nb_flash): test_light.brightness = 254 sleep(on_time) test_light.brightness = 0 sleep(off_time) y = time() print(y - x) b = Bridge('192.168.1.17') lights = b.lights print(lights) test_light = Light(b, "Sous-sol A2") test_light.brightness = 0 sleep(2) test_light.brightness = 254 sleep(2) test_light.brightness = 0 sleep(2) test_light.brightness = 254 # color = [1, 6000, 12000, 18000, 24000, 30000, 36000, 42000, 48000, 52000] # test_light.on = False
from phue import Bridge from threading import Thread import time, random # Bridge IP b = Bridge('192.168.1.3') b.connect() # Function to replicate the fire def fire_light(light): while True: # Grab the color of the bulb in kelvin color_temp = random.randint(2000, 3500) # Determine the brightness brightness = random.randint(0, 255) # Determine the time needed to change colors transition_time = random.randint(1, 25) # Adjust the light settings light.brightness = brightness light.transitiontime = transition_time light.colortemp_k = color_temp # Sleep till the transition is complete time.sleep(transition_time / 10) # Grab all the lights lights = b.get_light_objects('name') # Turn on the lights
#!/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():
# imports from phue import Bridge from subprocess import call import speech_recognition as sr import serial import requests import json # define the fact feel model api url FACTFEEL_API = "https://fact-feel-flaskapp.herokuapp.com/predict" r = sr.Recognizer() with sr.Microphone(device_index=2) as source: r.adjust_for_ambient_noise(source, duration=10) b = Bridge('192.168.0.186') b.connect() def listen1(): with sr.Microphone(device_index=2) as source: #r.adjust_for_ambient_noise(source) print("Say Something") audio = r.record(source, duration=15) print("got it") return audio def voice1(audio1): try: text1 = r.recognize_google(audio1)
class Action_class: # obj init Hue_Hub = Bridge('192.168.0.134') Heater = SmartPlug('192.168.0.146') Lighthouse = SmartPlug('192.168.0.196') ahk = AHK(executable_path='C:/Program Files/AutoHotkey/AutoHotkey.exe') # var init ahk_speakers = 'Run nircmd setdefaultsounddevice "Logitech Speakers" 1' ahk_headphones = 'Run nircmd setdefaultsounddevice "Headphones"' ahk_tv = 'Run nircmd setdefaultsounddevice "SONY TV" 1' @staticmethod def assistant_status(match_dict, assistant_name): ''' Opens folder given as folder_dir. ''' # TODO finish assistant_status function response = '' # virtual memory virt_mem = psutil.virtual_memory() if virt_mem.used > virt_mem.total / 2: response += 'I am a bit busy at the moment but it is fine.' # battery info battery = psutil.sensors_battery() if battery != None: print('Percent:', battery.percent) print('Seconds Left:', battery.secsleft) print('Plugged In:', battery.power_plugged) print(battery) if battery.power_plugged: battery_info = f'Battery is at {battery.percent}' response += battery_info if response == '': response = random.choice(match_dict['responses']) response = response.replace('{assistant_name}', assistant_name) return response @staticmethod def open_folder(folder): ''' Opens folder given as folder_dir. ''' # TODO finish open_folder function folders = { 'Home Control Interface': r'D:/Google Drive/Coding/Python/Scripts/1-Complete-Projects/Home Control Interface.lnk', 'Timed Sleep or Shutdown': r'D:/Google Drive/Coding/Python/Scripts/1-Complete-Projects/Timed Sleep or Shutdown.lnk', 'Media Release Updater': r'D:/Google Drive/Coding/Python/Scripts/1-Complete-Projects/Media Release Updater.lnk' } for folder_name, folder_dir in folders.items(): if folder in folder_name: subprocess.Popen(rf'explorer /select, {folder_dir}') return @staticmethod def run_script(script): ''' Runs script based on given script name if it is in the scripts dictionary. ''' # TODO finish run_script function scripts = { 'Home Control Interface': r'D:/Google Drive/Coding/Python/Scripts/1-Complete-Projects/Home Control Interface.lnk', 'Timed Sleep or Shutdown': r'D:/Google Drive/Coding/Python/Scripts/1-Complete-Projects/Timed Sleep or Shutdown.lnk', 'Media Release Updater': r'D:/Google Drive/Coding/Python/Scripts/1-Complete-Projects/Media Release Updater.lnk' } for script_name, script_dir in scripts.items(): if script in script_name: subprocess.run([sys.executable, f'{script}.lnk'], cwd=os.path.dirname(script_dir)) return print('No script found with that name.') def display_switch(self, pattern): ''' Switches display to the mode that matches the pattern argument. Works for PC and TV mode. Arguments: pattern -- matched response from Phrase_Matcher ''' if 'TV' in pattern: mode = 'TV' else: mode = 'PC' subprocess.call([f'{os.getcwd()}/Batches/{mode} Mode.bat' ]) # runs .bat for different modes sleep(10) if mode == 'PC': # switches audio default via an AHK wrapper self.ahk.run_script(self.ahk_speakers, blocking=False) else: self.ahk.run_script(self.ahk_tv, blocking=False) def set_audio_default(self, pattern): ''' Sets the audio device depending on the device is mentioned in the pattern. Arguments: pattern -- matched response from Phrase_Matcher ''' if 'pc' in pattern: self.ahk.run_script(self.ahk_speakers, blocking=False) elif 'tv' in pattern: self.ahk.run_script(self.ahk_tv, blocking=False) else: self.ahk.run_script(self.ahk_headphones, blocking=False) def start_vr(self): ''' Start VR Function. ''' # runs SteamVR subprocess.call( "D:/My Installed Games/Steam Games/steamapps/common/SteamVR/bin/win64/vrstartup.exe" ) if self.Lighthouse.get_sysinfo( )["relay_state"] == 0: # turns on Lighthouse if it is off self.Lighthouse.turn_on() @staticmethod def check_time_date(pattern) -> str: ''' Says the Date or time depending on which is in the pattern chosen. Arguments: pattern -- matched response from phrase_matcher ''' if 'time' in pattern: current_time = dt.datetime.now().strftime("%I:%M %p") if current_time[0] == '0': current_time = current_time[1:] return f'It is {current_time}' elif 'tomorrow' in pattern: tomorrow = dt.datetime.today() + dt.timedelta(days=1) return f"It is {tomorrow.strftime('%A, %B %d, %Y')}" elif 'date' or 'day' in pattern: return f"It is {dt.datetime.now().strftime('%A, %B %d, %Y')}" @staticmethod def time_till( month, day, year=None, subject=None, ): ''' Gives the time till the given date arrives. ''' if year == None: year = dt.datetime.now().year # time_till = dt.datetime(month=month, day=day, year=year) - dt.datetime.now() time_till = dt.datetime.strptime(f'{month}-{day}-{year}', f'%m-%d-%Y') - dt.datetime.now() if subject != None: return f'{subject} is in {time_till.days} days.' else: return f'{time_till.days} days till {month}/{day}/{year}.' @staticmethod def time_till_custom(pattern): ''' Gives the time till the given date arrives. ''' date_entry = re.search(rf'/d', pattern) month, day, year = date_entry.split('-') if year == None: year = dt.datetime.now().year time_till = dt.datetime.strptime(f'{month}-{day}-{year}', f'%m-%d-%Y') - dt.datetime.now() return f'{time_till.days} days till {month}/{day}/{year}.'
from colorthief import ColorThief import cv2 import config from phue import Bridge from rgbxy import Converter from rgbxy import GamutC import os import sys converter = Converter(GamutC) hue_bridge = Bridge(config.bridge_ip_address) def change_color_based_on_image(img): if config.resize_image: img = cv2.resize(img, (config.resize_width, config.resize_height)) h, w, c = img.shape min_x, min_y, max_x, max_y = get_sample_zone_coordinates(h, w) if config.debug: draw_debug_image(img, (min_x, min_y), (max_x, max_y)) sample_img = img[min_y:max_y, min_x:max_x] cv2.imwrite(config.tmp_image_name, sample_img) dominant_color = find_dominant_color(config.tmp_image_name) os.remove(config.tmp_image_name) set_hue_color(config.hue_light_id, dominant_color)
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)
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
type=int, default=1) parser.add_argument('--duration', '-D', help='Duration of color in seconds', type=int, default=2) parser.add_argument('--brightness', '-B', help='Brightness 0 - 254', type=int, default=254) args = parser.parse_args() b = Bridge() green = [0.1856, 0.6045] red = [0.5654, 0.3068] lights = b.get_light_objects('id') group = b.get_group(args.group, 'lights') i = 0 # change colors def color(color1, color2): for l in group: lights[int(l)].on = True lights[int(l)].brightness = args.brightness lights[int(l)].xy = color1 if (int(l) % 2) == 0 else color2 sleep(args.duration)
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)
from pyAudioAnalysis import audioBasicIO from pyAudioAnalysis import audioFeatureExtraction import os import pydub import numpy as np import csv import pyaudio from threading import Timer import time from phue import Bridge import wave from scipy.ndimage import gaussian_filter1d import random import shutil bridge = Bridge('10.0.0.10') lights = [7, 8, 10, 11, 12, 14] spatial_lights = [[14, 10, 8], [8, 14, 7], [7, 8, 12], [12, 7, 11], [11, 12, 10], [10, 14, 11]] spatial_lights_index = [14, 8, 7, 12, 11, 10] def sample(i): #This function is what executes light commands command = lights_track[i][2] #dictionary of command peices bridge.set_light(lights_track[i][1], command) print('Converting...') sound = pydub.AudioSegment.from_mp3( os.path.join('C:\\', 'Users', 'akauf', 'Desktop', 'song.mp3')) sound.export(os.path.join('E:\\', 'Python_Projects', 'Audio_engine',
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 __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))
h = 0 elif mx == r: h = (60 * ((g - b) / df) + 360) % 360 elif mx == g: h = (60 * ((b - r) / df) + 120) % 360 elif mx == b: h = (60 * ((r - g) / df) + 240) % 360 if mx == 0: s = 0 else: s = (df / mx) * 100 v = mx * 100 return h, s, v hue_brige = Bridge('192.168.0.3') # converter = Converter() # 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) #hue_brige.connect() # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", required=True, help="path to input video") ap.add_argument("-c", "--crop", type=str, default="0 0 0 0", help="size and position of TV screen in image (x y w h)") ap.add_argument("-y", "--display",
from cover_art import theScript as coverArt from cover_art import newSongMath as ns from cover_art import getVals from cover_art import colorCode as cc from Device_detection import deviceCode as detectDevice from Device_detection import correctUserStr as cu from token_check import * from phue import Bridge from PIL import ImageFile from cover_art import theLights username = ['[mag]intensity', 'h1z1vr98wjwqiyjfrs13bod9r'] # h1z1vr98wjwqiyjfrs13bod9r scope = 'user-read-playback-state,user-read-currently-playing,user-read-recently-played' # 'user-read-playback-state,user-read-currently-playing,user-read-recently-played'] b = Bridge('192.168.86.22') ImageFile.LOAD_TRUNCATED_IMAGES = True i = 0 def theCode(): global i detectDevice(username[i], scope, tokenCode(username[(i * -1) + 1], scope, len(username)), username, i, username[i]) # check for xbr if "mag" in cu(): if ns(parkerToken(scope)): getVals(parkerToken(scope)) coverArt(getVals(parkerToken(scope))) theLights(cc()) elif "h1z" in cu(): if ns(jaydenToken(scope)):
total = R + G + B 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))
# Changing Hue colors with target import libs from phue import Bridge, Group import time import sys import oscilliate_group as osc import reset bridge_ip = '192.168.1.2' b = Bridge(bridge_ip) g = Group(b, 1) up = True delay_mode = 'FAST' osc.OPTIONS = { 'r': 255, 'g': 255, 'b': 255, 'dr': 0, 'dg': 0, 'db': 0, 'ddr': 0, 'ddg': -5, 'ddb': -6, 'brightness': 255, 'dbrightness': 0, 'ddbrightness': 0 } osc.TARGET = {
from phue import Bridge from playsound import playsound bridge_ip_address = 'xxx.xxx.x.xxx' b = Bridge(bridge_ip_address) import time def access_lights(bridge_ip_address): b = Bridge(bridge_ip_address) light_names_list = b.get_light_objects('name') return light_names_list def fbi(): lights = access_lights(bridge_ip_address) for light in lights: lights[light].on = False time.sleep(10) for light in lights: lights[light].on = True def bomb(): lights = access_lights(bridge_ip_address) running = 0 while running < 3: time.sleep(0.5) for light in lights: lights[light].on = True time.sleep(0.5)
from gpiozero import LED, Button from signal import pause from time import sleep import random from phue import Bridge import logging import thread logging.basicConfig() lightrunning = {1:False, 2:False, 3:False} b = Bridge('192.168.1.178', 'YxPYRWNawywC-sKHkjuRho7iOwMMSrn3di2ETF74') # Enter bridge IP here. lights = b.get_light_objects() led = LED(27) button1 = Button(17, pull_up=False) button2 = Button(18, pull_up=False) class light_status(): def __init__(self): self.light1_status = 0 self.light2_status = 0 ls = light_status()
def access_lights(bridge_ip_address): b = Bridge(bridge_ip_address) light_names_list = b.get_light_objects('name') return light_names_list
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')
#!/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))
from flask import Flask, make_response, request, abort, jsonify, render_template from dumb_colors import predict_color, get_some_rgb_from_text from phue import Bridge import config import ast b = Bridge(config.bridge_ip) app = Flask(__name__) app.debug = True @app.route('/connect_bridge', methods=['POST']) def connect_bridge(): print("connecting to bridge...") b.connect() response = {} return jsonify(response), 201 @app.route('/change_color', methods=['POST']) def colorify_lights(): if not request.json or ('text_input' not in request.json): abort(400) text_input = request.json['text_input'].lower() which_lights = request.json['lights'] color = predict_color(text_input) rgb = get_some_rgb_from_text(text_input)
# ============================================================================================== #Setup # ============================================================================================== # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #Stuff you need to change! # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #The IP address of the Hue bridge and a list of lights you want to use bridgeip = '192.168.0.85' # <<<<<<<<<<< # The 'group' of lights you want to change - i.e. the Room Name in the Hue app roomname = 'Office' # <<<<<<<<<<< # ----------------------------------------------------------------------------------------------- #Do some internal setup # ----------------------------------------------------------------------------------------------- #Connect to the bridge b = Bridge(bridgeip) # IMPORTANT: If running for the first time: # Uncomment the b.connect() line Press button on bridge Run the code This will save your connection details # in /home/pi/.python_hue Delete that file if you change bridges #b.connect() # <<<<<<<<<< Find the room number from the room name allrooms = b.get_group() roomnumber = 0 for room in allrooms.keys(): if allrooms[room]['name'] == roomname: roomnumber = int(room) break if roomnumber == 0: print('The room name you have supplied in roomname is not recognised. Please try again. Exiting.') exit() # Hue 'xy' colours - expand at will
current_light_state[light] = [0, 0, 0] i += 1 return lights def init_lights(l, t, r, b): lights = {} lights = init_side(lights, l, "left") lights = init_side(lights, t, "top") lights = init_side(lights, r, "right") lights = init_side(lights, b, "bottom") return lights #main loop bridge = Bridge(hue_ip) bridge.connect() lights = init_lights(left, top, right, bottom) print(lights) while True: f = url.urlopen(ambilight_api) data = f.read() json_data = json.loads(data) ambilight_data = json_data['layer1'] for light in lights: side = lights[light][0] zone = lights[light][1]
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)
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
command = {'on' : True, 'bri' : 254,"xy": [0.7, 0.1]} else: command = {'on' : True, 'bri' : 254,"xy": [0.8, 0.1]} # d=subprocess.check_output(cmd, shell=True) # y= json.loads(d) # s=str(y["guesses"][0]['location']) # s=re.sub(r'[^\w]', '', s) # print("s is",s) # if re.sub(r'[^\w]', ' ', s)==reject: b.set_light(3,command) b=Bridge("192.168.0.199") b.connect() b.get_api() broker_address=str(sys.argv[1]) user = "******" password = "******" Connected = False port=1883 # b.set_light(2, 'bri',) # exit() client = mqtt.Client("hululululu") #create new instance client.username_pw_set(user, password=password) #set username and password client.on_connect= on_connect #attach function to callback client.on_message= on_message #attach function to callback