class HueController: def __init__(self): try: with open('.hueusername') as f: bridge_data = json.loads(f.read()) except: logger.warn("Bridge not authorised, need to press the button!") bridge_data = json.loads( requests.get('https://www.meethue.com/api/nupnp').text)[0] bridge_data['username'] = create_new_username( bridge_data['internalipaddress']) with open('.hueusername', 'w') as f: f.write(json.dumps(bridge_data)) self.bridge = Bridge(bridge_data['internalipaddress'], bridge_data['username']) logger.info("Successfully connected to Hue Bridge {}".format( bridge_data['internalipaddress'])) def print_all_lights(self): rooms = self.bridge.groups() for id, light in self.bridge.lights().items(): room = [r for r in rooms.values() if id in r['lights']] logger.info("[{}]: {} ({}){}".format( id, light['name'], light['type'], " in {}".format(room[0]['name']) if room else "")) def set_light(self, id, *args, **kwargs): self.bridge.lights[id].state(**kwargs) def perform(self, action): self.set_light(action['id'], bri=action['brightness'], hue=action['hue'])
def lighting_on(): client = MongoClient("mongodb://ec2-52-89-213-104.us-west-2.compute.amazonaws.com:27017/") db = client["Alfr3d_DB"] devicesCollection = db["devices"] logger.info("looking for devices") for device in devicesCollection.find({"name": "hue"}): logger.info("device found: " + str(device)) logger.info("looking for apikeys") username = config.get("HUE dev", str(device["MAC"]).replace(":", "")) logger.info("found key: " + str(username)) bridge = Bridge(device["IP"], username) logger.info(str(bridge.lights())) lights_data = json.loads(json.dumps(bridge.lights())) for light in lights_data: hue = light_hue() hue.number = light hue.ip = device["IP"] hue.username = username logger.info("all lights on") hue.hue_on()
def __init__(self, ip, username): self.ipAddress = ip self.username = username self.bridge = Bridge(self.ipAddress, self.username) # Key is the qhue object, value is the HuePhillipsType object self.lights, self.groups, self.zones, self.rooms = {}, {}, {}, {} self.createLights() self.createGroups()
def authenticate(self): # Data.Save("hue_username", None) if not self.username: try: self.username = create_new_username(self.hub_ip) except: pass Data.Save("hue_username", self.username) self.bridge = Bridge(self.hub_ip, self.username)
def __config(self): config = ConfigServiceImpl() ip = config.getOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.IP_OPTION) username = config.getOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.USERNAME_OPTION) if(username is None): username = self.getUsername(ip) config.setOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.USERNAME_OPTION, username) self.bridge = Bridge(ip, username)
def __init__(self, name, timer, config, logger): self.name = name self.config = config self.logger = logger self.mode = HueClass.MOTION self.timer = timer self.lightState = False self.initConfig() self.b = Bridge(self.ip, self.user) self.logger.info('Init Hue OK')
def find_a_light(hue, group_name): """Finds an appropriate light and returns it.""" hue = Bridge("192.168.1.11", "newdeveloper") # hue(devicetype="test user", username="******", http_method="post") groups = hue.groups() for item in groups: item_name = hue.groups(item)["name"] if item_name == group_name: lights = hue.groups(item)["lights"] break return lights
def main(): global bridge, lights, influxClient, client # create the bridge resource, passing the captured user name config = get_file(CONFIG_FILE_PATH) user = get_file(CRED_FILE_PATH) bridge = Bridge(config['bridge'], user['hue']) # create a lights resource lights = bridge.lights # MQTT local broker client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(BROKER_ADDRESS, BROKER_PORT) # connect to the database connect_to_ddbb() # start my threads # override_default_values() lights_weather_indication() # lights_schedule() # lights_rule() while(True): time.sleep(0.5)
def build_lights(cls): bridge = Bridge(HUE_BRIDGE_IP, HUE_BRIDGE_USERNAME) lights_json = cls.get_updated_lights_json(bridge) return [ Light(bridge, light_num, light_json) for light_num, light_json in lights_json.iteritems() ]
def sleepsequence(): bridge = Bridge(BRIDGE_IP, USERNAME) #dim other bedroom light bridge.lights[1].state(on=False) #start sequence on chosen light (LIGHT_ID) bridge.lights[LIGHT_ID].state(on=True, hue=SLEEP_HUE, bri=SLEEP_BRI, sat=SLEEP_SAT) sleep_bri = SLEEP_BRI #increase period from 5.4s to 10s (6bpm) & start_sequence = list(range(60, 100, 2)) #keep pace from this moment untill 8min after start end_sequence = [100] * int((8 * 600 - sum(start_sequence)) // 100) for period in start_sequence + end_sequence: #print('seq,period:{}, bri:{}'.format(period,sleep_bri)) up_transition = int(0.4 * period) down_transition = int(0.6 * period) sleep_bri = int(max(sleep_bri - 5, SLEEP_BRI / 4)) bridge.lights[LIGHT_ID].state(on=False, transitiontime=down_transition) time.sleep(down_transition / 10) bridge.lights[LIGHT_ID].state(on=True, hue=SLEEP_HUE, bri=sleep_bri, sat=SLEEP_SAT, transitiontime=up_transition) time.sleep(up_transition / 10) bridge.lights[LIGHT_ID].state(on=False, transitiontime=down_transition)
def main(): # check for a credential file if not path.exists(CRED_FILE_PATH): while True: try: username = create_new_username(BRIDGE_IP) break except QhueException as err: print( "Error occurred while creating a new username: {}".format( err)) # store the username in a credential file with open(CRED_FILE_PATH, "w") as cred_file: cred_file.write(username) print("Username saved in", CRED_FILE_PATH) else: print("Reading username from", CRED_FILE_PATH) with open(CRED_FILE_PATH, "r") as cred_file: username = cred_file.read() # create the bridge resource, passing the captured username bridge = Bridge(BRIDGE_IP, username) # create a lights resource lights = bridge.lights # query the API and print the results as JSON print(json.dumps(lights(), indent=2))
def __init__(self, args, verbose=False): self.verbose = verbose self.bridgeIP = args.get('bridgeIP') self.username = args.get('username') try: from qhue import Bridge except ImportError: exit("For using PhilipsHue is necessary to import it's bibliotec\n\ Please install it with: sudo pip install qhue") self.bridge = Bridge(self.bridgeIP, self.username) self.lights = self.bridge.lights
class PhilipsHueAutomation(Automation): """ Class provides an abstract instance of Automation to interface with the Philips Hue service. """ def __init__(self, hub_ip): self.username = Data.Load("hue_username") self.hub_ip = hub_ip self.p_light_groups = None self.bridge = None self.authenticate() self.p_name = "Philips Hue" # This cannot change. There are quite a few things keying off this name @property def name(self): return self.p_name def has_username(self): if self.username: return True return False def is_authenticated(self): try: self.bridge() return True except: return False def authenticate(self): # Data.Save("hue_username", None) if not self.username: try: self.username = create_new_username(self.hub_ip) except: pass Data.Save("hue_username", self.username) self.bridge = Bridge(self.hub_ip, self.username) def light_groups(self): self.p_light_groups = list() groups = self.bridge.groups() for group_id in groups: g = dict() if groups[group_id]['lights']: g['name'] = groups[group_id]['name'] g['id'] = group_id self.p_light_groups.append(g) return self.p_light_groups def change_group_state(self, lights, powered=False, dim=False): if dim: brightness = 0 else: brightness = 255 for light in lights: Log(self.bridge.groups[light]()) self.bridge.groups[light].action(on=powered, bri=brightness)
def hue_toggle(self): bridge = Bridge(self.ip, self.username) print bridge.lights[self.number]()['state']['on'] if bridge.lights[self.number]()['state']['on']: self.hue_off() else: self.hue_on()
def __init__(self): try: with open('.hueusername') as f: bridge_data = json.loads(f.read()) except: logger.warn("Bridge not authorised, need to press the button!") bridge_data = json.loads( requests.get('https://www.meethue.com/api/nupnp').text)[0] bridge_data['username'] = create_new_username( bridge_data['internalipaddress']) with open('.hueusername', 'w') as f: f.write(json.dumps(bridge_data)) self.bridge = Bridge(bridge_data['internalipaddress'], bridge_data['username']) logger.info("Successfully connected to Hue Bridge {}".format( bridge_data['internalipaddress']))
def bridge(self): if self.hue_bridge == None: found_bridges = discoverhue.find_bridges() if len(found_bridges) > 0: bridge_ip = urlparse(list(found_bridges.values())[0]).netloc self.hue_bridge = Bridge(bridge_ip, self.username) return self.hue_bridge
def __init__(self): self.b = Bridge("10.10.10.162", "Z2OGNqw1IseduPspV9dh3kfOIf2uLFo1Qlr9LzW7") print(self.b.url) lights = self.b.lights # Creates a new Resource with its own URL print(lights.url) # Should have '/lights' on the end # Let's actually call the API and print the results print(lights())
class HueServiceImpl(RoutineInterface): CONFIG_FILE_PATH = 'alarm_clock.ini' SECTION_NAME = 'hue' IP_OPTION_NAME = 'ip' USERNAME_OPTION_NAME = 'username' __instance = None @staticmethod def getInstance(): if HueServiceImpl.__instance == None: HueServiceImpl() return HueServiceImpl.__instance def __init__(self): if HueServiceImpl.__instance != None: raise Exception("This class is a singleton!") else: self.__config() HueServiceImpl.__instance = self def __config(self): config = ConfigServiceImpl() ip = config.getOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.IP_OPTION) username = config.getOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.USERNAME_OPTION) if(username is None): username = self.getUsername(ip) config.setOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.USERNAME_OPTION, username) self.bridge = Bridge(ip, username) def getUsername(self, ip): while True: try: username = create_new_username(ip) break except QhueException as err: print("Error occurred while creating a new username: {}".format(err)) return username def doRoutine(self, args): transitionTime = args['transitionMins'] * 600 self.bridge.groups(1, 'action', on=True, bri=1, sat=254) self.bridge.groups(1, 'action', bri=254, sat=0, transitiontime=int(transitionTime))
def cmd_communicate_hue_server(msg, ressource, bri): # pragma: no cover pseudo = get_username(msg) current_user = User.query.filter_by(username=pseudo).one() if "hue_username" in current_user.settings: Bridge(HUE_BRIDGE, current_user.settings.hue_username) else: reply_to_user( msg, "Pour utiliser les commandes HUE, vous devez faire « hue init »")
class Status: def __init__(self): self.username = os.environ['HUE_USER'] def set_bridge(self, ip=None): self.bridge = Bridge(ip, self.username) def rooms(self): print(yaml.safe_dump(self.bridge.groups(), indent=2))
def main(): global running signal.signal(signal.SIGTERM, _handle_signal) signal.signal(signal.SIGINT, _handle_signal) if not path.exists(CRED_FILE_PATH): while True: try: username = create_new_username(BRIDGE_IP) break except QhueException as err: print "Error occurred while creating a new username: {}".format( err) # store the username in a credential file with open(CRED_FILE_PATH, "w") as cred_file: cred_file.write(username) else: with open(CRED_FILE_PATH, "r") as cred_file: username = cred_file.read() b = Bridge(BRIDGE_IP, username) wonderwareOnline = WonderwareOnline('https://online.wonderware.com') header = '' with open(WWO_AUTH_HEADER, "r") as cred_file: header = cred_file.read() while running: startCollectingStates = datetime.datetime.now() lights = b.lights csv = WonderwareOnlineCSV() print 'Lights' for light in lights(): for stateItem in lights[light]()['state']: if stateItem == 'xy': continue csv.add_value(light + '.' + stateItem, lights[light]()['state'][stateItem]) print csv.build() wonderwareOnline.send_csv(header, csv.build()) if (running == False): break endCollectingStates = datetime.datetime.now() waitTimeInMilli = (60000000 - (endCollectingStates - startCollectingStates).microseconds) / 1000000.0 print 'waiting ' print waitTimeInMilli time.sleep(waitTimeInMilli)
class HuePhillipsBridge: def __init__(self, ip, username): self.ipAddress = ip self.username = username self.bridge = Bridge(self.ipAddress, self.username) # Key is the qhue object, value is the HuePhillipsType object self.lights, self.groups, self.zones, self.rooms = {}, {}, {}, {} self.createLights() self.createGroups() def createLights(self): for light in self.bridge.lights().keys(): print(light) self.lights[light] = HuePhillipsLight(self.bridge.lights[light]) def createGroups(self): for group in self.bridge.groups().keys(): realGroup = self.bridge.groups[group] if realGroup()['type'] == 'Zone': self.groups[group] = HuePhillipsZone( realGroup, self.getLightsFromGroup(realGroup)) self.zones[group] = self.groups[group] elif realGroup()['type'] == 'Room': self.groups[group] = HuePhillipsRoom( realGroup, self.getLightsFromGroup(realGroup)) self.rooms[group] = self.groups[group] def getAllLights(self): return list(self.lights.values()) def getLightsFromGroup(self, group): groupLights = [] for light in group()['lights']: groupLights.append(self.lights[light]) return groupLights def getRooms(self): return self.rooms.values() def getZones(self): return self.zones.values() def getGroups(self): return self.groups.values()
def on_after_startup(self): self._logger.info("Octohue is alive!") if self._settings.get(["statusDict"]) == '': self._logger.info("Bootstrapping Octohue Status Defaults") self._settings.set( ["statusDict"], { 'Connected': { 'colour': '#FFFFFF', 'ct': 155, 'brightness': 255, 'turnoff': False }, 'Disconnected': { 'colour': '', 'ct': 155, 'brightness': "", 'turnoff': True }, 'PrintStarted': { 'colour': '#FFFFFF', 'ct': 155, 'brightness': 255, 'turnoff': False }, 'PrintResumed': { 'colour': '#FFFFFF', 'ct': 155, 'brightness': 255, 'turnoff': False }, 'PrintDone': { 'colour': '#33FF36', 'ct': 155, 'brightness': 255, 'turnoff': False }, 'PrintFailed': { 'colour': '#FF0000', 'ct': 155, 'brightness': 255, 'turnoff': False } }) self._settings.save() self._logger.debug( "Bridge Address is %s" % self._settings.get(['bridgeaddr']) if self._settings. get(['bridgeaddr']) else "Please set Bridge Address in settings") self._logger.debug( "Hue Username is %s" % self._settings.get(['husername']) if self._settings. get(['husername']) else "Please set Hue Username in settings") self.pbridge = Bridge(self._settings.get(['bridgeaddr']), self._settings.get(['husername'])) self._logger.debug("Bridge established at: %s" % self.pbridge.url)
def __init__(self, bridge_info=None, ttime=None): """Initialize a transmitter, but don't start it yet.""" if bridge_info is None: self.bridge, _ = quickstart.quickstart() else: self.bridge = Bridge(*bridge_info) self.lamps = get_lamps(self.bridge) if ttime is not None: for lamp in self.lamps: lamp.ttime = ttime
def init_config(): IP = str(input("Please enter your hue bridge IP address: ")) if IP == "": print( 'Visit https://huetips.com/help/how-to-find-my-bridge-ip-address/ to know how to get your bridge IP address' ) sleep(300) username = create_new_username(IP) config = { 'IP': IP, 'username': username, "loops_per_sec": 2.0, "m_sat": 185, "r_sat": 70, "m_bri": 70, "r_bri": 50, "divider": 5, "crop": 1, "bezel": 1 } b = Bridge(config['IP'], config['username']) print('Please enter the number beside the lamp that you want to use :') for lamp in b.lights(): print(lamp, b.lights()[lamp]['name']) print() chosen_light = input() if chosen_light == "": print() print() print( "------- Please enter a number correspond to the desired bulb : -------" ) print() chosen_light = input() print() print() config['chosen_light'] = int(chosen_light) with open(directory + 'config.json', 'w') as fp: json.dump(config, fp)
def lightingOn(): client = MongoClient('mongodb://ec2-52-89-213-104.us-west-2.compute.amazonaws.com:27017/') client.Alfr3d_DB.authenticate(db_user,db_pass) db = client['Alfr3d_DB'] devicesCollection = db['devices'] logger.info("looking for devices") for device in devicesCollection.find({"$and":[ {"type":'lights'}, {"location.name":socket.gethostname()} ]}): logger.info("device found: "+ str(device)) if device['name'].startswith("hue"): logger.info("looking for apikeys") username = config.get("HUE dev", str(device['MAC']).replace(':','')) logger.info("found key: "+ str(username)) bridge = Bridge(device['IP'], username) logger.info(str(bridge.lights())) lights_data = json.loads(json.dumps(bridge.lights())) for light in lights_data: hue = light_hue() hue.number=light hue.ip = device['IP'] hue.username = username logger.info("all lights on") hue.hue_on() elif device['name'].startswith("Lifx"): bulb_label = device['name'] logger.info("looking for apikeys") lifx_token = config.get("Lifx", "token") logger.info("found key: "+ str(lifx_token)) headers = {"Authorization": "Bearer %s" % lifx_token,} response = requests.put('https://api.lifx.com/v1/lights/label:'+bulb_label+'/state', data={"power": "on"}, headers=headers) if response.json()[u'results'][0][u'status'] != u'ok': logger.error("failed to turn off the bulb "+str(bulb_label))
def activate_scene(scene_name): """ Activate a specific scene if the lights are already on """ b = Bridge(bridge_ip, bridge_username) scenes = b.scenes() for scene_id, scene in scenes.items(): if scene['name'] == scene_name: # Variable to store the current light state current_lightstates = {} status = b.scenes[scene_id](http_method='get') lightstates = status['lightstates'] # Check the current status of the lights # If every lights involved in this scene # are already off, don't change anything # It might means it is the day everything_is_off = True for light_id, light in lightstates.items(): light_status = b.lights[light_id](http_method='get') # Save the status of this light buble current_lightstates[light_id] = light_status['state'] if light_status['state']['on'] == True: everything_is_off = False if everything_is_off: # Save the current state (with everything off) save_current_state(current_lightstates) return False for light_id, light in lightstates.items(): if light['on'] == True: b.lights[light_id].state(on=True, bri=light['bri'], ct=light['ct']) else: b.lights[light_id].state(on=False) # Let's save the current state of the lights involved in this scene save_current_state(current_lightstates) return True
def process(self, inport, msg): hueUser = "******" bridge = Bridge("10.0.0.159", hueUser) converter = Converter() # Convert farbgeber to Hue xy v1xy = converter.rgb_to_xy(msg.data['v1'][0], msg.data['v1'][1], msg.data['v1'][2]) cxy = converter.rgb_to_xy(msg.data['c'][0], msg.data['c'][1], msg.data['c'][2]) contrasted = True # Send to all lights. First light found gets contrast color for lightId in bridge.lights(): if contrasted: bridge.lights[lightId].state(xy=v1xy) contrasted = False else: contrasted = True bridge.lights[lightId].state(xy=cxy) # Send light status out self.send('out', bridge.lights()) self.ack(msg)
class HueLightControler(object): """Class for setting the color of hue bulbs.""" def __init__(self, brige_ip, user): self.bridge = Bridge(brige_ip, user) self.lights = self.bridge.lights() def set_hue_color(self, lightid, red, green, blue): hsv = rgb_to_hsv((red, green, blue)) self.bridge.lights[lightid].state(on=True, hue=round((hsv[0] * 65535) / 360), sat=round(hsv[1] * 255), bri=round(hsv[2] * 255))
def on_settings_save(self, data): octoprint.plugin.SettingsPlugin.on_settings_save(self, data) self._logger.debug( "Saved Bridge Address: %s" % self._settings.get(['bridgeaddr']) if self._settings. get(['bridgeaddr']) else "Please set Bridge Address in settings") self._logger.debug( "Saved Hue Username: %s" % self._settings.get(['husername']) if self._settings. get(['husername']) else "Please set Hue Username in settings") self.pbridge = Bridge(self._settings.get(['bridgeaddr']), self._settings.get(['husername'])) self._logger.debug("New Bridge established at: %s" % self.pbridge.url)
def main(): # https://developers.google.com/calendar/quickstart/python # Initialize Calendar API creds = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('calendar', 'v3', credentials=creds) # https://developers.meethue.com/develop/hue-api/lights-api/ # https://github.com/quentinsf/qhue # Initialize Philips Hue Bridge bridge = Bridge(BRIDGE_IP, BRIDGE_USERNAME) lights = bridge.lights now_time = datetime.datetime.now().time() if now_time < WORK_DAY_END: TurnOnLights(lights) while now_time < WORK_DAY_END: now_time = datetime.datetime.now().time() # Identify if there is a GVC coming up or not event_type = GetCalendarEvents(service) if event_type == 'GVC': SetGVCColor(lights) elif event_type == 'Ambient': SetAmbientColor(lights) if LOGGING: print( 'Sleeping for {} seconds \n'.format(LIGHT_CHANGE_INTERVAL_SEC)) time.sleep(LIGHT_CHANGE_INTERVAL_SEC) print('You are done working, now go play!') TurnOffLights(lights)
def init(self): self.host = self.config(BRIDGE_HOST_CONFIG) self.username = self.config(BRIDGE_USERNAME_CONFIG) if not self.host: raise StopAndTalkException( "Bridge host not configured. Usage: !config " + BRIDGE_HOST_CONFIG + " <host> (e.g. 192.168.1.x, ...)") if not self.username: raise StopAndTalkException( "Username not configured. Usage: !config " + BRIDGE_USERNAME_CONFIG + " <username>") self.bridge = Bridge(self.host, self.username)