Exemplo n.º 1
0
    async def async_step_user(self, user_input=None):
        """Handle the start of the config flow."""
        from aioambient import Client
        from aioambient.errors import AmbientError

        if not user_input:
            return await self._show_form()

        if user_input[CONF_APP_KEY] in configured_instances(self.hass):
            return await self._show_form({CONF_APP_KEY: 'identifier_exists'})

        session = aiohttp_client.async_get_clientsession(self.hass)
        client = Client(user_input[CONF_API_KEY], user_input[CONF_APP_KEY],
                        session)

        try:
            devices = await client.api.get_devices()
        except AmbientError:
            return await self._show_form({'base': 'invalid_key'})

        if not devices:
            return await self._show_form({'base': 'no_devices'})

        # The Application Key (which identifies each config entry) is too long
        # to show nicely in the UI, so we take the first 12 characters (similar
        # to how GitHub does it):
        return self.async_create_entry(title=user_input[CONF_APP_KEY][:12],
                                       data=user_input)
Exemplo n.º 2
0
    async def async_step_user(self, user_input=None):
        """Handle the start of the config flow."""
        if not user_input:
            return await self._show_form()

        await self.async_set_unique_id(user_input[CONF_APP_KEY])
        self._abort_if_unique_id_configured()

        session = aiohttp_client.async_get_clientsession(self.hass)
        client = Client(user_input[CONF_API_KEY],
                        user_input[CONF_APP_KEY],
                        session=session)

        try:
            devices = await client.api.get_devices()
        except AmbientError:
            return await self._show_form({"base": "invalid_key"})

        if not devices:
            return await self._show_form({"base": "no_devices"})

        # The Application Key (which identifies each config entry) is too long
        # to show nicely in the UI, so we take the first 12 characters (similar
        # to how GitHub does it):
        return self.async_create_entry(title=user_input[CONF_APP_KEY][:12],
                                       data=user_input)
Exemplo n.º 3
0
async def main() -> None:
    """Create a session"""
    client = Client(
        "96255560b32d46bf82101c3a42a9213ffae52644090e485eac958e2c4e55e88a",
        "65a5fd146d2a4bc09640a1fdf8c44887595fb4a5b0504693b8554e12a4ca2d87")
    await client.api.get_devices()
    print('hi')
Exemplo n.º 4
0
async def async_setup_entry(hass, config_entry):
    """Set up the Ambient PWS as config entry."""
    from aioambient import Client
    from aioambient.errors import WebsocketError

    session = aiohttp_client.async_get_clientsession(hass)

    try:
        ambient = AmbientStation(
            hass, config_entry,
            Client(
                config_entry.data[CONF_API_KEY],
                config_entry.data[CONF_APP_KEY], session),
            hass.data[DOMAIN].get(DATA_CONFIG, {}).get(
                CONF_MONITORED_CONDITIONS, []))
        hass.loop.create_task(ambient.ws_connect())
        hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = ambient
    except WebsocketError as err:
        _LOGGER.error('Config entry failed: %s', err)
        raise ConfigEntryNotReady

    hass.bus.async_listen_once(
        EVENT_HOMEASSISTANT_STOP, ambient.client.websocket.disconnect())

    return True
Exemplo n.º 5
0
async def async_setup_entry(hass, config_entry):
    """Set up the Ambient PWS as config entry."""
    if not config_entry.unique_id:
        hass.config_entries.async_update_entry(
            config_entry, unique_id=config_entry.data[CONF_APP_KEY])

    session = aiohttp_client.async_get_clientsession(hass)

    try:
        ambient = AmbientStation(
            hass,
            config_entry,
            Client(
                config_entry.data[CONF_API_KEY],
                config_entry.data[CONF_APP_KEY],
                session=session,
            ),
        )
        hass.loop.create_task(ambient.ws_connect())
        hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = ambient
    except WebsocketError as err:
        LOGGER.error("Config entry failed: %s", err)
        raise ConfigEntryNotReady from err

    async def _async_disconnect_websocket(*_):
        await ambient.client.websocket.disconnect()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP,
                               _async_disconnect_websocket)

    return True
Exemplo n.º 6
0
async def test_connect_failure(event_loop):
    """Test connecting to the socket and an exception occurring."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session)
        client.websocket._sio.eio.connect = async_mock(side_effect=SocketIOError())

        with pytest.raises(WebsocketError):
            await client.websocket.connect()
Exemplo n.º 7
0
async def main() -> None:

    async with ClientSession() as websession:
        client = Client(API_KEY, APP_KEY, websession)

        data = await client.api.get_device_details(MAC_ADD, end_date="")

        csvify.txt(data, "weather.txt", "w")
        csvify.txtarchive(data, "weatherarchive.txt")
Exemplo n.º 8
0
async def test_api_error(aresponses, event_loop, devices_json):
    aresponses.add(
        "dash2.ambientweather.net",
        "/v1/devices",
        "get",
        aresponses.Response(text="", status=500),
    )

    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TEST_API_KEY, TEST_APP_KEY, websession)

        with pytest.raises(RequestError):
            await client.api.get_devices()
Exemplo n.º 9
0
async def test_get_devices(aresponses, event_loop, devices_json):
    aresponses.add(
        "dash2.ambientweather.net",
        "/v1/devices",
        "get",
        aresponses.Response(text=json.dumps(devices_json), status=200),
    )

    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TEST_API_KEY, TEST_APP_KEY, websession)

        devices = await client.api.get_devices()
        assert len(devices) == 2
Exemplo n.º 10
0
async def test_api_error(aresponses):
    """Test the REST API raising an exception upon HTTP error."""
    aresponses.add(
        "dash2.ambientweather.net",
        "/v1/devices",
        "get",
        aresponses.Response(text="", status=500),
    )

    async with aiohttp.ClientSession() as websession:
        client = Client(TEST_API_KEY, TEST_APP_KEY, websession)

        with pytest.raises(RequestError):
            await client.api.get_devices()
Exemplo n.º 11
0
async def test_session_from_scratch(aresponses):
    """Test that an aiohttp ClientSession is created on the fly if needed."""
    aresponses.add(
        "api.ambientweather.net",
        "/v1/devices",
        "get",
        aresponses.Response(text=load_fixture("devices_response.json"),
                            status=200),
    )

    client = Client(TEST_API_KEY, TEST_APP_KEY)

    devices = await client.api.get_devices()
    assert len(devices) == 2
Exemplo n.º 12
0
async def test_get_device_details(aresponses, event_loop, device_details_json):
    aresponses.add(
        "dash2.ambientweather.net",
        f"/v1/devices/{TEST_MAC}",
        "get",
        aresponses.Response(text=json.dumps(device_details_json), status=200),
    )

    async with aiohttp.ClientSession(loop=event_loop) as websession:
        client = Client(TEST_API_KEY, TEST_APP_KEY, websession)

        device_details = await client.api.get_device_details(
            TEST_MAC, end_date=datetime.datetime(2019, 1, 6)
        )
        assert len(device_details) == 2
Exemplo n.º 13
0
async def test_get_devices(aresponses):
    """Test retrieving devices from the REST API."""
    aresponses.add(
        "dash2.ambientweather.net",
        "/v1/devices",
        "get",
        aresponses.Response(text=load_fixture("devices_response.json"),
                            status=200),
    )

    async with aiohttp.ClientSession() as websession:
        client = Client(TEST_API_KEY, TEST_APP_KEY, websession)

        devices = await client.api.get_devices()
        assert len(devices) == 2
Exemplo n.º 14
0
async def test_get_device_details(aresponses):
    """Test retrieving device details from the REST API."""
    aresponses.add(
        "dash2.ambientweather.net",
        f"/v1/devices/{TEST_MAC}",
        "get",
        aresponses.Response(text=load_fixture("device_details_response.json"),
                            status=200),
    )

    async with aiohttp.ClientSession() as websession:
        client = Client(TEST_API_KEY, TEST_APP_KEY, websession)

        device_details = await client.api.get_device_details(
            TEST_MAC, end_date=datetime.datetime(2019, 1, 6))
        assert len(device_details) == 2
Exemplo n.º 15
0
async def main() -> None:
    """Create the aiohttp session and run the example."""
    logging.basicConfig(level=logging.INFO)
    async with ClientSession() as session:
        try:
            client = Client(API_KEY, APP_KEY, session)

            devices = await client.api.get_devices()
            _LOGGER.info("Devices: %s", devices)

            for device in devices:
                details = await client.api.get_device_details(device["macAddress"])
                _LOGGER.info("Device Details (%s): %s", device["macAddress"], details)

        except AmbientError as err:
            _LOGGER.error("There was an error: %s", err)
Exemplo n.º 16
0
async def test_reconnect(event_loop):
    """Test that reconnecting to the websocket does the right thing."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session=session)
        client.websocket._sio.eio._trigger_event = AsyncMock()
        client.websocket._sio.eio.connect = AsyncMock()

        async_on_connect = AsyncMock()
        async_on_disconnect = AsyncMock()

        client.websocket.async_on_connect(async_on_connect)
        client.websocket.async_on_disconnect(async_on_disconnect)

        await client.websocket.reconnect()
        await client.websocket._sio._trigger_event("disconnect", "/")
        async_on_disconnect.assert_called_once()
        await client.websocket._sio._trigger_event("connect", "/")
        async_on_connect.assert_called_once()
Exemplo n.º 17
0
async def test_connect_sync_success(event_loop):
    """Test connecting to the socket with a sync handler."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session)
        client.websocket._sio.eio._trigger_event = async_mock()
        client.websocket._sio.eio.connect = async_mock()

        on_connect = MagicMock()
        client.websocket.on_connect(on_connect)

        await client.websocket.connect()
        client.websocket._sio.eio.connect.mock.assert_called_once_with(
            f"https://dash2.ambientweather.net/?api=1&applicationKey={TEST_APP_KEY}",
            engineio_path="socket.io",
            headers={},
            transports=["websocket"],
        )

        await client.websocket._sio._trigger_event("connect", namespace="/")
        on_connect.assert_called_once()
Exemplo n.º 18
0
async def test_data_async(event_loop):
    """Test data and subscription with async handlers."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session=session)
        client.websocket._sio.eio._trigger_event = CoroutineMock()
        client.websocket._sio.eio.connect = CoroutineMock()
        client.websocket._sio.eio.disconnect = CoroutineMock()

        async_on_connect = CoroutineMock()
        async_on_data = CoroutineMock()
        async_on_disconnect = CoroutineMock()
        async_on_subscribed = CoroutineMock()

        client.websocket.async_on_connect(async_on_connect)
        client.websocket.async_on_data(async_on_data)
        client.websocket.async_on_disconnect(async_on_disconnect)
        client.websocket.async_on_subscribed(async_on_subscribed)

        await client.websocket.connect()
        client.websocket._sio.eio.connect.assert_called_once_with(
            f"https://api.ambientweather.net/?api=1&applicationKey={TEST_APP_KEY}",
            engineio_path="socket.io",
            headers={},
            transports=["websocket"],
        )

        await client.websocket._sio._trigger_event("connect", "/")
        async_on_connect.assert_called_once()

        await client.websocket._sio._trigger_event("data", "/", {"foo": "bar"})
        async_on_data.assert_called_once()

        await client.websocket._sio._trigger_event("subscribed", "/",
                                                   {"foo": "bar"})
        async_on_subscribed.assert_called()

        await client.websocket.disconnect()
        await client.websocket._sio._trigger_event("disconnect", "/")
        async_on_disconnect.assert_called_once()
        client.websocket._sio.eio.disconnect.assert_called_once_with(
            abort=True)
Exemplo n.º 19
0
async def main() -> None:
    """Run the websocket example."""
    logging.basicConfig(level=logging.INFO)

    async with ClientSession() as session:
        client = Client(API_KEY, APP_KEY, session=session)

        client.websocket.on_connect(print_hello)
        client.websocket.on_data(print_data)
        client.websocket.on_disconnect(print_goodbye)
        client.websocket.on_subscribed(print_subscribed)

        try:
            await client.websocket.connect()
        except WebsocketError as err:
            _LOGGER.error("There was a websocket error: %s", err)
            return

        while True:
            #_LOGGER.info("Simulating some other task occurring...")
            await asyncio.sleep(5)
Exemplo n.º 20
0
async def async_test_events(event_loop):
    """Test all events and async_handlers."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session)
        client.websocket._sio.eio._trigger_event = async_mock()
        client.websocket._sio.eio.connect = async_mock()
        client.websocket._sio.eio.disconnect = async_mock()

        on_connect = MagicMock()
        on_data = MagicMock()
        on_subscribed = MagicMock()

        client.websocket.on_connect(on_connect)
        client.websocket.on_data(on_data)
        client.websocket.on_disconnect(on_data)
        client.websocket.on_subscribed(on_subscribed)

        await client.websocket.connect()
        client.websocket._sio.eio.connect.mock.assert_called_once_with(
            f"https://dash2.ambientweather.net/?api=1&applicationKey={TEST_APP_KEY}",
            engineio_path="socket.io",
            headers={},
            transports=["websocket"],
        )

        await client.websocket._sio._trigger_event("connect", namespace="/")
        on_connect.assert_called_once()

        await client.websocket._sio._trigger_event("data", namespace="/")
        on_data.assert_called_once()

        await client.websocket._sio._trigger_event("subscribed", namespace="/")
        on_subscribed.assert_called()

        await client.websocket.disconnect()
        await client.websocket._sio._trigger_event("disconnect", namespace="/")
        on_subscribed.assert_called_once()
        client.websocket._sio.eio.disconnect.mock.assert_called_once_with(
            abort=True)
Exemplo n.º 21
0
 def __init__(self, api_key, app_key):
     self.client = Client(api_key, app_key)