class HueController: def __init__(self, ip): self.b = Bridge(ip) def turnRoomsOff(self, rooms): for room in rooms: self.b.set_group(room, 'on', False) def normalizeRooms(self, rooms): lightIds = [] for room in rooms: lightIds = lightIds + self.b.get_group(room, 'lights') print(lightIds) lights = self.b.get_light_objects('id') print(lights) for id in lightIds: id = int(id) lights[id].on = True lights[id].brightness = 254 lights[id].hue = 8597 lights[id].saturation = 121 pass def nightlight(self, rooms): lightIds = [] for room in rooms: lightIds = lightIds + self.b.get_group(room, 'lights') lights = self.b.get_light_objects('id') for id in lightIds: id = int(id) lights[id].on = True lights[id].brightness = 40 lights[id].hue = 6291 lights[id].saturation = 251 pass
def read_bridge_info (): global bridge_bureau global lights_diction global group_diction global group_dic_name_lights global sensor_diction global scene_diction global scene_dic_name_lights global bridge_bureau_ip global laptop_username global iphone_bart # bridge_bureau is an object of type Bridge bridge_bureau = Bridge(ip = bridge_bureau_ip, username = iphone_bart) # make a Diction of all lights by names lights_diction = bridge_bureau.get_light_objects(mode="name") # make a Diction of all groups by key= name and value = [lights] group_diction = bridge_bureau.get_group() group_dic_name_lights = {} # make a diction of all sensors sensor_diction = bridge_bureau.get_sensor() for x in sensor_diction : if sensor_diction[x]["name"]=="Hal kamer Gust" : print (sensor_diction[x]["config"]) # make a diction of all scenes scene_diction = bridge_bureau.get_scene() scene_dic_name_lights = {} return
def present(): b = Bridge('10.0.0.11', 'pi') b.connect() b.get_api() color = None r = requests.get( 'https://iswa.gsfc.nasa.gov/IswaSystemWebApp/DatabaseDataStreamServlet?format=JSON&resource=NOAA-KP&quantity=KP&duration=1' ) entries = r.json()[-26:] x = 0 y = 0 for i in entries: x += float(i['KP']) y += 1 mean = x / y # mean = 4 if (mean < 2): color = green elif (mean >= 2 and mean < 3): color = yellow elif (mean >= 3 and mean < 4): color = orange elif (mean >= 4): color = red temp = b.get_group(1) print("Cycle every " + str(_sleep / 60) + " min ------------------") print(" Changing color to: " + str(color)) print(" The average KP is: " + str(mean)) print(" Timestamps from " + str(entries[0]['timestamp']) + " to " + str(entries[-1]['timestamp'])) print(" Defaults are as: Bri: " + str(temp['action']['bri']) + " sat: " + str(temp['action']['sat']) + " hue: " + str(temp['action']['hue'])) b.set_group(1, 'bri', 0) b.set_group(1, 'bri', 0) time.sleep(2.5) b.set_group(1, 'sat', 255) b.set_group(1, 'hue', color) #Darken for i in range(0, flash_seq): b.set_group(1, 'bri', 255) # b.set_group(1, 'bri', 255, transitiontime=5) # On time.sleep(0.6) b.set_group(1, 'bri', 0) # b.set_group(1, 'bri', 0, transitiontime=5) # off time.sleep(0.6) b.set_group(1, 'bri', temp['action']['bri']) b.set_group(1, 'hue', temp['action']['hue']) b.set_group(1, 'sat', temp['action']['sat']) # Back on # b.set_group(1, 'bri', temp['action']['bri'], transitiontime=50) # b.set_group(1, 'hue', temp['action']['hue'], transitiontime=50) # b.set_group(1, 'sat', temp['action']['sat'], transitiontime=50) # Back on time.sleep(1)
def get_groups_and_scenes_by_ph_settings(self): try: phSetting = self.room_philip_group_and_scene.all().first() b = Bridge(phSetting.bridge_url, username=phSetting.username) b.connect() # import pdb;pdb.set_trace() phGroups = b.get_group() phScenes = b.get_scene() except (AttributeError, socket_error, PhueRequestTimeout): phSetting = None phGroups = [] phScenes = [] return phSetting, phGroups, phScenes
def check_room(room): b = Bridge(bridge_ip_address) groups = b.get_group() check = False for group in groups: if groups[group]['name'].lower() == room: room = groups[group]['name'] check = True if not check: raise RoomNotFound(room) return check, room
def access_room_lights(group): # Get bridge object b = Bridge(bridge_ip_address) # Get rooms lights lights = b.get_group(group, 'lights') # Initialize index c = 0 # Run through lights for light in lights: # Convert each element to integer lights[c] = int(lights[c]) if light[0] == light[-1]: c += 1 return lights
class PhillipsHueSkill(MycroftSkill): def __init__(self): super(PhillipsHueSkill, self).__init__(name="PhillipsHueSkill") self.brightness_step = int(self.settings.get('brightness_step', DEFAULT_BRIGHTNESS_STEP)) self.color_temperature_step = \ int(self.settings.get('color_temperature_step', DEFAULT_COLOR_TEMPERATURE_STEP)) verbose = self.settings.get('verbose', False) if type(verbose) == str: verbose = verbose.lower() verbose = True if verbose == 'true' else False self.verbose = verbose converter = Converter() self.colors = { "red": (65160, 254), "green": (27975, 254), "blue": (45908, 254), "pink": (52673, 254), "violet": (48156, 254), "yellow": (10821, 254), "orange": ( 6308, 254), "white": (41439, 81), } self.username = self.settings.get('username') if self.username == '': self.username = None self.ip = None # set in _connect_to_bridge self.bridge = None self.default_group = None self.groups_to_ids_map = dict() self.scenes_to_ids_map = defaultdict(dict) @property def connected(self): return self.bridge is not None @property def user_supplied_ip(self): return self.settings.get('ip') != '' @property def user_supplied_username(self): return self.settings.get('username') != '' def _register_with_bridge(self): """ Helper for connecting to the bridge. If we don't have a valid username for the bridge (ip) we are trying to use, this will cause one to be generated. """ self.speak_dialog('connect.to.bridge') i = 0 while i < 30: sleep(1) try: self.bridge = Bridge(self.ip) except PhueRegistrationException: continue else: break if not self.connected: self.speak_dialog('failed.to.register') else: self.speak_dialog('successfully.registered') def _update_bridge_data(self): """ This should be called any time a successful connection is established. It sets some member variables, and ensures that scenes and groups are registered as vocab. """ self.username = self.bridge.username with self.file_system.open('username', 'w') as conf_file: conf_file.write(self.username) if not self.default_group: self._set_default_group(self.settings.get('default_group')) self._register_groups_and_scenes() def _attempt_connection(self): """ This will attempt to connect to the bridge, but will not handle any errors on it's own. Raises ------ UnauthorizedUserException If self.username is not None, and is not registered with the bridge """ if self.user_supplied_ip: self.ip = self.settings.get('ip') else: device = next(filter(lambda device : "Philips hue" in device.model_name, upnpclient.discover())) self.ip = urllib.parse.urlparse(device.location).hostname if self.username: url = 'http://{ip}/api/{user}'.format(ip=self.ip, user=self.username) data = get(url).json() data = data[0] if isinstance(data, list) else data error = data.get('error') if error: description = error.get('description') if description == "unauthorized user": raise UnauthorizedUserException(self.username) else: raise Exception('Unknown Error: {0}'.format(description)) self.bridge = Bridge(self.ip, self.username) def _connect_to_bridge(self, acknowledge_successful_connection=False): """ Calls _attempt_connection, handling various exceptions by either alerting the user to issues with the config/setup, or registering the application with the bridge. Parameters ---------- acknowledge_successful_connection : bool Speak when a successful connection is established. Returns ------- bool True if a connection is established. """ try: self._attempt_connection() except DeviceNotFoundException: self.speak_dialog('bridge.not.found') return False except ConnectionError: self.speak_dialog('failed.to.connect') if self.user_supplied_ip: self.speak_dialog('ip.in.config') return False except socket.error as e: if 'No route to host' in e.args: self.speak_dialog('no.route') else: self.speak_dialog('failed.to.connect') return False except UnauthorizedUserException: if self.user_supplied_username: self.speak_dialog('invalid.user') return False else: self._register_with_bridge() except PhueRegistrationException: self._register_with_bridge() if not self.connected: return False if acknowledge_successful_connection: self.speak_dialog('successfully.connected') self._update_bridge_data() return True def _set_default_group(self, identifier): """ Sets the group to which commands will be applied, when a group is not specified in the command. Parameters ---------- identifier : str or int The name of the group, or it's integer id Notes ----- If the group does not exist, 0 (all lights) will be used. """ try: self.default_group = Group(self.bridge, identifier) except LookupError: self.speak_dialog('could.not.find.group', {'name': identifier}) self.speak_dialog('using.group.0') self.default_group = Group(self.bridge, 0) def _register_groups_and_scenes(self): """ Register group and scene names as vocab, and update our caches. """ groups = self.bridge.get_group() for id, group in groups.items(): name = group['name'].lower() self.groups_to_ids_map[name] = id self.register_vocabulary(name, "Group") scenes = self.bridge.get_scene() for id, scene in scenes.items(): name = scene['name'].lower() group_id = scene.get('group') group_id = int(group_id) if group_id else None self.scenes_to_ids_map[group_id][name] = id self.register_vocabulary(name, "Scene") def initialize(self): """ Attempt to connect to the bridge, and build/register intents. """ self.load_data_files(dirname(__file__)) if self.file_system.exists('username'): if not self.user_supplied_username: with self.file_system.open('username', 'r') as conf_file: self.username = conf_file.read().strip(' \n') try: self._attempt_connection() self._update_bridge_data() except (PhueRegistrationException, DeviceNotFoundException, UnauthorizedUserException, ConnectionError, socket.error): # Swallow it for now; _connect_to_bridge will deal with it pass self.register_intent_file("turn.on.intent", self.handle_turn_on_intent) self.register_intent_file("turn.off.intent", self.handle_turn_off_intent) self.register_intent_file("set.lights.intent", self.handle_set_lights_brightness_intent) self.register_intent_file("set.lights.scene.intent", self.handle_set_lights_scene_intent) self.register_intent_file("set.lights.color.intent", self.handle_set_lights_color_intent) # adjust_brightness_intent = IntentBuilder("AdjustBrightnessIntent") \ # .one_of("IncreaseKeyword", "DecreaseKeyword", "DimKeyword") \ # .one_of("Group", "LightsKeyword") \ # .optionally("BrightnessKeyword") \ # .build() # self.register_intent(adjust_brightness_intent, # self.handle_adjust_brightness_intent) # adjust_color_temperature_intent = \ # IntentBuilder("AdjustColorTemperatureIntent") \ # .one_of("IncreaseKeyword", "DecreaseKeyword") \ # .one_of("Group", "LightsKeyword") \ # .require("ColorTemperatureKeyword") \ # .build() # self.register_intent(adjust_color_temperature_intent, # self.handle_adjust_color_temperature_intent) # connect_lights_intent = \ # IntentBuilder("ConnectLightsIntent") \ # .require("ConnectKeyword") \ # .one_of("Group", "LightsKeyword") \ # .build() # self.register_intent(connect_lights_intent, # self.handle_connect_lights_intent) def _find_fuzzy(self, dictionary, value): result = process.extractOne(value, dictionary.keys()) if result is None: return None (value, confidence) = result if confidence < 60: return None else: return dictionary[value] def _find_group(self, group_name): group_id = self._find_fuzzy(self.groups_to_ids_map, group_name) if group_id is not None: return Group(self.bridge, group_id) @get_group def handle_turn_on_intent(self, message, group): group.on = True @get_group def handle_turn_off_intent(self, message, group): group.on = False @get_group def handle_set_lights_brightness_intent(self, message, group): value = message.data.get('percent') value = int(value.rstrip('%')) if value == 0: group.on = False else: brightness = int(value / 100.0 * 254) group.on = True group.brightness = brightness if self.verbose: self.speak_dialog('set.brightness', {'brightness': value}) @get_group def handle_set_lights_scene_intent(self, message, group): scene_name = message.data.get('scene') scene_id = self._find_fuzzy(self.scenes_to_ids_map[group.group_id], scene_name) if not scene_id: scene_id = self._find_fuzzy(self.scenes_to_ids_map[None], scene_name) if scene_id: if self.verbose: self.speak_dialog('activate.scene', {'scene': scene_name}) self.bridge.activate_scene(group.group_id, scene_id) else: self.speak_dialog('scene.not.found', {'scene': scene_name}) @get_group def handle_set_lights_color_intent(self, message, group): color_name = message.data.get('color') (hue, sat) = self.colors[color_name] for light in group.lights: light.on = True light.hue = hue light.saturation = sat # TODO support # @intent_handler # def handle_adjust_brightness_intent(self, message, group): # if "IncreaseKeyword" in message.data: # brightness = group.brightness + self.brightness_step # group.brightness = \ # brightness if brightness < 255 else 254 # dialog = 'increase.brightness' # else: # brightness = group.brightness - self.brightness_step # group.brightness = brightness if brightness > 0 else 0 # dialog = 'decrease.brightness' # if self.verbose: # self.speak_dialog(dialog) # TODO support # @intent_handler # def handle_adjust_color_temperature_intent(self, message, group): # if "IncreaseKeyword" in message.data: # color_temperature = \ # group.colortemp_k + self.color_temperature_step # group.colortemp_k = \ # color_temperature if color_temperature < 6500 else 6500 # dialog = 'increase.color.temperature' # else: # color_temperature = \ # group.colortemp_k - self.color_temperature_step # group.colortemp_k = \ # color_temperature if color_temperature > 2000 else 2000 # dialog = 'decrease.color.temperature' # if self.verbose: # self.speak_dialog(dialog) # TODO support # @intent_handler # def handle_connect_lights_intent(self, message, group): # if self.user_supplied_ip: # self.speak_dialog('ip.in.config') # return # if self.verbose: # self.speak_dialog('connecting') # self._connect_to_bridge(acknowledge_successful_connection=True) def stop(self): pass
def get_light_state(light): command = { 'transitiontime': light.transitiontime, 'on': light.on, 'effect': light.effect, 'saturation': light.saturation, 'brightness': light.brightness, 'xy': light.xy } return command bridge = Bridge(BRIDGE_IP) bridge.connect() GROUP_ID = bridge.get_group_id_by_name(GROUP_NAME) bedroom_light_ids = bridge.get_group(GROUP_NAME,'lights') lights = bridge.get_light_objects('id') print("Getting Lights") backup_lights = [] for x in bedroom_light_ids: light_id = int(x) id_command = (light_id, get_light_state(lights[light_id])) print("Backing up: " + str(light_id)) backup_lights.append(id_command) time.sleep(1) print("Turning off lights") bridge.set_group(1, 'on', False) time.sleep(3) print("Restoring lights") for id, command in backup_lights: bridge.set_light(id, command)
class PhillipsHueSkill(MycroftSkill): def __init__(self): super(PhillipsHueSkill, self).__init__(name="PhillipsHueSkill") self.brightness_step = int( self.settings.get('brightness_step', DEFAULT_BRIGHTNESS_STEP)) self.color_temperature_step = \ int(self.settings.get('color_temperature_step', DEFAULT_COLOR_TEMPERATURE_STEP)) verbose = self.settings.get('verbose', False) if type(verbose) == str: verbose = verbose.lower() verbose = True if verbose == 'true' else False self.verbose = verbose self.username = self.settings.get('username') if self.username == '': self.username = None self.ip = None # set in _connect_to_bridge self.bridge = None self.default_group = None self.groups_to_ids_map = dict() self.scenes_to_ids_map = defaultdict(dict) self.colors_to_cie_color_map = self._map_colors_to_cie_colors( os.path.join(os.path.dirname(os.path.realpath(__file__)), "colors")) @property def connected(self): return self.bridge is not None @property def user_supplied_ip(self): return self.settings.get('ip') != '' @property def user_supplied_username(self): return self.settings.get('username') != '' def _register_with_bridge(self): """ Helper for connecting to the bridge. If we don't have a valid username for the bridge (ip) we are trying to use, this will cause one to be generated. """ self.speak_dialog('connect.to.bridge') i = 0 while i < 30: sleep(1) try: self.bridge = Bridge(self.ip) except PhueRegistrationException: continue else: break if not self.connected: self.speak_dialog('failed.to.register') else: self.speak_dialog('successfully.registered') def _update_bridge_data(self): """ This should be called any time a successful connection is established. It sets some member variables, and ensures that scenes and groups are registered as vocab. """ self.username = self.bridge.username with self.file_system.open('username', 'w') as conf_file: conf_file.write(self.username) if not self.default_group: self._set_default_group(self.settings.get('default_group')) self._register_groups_and_scenes() self._register_colors() def _attempt_connection(self): """ This will attempt to connect to the bridge, but will not handle any errors on it's own. Raises ------ UnauthorizedUserException If self.username is not None, and is not registered with the bridge """ if self.user_supplied_ip: self.ip = self.settings.get('ip') else: self.ip = _discover_bridge() if self.username: url = 'http://{ip}/api/{user}'.format(ip=self.ip, user=self.username) data = get(url).json() data = data[0] if isinstance(data, list) else data error = data.get('error') if error: description = error.get('description') if description == "unauthorized user": raise UnauthorizedUserException(self.username) else: raise Exception('Unknown Error: {0}'.format(description)) self.bridge = Bridge(self.ip, self.username) def _connect_to_bridge(self, acknowledge_successful_connection=False): """ Calls _attempt_connection, handling various exceptions by either alerting the user to issues with the config/setup, or registering the application with the bridge. Parameters ---------- acknowledge_successful_connection : bool Speak when a successful connection is established. Returns ------- bool True if a connection is established. """ try: self._attempt_connection() except DeviceNotFoundException: self.speak_dialog('bridge.not.found') return False except ConnectionError: self.speak_dialog('failed.to.connect') if self.user_supplied_ip: self.speak_dialog('ip.in.config') return False except socket.error as e: if 'No route to host' in e.args: self.speak_dialog('no.route') else: self.speak_dialog('failed.to.connect') return False except UnauthorizedUserException: if self.user_supplied_username: self.speak_dialog('invalid.user') return False else: self._register_with_bridge() except PhueRegistrationException: self._register_with_bridge() if not self.connected: return False if acknowledge_successful_connection: self.speak_dialog('successfully.connected') self._update_bridge_data() return True def _set_default_group(self, identifier): """ Sets the group to which commands will be applied, when a group is not specified in the command. Parameters ---------- identifier : str or int The name of the group, or it's integer id Notes ----- If the group does not exist, 0 (all lights) will be used. """ try: self.default_group = Group(self.bridge, identifier) except LookupError: self.speak_dialog('could.not.find.group', {'name': identifier}) self.speak_dialog('using.group.0') self.default_group = Group(self.bridge, 0) def _register_groups_and_scenes(self): """ Register group and scene names as vocab, and update our caches. """ groups = self.bridge.get_group() for id, group in groups.items(): name = group['name'].lower() self.groups_to_ids_map[name] = id self.register_vocabulary(name, "Group") scenes = self.bridge.get_scene() for id, scene in scenes.items(): name = scene['name'].lower() group_id = scene.get('group') group_id = int(group_id) if group_id else None self.scenes_to_ids_map[group_id][name] = id self.register_vocabulary(name, "Scene") def initialize(self): """ Attempt to connect to the bridge, and build/register intents. """ self.load_data_files(dirname(__file__)) if self.file_system.exists('username'): if not self.user_supplied_username: with self.file_system.open('username', 'r') as conf_file: self.username = conf_file.read().strip(' \n') try: self._attempt_connection() self._update_bridge_data() except (PhueRegistrationException, DeviceNotFoundException, UnauthorizedUserException, ConnectionError, socket.error): # Swallow it for now; _connect_to_bridge will deal with it pass toggle_intent = IntentBuilder("ToggleIntent") \ .one_of("OffKeyword", "OnKeyword") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(toggle_intent, self.handle_toggle_intent) activate_scene_intent = IntentBuilder("ActivateSceneIntent") \ .require("Scene") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(activate_scene_intent, self.handle_activate_scene_intent) adjust_brightness_intent = IntentBuilder("AdjustBrightnessIntent") \ .one_of("IncreaseKeyword", "DecreaseKeyword", "DimKeyword") \ .one_of("Group", "LightsKeyword") \ .optionally("BrightnessKeyword") \ .build() self.register_intent(adjust_brightness_intent, self.handle_adjust_brightness_intent) set_brightness_intent = IntentBuilder("SetBrightnessIntent") \ .require("Value") \ .one_of("Group", "LightsKeyword") \ .optionally("BrightnessKeyword") \ .build() self.register_intent(set_brightness_intent, self.handle_set_brightness_intent) adjust_color_temperature_intent = \ IntentBuilder("AdjustColorTemperatureIntent") \ .one_of("IncreaseKeyword", "DecreaseKeyword") \ .one_of("Group", "LightsKeyword") \ .require("ColorTemperatureKeyword") \ .build() self.register_intent(adjust_color_temperature_intent, self.handle_adjust_color_temperature_intent) connect_lights_intent = \ IntentBuilder("ConnectLightsIntent") \ .require("ConnectKeyword") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(connect_lights_intent, self.handle_connect_lights_intent) change_color_intent = \ IntentBuilder("ChangeLightColorIntent") \ .require("Color") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(change_color_intent, self.handle_change_color_intent) @intent_handler def handle_toggle_intent(self, message, group): if "OffKeyword" in message.data: dialog = 'turn.off' group.on = False else: dialog = 'turn.on' group.on = True if self.verbose: self.speak_dialog(dialog) @intent_handler def handle_activate_scene_intent(self, message, group): scene_name = message.data['Scene'].lower() scene_id = self.scenes_to_ids_map[group.group_id].get(scene_name) if not scene_id: scene_id = self.scenes_to_ids_map[None].get(scene_name) if scene_id: if self.verbose: self.speak_dialog('activate.scene', {'scene': scene_name}) self.bridge.activate_scene(group.group_id, scene_id) else: self.speak_dialog('scene.not.found', {'scene': scene_name}) @intent_handler def handle_adjust_brightness_intent(self, message, group): if "IncreaseKeyword" in message.data: brightness = group.brightness + self.brightness_step group.brightness = \ brightness if brightness < 255 else 254 dialog = 'increase.brightness' else: brightness = group.brightness - self.brightness_step group.brightness = brightness if brightness > 0 else 0 dialog = 'decrease.brightness' if self.verbose: self.speak_dialog(dialog) @intent_handler def handle_set_brightness_intent(self, message, group): value = int(message.data['Value'].rstrip('%')) brightness = int(value / 100.0 * 254) group.on = True group.brightness = brightness if self.verbose: self.speak_dialog('set.brightness', {'brightness': value}) @intent_handler def handle_adjust_color_temperature_intent(self, message, group): if "IncreaseKeyword" in message.data: color_temperature = \ group.colortemp_k + self.color_temperature_step group.colortemp_k = \ color_temperature if color_temperature < 6500 else 6500 dialog = 'increase.color.temperature' else: color_temperature = \ group.colortemp_k - self.color_temperature_step group.colortemp_k = \ color_temperature if color_temperature > 2000 else 2000 dialog = 'decrease.color.temperature' if self.verbose: self.speak_dialog(dialog) @intent_handler def handle_connect_lights_intent(self, message, group): if self.user_supplied_ip: self.speak_dialog('ip.in.config') return if self.verbose: self.speak_dialog('connecting') self._connect_to_bridge(acknowledge_successful_connection=True) @intent_handler def handle_change_color_intent(self, message, group): if message.data["Color"] in self.colors_to_cie_color_map: group.xy = self.colors_to_cie_color_map[message.data["Color"]] dialog = "change.color" else: dialog = "color.not.found" if self.verbose: self.speak_dialog(dialog, {"color": message.data["Color"]}) def stop(self): pass def _map_colors_to_cie_colors(self, color_files_directory_path): cie_colors_map = dict() try: colors_json = json.load( open( os.path.join(color_files_directory_path, "color-definitions.json"))) if self.lang.startswith("en"): for color_name, rgb_values in colors_json.items(): cie_colors_map[color_name] = self._rgb_to_cie( rgb_values[0], rgb_values[1], rgb_values[2]) else: color_mapping = json.load( open( self._get_color_file_path(color_files_directory_path))) for foreign_color_name, english_color_name in color_mapping.items( ): if english_color_name in colors_json: rgb_values = colors_json[english_color_name] cie_colors_map[foreign_color_name] = self._rgb_to_cie( rgb_values[0], rgb_values[1], rgb_values[2]) except Exception as e: LOGGER.error(e) return cie_colors_map def _get_color_file_path(self, color_files_directory_path): file_path = os.path.join(color_files_directory_path, self.lang.split("-")[0] + "-colors.json") return file_path if os.path.isfile(file_path) else "" def _register_colors(self): for color_name in self.colors_to_cie_color_map: self.register_vocabulary(color_name, "Color") """ This function is based on the project https://github.com/usolved/cie-rgb-converter which is licensed under MIT license. MIT License Copyright (c) 2017 www.usolved.net Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ def _rgb_to_cie(self, red, green, blue): red = pow((red + 0.055) / (1.0 + 0.055), 2.4) if (red > 0.04045) else (red / 12.92) green = pow( (green + 0.055) / (1.0 + 0.055), 2.4) if (green > 0.04045) else (green / 12.92) blue = pow((blue + 0.055) / (1.0 + 0.055), 2.4) if (blue > 0.04045) else (blue / 12.92) X = red * 0.664511 + green * 0.154324 + blue * 0.162028 Y = red * 0.283881 + green * 0.668433 + blue * 0.047685 Z = red * 0.000088 + green * 0.072310 + blue * 0.986039 x = round((X / (X + Y + Z)), 4) y = round((Y / (X + Y + Z)), 4) return [x, y]
import socket import colorsys from collections import OrderedDict from flask import Flask, render_template, jsonify, request from phue import Bridge import json import os app = Flask(__name__) b = Bridge('192.168.1.15') # Enter IP here b.connect() groups = OrderedDict(sorted(b.get_group().items())) global_lights = b.get_light_objects('id') global_lights_names = b.get_light_objects('name') scenesdir = os.path.join(os.path.dirname(__file__), 'scenes') def get_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) return s.getsockname()[0] def get_scenenames(): ret = [ f.split('.')[:-1] for f in os.listdir(scenesdir) if os.path.isfile(os.path.join(scenesdir, f)) ]
#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 redxy = (0.675, 0.322) greenxy = (0.4091, 0.518) bluexy = (0.167, 0.04) yellowxy = (0.4325035269415173,0.5007488105282536) bluevioletxy = (0.2451169740627056, 0.09787810393609737) orangexy = (0.6007303214398861,0.3767456073628519)
signal.signal(signal.SIGTERM, signal_handler) b = Bridge(get_environment_variable("bridge_ip")) b.connect() groups = get_groups() previous_room_brightnesses = { group_id: None for group_id in groups.keys() } while True: for group_id, light_ids in groups.items(): group = b.get_group(group_id) group_brightness = group['action']['bri'] if previous_room_brightnesses[group_id] != group_brightness: previous_room_brightnesses[group_id] = group_brightness time.sleep(.5) for light_id in light_ids: light = b.get_light(light_id) # if light['state']['bri'] != group_brightness: b.set_light(light_id, "bri", group_brightness) time.sleep(.1)
class BridgeContainer(): def __init__(self, transitiontime=50, individual=None, ip=None, dummy=False): if dummy: self.mybridge = DummyBridge() self.individual = 1 self.transitiontime = 50 return self.mybridge = None while not self.mybridge: try: if not ip: # try to find a bridge with meethue api logging.debug("will try finding the hue bridge") print "1111" localbridge = json.loads(urlopen(' /nupnp').read()) ip = localbridge[0]["internalipaddress"] logging.info('connecting to localbridge at ' + str(ip)) print "????" self.mybridge = Bridge(ip) self.mybridge.connect() self.mybridge.get_api() except Exception as e: logging.warn( 'failed to connect to HUE server did you push the button?') self.mybridge = None sleep(10) self.transitiontime = transitiontime self.individual = None if individual: self.individual = int(individual) self.alert() def setTransitionTime(self, value): # this should be the transistion time in seconds self.transitiontime = int(10 * float(value)) def sendAll(self, **options): lamp = self.individual or 0 for k, v in options.iteritems(): if v is None: del (options[k]) if self.transitiontime >= 0: options['transitiontime'] = self.transitiontime if self.individual: self.mybridge.set_light(self.individual, options) else: self.mybridge.set_group(0, options) def getAll(self): # returns dictionary with all values # {"state": {"on":true,"bri":254,"hue":45000,"sat":253,"xy":[0.1914,0.0879],"ct":500,"alert":"select","effect":"none","colormode":"hs","reachable":true}, # "type": "Extended color light", "name": "Hue Lamp", "modelid": "LCT001", "swversion": "66009663", "pointsymbol": { "1":"none", "2":"none", "3":"none", "4":"none", "5":"none", "6":"none", "7":"none", "8":"none" }} return self.mybridge.get_light(self.individual)['state'] def setEffect(self, value): self.sendAll(effect=effect) def setHue(self, value): self.sendAll(hue=value) def setBri(self, value): self.sendAll(bri=value) def setSat(self, value): self.sendAll(sat=value) def get_state(self): if self.individual: logging.debug(str(self.mybridge.get_light(self.individual))) return self.mybridge.get_light(self.individual)['state'] def toggle(self, dummy=None): if self.individual: if self.mybridge.get_light(self.individual)['state']['on']: self.mybridge.set_light(self.individual, {'on': False}) else: self.mybridge.set_light(self.individual, {'on': True}) else: if self.mybridge.get_group(0)['action']['on']: self.mybridge.set_group(0, {'on': False}) else: self.mybridge.set_group(0, {'on': True}) def setOn(self, value): if self.individual: if value: self.mybridge.set_light(self.individual, {'on': True}) else: self.mybridge.set_light(self.individual, {'on': False}) def alert(self, dummy=None): if self.individual: self.mybridge.set_light(self.individual, {'alert': 'select'}) else: self.mybridge.set_group(0, {'alert': 'select'})
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) # loop endlessly while True: if (i % 2) == 0:
#Set Target Bulbs and Groups b1 = 2 b2 = 10 b3 = 12 g1 = 2 g2 = 3 #Get Current Status of Bulbs and Groups h1 = b.get_light(b1,'hue') h2 = b.get_light(b2,'hue') h3 = b.get_light(b3,'hue') br1 = b.get_light(b1,'bri') br2 = b.get_light(b2,'bri') br3 = b.get_light(b3,'bri') brg1 = b.get_group(g1,'bri') brg2 = b.get_group(g2,'bri') p1 = b.get_light(b1,'on') p2 = b.get_light(b2,'on') p3 = b.get_light(b3,'on') pg1 = b.get_group(g1,'on') pg2 = b.get_group(g2,'on') #Turn Bulbs on and Quickly Set Brightness to 0 b.set_light(b1,'on',True) b.set_light(b1,'bri',0) b.set_light(b2,'on',True) b.set_light(b2,'bri',0)
#!/usr/bin/python from phue import Bridge import pprint # hard coded ip address, found by looking at the router settings. b = Bridge('10.0.0.44') # only use the first group group = b.get_group(1) # print current status print(f"Any lights on in {group['name']}: {group['state']['any_on']}") light_status = "[" for light in group['lights']: light = b.get_light(int(light)) status = f"{light['state']['bri']:3}" if light['state']['on'] else "off" light_status += f"({light['name']}: {status}), " print(light_status[:-2]+"]") # print available scenes and inputs indexed_scenes = list(enumerate([scene.name for scene in b.scenes])) print("Available scenes:") pprint.pp(indexed_scenes) commands = input("Enter scene index, 'on', 'off', or -brightness value (1-255) (empty cancels): ") # handle the command(s) given for command in commands.split(): if command == "": pass elif command == 'on':
from phue import Bridge import sys group_name, action = sys.argv[1:] # TODO: env var? b = Bridge('192.168.1.119') b.connect() b.get_api() group_id = b.get_group_id_by_name(group_name) light_ids = b.get_group(group_name, "lights") lights = b.get_light_objects('id') for light_id in light_ids: light_id = int(light_id) if action.lower() == 'on': lights[light_id].on = True elif action.lower() == 'off': lights[light_id].on = False elif action.lower() == 'toggle': lights[light_id].on = not lights[light_id].on else: print(f"Invalid action: {action}") break
b = Bridge("192.168.1.79") b2 = Bridge("192.168.1.78") formatter = logging.Formatter( '%(name)-8s:%(asctime)-12s %(levelname)-8s %(message)s') console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) logger = logging.getLogger('HomeGUI') logger.addHandler(console) logger.setLevel(logging.DEBUG) groups = b.get_group() for groupId in groups: group = groups[groupId] if len(group['lights']) > 0: recycle = group['recycle'] type = group['type'] name = group['name'] all_on = group['state']['all_on'] any_on = group['state']['any_on'] logger.info("Group:" + str(name)) logger.info("Group ID:" + str(groupId)) logger.info("Group:" + str(group))
This example creates a slider that controls the brightness of the first 3 lights. ''' b = Bridge(base_url) # Enter bridge IP here. #If running for the first time, press button on bridge and run with b.connect() uncommented b.connect() #b.set_light([1,2,3], 'on', True) #lights = b.lights l_id=0 lights = b.get_light_objects('id') #print(lights) # Print light names gruppo = b.get_group(1, 'name') stato = b.get_group(1,'on') while True: if stato: print("Le luci di "+b.get_group(1, 'name')+": Accese") comando = input('Vuoi spegnerle? S/N: ') if comando == "S": b.set_group(1, 'on', False) stato = False else: luce = 'Spenta' print("Le luci di "+b.get_group(1, 'name')+": Spente") comando = input('Vuoi accenderle? S/N: ') if comando == "S": b.set_group(1, 'on', True)
if __name__ == '__main__': ind = AppIndicator3.Indicator.new( "Hue control", "indicator-messages", AppIndicator3.IndicatorCategory.APPLICATION_STATUS) ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) menu = Gtk.Menu() # TODO dynamic config blabla bridge = Bridge('10.0.0.120') bridge.connect() for i, g in bridge.get_group().items(): if g['type'] != 'Room': continue gid = int(i) item = Gtk.MenuItem() item.set_label(g['name'] + ' - ALL') item.connect("activate", lambda x, y, gid=gid: toggle_group(gid), '') menu.append(item) for l in g['lights']: lid = int(l) light = bridge.get_light(lid) item = Gtk.MenuItem() item.set_label(g['name'] + ': ' + light['name']) item.connect("activate", lambda x, y, lid=lid: toggle_light(lid),
try: #Initial setup print("Initial setup") GPIO.setmode(GPIO.BCM) # Bridge setup bridge_bureau_ip = "10.0.1.2" laptop_username = "******" iphone_bart = 'fTK7yEWdh9HQaSfxZi94ArSpMlbT86DH67jjxAQj' # bridge_bureau is an object of type Bridge bridge_bureau = Bridge(ip = bridge_bureau_ip, username = iphone_bart) # make a Diction of all lights by names lights_diction = bridge_bureau.get_light_objects(mode="name") # make a Diction of all groups by key= name and value = [lights] group_diction = bridge_bureau.get_group() group_dic_name_lights = {} # make a diction of all sensors sensor_diction = bridge_bureau.get_sensor() for x in sensor_diction : if sensor_diction[x]["name"]=="Hal kamer Gust" : pass # make a diction of all scenes scene_diction = bridge_bureau.get_scene() scene_dic_name_lights = {} # Read list of switches out of text file switches.txt
class LightHuePlugin(LightPlugin): """ Philips Hue lights plugin. Requires: * **phue** (``pip install phue``) """ MAX_BRI = 255 MAX_SAT = 255 MAX_HUE = 65535 ANIMATION_CTRL_QUEUE_NAME = 'platypush/light/hue/AnimationCtrl' _BRIDGE_RECONNECT_SECONDS = 5 _MAX_RECONNECT_TRIES = 5 class Animation(Enum): COLOR_TRANSITION = 'color_transition' BLINK = 'blink' def __eq__(self, other): if isinstance(other, str): return self.value == other elif isinstance(other, self.__class__): return self == other def __init__(self, bridge, lights=None, groups=None): """ :param bridge: Bridge address or hostname :type bridge: str :param lights: Default lights to be controlled (default: all) :type lights: list[str] :param groups Default groups to be controlled (default: all) :type groups: list[str] """ super().__init__() self.bridge_address = bridge self.bridge = None self.logger.info('Initializing Hue lights plugin - bridge: "{}"'.format(self.bridge_address)) self.connect() self.lights = []; self.groups = [] if lights: self.lights = lights elif groups: self.groups = groups self._expand_groups() else: self.lights = [l.name for l in self.bridge.lights] self.redis = None self.animation_thread = None self.animations = {} self._init_animations() self.logger.info('Configured lights: "{}"'. format(self.lights)) def _expand_groups(self): groups = [g for g in self.bridge.groups if g.name in self.groups] for g in groups: for l in g.lights: self.lights += [l.name] def _init_animations(self): self.animations = { 'groups': {}, 'lights': {}, } for g in self.bridge.groups: self.animations['groups'][g.group_id] = None for l in self.bridge.lights: self.animations['lights'][l.light_id] = None @action def connect(self): """ Connect to the configured Hue bridge. If the device hasn't been paired yet, uncomment the ``.connect()`` and ``.get_api()`` lines and retry after clicking the pairing button on your bridge. """ # Lazy init if not self.bridge: from phue import Bridge, PhueRegistrationException success = False n_tries = 0 while not success: try: n_tries += 1 self.bridge = Bridge(self.bridge_address) success = True except PhueRegistrationException as e: self.logger.warning('Bridge registration error: {}'. format(str(e))) if n_tries >= self._MAX_RECONNECT_TRIES: self.logger.error(('Bridge registration failed after ' + '{} attempts').format(n_tries)) break time.sleep(self._BRIDGE_RECONNECT_SECONDS) self.logger.info('Bridge connected') self.get_scenes() else: self.logger.info('Bridge already connected') @action def get_scenes(self): """ Get the available scenes on the devices. :returns: The scenes configured on the bridge. Example output:: { "scene-id-1": { "name": "Scene 1", "lights": [ "1", "3" ], "owner": "owner-id", "recycle": true, "locked": false, "appdata": {}, "picture": "", "lastupdated": "2018-06-01T00:00:00", "version": 1 } } """ return self.bridge.get_scene() @action def get_lights(self): """ Get the configured lights. :returns: List of available lights as id->dict. Example:: { "1": { "state": { "on": true, "bri": 254, "hue": 1532, "sat": 215, "effect": "none", "xy": [ 0.6163, 0.3403 ], "ct": 153, "alert": "none", "colormode": "hs", "reachable": true }, "type": "Extended color light", "name": "Lightbulb 1", "modelid": "LCT001", "manufacturername": "Philips", "uniqueid": "00:11:22:33:44:55:66:77-88", "swversion": "5.105.0.21169" } } """ return self.bridge.get_light() @action def get_groups(self): """ Get the list of configured light groups. :returns: List of configured light groups as id->dict. Example:: { "1": { "name": "Living Room", "lights": [ "16", "13", "12", "11", "10", "9", "1", "3" ], "type": "Room", "state": { "all_on": true, "any_on": true }, "class": "Living room", "action": { "on": true, "bri": 241, "hue": 37947, "sat": 221, "effect": "none", "xy": [ 0.2844, 0.2609 ], "ct": 153, "alert": "none", "colormode": "hs" } } } """ return self.bridge.get_group() @action def get_animations(self): """ Get the list of running light animations. :returns: dict. Structure:: { "groups": { "id_1": { "type": "color_transition", "hue_range": [0,65535], "sat_range": [0,255], "bri_range": [0,255], "hue_step": 10, "sat_step": 10, "bri_step": 2, "transition_seconds": 2 } }, "lights": { "id_1": {} } } """ return self.animations def _exec(self, attr, *args, **kwargs): try: self.connect() self.stop_animation() except Exception as e: # Reset bridge connection self.bridge = None raise e lights = []; groups = [] if 'lights' in kwargs: lights = kwargs.pop('lights').split(',').strip() \ if isinstance(lights, str) else kwargs.pop('lights') if 'groups' in kwargs: groups = kwargs.pop('groups').split(',').strip() \ if isinstance(groups, str) else kwargs.pop('groups') if not lights and not groups: lights = self.lights groups = self.groups if not self.bridge: self.connect() try: if attr == 'scene': self.bridge.run_scene(groups[0], kwargs.pop('name')) else: if groups: self.bridge.set_group(groups, attr, *args, **kwargs) if lights: self.bridge.set_light(lights, attr, *args, **kwargs) except Exception as e: # Reset bridge connection self.bridge = None raise e @action def set_light(self, light, **kwargs): """ Set a light (or lights) property. :param light: Light or lights to set. Can be a string representing the light name, a light object, a list of string, or a list of light objects. :param kwargs: key-value list of parameters to set. Example call:: { "type": "request", "target": "hostname", "action": "light.hue.set_light", "args": { "light": "Bulb 1", "sat": 255 } } """ self.connect() self.bridge.set_light(light, **kwargs) @action def set_group(self, group, **kwargs): """ Set a group (or groups) property. :param group: Group or groups to set. Can be a string representing the group name, a group object, a list of strings, or a list of group objects. :param kwargs: key-value list of parameters to set. Example call:: { "type": "request", "target": "hostname", "action": "light.hue.set_group", "args": { "light": "Living Room", "sat": 255 } } """ self.connect() self.bridge.set_group(group, **kwargs) @action def on(self, lights=None, groups=None, **kwargs): """ Turn lights/groups on. :param lights: Lights to turn on (names or light objects). Default: plugin default lights :param groups: Groups to turn on (names or group objects). Default: plugin default groups """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('on', True, lights=lights, groups=groups, **kwargs) @action def off(self, lights=None, groups=None, **kwargs): """ Turn lights/groups off. :param lights: Lights to turn off (names or light objects). Default: plugin default lights :param groups: Groups to turn off (names or group objects). Default: plugin default groups """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('on', False, lights=lights, groups=groups, **kwargs) @action def toggle(self, lights=None, groups=None, **kwargs): """ Toggle lights/groups on/off. :param lights: Lights to turn off (names or light objects). Default: plugin default lights :param groups: Groups to turn off (names or group objects). Default: plugin default groups """ if groups is None: groups = [] if lights is None: lights = [] lights_on = [] lights_off = [] groups_on = [] groups_off = [] if groups: all_groups = self.bridge.get_group().values() groups_on = [ group['name'] for group in all_groups if group['name'] in groups and group['state']['any_on'] is True ] groups_off = [ group['name'] for group in all_groups if group['name'] in groups and group['state']['any_on'] is False ] if not groups and not lights: lights = self.lights if lights: all_lights = self.bridge.get_light().values() lights_on = [ light['name'] for light in all_lights if light['name'] in lights and light['state']['on'] is True ] lights_off = [ light['name'] for light in all_lights if light['name'] in lights and light['state']['on'] is False ] if lights_on or groups_on: self._exec('on', False, lights=lights_on, groups=groups_on, **kwargs) if lights_off or groups_off: self._exec('on', True, lights=lights_off, groups=groups_off, **kwargs) @action def bri(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups brightness. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param value: Brightness value (range: 0-255) """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('bri', int(value) % (self.MAX_BRI+1), lights=lights, groups=groups, **kwargs) @action def sat(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups saturation. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param value: Saturation value (range: 0-255) """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('sat', int(value) % (self.MAX_SAT+1), lights=lights, groups=groups, **kwargs) @action def hue(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups color hue. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param value: Hue value (range: 0-65535) """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('hue', int(value) % (self.MAX_HUE+1), lights=lights, groups=groups, **kwargs) @action def xy(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups XY colors. :param value: xY value :type value: list[float] containing the two values """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('xy', value, lights=lights, groups=groups, **kwargs) @action def ct(self, value, lights=None, groups=None, **kwargs): """ Set lights/groups color temperature. :param value: Temperature value (range: 0-255) :type value: int """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('ct', value, lights=lights, groups=groups, **kwargs) @action def delta_bri(self, delta, lights=None, groups=None, **kwargs): """ Change lights/groups brightness by a delta [-100, 100] compared to the current state. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param delta: Brightness delta value (range: -100, 100) """ if groups is None: groups = [] if lights is None: lights = [] bri = 0 if lights: bri = statistics.mean([ light['state']['bri'] for light in self.bridge.get_light().values() if light['name'] in lights ]) elif groups: bri = statistics.mean([ group['action']['bri'] for group in self.bridge.get_group().values() if group['name'] in groups ]) else: bri = statistics.mean([ light['state']['bri'] for light in self.bridge.get_light().values() if light['name'] in self.lights ]) delta *= (self.MAX_BRI/100) if bri+delta < 0: bri = 0 elif bri+delta > self.MAX_BRI: bri = self.MAX_BRI else: bri += delta return self._exec('bri', int(bri), lights=lights, groups=groups, **kwargs) @action def delta_sat(self, delta, lights=None, groups=None, **kwargs): """ Change lights/groups saturation by a delta [-100, 100] compared to the current state. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param delta: Saturation delta value (range: -100, 100) """ if groups is None: groups = [] if lights is None: lights = [] sat = 0 if lights: sat = statistics.mean([ light['state']['sat'] for light in self.bridge.get_light().values() if light['name'] in lights ]) elif groups: sat = statistics.mean([ group['action']['sat'] for group in self.bridge.get_group().values() if group['name'] in groups ]) else: sat = statistics.mean([ light['state']['sat'] for light in self.bridge.get_light().values() if light['name'] in self.lights ]) delta *= (self.MAX_SAT/100) if sat+delta < 0: sat = 0 elif sat+delta > self.MAX_SAT: sat = self.MAX_SAT else: sat += delta return self._exec('sat', int(sat), lights=lights, groups=groups, **kwargs) @action def delta_hue(self, delta, lights=None, groups=None, **kwargs): """ Change lights/groups hue by a delta [-100, 100] compared to the current state. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param delta: Hue delta value (range: -100, 100) """ if groups is None: groups = [] if lights is None: lights = [] hue = 0 if lights: hue = statistics.mean([ light['state']['hue'] for light in self.bridge.get_light().values() if light['name'] in lights ]) elif groups: hue = statistics.mean([ group['action']['hue'] for group in self.bridge.get_group().values() if group['name'] in groups ]) else: hue = statistics.mean([ light['state']['hue'] for light in self.bridge.get_light().values() if light['name'] in self.lights ]) delta *= (self.MAX_HUE/100) if hue+delta < 0: hue = 0 elif hue+delta > self.MAX_HUE: hue = self.MAX_HUE else: hue += delta return self._exec('hue', int(hue), lights=lights, groups=groups, **kwargs) @action def scene(self, name, lights=None, groups=None, **kwargs): """ Set a scene by name. :param lights: Lights to control (names or light objects). Default: plugin default lights :param groups: Groups to control (names or group objects). Default: plugin default groups :param name: Name of the scene """ if groups is None: groups = [] if lights is None: lights = [] return self._exec('scene', name=name, lights=lights, groups=groups, **kwargs) @action def is_animation_running(self): """ :returns: True if there is an animation running, false otherwise. """ return self.animation_thread is not None @action def stop_animation(self): """ Stop a running animation if any """ if self.animation_thread and self.animation_thread.is_alive(): redis = self._get_redis() redis.rpush(self.ANIMATION_CTRL_QUEUE_NAME, 'STOP') self._init_animations() @action def animate(self, animation, duration=None, hue_range=None, sat_range=None, bri_range=None, lights=None, groups=None, hue_step=1000, sat_step=2, bri_step=1, transition_seconds=1.0): """ Run a lights animation. :param animation: Animation name. Supported types: **color_transition** and **blink** :type animation: str :param duration: Animation duration in seconds (default: None, i.e. continue until stop) :type duration: float :param hue_range: If you selected a color color_transition.html, this will specify the hue range of your color color_transition.html. Default: [0, 65535] :type hue_range: list[int] :param sat_range: If you selected a color color_transition.html, this will specify the saturation range of your color color_transition.html. Default: [0, 255] :type sat_range: list[int] :param bri_range: If you selected a color color_transition.html, this will specify the brightness range of your color color_transition.html. Default: [254, 255] :type bri_range: list[int] :param lights: Lights to control (names, IDs or light objects). Default: plugin default lights :param groups: Groups to control (names, IDs or group objects). Default: plugin default groups :param hue_step: If you selected a color color_transition.html, this will specify by how much the color hue will change between iterations. Default: 1000 :type hue_step: int :param sat_step: If you selected a color color_transition.html, this will specify by how much the saturation will change between iterations. Default: 2 :type sat_step: int :param bri_step: If you selected a color color_transition.html, this will specify by how much the brightness will change between iterations. Default: 1 :type bri_step: int :param transition_seconds: Time between two transitions or blinks in seconds. Default: 1.0 :type transition_seconds: float """ if bri_range is None: bri_range = [self.MAX_BRI - 1, self.MAX_BRI] if sat_range is None: sat_range = [0, self.MAX_SAT] if hue_range is None: hue_range = [0, self.MAX_HUE] if groups: groups = [g for g in self.bridge.groups if g.name in groups or g.group_id in groups] lights = lights or [] for g in groups: lights.extend([l.name for l in g.lights]) elif lights: lights = [l.name for l in self.bridge.lights if l.name in lights or l.light_id in lights] else: lights = self.lights info = { 'type': animation, 'duration': duration, 'hue_range': hue_range, 'sat_range': sat_range, 'bri_range': bri_range, 'hue_step': hue_step, 'sat_step': sat_step, 'bri_step': bri_step, 'transition_seconds': transition_seconds, } if groups: for g in groups: self.animations['groups'][g.group_id] = info for l in self.bridge.lights: if l.name in lights: self.animations['lights'][l.light_id] = info def _initialize_light_attrs(lights): if animation == self.Animation.COLOR_TRANSITION: return { l: { 'hue': random.randint(hue_range[0], hue_range[1]), 'sat': random.randint(sat_range[0], sat_range[1]), 'bri': random.randint(bri_range[0], bri_range[1]), } for l in lights } elif animation == self.Animation.BLINK: return { l: { 'on': True, 'bri': self.MAX_BRI, 'transitiontime': 0, } for l in lights } def _next_light_attrs(lights): if animation == self.Animation.COLOR_TRANSITION: for (light, attrs) in lights.items(): for (attr, value) in attrs.items(): attr_range = [0,0] attr_step = 0 if attr == 'hue': attr_range = hue_range attr_step = hue_step elif attr == 'bri': attr_range = bri_range attr_step = bri_step elif attr == 'sat': attr_range = sat_range attr_step = sat_step lights[light][attr] = ((value - attr_range[0] + attr_step) % (attr_range[1]-attr_range[0]+1)) + \ attr_range[0] elif animation == self.Animation.BLINK: lights = { light: { 'on': False if attrs['on'] else True, 'bri': self.MAX_BRI, 'transitiontime': 0, } for (light, attrs) in lights.items() } return lights def _should_stop(): try: redis = self._get_redis(transition_seconds) redis.blpop(self.ANIMATION_CTRL_QUEUE_NAME) return True except QueueTimeoutError: return False def _animate_thread(lights): set_thread_name('HueAnimate') self.logger.info('Starting {} animation'.format( animation, (lights or groups))) lights = _initialize_light_attrs(lights) animation_start_time = time.time() stop_animation = False while True: if stop_animation or \ (duration and time.time() - animation_start_time > duration): break try: if animation == self.Animation.COLOR_TRANSITION: for (light, attrs) in lights.items(): self.logger.debug('Setting {} to {}'.format(light, attrs)) self.bridge.set_light(light, attrs) stop_animation = _should_stop() if stop_animation: break elif animation == self.Animation.BLINK: conf = lights[list(lights.keys())[0]] self.logger.debug('Setting lights to {}'.format(conf)) if groups: self.bridge.set_group([g.name for g in groups], conf) else: self.bridge.set_light(lights.keys(), conf) stop_animation = _should_stop() if stop_animation: break except Exception as e: self.logger.warning(e) time.sleep(2) lights = _next_light_attrs(lights) self.logger.info('Stopping animation') self.animation_thread = None self.redis = None self.stop_animation() self.animation_thread = Thread(target=_animate_thread, name='HueAnimate', args=(lights,)) self.animation_thread.start() def _get_redis(self, socket_timeout=1.0): if not self.redis: redis_args = get_backend('redis').redis_args redis_args['socket_timeout'] = socket_timeout self.redis = Redis(**redis_args) return self.redis def status(self): # TODO pass
class hue_rgb(): def __init__(self, _ip): self.Point = collections.namedtuple('Point', ['x', 'y']) self.b = Bridge(_ip) self.b.connect() self.b.get_api() self.group = None self.lights = [] def convert_rgb(self, red, green, blue): red = red / 255 blue = blue / 255 green = green / 255 red = pow((red + 0.055) / (1.0 + 0.055), 2.4) if (red > 0.04045) else (red / 12.92) green = pow( (green + 0.055) / (1.0 + 0.055), 2.4) if (green > 0.04045) else (green / 12.92) blue = pow((blue + 0.055) / (1.0 + 0.055), 2.4) if (blue > 0.04045) else (blue / 12.92) X = red * 0.664511 + green * 0.154324 + blue * 0.162028 Y = red * 0.283881 + green * 0.668433 + blue * 0.047685 Z = red * 0.000088 + green * 0.072310 + blue * 0.986039 if (Z == 0): Z = .1 x = X / (X + Y + Z) y = Y / (X + Y + Z) p = self.Point(X, Y) return p def set_light_list(self): g = self.b.get_group(self.group, 'lights') self.lights = [] lights = self.b.get_light_objects() for light in g: self.lights.append(lights[int(light) - 1]) def get_group_status(self): return self.b.get_group(self.group) def get_all(self): groups = {} for group in self.b.get_group(): groups[str(self.b.get_group( int(group), 'name'))] = self.b.get_group(int(group)) return groups def set_group(self, name): if (name.lower() == 'all'): self.lights = self.b.get_light_objects() else: for group in self.b.get_group(): if (self.b.get_group(int(group), 'name') == str(name)): self.group = int(group) self.set_light_list() def rgb_set(self, rgb): print('IN SET') red = float(rgb[0]) green = float(rgb[1]) blue = float(rgb[2]) print('IN SET') point = self.convert_rgb(red, green, blue) print('point is', point) x = point[0] y = point[1] for light in self.lights: light.xy = [x, y] def brightness(self, amount): for light in self.lights: light.brightness = int(amount) def on(self, state): state = bool(state) for light in self.lights: light.on = state def transition(self, command): for light in self.lights: light.transitiontime = float(command['transitiontime'])
def my_range(start, end, step): while start <= end: yield start start += step #/CUSTOM FOR STATEMENT SETUP #BRIDGE SETUP if b == None: b.connect() print("connecting to bridge...") else: print("bridge is connected") print(b.get_group(1, 'lights')) #/BRIDGE SETUP #GET COLOR LIGHTS for room in b.get_group(): for name in rainbowRooms: iRoom = int(room) if b.get_group(iRoom, 'name') == name.__str__(): for light in b.get_group(iRoom, 'lights'): iLight = int(light) if b.get_light(iLight, 'type') == "Extended color light": colorLights.append(b.get_light(iLight, 'name')) b.set_light(iLight, 'on', True) b.set_light(iLight, 'bri', 254) print(colorLights)
LARGE_FONT = ("Verdana", 25) roomToBeControlled = 0 # create Spotify client spotifyAuthManager = SpotifyOAuth(client_id=spotifyClientId, client_secret=spotifyClientSecret, redirect_uri=spotifyRedirectUri, scope=spotifyScope, open_browser=False, username=spotifyUsername) spotify = spotipy.Spotify(auth_manager=spotifyAuthManager) # create and connect to Hue bridge object b = Bridge(hueBridgeIp) b.connect() lightGroups = b.get_group() tapoDeviceObjects = [] class HomeController(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) if runFullscreen: self.attributes('-fullscreen', True) self.config(cursor="none") container.pack(side="top", fill="both", expand=True)
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
trinkey = serial.Serial(p.device) break else: print("Did not find Slider Trinkey port :(") sys.exit() # If the app is not registered and the button on the Hue Bridge is not pressed, press the button # and call connect() (this only needs to be run a single time) b.connect() b.get_api() is_group = False light = None # First, check if it's a group name. for group_data in b.get_group().values(): if group_data["name"] == LAMP_OR_GROUP_NAME: print("Found group with name", LAMP_OR_GROUP_NAME) is_group = True # If it's not a group, find the lamp by name. if not is_group: light_names = b.get_light_objects("name") light = light_names[LAMP_OR_GROUP_NAME] print("Found light with name", LAMP_OR_GROUP_NAME) current_brightness = None while True: x = trinkey.readline().decode("utf-8") if not x.startswith("Slider: "): continue
import RPi.GPIO as GPIO import time from phue import Bridge b = Bridge('<ip of bridge here>') #b.connect() print(b.get_group(1)) b.set_group(1, 'on', False) on = False GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP) button_two_clicks = 0 default_warm = 400 default_cool = 153 def set_scene(scene_number): print('Set Scene %d' % scene_number) if scene_number == 0: b.set_group(1, 'ct', default_warm) b.set_group(1, 'bri', 254) if scene_number == 1: b.set_group(1, 'ct', default_warm) b.set_group(1, 'bri', 127) if scene_number == 2: b.set_group(1, 'ct', default_warm) b.set_group(1, 'bri', 63)
class PhillipsHueSkill(MycroftSkill): def __init__(self): super(PhillipsHueSkill, self).__init__(name="PhillipsHueSkill") self.brightness_step = int(self.settings.get('brightness_step')) self.color_temperature_step = \ int(self.settings.get('color_temperature_step')) self.verbose = self.settings.get('verbose', False) self.username = self.settings.get('username') if self.username == '': self.username = None self.ip = None # set in _connect_to_bridge self.bridge = None self.default_group = None self.groups_to_ids_map = dict() self.scenes_to_ids_map = dict() @property def connected(self): return self.bridge is not None @property def user_supplied_ip(self): return self.settings.get('ip') != '' @property def user_supplied_username(self): return self.settings.get('username') != '' def _register_with_bridge(self): """ Helper for connecting to the bridge. If we don't have a valid username for the bridge (ip) we are trying to use, this will cause one to be generated. """ self.speak_dialog('connect.to.bridge') i = 0 while i < 30: sleep(1) try: self.bridge = Bridge(self.ip) except PhueRegistrationException: continue else: break if not self.connected: self.speak_dialog('failed.to.register') else: self.speak_dialog('successfully.registered') def _update_bridge_data(self): """ This should be called any time a successful connection is established. It sets some member variables, and ensures that scenes and groups are registered as vocab. """ self.username = self.bridge.username with self.file_system.open('username', 'w') as conf_file: conf_file.write(self.username) if not self.default_group: self._set_default_group(self.settings.get('default_group')) self._register_groups_and_scenes() def _attempt_connection(self): """ This will attempt to connect to the bridge, but will not handle any errors on it's own. Raises ------ UnauthorizedUserException If self.username is not None, and is not registered with the bridge """ if self.user_supplied_ip: self.ip = self.settings.get('ip') else: self.ip = _discover_bridge() if self.username: url = 'http://{ip}/api/{user}'.format(ip=self.ip, user=self.username) data = get(url).json() data = data[0] if isinstance(data, list) else data error = data.get('error') if error: description = error.get('description') if description == "unauthorized user": raise UnauthorizedUserException(self.username) else: raise Exception('Unknown Error: {0}'.format(description)) self.bridge = Bridge(self.ip, self.username) def _connect_to_bridge(self, acknowledge_successful_connection=False): """ Calls _attempt_connection, handling various exceptions by either alerting the user to issues with the config/setup, or registering the application with the bridge. Parameters ---------- acknowledge_successful_connection : bool Speak when a successful connection is established. Returns ------- bool True if a connection is established. """ try: self._attempt_connection() except DeviceNotFoundException: self.speak_dialog('bridge.not.found') return False except ConnectionError: self.speak_dialog('failed.to.connect') if self.user_supplied_ip: self.speak_dialog('ip.in.config') return False except socket.error as e: if 'No route to host' in e.args: self.speak_dialog('no.route') else: self.speak_dialog('failed.to.connect') return False except UnauthorizedUserException: if self.user_supplied_username: self.speak_dialog('invalid.user') return False else: self._register_with_bridge() except PhueRegistrationException: self._register_with_bridge() if not self.connected: return False if acknowledge_successful_connection: self.speak_dialog('successfully.connected') self._update_bridge_data() return True def _set_default_group(self, identifier): """ Sets the group to which commands will be applied, when a group is not specified in the command. Parameters ---------- identifier : str or int The name of the group, or it's integer id Notes ----- If the group does not exist, 0 (all lights) will be used. """ try: self.default_group = Group(self.bridge, identifier) except LookupError: self.speak_dialog('could.not.find.group', {'name': identifier}) self.speak_dialog('using.group.0') self.default_group = Group(self.bridge, 0) def _register_groups_and_scenes(self): """ Register group and scene names as vocab, and update our caches. """ groups = self.bridge.get_group() for id, group in groups.items(): name = group['name'].lower() self.groups_to_ids_map[name] = id self.register_vocabulary(name, "Group") scenes = self.bridge.get_scene() for id, scene in scenes.items(): name = scene['name'].lower() self.scenes_to_ids_map[name] = id self.register_vocabulary(name, "Scene") def initialize(self): """ Attempt to connect to the bridge, and build/register intents. """ self.load_data_files(dirname(__file__)) if self.file_system.exists('username'): if not self.user_supplied_username: with self.file_system.open('username', 'r') as conf_file: self.username = conf_file.read().strip(' \n') try: self._attempt_connection() self._update_bridge_data() except (PhueRegistrationException, DeviceNotFoundException, UnauthorizedUserException, ConnectionError, socket.error): # Swallow it for now; _connect_to_bridge will deal with it pass toggle_intent = IntentBuilder("ToggleIntent") \ .one_of("OffKeyword", "OnKeyword") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(toggle_intent, self.handle_toggle_intent) activate_scene_intent = IntentBuilder("ActivateSceneIntent") \ .require("Scene") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(activate_scene_intent, self.handle_activate_scene_intent) adjust_brightness_intent = IntentBuilder("AdjustBrightnessIntent") \ .one_of("IncreaseKeyword", "DecreaseKeyword", "DimKeyword") \ .one_of("Group", "LightsKeyword") \ .optionally("BrightnessKeyword") \ .build() self.register_intent(adjust_brightness_intent, self.handle_adjust_brightness_intent) set_brightness_intent = IntentBuilder("SetBrightnessIntent") \ .require("Value") \ .one_of("Group", "LightsKeyword") \ .optionally("BrightnessKeyword") \ .build() self.register_intent(set_brightness_intent, self.handle_set_brightness_intent) adjust_color_temperature_intent = \ IntentBuilder("AdjustColorTemperatureIntent") \ .one_of("IncreaseKeyword", "DecreaseKeyword") \ .one_of("Group", "LightsKeyword") \ .require("ColorTemperatureKeyword") \ .build() self.register_intent(adjust_color_temperature_intent, self.handle_adjust_color_temperature_intent) connect_lights_intent = \ IntentBuilder("ConnectLightsIntent") \ .require("ConnectKeyword") \ .one_of("Group", "LightsKeyword") \ .build() self.register_intent(connect_lights_intent, self.handle_connect_lights_intent) @intent_handler def handle_toggle_intent(self, message, group): if "OffKeyword" in message.data: dialog = 'turn.off' group.on = False else: dialog = 'turn.on' group.on = True if self.verbose: self.speak_dialog(dialog) @intent_handler def handle_activate_scene_intent(self, message, group): scene_name = message.data['Scene'].lower() scene_id = self.scenes_to_ids_map[scene_name] if scene_id: if self.verbose: self.speak_dialog('activate.scene', {'scene': scene_name}) self.bridge.activate_scene(group.group_id, scene_id) else: self.speak_dialog('scene.not.found', {'scene': scene_name}) @intent_handler def handle_adjust_brightness_intent(self, message, group): if "IncreaseKeyword" in message.data: brightness = group.brightness + self.brightness_step group.brightness = \ brightness if brightness < 255 else 254 dialog = 'increase.brightness' else: brightness = group.brightness - self.brightness_step group.brightness = brightness if brightness > 0 else 0 dialog = 'decrease.brightness' if self.verbose: self.speak_dialog(dialog) @intent_handler def handle_set_brightness_intent(self, message, group): value = int(message.data['Value'].rstrip('%')) brightness = int(value / 100.0 * 254) group.on = True group.brightness = brightness if self.verbose: self.speak_dialog('set.brightness', {'brightness': value}) @intent_handler def handle_adjust_color_temperature_intent(self, message, group): if "IncreaseKeyword" in message.data: color_temperature = \ group.colortemp_k + self.color_temperature_step group.colortemp_k = \ color_temperature if color_temperature < 6500 else 6500 dialog = 'increase.color.temperature' else: color_temperature = \ group.colortemp_k - self.color_temperature_step group.colortemp_k = \ color_temperature if color_temperature > 2000 else 2000 dialog = 'decrease.color.temperature' if self.verbose: self.speak_dialog(dialog) @intent_handler def handle_connect_lights_intent(self, message, group): if self.user_supplied_ip: self.speak_dialog('ip.in.config') return if self.verbose: self.speak_dialog('connecting') self._connect_to_bridge(acknowledge_successful_connection=True) def stop(self): pass
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(): # turn on/off the lights in a fun fashion. unnecessary b.set_light('Dining Room 1', 'on', True, transitiontime=1)
# If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single time) b.connect() # Get the bridge state (This returns the full dictionary that you can explore) # print( b.get_api() ) print("\n\n") # Prints if light 1 is on or not # print( b.get_light(1, 'on') ) # artery light group GROUP = 3 artery_lights = b.get_group(GROUP, 'lights') artery_lights = list(map(lambda l: int(l), artery_lights)) print(artery_lights) b.set_group(GROUP, 'on', True) red = [0.648427, 0.330856] # red: 255, 0, 0 green = [0.330853, 0.586362] # green: 65, 210, 27 while True: key = getch.getch() print(key) if key == ' ': color = (random.random(), random.random()) print('changing to')
clicks = 0 realClicks = 0 # Import stuff for Hue Lifx from phue import Bridge ##The Hue Api import lifx ##The LIFX Api # Make Connections to and pool Hue / lifx # Create LIFX Connection xLights = lifx.Lifx() #Create Hue Connection b = Bridge('192.168.0.45') hLights = b.get_light_objects() hGroups = b.get_group() #Do this stuff, for like, forever... while True: delta = encoder.get_delta() if delta!=0: # print ("rotate %d " % delta) clicks += delta # print (clicks) # print (clicks % 4) if clicks % 4 == 0: # print ("DERP, THAT'S ONE CLICK REALLY!!") print (clicks / 4) sw_state = switch.get_state()
class HuePlay(object): DEFAULT_GROUP = 'Gaming' GROUP_LIGHTS = [ u'RP Lamp 1', u'RP Lamp 2', ] ATTRIBUTES = [ 'on', 'xy', 'saturation', 'brightness', 'transitiontime' ] def __init__(self, address): self.bridge = Bridge(address) self.bridge.connect() self.scenes = {} def initializeGroups(self, group=DEFAULT_GROUP, lights=GROUP_LIGHTS): if self.bridge.get_group(self.DEFAULT_GROUP) is not None: self.bridge.delete_group(self.DEFAULT_GROUP) self.bridge.create_group(self.DEFAULT_GROUP, self.GROUP_LIGHTS) def setScene(self, name): if name in self.scenes.keys(): light_names = self.bridge.get_light_objects('name') for light in self.GROUP_LIGHTS: light_names[light].on = True light_names[light].xy = self.scenes[name].xy light_names[light].saturation = self.scenes[name].saturation light_names[light].brightness = self.scenes[name].brightness self.last_scene = name def loadScenes(self, scenefile='scenes/scenes.yaml'): with open(scenefile) as f: scene_yaml = yaml.load(f) for s in scene_yaml["scenes"].keys(): temp = scene_yaml["scenes"][s] scene = HueScene(name=s) scene.xy = temp["colors"] scene.saturation = temp["saturation"] scene.brightness = temp["brightness"] self.scenes[s] = scene def setCurrent(self, attribute, value, transition=None): if attribute in self.ATTRIBUTES: light_names = self.bridge.get_light_objects('name') for light in self.GROUP_LIGHTS: tt = light_names[light].transitiontime light_names[light].transitiontime = 1 setattr(light_names[light], attribute, value) light_names[light].transitiontime = tt def setBrightness(self, value): light_names = self.bridge.get_light_objects('name') for light in self.GROUP_LIGHTS: tt = light_names[light].transitiontime light_names[light].transitiontime = 1 light_names[light].brightness = value light_names[light].transitiontime = tt def setXValue(self, value, maximum=127): light_names = self.bridge.get_light_objects('name') for light in self.GROUP_LIGHTS: xvalue = float(value)/maximum yvalue = light_names[light].xy[1] light_names[light].xy = (xvalue, yvalue) def setYValue(self, value, maximum=127): light_names = self.bridge.get_light_objects('name') for light in self.GROUP_LIGHTS: yvalue = float(value)/maximum xvalue = light_names[light].xy[1] light_names[light].xy = (xvalue, yvalue) def toggleLight(self): light_names = self.bridge.get_light_objects('name') for light in self.GROUP_LIGHTS: tt = light_names[light].transitiontime light_names[light].transitiontime = 4 light_names[light].on ^= True light_names[light].transitiontime = tt return light_names[light].on