Exemplo n.º 1
0
async def async_setup_entry(hass, entry):
    """Set up the AVM Fritz!Box platforms."""
    fritz = Fritzhome(
        host=entry.data[CONF_HOST],
        user=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
    )

    try:
        await hass.async_add_executor_job(fritz.login)
    except LoginError:
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN,
                context={"source": SOURCE_REAUTH},
                data=entry,
            ))
        return False

    hass.data.setdefault(DOMAIN, {CONF_CONNECTIONS: {}, CONF_DEVICES: set()})
    hass.data[DOMAIN][CONF_CONNECTIONS][entry.entry_id] = fritz

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    def logout_fritzbox(event):
        """Close connections to this fritzbox."""
        fritz.logout()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzbox)

    return True
Exemplo n.º 2
0
def get_switch_test_device():
    mock = MagicMock()
    mock.side_effect = [response("device_list"), "1"]

    fritz = Fritzhome("10.0.0.1", "user", "pass")
    fritz._request = mock
    element = fritz.get_device_element("08761 0000434")
    device = FritzhomeDevice(fritz=fritz, node=element)
    return device
    def setup(self):
        self.mock = MagicMock()
        self.fritz = Fritzhome("10.0.0.1", "user", "pass")
        self.fritz._request = self.mock
        self.fritz._devices = {}

        self.mock.side_effect = [Helper.response("templates/template_list")]

        self.fritz.update_templates()
Exemplo n.º 4
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the AVM FRITZ!SmartHome platforms."""
    fritz = Fritzhome(
        host=entry.data[CONF_HOST],
        user=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
    )

    try:
        await hass.async_add_executor_job(fritz.login)
    except LoginError as err:
        raise ConfigEntryAuthFailed from err

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        CONF_CONNECTIONS: fritz,
    }

    coordinator = FritzboxDataUpdateCoordinator(hass, entry)

    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][entry.entry_id][CONF_COORDINATOR] = coordinator

    def _update_unique_id(entry: RegistryEntry) -> dict[str, str] | None:
        """Update unique ID of entity entry."""
        if (
            entry.unit_of_measurement == TEMP_CELSIUS
            and "_temperature" not in entry.unique_id
        ):
            new_unique_id = f"{entry.unique_id}_temperature"
            LOGGER.info(
                "Migrating unique_id [%s] to [%s]", entry.unique_id, new_unique_id
            )
            return {"new_unique_id": new_unique_id}

        if entry.domain == BINARY_SENSOR_DOMAIN and "_" not in entry.unique_id:
            new_unique_id = f"{entry.unique_id}_alarm"
            LOGGER.info(
                "Migrating unique_id [%s] to [%s]", entry.unique_id, new_unique_id
            )
            return {"new_unique_id": new_unique_id}
        return None

    await async_migrate_entries(hass, entry.entry_id, _update_unique_id)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    def logout_fritzbox(event: Event) -> None:
        """Close connections to this fritzbox."""
        fritz.logout()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzbox)
    )

    return True
Exemplo n.º 5
0
def get_switch_test_device():
    mock = MagicMock()
    mock.side_effect = [device_list_xml, '1']

    fritz = Fritzhome('10.0.0.1', 'user', 'pass')
    fritz._request = mock
    element = fritz.get_device_element('08761 0000434')
    device = FritzhomeDevice(fritz=fritz, node=element)
    return device
Exemplo n.º 6
0
    def test_device_hkr_fw_03_54(self):
        mock = MagicMock()
        mock.side_effect = [
            device_hkr_fw_03_54_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('23456')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '23456')
        assert_true(device.present)
Exemplo n.º 7
0
    def test_device_init_no_devicelock_element(self):
        mock = MagicMock()
        mock.side_effect = [
            device_no_devicelock_element_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('08761 0373130')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '08761 0373130')
        assert_true(device.present)
Exemplo n.º 8
0
    def test_device_init_present_false(self):
        mock = MagicMock()
        mock.side_effect = [
            device_not_present_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('11960 0089208')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '11960 0089208')
        assert_false(device.present)
Exemplo n.º 9
0
 def _try_connect(self):
     """Try to connect and check auth."""
     fritzbox = Fritzhome(host=self._host,
                          user=self._username,
                          password=self._password)
     try:
         fritzbox.login()
         fritzbox.logout()
         return RESULT_SUCCESS
     except OSError:
         return RESULT_NOT_FOUND
     except LoginError:
         return RESULT_AUTH_FAILED
Exemplo n.º 10
0
    def test_hkr_without_temperature_values(self):
        mock = MagicMock()
        mock.side_effect = [
            device_hkr_no_temp_values_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('11960 0071472')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '11960 0071472')
        eq_(device.offset, None)
        eq_(device.temperature, None)
Exemplo n.º 11
0
    def test_device_alert_no_alertstate(self):
        mock = MagicMock()
        mock.side_effect = [
            device_alert_no_alertstate_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('05333 0077045-3')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '05333 0077045-3')
        assert_true(device.present)
        eq_(device.alert_state, None)
Exemplo n.º 12
0
 def connect(self):
     """
     Connects to the AVM Fritzbox
     """
     try:
         self.fritzbox = Fritzhome(host=self.host,
                                   user=self.user,
                                   password=self.password)
         self.fritzbox.login()
         self.logger.debug('Login to Fritz!Box {} as {} successful.'.format(
             self.host, self.user))
     except LoginError:
         self.logger.debug('Login to Fritz!Box {} as {} failed.'.format(
             self.host, self.user))
Exemplo n.º 13
0
    def test_device_update(self):
        mock = MagicMock()
        mock.side_effect = [
            device_list_battery_ok_xml,
            device_list_battery_low_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('11959 0171328')
        device = FritzhomeDevice(fritz=fritz, node=element)

        assert_false(device.battery_low)
        device.update()
        assert_true(device.battery_low)
Exemplo n.º 14
0
 def _try_connect(self):
     """Try to connect and check auth."""
     fritzbox = Fritzhome(
         host=self._host, user=self._username, password=self._password
     )
     try:
         fritzbox.login()
         fritzbox.get_device_elements()
         fritzbox.logout()
         return RESULT_SUCCESS
     except LoginError:
         return RESULT_INVALID_AUTH
     except HTTPError:
         return RESULT_NOT_SUPPORTED
     except OSError:
         return RESULT_NO_DEVICES_FOUND
Exemplo n.º 15
0
    def test_device_init(self):
        mock = MagicMock()
        mock.side_effect = [
            device_list_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('08761 0000434')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '08761 0000434')
        eq_(device.fw_version, '03.33')
        assert_true(device.present)
        assert_true(device.has_switch)
        assert_true(device.has_temperature_sensor)
        assert_true(device.has_powermeter)
Exemplo n.º 16
0
    def test_device_hkr_fw_03_50(self):
        mock = MagicMock()
        mock.side_effect = [
            device_hkr_fw_03_50_xml,
        ]

        fritz = Fritzhome('10.0.0.1', 'user', 'pass')
        fritz._request = mock
        element = fritz.get_device_element('12345')
        device = FritzhomeDevice(node=element)

        eq_(device.ain, '12345')
        assert_true(device.present)
        eq_(device.device_lock, None)
        eq_(device.lock, None)
        eq_(device.error_code, None)
        eq_(device.battery_low, None)
Exemplo n.º 17
0
def setup(hass, config):
    """Set up the fritzbox component."""
    from pyfritzhome import Fritzhome, LoginError

    fritz_list = []

    if CONF_DEVICES in config[DOMAIN] and config[DOMAIN].get(CONF_DEVICES):
        configured_devices = config[DOMAIN].get(CONF_DEVICES)
        for device in configured_devices:
            try:
                host = device['host']
                username = device['username']
                password = device['password']
                fritzbox = Fritzhome(host=host,
                                     user=username,
                                     password=password)
                fritzbox.login()
                fritz_list.append(fritzbox)
                _LOGGER.info("Connected to device %s", device)
            except LoginError:
                _LOGGER.warning("Login to Fritz!Box %s as %s failed", host,
                                username)
                continue
            except KeyError:
                _LOGGER.warning("Configuration error")
                continue

    hass.data[DOMAIN] = fritz_list

    def logout_fritzboxes(event):
        """Close all connections to the fritzboxes."""
        for fritz in fritz_list:
            fritz.logout()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzboxes)

    for domain in SUPPORTED_DOMAINS:
        discovery.load_platform(hass, domain, DOMAIN, {}, config)

    _LOGGER.info('Connected to fritzbox')

    return True
Exemplo n.º 18
0
def setup(hass, config):
    """Set up the fritzbox component."""
    from pyfritzhome import Fritzhome, LoginError

    fritz_list = []

    configured_devices = config[DOMAIN].get(CONF_DEVICES)
    for device in configured_devices:
        host = device.get(CONF_HOST)
        username = device.get(CONF_USERNAME)
        password = device.get(CONF_PASSWORD)
        fritzbox = Fritzhome(host=host, user=username,
                             password=password)
        try:
            fritzbox.login()
            _LOGGER.info("Connected to device %s", device)
        except LoginError:
            _LOGGER.warning("Login to Fritz!Box %s as %s failed",
                            host, username)
            continue

        fritz_list.append(fritzbox)

    if not fritz_list:
        _LOGGER.info("No fritzboxes configured")
        return False

    hass.data[DOMAIN] = fritz_list

    def logout_fritzboxes(event):
        """Close all connections to the fritzboxes."""
        for fritz in fritz_list:
            fritz.logout()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzboxes)

    for domain in SUPPORTED_DOMAINS:
        discovery.load_platform(hass, domain, DOMAIN, {}, config)

    return True
Exemplo n.º 19
0
 def setup(self):
     self.mock = MagicMock()
     self.fritz = Fritzhome("10.0.0.1", "user", "pass")
     self.fritz._request = self.mock
     self.fritz._devices = {}
Exemplo n.º 20
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the AVM FRITZ!SmartHome platforms."""
    fritz = Fritzhome(
        host=entry.data[CONF_HOST],
        user=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
    )

    try:
        await hass.async_add_executor_job(fritz.login)
    except LoginError as err:
        raise ConfigEntryAuthFailed from err

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        CONF_CONNECTIONS: fritz,
    }

    def _update_fritz_devices() -> dict[str, FritzhomeDevice]:
        """Update all fritzbox device data."""
        try:
            devices = fritz.get_devices()
        except requests.exceptions.HTTPError:
            # If the device rebooted, login again
            try:
                fritz.login()
            except requests.exceptions.HTTPError as ex:
                raise ConfigEntryAuthFailed from ex
            devices = fritz.get_devices()

        data = {}
        for device in devices:
            device.update()
            data[device.ain] = device
        return data

    async def async_update_coordinator() -> dict[str, FritzhomeDevice]:
        """Fetch all device data."""
        return await hass.async_add_executor_job(_update_fritz_devices)

    hass.data[DOMAIN][entry.entry_id][
        CONF_COORDINATOR] = coordinator = DataUpdateCoordinator(
            hass,
            LOGGER,
            name=f"{entry.entry_id}",
            update_method=async_update_coordinator,
            update_interval=timedelta(seconds=30),
        )

    await coordinator.async_config_entry_first_refresh()

    def _update_unique_id(entry: RegistryEntry) -> dict[str, str] | None:
        """Update unique ID of entity entry."""
        if (entry.unit_of_measurement == TEMP_CELSIUS
                and "_temperature" not in entry.unique_id):
            new_unique_id = f"{entry.unique_id}_temperature"
            LOGGER.info("Migrating unique_id [%s] to [%s]", entry.unique_id,
                        new_unique_id)
            return {"new_unique_id": new_unique_id}
        return None

    await async_migrate_entries(hass, entry.entry_id, _update_unique_id)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    def logout_fritzbox(event: Event) -> None:
        """Close connections to this fritzbox."""
        fritz.logout()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzbox))

    return True
Exemplo n.º 21
0
 def setup(self):
     self.mock = MagicMock()
     self.fritz = Fritzhome('10.0.0.1', 'user', 'pass')
     self.fritz._request = self.mock
Exemplo n.º 22
0
def main(args=None):
    """The main function."""
    parser = argparse.ArgumentParser(
        description='Fritz!Box Smarthome CLI tool.')
    parser.add_argument('-v',
                        action='store_true',
                        dest='verbose',
                        help='be more verbose')
    parser.add_argument('-f',
                        '--fritzbox',
                        type=str,
                        dest='host',
                        help='Fritz!Box IP address',
                        default='fritz.box')
    parser.add_argument('-u', '--user', type=str, dest='user', help='Username')
    parser.add_argument('-p',
                        '--password',
                        type=str,
                        dest='password',
                        help='Username')
    parser.add_argument('-a',
                        '--ain',
                        type=str,
                        dest='ain',
                        help='Actor Identification',
                        default=None)
    parser.add_argument('-V',
                        '--version',
                        action='version',
                        version='{version}'.format(version=__version__),
                        help='Print version')

    _sub = parser.add_subparsers(title='Commands')

    # list all devices
    subparser = _sub.add_parser('list', help='List all available devices')
    subparser.set_defaults(func=list_all)

    # device
    subparser = _sub.add_parser('device', help='Device/Actor commands')
    _sub_switch = subparser.add_subparsers()

    # device name
    subparser = _sub_switch.add_parser('name', help='get the device name')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_name)

    # device presence
    subparser = _sub_switch.add_parser('present',
                                       help='get the device presence')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_presence)

    # device stats
    subparser = _sub_switch.add_parser('stats',
                                       help='get the device statistic')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=device_statistic)

    # switch
    subparser = _sub.add_parser('switch', help='Switch commands')
    _sub_switch = subparser.add_subparsers()

    # switch get
    subparser = _sub_switch.add_parser('get', help='get state')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_get)

    # switch on
    subparser = _sub_switch.add_parser('on', help='set on state')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_on)

    # switch off
    subparser = _sub_switch.add_parser('off', help='set off state')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_off)

    # switch toggle
    subparser = _sub_switch.add_parser('toggle', help='set off state')
    subparser.add_argument('ain',
                           type=str,
                           metavar="AIN",
                           help='Actor Identification')
    subparser.set_defaults(func=switch_toggle)

    args = parser.parse_args(args)

    logging.basicConfig()
    if args.verbose:
        logging.getLogger('pyfritzhome').setLevel(logging.DEBUG)

    fritzbox = None
    try:
        fritzbox = Fritzhome(host=args.host,
                             user=args.user,
                             password=args.password)
        fritzbox.login()
        args.func(fritzbox, args)
    finally:
        if fritzbox is not None:
            fritzbox.logout()
Exemplo n.º 23
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the AVM Fritz!Box platforms."""
    fritz = Fritzhome(
        host=entry.data[CONF_HOST],
        user=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
    )

    try:
        await hass.async_add_executor_job(fritz.login)
    except LoginError as err:
        raise ConfigEntryAuthFailed from err

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        CONF_CONNECTIONS: fritz,
    }

    def _update_fritz_devices() -> dict[str, FritzhomeDevice]:
        """Update all fritzbox device data."""
        try:
            devices = fritz.get_devices()
        except requests.exceptions.HTTPError:
            # If the device rebooted, login again
            try:
                fritz.login()
            except requests.exceptions.HTTPError as ex:
                raise ConfigEntryAuthFailed from ex
            devices = fritz.get_devices()

        data = {}
        for device in devices:
            device.update()
            data[device.ain] = device
        return data

    async def async_update_coordinator():
        """Fetch all device data."""
        return await hass.async_add_executor_job(_update_fritz_devices)

    hass.data[DOMAIN][entry.entry_id][
        CONF_COORDINATOR] = coordinator = DataUpdateCoordinator(
            hass,
            LOGGER,
            name=f"{entry.entry_id}",
            update_method=async_update_coordinator,
            update_interval=timedelta(seconds=30),
        )

    await coordinator.async_config_entry_first_refresh()

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    def logout_fritzbox(event):
        """Close connections to this fritzbox."""
        fritz.logout()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, logout_fritzbox))

    return True
Exemplo n.º 24
0
def main(args=None):
    """The main function."""
    parser = argparse.ArgumentParser(description="Fritz!Box Smarthome CLI tool.")
    parser.add_argument(
        "-v", action="store_true", dest="verbose", help="be more verbose"
    )
    parser.add_argument(
        "-f",
        "--fritzbox",
        type=str,
        dest="host",
        help="Fritz!Box IP address",
        default="fritz.box",
    )
    parser.add_argument("-u", "--user", type=str, dest="user", help="Username")
    parser.add_argument("-p", "--password", type=str, dest="password", help="Username")
    parser.add_argument(
        "-a",
        "--ain",
        type=str,
        dest="ain",
        help="Actor/Template Identification",
        default=None,
    )
    parser.add_argument(
        "-V",
        "--version",
        action="version",
        version="{version}".format(version=__version__),
        help="Print version",
    )

    _sub = parser.add_subparsers(title="Commands")

    # list all devices
    subparser = _sub.add_parser("list", help="List all available devices")
    subparser.set_defaults(func=list_all)

    # device
    subparser = _sub.add_parser("device", help="Device/Actor commands")
    _sub_switch = subparser.add_subparsers()

    # device name
    subparser = _sub_switch.add_parser("name", help="get the device name")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=device_name)

    # device presence
    subparser = _sub_switch.add_parser("present", help="get the device presence")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=device_presence)

    # device stats
    subparser = _sub_switch.add_parser("stats", help="get the device statistics")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=device_statistics)

    # switch
    subparser = _sub.add_parser("switch", help="Switch commands")
    _sub_switch = subparser.add_subparsers()

    # switch get
    subparser = _sub_switch.add_parser("get", help="get state")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=switch_get)

    # switch on
    subparser = _sub_switch.add_parser("on", help="set on state")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=switch_on)

    # switch off
    subparser = _sub_switch.add_parser("off", help="set off state")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=switch_off)

    # switch toggle
    subparser = _sub_switch.add_parser("toggle", help="set off state")
    subparser.add_argument("ain", type=str, metavar="AIN", help="Actor Identification")
    subparser.set_defaults(func=switch_toggle)

    # templates
    subparser = _sub.add_parser("template", help="Template commands")
    _sub_switch = subparser.add_subparsers()

    # list templates
    subparser = _sub_switch.add_parser("list", help="List all available templates")
    subparser.set_defaults(func=list_templates)

    # apply templates
    subparser = _sub_switch.add_parser("apply", help="Apply template")
    subparser.set_defaults(func=template_apply)

    args = parser.parse_args(args)

    logging.basicConfig()
    if args.verbose:
        logging.getLogger("pyfritzhome").setLevel(logging.DEBUG)

    fritzbox = None
    try:
        fritzbox = Fritzhome(host=args.host, user=args.user, password=args.password)
        fritzbox.login()
        args.func(fritzbox, args)
    finally:
        if fritzbox is not None:
            fritzbox.logout()