def uponUs(): print('DoomsDay is Upon Us') # read bridge ip from web with urllib.request.urlopen(r"https://www.meethue.com/api/nupnp") as url: data = json.loads(url.read().decode()) ip = data[0]['internalipaddress'] # philips hue light connection while True: try: b = Bridge(ip) break except phue.PhueRegistrationException: print('please press connect button on bridge') while True: my_random_light = random.randint(1, 13) my_random_power = random.randint(170, 254) b.set_light(my_random_light, 'bri', my_random_power) print('light: ' + str(my_random_light) + ' power: ' + str(my_random_power)) time.sleep(random.randint(10, 15)) my_random_power = random.randint(10, 80) b.set_light(my_random_light, 'bri', my_random_power) print(' next power: ' + str(my_random_power)) time.sleep(random.randint(5, 10))
def lights_turnoff_ko(hermes, intent_message): ip, user, no = read_configuration_file(CONFIG_FILE) bridge = Bridge(ip, user) print bridge.set_light(no, command(False, 0)) hermes.publish_end_session(intent_message.session_id, u"조명을 껐습니다".encode("utf-8"))
class Bridge: bridge_ip = '192.168.1.65' def __init__(self): self.bridge = HueBridge(self.bridge_ip) self.bridge.get_api() self.names = [i for i in self.bridge.get_light_objects('name')] self.lights = self.bridge.get_light_objects('name') def brightness(self, bri): for light in self.names: self.bridge.set_light(light, 'bri', bri) def saturation(self, sat): for light in self.names: self.lights[light].saturation = sat def hue(self, hue): for light in self.names: self.lights[light].hue = hue def execute(self, hue, bri, sat): for light in self.names: self.lights[light].hue = hue self.bridge.set_light(light, 'bri', bri) self.lights[light].saturation = sat
def lights_shift_ko(hermes, intent_message): # type: (Hermes, IntentMessage) -> None ip, user, no = read_configuration_file(CONFIG_FILE) bridge = Bridge(ip, user) slot_map = to_slot_map(intent_message) brightness = bridge.get_light(no, "bri") print "brightness", brightness up_down = slot_map.get("up_down")[0] print dir(up_down.slot_value.value.value) if up_down.slot_value.value.value == "up": up = True else: up = False if up: brightness = brightness + 25 if brightness > 254: brightness = 254 message += u"最大値でつけました" else: message += u"明るくしました" print bridge.set_light(no, command(bri=brightness)) else: brightness = brightness - 25 if brightness < 0: brightness = 0 message += u"消しました" else: message += u"暗くしました" print bridge.set_light(no, command(bri=brightness))
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 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 frontHallLampOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() bridge.set_light('Front Hall', 'on', False) return 'Hi!'
def deskLampOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() bridge.set_light('Living Room Lamp', 'on', False) return 'Hi!'
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)
def turn_lights_on(): b = Bridge('192.168.0.51') b.connect() b.get_api() command = {'hue': 25500, 'on': True} b.set_light(4, command) turn_music_on()
def Threaded_light_worker(self, bridgeIP, light, command_dict): ''' Threaded loop for changing all lights. This method uses the parameters set on the "All Lights" page to send commands to all hue lights at the same time. This assumes you would like to control all lights in the same fashion - as a single group. Notes --------------- None Args --------------- bridgeIP(str) > light(str) > command(dict) > Returns --------------- None ''' My_bridge = Bridge(bridgeIP) My_bridge.set_light(light, command_dict) return
class HueManager: def __init__(self, ip): try: self._bridge = Bridge(ip) except PhueRegistrationException: raise RegistrationException @staticmethod def get_bridge_list(): bridges = discoverhue.find_bridges() return list( map( lambda bridge: { 'id': bridge, 'value': urlparse(bridges[bridge]).hostname }, bridges)) def get_light_list(self): results = [] lights = self._bridge.get_light_objects('id') for k in lights: results.append({'id': lights[k].light_id, 'value': lights[k].name}) return results def set_light(self, light_id, parameter, value=None, transition_time=None): self._bridge.set_light(light_id, parameter, value, transition_time)
def 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 bedroomLightOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() bridge.set_light('Bedroom', 'on', False) return 'Hi!'
def lights_set_ko(hermes, intent_message): # type: (Hermes, IntentMessage) -> None ip, user, no = read_configuration_file(CONFIG_FILE) bridge = Bridge(ip, user) print bridge.set_light(no, command()) hermes.publish_end_session(intent_message.session_id, u"라이트를 붙였습니다".encode("utf-8"))
def allLightsOff(): bridge = Bridge('192.168.0.2') bridge.connect() bridge.get_api() for light in bridge.lights: bridge.set_light(light.name, 'on', False) return 'Hi!'
def turn_on_led(led_num): ni.ifaddresses('eth0') ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr'] b = Bridge('192.168.4.50') b.connect() b.get_api() b.set_light(led_num, 'on', True)
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)
class OceanWorker(object): def __init__(self): self.twilio_client = None if TWILIO_SID: self.init_twilio() self.beanstalk_client = None self.init_beanstalk() self.bridge = None self.init_bridge() def init_bridge(self): print("[BRIDGE SERVICE] Initializing...") self.bridge = Bridge(BRIDGE_IP, username=BRIDGE_UN) def init_beanstalk(self): print("[BEANSTALK SERVICE] Initializing Beanstalk Client") self.beanstalk_client = greenstalk.Client(host=BEANSTALK_IP, port=BEANSTALK_PORT, watch="ocean") def init_twilio(self): print("[TWILIO SERVICE] Initializing...") self.twilio_client = Client(TWILIO_SID, TWILIO_TOK) def send_sms(self): message = self.twilio_client.messages \ .create( body="Motion Detected. Lights should now change", messaging_service_sid=TWILIO_MSG_SID, to=TEST_SMS ) print("[TWILIO SERVICE] Message sent with ID: {0}".format(message.sid)) def process_messages(self): print("[OCEAN WORKER] Waiting for Job...") job = self.beanstalk_client.reserve() print("[OCEAN WORKER] recieved job: {0}".format(job.id)) try: params = json.loads(job.body) except: print("[OCEAN WORKER] Invalid JSON") self.beanstalk_client.delete(job) return print("[OCEAN WORKER] Setting light saturation to {0}".format( params['sat'])) print("[OCEAN WORKER] Setting light XY to {0}".format(params['xy'])) status = self.bridge.set_light(WEATHER_LIGHT_ID, params) if len(status) and len(status[0]): if 'error' in status[0][0]: print("[OCEAN WORKER] {0}".format( status[0][0]['error']['description'])) self.bridge.set_light(WEATHER_LIGHT_ID, "on", True) self.bridge.set_light(WEATHER_LIGHT_ID, params) # send_sms() self.beanstalk_client.delete(job)
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)
class Hue(Command): def __init__(self): self.bridge = Bridge(ip=settings.HUE_IP_ADDRESS, username=settings.HUE_USER) def on(self, device): light = str(closest_match(device, self.bridge.get_light_objects('name').keys())) self.bridge.set_light(light, 'on', True) def off(self, device): light = str(closest_match(device, self.bridge.get_light_objects('name').keys())) self.bridge.set_light(light, 'on', False)
def setLightStatus(request, username=None, light_id=None, status=False): from phue import Bridge # ip_address = '127.0.0.1:9000' ip_address = request.data.get('ip_address') b = Bridge(ip_address, username=username) b.connect() print(b.get_api()) new_status = True if status == '1' else False b.set_light(int(light_id), 'on', new_status) ctx = {'on': new_status} return Response(ctx)
def Update_light_by_par_index(self, par_index, debug=False): ''' This is helper method for sending a set_light() command to a specific hue light. This method fetches the appropriate light name, constructs a command list, and then sends a command to the hue bridge to set the specified light appropriately. Notes --------------- None Args --------------- par_index (int) > The integer value associated with the custom parameter index for a light debug (bool) > A boolean value for toggling logged output Examples --------------- self.Update_light_by_par_index(1) Returns --------------- None ''' My_bridge = Bridge(self.Bridge_ip.eval()) command_dict = self.Build_command_dict(par_index) light_name = parent().pars('Lightname{}'.format(par_index))[0].val # threaded approach if self.Use_threads: myThread = threading.Thread( target=self.Threaded_light_worker, args=( self.Bridge_ip.eval(), light_name, command_dict,)) myThread.start() # non-threaded approach else: My_bridge.set_light(light_name, command_dict) if debug: print("light name | ", light_name) print("command dict | ", command_dict) else: pass return
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")
class PhueOnOffManager: def __init__(self, addr, lightname): self.b = Bridge(addr) self.b.connect() self.lightname = lightname def read(self): value = self.b.get_light(self.lightname, 'on') return str(value) def write(self, value): self.b.set_light(self.lightname, 'on', value)
class Hue(drivers.Power): def setup(self): self.bridge = Bridge(self.bridge_address) self.bridge.connect() def on(self): logger.info('turning on light {}'.format(self.light_number)) self.bridge.set_light(int(self.light_number), 'on', True) def off(self): logger.info('turning off light {}'.format(self.light_number)) self.bridge.set_light(int(self.light_number), 'on', False)
class AutoHomeHue: hue = None def __init__(self): self.hue = Bridge(ip='10.90.0.106', config_file_path="/var/lib/hue/hue.conf") def lights(self): return self.hue.lights def lights_name(self): return self.hue.get_light_objects('name') def is_locked(self, lamp): return os.path.isfile("/var/lib/hue/locks/{}".format(lamp.light_id)) def lock(self, lamp): open("/var/lib/hue/locks/{}".format(lamp.light_id), 'a').close() def unlock(self, lamp): os.remove("/var/lib/hue/locks/{}".format(lamp.light_id)) def brightness(self, lamp, value, time=100): lamp.on = True self.hue.set_light(lamp.light_id, 'bri', value, transitiontime=time) def color(self, lamp, hue=None, sat=None, xy=None): lamp.on = True if hue: lamp.hue = hue if sat: lamp.sat = sat if xy: lamp.xy = xy def time_based_white(self, light): if not self.hue.get_light(light.name, 'on'): return False if not self.hue.get_light(light.name, 'reachable'): return False hour = datetime.datetime.now().hour # Be nice, show a nice warm light # between 00:00 - 08:00 if hour < 8: hour = 24 ct = 154 + ((500-154)/24) * hour if light.light_id != 13 and light.colortemp != ct: self.hue.set_light(light.name, 'ct', ct) return True return False
def hue_green(): if not HUE_ACTIVE: return b = Bridge(HUE_BRIDGE_IP) b.connect() b.set_light(HUE_INDICATOR_LIGHT_NAME, { "on":True, "bri":254, "xy":[0.188071151799067,0.7032850275650089] } )
def hue_red(): if not HUE_ACTIVE: return b = Bridge(HUE_BRIDGE_IP) b.connect() b.set_light(HUE_INDICATOR_LIGHT_NAME, { "on":True, "bri":254, "xy":[0.6809, 0.3011] } )
def weatherLab(self): if self.aV8 == True: import weather t = Timer(5, self.weatherLab) t.start() else: from phue import Bridge b = Bridge('192.168.0.13') b.set_light(2, 'on', False) t = Timer(5, self.weatherLab) t.cancel()
def change_light( prev_faces, curr, prev_power): # photo attributes JUMP = 24 max_power = 254 min_power = 51 light_id = 2 # read bridge ip from web with urllib.request.urlopen(r"https://www.meethue.com/api/nupnp") as url: data = json.loads(url.read().decode()) ip = data[0]['internalipaddress'] # philips hue light connection while True: try: b = Bridge(ip) break except phue.PhueRegistrationException : print('please press connect button on bridge') power = min_power diff = 0 if prev_faces > curr : diff = prev_faces - curr if prev_faces < curr : diff = curr - prev_faces power += ( JUMP * (curr) ) # calibrate if overflow if power > max_power : power = max_power if power < min_power : power = min_power # change light power b.set_light(light_id, 'bri', int(power)) prev_power = power prev_faces = curr return ( prev_faces, prev_power )
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 change_light( prev_faces, curr, prev_power, ip): # photo attributes JUMP = 24 max_power = 254 min_power = 51 light_id = 5 # philips hue light connection while True: try: b = Bridge(ip) break except phue.PhueRegistrationException : print('please press connect button on bridge') power = min_power diff = 0 if prev_faces > curr : diff = prev_faces - curr if prev_faces < curr : diff = curr - prev_faces power += ( JUMP * (curr) ) # calibrate if overflow if power > max_power : power = max_power if power < min_power : power = min_power # change light power b.set_light(light_id, 'bri', int(power)) print(power) prev_power = power prev_faces = curr return ( prev_faces, prev_power )
class PhueOnOffManager: def __init__(self, addr, lightname): self.b = Bridge(addr) self.b.connect() self.lightname = lightname def read(self): value = self.b.get_light(self.lightname, 'bri') return int(value) def write(self, value): if value > 254: value = 254 elif value < 0: value = 0 self.b.set_light(self.lightname, 'bri', value)
class HueControl(): def initBridge(self, ip): self.bridge = Bridge(ip) self.bridge.connect() self.bridge.get_api() def __init__(self, jarvis, hueBridgeIP): self.initBridge(hueBridgeIP) self.jarvis = jarvis def setHue(self, hueValue): """ Set Hue from 0 to 65280 """ self.bridge.set_light(2, 'hue', hueValue) def setSaturation(self, satValue): """ Set Saturation from 0 to 254 """ self.bridge.set_light(2, 'sat', hueValue) def setBrightness(self, briValue): """ Set brightness from 0 to 254 """ self.bridge.set_light(2, 'bri', hueValue) def setCommand(self, command): self.bridge.set_light(2, command) def setState(self, state): self.bridge.set_light(2, 'on', state) def getState(self): return self.bridge.get_light(2, 'on') def toggleState(self): wantedState = not self.getState() self.setState(wantedState)
class HueController: def __init__(self, ip, username=None, config=None): self.bridge = Bridge(ip, username, config) self.bridge.connect() def toggle(self, lights, is_lit): all_lights = [lights] if type(lights) is not list else lights [self.bridge.set_light(light, 'on', is_lit) for light in all_lights]
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 = []
def blink_lights(self): try: ip = requests.get('https://www.meethue.com/api/nupnp').json( )[0]['internalipaddress'] hue = Bridge(ip) hue.connect() light_group = int(list(hue.get_api()['groups'].keys())[0]) red = [0.6786, 0.3159] reading = [0.4452, 0.4068] sleep_time = 0.5 # save the original light settings, so they can be reset when the alarm is turned off lights = hue.get_api()['lights'] orig_settings = {} for light_id in lights.keys(): light = lights[light_id] xy = light['state']['xy'] bri = light['state']['bri'] on = light['state']['on'] orig_settings[light_id] = xy, bri, on print(orig_settings) hue.set_group(light_group, 'on', True) hue.set_group(light_group, 'xy', red) while self.ringing: hue.set_group(light_group, 'bri', 255) sleep(sleep_time) hue.set_group(light_group, 'bri', 0) sleep(sleep_time) # return the lights to their original settings for light_id in orig_settings.keys(): orig_setting = orig_settings[light_id] command = { 'xy': orig_setting[0], 'bri': orig_setting[1], 'on': orig_setting[2] } hue.set_light(int(light_id), command) except PhueRegistrationException: print( 'ERROR: The link button needs to be pressed to control the lights' )
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 process_request(req): result = req.get('result') if result is None: return {} parameters = result.get('parameters') if parameters is None: return {} state = parameters.get('LightState') if state is None: return {} speech = "" b = Bridge(huehost) b.connect() # b.get_api() # Should take groupname into account when deciding on which lamp to turn on # b.get_group() if state == "on" or state == "On": if not b.get_light(1, 'on'): b.set_light(1, 'on', True) b.set_light(1, 'bri', 254) speech = "Turned lamp on" else: speech = "Lamp was already on." elif state == "off" or state == "Off": if b.get_light(1, 'on'): b.set_light(1, 'on', False) speech = "Turned lamp off" else: speech = "Lamp was already off" else: speech = "I couldn't understand the lampstate: " + state return { "speech": speech, "displayText": speech, # "data": data, # "contextOut": [], "source": "apiai-hue-webhook" }
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 arriving_home(): # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # set the lights to approximately 80% over 3 seconds command = { 'transitiontime': 30, 'on': True, 'bri': 203 } hue.set_light(1, command) # connect to the Sonos sonos = SoCo(SONOS_IP) # clear the queue sonos.clear_queue() # set volume sonos.volume = 25 # play Arriving Home playlist playlist = get_sonos_playlist(sonos, ARRIVING_HOME_PLAYLIST_NAME) print playlist if playlist: sonos.add_to_queue(playlist) # turn on shuffle, turn off repeat sonos.play_mode = 'SHUFFLE_NOREPEAT' # play sonos.play() # we're in shuffle mode, but the first track is always the same sonos.next() return jsonify(status="success")
def __init__(self): config = self.getConfigs() ip_bridge = config["ip_bridge"] hyperionPath = config["hyperionPath"] bridge = Bridge(ip_bridge) bridge.connect() lights = bridge.get_light_objects('id') if self.lightsOn(lights) == True: bridge.set_light([1,2,3,5], 'on', False) print('OFF') else: bridge.set_light([1,2,3,5], 'on', True) bridge.set_light([1,2,3,5], 'xy', [0.139,0.081]) bridge.set_light([1,2], 'bri', 5) bridge.set_light([3,5], 'bri', 100) subprocess.call(hyperionPath, shell=True) print('ON')
class hueService(win32serviceutil.ServiceFramework): _svc_name_ = "ambihue" _svc_display_name_ = "Ambient Hue Lighting" _svc_description_ = "Monitors screen colours to change the light of a Phillips Hue lamp" bridge = None def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.bridge = Bridge(hubIP) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) command = {'transitiontime': 25, 'on': False} self.bridge.set_light(lightID, command) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # Leave a message in Event Viewer that the service has started servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.timeout = 500 # This is how long the service will wait to run / refresh itself while 1: # Wait for service stop signal, if I timeout, loop again rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # Check to see if self.hWaitStop happened if rc == win32event.WAIT_OBJECT_0: # Stop signal encountered servicemanager.LogInfoMsg("AmbiHue - STOPPED!") #For Event Log break else: #Ok, here's the real money shot right here. #[actual service code between rests] r, g, b = ambihue.getAverageScreenColor() ambihue.turnLightToColor(self.bridge, lightID, r, g, b)
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 arriving_home(): # connect to Philips Hue Bridge hue = Bridge(ip=HUE_IP, username=HUE_USERNAME) # set the lights to appropriate brightness over appropriate time command = { 'transitiontime': (ARRIVING_HOME_DIMMER_SECONDS * 10), 'on': True, 'bri': ARRIVING_HOME_DIMMER_BRIGHTNESS } hue.set_light(ARRIVING_HOME_LIGHTS, command) # connect to the Sonos sonos = SoCo(SONOS_IP) # clear the queue sonos.clear_queue() # set volume sonos.volume = ARRIVING_HOME_VOLUME # play Arriving Home playlist playlist = get_sonos_playlist(sonos, ARRIVING_HOME_PLAYLIST_NAME) if playlist: sonos.add_to_queue(playlist) # turn on shuffle, turn off repeat sonos.play_mode = 'SHUFFLE_NOREPEAT' # play sonos.play() # we're in shuffle mode, but the first track is always the same sonos.next() return jsonify(status="success")
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 main(): hue_bridge = Bridge(BRIDGE_IP) # If the app is not registered and the button is not pressed, press the button and call connect() # (this only needs to be run a single time) # hue_bridge.connect() # turn the lamp on if it is not already, make note of what color lamp is currently set at hue_bridge.set_light(LIGHT_ID, 'on', True) initial_state = hue_bridge.get_light(LIGHT_ID)['state'] # Get weather Info max_temp, rain_probabilities = get_weather(WEATHER_URL) yday_temp = get_yesterday_temp(TEMPERATURE_FILE) # Change lamp color depending on weather data change_color(yday_temp, max_temp, rain_probabilities, hue_bridge) # delay for 2 hour then set lamp to previous color time.sleep(7200) hue_bridge.set_light(LIGHT_ID, initial_state) save_max_temp(TEMPERATURE_FILE, max_temp)
class HueController: def __init__(self): self.name = "Hue Controller Object" self.b = Bridge(ip="10.0.1.16", username="******") # self.bri = 254 self.command = {"transitiontime": 100, "on": True, "bri": 127} self.lights = self.b.get_light_objects() try: self.b.connect() except Exception as e: print(e) def randomize(self): # for light in self.lights: # light.brightness = 113 # light.xy = [random.random(), random.random()] for i in range(1, 100): print(i) for light in self.lights: light.brightness = random.randint(1, 254) light.xy = [random.random(), random.random()] # sleep(0.50) def state(self, state=None): if state == "on": print("set lights on") # self.b.set_light( [1, 2, 3], 'on', True) self.b.set_light(3, self.command) elif state == "off": print("Set lights OFF") self.b.set_light([1, 2, 3], "on", False) else: print("Dont understand")
class Hue(): def __init__(self, bridge, lightbulb=None): self.bridgeAddress = bridge self.lightsMap = {} if lightbulb: m = re.split('\s*,\s*', lightbulb) self.lightbulbs = m if m else [lightbulb] def connect(self): self.bridge = Bridge(self.bridgeAddress) self.bridge.connect() self.bridge.get_api() for light in self.bridge.lights: self.lightsMap[light.name] = light if not hasattr(self, 'lightbulbs'): self.lightbulbs = [] for light in self.bridge.lights: self.lightbulbs.append(light.name) def setBri(self, bri): if bri == 0: for light in self.lightbulbs: self.bridge.set_light(light, 'on', False) else: for light in self.lightbulbs: if not self.bridge.get_light(light, 'on'): self.bridge.set_light(light, 'on', True) self.bridge.set_light(self.lightbulbs, 'bri', bri) def setSat(self, sat): self.bridge.set_light(self.lightbulbs, 'sat', sat) def setHue(self, hue): self.bridge.set_light(self.lightbulbs, 'hue', hue)
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 set_lamp_state(is_late): try: b = Bridge(conf.HUE_BRIDGE_IP) except PhueRequestTimeout: return LIGHT_SET_FAILED_BRIDGE_COMMS except socket.error: return LIGHT_SET_FAILED_BRIDGE_COMMS b.set_light(conf.HUE_LIGHT_NAME, 'on', True) # Make sure it's on b.set_light(conf.HUE_LIGHT_NAME, 'bri', 254) # Max brightness if is_late: b.set_light(conf.HUE_LIGHT_NAME, 'hue', RED) else: b.set_light(conf.HUE_LIGHT_NAME, 'hue', GREEN) # Only stay on for 30 seconds b.set_light(conf.HUE_LIGHT_NAME, 'on', False, transitiontime=300) return LIGHT_SET_OK
def main(): import sys import random as random random.seed() from time import sleep from phue import Bridge print('Disco Light Test') print('Usage: DiscoLight.py <BPM> <\'Light name\'>') # Get disco parameters. if len(sys.argv) >= 3: # The name of the python script is always the first argument, so that plus 2 parameters = 3. bpm = float(sys.argv[1]) name = str(' '.join(sys.argv[2:])) # TODO: learn how to accept 'text in quotes'. elif len(sys.argv) == 1: # Use interactive input. # lights = b.get_light_objects('name') bpm = float(input("BPM (can be decimal): ")) name = input("Name of disco light: ") else: print("Incorrect number of input arguments, 2 parameters must be provided.") quit() b = Bridge() light_id = int(b.get_light_id_by_name(name)) # Convert beats per minute (BPM) to tenths of seconds if bpm >= 0: transitiontime = int(round(60 / bpm * 10, 0)) waittime = transitiontime / 10 else: # use negative bpm to specify flash transitions transitiontime = 0 waittime = round(60 / -bpm * 10, 0) / 10 print('\'' + name + '\' at ' + str(abs(bpm)) + ' bpm (' + str(waittime) + ' s)') while True: hue = random.randint(0, 65535) # 0 to 65535 brightness = random.randint(0, 254) # 0 to 254 saturation = random.randint(0, 10) # 0 to 254 if saturation != 0: saturation = random.randint(191, 254) # 0 to 254 # command = {'colormode' : 'hs'} # result = b.set_light(light_id, command) # print(result) command = {'transitiontime' : transitiontime, 'hue' : hue, 'sat' : saturation, 'bri' : brightness} result = b.set_light(light_id, command) sleep(waittime)
def hued_wav_file(sound_file: str, bridge: Bridge, light: Light): """ Hue light responds to WAV sound file :param sound_file: :param bridge: :return: """ chunk = 2048 # Change if too fast/slow, never less than 1024 scale = 10 # Change if too dim/bright 50 exponent = 2 # Change if too little/too much difference between loud and quiet sounds bridge.set_light(light.light_id, {'on': True, 'bri': 0, 'sat': 0, 'transitiontime': 0}) wf = wave.open(sound_file, 'rb') p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(chunk) old_bright = 0 try: while data != '': stream.write(data) rms = audioop.rms(data, 2) level = min(rms / (2.0 ** 16) * scale, 1.0) level = level ** exponent level = int(level * 254) # print(level) # bright = level if (level >= 0 and level <= 254) else 1 bright = level # print("%s | %s" % (level, bright)) # print("bright: %s" % bright) diff = old_bright - bright if abs(diff) > 5: # print("-> update hue: (%s-%s) %s" % (old_bright, bright, diff)) bridge.set_light(light.light_id, {'bri': bright, 'transitiontime': 0}) old_bright = bright # read in the next chunk of data data = wf.readframes(chunk) finally: stream.stop_stream() stream.close() p.terminate() bridge.set_light(light.light_id, {'on': False, 'bri': 0, 'sat': 0, 'transitiontime': 0})
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
#!/usr/bin/python from phue import Bridge from time import sleep b = Bridge('192.168.1.26') ##Bulbs # 1 Bedroom Dome 1 # 2 Bedroom Lamp # 3 Bedroom Dome 2 # 4 # 5 Closet 2 # 6 Closet 1 # 7 Bathroom 1 # 8 Bathroom 3 # 9 Bathroom 2 # 10 Bathroom Dome # 12 Couch ##Groups # 1 Bedroom Dome # 2 Bathroom Mirror # 3 Closet #Set Target Bulbs and Groups b1 = 1 g1 = 2 b.set_light(10,'hue',0)
#b.set_light(lights[LightId].name,transitiontime=1) #b.set_light(lights[LightId].name,'sat',LightSaturation) #b.set_light(lights[LightId].name,'bri',LightIntensity) #b.set_light(lights[LightId].name,'hue',1) #for hue in range(0,65534,1000): #b.set_light(lights[LightId].name,'hue',65534,transitiontime=1) #command={'transitiontime':150,'on':True,'bri':LightIntensity} #b.set_light(lights[LightId].name,command) #command={'transitiontime':1} #b.set_light(lights[LightId].name,command) exit(0) for light in lights_list: if (light.on == True): # LightName=b.get_light(light, 'name') LightName=light.name LightHue=512; b.set_light(LightName,'hue',LightHue); print "%s hue is now %s" % (LightName,LightHue) else: print "%s is OFF" % LightName exit(0)
LightId=int(arg) elif opt in ("-h", "--hue"): LightHue=int(arg) elif opt in ("-i", "--int"): LightIntensity=int(arg) elif opt in ("-s", "--sat"): LightSaturation=int(arg) print 'Changing light id %s to hue of %s, intensity of %s, and saturation of %s ...' % (LightId,LightHue,LightIntensity,LightSaturation) b=Bridge('192.168.44.171') # Get a flat list of the light objects lights=b.get_light_objects('list') b.set_light(lights[LightId].name,'bri',LightIntensity) b.set_light(lights[LightId].name,'hue',LightHue) b.set_light(lights[LightId].name,'sat',LightSaturation) exit(0) for light in lights_list: if (light.on == True): # LightName=b.get_light(light, 'name') LightName=light.name LightHue=512; b.set_light(LightName,'hue',LightHue); print "%s hue is now %s" % (LightName,LightHue) else: print "%s is OFF" % LightName
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)