Search in sources :

Example 1 with MultiplexingClientException

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

the class MultiplexingClient method open.

/**
 * Opens this multiplexing client. This may be done before or after registering any number of device clients.
 * <p>
 * This call behaves synchronously, so if it returns without throwing, then all registered device clients were
 * successfully opened.
 * <p>
 * If this client is already open, then this method will do nothing.
 * <p>
 * @param withRetry if true, this open call will apply the current retry policy to allow for the open call to be
 * retried if it fails.
 *
 * @throws MultiplexingClientException If any IO or authentication errors occur while opening the multiplexed connection.
 * @throws MultiplexingClientDeviceRegistrationAuthenticationException If one or many of the registered devices failed to authenticate.
 * Any devices not found in the map of registration exceptions provided by
 * {@link MultiplexingClientDeviceRegistrationAuthenticationException#getRegistrationExceptions()} have registered successfully.
 * Even when this is thrown, the AMQPS/AMQPS_WS connection is still open, and other clients may be registered to it.
 */
public void open(boolean withRetry) throws MultiplexingClientException {
    synchronized (this.operationLock) {
        log.info("Opening multiplexing client");
        try {
            this.deviceIO.openWithoutWrappingException(withRetry);
        } catch (TransportException e) {
            // so that users don't need to look at the cause of the thrown exception to get this important information.
            if (e instanceof MultiplexingDeviceUnauthorizedException) {
                MultiplexingClientDeviceRegistrationAuthenticationException newException = new MultiplexingClientDeviceRegistrationAuthenticationException(OPEN_ERROR_MESSAGE, e);
                // Bring the exceptions map from the cause to the root level exception, so that users don't have to use
                // fields from inner exceptions.
                newException.setRegistrationExceptionsMap(((MultiplexingDeviceUnauthorizedException) e).getRegistrationExceptions());
                throw newException;
            }
            throw new MultiplexingClientException(OPEN_ERROR_MESSAGE, e);
        }
        log.info("Successfully opened multiplexing client");
    }
}
Also used : MultiplexingDeviceUnauthorizedException(com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingDeviceUnauthorizedException) MultiplexingClientDeviceRegistrationAuthenticationException(com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientDeviceRegistrationAuthenticationException) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException) MultiplexingClientException(com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException)

Example 2 with MultiplexingClientException

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

the class TransportClient method open.

/**
 * Creates a deviceIO and sets it to all the device client.
 * Verifies all device client's SAS tokens and renew them if it is necessary.
 * Opens the transport client connection.
 *
 * @throws IllegalStateException if the connection is already open.
 * @throws IOException if the connection to an IoT Hub cannot be opened.
 */
public void open() throws IllegalStateException, IOException {
    // Codes_SRS_TRANSPORTCLIENT_12_008: [The function shall throw  IllegalStateException if the connection is already open.]
    if ((this.deviceIO != null) && (this.deviceIO.isOpen())) {
        throw new IllegalStateException("The transport client connection is already open.");
    }
    // Codes_SRS_TRANSPORTCLIENT_12_009: [The function shall do nothing if the the registration list is empty.]
    if (this.deviceClientList.size() > 0) {
        // Codes_SRS_TRANSPORTCLIENT_12_011: [The function shall create a new DeviceIO using the first registered device client's configuration.]
        this.deviceIO = new DeviceIO(deviceClientList.get(0).getConfig(), SEND_PERIOD_MILLIS, RECEIVE_PERIOD_MILLIS_AMQPS, true);
        deviceClientList.get(0).setDeviceIO(this.deviceIO);
        // Codes_SRS_TRANSPORTCLIENT_12_012: [The function shall set the created DeviceIO to all registered device client.]
        List<DeviceClientConfig> configList = new ArrayList<>();
        for (int i = 1; i < this.deviceClientList.size(); i++) {
            deviceClientList.get(i).setDeviceIO(this.deviceIO);
            // propagate this client config to amqp connection
            configList.add(deviceClientList.get(i).getConfig());
        }
        try {
            this.deviceIO.registerMultiplexedDeviceClient(configList, DEFAULT_REGISTRATION_TIMEOUT_MILLISECONDS);
        } catch (InterruptedException e) {
            throw new IOException("Interrupted while registering device clients to the multiplexed connection", e);
        } catch (MultiplexingClientException e) {
            throw new IOException("Failed to register one or more device clients to the multiplexed connection", e);
        }
        // Codes_SRS_TRANSPORTCLIENT_12_013: [The function shall open the transport in multiplexing mode.]
        // this.deviceIO.multiplexOpen(deviceClientList);
        // if client is added just open to get rid of multiplex open.
        this.deviceIO.open(false);
    }
    this.transportClientState = TransportClientState.OPENED;
    log.info("Transport client opened successfully");
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) MultiplexingClientException(com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException)

Example 3 with MultiplexingClientException

use of com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException 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

MultiplexingClientException (com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 DeviceClient (com.microsoft.azure.sdk.iot.device.DeviceClient)1 IotHubClientProtocol (com.microsoft.azure.sdk.iot.device.IotHubClientProtocol)1 Message (com.microsoft.azure.sdk.iot.device.Message)1 MultiplexingClient (com.microsoft.azure.sdk.iot.device.MultiplexingClient)1 MultiplexingClientOptions (com.microsoft.azure.sdk.iot.device.MultiplexingClientOptions)1 MultiplexingClientDeviceRegistrationAuthenticationException (com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientDeviceRegistrationAuthenticationException)1 MultiplexingDeviceUnauthorizedException (com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingDeviceUnauthorizedException)1 TransportException (com.microsoft.azure.sdk.iot.device.exceptions.TransportException)1 HashMap (java.util.HashMap)1