Search in sources :

Example 31 with DeviceClient

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

the class Tools method getX509TestDevice.

private static TestDeviceIdentity getX509TestDevice(String iotHubConnectionString, IotHubClientProtocol protocol, boolean needCleanTwin) throws URISyntaxException, IOException, IotHubException, GeneralSecurityException {
    // and the subsequent callers just used one of those devices
    synchronized (testX509DeviceQueueLock) {
        TestDeviceIdentity testDeviceIdentity;
        if (!needCleanTwin && testX509DeviceWithTwinQueue.size() > 0) {
            log.debug("Acquiring test device from testX509DeviceWithTwinQueue");
            testDeviceIdentity = testX509DeviceWithTwinQueue.remove();
        } else {
            if (testX509DeviceQueue.size() < 1) {
                // No cached devices to return, so create a new set of devices to cache, and return one of the newly created devices
                log.debug("Proactively adding another {} devices to the X509 test device queue", PROACTIVE_TEST_DEVICE_REGISRATION_COUNT);
                List<Device> devicesToAdd = new ArrayList<>();
                for (int i = 0; i < PROACTIVE_TEST_DEVICE_REGISRATION_COUNT; i++) {
                    Device deviceToAdd = Device.createDevice("test-device-" + UUID.randomUUID().toString(), AuthenticationType.SELF_SIGNED);
                    String x509Thumbprint = IntegrationTest.x509CertificateGenerator.getX509Thumbprint();
                    deviceToAdd.setThumbprintFinal(x509Thumbprint, x509Thumbprint);
                    devicesToAdd.add(deviceToAdd);
                }
                addDevices(devicesToAdd, iotHubConnectionString);
                for (int i = 0; i < PROACTIVE_TEST_DEVICE_REGISRATION_COUNT; i++) {
                    testX509DeviceQueue.add(new TestDeviceIdentity(null, devicesToAdd.get(i)));
                }
            }
            log.debug("Acquiring test device from testX509DeviceQueue");
            testDeviceIdentity = testX509DeviceQueue.remove();
        }
        SSLContext sslContext = SSLContextBuilder.buildSSLContext(IntegrationTest.x509CertificateGenerator.getPublicCertificate(), IntegrationTest.x509CertificateGenerator.getPrivateKey());
        DeviceClient client = new DeviceClient(getRegistyManager(iotHubConnectionString).getDeviceConnectionString(testDeviceIdentity.getDevice()), protocol, sslContext);
        testDeviceIdentity.setDeviceClient(client);
        return testDeviceIdentity;
    }
}
Also used : Device(com.microsoft.azure.sdk.iot.service.Device) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) ArrayList(java.util.ArrayList) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) SSLContext(javax.net.ssl.SSLContext)

Example 32 with DeviceClient

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

the class FileUploadSimpleSample method main.

/**
 * Upload a single file to blobs using IoT Hub.
 *
 * @param args
 * args[0] = IoT Hub connection string
 * args[1] = File to upload
 */
public static void main(String[] args) throws IOException, URISyntaxException {
    String connString;
    String fullFileName;
    System.out.println("Starting...");
    System.out.println("Beginning setup.");
    if (args.length == 2) {
        connString = args[0];
        fullFileName = args[1];
    } else {
        System.out.format("Expected the following argument but received: %d.\n" + "The program should be called with the following args: \n" + "[Device connection string] - String containing Hostname, Device Id & Device Key in the following formats: HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>\n" + "[File to upload] - String containing the full path for the file to upload.\n", args.length);
        return;
    }
    // File upload will always use HTTPS, DeviceClient will use this protocol only
    // for the other services like Telemetry, Device Method and Device Twin.
    IotHubClientProtocol protocol = IotHubClientProtocol.MQTT;
    System.out.println("Successfully read input parameters.");
    DeviceClient client = new DeviceClient(connString, protocol);
    System.out.println("Successfully created an IoT Hub client.");
    try {
        File file = new File(fullFileName);
        if (file.isDirectory()) {
            throw new IllegalArgumentException(fullFileName + " is a directory, please provide a single file name, or use the FileUploadSample to upload directories.");
        }
        System.out.println("Retrieving SAS URI from IoT Hub...");
        FileUploadSasUriResponse sasUriResponse = client.getFileUploadSasUri(new FileUploadSasUriRequest(file.getName()));
        System.out.println("Successfully got SAS URI from IoT Hub");
        System.out.println("Correlation Id: " + sasUriResponse.getCorrelationId());
        System.out.println("Container name: " + sasUriResponse.getContainerName());
        System.out.println("Blob name: " + sasUriResponse.getBlobName());
        System.out.println("Blob Uri: " + sasUriResponse.getBlobUri());
        System.out.println("Using the Azure Storage SDK to upload file to Azure Storage...");
        try {
            BlobClient blobClient = new BlobClientBuilder().endpoint(sasUriResponse.getBlobUri().toString()).buildClient();
            blobClient.uploadFromFile(fullFileName);
        } catch (Exception e) {
            System.out.println("Exception encountered while uploading file to blob: " + e.getMessage());
            System.out.println("Failed to upload file to Azure Storage.");
            System.out.println("Notifying IoT Hub that the SAS URI can be freed and that the file upload failed.");
            // Note that this is done even when the file upload fails. IoT Hub has a fixed number of SAS URIs allowed active
            // at any given time. Once you are done with the file upload, you should free your SAS URI so that other
            // SAS URIs can be generated. If a SAS URI is not freed through this API, then it will free itself eventually
            // based on how long SAS URIs are configured to live on your IoT Hub.
            FileUploadCompletionNotification completionNotification = new FileUploadCompletionNotification(sasUriResponse.getCorrelationId(), false);
            client.completeFileUpload(completionNotification);
            System.out.println("Notified IoT Hub that the SAS URI can be freed and that the file upload was a failure.");
            client.closeNow();
            return;
        }
        System.out.println("Successfully uploaded file to Azure Storage.");
        System.out.println("Notifying IoT Hub that the SAS URI can be freed and that the file upload was a success.");
        FileUploadCompletionNotification completionNotification = new FileUploadCompletionNotification(sasUriResponse.getCorrelationId(), true);
        client.completeFileUpload(completionNotification);
        System.out.println("Successfully notified IoT Hub that the SAS URI can be freed, and that the file upload was a success");
    } catch (Exception e) {
        System.out.println("On exception, shutting down \n" + " Cause: " + e.getCause() + " \nERROR: " + e.getMessage());
        System.out.println("Shutting down...");
        client.closeNow();
    }
    System.out.println("Press any key to exit...");
    Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
    scanner.nextLine();
    System.out.println("Shutting down...");
    client.closeNow();
}
Also used : Scanner(java.util.Scanner) BlobClient(com.azure.storage.blob.BlobClient) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) IotHubClientProtocol(com.microsoft.azure.sdk.iot.device.IotHubClientProtocol) FileUploadSasUriResponse(com.microsoft.azure.sdk.iot.deps.serializer.FileUploadSasUriResponse) BlobClientBuilder(com.azure.storage.blob.BlobClientBuilder) FileUploadCompletionNotification(com.microsoft.azure.sdk.iot.deps.serializer.FileUploadCompletionNotification) File(java.io.File) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) FileUploadSasUriRequest(com.microsoft.azure.sdk.iot.deps.serializer.FileUploadSasUriRequest)

Example 33 with DeviceClient

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

Example 34 with DeviceClient

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

the class DesiredPropertiesTests method testSubscribeToDesiredPropertiesBatch.

// This test is for the startDeviceTwin/startTwin API that takes the TwinPropertiesCallback rather than the TwinPropertyCallback
// This callback should receive the full twin update in one callback, rather than one callback per updated
// desired property
@Test
@StandardTierHubOnlyTest
public void testSubscribeToDesiredPropertiesBatch() throws Exception {
    super.setUpNewDeviceAndModule(false);
    String expectedKey1 = UUID.randomUUID().toString();
    String expectedValue1 = UUID.randomUUID().toString();
    String expectedKey2 = UUID.randomUUID().toString();
    String expectedValue2 = UUID.randomUUID().toString();
    TwinCollection expectedDesiredProperties = new TwinCollection();
    expectedDesiredProperties.putFinal(expectedKey1, expectedValue1);
    expectedDesiredProperties.putFinal(expectedKey2, expectedValue2);
    TwinPropertiesCallback twinPropertiesCallback = new TwinPropertiesCallbackImpl(expectedDesiredProperties);
    Success desiredPropertiesCallbackState = new Success();
    testInstance.testIdentity.getClient().open();
    if (testInstance.testIdentity.getClient() instanceof DeviceClient) {
        ((DeviceClient) testInstance.testIdentity.getClient()).startDeviceTwin(new DeviceTwinStatusCallBack(), testInstance.deviceUnderTest, twinPropertiesCallback, desiredPropertiesCallbackState);
    } else {
        ((ModuleClient) testInstance.testIdentity.getClient()).startTwin(new DeviceTwinStatusCallBack(), testInstance.deviceUnderTest, twinPropertiesCallback, desiredPropertiesCallbackState);
    }
    long startTime = System.currentTimeMillis();
    while (testInstance.deviceUnderTest.deviceTwinStatus != IotHubStatusCode.OK) {
        Thread.sleep(200);
        if (System.currentTimeMillis() - startTime > START_TWIN_TIMEOUT_MILLISECONDS) {
            fail("Timed out waiting for twin to start");
        }
    }
    DeviceTwinDevice serviceClientTwin;
    if (testInstance.clientType == ClientType.DEVICE_CLIENT) {
        serviceClientTwin = new DeviceTwinDevice(testInstance.testIdentity.getClient().getConfig().getDeviceId());
    } else {
        serviceClientTwin = new DeviceTwinDevice(testInstance.testIdentity.getClient().getConfig().getDeviceId(), testInstance.testIdentity.getClient().getConfig().getModuleId());
    }
    Set<com.microsoft.azure.sdk.iot.service.devicetwin.Pair> desiredProperties = new HashSet<>();
    desiredProperties.add(new com.microsoft.azure.sdk.iot.service.devicetwin.Pair(expectedKey1, expectedValue1));
    desiredProperties.add(new com.microsoft.azure.sdk.iot.service.devicetwin.Pair(expectedKey2, expectedValue2));
    serviceClientTwin.setDesiredProperties(desiredProperties);
    testInstance.twinServiceClient.updateTwin(serviceClientTwin);
    startTime = System.currentTimeMillis();
    while (!desiredPropertiesCallbackState.wasCallbackFired()) {
        Thread.sleep(200);
        if (System.currentTimeMillis() - startTime > DESIRED_PROPERTIES_PROPAGATION_TIME_MILLISECONDS) {
            fail("Timed out waiting for desired properties callback to execute");
        }
    }
    assertTrue("Desired properties callback executed, but with unexpected properties", desiredPropertiesCallbackState.getResult());
}
Also used : DeviceTwinDevice(com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice) ModuleClient(com.microsoft.azure.sdk.iot.device.ModuleClient) TwinCollection(com.microsoft.azure.sdk.iot.deps.twin.TwinCollection) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) TwinPropertiesCallback(com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertiesCallback) Pair(com.microsoft.azure.sdk.iot.device.DeviceTwin.Pair) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) ContinuousIntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest) IotHubTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.IotHubTest) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) Test(org.junit.Test)

Example 35 with DeviceClient

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

the class DeviceTwinCommon method setUpTwin.

protected void setUpTwin(DeviceState deviceState, boolean openDeviceClient, InternalClient client) throws IOException, IotHubException, InterruptedException {
    // set up twin on DeviceClient
    deviceState.dCDeviceForTwin = new DeviceExtension();
    if ((this.testInstance.protocol == AMQPS || this.testInstance.protocol == AMQPS_WS) && this.testInstance.authenticationType == SAS) {
        client.setOption("SetAmqpOpenAuthenticationSessionTimeout", AMQP_AUTHENTICATION_SESSION_TIMEOUT_SECONDS);
        client.setOption("SetAmqpOpenDeviceSessionsTimeout", AMQP_DEVICE_SESSION_TIMEOUT_SECONDS);
    }
    if (openDeviceClient) {
        client.open();
        if (client instanceof DeviceClient) {
            ((DeviceClient) client).startDeviceTwin(new DeviceTwinStatusCallBack(), deviceState, deviceState.dCDeviceForTwin, deviceState);
        } else {
            ((ModuleClient) client).startTwin(new DeviceTwinStatusCallBack(), deviceState, deviceState.dCDeviceForTwin, deviceState);
        }
    }
    deviceState.deviceTwinStatus = IotHubStatusCode.ERROR;
    // set up twin on ServiceClient
    if (testInstance.twinServiceClient != null) {
        if (testInstance.clientType == ClientType.DEVICE_CLIENT) {
            deviceState.sCDeviceForTwin = new DeviceTwinDevice(deviceState.sCDeviceForRegistryManager.getDeviceId());
        } else {
            deviceState.sCDeviceForTwin = new DeviceTwinDevice(deviceState.sCDeviceForRegistryManager.getDeviceId(), deviceState.sCModuleForRegistryManager.getId());
        }
        testInstance.twinServiceClient.getTwin(deviceState.sCDeviceForTwin);
        Thread.sleep(DELAY_BETWEEN_OPERATIONS);
    }
}
Also used : DeviceTwinDevice(com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) ModuleClient(com.microsoft.azure.sdk.iot.device.ModuleClient)

Aggregations

DeviceClient (com.microsoft.azure.sdk.iot.device.DeviceClient)38 Test (org.junit.Test)21 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)16 IntegrationTest (tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest)14 Device (com.microsoft.azure.sdk.iot.service.Device)10 DeviceTwinDevice (com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice)10 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 IotHubClientProtocol (com.microsoft.azure.sdk.iot.device.IotHubClientProtocol)6 URISyntaxException (java.net.URISyntaxException)6 Message (com.microsoft.azure.sdk.iot.device.Message)5 MultiplexingClientDeviceRegistrationAuthenticationException (com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientDeviceRegistrationAuthenticationException)5 ModuleClient (com.microsoft.azure.sdk.iot.device.ModuleClient)4 UnauthorizedException (com.microsoft.azure.sdk.iot.device.exceptions.UnauthorizedException)4 Property (com.microsoft.azure.sdk.iot.device.DeviceTwin.Property)3 MultiplexingClient (com.microsoft.azure.sdk.iot.device.MultiplexingClient)3 RegistryManager (com.microsoft.azure.sdk.iot.service.RegistryManager)3 DigitalTwinGetHeaders (com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders)3 BasicDigitalTwin (com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin)3