コード例 #1
0
 public async Task <string> GetUniqueModelIdAsync(DigitalTwinsClient dtClient, string baseName)
 {
     return(await GetUniqueIdAsync(baseName, (modelId) => dtClient.GetModelAsync(modelId)).ConfigureAwait(false));
 }
コード例 #2
0
        public async static void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            try
            {
                log.LogInformation(eventGridEvent.Topic.ToString());
                log.LogInformation(eventGridEvent.Subject.ToString());
                log.LogInformation(eventGridEvent.Data.ToString());

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

                JObject digitalTwin  = JObject.Parse(client.GetDigitalTwin(eventGridEvent.Subject.ToString()));
                string  deviceTwinId = digitalTwin["device_twin_id"].ToString();

                ServiceClient service         = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
                JObject       digitalTwinData = JObject.Parse(eventGridEvent.Data.ToString());

                string digitalTwinModelId = (string)digitalTwinData["data"]["modelId"].ToString();

                ModelData digitalTwinModelData = await client.GetModelAsync(digitalTwinModelId);

                JObject digitalTwinModel         = JObject.Parse(digitalTwinModelData.Model);
                JArray  digitalTwinModelContents = (JArray)digitalTwinModel["contents"];

                JObject data  = (JObject)digitalTwinData["data"];
                JArray  patch = (JArray)digitalTwinData["data"]["patch"];

                JObject reformattedData = new JObject();
                reformattedData.Add("device", eventGridEvent.Subject.ToString());

                JObject values = new JObject();
                foreach (JObject item in patch)
                {
                    string name = item["path"].ToString().Replace("/", "");
                    foreach (JObject modelItem in digitalTwinModelContents)
                    {
                        if (modelItem["@type"].ToString().Equals("Property") && modelItem["name"].ToString().Equals(name))
                        {
                            JToken writable = modelItem.SelectToken("writable");
                            if (writable != null)
                            {
                                if (writable.ToObject <bool>() == true)
                                {
                                    values.Add(new JProperty(name, item["value"]));
                                }
                            }
                            break;
                        }
                    }
                }

                if (values.Count > 0)
                {
                    reformattedData.Add("values", values);

                    log.LogInformation("Sending IOTHub device {0} payload {1}:", deviceTwinId, reformattedData.ToString());

                    var methodInvocation = new CloudToDeviceMethod("publish")
                    {
                        ResponseTimeout = TimeSpan.FromSeconds(30)
                    };
                    methodInvocation.SetPayloadJson(reformattedData.ToString());

                    var response = await service.InvokeDeviceMethodAsync(deviceTwinId, methodInvocation);

                    log.LogInformation("Response status: {0}, payload:", response.Status, response.GetPayloadAsJson());
                }
                else
                {
                    log.LogInformation("No writable values found that could sent to IOTHub");
                }
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
            }
        }
コード例 #3
0
 internal static async Task <string> GetUniqueModelIdAsync(string baseName, DigitalTwinsClient client)
 {
     return(await GetUniqueIdAsync(baseName, (modelId) => client.GetModelAsync(modelId)));
 }
コード例 #4
0
        /// <summary>
        /// Creates a new model with a random Id
        /// Decommission the newly created model and check for success
        /// </summary>
        public async Task RunSamplesAsync(DigitalTwinsClient client)
        {
            PrintHeader("MODEL LIFECYCLE SAMPLE");

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

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

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

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

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

            // Then we create the model

            try
            {
                #region Snippet:DigitalTwinsSampleCreateModels

                await client.CreateModelsAsync(new[] { newComponentModelPayload, newModelPayload });

                Console.WriteLine($"Created models '{componentModelId}' and '{sampleModelId}'.");

                #endregion Snippet:DigitalTwinsSampleCreateModels
            }
            catch (RequestFailedException ex) when(ex.Status == (int)HttpStatusCode.Conflict)
            {
                Console.WriteLine($"One or more models already existed.");
            }
            catch (Exception ex)
            {
                FatalError($"Failed to create models due to:\n{ex}");
            }

            // Get Model
            try
            {
                #region Snippet:DigitalTwinsSampleGetModel

                Response <ModelData> sampleModelResponse = await client.GetModelAsync(sampleModelId);

                Console.WriteLine($"Retrieved model '{sampleModelResponse.Value.Id}'.");

                #endregion Snippet:DigitalTwinsSampleGetModel
            }
            catch (Exception ex)
            {
                FatalError($"Failed to get a model due to:\n{ex}");
            }

            // Now we decommission the model

            #region Snippet:DigitalTwinsSampleDecommisionModel

            try
            {
                await client.DecommissionModelAsync(sampleModelId);

                Console.WriteLine($"Decommissioned model '{sampleModelId}'.");
            }
            catch (RequestFailedException ex)
            {
                FatalError($"Failed to decommision model '{sampleModelId}' due to:\n{ex}");
            }

            #endregion Snippet:DigitalTwinsSampleDecommisionModel

            // Now delete created model

            #region Snippet:DigitalTwinsSampleDeleteModel

            try
            {
                await client.DeleteModelAsync(sampleModelId);

                Console.WriteLine($"Deleted model '{sampleModelId}'.");
            }
            catch (Exception ex)
            {
                FatalError($"Failed to delete model '{sampleModelId}' due to:\n{ex}");
            }

            #endregion Snippet:DigitalTwinsSampleDeleteModel
        }