Esempio n. 1
0
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)

    else:
        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
    print lights()
 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)
Esempio n. 3
0
def quickstart():

    if not os.path.exists(_uname_file_location):

        username = qhue.create_new_username(_bridge_ip)

        with open(_uname_file_location, 'w') as f:
            f.write(username)

    else:

        with open(_uname_file_location, 'r') as f:
            username = f.read()

    b = qhue.Bridge(_bridge_ip, username)

    lights = b.lights

    return b, lights
Esempio n. 4
0
def quickstart():

    if not os.path.exists(_uname_file_location):

        username = qhue.create_new_username(_bridge_ip)

        with open(_uname_file_location, 'w') as f:
            f.write(username)

    else:

        with open(_uname_file_location, 'r') as f:
            username = f.read()

    b = qhue.Bridge(_bridge_ip, username)

    lights = b.lights

    return b, lights
Esempio n. 5
0
 def checkHueUserName(self):
     ip = self._settings.get(["hueBridge"])
     if ip == "":
         self._logger.info("Please configure the Hue's bridge in settings")
         return
     self._logger.info("Checking hue username...")
     if not path.exists(CRED_FILE_PATH):
         while True:
             try:
                 self.hueUsername = create_new_username(ip)
                 break
             except QhueException as err:
                 self._logger.err("Create username failed: {}".format(err))
         with open(CRED_FILE_PATH, "w") as cred_file:
             cred_file.write(self.hueUsername)
     else:
         with open(CRED_FILE_PATH, "r") as cred_file:
             self.hueUsername = cred_file.read()
     self._logger.info("Hue username : %s" % self.hueUsername)
     self.lampTest(3)
Esempio n. 6
0
    def get_bridge(self):
        if not os.path.exists(CRED_FILE_PATH):
            while True:
                try:
                    username = create_new_username(BRIDGE_IP)
                    break
                except QhueException as err:
                    print("Error occurred while creating new user: {}".format(
                        err))
                    return

            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()

        bridge = Bridge(BRIDGE_IP, username)
        return bridge
Esempio n. 7
0
def main():

    # check for a credential file
    if not path.exists(CRED_FILE_PATH):

        print('Please enter the IP adress of the bridge')
        regex = re.compile(IP_REG, flags=re.IGNORECASE)
        BRIDGE_IP = input('> ')

        while not regex.match(BRIDGE_IP):
            print('You did not enter a valid IP adress, please try again')
            BRIDGE_IP = input('> ')

        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+'\n')
            cred_file.write(BRIDGE_IP)

    else:
        with open(CRED_FILE_PATH, "r") as cred_file:
            lines = cred_file.read().split('\n')
            username = lines[0]
            BRIDGE_IP = lines[1]

    # create the bridge resource, passing the captured username
    bridge = Bridge(BRIDGE_IP, username)

    # create a lights resource
    light = bridge.lights
    scheduler(light)
Esempio n. 8
0
def cmd_init_hue(msg):  # pragma: no cover
    reply_to_user(msg, "Association avec votre bridge HUE.")
    reply_to_user(
        msg,
        "Pour m’autoriser à dialoguer avec votre bridge HUE, merci d’appuyer sur le bouton présent sur celui-ci."
    )
    # Récupération du « username » depuis le BRIDGE HUE
    hue_username = create_new_username(HUE_BRIDGE)

    # Récupération du pseudo de la personne qui parle
    pseudo = get_username(msg)

    # Sauvegarde de l’association entre l’username hue et la personne qui parle
    current_user = save_new_user(pseudo,
                                 msg["telegram"]["update"].message.chat.id)
    current_user.settings.hue_username = hue_username
    db_session.merge(current_user)
    db_session.commit()

    # Retour pour le client
    reply_to_user(
        msg,
        "L’association avec votre brigde est maintenant effectif, vous pouvez utiliser toutes les commandes."
    )
Esempio n. 9
0
    def setup_app(self):
        self.connection.add_handler(self.message_handler)
        bridgeip = self.get_config_option("ip", "192.168.80.109")
        self.log.info("Configuration parameter 'ip' was set to %s", bridgeip)



        # check for a credential file
        if not path.exists(CRED_FILE_PATH):

            while True:
                try:
                    username = create_new_username(bridgeip)
                    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()

        # create the bridge resource, passing the captured username
        self.bridge = Bridge(bridgeip, username)
        self.converter = Converter()

        # create a lights resource
        lights = self.bridge.lights

        # query the API and print the results
        for light in lights():
            print self.bridge.lights[light]()
            self.connection.add_device(light, "dimmerrgb")
Esempio n. 10
0
HUE_BRI_DELTA = 32

# --------------------------------------------------------------------------- #
# The actual code
# --------------------------------------------------------------------------- #

# Connect to hue
hue_username = None
config_path = os.path.expanduser(HUE_CONF_PATH)
if os.path.exists(config_path):
    with open(config_path, "r") as f:
        hue_username = f.read()
else:
    while True:
        try:
            hue_username = qhue.create_new_username(HUE_BRIDGE_IP)
            break
        except qhue.QhueException as err:
            print(
                "Error occurred while creating a new username: {}".format(err))

    with open(config_path, "w") as f:
        f.write(hue_username)

hue = qhue.Bridge(HUE_BRIDGE_IP, hue_username)

all_light_group = hue.groups[0]
light_group = hue.groups[1]
ceiling_group = hue.groups[2]

# Open the input device
Esempio n. 11
0
username = "******"

hue_order = [5, 7, 8, 6, 9, 1, 3, 2, 4]

#hue_queue = deque(hue_order)
#hue_queue.rotate(3)


def setlight(lightid='14', on=True, hue=200, bri=128):
    bridge.lights[lightid].state(on=on)
    if on:
        bridge.lights[lightid].state(bri=bri, hue=hue)


if username is None:
    username = create_new_username(BRIDGE_IP)
    print("New user: {} . Put this in the username variable above.".format(
        username))

bridge = Bridge(BRIDGE_IP, username)
lights = bridge.lights()
for num, info in lights.items():
    print("{:16} {}".format(info['name'], num))

v = random.randint(0, 255)


def work_lights():
    for light in hue_order:
        lightid = str(light)
        bridge.lights[lightid].state(on=True)
Esempio n. 12
0
from qhue import create_new_username
import configparser

config = configparser.ConfigParser()
config.read("config.ini")

bridgeAddress = config.get("DEFAULT", "bridgeAddress")
print("brdge at", bridgeAddress)

username = create_new_username(bridgeAddress)
print(username)
Esempio n. 13
0
    if not path.exists(CONFIGDIRPATH):
        makedirs(CONFIGDIRPATH)
    config = ConfigDefault
    writeConfig(config)

# Connect to bridge
if config["EnableHue"]:
    try:
        import qhue
        bridge = qhue.Bridge(config["ip"], config["username"])
        test = bridge.lights()
    except ImportError:
        print(lang["QhueLibMissingMessage"])
    except qhue.qhue.QhueException:
        try:
            config["username"] = qhue.create_new_username(config["ip"])
            bridge = qhue.Bridge(config["ip"], config["username"])
            writeConfig(CONFIG, config)
        except qhue.qhue.QhueException:
            print(lang["HueUsernameCreateTimeOut"])
            exit()
    except:
        config["EnableHue"] = False
        print(lang["HueErrDisabled"])

def setHueLightsState(lights, state):
    if config["EnableHue"]:
        for i in lights:
            bridge.groups[i].action(on=state)

def toggleHueLightsState(lights):
Esempio n. 14
0
			hue_bridges.append(s)
	print("done")

	if len(hue_bridges) == 1:
		hue_ip = get_ip_address(hue_bridges[0].location)
	else:
		print("Multiple bridges found:")
		for h in hue_bridges:
			print("  " + get_ip_address(h.location))
		print("")
		print("Run this script with the IP address you want to use")
		exit(0)
else:
	hue_ip = sys.argv[1]

print("Initializing... ", end='')
try:
	username = qhue.create_new_username(hue_ip)
except qhue.QhueException as err:
	print("\nError occurred while creating a new username: {}".format(err))
	exit(1)
print("done")

print("Writing config file... ", end='')
# create config
with open("config", "w") as cfg_file:
	cfg_file.write("HUE_BRIDGE_IP = \"" + hue_ip + "\"\n")
	cfg_file.write("HUE_USERNAME = \"" + username + "\"\n")
print("done")

Esempio n. 15
0
        if s.hue_bridgeid != None:
            hue_bridges.append(s)
    print("done")

    if len(hue_bridges) == 1:
        hue_ip = get_ip_address(hue_bridges[0].location)
    else:
        print("Multiple bridges found:")
        for h in hue_bridges:
            print("  " + get_ip_address(h.location))
        print("")
        print("Run this script with the IP address you want to use")
        exit(0)
else:
    hue_ip = sys.argv[1]

print("Initializing... ", end='')
try:
    username = qhue.create_new_username(hue_ip)
except qhue.QhueException as err:
    print("\nError occurred while creating a new username: {}".format(err))
    exit(1)
print("done")

print("Writing config file... ", end='')
# create config
with open("config", "w") as cfg_file:
    cfg_file.write("HUE_BRIDGE_IP = \"" + hue_ip + "\"\n")
    cfg_file.write("HUE_USERNAME = \"" + username + "\"\n")
print("done")
Esempio n. 16
0
from os import path
from qhue import Bridge, create_new_username
import requests
i = requests.get("https://www.meethue.com/api/nupnp")
info = i.json()
ipaddress = info[0].get("internalipaddress")
CRED_FILE_PATH = "qhue_username.txt"

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)

    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(ipaddress, username)

def turnon(lightname):
    bright = raw_input("How bright would you like the light(s) to be, where 1 is the dimmest and 254 is the brightest? ")
    if int(bright) >= 1 and int(bright) <= 254:
        b.lights[lightlist[lightname]].state(on = True, bri = int(bright))
    else:
        print "You must enter a number between 1 and 254. "

def turnoff(lightname):
Esempio n. 17
0
from qhue import Bridge, create_new_username
import time

username = create_new_username("192.168.1.204")

b = Bridge("192.168.1.204", username)

print(b.url)
lights = b.lights
print(lights.url)

for i in range(5):
    info = lights[1]()
    status = info['state'].get('on')
    print(status)
    if status is True:
        lights[1].state(on=False)
        print("Lights off")
        time.sleep(3)
    else:
        lights[1].state(on=True)
        print("Lights on")
        time.sleep(3)
Esempio n. 18
0
def main():
    global currentIp
    parser = argparse.ArgumentParser(
        description=
        "A little CLI program to control my lights more easily (v1.1)")

    #Command Options
    parser.add_argument("--setup",
                        action="store_true",
                        help="Automatically setup a hue bridge")
    parser.add_argument(
        "--change",
        action="store_true",
        help="Used to change the brightness/colour/state of a given light")
    parser.add_argument(
        "--rename",
        action="store_true",
        help="Rename a light to make it more easily accessible")
    parser.add_argument(
        "--lights",
        action="store_true",
        help="List all available lights connected to a hue bridge")
    parser.add_argument(
        "--switch",
        action="store_true",
        help="Switch between different profiles for different hue bridge IPs")
    parser.add_argument("--ips",
                        action="store_true",
                        help="List all bridge IPs on your network")
    parser.add_argument("--info",
                        action="store_true",
                        help="Get all the infomation about a light")
    parser.add_argument(
        "--addscene",
        action="store_true",
        help="Creates a scene for a given light based with its current settings"
    )
    parser.add_argument("--scenes",
                        action="store_true",
                        help="List all the scenes")
    parser.add_argument("--delscene",
                        action="store_true",
                        help="Delete a scene")
    parser.add_argument("--overide",
                        action="store_true",
                        help="Delete a scene")

    #Parameters
    parser.add_argument("-scene", type=str, default="")
    parser.add_argument("-name", type=str, default="")
    parser.add_argument("-id", type=str, default="")
    parser.add_argument("-ip", type=str, default="")
    parser.add_argument("-bri", type=int, default=None)
    parser.add_argument("-hue", type=int, default=None)
    parser.add_argument("-sat", type=int, default=None)
    parser.add_argument("-on", action="store_true")
    parser.add_argument("-off", action="store_true")

    args = parser.parse_args()

    args.name = args.name.strip()
    args.id = args.id.strip()
    args.ip = args.ip.strip()

    try:
        try:
            profile = profiles[str(currentIp)]

            ip, username = profile.ip, profile.username

            bridge = qhue.Bridge(ip, username)
        except Exception as e:
            if not args.setup:
                print("Please run hue --setup to get started")
        #setup a bridge profile so it can be referrenced in other commands
        if args.setup:
            #required arguments
            if args.name == "":
                print("-name is a required parameter of the --setup command")
                return

            print("Retrieving Hue Bridge ip:\n")
            #get a list of bridge ips on the users network
            response = requests.get("https://discovery.meethue.com/")
            response.raise_for_status()
            if args.ip:
                ip = args.ip
                #if the user explicitly chooses a bridge ip to connect to, it must be validated to make sure it exists on the network
                if not ip in [
                        bridge["internalipaddress"]
                        for bridge in ast.literal_eval(response.text)
                ]:
                    print("The provided ip could not be found on your network")
                    return
            else:
                try:
                    #if one wasn't explicitly specified, it should just choose to setup with the first one it finds (most people will only have one bridge anyway)
                    ip = ast.literal_eval(
                        response.text)[0]["internalipaddress"]
                except:
                    #if no bridge ips could be found
                    print("Couldn't find a hue bridge on your network :(")
                    return
            print("IP:", ip, "\n")
            print(
                "Press the pair button on the hue bridge to complete the connection process\n"
            )
            #pair the bridge with the program
            try:
                username = qhue.create_new_username(ip, None, 60, 120)
            except qhue.QhueException:
                print("2 minute time limit exceeded")
                raise KeyboardInterrupt()
            print("Username:"******"\n")

            lights = {}

            bridge = qhue.Bridge(ip, username)

            #turn on all the lights so they can be dimmed one by one and the user can work out which light is which
            for light in bridge.lights():
                light = bridge.lights[light]
                try:
                    light.state(on=True)
                    light.state(bri=255)
                except:
                    pass

            input(
                "Turn on all of your lights so they can be identified and then press enter\n"
            )

            for light in bridge.lights():
                light = bridge.lights[light]
                if light()["state"]["on"]:
                    try:
                        light.state(bri=122)
                    except:
                        light.state(on=False)
                    #names are assaigned to each light to make it easier for the user to change them later on
                    name = input(
                        "Enter a name for the light I just turned off:\n"
                    ).strip()
                    while name in lights.values() or name == "":
                        name = input(
                            "That is not a valid name for the light:\n").strip(
                            )
                    lights[str(light()["uniqueid"])] = name
                else:
                    #tell the user that one of the lights couldn't be setup as it was turned off and can't be identified
                    print(
                        f"Light {light()['uniqueid']} was off and thus cannot be identified. You can specify a name for it manually with hue -rn -id <Light Id> -name <Light Name>"
                    )

            #store the bridge profile
            profiles[str(ip)] = Profile(args.name, lights, ip, username)
            pickle.dump([ip, profiles], open(profilesFileLocation, "wb"))

            print(
                f"Profile sucessfully set for this IP and the current IP was switched to {ip}"
            )
            return

        #list all lights connected to a bridge
        elif args.lights:
            print(f"\n{profile.name}\t-\t{profile.ip}\n")

            table = []
            #get the ids and names of all lights connected to the bridge
            for light in bridge.lights():
                light = bridge.lights[light]
                id = light()["uniqueid"]
                try:
                    name = profile.lights[id]
                except KeyError:
                    name = "N/A"  #specify this if the light hasn't been assaigned a name on this profile. this could be because it was added to the bridge after the initial setup of the profile
                table.append(["\t" + name, id])
            #display table function used to make the infomation more presentable and easy to read
            DisplayTable(table)

        #list all bridge ips the user can connect to
        elif args.ips:
            response = requests.get("https://discovery.meethue.com/")
            response.raise_for_status()
            ips = []
            #get ips and names of bridges on the network
            for ip in [
                    bridge["internalipaddress"]
                    for bridge in ast.literal_eval(response.text)
            ]:
                if ip in profiles:
                    ips.append(
                        ["\t" + profiles[ip].name, ip]
                    )  #if the user has already setup this bridge, it will have a name
                else:
                    ips.append(
                        ["\tN/A", ip]
                    )  #otherwise it will not and N/A will be put there instead
            print("Bridge IPs:\n")
            #display table function used to make the infomation more presentable and easy to read
            DisplayTable(ips)

        #renames a light on a bridge profile
        elif args.rename:
            #required parameters for this function
            if args.name == "":
                print("-name is a required parameter of the --rename command")
                return
            if args.id == "":
                print("-id is a required parameter of the --rename command")
                return
            #make sure the specified light id is valid
            if args.id in [
                    bridge.lights[light]()["uniqueid"]
                    for light in bridge.lights()
            ]:
                profile = profiles[str(currentIp)]
                try:
                    oldName = profile.lights[args.id]
                except KeyError:
                    oldName = "N/A"
                #make sure there won't be multiple lights with the same name on the bridge profile
                if args.name not in profile.lights.values():
                    profile.lights[args.id] = args.name
                else:
                    print(
                        f"A light with the name {args.name} already exists in this profile"
                    )
                    return
                #save the changes to the profiles file
                pickle.dump([ip, profiles], open(profilesFileLocation, "wb"))

                print(
                    f"Changed light {args.id} name from {oldName} to {args.name} "
                )
            else:
                print(
                    "Invalid id, use --light to get a list of lights and their ids"
                )

        #command used for turning lights on and off and changing brightness
        elif args.change:
            #get the light
            result = get_light(profile, args)
            if result:
                light, name, id = result
            else:
                return

            if args.on:
                light.state(on=True)
                print(f"Turned On {name} - {id}")

            if not args.scene:
                #if the brightness value was specified but it contained a number outside of the range of 0-255 an error should be thrown
                if args.bri != None:
                    if args.bri < 0 or args.bri > 255:
                        print(
                            "-bri parameter only accepts values between 0-255")
                        return

                if args.hue != None:
                    if args.hue < 0 or args.hue > 65535:
                        print(
                            "-hue parameter only accepts values between 0-65535"
                        )
                        return

                if args.sat != None:
                    if args.sat < 0 or args.sat > 255:
                        print(
                            "-sat parameter only accepts values between 0-255")
                        return

                if args.bri and args.bri != 0:
                    if not light()["state"]["on"]:
                        #turn the light on if it was off beforehand
                        light.state(on=True)
                load = {}
                if args.bri: load["bri"] = args.bri
                if args.hue: load["hue"] = args.hue
                if args.sat: load["sat"] = args.sat
            else:
                try:
                    scene = profile.scenes[args.scene]
                except KeyError:
                    print("There isn't a scene with that name")
                    return
                load = {"hue": scene.hue, "sat": scene.sat, "bri": scene.bri}
            if load != {}:
                light.state(**load)
            #if the user wanted to change the brightness of their light
            if args.bri != 0 and args.bri:
                print(
                    f"Set {name} to HSB: {load['hue'],load['sat'],load['bri']}"
                )
            #turn the light off if the -off keyword was used or the user set -bri to 0
            if args.off or args.bri == 0:
                light.state(on=False)
                print(f"Turned Off {name} - {id}")

        #switch between different hue bridges
        elif args.switch:
            #if the user is switching to a specified bridge ip
            if args.ip != "":
                #the bridge ip must already have a profile associated with it
                if args.ip in profiles:
                    #change the current ip and save it to the profiles file
                    currentIp = args.ip
                    pickle.dump([currentIp, profiles],
                                open(profilesFileLocation, "wb"))
                    print(
                        f"Switched profile to {profiles[currentIp].name} - {currentIp}"
                    )
                else:
                    #if the ip hasn't got a profile for it, reccomend the user sets it up
                    print(
                        f"Couldn't find a profile/bridge with the ip, {args.ip}. Use 'hue --setup -ip {args.ip} -name <profile name>' to get started"
                    )
            #if the user is switching to a given bridge name
            elif args.name != "":
                #search for a profile with the specified name
                profile = list(
                    filter(lambda profile: profiles[profile].name == args.name,
                           profiles))
                if profile == []:
                    print(
                        f"Couldn't find a profile with the name, {args.name}")
                else:
                    #change the current ip and save it to the profiles file
                    currentIp = profiles[profile[0]].ip
                    pickle.dump([currentIp, profiles],
                                open(profilesFileLocation, "wb"))
                    print(f"Switched profile to {args.name} - {currentIp}")
            else:
                print(
                    "Either -name or -ip is a required parameter of the --switch command"
                )
        elif args.info:
            result = get_light(profile, args)
            if result:
                light, name, id = result
            else:
                return

            print("\n" + name + "\t" + id + "\n")

            DisplayTable([["\t" + key, light()["state"][key]]
                          for key in light()["state"]])
        elif args.addscene:
            result = get_light(profile, args)
            if result:
                light, name, id = result
            else:
                return
            light = light()["state"]

            if not args.scene:
                print("-scene is a required parameter of --addscene")

            if "hue" in light:
                profile.scenes[args.scene] = (Scene(light["bri"], light["hue"],
                                                    light["sat"]))
            else:
                profile.scenes[args.scene] = (Scene(light["bri"], 8504, 130))
            pickle.dump([currentIp, profiles], open(profilesFileLocation,
                                                    "wb"))
            print(f"Set a scene called {args.scene} from the light: {name}")
        elif args.delscene:
            if not args.scene:
                print("-scene is a required parameter of --delscene")
            try:
                del profile.scenes[args.scene]
            except KeyError:
                print("There is no scene with that name")
                return
            print(f"Deleted a scene called {args.scene}")
            pickle.dump([currentIp, profiles], open(profilesFileLocation,
                                                    "wb"))
        elif args.scenes:
            table = [[key, profile.scenes[key]]
                     for key in profile.scenes.keys()]
            DisplayTable(table)
        elif args.overide:
            result = get_light(profile, args)
            if not result: return
            light, name, id = result
            state = light()["state"]
            scene = dict(Scene(state["bri"], state["hue"], state["sat"]))
            while True:
                light.state(**scene)
                time.sleep(0.2)

    #handle exceptions
    except KeyboardInterrupt:  #if the user presses ctrl+c
        print("Cancelled")
    except requests.exceptions.ConnectTimeout:  #if the program fails to connect to the bridge
        print(f"Failed to connect to {ip}")
    except KeyError as e:  #an error that will occur when some commands are used before the user has setup a bridge to connect to
        if not str(currentIp) in profiles:
            print(
                "There is no Ip or profile set to retrieve from. Run 'hue --setup -name <profile name>' to get started"
            )
            return
        else:
            print(traceback.format_exc(
            ))  #if another key error occurs then this should show an error