Search in sources :

Example 1 with MultiplexingClient

use of com.microsoft.azure.sdk.iot.device.MultiplexingClient in project azure-iot-sdk-java by Azure.

the class DigitalTwinClientTests method getMultiplexedDigitalTwinsRegisteredBeforeOpen.

// Open a multiplexed connection with two devices, each with a different model Id. Verify that their reported twin has
// the expected model Ids.
@Test
@StandardTierHubOnlyTest
public void getMultiplexedDigitalTwinsRegisteredBeforeOpen() throws IotHubException, IOException, URISyntaxException, MultiplexingClientException, InterruptedException {
    if (protocol == MQTT || protocol == MQTT_WS) {
        // multiplexing isn't supported over MQTT, so it can't be tested
        return;
    }
    MultiplexingClient multiplexingClient = new MultiplexingClient(deviceClient.getConfig().getIotHubHostname(), protocol);
    List<DeviceClient> multiplexedDeviceClients = new ArrayList<>();
    multiplexedDeviceClients.add(createDeviceClient(protocol, E2ETestConstants.THERMOSTAT_MODEL_ID));
    multiplexedDeviceClients.add(createDeviceClient(protocol, E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID));
    // register the devices before the multiplexing client has been opened
    multiplexingClient.registerDeviceClients(multiplexedDeviceClients);
    multiplexingClient.open();
    // act
    String thermostatDeviceId = multiplexedDeviceClients.get(0).getConfig().getDeviceId();
    BasicDigitalTwin thermostatResponse = digitalTwinClient.getDigitalTwin(thermostatDeviceId, BasicDigitalTwin.class);
    ServiceResponseWithHeaders<BasicDigitalTwin, DigitalTwinGetHeaders> thermostatResponseWithHeaders = digitalTwinClient.getDigitalTwinWithResponse(thermostatDeviceId, BasicDigitalTwin.class);
    String temperatureControllerDeviceId = multiplexedDeviceClients.get(1).getConfig().getDeviceId();
    BasicDigitalTwin temperatureControllerResponse = digitalTwinClient.getDigitalTwin(temperatureControllerDeviceId, BasicDigitalTwin.class);
    ServiceResponseWithHeaders<BasicDigitalTwin, DigitalTwinGetHeaders> temperatureControllerResponseWithHeaders = digitalTwinClient.getDigitalTwinWithResponse(temperatureControllerDeviceId, BasicDigitalTwin.class);
    // assert
    assertEquals(thermostatResponse.getMetadata().getModelId(), E2ETestConstants.THERMOSTAT_MODEL_ID);
    assertEquals(thermostatResponseWithHeaders.body().getMetadata().getModelId(), E2ETestConstants.THERMOSTAT_MODEL_ID);
    assertEquals(temperatureControllerResponse.getMetadata().getModelId(), E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID);
    assertEquals(temperatureControllerResponseWithHeaders.body().getMetadata().getModelId(), E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID);
}
Also used : BasicDigitalTwin(com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) ArrayList(java.util.ArrayList) DigitalTwinGetHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) MultiplexingClient(com.microsoft.azure.sdk.iot.device.MultiplexingClient) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) DigitalTwinTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.DigitalTwinTest) IntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) Test(org.junit.Test)

Example 2 with MultiplexingClient

use of com.microsoft.azure.sdk.iot.device.MultiplexingClient in project azure-iot-sdk-java by Azure.

the class DigitalTwinClientTests method getMultiplexedDigitalTwinsRegisteredAfterOpen.

// Open a multiplexed connection with no devices, then register two devices, each with a different model Id.
// Verify that their reported twin has the expected model Ids.
@Test
@StandardTierHubOnlyTest
public void getMultiplexedDigitalTwinsRegisteredAfterOpen() throws IotHubException, IOException, URISyntaxException, MultiplexingClientException, InterruptedException {
    if (protocol == MQTT || protocol == MQTT_WS) {
        // multiplexing isn't supported over MQTT, so it can't be tested
        return;
    }
    MultiplexingClient multiplexingClient = new MultiplexingClient(deviceClient.getConfig().getIotHubHostname(), protocol);
    List<DeviceClient> multiplexedDeviceClients = new ArrayList<>();
    multiplexedDeviceClients.add(createDeviceClient(protocol, E2ETestConstants.THERMOSTAT_MODEL_ID));
    multiplexedDeviceClients.add(createDeviceClient(protocol, E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID));
    multiplexingClient.open();
    // register the devices after the multiplexing client has been opened
    multiplexingClient.registerDeviceClients(multiplexedDeviceClients);
    // act
    String thermostatDeviceId = multiplexedDeviceClients.get(0).getConfig().getDeviceId();
    BasicDigitalTwin thermostatResponse = digitalTwinClient.getDigitalTwin(thermostatDeviceId, BasicDigitalTwin.class);
    ServiceResponseWithHeaders<BasicDigitalTwin, DigitalTwinGetHeaders> thermostatResponseWithHeaders = digitalTwinClient.getDigitalTwinWithResponse(thermostatDeviceId, BasicDigitalTwin.class);
    String temperatureControllerDeviceId = multiplexedDeviceClients.get(1).getConfig().getDeviceId();
    BasicDigitalTwin temperatureControllerResponse = digitalTwinClient.getDigitalTwin(temperatureControllerDeviceId, BasicDigitalTwin.class);
    ServiceResponseWithHeaders<BasicDigitalTwin, DigitalTwinGetHeaders> temperatureControllerResponseWithHeaders = digitalTwinClient.getDigitalTwinWithResponse(temperatureControllerDeviceId, BasicDigitalTwin.class);
    // assert
    assertEquals(thermostatResponse.getMetadata().getModelId(), E2ETestConstants.THERMOSTAT_MODEL_ID);
    assertEquals(thermostatResponseWithHeaders.body().getMetadata().getModelId(), E2ETestConstants.THERMOSTAT_MODEL_ID);
    assertEquals(temperatureControllerResponse.getMetadata().getModelId(), E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID);
    assertEquals(temperatureControllerResponseWithHeaders.body().getMetadata().getModelId(), E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID);
}
Also used : BasicDigitalTwin(com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) ArrayList(java.util.ArrayList) DigitalTwinGetHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) MultiplexingClient(com.microsoft.azure.sdk.iot.device.MultiplexingClient) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) DigitalTwinTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.DigitalTwinTest) IntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) Test(org.junit.Test)

Example 3 with MultiplexingClient

use of com.microsoft.azure.sdk.iot.device.MultiplexingClient in project azure-iot-sdk-java by Azure.

the class MultiplexingSample method main.

/**
 * Multiplex devices an IoT Hub using AMQPS / AMQPS_WS
 *
 * @param args
 * args[0] = protocol ("amqps" or "amqps_ws")
 * args[1] = host name to connect to (for instance, "my-iot-hub.azure-devices.net")
 * args[2] = IoT Hub connection string - Device Client 1
 * args[3] = IoT Hub connection string - Device Client 2
 * Add up to 998 device connection strings from args[4] on.
 *
 * Any additional arguments will be interpreted as additional connections strings. This allows this sample to be
 * run with more than 2 devices.
 */
public static void main(String[] args) throws URISyntaxException, InterruptedException, MultiplexingClientException {
    System.out.println("Starting...");
    System.out.println("Beginning setup.");
    if (args.length < 4) {
        System.out.format("Expected at least 3 arguments but received: %d.\n" + "The program should be called with the following args: \n" + "1. [Protocol]                   - amqps | amqps_ws\n" + "2. [HostName]                   - my-iot-hub.azure-devices.net\n" + "3. [Device 1 connection string] - String containing Hostname, Device Id & Device Key in one of the following formats: HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>\n" + "4. [Device 2 connection string] - String containing Hostname, Device Id & Device Key in one of the following formats: HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>\n" + ".\n" + ".\n" + ".\n", args.length);
        return;
    }
    IotHubClientProtocol protocol = IotHubClientProtocol.AMQPS;
    if (args[0].equalsIgnoreCase("amqps_ws")) {
        protocol = IotHubClientProtocol.AMQPS_WS;
    }
    String hostName = args[1];
    // This sample requires users for pass in at least 2 device connection strings, so this sample may multiplex
    final int multiplexedDeviceCount = args.length - 2;
    // Options include setting a custom SSLContext to use for the SSL handshake, configuring proxy support, and setting threading strategies
    MultiplexingClientOptions options = MultiplexingClientOptions.builder().build();
    final MultiplexingClient multiplexingClient = new MultiplexingClient(hostName, protocol, options);
    MultiplexingClientManager multiplexingClientManager = new MultiplexingClientManager(multiplexingClient, "MultiplexingClient");
    System.out.println("Creating device clients that will be multiplexed");
    final List<String> deviceIds = new ArrayList<>();
    final Map<String, DeviceClient> multiplexedDeviceClients = new HashMap<>(multiplexedDeviceCount);
    final Map<String, DeviceClientManager> deviceManagers = new HashMap<>(multiplexedDeviceCount);
    for (int i = 0; i < multiplexedDeviceCount; i++) {
        DeviceClient clientToMultiplex = new DeviceClient(args[i + 2], protocol);
        String deviceId = clientToMultiplex.getConfig().getDeviceId();
        deviceIds.add(deviceId);
        multiplexedDeviceClients.put(deviceId, clientToMultiplex);
        deviceManagers.put(deviceId, new DeviceClientManager(clientToMultiplex, multiplexingClientManager));
    }
    System.out.println("Opening multiplexed connection for " + deviceManagers.size() + " devices.");
    // All previously registered device clients will be opened alongside this multiplexing client
    try {
        multiplexingClientManager.open();
    } catch (MultiplexingClientException | IOException e) {
        // error is logged by the MultiplexingClientManager, no need to log it here, too
        System.out.println("Exiting sample...");
        System.exit(-1);
    }
    System.out.println("Multiplexed connection opened successfully");
    // Note that all the clients are registered at once. This method will asynchronously start the registration
    // process for each device client, and then it will block until all registrations are complete before returning.
    // If instead each client was registered separately through multiplexingClient.registerDeviceClient(), it would
    // take a longer time since it would block on each registration completing, rather than block on all registrations completing
    System.out.println("Registering " + multiplexedDeviceCount + " clients to the multiplexing client...");
    try {
        multiplexingClientManager.registerDeviceClients(multiplexedDeviceClients.values());
    } catch (MultiplexingClientException e) {
        // error is logged by the MultiplexingClientManager, no need to log it here, too
        System.out.println("Exiting sample...");
        System.exit(-1);
    }
    System.out.println("Successfully registered " + multiplexedDeviceCount + " clients to the multiplexing client");
    for (String deviceId : deviceIds) {
        System.out.printf("Sending message from device %s%n", deviceId);
        Message message = new Message("some payload");
        multiplexedDeviceClients.get(deviceId).sendEventAsync(message, new TelemetryAcknowledgedEventCallback(), message.getMessageId());
    }
    System.out.println("Waiting while messages get sent asynchronously...");
    while (acknowledgedSentMessages < multiplexedDeviceCount) {
        System.out.printf("Waiting on %d messages to be acknowledged out of %d%n", multiplexedDeviceCount - acknowledgedSentMessages, multiplexedDeviceCount);
        Thread.sleep(200);
    }
    System.out.println("All messages sent successfully");
    // This code demonstrates how to remove a device from an active multiplexed connection without shutting down
    // the whole multiplexed connection or any of the other devices.
    String deviceIdToUnregister = deviceIds.get(0);
    System.out.println("Unregistering device " + deviceIdToUnregister + " from multiplexed connection...");
    try {
        multiplexingClientManager.unregisterDeviceClient(multiplexedDeviceClients.get(deviceIdToUnregister));
    } catch (MultiplexingClientException e) {
        // error is logged by the MultiplexingClientManager, no need to log it here, too
        System.out.println("Exiting sample...");
        System.exit(-1);
    }
    System.out.println("Successfully unregistered device " + deviceIdToUnregister + " from an active multiplexed connection.");
    // Will always be true since this device client was registered to a multiplexing client at one point, even though
    // it isn't right now. Clients like these cannot be used to crete non-multiplexed connections, but may
    // be re-registered to any MultiplexingClient instance.
    boolean isMultiplexed = multiplexedDeviceClients.get(deviceIdToUnregister).isMultiplexed();
    // This code demonstrates how to add a device to an active multiplexed connection without shutting down
    // the whole multiplexed connection or any of the other devices.
    System.out.println("Re-registering device " + deviceIdToUnregister + " to an active multiplexed connection...");
    try {
        multiplexingClientManager.registerDeviceClient(multiplexedDeviceClients.get(deviceIdToUnregister));
    } catch (MultiplexingClientException e) {
        // error is logged by the MultiplexingClientManager, no need to log it here, too
        System.out.println("Exiting sample...");
        System.exit(-1);
    }
    System.out.println("Successfully registered " + deviceIdToUnregister + " to an active multiplexed connection");
    // Before closing a multiplexing client, you do not need to unregister all of the registered clients.
    // If they are not unregistered, then you can re-open the multiplexing client later and it will still
    // have all of your registered devices
    System.out.println("Closing entire multiplexed connection...");
    // This call will close all multiplexed device client instances as well
    multiplexingClientManager.closeClient();
    System.out.println("Successfully closed the multiplexed connection");
    System.out.println("Shutting down...");
}
Also used : Message(com.microsoft.azure.sdk.iot.device.Message) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) MultiplexingClient(com.microsoft.azure.sdk.iot.device.MultiplexingClient) MultiplexingClientException(com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) IotHubClientProtocol(com.microsoft.azure.sdk.iot.device.IotHubClientProtocol) MultiplexingClientOptions(com.microsoft.azure.sdk.iot.device.MultiplexingClientOptions)

Aggregations

DeviceClient (com.microsoft.azure.sdk.iot.device.DeviceClient)3 MultiplexingClient (com.microsoft.azure.sdk.iot.device.MultiplexingClient)3 ArrayList (java.util.ArrayList)3 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)2 DigitalTwinGetHeaders (com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders)2 BasicDigitalTwin (com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin)2 Test (org.junit.Test)2 IntegrationTest (tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest)2 DigitalTwinTest (tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.DigitalTwinTest)2 StandardTierHubOnlyTest (tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest)2 IotHubClientProtocol (com.microsoft.azure.sdk.iot.device.IotHubClientProtocol)1 Message (com.microsoft.azure.sdk.iot.device.Message)1 MultiplexingClientOptions (com.microsoft.azure.sdk.iot.device.MultiplexingClientOptions)1 MultiplexingClientException (com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException)1 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1