Search in sources :

Example 1 with UpdateOperationUtility

use of com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility in project azure-iot-sdk-java by Azure.

the class TemperatureController method UpdateDigitalTwinComponentProperty.

private static void UpdateDigitalTwinComponentProperty() {
    // Get digital twin.
    ServiceResponseWithHeaders<String, DigitalTwinGetHeaders> getResponse = GetDigitalTwin();
    // Construct the options for conditional update.
    DigitalTwinUpdateRequestOptions options = new DigitalTwinUpdateRequestOptions();
    options.setIfMatch(getResponse.headers().eTag());
    UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility();
    // The json patch format can be found here - https://docs.microsoft.com/en-us/azure/iot-pnp/howto-manage-digital-twin#update-a-digital-twin.
    // Add a new component.
    String newComponentName = "newThermostat";
    System.out.println("--------------------------------------------------------------------------------------------");
    System.out.println("Add a new component " + newComponentName);
    System.out.println("--------------------------------------------------------------------------------------------");
    options.setIfMatch(getResponse.headers().eTag());
    String path = "/" + newComponentName;
    Map<String, Object> properties = new HashMap<>();
    properties.put(propertyName, 50);
    updateOperationUtility.appendAddComponentOperation(path, properties);
    List<Object> digitalTwinUpdateOperations = updateOperationUtility.getUpdateOperations();
    ServiceResponseWithHeaders<Void, DigitalTwinUpdateHeaders> updateResponse = client.updateDigitalTwinWithResponse(digitalTwinid, digitalTwinUpdateOperations, options);
    System.out.println("Update Digital Twin response status: " + updateResponse.response().message());
    getResponse = GetDigitalTwin();
    // Replace an existing component.
    String component1 = "thermostat1";
    String component2 = "thermostat2";
    System.out.println("--------------------------------------------------------------------------------------------");
    System.out.println("Replace existing components " + component1 + " and " + component2);
    System.out.println("--------------------------------------------------------------------------------------------");
    options.setIfMatch(getResponse.headers().eTag());
    path = "/" + component1;
    Map<String, Object> t1properties = new HashMap<>();
    t1properties.put(propertyName, 50);
    updateOperationUtility.appendReplaceComponentOperation(path, t1properties);
    path = "/" + component2;
    Map<String, Object> t2properties = new HashMap<>();
    t2properties.put(propertyName, 40);
    updateOperationUtility.appendReplaceComponentOperation(path, t2properties);
    digitalTwinUpdateOperations = updateOperationUtility.getUpdateOperations();
    updateResponse = client.updateDigitalTwinWithResponse(digitalTwinid, digitalTwinUpdateOperations, options);
    System.out.println("Update Digital Twin response status: " + updateResponse.response().message());
    getResponse = GetDigitalTwin();
    // Remove the new component.
    System.out.println("--------------------------------------------------------------------------------------------");
    System.out.println("Remove the new component " + newComponentName);
    System.out.println("--------------------------------------------------------------------------------------------");
    options.setIfMatch(getResponse.headers().eTag());
    path = "/newThermostat";
    updateOperationUtility.appendRemoveComponentOperation(path);
    digitalTwinUpdateOperations = updateOperationUtility.getUpdateOperations();
    updateResponse = client.updateDigitalTwinWithResponse(digitalTwinid, digitalTwinUpdateOperations, options);
    System.out.println("Update Digital Twin response status: " + updateResponse.response().message());
    GetDigitalTwin();
}
Also used : UpdateOperationUtility(com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility) DigitalTwinUpdateHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinUpdateHeaders) HashMap(java.util.HashMap) DigitalTwinGetHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders) JsonObject(com.google.gson.JsonObject)

Example 2 with UpdateOperationUtility

use of com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility in project azure-iot-sdk-java by Azure.

the class DigitalTwinClientComponentTests method updateDigitalTwin.

@Test
@StandardTierHubOnlyTest
public void updateDigitalTwin() {
    // arrange
    String newProperty = "currentTemperature";
    Integer newPropertyValue = 35;
    String newComponent = "newThermostat";
    String newComponentPath = "/newThermostat";
    Map<String, Object> componentProperties = new HashMap<>();
    componentProperties.put(newProperty, newPropertyValue);
    DigitalTwinUpdateRequestOptions optionsWithoutEtag = new DigitalTwinUpdateRequestOptions();
    optionsWithoutEtag.setIfMatch("*");
    // get digital twin and Etag before update
    ServiceResponseWithHeaders<BasicDigitalTwin, DigitalTwinGetHeaders> responseWithHeaders = digitalTwinClient.getDigitalTwinWithResponse(deviceId, BasicDigitalTwin.class);
    DigitalTwinUpdateRequestOptions optionsWithEtag = new DigitalTwinUpdateRequestOptions();
    optionsWithEtag.setIfMatch(responseWithHeaders.headers().eTag());
    // act
    // Add component at root level - conditional update with max overload
    UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility().appendAddComponentOperation(newComponentPath, componentProperties);
    digitalTwinClient.updateDigitalTwinWithResponse(deviceId, updateOperationUtility.getUpdateOperations(), optionsWithEtag);
    BasicDigitalTwin digitalTwin = digitalTwinClient.getDigitalTwinWithResponse(deviceId, BasicDigitalTwin.class).body();
    // assert
    assertEquals(E2ETestConstants.TEMPERATURE_CONTROLLER_MODEL_ID, digitalTwin.getMetadata().getModelId());
    assertTrue(digitalTwin.getCustomProperties().containsKey(newComponent));
}
Also used : UpdateOperationUtility(com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility) BasicDigitalTwin(com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin) DigitalTwinGetHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) IntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) DigitalTwinTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.DigitalTwinTest)

Example 3 with UpdateOperationUtility

use of com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility in project azure-iot-sdk-java by Azure.

the class DigitalTwinClientTests method updateDigitalTwin.

@Test
@StandardTierHubOnlyTest
public void updateDigitalTwin() throws IOException {
    // arrange
    String newProperty = "currentTemperature";
    String newPropertyPath = "/currentTemperature";
    Integer newPropertyValue = 35;
    // Property update callback
    TwinPropertyCallBack twinPropertyCallBack = (property, context) -> {
        Set<Property> properties = new HashSet<>();
        properties.add(property);
        try {
            deviceClient.sendReportedProperties(properties);
        } catch (IOException e) {
        }
    };
    // IotHub event callback
    IotHubEventCallback iotHubEventCallback = (responseStatus, callbackContext) -> {
    };
    // start device twin and setup handler for property updates in device
    deviceClient.startDeviceTwin(iotHubEventCallback, null, twinPropertyCallBack, null);
    Map<Property, Pair<TwinPropertyCallBack, Object>> desiredPropertyUpdateCallback = Collections.singletonMap(new Property(newProperty, null), new Pair<>(twinPropertyCallBack, null));
    deviceClient.subscribeToTwinDesiredProperties(desiredPropertyUpdateCallback);
    DigitalTwinUpdateRequestOptions optionsWithoutEtag = new DigitalTwinUpdateRequestOptions();
    optionsWithoutEtag.setIfMatch("*");
    // get digital twin and Etag before update
    ServiceResponseWithHeaders<BasicDigitalTwin, DigitalTwinGetHeaders> responseWithHeaders = digitalTwinClient.getDigitalTwinWithResponse(deviceId, BasicDigitalTwin.class);
    DigitalTwinUpdateRequestOptions optionsWithEtag = new DigitalTwinUpdateRequestOptions();
    optionsWithEtag.setIfMatch(responseWithHeaders.headers().eTag());
    // act
    // Add properties at root level - conditional update with max overload
    UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility().appendAddPropertyOperation(newPropertyPath, newPropertyValue);
    digitalTwinClient.updateDigitalTwinWithResponse(deviceId, updateOperationUtility.getUpdateOperations(), optionsWithEtag);
    BasicDigitalTwin digitalTwin = digitalTwinClient.getDigitalTwinWithResponse(deviceId, BasicDigitalTwin.class).body();
    // assert
    assertEquals(E2ETestConstants.THERMOSTAT_MODEL_ID, digitalTwin.getMetadata().getModelId());
    assertTrue(digitalTwin.getMetadata().getWriteableProperties().containsKey(newProperty));
    assertEquals(newPropertyValue, digitalTwin.getMetadata().getWriteableProperties().get(newProperty).getDesiredValue());
}
Also used : IotHubServiceSasToken(com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken) Device(com.microsoft.azure.sdk.iot.service.Device) SasTokenTools(tests.integration.com.microsoft.azure.sdk.iot.helpers.SasTokenTools) Arrays(java.util.Arrays) MultiplexingClient(com.microsoft.azure.sdk.iot.device.MultiplexingClient) ClientOptions(com.microsoft.azure.sdk.iot.device.ClientOptions) DigitalTwinClient(com.microsoft.azure.sdk.iot.service.digitaltwin.DigitalTwinClient) IotHubClientProtocol(com.microsoft.azure.sdk.iot.device.IotHubClientProtocol) URISyntaxException(java.net.URISyntaxException) ZonedDateTime(java.time.ZonedDateTime) DigitalTwinClientOptions(com.microsoft.azure.sdk.iot.service.digitaltwin.DigitalTwinClientOptions) MultiplexingClientException(com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException) ProxyOptions(com.microsoft.azure.sdk.iot.service.ProxyOptions) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) DigitalTwinCommandResponse(com.microsoft.azure.sdk.iot.service.digitaltwin.models.DigitalTwinCommandResponse) Proxy(java.net.Proxy) After(org.junit.After) Map(java.util.Map) DeviceClient(com.microsoft.azure.sdk.iot.device.DeviceClient) ZoneOffset(java.time.ZoneOffset) DefaultHttpProxyServer(org.littleshoot.proxy.impl.DefaultHttpProxyServer) Parameterized(org.junit.runners.Parameterized) AfterClass(org.junit.AfterClass) Tools(tests.integration.com.microsoft.azure.sdk.iot.helpers.Tools) DigitalTwinTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.DigitalTwinTest) AzureSasCredential(com.azure.core.credential.AzureSasCredential) DeviceMethodCallback(com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodCallback) TwinPropertyCallBack(com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertyCallBack) ServiceResponseWithHeaders(com.microsoft.rest.ServiceResponseWithHeaders) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) DigitalTwinInvokeCommandHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.models.DigitalTwinInvokeCommandHeaders) InetSocketAddress(java.net.InetSocketAddress) StandardCharsets(java.nio.charset.StandardCharsets) UpdateOperationUtility(com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TokenCredential(com.azure.core.credential.TokenCredential) DigitalTwinInvokeCommandRequestOptions(com.microsoft.azure.sdk.iot.service.digitaltwin.models.DigitalTwinInvokeCommandRequestOptions) HttpProxyServer(org.littleshoot.proxy.HttpProxyServer) DeviceMethodData(com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodData) BeforeClass(org.junit.BeforeClass) RegistryManagerOptions(com.microsoft.azure.sdk.iot.service.RegistryManagerOptions) RunWith(org.junit.runner.RunWith) IntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.IntegrationTest) RegistryManager(com.microsoft.azure.sdk.iot.service.RegistryManager) DigitalTwinGetHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders) DigitalTwinUpdateRequestOptions(com.microsoft.azure.sdk.iot.service.digitaltwin.models.DigitalTwinUpdateRequestOptions) ArrayList(java.util.ArrayList) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) HashSet(java.util.HashSet) RestException(com.microsoft.rest.RestException) Timeout(org.junit.rules.Timeout) IotHubEventCallback(com.microsoft.azure.sdk.iot.device.IotHubEventCallback) Pair(com.microsoft.azure.sdk.iot.device.DeviceTwin.Pair) BasicDigitalTwin(com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin) Before(org.junit.Before) Property(com.microsoft.azure.sdk.iot.device.DeviceTwin.Property) TestCase.fail(junit.framework.TestCase.fail) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) E2ETestConstants(tests.integration.com.microsoft.azure.sdk.iot.digitaltwin.helpers.E2ETestConstants) AuthenticationType(com.microsoft.azure.sdk.iot.service.auth.AuthenticationType) Rule(org.junit.Rule) Ignore(org.junit.Ignore) IotHubConnectionStringBuilder(com.microsoft.azure.sdk.iot.service.IotHubConnectionStringBuilder) DateTimeFormatter(java.time.format.DateTimeFormatter) IotHubException(com.microsoft.azure.sdk.iot.service.exceptions.IotHubException) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) IotHubEventCallback(com.microsoft.azure.sdk.iot.device.IotHubEventCallback) UpdateOperationUtility(com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility) Set(java.util.Set) HashSet(java.util.HashSet) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) IOException(java.io.IOException) DigitalTwinUpdateRequestOptions(com.microsoft.azure.sdk.iot.service.digitaltwin.models.DigitalTwinUpdateRequestOptions) BasicDigitalTwin(com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin) DigitalTwinGetHeaders(com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders) TwinPropertyCallBack(com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertyCallBack) Property(com.microsoft.azure.sdk.iot.device.DeviceTwin.Property) Pair(com.microsoft.azure.sdk.iot.device.DeviceTwin.Pair) 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 4 with UpdateOperationUtility

use of com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility in project azure-iot-sdk-java by Azure.

the class Thermostat method UpdateDigitalTwin.

private static void UpdateDigitalTwin() throws InterruptedException {
    CountDownLatch latch1 = new CountDownLatch(1);
    // Update the digital twin.
    UpdateOperationUtility updateOperationUtility = new UpdateOperationUtility();
    // Add a new property at root level.
    String newProperty = "currentTemperature";
    String existingProperty = "targetTemperature";
    System.out.println("--------------------------------------------------------------------------------------------");
    System.out.println("Add properties at root level - " + newProperty + " and " + existingProperty);
    System.out.println("--------------------------------------------------------------------------------------------");
    updateOperationUtility.appendAddPropertyOperation("/" + newProperty, 35);
    updateOperationUtility.appendAddPropertyOperation("/" + existingProperty, 35);
    asyncClient.updateDigitalTwin(digitalTwinid, updateOperationUtility.getUpdateOperations()).subscribe(getResponse -> {
        System.out.println("Updated Digital Twin");
        latch1.countDown();
    }, error -> {
        System.out.println("Update Digital Twin failed: " + error);
        latch1.countDown();
    });
    latch1.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    GetDigitalTwin();
    // Replace an existing property at root level.
    CountDownLatch latch2 = new CountDownLatch(1);
    System.out.println("--------------------------------------------------------------------------------------------");
    System.out.println("Replace an existing property at root level " + existingProperty);
    System.out.println("--------------------------------------------------------------------------------------------");
    updateOperationUtility.appendReplacePropertyOperation("/targetTemperature", 50);
    asyncClient.updateDigitalTwin(digitalTwinid, updateOperationUtility.getUpdateOperations()).subscribe(getResponse -> {
        System.out.println("Updated Digital Twin");
        latch2.countDown();
    }, error -> {
        System.out.println("Update Digital Twin failed: " + error);
        latch2.countDown();
    });
    latch2.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    GetDigitalTwin();
    // Remove the new property at root level.
    CountDownLatch latch3 = new CountDownLatch(1);
    System.out.println("--------------------------------------------------------------------------------------------");
    System.out.println("Remove the new property at root level " + newProperty);
    System.out.println("--------------------------------------------------------------------------------------------");
    updateOperationUtility.appendRemovePropertyOperation("/currentTemperature");
    asyncClient.updateDigitalTwin(digitalTwinid, updateOperationUtility.getUpdateOperations()).subscribe(getResponse -> {
        System.out.println("Updated Digital Twin");
        latch3.countDown();
    }, error -> {
        System.out.println("Update Digital Twin failed: " + error);
        latch3.countDown();
    });
    latch3.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    GetDigitalTwin();
}
Also used : UpdateOperationUtility(com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

UpdateOperationUtility (com.microsoft.azure.sdk.iot.service.digitaltwin.UpdateOperationUtility)4 DigitalTwinGetHeaders (com.microsoft.azure.sdk.iot.service.digitaltwin.customized.DigitalTwinGetHeaders)3 BasicDigitalTwin (com.microsoft.azure.sdk.iot.service.digitaltwin.serialization.BasicDigitalTwin)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 AzureSasCredential (com.azure.core.credential.AzureSasCredential)1 TokenCredential (com.azure.core.credential.TokenCredential)1 JsonObject (com.google.gson.JsonObject)1 ClientOptions (com.microsoft.azure.sdk.iot.device.ClientOptions)1 DeviceClient (com.microsoft.azure.sdk.iot.device.DeviceClient)1 DeviceMethodCallback (com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodCallback)1 DeviceMethodData (com.microsoft.azure.sdk.iot.device.DeviceTwin.DeviceMethodData)1 Pair (com.microsoft.azure.sdk.iot.device.DeviceTwin.Pair)1 Property (com.microsoft.azure.sdk.iot.device.DeviceTwin.Property)1 TwinPropertyCallBack (com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertyCallBack)1 IotHubClientProtocol (com.microsoft.azure.sdk.iot.device.IotHubClientProtocol)1 IotHubEventCallback (com.microsoft.azure.sdk.iot.device.IotHubEventCallback)1 MultiplexingClient (com.microsoft.azure.sdk.iot.device.MultiplexingClient)1 MultiplexingClientException (com.microsoft.azure.sdk.iot.device.exceptions.MultiplexingClientException)1