Ejemplo n.º 1
0
    def tests_cookies(self, m):
        """Check that cookies are saved and loaded successfully."""
        m.post(CONST.LOGIN_URL, text=LOGIN.post_response_ok())
        m.get(CONST.OAUTH_TOKEN_URL, text=OAUTH_CLAIMS.get_response_ok())
        m.post(CONST.LOGOUT_URL, text=LOGOUT.post_response_ok())
        m.get(CONST.DEVICES_URL, text=DEVICES.EMPTY_DEVICE_RESPONSE)
        m.get(CONST.PANEL_URL, text=PANEL.get_response_ok())

        # Define test pickle file and cleanup old one if exists
        cache_path = "./test_cookies.pickle"

        if os.path.exists(cache_path):
            os.remove(cache_path)

        # Assert that no cookies file exists
        self.assertFalse(os.path.exists(cache_path))

        # Create abode
        abode = abodepy.Abode(username='******',
                              password='******',
                              auto_login=False,
                              get_devices=False,
                              disable_cache=False,
                              cache_path=cache_path)

        # Mock cookie created by Abode after login
        cookie = requests.cookies.create_cookie(name='SESSION', value='COOKIE')
        # pylint: disable=protected-access
        abode._session.cookies.set_cookie(cookie)

        abode.login()

        # Test that our cookies are fully realized prior to login
        # pylint: disable=W0212
        self.assertIsNotNone(abode._cache['id'])
        self.assertIsNotNone(abode._cache['password'])
        self.assertIsNotNone(abode._cache['uuid'])
        self.assertIsNotNone(abode._cache['cookies'])

        # Test that we now have a cookies file
        self.assertTrue(os.path.exists(cache_path))

        # Copy our current cookies file and data
        first_cookies_data = abode._cache

        # New abode instance reads in old data
        abode = abodepy.Abode(username='******',
                              password='******',
                              auto_login=False,
                              get_devices=False,
                              disable_cache=False,
                              cache_path=cache_path)

        # Test that the cookie data is the same
        self.assertEqual(abode._cache['uuid'], first_cookies_data['uuid'])

        # Cleanup cookies
        os.remove(cache_path)
Ejemplo n.º 2
0
    def tests_auto_login(self, m):
        """Test that automatic login works."""
        auth_token = MOCK.AUTH_TOKEN
        user_json = USER.get_response_ok()
        login_json = LOGIN.post_response_ok(auth_token, user_json)
        panel_json = PANEL.get_response_ok()

        m.post(CONST.LOGIN_URL, text=login_json)
        m.get(CONST.OAUTH_TOKEN_URL, text=OAUTH_CLAIMS.get_response_ok())
        m.get(CONST.PANEL_URL, text=panel_json)
        m.post(CONST.LOGOUT_URL, text=LOGOUT.post_response_ok())

        abode = abodepy.Abode(username='******',
                              password='******',
                              auto_login=True,
                              get_devices=False,
                              disable_cache=True)

        # pylint: disable=W0212
        self.assertEqual(abode._cache[CONST.ID], 'fizz')
        self.assertEqual(abode._cache[CONST.PASSWORD], 'buzz')
        self.assertEqual(abode._token, MOCK.AUTH_TOKEN)
        self.assertEqual(abode._panel, json.loads(panel_json))
        self.assertEqual(abode._user, json.loads(user_json))
        self.assertIsNone(abode._devices)
        self.assertIsNone(abode._automations)

        abode.logout()

        abode = None
Ejemplo n.º 3
0
    def test_invalid_cookies(self, m):
        """Check that empty cookies file is loaded successfully."""
        m.post(CONST.LOGIN_URL, text=LOGIN.post_response_ok())
        m.get(CONST.OAUTH_TOKEN_URL, text=OAUTH_CLAIMS.get_response_ok())
        m.post(CONST.LOGOUT_URL, text=LOGOUT.post_response_ok())
        m.get(CONST.DEVICES_URL, text=DEVICES.EMPTY_DEVICE_RESPONSE)
        m.get(CONST.PANEL_URL, text=PANEL.get_response_ok())

        # Test empty cookies file
        invalid_cache_path = "./test_cookies_invalid.pickle"

        # Remove the file if it exists
        if os.path.exists(invalid_cache_path):
            os.remove(invalid_cache_path)

        # Create an invalid pickle file
        with open(invalid_cache_path, 'a') as file:
            file.write("Invalid file goes here")

        # Assert that cookies file exists
        self.assertTrue(os.path.exists(invalid_cache_path))

        # Cookies are created
        empty_abode = abodepy.Abode(username='******',
                                    password='******',
                                    auto_login=True,
                                    get_devices=False,
                                    disable_cache=False,
                                    cache_path=invalid_cache_path)

        # Test that some cache exists
        # pylint: disable=W0212
        self.assertIsNotNone(empty_abode._cache['id'])
        self.assertIsNotNone(empty_abode._cache['password'])
        self.assertIsNotNone(empty_abode._cache['uuid'])
Ejemplo n.º 4
0
    def tests_auto_fetch(self, m):
        """Test that automatic device and automation retrieval works."""
        auth_token = MOCK.AUTH_TOKEN
        user_json = USER.get_response_ok()
        login_json = LOGIN.post_response_ok(auth_token, user_json)
        panel_json = PANEL.get_response_ok()

        m.post(CONST.LOGIN_URL, text=login_json)
        m.get(CONST.PANEL_URL, text=panel_json)
        m.get(CONST.DEVICES_URL, text=DEVICES.EMPTY_DEVICE_RESPONSE)
        m.get(CONST.AUTOMATION_URL, text=DEVICES.EMPTY_DEVICE_RESPONSE)
        m.post(CONST.LOGOUT_URL, text=LOGOUT.post_response_ok())

        abode = abodepy.Abode(username='******',
                              password='******',
                              auto_login=False,
                              get_devices=True,
                              get_automations=True)

        # pylint: disable=W0212
        self.assertEqual(abode._username, 'fizz')
        self.assertEqual(abode._password, 'buzz')
        self.assertEqual(abode._token, MOCK.AUTH_TOKEN)
        self.assertEqual(abode._panel, json.loads(panel_json))
        self.assertEqual(abode._user, json.loads(user_json))

        # Contains one device, our alarm
        self.assertEqual(abode._devices, {'area_1': abode.get_alarm()})

        # Contains no automations
        self.assertEqual(abode._automations, {})

        abode.logout()

        abode = None
Ejemplo n.º 5
0
    def __init__(self, username, password):
        """Initialize Abode oject."""
        import abodepy

        self.abode = abodepy.Abode(username, password)
        self.devices = self.abode.get_devices()

        _LOGGER.debug("Abode Security set up with %s devices",
                      len(self.devices))
Ejemplo n.º 6
0
 def __init__(self, username, password, name, polling, exclude, lights):
     """Initialize the system."""
     import abodepy
     self.abode = abodepy.Abode(
         username, password, auto_login=True, get_devices=True,
         get_automations=True)
     self.name = name
     self.polling = polling
     self.exclude = exclude
     self.lights = lights
     self.devices = []
Ejemplo n.º 7
0
def setup(hass, config):
    """Set up Abode component."""
    import abodepy

    conf = config[DOMAIN]
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD)

    try:
        hass.data[DATA_ABODE] = abode = abodepy.Abode(username, password)

        devices = abode.get_devices()

        _LOGGER.info("Logged in to Abode and found %s devices", len(devices))

    except (ConnectTimeout, HTTPError) as ex:
        _LOGGER.error("Unable to connect to Abode: %s", str(ex))
        hass.components.persistent_notification.create(
            'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    for platform in ABODE_PLATFORMS:
        discovery.load_platform(hass, platform, DOMAIN, {}, config)

    def logout(event):
        """Logout of Abode."""
        abode.stop_listener()
        abode.logout()
        _LOGGER.info("Logged out of Abode")

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, logout)

    def startup(event):
        """Listen for push events."""
        abode.start_listener()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, startup)

    return True
Ejemplo n.º 8
0
    def setUp(self):
        """Set up Abode module."""
        self.abode = abodepy.Abode(username=USERNAME,
                                   password=PASSWORD,
                                   disable_cache=True)

        self.all_devices = ("[" + IRCAMERA.device(
            devid=IRCAMERA.DEVICE_ID,
            status=CONST.STATUS_ONLINE,
            low_battery=False,
            no_response=False,
        ) + "," + IPCAM.device(
            devid=IPCAM.DEVICE_ID,
            status=CONST.STATUS_ONLINE,
            low_battery=False,
            no_response=False,
        ) + "]")

        # Logout to reset everything
        self.abode.logout()
Ejemplo n.º 9
0
 def setUp(self):
     """Set up Abode module."""
     self.abode = abodepy.Abode(username=USERNAME,
                                password=PASSWORD)
Ejemplo n.º 10
0
 def setUp(self):
     """Set up Abode module."""
     self.abode_no_cred = abodepy.Abode(disable_cache=True)
     self.abode = abodepy.Abode(username=USERNAME,
                                password=PASSWORD,
                                disable_cache=True)
Ejemplo n.º 11
0
def call():
    """Execute command line helper."""
    args = get_arguments()

    # Set up logging
    if args.debug:
        log_level = logging.DEBUG
    elif args.quiet:
        log_level = logging.WARN
    else:
        log_level = logging.INFO

    setup_logging(log_level)

    abode = None

    if not args.cache:
        if not args.username or not args.password:
            raise Exception("Please supply a cache or username and password.")

    try:
        # Create abodepy instance.
        if args.cache and args.username and args.password:
            abode = abodepy.Abode(username=args.username,
                                  password=args.password,
                                  get_devices=args.mfa is None,
                                  cache_path=args.cache)
        elif args.cache and not (not args.username or not args.password):
            abode = abodepy.Abode(get_devices=args.mfa is None,
                                  cache_path=args.cache)
        else:
            abode = abodepy.Abode(username=args.username,
                                  password=args.password,
                                  get_devices=args.mfa is None)

        # Since the MFA code is very time sensitive, if the user has provided
        # one we should use it to log in as soon as possible
        if args.mfa:
            abode.login(mfa_code=args.mfa)
            # Now we can fetch devices from Abode
            abode.get_devices()

        # Output current mode.
        if args.mode:
            _LOGGER.info("Current alarm mode: %s", abode.get_alarm().mode)

        # Change system mode.
        if args.arm:
            if abode.get_alarm().set_mode(args.arm):
                _LOGGER.info("Alarm mode changed to: %s", args.arm)
            else:
                _LOGGER.warning("Failed to change alarm mode to: %s", args.arm)

        # Set setting
        for setting in args.set or []:
            keyval = setting.split("=")
            if abode.set_setting(keyval[0], keyval[1]):
                _LOGGER.info("Setting %s changed to %s", keyval[0], keyval[1])

        # Switch on
        for device_id in args.on or []:
            device = abode.get_device(device_id)

            if device:
                if device.switch_on():
                    _LOGGER.info("Switched on device with id: %s", device_id)
            else:
                _LOGGER.warning("Could not find device with id: %s", device_id)

        # Switch off
        for device_id in args.off or []:
            device = abode.get_device(device_id)

            if device:
                if device.switch_off():
                    _LOGGER.info("Switched off device with id: %s", device_id)
            else:
                _LOGGER.warning("Could not find device with id: %s", device_id)

        # Lock
        for device_id in args.lock or []:
            device = abode.get_device(device_id)

            if device:
                if device.lock():
                    _LOGGER.info("Locked device with id: %s", device_id)
            else:
                _LOGGER.warning("Could not find device with id: %s", device_id)

        # Unlock
        for device_id in args.unlock or []:
            device = abode.get_device(device_id)

            if device:
                if device.unlock():
                    _LOGGER.info("Unlocked device with id: %s", device_id)
            else:
                _LOGGER.warning("Could not find device with id: %s", device_id)

        # Output Json
        for device_id in args.json or []:
            device = abode.get_device(device_id)

            if device:
                # pylint: disable=protected-access
                print(json.dumps(device._json_state, sort_keys=True,
                                 indent=4, separators=(',', ': ')))
            else:
                _LOGGER.warning("Could not find device with id: %s", device_id)

        # Print
        def _device_print(dev, append=''):
            print("%s%s",
                  dev.desc, append)

        # Print out all automations
        if args.automations:
            for automation in abode.get_automations():
                _device_print(automation)

        # Enable automation
        for automation_id in args.activate or []:
            automation = abode.get_automation(automation_id)

            if automation:
                if automation.set_active(True):
                    _LOGGER.info(
                        "Activated automation with id: %s", automation_id)
            else:
                _LOGGER.warning(
                    "Could not find automation with id: %s", automation_id)

        # Disable automation
        for automation_id in args.deactivate or []:
            automation = abode.get_automation(automation_id)

            if automation:
                if automation.set_active(False):
                    _LOGGER.info(
                        "Deactivated automation with id: %s", automation_id)
            else:
                _LOGGER.warning(
                    "Could not find automation with id: %s", automation_id)

        # Trigger automation
        for automation_id in args.trigger or []:
            automation = abode.get_automation(automation_id)

            if automation:
                if automation.trigger():
                    _LOGGER.info(
                        "Triggered automation with id: %s", automation_id)
            else:
                _LOGGER.warning(
                    "Could not find automation with id: %s", automation_id)

        # Trigger image capture
        for device_id in args.capture or []:
            device = abode.get_device(device_id)

            if device:
                if device.capture():
                    _LOGGER.info(
                        "Image requested from device with id: %s", device_id)
                else:
                    _LOGGER.warning(
                        "Failed to request image from device with id: %s",
                        device_id)
            else:
                _LOGGER.warning("Could not find device with id: %s", device_id)

        # Save camera image
        for keyval in args.image or []:
            devloc = keyval.split("=")
            device = abode.get_device(devloc[0])

            if device:
                try:
                    if (device.refresh_image() and
                            device.image_to_file(devloc[1])):
                        _LOGGER.info(
                            "Saved image to %s for device id: %s", devloc[1],
                            devloc[0])
                except AbodeException as exc:
                    _LOGGER.warning("Unable to save image: %s", exc)
            else:
                _LOGGER.warning(
                    "Could not find device with id: %s", devloc[0])

        # Print out all devices.
        if args.devices:
            for device in abode.get_devices():
                _device_print(device)

        def _device_callback(dev):
            _device_print(dev, ", At: " + time.strftime("%Y-%m-%d %H:%M:%S"))

        def _timeline_callback(tl_json):
            event_code = int(tl_json['event_code'])
            if 5100 <= event_code <= 5199:
                # Ignore device changes
                return

            _LOGGER.info("%s - %s at %s %s",
                         tl_json['event_name'], tl_json['event_type'],
                         tl_json['date'], tl_json['time'])

        # Print out specific devices by device id.
        if args.device:
            for device_id in args.device:
                device = abode.get_device(device_id)

                if device:
                    _device_print(device)

                    # Register the specific devices if we decide to listen.
                    abode.events.add_device_callback(device_id,
                                                     _device_callback)
                else:
                    _LOGGER.warning(
                        "Could not find device with id: %s", device_id)

        # Start device change listener.
        if args.listen:
            # If no devices were specified then we listen to all devices.
            if args.device is None:
                _LOGGER.info("Adding all devices to listener...")

                for device in abode.get_devices():
                    abode.events.add_device_callback(device.device_id,
                                                     _device_callback)

            abode.events.add_timeline_callback(TIMELINE.ALL,
                                               _timeline_callback)

            _LOGGER.info("Listening for device and timeline updates...")
            abode.events.start()
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                abode.events.stop()
                _LOGGER.info("Device update listening stopped.")
    except abodepy.AbodeException as exc:
        _LOGGER.error(exc)
    finally:
        if abode:
            abode.logout()