def test_long_running_partition_send_async(connection_str):
    parser = argparse.ArgumentParser()
    parser.add_argument("--duration", help="Duration in seconds of the test", type=int, default=30)
    parser.add_argument("--payload", help="payload size", type=int, default=1024)
    parser.add_argument("--batch", help="Number of events to send and wait", type=int, default=200)
    parser.add_argument("--partitions", help="Comma seperated partition IDs")
    parser.add_argument("--conn-str", help="EventHub connection string", default=connection_str)
    parser.add_argument("--eventhub", help="Name of EventHub")
    parser.add_argument("--address", help="Address URI to the EventHub entity")
    parser.add_argument("--sas-policy", help="Name of the shared access policy to authenticate with")
    parser.add_argument("--sas-key", help="Shared access key")
    parser.add_argument("--logger-name", help="Unique log file ID")

    loop = asyncio.get_event_loop()
    args, _ = parser.parse_known_args()

    if args.conn_str:
        client = EventHubClientAsync.from_connection_string(
            args.conn_str,
            eventhub=args.eventhub, debug=True)
    elif args.address:
        client = EventHubClientAsync(
            args.address,
            username=args.sas_policy,
            password=args.sas_key,
            auth_timeout=500)
    else:
        try:
            import pytest
            pytest.skip("Must specify either '--conn-str' or '--address'")
        except ImportError:
            raise ValueError("Must specify either '--conn-str' or '--address'")

    try:
        if not args.partitions:
            partitions = loop.run_until_complete(get_partitions(client))
        else:
            pid_range = args.partitions.split("-")
            if len(pid_range) > 1:
                partitions = [str(i) for i in range(int(pid_range[0]), int(pid_range[1]) + 1)]
            else:
                partitions = args.partitions.split(",")
        pumps = []
        for pid in partitions:
            sender = client.add_async_sender(partition=pid, send_timeout=0, keep_alive=False)
            pumps.append(pump(pid, sender, args, args.duration))
        loop.run_until_complete(client.run_async())
        results = loop.run_until_complete(asyncio.gather(*pumps, return_exceptions=True))
        assert not results
    except Exception as e:
        logger.error("Sender failed: {}".format(e))
    finally:
        logger.info("Shutting down sender")
        loop.run_until_complete(client.stop_async())
def test_long_running_partition_send_async(connection_str):
    parser = argparse.ArgumentParser()
    parser.add_argument("--duration", help="Duration in seconds of the test", type=int, default=30)
    parser.add_argument("--payload", help="payload size", type=int, default=1024)
    parser.add_argument("--batch", help="Number of events to send and wait", type=int, default=200)
    parser.add_argument("--partitions", help="Comma seperated partition IDs")
    parser.add_argument("--conn-str", help="EventHub connection string", default=connection_str)
    parser.add_argument("--eventhub", help="Name of EventHub")
    parser.add_argument("--address", help="Address URI to the EventHub entity")
    parser.add_argument("--sas-policy", help="Name of the shared access policy to authenticate with")
    parser.add_argument("--sas-key", help="Shared access key")
    parser.add_argument("--logger-name", help="Unique log file ID")

    loop = asyncio.get_event_loop()
    args, _ = parser.parse_known_args()

    if args.conn_str:
        client = EventHubClientAsync.from_connection_string(
            args.conn_str,
            eventhub=args.eventhub, debug=True)
    elif args.address:
        client = EventHubClientAsync(
            args.address,
            username=args.sas_policy,
            password=args.sas_key,
            auth_timeout=500)
    else:
        try:
            import pytest
            pytest.skip("Must specify either '--conn-str' or '--address'")
        except ImportError:
            raise ValueError("Must specify either '--conn-str' or '--address'")

    try:
        if not args.partitions:
            partitions = loop.run_until_complete(get_partitions(client))
        else:
            pid_range = args.partitions.split("-")
            if len(pid_range) > 1:
                partitions = [str(i) for i in range(int(pid_range[0]), int(pid_range[1]) + 1)]
            else:
                partitions = args.partitions.split(",")
        pumps = []
        for pid in partitions:
            sender = client.add_async_sender(partition=pid, send_timeout=0, keep_alive=False)
            pumps.append(pump(pid, sender, args, args.duration))
        loop.run_until_complete(client.run_async())
        results = loop.run_until_complete(asyncio.gather(*pumps, return_exceptions=True))
        assert not results
    except Exception as e:
        logger.error("Sender failed: {}".format(e))
    finally:
        logger.info("Shutting down sender")
        loop.run_until_complete(client.stop_async())
async def sendMessageAsync(payload, partition="0"):
    global g_logObj
    g_logObj.debug("sendMessageAsync")

    client = EventHubClientAsync(ADDRESS,
                                 debug=True,
                                 username=USER,
                                 password=KEY)
    sender = client.add_async_sender(partition=partition)
    await client.run_async()
    data = EventData(payload)
    await sender.send(data)
    await client.stop_async()
    print('message sent {}'.format(payload))
示例#4
0
async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
    """Activate Azure EH component."""
    config = yaml_config[DOMAIN]

    event_hub_address = (
        f"amqps://{config[CONF_EVENT_HUB_NAMESPACE]}"
        f".servicebus.windows.net/{config[CONF_EVENT_HUB_INSTANCE_NAME]}"
    )
    entities_filter = config[CONF_FILTER]

    client = EventHubClientAsync(
        event_hub_address,
        debug=True,
        username=config[CONF_EVENT_HUB_SAS_POLICY],
        password=config[CONF_EVENT_HUB_SAS_KEY],
    )
    async_sender = client.add_async_sender()
    await client.run_async()

    encoder = JSONEncoder()

    async def async_send_to_event_hub(event: Event):
        """Send states to Event Hub."""
        state = event.data.get("new_state")
        if (
            state is None
            or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE)
            or not entities_filter(state.entity_id)
        ):
            return

        event_data = EventData(
            json.dumps(obj=state.as_dict(), default=encoder.encode).encode("utf-8")
        )
        await async_sender.send(event_data)

    async def async_shutdown(event: Event):
        """Shut down the client."""
        await client.stop_async()

    hass.bus.async_listen(EVENT_STATE_CHANGED, async_send_to_event_hub)
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_shutdown)

    return True