private static string generatePatchForTurbine(PowerValues powerValues)
        {
            UpdateOperationsUtility uou = new UpdateOperationsUtility();

            uou.AppendReplaceOp("/powerObserved", powerValues.powerObserved);
            uou.AppendReplaceOp("/powerPM", powerValues.powerPM);
            uou.AppendReplaceOp("/powerDM", powerValues.powerDM);

            return(uou.Serialize());
        }
Пример #2
0
        public async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            // After this is deployed, you need to turn the Managed Identity Status to "On",
            // Grab Object Id of the function and assigned "Azure Digital Twins Owner (Preview)" role
            // to this function identity in order for this function to be authorized on ADT APIs.
            if (adtInstanceUrl == null)
            {
                log.LogError("Application setting \"ADT_SERVICE_URL\" not set");
            }

            try
            {
                //Authenticate with Digital Twins
                ManagedIdentityCredential cred   = new ManagedIdentityCredential("https://digitaltwins.azure.net");
                DigitalTwinsClient        client = new DigitalTwinsClient(new Uri(adtInstanceUrl),
                                                                          cred,
                                                                          new DigitalTwinsClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                });

                if (eventGridEvent != null && eventGridEvent.Data != null)
                {
                    log.LogInformation(eventGridEvent.Data.ToString());

                    JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
                    byte[]  body_byte     = System.Convert.FromBase64String(deviceMessage["body"].ToString());
                    var     body_value    = System.Text.ASCIIEncoding.ASCII.GetString(body_byte);
                    var     body_json     = (JObject)JsonConvert.DeserializeObject(body_value);

                    //log.LogInformation($"Body {body_json}");

                    log.LogInformation(deviceMessage.ToString());
                    string deviceId    = (string)deviceMessage["systemProperties"]["iothub-connection-device-id"];
                    var    temperature = body_json["temperature_hts221"];
                    var    humidity    = body_json["humidity"];

                    log.LogInformation($"Device:{deviceId} Temperature is:{temperature} Humidity is:{humidity}");

                    //Update twin using device temperature
                    var uou = new UpdateOperationsUtility();
                    uou.AppendReplaceOp("/Temperature", temperature.Value <double>());
                    uou.AppendReplaceOp("/HumidityLevel", humidity.Value <double>());
                    await client.UpdateDigitalTwinAsync(deviceId, uou.Serialize());
                }
            }
            catch (Exception e)
            {
                log.LogError($"Error in ingest function: {e.Message}");
            }
        }
        public static string GetRelationshipUpdatePayload(string propertyName, bool propertyValue)
        {
            var uou = new UpdateOperationsUtility();

            uou.AppendReplaceOp(propertyName, propertyValue);
            return(RemoveNewLines(uou.Serialize()));
        }
        public static string GetWifiComponentUpdatePayload()
        {
            var uou = new UpdateOperationsUtility();

            uou.AppendReplaceOp("/Network", "New Network");
            return(RemoveNewLines(uou.Serialize()));
        }
        public async void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            // After this is deployed, you need to turn the Managed Identity Status to "On",
            // Grab Object Id of the function and assigned "Azure Digital Twins Owner (Preview)" role
            // to this function identity in order for this function to be authorized on ADT APIs.

            //Authenticate with Digital Twins
            var credentials           = new DefaultAzureCredential();
            DigitalTwinsClient client = new DigitalTwinsClient(
                new Uri(adtServiceUrl), credentials, new DigitalTwinsClientOptions
            {
                Transport = new HttpClientTransport(httpClient)
            });

            log.LogInformation($"ADT service client connection created.");

            if (eventGridEvent != null && eventGridEvent.Data != null)
            {
                log.LogInformation(eventGridEvent.Data.ToString());

                // Reading deviceId and temperature for IoT Hub JSON
                JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
                string  deviceId      = (string)deviceMessage["systemProperties"]["iothub-connection-device-id"];
                var     temperature   = deviceMessage["body"]["Temperature"];

                log.LogInformation($"Device:{deviceId} Temperature is:{temperature}");

                //Update twin using device temperature
                var uou = new UpdateOperationsUtility();
                uou.AppendReplaceOp("/Temperature", temperature.Value <double>());
                await client.UpdateDigitalTwinAsync(deviceId, uou.Serialize());
            }
        }
        public static string GetRoomTwinUpdatePayload()
        {
            var uou = new UpdateOperationsUtility();

            uou.AppendAddOp("/Humidity", 30);
            uou.AppendReplaceOp("/Temperature", 70);
            uou.AppendRemoveOp("/EmployeeId");
            return(RemoveNewLines(uou.Serialize()));
        }
        private static string generatePatchForSensor(WTInfo info, TemperatureValues tempValues)
        {
            UpdateOperationsUtility uou = new UpdateOperationsUtility();

            uou.AppendReplaceOp("/blade1PitchAngle", info.Blade1PitchPosition);
            uou.AppendReplaceOp("/blade2PitchAngle", info.Blade2PitchPosition);
            uou.AppendReplaceOp("/blade3PitchAngle", info.Blade3PitchPosition);
            uou.AppendReplaceOp("/yawPosition", info.YawPosition);
            uou.AppendReplaceOp("/windDirection", info.WindDir);
            uou.AppendReplaceOp("/windSpeed", info.WindSpeed);
            uou.AppendReplaceOp("/temperatureNacelle", tempValues.nacelle);
            uou.AppendReplaceOp("/temperatureGenerator", tempValues.generator);
            uou.AppendReplaceOp("/temperatureGearBox", tempValues.gearBox);

            return(uou.Serialize());
        }
        public void UpdateOperationsUtility_BuildAdd()
        {
            // arrange

            const string addOp     = "add";
            const string replaceOp = "replace";
            const string removeOp  = "remove";

            const string addPath      = "/addComponentPath123";
            const string addValue     = "value123";
            const string replacePath  = "/replaceComponentPath123";
            const string replaceValue = "value456";
            const string removePath   = "/removeComponentPath123";

            var dtUpdateUtility = new UpdateOperationsUtility();

            dtUpdateUtility.AppendAddOp(addPath, addValue);
            dtUpdateUtility.AppendReplaceOp(replacePath, replaceValue);
            dtUpdateUtility.AppendRemoveOp(removePath);

            // act
            string actual = dtUpdateUtility.Serialize();

            // assert

            JsonDocument parsed = JsonDocument.Parse(actual);

            parsed.RootElement.ValueKind.Should().Be(JsonValueKind.Array, "operations should be nested in an array");
            parsed.RootElement.GetArrayLength().Should().Be(3, "three operations were included");

            JsonElement addElement = parsed.RootElement[0];

            addElement.GetProperty("op").GetString().Should().Be(addOp);
            addElement.GetProperty("path").GetString().Should().Be(addPath);
            addElement.GetProperty("value").GetString().Should().Be(addValue);

            JsonElement replaceElement = parsed.RootElement[1];

            replaceElement.GetProperty("op").GetString().Should().Be(replaceOp);
            replaceElement.GetProperty("path").GetString().Should().Be(replacePath);
            replaceElement.GetProperty("value").GetString().Should().Be(replaceValue);

            JsonElement removeElement = parsed.RootElement[2];

            removeElement.GetProperty("op").GetString().Should().Be(removeOp);
            removeElement.GetProperty("path").GetString().Should().Be(removePath);
            removeElement.TryGetProperty("value", out _).Should().BeFalse();
        }
        public static async Task UpdateTwinPropertyAsync(DigitalTwinsClient client, string twinId, string propertyPath, object value, ILogger log)
        {
            // If the twin does not exist, this will log an error
            try
            {
                var uou = new UpdateOperationsUtility();
                uou.AppendReplaceOp(propertyPath, value);
                string patchPayload = uou.Serialize();
                log.LogInformation($"UpdateTwinPropertyAsync sending {patchPayload}");

                await client.UpdateDigitalTwinAsync(twinId, patchPayload);
            }
            catch (RequestFailedException exc)
            {
                log.LogInformation($"*** Error:{exc.Status}/{exc.Message}");
            }
        }
Пример #10
0
        private async Task UpdateDigitalTwinProperty(DigitalTwinsClient client, string deviceId, JToken body, string propertyName)
        {
            var propertyToken = body[propertyName];

            if (propertyToken != null)
            {
                if (Constants.Telemetries.Contains(propertyName.ToUpper()))
                {
                    var data = new Dictionary <string, double>();
                    data.Add(propertyName, propertyToken.Value <double>());
                    await client.PublishTelemetryAsync(deviceId, JsonConvert.SerializeObject(data));
                }
                else
                {
                    // Update twin using device property
                    var uou = new UpdateOperationsUtility();
                    uou.AppendReplaceOp($"/{propertyName}", propertyToken.Value <double>());
                    await client.UpdateDigitalTwinAsync(deviceId, uou.Serialize());
                }
            }
        }
        /// <summary>
        /// Creates a digital twin with Component and upates Component
        /// </summary>
        public async Task RunSamplesAsync()
        {
            PrintHeader("COMPONENT SAMPLE");

            // For the purpose of this example we will create temporary models using a random model Ids.
            // We have to make sure these model Ids are unique within the DT instance.

            string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, DigitalTwinsClient).ConfigureAwait(false);

            string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, DigitalTwinsClient).ConfigureAwait(false);

            string dtId1 = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);

            string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
                                              .Replace(SamplesConstants.ComponentId, componentModelId);

            string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
                                     .Replace(SamplesConstants.ModelId, modelId)
                                     .Replace(SamplesConstants.ComponentId, componentModelId);

            // Then we create models
            Response <IReadOnlyList <Models.ModelData> > createModelsResponse = await DigitalTwinsClient
                                                                                .CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload })
                                                                                .ConfigureAwait(false);

            Console.WriteLine($"Successfully created models Ids {componentModelId} and {modelId} with response {createModelsResponse.GetRawResponse().Status}.");

            #region Snippet:DigitalTwinsSampleCreateBasicTwin

            // Create digital twin with Component payload using the BasicDigitalTwin serialization helper

            var basicDigitalTwin = new BasicDigitalTwin
            {
                Id = dtId1
            };
            basicDigitalTwin.Metadata.ModelId = modelId;
            basicDigitalTwin.CustomProperties.Add("Prop1", "Value1");
            basicDigitalTwin.CustomProperties.Add("Prop2", "Value2");

            var componentMetadata = new ModelProperties();
            componentMetadata.Metadata.ModelId = componentModelId;
            componentMetadata.CustomProperties.Add("ComponentProp1", "ComponentValue1");
            componentMetadata.CustomProperties.Add("ComponentProp2", "ComponentValue2");

            basicDigitalTwin.CustomProperties.Add("Component1", componentMetadata);

            string dt1Payload = JsonSerializer.Serialize(basicDigitalTwin);

            Response <string> createDt1Response = await DigitalTwinsClient.CreateDigitalTwinAsync(dtId1, dt1Payload).ConfigureAwait(false);

            Console.WriteLine($"Created digital twin {dtId1} with response {createDt1Response.GetRawResponse().Status}.");

            #endregion Snippet:DigitalTwinsSampleCreateBasicTwin

            #region Snippet:DigitalTwinsSampleCreateCustomTwin

            string dtId2 = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);

            var customDigitalTwin = new CustomDigitalTwin
            {
                Id       = dtId2,
                Metadata = new CustomDigitalTwinMetadata {
                    ModelId = modelId
                },
                Prop1      = "Prop1 val",
                Prop2      = "Prop2 val",
                Component1 = new Component1
                {
                    Metadata = new Component1Metadata {
                        ModelId = componentModelId
                    },
                    ComponentProp1 = "Component prop1 val",
                    ComponentProp2 = "Component prop2 val",
                }
            };
            string dt2Payload = JsonSerializer.Serialize(customDigitalTwin);

            Response <string> createDt2Response = await DigitalTwinsClient.CreateDigitalTwinAsync(dtId2, dt2Payload).ConfigureAwait(false);

            Console.WriteLine($"Created digital twin {dtId2} with response {createDt2Response.GetRawResponse().Status}.");

            #endregion Snippet:DigitalTwinsSampleCreateCustomTwin

            #region Snippet:DigitalTwinsSampleUpdateComponent

            // Update Component1 by replacing the property ComponentProp1 value
            var componentUpdateUtility = new UpdateOperationsUtility();
            componentUpdateUtility.AppendReplaceOp("/ComponentProp1", "Some new value");
            string updatePayload = componentUpdateUtility.Serialize();

            Response <string> response = await DigitalTwinsClient.UpdateComponentAsync(dtId1, "Component1", updatePayload);

            Console.WriteLine($"Updated component for digital twin {dtId1}. Update response status: {response.GetRawResponse().Status}");

            #endregion Snippet:DigitalTwinsSampleUpdateComponent

            // Get Component

            #region Snippet:DigitalTwinsSampleGetComponent

            response = await DigitalTwinsClient.GetComponentAsync(dtId1, SamplesConstants.ComponentPath).ConfigureAwait(false);

            Console.WriteLine($"Get component for digital twin: \n{response.Value}. Get response status: {response.GetRawResponse().Status}");

            #endregion Snippet:DigitalTwinsSampleGetComponent

            // Clean up

            try
            {
                await DigitalTwinsClient.DeleteDigitalTwinAsync(dtId1).ConfigureAwait(false);

                await DigitalTwinsClient.DeleteDigitalTwinAsync(dtId2).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete digital twin due to {ex}");
            }

            try
            {
                await DigitalTwinsClient.DeleteModelAsync(modelId).ConfigureAwait(false);

                await DigitalTwinsClient.DeleteModelAsync(componentModelId).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete models due to {ex}");
            }
        }
Пример #12
0
        /// <summary>
        /// Creates a digital twin with Component and upates Component
        /// </summary>
        public async Task RunSamplesAsync(DigitalTwinsClient client)
        {
            PrintHeader("COMPONENT SAMPLE");

            // For the purpose of this example we will create temporary models using a random model Ids.
            // We have to make sure these model Ids are unique within the DT instance.

            string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, client);

            string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, client);

            string basicDtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, client);

            string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
                                              .Replace(SamplesConstants.ComponentId, componentModelId);

            string newModelPayload = SamplesConstants.TemporaryModelWithComponentPayload
                                     .Replace(SamplesConstants.ModelId, modelId)
                                     .Replace(SamplesConstants.ComponentId, componentModelId);

            // Then we create models
            Response <IReadOnlyList <Models.ModelData> > createModelsResponse = await client.CreateModelsAsync(
                new[]
            {
                newComponentModelPayload,
                newModelPayload
            });

            Console.WriteLine($"Created models with Ids {componentModelId} and {modelId}. Response status: {createModelsResponse.GetRawResponse().Status}.");

            #region Snippet:DigitalTwinsSampleCreateBasicTwin

            // Create digital twin with component payload using the BasicDigitalTwin serialization helper

            var basicTwin = new BasicDigitalTwin
            {
                Id = basicDtId,
                // model Id of digital twin
                Metadata         = { ModelId = modelId },
                CustomProperties =
                {
                    // digital twin properties
                    { "Prop1",          "Value1"            },
                    { "Prop2",                          987 },
                    // component
                    {
                        "Component1",
                        new ModelProperties
                        {
                            // component properties
                            CustomProperties =
                            {
                                { "ComponentProp1", "Component value 1" },
                                { "ComponentProp2",                 123 },
                            },
                        }
                    },
                },
            };

            string basicDtPayload = JsonSerializer.Serialize(basicTwin);

            Response <string> createBasicDtResponse = await client.CreateDigitalTwinAsync(basicDtId, basicDtPayload);

            Console.WriteLine($"Created digital twin with Id {basicDtId}. Response status: {createBasicDtResponse.GetRawResponse().Status}.");

            #endregion Snippet:DigitalTwinsSampleCreateBasicTwin

            // You can also get a digital twin and deserialize it into a BasicDigitalTwin.
            // It works well for basic stuff, but as you can see it gets more difficult when delving into
            // more complex properties, like components.

            #region Snippet:DigitalTwinsSampleGetBasicDigitalTwin

            Response <string> getBasicDtResponse = await client.GetDigitalTwinAsync(basicDtId);

            if (getBasicDtResponse.GetRawResponse().Status == (int)HttpStatusCode.OK)
            {
                BasicDigitalTwin basicDt = JsonSerializer.Deserialize <BasicDigitalTwin>(getBasicDtResponse.Value);

                // Must cast Component1 as a JsonElement and get its raw text in order to deserialize it as a dictionary
                string component1RawText = ((JsonElement)basicDt.CustomProperties["Component1"]).GetRawText();
                IDictionary <string, object> component1 = JsonSerializer.Deserialize <IDictionary <string, object> >(component1RawText);

                Console.WriteLine($"Retrieved and deserialized digital twin {basicDt.Id}:\n\t" +
                                  $"ETag: {basicDt.ETag}\n\t" +
                                  $"Prop1: {basicDt.CustomProperties["Prop1"]}\n\t" +
                                  $"Prop2: {basicDt.CustomProperties["Prop2"]}\n\t" +
                                  $"ComponentProp1: {component1["ComponentProp1"]}\n\t" +
                                  $"ComponentProp2: {component1["ComponentProp2"]}");
            }

            #endregion Snippet:DigitalTwinsSampleGetBasicDigitalTwin

            string customDtId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, client);

            // Alternatively, you can create your own custom data types to serialize and deserialize your digital twins.
            // By specifying your properties and types directly, it requires less code or knowledge of the type for
            // interaction.

            #region Snippet:DigitalTwinsSampleCreateCustomTwin

            var customTwin = new CustomDigitalTwin
            {
                Id         = customDtId,
                Metadata   = { ModelId = modelId },
                Prop1      = "Prop1 val",
                Prop2      = 987,
                Component1 = new Component1
                {
                    ComponentProp1 = "Component prop1 val",
                    ComponentProp2 = 123,
                }
            };
            string dt2Payload = JsonSerializer.Serialize(customTwin);

            Response <string> createCustomDtResponse = await client.CreateDigitalTwinAsync(customDtId, dt2Payload);

            Console.WriteLine($"Created digital twin with Id {customDtId}. Response status: {createCustomDtResponse.GetRawResponse().Status}.");

            #endregion Snippet:DigitalTwinsSampleCreateCustomTwin

            // Getting and deserializing a digital twin into a custom data type is extremely easy.
            // Custom types provide the best possible experience.

            #region Snippet:DigitalTwinsSampleGetCustomDigitalTwin

            Response <string> getCustomDtResponse = await client.GetDigitalTwinAsync(customDtId);

            if (getCustomDtResponse.GetRawResponse().Status == (int)HttpStatusCode.OK)
            {
                CustomDigitalTwin customDt = JsonSerializer.Deserialize <CustomDigitalTwin>(getCustomDtResponse.Value);
                Console.WriteLine($"Retrieved and deserialized digital twin {customDt.Id}:\n\t" +
                                  $"ETag: {customDt.ETag}\n\t" +
                                  $"Prop1: {customDt.Prop1}\n\t" +
                                  $"Prop2: {customDt.Prop2}\n\t" +
                                  $"ComponentProp1: {customDt.Component1.ComponentProp1}\n\t" +
                                  $"ComponentProp2: {customDt.Component1.ComponentProp2}");
            }

            #endregion Snippet:DigitalTwinsSampleGetCustomDigitalTwin

            #region Snippet:DigitalTwinsSampleUpdateComponent

            // Update Component1 by replacing the property ComponentProp1 value
            var componentUpdateUtility = new UpdateOperationsUtility();
            componentUpdateUtility.AppendReplaceOp("/ComponentProp1", "Some new value");
            string updatePayload = componentUpdateUtility.Serialize();

            Response <string> response = await client.UpdateComponentAsync(basicDtId, "Component1", updatePayload);

            Console.WriteLine($"Updated component for digital twin with Id {basicDtId}. Response status: {response.GetRawResponse().Status}");

            #endregion Snippet:DigitalTwinsSampleUpdateComponent

            // Get Component

            #region Snippet:DigitalTwinsSampleGetComponent

            response = await client.GetComponentAsync(basicDtId, SamplesConstants.ComponentPath);

            Console.WriteLine($"Retrieved component for digital twin with Id {basicDtId}. Response status: {response.GetRawResponse().Status}");

            #endregion Snippet:DigitalTwinsSampleGetComponent

            // Clean up

            try
            {
                await client.DeleteDigitalTwinAsync(basicDtId);

                await client.DeleteDigitalTwinAsync(customDtId);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete digital twin due to {ex}");
            }

            try
            {
                await client.DeleteModelAsync(modelId);

                await client.DeleteModelAsync(componentModelId);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete models due to {ex}");
            }
        }
Пример #13
0
        /// <summary>
        /// Creates a digital twin with Component and upates Component
        /// </summary>
        public async Task RunSamplesAsync()
        {
            PrintHeader("COMPONENT SAMPLE");

            // For the purpose of this example we will create temporary models using a random model Ids.
            // We have to make sure these model Ids are unique within the DT instance.

            string componentModelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryComponentModelPrefix, DigitalTwinsClient).ConfigureAwait(false);

            string modelId = await GetUniqueModelIdAsync(SamplesConstants.TemporaryModelPrefix, DigitalTwinsClient).ConfigureAwait(false);

            string twinId = await GetUniqueTwinIdAsync(SamplesConstants.TemporaryTwinPrefix, DigitalTwinsClient).ConfigureAwait(false);

            string newComponentModelPayload = SamplesConstants.TemporaryComponentModelPayload
                                              .Replace(SamplesConstants.ComponentId, componentModelId);

            string newModelPayload = SamplesConstants.TemporaryModelPayload
                                     .Replace(SamplesConstants.ModelId, modelId)
                                     .Replace(SamplesConstants.ComponentId, componentModelId);

            // Then we create models
            await DigitalTwinsClient.CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload }).ConfigureAwait(false);

            Console.WriteLine($"Successfully created models with Ids: {componentModelId}, {modelId}");

            // Create digital twin with Component payload
            string twinPayload = SamplesConstants.TemporaryTwinPayload
                                 .Replace(SamplesConstants.ModelId, modelId)
                                 .Replace(SamplesConstants.ComponentId, componentModelId);

            await DigitalTwinsClient.CreateDigitalTwinAsync(twinId, twinPayload).ConfigureAwait(false);

            Console.WriteLine($"Created digital twin {twinId}.");

            #region Snippet:DigitalTwinSampleUpdateComponent

            // Update Component with replacing property value
            string propertyPath = "/ComponentProp1";
            string propValue    = "New Value";

            var componentUpdateUtility = new UpdateOperationsUtility();
            componentUpdateUtility.AppendReplaceOp(propertyPath, propValue);

            Response <string> response = await DigitalTwinsClient.UpdateComponentAsync(twinId, SamplesConstants.ComponentPath, componentUpdateUtility.Serialize());

            #endregion Snippet:DigitalTwinSampleUpdateComponent

            Console.WriteLine($"Updated component for digital twin {twinId}. Update response status: {response.GetRawResponse().Status}");

            // Get Component

            #region Snippet:DigitalTwinSampleGetComponent

            response = await DigitalTwinsClient.GetComponentAsync(twinId, SamplesConstants.ComponentPath).ConfigureAwait(false);

            #endregion Snippet:DigitalTwinSampleGetComponent

            Console.WriteLine($"Get component for digital twin: \n{response.Value}. Get response status: {response.GetRawResponse().Status}");

            // Now delete a Twin
            await DigitalTwinsClient.DeleteDigitalTwinAsync(twinId).ConfigureAwait(false);

            // Delete models
            try
            {
                await DigitalTwinsClient.DeleteModelAsync(modelId).ConfigureAwait(false);

                await DigitalTwinsClient.DeleteModelAsync(componentModelId).ConfigureAwait(false);
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Failed to delete models due to {ex}");
            }
        }
Пример #14
0
        public async static void Run([EventGridTrigger] EventGridEvent ev, ILogger log)
        {
            if (adtInstanceUrl == null)
            {
                log.LogError("Application setting \"ADT_SERVICE_URL\" not set");
            }
            try
            {
                // Authenticate with Digital Twins

                ManagedIdentityCredential cred   = new ManagedIdentityCredential("https://digitaltwins.azure.net");
                DigitalTwinsClient        client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, new DigitalTwinsClientOptions {
                    Transport = new HttpClientTransport(httpClient)
                });
                log.LogInformation("ADT service client connection created.");

                if (ev != null && ev.Data != null)
                {
                    // Extract JSON body from event

                    JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(ev.Data.ToString());
                    byte[]  data          = System.Convert.FromBase64String((string)deviceMessage ["body"]);
                    JObject body          = (JObject)JsonConvert.DeserializeObject(System.Text.ASCIIEncoding.ASCII.GetString(data));

                    // Extract device twin id from message and digital twin id from system properties

                    string deviceId = (string)deviceMessage ["systemProperties"]["iothub-connection-device-id"];
                    string twinId   = (string)body ["twin_id"];
                    log.LogInformation($"Routing from device_id: {deviceId}");
                    log.LogInformation($"Routing to twin_id: {twinId}");

                    // Iterate set of readings and create change set for twin

                    JObject readings = (JObject)body ["readings"];
                    var     uou      = new UpdateOperationsUtility();
                    foreach (var reading in readings)
                    {
                        string type  = (string)reading.Value ["type"];
                        string key   = (string)reading.Key;
                        var    value = reading.Value ["value"];

                        log.LogInformation($"key: {key} value: {value} type: {type}");

                        switch (type.ToLower())
                        {
                        case "bool":
                            uou.AppendReplaceOp($"/{key}", value.Value <bool>());
                            break;

                        case "int8":
                            uou.AppendReplaceOp($"/{key}", value.Value <SByte>());
                            break;

                        case "int16":
                            uou.AppendReplaceOp($"/{key}", value.Value <Int16>());
                            break;

                        case "int32":
                            uou.AppendReplaceOp($"/{key}", value.Value <Int32>());
                            break;

                        case "uint8":
                            uou.AppendReplaceOp($"/{key}", value.Value <Byte>());
                            break;

                        case "uint16":
                            uou.AppendReplaceOp($"/{key}", value.Value <UInt16>());
                            break;

                        case "float32":
                            uou.AppendReplaceOp($"/{key}", value.Value <float>());
                            break;

                        case "float64":
                            uou.AppendReplaceOp($"/{key}", value.Value <double>());
                            break;

                        default:
                            log.LogWarning($"{key} using {type} type isn't supported");
                            break;
                        }
                    }
                    // Update digital twin
                    string digitalTwinPatch = uou.Serialize();
                    log.LogInformation($"Updating twin: {twinId} with patch {digitalTwinPatch}");
                    await client.UpdateDigitalTwinAsync(twinId, digitalTwinPatch);
                }
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
            }
        }