Ejemplo n.º 1
0
def setup(hass, config):
    """Set up the Somfy component."""
    from pymfy.api.somfy_api import SomfyApi

    hass.data[DOMAIN] = {}

    # This is called to create the redirect so the user can Authorize Home .
    redirect_uri = '{}{}'.format(
        hass.config.api.base_url, SOMFY_AUTH_CALLBACK_PATH)
    conf = config[DOMAIN]
    api = SomfyApi(conf.get(CONF_CLIENT_ID),
                   conf.get(CONF_CLIENT_SECRET),
                   redirect_uri, hass.config.path(DEFAULT_CACHE_PATH))
    hass.data[DOMAIN][API] = api

    if not api.token:
        authorization_url, _ = api.get_authorization_url()
        hass.components.persistent_notification.create(
            'In order to authorize Home Assistant to view your Somfy devices'
            ' you must visit this <a href="{}" target="_blank">link</a>.'
            .format(authorization_url),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_CB_ID
        )
        hass.http.register_view(SomfyAuthCallbackView(config))
    else:
        update_all_devices(hass)
        for component in SOMFY_COMPONENTS:
            discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
Ejemplo n.º 2
0
    async def _get_authorization_url(self):
        """Get Somfy authorization url."""
        from pymfy.api.somfy_api import SomfyApi
        flow = self.hass.data[DATA_FLOW_IMPL][self.flow_impl]
        client_id = flow[CLIENT_ID]
        client_secret = flow[CLIENT_SECRET]
        redirect_uri = '{}{}'.format(self.hass.config.api.base_url,
                                     AUTH_CALLBACK_PATH)
        api = SomfyApi(client_id, client_secret, redirect_uri)

        self.hass.http.register_view(SomfyAuthCallbackView())
        return api.get_authorization_url()
Ejemplo n.º 3
0
    async def _async_create_session(self, code):
        """Create Somfy api and entries."""
        flow = self.hass.data[DATA_FLOW_IMPL][DOMAIN]
        client_id = flow[CLIENT_ID]
        client_secret = flow[CLIENT_SECRET]
        from pymfy.api.somfy_api import SomfyApi
        redirect_uri = '{}{}'.format(self.hass.config.api.base_url,
                                     AUTH_CALLBACK_PATH)
        api = SomfyApi(client_id, client_secret, redirect_uri)
        token = await self.hass.async_add_executor_job(api.request_token, None,
                                                       code)
        _LOGGER.debug("Got new token")
        # if not api.is_authorized:
        #    _LOGGER.error('Authentication Error')
        #    return self.async_abort(reason='auth_error')

        _LOGGER.info('Successfully authenticated Somfy')
        return self.async_create_entry(
            title='',
            data={
                'token': token,
                'refresh_args': {
                    'client_id': client_id,
                    'client_secret': client_secret
                }
            },
        )
Ejemplo n.º 4
0
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry):
    """Set up Somfy from a config entry."""
    def token_saver(token):
        _LOGGER.debug("Saving updated token")
        entry.data[CONF_TOKEN] = token
        update_entry = partial(hass.config_entries.async_update_entry,
                               data={**entry.data})
        hass.add_job(update_entry, entry)

    # Force token update.
    from pymfy.api.somfy_api import SomfyApi

    hass.data[DOMAIN][API] = SomfyApi(
        entry.data["refresh_args"]["client_id"],
        entry.data["refresh_args"]["client_secret"],
        token=entry.data[CONF_TOKEN],
        token_updater=token_saver,
    )

    await update_all_devices(hass)

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

    return True
Ejemplo n.º 5
0
    async def _get_authorization_url(self):
        """Get Somfy authorization url."""
        from pymfy.api.somfy_api import SomfyApi
        client_id = self.hass.data[DOMAIN][CLIENT_ID]
        client_secret = self.hass.data[DOMAIN][CLIENT_SECRET]
        redirect_uri = '{}{}'.format(self.hass.config.api.base_url,
                                     AUTH_CALLBACK_PATH)
        api = SomfyApi(client_id, client_secret, redirect_uri)

        self.hass.http.register_view(SomfyAuthCallbackView())
        # Thanks to the state, we can forward the flow id to Somfy that will
        # add it in the callback.
        return await self.hass.async_add_executor_job(
            api.get_authorization_url, self.flow_id)
Ejemplo n.º 6
0
    async def async_step_creation(self, user_input=None):
        """Create Somfy api and entries."""
        client_id = self.hass.data[DOMAIN][CLIENT_ID]
        client_secret = self.hass.data[DOMAIN][CLIENT_SECRET]
        code = self.code
        from pymfy.api.somfy_api import SomfyApi

        redirect_uri = "{}{}".format(self.hass.config.api.base_url, AUTH_CALLBACK_PATH)
        api = SomfyApi(client_id, client_secret, redirect_uri)
        token = await self.hass.async_add_executor_job(api.request_token, None, code)
        _LOGGER.info("Successfully authenticated Somfy")
        return self.async_create_entry(
            title="Somfy",
            data={
                "token": token,
                "refresh_args": {
                    "client_id": client_id,
                    "client_secret": client_secret,
                },
            },
        )
Ejemplo n.º 7
0
 def device(self):
     api = SomfyApi("foo", "faa", "https://whatever.com")
     device_path = os.path.join(CURRENT_DIR, "roller_shutter.json")
     with open(device_path) as get_device:
         dumb_device = Device(**json.loads(get_device.read()))
     return SomfyDevice(dumb_device, api)
Ejemplo n.º 8
0
 def setup_method(self):
     self.api = SomfyApi('foo', 'faa', 'https://whatever.com')
     device_path = os.path.join(CURRENT_DIR, 'get_device.json')
     with open(device_path, 'r') as get_device:
         self.dumb_device = Device(json.loads(get_device.read()))
     self.somfy_device = SomfyDevice(self.dumb_device, self.api)
Ejemplo n.º 9
0
 def setup_method(self):
     self.api = SomfyApi('foo', 'faa', 'https://whatever.com')
Ejemplo n.º 10
0
class TestSomfyApi:
    __slots__ = 'api'

    def setup_method(self):
        self.api = SomfyApi('foo', 'faa', 'https://whatever.com')

    @httpretty.activate
    def test_get_sites(self):
        with open(os.path.join(CURRENT_DIR, 'get_sites.json'),
                  'r') as get_sites:
            httpretty.register_uri(httpretty.GET,
                                   BASE_URL + '/site',
                                   body=get_sites.read())
        sites = self.api.get_sites()
        assert len(sites) == 2
        assert sites[0].id == 'site-1'
        assert sites[0].label == 'TaHoma'
        assert sites[1].id == 'site-2'
        assert sites[1].label == 'Conexoon'

    @httpretty.activate
    def test_get_site(self):
        with open(os.path.join(CURRENT_DIR, 'get_site.json'), 'r') as get_site:
            httpretty.register_uri(httpretty.GET,
                                   BASE_URL + '/site/site-1',
                                   body=get_site.read())
        site = self.api.get_site('site-1')
        assert site.id == 'site-1'
        assert site.label == 'TaHoma'

    @httpretty.activate
    def test_devices(self):
        sites_path = os.path.join(CURRENT_DIR, 'get_sites.json')
        devices_path_1 = os.path.join(CURRENT_DIR, 'get_devices_1.json')
        devices_path_2 = os.path.join(CURRENT_DIR, 'get_devices_2.json')
        with open(sites_path, 'r') as get_sites, \
                open(devices_path_1, 'r') as get_devices_1, \
                open(devices_path_2, 'r') as get_devices_2:
            httpretty.register_uri(httpretty.GET,
                                   BASE_URL + '/site',
                                   body=get_sites.read())
            httpretty.register_uri(httpretty.GET,
                                   BASE_URL + '/site/site-1/device',
                                   body=get_devices_1.read())
            httpretty.register_uri(httpretty.GET,
                                   BASE_URL + '/site/site-2/device',
                                   body=get_devices_2.read())

        assert len(self.api.get_devices()) == 4
        assert len(self.api.get_devices('site-1')) == 3
        assert len(self.api.get_devices(site_id='site-1')) == 3
        assert len(self.api.get_devices(category=Category.ROLLER_SHUTTER)) == 3
        assert len(self.api.get_devices('site-2',
                                        Category.ROLLER_SHUTTER)) == 1

    @httpretty.activate
    def test_get_device(self):
        device_path = os.path.join(CURRENT_DIR, 'roller_shutter.json')
        with open(device_path, 'r') as get_device:
            httpretty.register_uri(httpretty.GET,
                                   BASE_URL + '/device/device-3',
                                   body=get_device.read())
        device = self.api.get_device('device-3')
        assert device.id == 'device-3'
        assert device.name == 'Room 3'
        assert device.states[0].name == 'position'
        assert device.states[0].value == 50
        assert device.states[0].type == 'integer'

    @httpretty.activate
    def test_send_command(self):
        url = BASE_URL + '/device/my-id/exec'
        httpretty.register_uri(httpretty.POST, url, body='{"job_id": "9"}')
        # Exception must not be raised
        assert '9' == self.api.send_command('my-id', 'open')
Ejemplo n.º 11
0
 def api(self):
     return SomfyApi("foo", "faa", "https://whatever.com")
Ejemplo n.º 12
0
 def api(self, request):
     params = getattr(request, "param", None) or {}
     return SomfyApi("foo", "faa", "https://whatever.com", **params)
Ejemplo n.º 13
0
 def device(self):
     api = SomfyApi("foo", "faa", "https://whatever.com")
     device_path = os.path.join(CURRENT_DIR, "camera.json")
     with open(device_path, "r") as get_device:
         device = Device(**json.loads(get_device.read()))
     return CameraProtect(device, api)
Ejemplo n.º 14
0
 def device(self):
     api = SomfyApi("foo", "faa", "https://whatever.com")
     device_path = os.path.join(CURRENT_DIR, "hvac.json")
     with open(device_path) as get_device:
         device = Device(**json.loads(get_device.read()))
     return Thermostat(device, api)