示例#1
0
    def get_bridgeinfo(self):
        if self.bridge.get('serialNumber', '') == '':
            self.br = None
            self.bridge_lights = {}
            self.bridge_groups = {}
            self.bridge_config = {}
            self.bridge_scenes = {}
            self.bridge_sensors = {}
            return
        self.logger.info("get_bridgeinfo: self.bridge = {}".format(
            self.bridge))
        self.br = qhue.Bridge(
            self.bridge['ip'] + ':' + str(self.bridge['port']),
            self.bridge['username'])
        try:
            self.bridge_lights = self.br.lights()
            self.bridge_groups = self.br.groups()
            self.bridge_config = self.br.config()
            self.bridge_scenes = self.br.scenes()
            self.bridge_sensors = self.br.sensors()
        except Exception as e:
            self.logger.error(
                f"Bridge '{self.bridge.get('serialNumber','')}' returned exception {e}"
            )
            self.br = None
            self.bridge_lights = {}
            self.bridge_groups = {}
            self.bridge_config = {}
            self.bridge_scenes = {}
            self.bridge_sensors = {}
            return False

        return True
 def _check_bridge_model(self):
     bridge = qhue.Bridge(self.bridge_ip, None, timeout=QHUE_TIMEOUT)
     try:
         bridge_config = bridge.config()
         model = bridge_config["modelid"]
     except QhueException as exc:
         xbmc.log(
             f"[script.service.hue] Exception: checkBridgeModel {exc.type_id}: {exc.message} {traceback.format_exc()}"
         )
         reporting.process_exception(exc)
         return None
     except requests.RequestException as exc:
         xbmc.log(f"[script.service.hue] Requests exception: {exc}")
         notification(header=_("Hue Service"),
                      message=_(f"Connection Error"),
                      icon=xbmcgui.NOTIFICATION_ERROR)
     if model == "BSB002":
         xbmc.log(f"[script.service.hue] Bridge model OK: {model}")
         return True
     xbmc.log(f"[script.service.hue] Unsupported bridge model: {model}")
     xbmcgui.Dialog().ok(
         _("Unsupported Hue Bridge"),
         _("Hue Bridge V1 (Round) is unsupported. Hue Bridge V2 (Square) is required."
           ))
     return None
示例#3
0
def get_target(args):
    if not args.hue_username and args.hue:
        print("Need to create the username")
        from qhue import create_new_username
        username = create_new_username(args.hue)
        print("Add '--hue-username %s' to the command line and restart" %
              username)
        sys.exit(0)
    print("Will control Philips Hue @ %s" % args.hue)
    b = qhue.Bridge(args.hue, args.hue_username)
    lights = list(map(int, args.hue_lights.split(',')))

    def set_lights(state):
        if state == "blue":
            hue = 46920
        elif state == "green":
            hue = 25500
        elif state == "mix":
            hue = (46920 + 25500) // 2
        else:
            hue = 0
        for light in lights:
            b.lights[light].state(bri=127, hue=hue)
        for light in lights:
            b.lights[light].state(bri=255, hue=hue)

    return set_lights
示例#4
0
    def __init__(self, ip: str, user: str, main_light: int, lights: list, tradfri: 'Tradfri' = None):
        """
            Parameters
            ----------
            ip : str
                Address of Hue Bridge. DNS will be resolved.

            user : str
                The secret string generated when pairing with the Bridge.

            main_lights : int
                The light we want to watch and copy changes from.

            lights : list
                A list of IDs of Hue lights, which should be controlled.

            tradfri : Tradfri
                The Tradfri instance we are controlling with the main light.
        """
        super().__init__(ip, user, main_light, lights)
        self.bridge = qhue.Bridge(ip, user)

        self.hue = None
        self.bri = None
        self.sat = None
        self.state = None
        self.tradfri = tradfri
 def __init__(self, lampname):
     self.name = lampname
     self.bridge = qhue.Bridge(ip, username)
     self.lampid = get_lamp_id_by_name(self.bridge, lampname)
     self.url = self.bridge.lights[self.lampid].url + '/state'
     self.on = self.bridge.lights[self.lampid]()['state']['on']
     self.xy = self.bridge.lights[self.lampid]()['state']['xy']
     self.brightnessPercent = self.bridge.lights[self.lampid]()['state']['bri'] / 255.0
示例#6
0
 def api_create_user(self, devicetype):
     import qhue
     qb = qhue.Bridge(self.url.hostname, None)
     try:
         api_response = qb(devicetype=devicetype, http_method="post")
     except qhue.QhueException:
         # fake the response until we add exception handling in base
         api_response = [{"error": {"type": 101}}]
     return api_response
示例#7
0
 def page_light(self, turn_on):
     """Turn a light used to indicate a page either on or off."""
     (bridge_ip, bridge_code) = self.get_bridge_info()
     bridge = qhue.Bridge(bridge_ip, bridge_code)
     for lid in PAGE_LIGHT:
         if turn_on:
             self.set_light_by_hsl(bridge, lid, (255, 1, 1), 10)
         else:
             self.turn_light_off(bridge, lid, 10)
示例#8
0
def set_scene(scene_name):
    bridge = qhue.Bridge(get_bridge_address(), settings.HUELIGHTS_USERNAME)
    if scene_name not in _cached_scene_names_to_ids:
        for scene_id, scene_info in bridge.scenes().items():
            _cached_scene_names_to_ids[scene_info["name"]] = scene_id

        if scene_name not in _cached_scene_names_to_ids:
            raise RuntimeError("Invalid scene name")

    bridge.groups[0].action(scene=_cached_scene_names_to_ids[scene_name])
示例#9
0
 def __init__(self, lamp_id):
     # not accessible
     ip = HUE_IP
     username = HUE_USERNAME
     # accessible
     self.bridge = qhue.Bridge(ip, username)
     self.getter = self.bridge.lights[lamp_id]()
     self.setter = self.bridge.lights[lamp_id]
     self.is_on = self.getter['state']['on']
     self.colour = self.getter['state']['xy']
     self.name = self.getter['name']
示例#10
0
def get_light(profile, args):
    ip, username = profile.ip, profile.username

    bridge = qhue.Bridge(ip, username)
    #get the light from a specified name
    if args.name != "":
        name = args.name
        light = list(
            filter(lambda l: profile.lights[l] == args.name, profile.lights))
        #find a light id with that name
        if light == []:  #no matches
            print(
                f"Couldn't find a light with the name {args.name} in this profile"
            )
            return
        else:
            #once the id has been retrieved it can be extracted the same way as below
            id = light[0]
            light = list(
                filter(lambda l: bridge.lights()[l]["uniqueid"] == id,
                       bridge.lights()))
            if light != []:
                #if a match was found with the specified id
                light = bridge.lights[light[0]]
            else:
                #this will probably only happen if a bridge was removed from a network (was setup) and the program is still trying to access it
                print(
                    f"Couldn't find a light with the id, {id} associated with {args.name}"
                )
                return
    #get the light from a specified id
    elif args.id != "":
        id = args.id
        #try and get the name of the light if it is in the bridge profile, otherwise just leave it as "N/A"
        try:
            name = profile.lights[id]
        except:
            name = "N/A"
        light = list(
            filter(lambda l: bridge.lights()[l]["uniqueid"] == args.id,
                   bridge.lights()))
        #find a light with
        if light != []:
            light = bridge.lights[light[0]]
        else:
            print(f"Couldn't find a light with the id, {args.id}")
            return
    else:
        #if the name nor id were specified, throw an error to say that one of the two are required
        print(
            "Either the parameter -name or -id are required for the --change command"
        )
        return
    return light, name, id
示例#11
0
    def connect_bridge(self, silent=False):

        xbmc.log(
            f"[script.service.hue] in connect_bridge() with settings: bridgeIP: {self.bridge_ip}, bridgeUser: {self.bridge_user}"
        )

        if self.bridge_ip and self.bridge_user:
            if not self._check_version():
                xbmc.log(
                    "[script.service.hue] in connect_bridge(): Bridge not responding to connection test, attempt finding a new bridge IP."
                )

                if self._discover_bridge_ip():
                    xbmc.log(
                        f"[script.service.hue] in connect_bridge(): New IP found: {self.bridge_ip}. Saving"
                    )
                    ADDON.setSettingString("bridgeIP", self.bridge_ip)
                else:
                    xbmc.log("[script.service.hue] Bridge not found")
                    notification(_("Hue Service"),
                                 _("Bridge connection failed"),
                                 icon=xbmcgui.NOTIFICATION_ERROR)
                    self.connected = False
                    return

            xbmc.log("[script.service.hue] in Connect(): Checking User")
            if self._check_user():
                bridge = qhue.Bridge(self.bridge_ip,
                                     self.bridge_user,
                                     timeout=QHUE_TIMEOUT)
                self.connected = True
                self.bridge = bridge
                xbmc.log(
                    f"[script.service.hue] Successfully connected to Hue Bridge: {self.bridge_ip}"
                )
                if not silent:
                    notification(_("Hue Service"),
                                 _("Hue connected"),
                                 sound=False)
                return
            else:
                xbmc.log("[script.service.hue] Bridge not responding")
                notification(_("Hue Service"),
                             _("Bridge connection failed"),
                             icon=xbmcgui.NOTIFICATION_ERROR)
                self.connected = False

        else:
            xbmc.log("[script.service.hue] Bridge not configured")
            notification(_("Hue Service"),
                         _("Bridge not configured"),
                         icon=xbmcgui.NOTIFICATION_ERROR)
            self.connected = False
示例#12
0
def main():
    """The main function."""
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--config',
                    default=str(Path.home() / '.philipshue.ini'),
                    help='the config file location')
    args = ap.parse_args()

    while True:
        try:
            cp = configparser.ConfigParser()
            cp.read(args.config)
            cf = cp['DEFAULT']
            bridge_location = cf['bridge_location']
            bridge_username = cf['bridge_username']
        except KeyError:
            setup(args.config)
            continue
        break

    print(f'Connecting to {bridge_location}...')
    try:
        bridge = qhue.Bridge(bridge_location, bridge_username)
        num_lights = len(bridge.lights())
        print(f'Connected to {bridge_location}. {num_lights} lights found.')
    except requests.ConnectionError as err:
        print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}')
        sys.exit(1)

    session = PromptSession(
        '> ',
        lexer=PygmentsLexer(Python3Lexer),
        style=style_from_pygments_cls(PYGMENTS_STYLE),
        auto_suggest=AutoSuggestFromHistory(),
        input_processors=[HighlightMatchingBracketProcessor('()[]{}')],
        history=FileHistory(Path.home() / '.philipshue.hist'))
    while True:
        try:
            cmd = session.prompt()
            start = time.perf_counter()
            out = exec_cmd(cmd, bridge=bridge)
            time_taken = time.perf_counter() - start
            prettyprinter.cpprint(out)
            print(f'Time taken: {sgr(1, 34)}{time_taken*1000:.3f} ms{sgr(0)}')
        except KeyboardInterrupt:
            pass
        except EOFError:
            break
        except requests.ConnectionError as err:
            print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}')
            sys.exit(1)
        except Exception as err:
            print(f'{sgr(1, 31)}{err.__class__.__name__}{sgr(0)}: {err}')
示例#13
0
文件: hue.py 项目: xerosbeat/IkaLog
    def __init__(self, host=None, user=None):
        self.enabled = (not host is None)
        if not (host and user):
            self.hue_bridge = None
            return None

        self.check_import()

        import qhue
        try:
            self.hue_bridge = qhue.Bridge(host, user)
        except:
            IkaUtils.dprint('%s: Exception.' % self)
            IkaUtils.dprint(traceback.format_exc())
示例#14
0
    def _check_user(self):
        xbmc.log(
            "[script.service.hue] in user_test() Attempt initial connection")
        b = qhue.Bridge(self.bridge_ip, self.bridge_user, timeout=QHUE_TIMEOUT)
        try:
            zigbee = b.config()['zigbeechannel']
        except (requests.RequestException, qhue.QhueException, KeyError):
            return False

        if zigbee:
            xbmc.log(
                f"[script.service.hue] Hue User Authorized. Bridge Zigbee Channel: {zigbee}"
            )
            return True
        return False
示例#15
0
文件: __init__.py 项目: mptei/plugins
 def get_bridgeinfo(self):
     if self.bridge.get('serialNumber', '') == '':
         self.br = None
         self.bridge_lights = {}
         self.bridge_groups = {}
         self.bridge_config = {}
         self.bridge_scenes = {}
         self.bridge_sensors = {}
         return
     self.logger.info("get_bridgeinfo: self.bridge = {}".format(
         self.bridge))
     self.br = qhue.Bridge(self.bridge['ip'], self.bridge['username'])
     self.bridge_lights = self.br.lights()
     self.bridge_groups = self.br.groups()
     self.bridge_config = self.br.config()
     self.bridge_scenes = self.br.scenes()
     self.bridge_sensors = self.br.sensors()
     return
示例#16
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
示例#17
0
    def _check_version(self):
        b = qhue.Bridge(self.bridge_ip, None, timeout=QHUE_TIMEOUT)
        try:
            api_version = b.config()['apiversion']
        except QhueException as error:
            xbmc.log(
                f"[script.service.hue] Version check connection failed.  {error.type_id}: {error.message} {traceback.format_exc()}"
            )
            reporting.process_exception(error)
            return False
        except requests.RequestException as error:
            xbmc.log(
                f"[script.service.hue] Version check connection failed.  {error}"
            )
            return False
        except KeyError as error:
            notification(_("Hue Service"),
                         _("Bridge outdated. Please update your bridge."),
                         icon=xbmcgui.NOTIFICATION_ERROR)
            xbmc.log(
                f"[script.service.hue] in _version_check():  Connected! Bridge too old: {api_version}, error: {error}"
            )
            return False

        api_split = api_version.split(".")

        if api_version and int(api_split[0]) >= 1 and int(
                api_split[1]) >= 38:  # minimum bridge version 1.38
            xbmc.log(
                f"[script.service.hue] Bridge Found! Hue API version: {api_version}"
            )
            return True

        notification(_("Hue Service"),
                     _("Bridge outdated. Please update your bridge."),
                     icon=xbmcgui.NOTIFICATION_ERROR)
        xbmc.log(
            f"[script.service.hue] in _connection_test():  Connected! Bridge too old: {api_version}"
        )
        return False
示例#18
0
def main():
    """
    main
    """
    hue_bridge = qhue.Bridge(os.environ.get('HUE_BRIDGE'),
                             os.environ.get('HUE_USERNAME'))
    if not hue_bridge:
        print("Oops")
        sys.exit(1)
    sensors = hue_bridge.sensors
    for _, sensor in sensors().items():
        if sensor.get('type') == 'ZLLSwitch':
            __memory__[sensor['uniqueid']] = sensor['state']['lastupdated']
    print("Started")
    sleep_time = os.environ.get('SLEEP_TIME', 0.3)
    while True:
        try:
            for _, sensor in sensors().items():
                if sensor.get('type') == 'ZLLSwitch':
                    check_change((sensor))
            time.sleep(sleep_time)
        except KeyboardInterrupt:
            clean_exit(False, False)
            break
示例#19
0
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
dev = evdev.InputDevice(INPUT_DEVICE)

# Grab exclusive access to all events so gnome doesn't throw a fit
with dev.grab_context():
    for event in dev.read_loop():
        if event.type == ecodes.EV_KEY:
            key_event = KeyEvent(event)

            if key_event.keystate == KeyEvent.key_up:
示例#20
0
def reset_light_brightness(light_states, light_brightness, id):
    if light_states[id] == LightStatesEnum.JUST_TURNED_ON:
        previous_brightness = light_brightness[id]
        lights[id].state(bri=previous_brightness)
        light_states[id] = LightStatesEnum.ON
        log.info("Just reset brightness of %s to: %d" % (getName(id), previous_brightness))


def reset_all_light_brightnesses(light_states, light_brightness):
    for light in light_states:
        reset_light_brightness(light_states, light_brightness, light)


if __name__ == "__main__":
    b = qhue.Bridge(credentials.BRIDGE_IP, credentials.USERNAME)
    lights = b.lights

    light_states = {}
    for light in lights():
        light_states[light] = LightStatesEnum.UNKNOWN
    light_brightness = {}
    for light in lights():
        light_brightness[light] = -1

    while True:
        try:
            snapShot = lights()
            update_light_states(light_states, light_brightness, snapShot)
            reset_all_light_brightnesses(light_states, light_brightness)
示例#21
0
except IOError:
    logPrint("Could not find configuration file!", 40)
    sys.exit("Aborting ...")
else:
    with stream:
        try:
            config = yaml.safe_load(stream)
            logPrint("Configuration file loaded successfully.", 20)
        except yaml.YAMLError as yaml_error:
            logPrint(
                "A YAML error was raised while reading the configuration file: "
                + str(yaml_error), 40)
            sys.exit("Aborting ...")

"Initialising Hue bridge object from Qhue"
hue_bridge = qhue.Bridge(config["hue"]["ip"], config["hue"]["key"])

"Load Hue groups"
try:
    hue_groups = hue_bridge.groups
except qhue.QhueException as error:
    logPrint("Hue related error thrown: " + str(error) + ".", 40)
    sys.exit("Aborting ...")

"Get Chromecast device"
cast = get_ccast()
logPrint("Got Chromecast: " + str(cast.device), 20)
sleep(1)

while True:
    if ccast_active(cast):
示例#22
0
文件: all-off.py 项目: andrsd/rpi-hue
#!/usr/bin/env python2
#
# Turn all lights off
#

import qhue

CONFIG_FILE = "config"

execfile(CONFIG_FILE)
b = qhue.Bridge(HUE_BRIDGE_IP, HUE_USERNAME)
b.groups['0'].action(on=False)

示例#23
0
from __future__ import division
from flask import render_template
from flask import request
from hue import app
import json
import qhue

bridge = qhue.Bridge(app.config["bridge_ip"], app.config["bridge_user"])


@app.route("/state", methods=["POST"])
def change_light_state():
    form = request.get_json()
    bridge.lights[form["light"]].state(on=form["state"])
    return "", 200


@app.route("/light/<light>", methods=["GET"])
def get_light_state(light):
    return json.dumps(bridge.lights[light]())


@app.route("/light_test/<light>", methods=["GET"])
def get_light_state_test(light):
    color_light = dict(
        type="Extended color light",
        name="Hue color light 1",
        state={"reachable": True,
               "on": True})
    return json.dumps(color_light)
示例#24
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
示例#25
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._bridge_impl: qhue.Bridge = qhue.Bridge(str(self.ip),
                                                  self.username)
示例#26
0
 def api_validate_user(self):
     import qhue
     qb = qhue.Bridge(self.url.hostname, self.url.username)
     return qb.config()