Example #1
0
    async def async_added_to_opp(self):
        """Connect camera methods to signals."""
        def _dispatch_proxy(method):
            """Expand parameters & filter entity IDs."""
            async def _call(params):
                entity_ids = params.get(ATTR_ENTITY_ID)
                filtered_params = {
                    k: v
                    for k, v in params.items() if k != ATTR_ENTITY_ID
                }
                if entity_ids is None or self.entity_id in entity_ids:
                    await method(**filtered_params)

            return _call

        self._listeners.extend([
            async_dispatcher_connect(
                self.opp,
                SIGNAL_LOGI_CIRCLE_RECONFIGURE,
                _dispatch_proxy(self.set_config),
            ),
            async_dispatcher_connect(
                self.opp,
                SIGNAL_LOGI_CIRCLE_SNAPSHOT,
                _dispatch_proxy(self.livestream_snapshot),
            ),
            async_dispatcher_connect(
                self.opp,
                SIGNAL_LOGI_CIRCLE_RECORD,
                _dispatch_proxy(self.download_livestream),
            ),
        ])
Example #2
0
 async def async_added_to_opp(self):
     """Add device to dict."""
     async_dispatcher_connect(
         self.opp,
         SIGNAL_REFRESH_ENTITY_FORMAT.format(self.entity_id),
         self.refresh_from_network,
     )
Example #3
0
    async def async_added_to_opp(self):
        """Register update callback."""
        # Remove temporary bogus entity_id if added
        tmp_entity = TMP_ENTITY.format(self._device_id)
        if (tmp_entity in self.opp.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR][
                self._device_id]):
            self.opp.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR][
                self._device_id].remove(tmp_entity)

        # Register id and aliases
        self.opp.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR][
            self._device_id].append(self.entity_id)
        if self._aliases:
            for _id in self._aliases:
                self.opp.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR][
                    _id].append(self.entity_id)
        self.async_on_remove(
            async_dispatcher_connect(self.opp, SIGNAL_AVAILABILITY,
                                     self._availability_callback))
        self.async_on_remove(
            async_dispatcher_connect(
                self.opp,
                SIGNAL_HANDLE_EVENT.format(self.entity_id),
                self.handle_event_callback,
            ))

        # Process the initial event now that the entity is created
        if self._initial_event:
            self.handle_event_callback(self._initial_event)
Example #4
0
async def test_internal_discovery_callback_fill_out_group(opp):
    """Test internal discovery automatically filling out information."""
    discover_cast, _, _ = await async_setup_cast_internal_discovery(opp)
    info = get_fake_chromecast_info(host="host1", port=12345)
    zconf = get_fake_zconf(host="host1", port=12345)
    full_info = attr.evolve(
        info,
        model_name="",
        friendly_name="Speaker",
        uuid=FakeUUID,
        is_dynamic_group=False,
    )

    with patch(
        "openpeerpower.components.cast.helpers.dial.get_device_status",
        return_value=full_info,
    ), patch(
        "openpeerpower.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
        return_value=zconf,
    ):
        signal = MagicMock()

        async_dispatcher_connect(opp, "cast_discovered", signal)
        discover_cast("the-service", info)
        await opp.async_block_till_done()

        # when called with incomplete info, it should use HTTP to get missing
        discover = signal.mock_calls[0][1][0]
        assert discover == full_info
Example #5
0
 async def async_added_to_opp(self):
     """Store entity_id and register state change callback."""
     entity_id_key = self._addr or self._type
     self._data[entity_id_key] = self.entity_id
     async_dispatcher_connect(self.opp,
                              f"konnected.{self.entity_id}.update",
                              self.async_set_state)
Example #6
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Cast from a config entry."""
    opp.data.setdefault(ADDED_CAST_DEVICES_KEY, set())

    # Import CEC IGNORE attributes
    pychromecast.IGNORE_CEC += config_entry.data.get(CONF_IGNORE_CEC) or []

    wanted_uuids = config_entry.data.get(CONF_UUID) or None

    @callback
    def async_cast_discovered(discover: ChromecastInfo) -> None:
        """Handle discovery of a new chromecast."""
        # If wanted_uuids is set, we're only accepting specific cast devices identified
        # by UUID
        if wanted_uuids is not None and discover.uuid not in wanted_uuids:
            # UUID not matching, ignore.
            return

        cast_device = _async_create_cast_device(opp, discover)
        if cast_device is not None:
            async_add_entities([cast_device])

    async_dispatcher_connect(opp, SIGNAL_CAST_DISCOVERED,
                             async_cast_discovered)
    ChromeCastZeroconf.set_zeroconf(await zeroconf.async_get_instance(opp))
    opp.async_add_executor_job(setup_internal_discovery, opp, config_entry)
Example #7
0
    async def async_added_to_opp(self):
        """Connect and subscribe to dispatcher signals and state updates."""
        async_dispatcher_connect(self.opp, DOMAIN, self.async_signal_handler)

        await self._client.register_state_update_callback(
            self.async_handle_state_update
        )
Example #8
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up device tracker for Mikrotik component."""
    hub = opp.data[DOMAIN][config_entry.entry_id]

    tracked = {}

    registry = await entity_registry.async_get_registry(opp)

    # Restore clients that is not a part of active clients list.
    for entity in registry.entities.values():

        if (entity.config_entry_id == config_entry.entry_id
                and entity.domain == DEVICE_TRACKER):

            if (entity.unique_id in hub.api.devices
                    or entity.unique_id not in hub.api.all_devices):
                continue
            hub.api.restore_device(entity.unique_id)

    @callback
    def update_hub():
        """Update the status of the device."""
        update_items(hub, async_add_entities, tracked)

    async_dispatcher_connect(opp, hub.signal_update, update_hub)

    update_hub()
Example #9
0
async def async_setup_entry(opp, entry, async_add_entities):
    """Set up Plaato from a config entry."""
    entry_data = opp.data[DOMAIN][entry.entry_id]

    @callback
    async def _async_update_from_webhook(device_id, sensor_data: PlaatoDevice):
        """Update/Create the sensors."""
        entry_data[SENSOR_DATA] = sensor_data

        if device_id != entry_data[DEVICE][DEVICE_ID]:
            entry_data[DEVICE][DEVICE_ID] = device_id
            async_add_entities([
                PlaatoSensor(entry_data, sensor_type)
                for sensor_type in sensor_data.sensors
            ])
        else:
            for sensor_type in sensor_data.sensors:
                async_dispatcher_send(opp,
                                      SENSOR_SIGNAL % (device_id, sensor_type))

    if entry.data[CONF_USE_WEBHOOK]:
        async_dispatcher_connect(opp, SENSOR_UPDATE,
                                 _async_update_from_webhook)
    else:
        coordinator = entry_data[COORDINATOR]
        async_add_entities(
            PlaatoSensor(entry_data, sensor_type, coordinator)
            for sensor_type in coordinator.data.sensors)
Example #10
0
    async def async_added_to_opp(self) -> None:
        """Handle common setup when added to opp."""
        await self.speaker.async_seen()

        self.async_on_remove(
            async_dispatcher_connect(
                self.opp,
                f"{SONOS_POLL_UPDATE}-{self.soco.uid}",
                self.async_poll,
            )
        )
        self.async_on_remove(
            async_dispatcher_connect(
                self.opp,
                f"{SONOS_STATE_UPDATED}-{self.soco.uid}",
                self.async_write_op_state,
            )
        )
        self.async_on_remove(
            async_dispatcher_connect(
                self.opp,
                f"{SONOS_HOUSEHOLD_UPDATED}-{self.soco.household_id}",
                self.async_write_op_state,
            )
        )
        async_dispatcher_send(
            self.opp, f"{SONOS_ENTITY_CREATED}-{self.soco.uid}", self.platform.domain
        )
Example #11
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Roon MediaPlayer from Config Entry."""
    roon_server = opp.data[DOMAIN][config_entry.entry_id]
    media_players = set()

    # Register entity services
    platform = entity_platform.async_get_current_platform()
    platform.async_register_entity_service(
        SERVICE_TRANSFER,
        {vol.Required(ATTR_TRANSFER): cv.entity_id},
        "async_transfer",
    )

    @callback
    def async_update_media_player(player_data):
        """Add or update Roon MediaPlayer."""
        dev_id = player_data["dev_id"]
        if dev_id not in media_players:
            # new player!
            media_player = RoonDevice(roon_server, player_data)
            media_players.add(dev_id)
            async_add_entities([media_player])
        else:
            # update existing player
            async_dispatcher_send(
                opp, f"room_media_player_update_{dev_id}", player_data
            )

    # start listening for players to be added or changed by the server component
    async_dispatcher_connect(opp, "roon_media_player", async_update_media_player)
async def test_internal_discovery_callback_fill_out(opp):
    """Test internal discovery automatically filling out information."""
    import pychromecast  # imports mock pychromecast

    pychromecast.ChromecastConnectionError = IOError

    discover_cast, _ = await async_setup_cast_internal_discovery(opp)
    info = get_fake_chromecast_info(uuid=None)
    full_info = attr.evolve(info,
                            model_name="google home",
                            friendly_name="Speaker",
                            uuid=FakeUUID)

    with patch(
            "openpeerpower.components.cast.helpers.dial.get_device_status",
            return_value=full_info,
    ):
        signal = MagicMock()

        async_dispatcher_connect(opp, "cast_discovered", signal)
        discover_cast("the-service", info)
        await opp.async_block_till_done()

        # when called with incomplete info, it should use HTTP to get missing
        discover = signal.mock_calls[0][1][0]
        assert discover == full_info
Example #13
0
async def test_update_device(opp):
    """Test that update works."""
    host = "1.2.3.4"
    entry = MockConfigEntry(domain=dynalite.DOMAIN,
                            data={dynalite.CONF_HOST: host})
    entry.add_to_opp(opp)
    with patch("openpeerpower.components.dynalite.bridge.DynaliteDevices"
               ) as mock_dyn_dev:
        mock_dyn_dev().async_setup = AsyncMock(return_value=True)
        assert await opp.config_entries.async_setup(entry.entry_id)
        # Not waiting so it add the devices before registration
        update_device_func = mock_dyn_dev.mock_calls[1][2][
            "update_device_func"]
    device = Mock()
    device.unique_id = "abcdef"
    wide_func = Mock()
    async_dispatcher_connect(opp, f"dynalite-update-{host}", wide_func)
    specific_func = Mock()
    async_dispatcher_connect(opp, f"dynalite-update-{host}-{device.unique_id}",
                             specific_func)
    update_device_func()
    await opp.async_block_till_done()
    wide_func.assert_called_once()
    specific_func.assert_not_called()
    update_device_func(device)
    await opp.async_block_till_done()
    wide_func.assert_called_once()
    specific_func.assert_called_once()
async def async_setup_scanner(opp, config, async_see, discovery_info=None):
    """Set up the MySensors device scanner."""
    new_devices = mysensors.setup_mysensors_platform(
        opp,
        DOMAIN,
        discovery_info,
        MySensorsDeviceScanner,
        device_args=(opp, async_see),
    )
    if not new_devices:
        return False

    for device in new_devices:
        gateway_id = id(device.gateway)
        dev_id = (gateway_id, device.node_id, device.child_id, device.value_type)
        async_dispatcher_connect(
            opp,
            mysensors.const.CHILD_CALLBACK.format(*dev_id),
            device.async_update_callback,
        )
        async_dispatcher_connect(
            opp,
            mysensors.const.NODE_CALLBACK.format(gateway_id, device.node_id),
            device.async_update_callback,
        )

    return True
Example #15
0
def async_subscribe_connection_status(opp, connection_status_callback):
    """Subscribe to MQTT connection changes."""
    connection_status_callback_job = OppJob(connection_status_callback)

    async def connected():
        task = opp.async_run_opp_job(connection_status_callback_job, True)
        if task:
            await task

    async def disconnected():
        task = opp.async_run_opp_job(connection_status_callback_job, False)
        if task:
            await task

    subscriptions = {
        "connect":
        async_dispatcher_connect(opp, MQTT_CONNECTED, connected),
        "disconnect":
        async_dispatcher_connect(opp, MQTT_DISCONNECTED, disconnected),
    }

    @callback
    def unsubscribe():
        subscriptions["connect"]()
        subscriptions["disconnect"]()

    return unsubscribe
Example #16
0
 async def async_added_to_opp(self):
     """Call when entity is added to opp."""
     self._remove_signal_delete = async_dispatcher_connect(
         self.opp, f"gdacs_delete_{self._external_id}",
         self._delete_callback)
     self._remove_signal_update = async_dispatcher_connect(
         self.opp, f"gdacs_update_{self._external_id}",
         self._update_callback)
Example #17
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Z-Wave Fan from Config Entry."""
    @callback
    def async_add_fan(fan):
        """Add Z-Wave Fan."""
        async_add_entities([fan])

    async_dispatcher_connect(opp, "zwave_new_fan", async_add_fan)
Example #18
0
 def __init__(self, opp, addr, name):
     """Register callback that will be used for signals."""
     self._opp = opp
     self._addr = addr
     self._name = name
     self._id = slugify(self._name)
     signal = f"homeworks_entity_{self._addr}"
     async_dispatcher_connect(self._opp, signal, self._update_callback)
Example #19
0
 async def async_added_to_opp(self):
     """Connect to the OpenTherm Gateway device."""
     _LOGGER.debug("Added OpenTherm Gateway climate device %s",
                   self.friendly_name)
     self._unsub_updates = async_dispatcher_connect(
         self.opp, self._gateway.update_signal, self.receive_report)
     self._unsub_options = async_dispatcher_connect(
         self.opp, self._gateway.options_update_signal, self.update_options)
Example #20
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Z-Wave Light from Config Entry."""
    @callback
    def async_add_light(light):
        """Add Z-Wave Light."""
        async_add_entities([light])

    async_dispatcher_connect(opp, "zwave_new_light", async_add_light)
Example #21
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Z-Wave Climate device from Config Entry."""
    @callback
    def async_add_climate(climate):
        """Add Z-Wave Climate Device."""
        async_add_entities([climate])

    async_dispatcher_connect(opp, "zwave_new_climate", async_add_climate)
Example #22
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Z-Wave Cover from Config Entry."""
    @callback
    def async_add_cover(cover):
        """Add Z-Wave Cover."""
        async_add_entities([cover])

    async_dispatcher_connect(opp, "zwave_new_cover", async_add_cover)
Example #23
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Z-Wave Switch from Config Entry."""
    @callback
    def async_add_switch(switch):
        """Add Z-Wave Switch."""
        async_add_entities([switch])

    async_dispatcher_connect(opp, "zwave_new_switch", async_add_switch)
Example #24
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up Z-Wave binary sensors from Config Entry."""
    @callback
    def async_add_binary_sensor(binary_sensor):
        """Add Z-Wave  binary sensor."""
        async_add_entities([binary_sensor])

    async_dispatcher_connect(opp, "zwave_new_binary_sensor",
                             async_add_binary_sensor)
Example #25
0
 async def async_accept_signal(self, channel, signal, func, signal_override=False):
     """Accept a signal from a channel."""
     unsub = None
     if signal_override:
         unsub = async_dispatcher_connect(self.opp, signal, func)
     else:
         unsub = async_dispatcher_connect(
             self.opp, f"{channel.unique_id}_{signal}", func
         )
     self._unsubs.append(unsub)
Example #26
0
 async def async_added_to_opp(self):
     """Call when entity is added to opp."""
     self.opp.data[DOMAIN]["entities"][self.object_id] = self.entity_id
     self.async_on_remove(
         async_dispatcher_connect(self.opp, SIGNAL_DELETE_ENTITY,
                                  self._delete_callback))
     self.async_on_remove(
         async_dispatcher_connect(self.opp, SIGNAL_UPDATE_ENTITY,
                                  self._update_callback))
     self._inc_device_count()
Example #27
0
 async def async_added_to_opp(self) -> None:
     """Subscribe MQTT events."""
     await super().async_added_to_opp()
     await self._availability_subscribe_topics()
     self.async_on_remove(
         async_dispatcher_connect(self.opp, MQTT_CONNECTED,
                                  self.async_mqtt_connect))
     self.async_on_remove(
         async_dispatcher_connect(self.opp, MQTT_DISCONNECTED,
                                  self.async_mqtt_connect))
Example #28
0
async def async_setup_entry(opp, config_entry, async_add_entities):
    """Set up a Point's alarm_control_panel based on a config entry."""
    async def async_discover_home(home_id):
        """Discover and add a discovered home."""
        client = opp.data[POINT_DOMAIN][config_entry.entry_id]
        async_add_entities([MinutPointAlarmControl(client, home_id)], True)

    async_dispatcher_connect(opp,
                             POINT_DISCOVERY_NEW.format(DOMAIN, POINT_DOMAIN),
                             async_discover_home)
Example #29
0
async def test_empty_integrations_list_is_only_sent_at_the_end_of_bootstrap(
        opp):
    """Test empty integrations list is only sent at the end of bootstrap."""
    order = []

    def gen_domain_setup(domain):
        async def async_setup(opp, config):
            order.append(domain)
            await asyncio.sleep(0.1)

            async def _background_task():
                await asyncio.sleep(0.2)

            await opp.async_create_task(_background_task())
            return True

        return async_setup

    mock_integration(
        opp,
        MockModule(
            domain="normal_integration",
            async_setup=gen_domain_setup("normal_integration"),
            partial_manifest={"after_dependencies": ["an_after_dep"]},
        ),
    )
    mock_integration(
        opp,
        MockModule(
            domain="an_after_dep",
            async_setup=gen_domain_setup("an_after_dep"),
        ),
    )

    integrations = []

    @core.callback
    def _bootstrap_integrations(data):
        integrations.append(data)

    async_dispatcher_connect(opp, SIGNAL_BOOTSTRAP_INTEGRATONS,
                             _bootstrap_integrations)
    with patch.object(bootstrap, "SLOW_STARTUP_CHECK_INTERVAL", 0.05):
        await bootstrap._async_set_up_integrations(opp, {
            "normal_integration": {},
            "an_after_dep": {}
        })

    assert integrations[0] != {}
    assert "an_after_dep" in integrations[0]
    assert integrations[-3] != {}
    assert integrations[-1] == {}

    assert "normal_integration" in opp.config.components
    assert order == ["an_after_dep", "normal_integration"]
Example #30
0
async def trace_action(opp, script_run, stop, variables):
    """Trace action execution."""
    path = trace_path_get()
    trace_element = action_trace_append(variables, path)
    trace_stack_push(trace_stack_cv, trace_element)

    trace_id = trace_id_get()
    if trace_id:
        key = trace_id[0]
        run_id = trace_id[1]
        breakpoints = opp.data[DATA_SCRIPT_BREAKPOINTS]
        if key in breakpoints and (
            (run_id in breakpoints[key] and
             (path in breakpoints[key][run_id]
              or NODE_ANY in breakpoints[key][run_id])) or
            (RUN_ID_ANY in breakpoints[key] and
             (path in breakpoints[key][RUN_ID_ANY]
              or NODE_ANY in breakpoints[key][RUN_ID_ANY]))):
            async_dispatcher_send(opp, SCRIPT_BREAKPOINT_HIT, key, run_id,
                                  path)

            done = asyncio.Event()

            @callback
            def async_continue_stop(command=None):
                if command == "stop":
                    stop.set()
                done.set()

            signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
            remove_signal1 = async_dispatcher_connect(opp, signal,
                                                      async_continue_stop)
            remove_signal2 = async_dispatcher_connect(
                opp, SCRIPT_DEBUG_CONTINUE_ALL, async_continue_stop)

            tasks = [
                opp.async_create_task(flag.wait()) for flag in (stop, done)
            ]
            await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
            for task in tasks:
                task.cancel()
            remove_signal1()
            remove_signal2()

    try:
        yield trace_element
    except _StopScript as ex:
        trace_element.set_error(ex.__cause__ or ex)
        raise ex
    except Exception as ex:
        trace_element.set_error(ex)
        raise ex
    finally:
        trace_stack_pop(trace_stack_cv)