Ejemplo n.º 1
0
        public static async void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            if (adtServiceUrl == null)
            {
                log.LogError("Application setting \"ADT_SERVICE_URL\" not set");
                return;
            }

            DefaultAzureCredential credentials = new DefaultAzureCredential();
            DigitalTwinsClient     dtClient    = new DigitalTwinsClient(new Uri(adtServiceUrl), credentials, new DigitalTwinsClientOptions {
                Transport = new HttpClientTransport(httpClient)
            });

            JObject payload = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());

            if (payload.ContainsKey("body"))
            {
                JObject payloadBody = (JObject)payload["body"];

                if (payloadBody.ContainsKey("format") && ((string)payloadBody["format"]).StartsWith("rec3.2"))
                {
                    RecEdgeMessage recMessage = JsonConvert.DeserializeObject <RecEdgeMessage>(payloadBody.ToString());
                    foreach (Observation observation in recMessage.observations)
                    {
                        Uri    sensorId = observation.sensorId;
                        string twinId   = sensorId.AbsolutePath.TrimStart('/').Replace(":", "");

                        var updateTwinData = new JsonPatchDocument();
                        if (observation.numericValue.HasValue)
                        {
                            updateTwinData.AppendAdd("/lastValue", observation.numericValue.Value);
                        }
                        else if (observation.booleanValue.HasValue)
                        {
                            updateTwinData.AppendAdd("/lastValue", observation.booleanValue.Value);
                        }
                        else
                        {
                            updateTwinData.AppendAdd("/lastValue", observation.stringValue);
                        }

                        try {
                            log.LogInformation($"Updating twin '{twinId}' with operation '{updateTwinData.ToString()}'");
                            await dtClient.UpdateDigitalTwinAsync(twinId, updateTwinData);
                        }
                        catch (Exception ex) {
                            log.LogError(ex, ex.Message);
                        }
                    }
                }
            }
        }
        public async Task UpdateTwinAsync(DigitalTwinsClient client)
        {
            // ------------------ UPDATE TWIN (Longer example than in the runnable sample)---------------------
            // <UpdateTwin>
            var updateTwinData = new JsonPatchDocument();

            updateTwinData.AppendAdd("/Temperature", 25.0);
            updateTwinData.AppendAdd("/myComponent/Property", "Hello");
            // Un-set a property
            updateTwinData.AppendRemove("/Humidity");

            await client.UpdateDigitalTwinAsync("myTwin", updateTwinData).ConfigureAwait(false);

            // </UpdateTwin>
        }
        public void AddIsSerializedCorrectly()
        {
            JsonPatchDocument document = new JsonPatchDocument();

            document.AppendAdd("/a/b/c", "[ \"foo\", \"bar\" ]");
            Assert.AreEqual(document.ToString(), "[{\"op\":\"add\",\"path\":\"/a/b/c\",\"value\":[\"foo\",\"bar\"]}]");
        }
        private async Task PatchTemperature(DigitalTwinsClient client, string digitalTwinId, double temperature)
        {
            var updateTwinData = new JsonPatchDocument();

            updateTwinData.AppendAdd("/Humidity", temperature);
            //updateTwinData.AppendReplace("/Temperature", temperature);
            var response = await client.UpdateDigitalTwinAsync(digitalTwinId, updateTwinData);

            log.LogInformation($"{digitalTwinId} temperature patched to {temperature}");
        }
        public void MultipleOperationsSerializedInOrder()
        {
            JsonPatchDocument document = new JsonPatchDocument();

            document.AppendTest("/a/b/c", "\"foo\"");
            document.AppendAdd("/a/b/c", "42");
            document.AppendReplace("/a/b/c", "[ \"foo\", \"bar\" ]");
            document.AppendRemove("/a/b/c");
            document.AppendMove("/a/b/c", "/a/b/d");
            document.AppendCopy("/a/b/c", "/a/b/d");

            Assert.AreEqual(document.ToString(),
                            "[" +
                            "{\"op\":\"test\",\"path\":\"/a/b/c\",\"value\":\"foo\"}," +
                            "{\"op\":\"add\",\"path\":\"/a/b/c\",\"value\":42}," +
                            "{\"op\":\"replace\",\"path\":\"/a/b/c\",\"value\":[\"foo\",\"bar\"]}," +
                            "{\"op\":\"remove\",\"path\":\"/a/b/c\"}," +
                            "{\"op\":\"move\",\"from\":\"/a/b/c\",\"path\":\"/a/b/d\"}," +
                            "{\"op\":\"copy\",\"from\":\"/a/b/c\",\"path\":\"/a/b/d\"}" +
                            "]");
        }
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Create the Azure Digital Twins client for API calls
            string adtInstanceUrl = "https://<your-instance-hostname>";
            var    credentials    = new DefaultAzureCredential();
            var    client         = new DigitalTwinsClient(new Uri(adtInstanceUrl), credentials);

            Console.WriteLine($"Service client created – ready to go");

            // Upload models
            Console.WriteLine($"Upload a model");
            string dtdl   = File.ReadAllText("<path-to>/Room.json");
            var    models = new List <string> {
                dtdl
            };
            // Upload the model to the service
            await client.CreateModelsAsync(models);

            // Create new digital twin
            // <CreateTwin_withHelper>
            string twinId   = "myTwinID";
            var    initData = new BasicDigitalTwin
            {
                Id       = twinId,
                Metadata = { ModelId = "dtmi:example:Room;1" },
                // Initialize properties
                Contents =
                {
                    { "Temperature", 25.0 },
                    { "Humidity",    50.0 },
                },
            };

            // <CreateTwinCall>
            await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(twinId, initData);

            // </CreateTwinCall>
            // </CreateTwin_withHelper>
            Console.WriteLine("Twin created successfully");

            //Print twin
            Console.WriteLine("--- Printing twin details:");
            twin = await FetchAndPrintTwinAsync(twinId, client);

            Console.WriteLine("--------");

            //Update twin data
            var updateTwinData = new JsonPatchDocument();

            updateTwinData.AppendAdd("/Temperature", 25.0);
            // <UpdateTwinCall>
            await client.UpdateDigitalTwinAsync(twin_ID, updateTwinData);

            // </UpdateTwinCall>
            Console.WriteLine("Twin properties updated");
            Console.WriteLine();

            //Print twin again
            Console.WriteLine("--- Printing twin details (after update):");
            FetchAndPrintTwin(twin_ID, client);
            Console.WriteLine("--------");
            Console.WriteLine();

            //Delete twin
            await DeleteTwin(client, twin_ID);
        }
Ejemplo n.º 7
0
        public async Task DigitalTwins_Lifecycle()
        {
            DigitalTwinsClient client = GetClient();

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            try
            {
                // arrange

                // create room model
                string roomModel = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                await client.CreateModelsAsync(new List <string> {
                    roomModel
                }).ConfigureAwait(false);

                // act

                // create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // get twin
                await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false);

                // update twin
                JsonPatchDocument updateTwinPatchDocument = new JsonPatchDocument();
                updateTwinPatchDocument.AppendAdd("/Humidity", 30);
                updateTwinPatchDocument.AppendReplace("/Temperature", 70);
                updateTwinPatchDocument.AppendRemove("/EmployeeId");

                var requestOptions = new UpdateDigitalTwinOptions
                {
                    IfMatch = "*"
                };

                await client.UpdateDigitalTwinAsync(roomTwinId, updateTwinPatchDocument, requestOptions).ConfigureAwait(false);

                // delete a twin
                await client.DeleteDigitalTwinAsync(roomTwinId).ConfigureAwait(false);

                // assert
                Func <Task> act = async() =>
                {
                    await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false);
                };

                act.Should().Throw <RequestFailedException>()
                .And.Status.Should().Be((int)HttpStatusCode.NotFound);
            }
            finally
            {
                // cleanup
                try
                {
                    if (!string.IsNullOrWhiteSpace(roomModelId))
                    {
                        await client.DeleteModelAsync(roomModelId).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // Create the Azure Digital Twins client for API calls
            DigitalTwinsClient client = createDtClient();

            Console.WriteLine($"Service client created – ready to go");
            Console.WriteLine();

            // Upload models
            Console.WriteLine($"Upload models");
            Console.WriteLine();
            string dtdl   = File.ReadAllText("<path-to>/Room.json");
            string dtdl1  = File.ReadAllText("<path-to>/Floor.json");
            var    models = new List <string>
            {
                dtdl,
                dtdl1,
            };
            // Upload the models to the service
            await client.CreateModelsAsync(models);

            // Create new (Floor) digital twin
            var    floorTwin = new BasicDigitalTwin();
            string srcId     = "myFloorID";

            floorTwin.Metadata.ModelId = "dtmi:example:Floor;1";
            // Floor twins have no properties, so nothing to initialize
            // Create the twin
            await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(srcId, floorTwin);

            Console.WriteLine("Twin created successfully");

            // Create second (Room) digital twin
            var    roomTwin = new BasicDigitalTwin();
            string targetId = "myRoomID";

            roomTwin.Metadata.ModelId = "dtmi:example:Room;1";
            // Initialize properties
            roomTwin.Contents.Add("Temperature", 35.0);
            roomTwin.Contents.Add("Humidity", 55.0);
            // Create the twin
            await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(targetId, roomTwin);

            // Create relationship between them
            var properties = new Dictionary <string, object>
            {
                { "ownershipUser", "ownershipUser original value" },
            };

            // <UseCreateRelationship>
            await CustomMethod_CreateRelationshipAsync(client, srcId, targetId, "contains", properties);

            // </UseCreateRelationship>
            Console.WriteLine();

            // Update relationship's Name property
            // <UseUpdateRelationship>
            var updatePropertyPatch = new JsonPatchDocument();

            updatePropertyPatch.AppendAdd("/ownershipUser", "ownershipUser NEW value");
            await CustomMethod_UpdateRelationshipAsync(client, srcId, $"{srcId}-contains->{targetId}", updatePropertyPatch);

            // </UseUpdateRelationship>
            Console.WriteLine();

            //Print twins and their relationships
            Console.WriteLine("--- Printing details:");
            Console.WriteLine($"Outgoing relationships from source twin, {srcId}:");
            // <UseFetchAndPrint>
            await CustomMethod_FetchAndPrintTwinAsync(srcId, client);

            // </UseFetchAndPrint>
            Console.WriteLine();
            Console.WriteLine($"Incoming relationships to target twin, {targetId}:");
            await CustomMethod_FetchAndPrintTwinAsync(targetId, client);

            Console.WriteLine("--------");
            Console.WriteLine();

            // Delete the relationship
            // <UseDeleteRelationship>
            await CustomMethod_DeleteRelationshipAsync(client, srcId, $"{srcId}-contains->{targetId}");

            // </UseDeleteRelationship>
            Console.WriteLine();

            // Print twins and their relationships again
            Console.WriteLine("--- Printing details (after relationship deletion):");
            Console.WriteLine("Outgoing relationships from source twin:");
            await CustomMethod_FetchAndPrintTwinAsync(srcId, client);

            Console.WriteLine();
            Console.WriteLine("Incoming relationships to target twin:");
            await CustomMethod_FetchAndPrintTwinAsync(targetId, client);

            Console.WriteLine("--------");
            Console.WriteLine();
        }
Ejemplo n.º 9
0
        public async Task DigitalTwins_DeleteTwinSucceedsIfMatchProvidesCorrectEtag()
        {
            DigitalTwinsClient client = GetClient();

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            try
            {
                // arrange

                // create room model
                string roomModel = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                await client.CreateModelsAsync(new List <string> {
                    roomModel
                }).ConfigureAwait(false);

                // act

                // create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // update twin
                JsonPatchDocument updateTwinPatchDocument = new JsonPatchDocument();
                updateTwinPatchDocument.AppendAdd("/Humidity", 30);
                updateTwinPatchDocument.AppendReplace("/Temperature", 70);
                updateTwinPatchDocument.AppendRemove("/EmployeeId");
                await client.UpdateDigitalTwinAsync(roomTwinId, updateTwinPatchDocument, ETag.All).ConfigureAwait(false);

                // get twin
                ETag?correctETag = (await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false)).Value.ETag;
                Assert.IsNotNull(correctETag);

                try
                {
                    // since the ETag is not out of date, this call should not throw a 412
                    await client.DeleteDigitalTwinAsync(roomTwinId, correctETag).ConfigureAwait(false);
                }
                catch (RequestFailedException ex) when(ex.Status == (int)HttpStatusCode.PreconditionFailed)
                {
                    throw new AssertionException("UpdateRelationship should not have thrown PreconditionFailed because the ETag was up to date", ex);
                }
            }
            finally
            {
                // cleanup
                try
                {
                    if (!string.IsNullOrWhiteSpace(roomModelId))
                    {
                        await client.DeleteModelAsync(roomModelId).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
Ejemplo n.º 10
0
        public async Task DigitalTwins_DeleteTwinFailsIfMatchProvidesOutdatedEtag()
        {
            DigitalTwinsClient client = GetClient();

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            try
            {
                // arrange

                // create room model
                string roomModel = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                await client.CreateModelsAsync(new List <string> {
                    roomModel
                }).ConfigureAwait(false);

                // act

                // create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // get twin
                ETag?etagBeforeUpdate = (await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false)).Value.ETag;

                // update twin
                JsonPatchDocument updateTwinPatchDocument = new JsonPatchDocument();
                updateTwinPatchDocument.AppendAdd("/Humidity", 30);
                updateTwinPatchDocument.AppendReplace("/Temperature", 70);
                updateTwinPatchDocument.AppendRemove("/EmployeeId");

                await client.UpdateDigitalTwinAsync(roomTwinId, updateTwinPatchDocument, ETag.All).ConfigureAwait(false);

                // assert
                Func <Task> act = async() =>
                {
                    // since the ETag is out of date, this call should throw a 412
                    await client.DeleteDigitalTwinAsync(roomTwinId, etagBeforeUpdate).ConfigureAwait(false);
                };

                act.Should().Throw <RequestFailedException>()
                .And.Status.Should().Be((int)HttpStatusCode.PreconditionFailed);
            }
            finally
            {
                // cleanup
                try
                {
                    if (!string.IsNullOrWhiteSpace(roomModelId))
                    {
                        await client.DeleteModelAsync(roomModelId).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
Ejemplo n.º 11
0
        public async Task DigitalTwins_PatchTwinFailsIfInvalidETagProvided()
        {
            DigitalTwinsClient client = GetClient();

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            try
            {
                // arrange

                // create room model
                string roomModel = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                await client.CreateModelsAsync(new List <string> {
                    roomModel
                }).ConfigureAwait(false);

                // act

                // create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // get twin
                ETag?etagBeforeUpdate = (await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false)).Value.ETag;

                Assert.IsNotNull(etagBeforeUpdate);

                // update twin once to make the previous etag fall out of date
                JsonPatchDocument updateTwinPatchDocument = new JsonPatchDocument();
                updateTwinPatchDocument.AppendAdd("/Humidity", 30);
                updateTwinPatchDocument.AppendReplace("/Temperature", 70);
                updateTwinPatchDocument.AppendRemove("/EmployeeId");
                await client.UpdateDigitalTwinAsync(roomTwinId, updateTwinPatchDocument, ETag.All).ConfigureAwait(false);

                // update twin again, but with an out of date etag, which should cause a 412 from service
                JsonPatchDocument secondUpdateTwinPatchDocument = new JsonPatchDocument();
                secondUpdateTwinPatchDocument.AppendReplace("/Humidity", 80);
                Func <Task> act = async() =>
                {
                    await client.UpdateDigitalTwinAsync(roomTwinId, secondUpdateTwinPatchDocument, etagBeforeUpdate).ConfigureAwait(false);
                };

                act.Should().Throw <RequestFailedException>()
                .And.Status.Should().Be((int)HttpStatusCode.PreconditionFailed);
            }
            finally
            {
                // cleanup
                try
                {
                    if (!string.IsNullOrWhiteSpace(roomModelId))
                    {
                        await client.DeleteModelAsync(roomModelId).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }
Ejemplo n.º 12
0
        public async void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            try
            {
                // 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();
                log.LogInformation(credentials.ToString());
                DigitalTwinsClient client = new DigitalTwinsClient(
                    new Uri(adtServiceUrl), credentials, new DigitalTwinsClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                });
                log.LogInformation($"ADT service client connection created.");
                if (eventGridEvent.Data.ToString().Contains("Alert"))
                {
                    JObject alertMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
                    string  deviceId     = (string)alertMessage["systemProperties"]["iothub-connection-device-id"];
                    var     ID           = alertMessage["body"]["TurbineID"];
                    var     alert        = alertMessage["body"]["Alert"];
                    log.LogInformation($"Device:{deviceId} Device Id is:{ID}");
                    log.LogInformation($"Device:{deviceId} Alert Status is:{alert}");

                    var updateProperty = new JsonPatchDocument();
                    updateProperty.AppendReplace("/Alert", alert.Value <bool>());
                    updateProperty.AppendReplace("/TurbineID", ID.Value <string>());
                    log.LogInformation(updateProperty.ToString());
                    try
                    {
                        await client.UpdateDigitalTwinAsync(deviceId, updateProperty);
                    }
                    catch (Exception e)
                    {
                        log.LogInformation(e.Message);
                    }
                }
                else if (eventGridEvent != null && eventGridEvent.Data != null)
                {
                    JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString());
                    string  deviceId      = (string)deviceMessage["systemProperties"]["iothub-connection-device-id"];
                    var     ID            = deviceMessage["body"]["TurbineID"];
                    var     TimeInterval  = deviceMessage["body"]["TimeInterval"];
                    var     Description   = deviceMessage["body"]["Description"];
                    var     Code          = deviceMessage["body"]["Code"];
                    var     WindSpeed     = deviceMessage["body"]["WindSpeed"];
                    var     Ambient       = deviceMessage["body"]["Ambient"];
                    var     Rotor         = deviceMessage["body"]["Rotor"];
                    var     Power         = deviceMessage["body"]["Power"];

                    log.LogInformation($"Device:{deviceId} Device Id is:{ID}");
                    log.LogInformation($"Device:{deviceId} Time interval is:{TimeInterval}");
                    log.LogInformation($"Device:{deviceId} Description is:{Description}");
                    log.LogInformation($"Device:{deviceId} CodeNumber is:{Code}");
                    log.LogInformation($"Device:{deviceId} WindSpeed is:{WindSpeed}");
                    log.LogInformation($"Device:{deviceId} Ambient Temperature is:{Ambient}");
                    log.LogInformation($"Device:{deviceId} Rotor RPM is:{Rotor}");
                    log.LogInformation($"Device:{deviceId} Power is:{Power}");
                    var updateProperty   = new JsonPatchDocument();
                    var turbineTelemetry = new Dictionary <string, Object>()
                    {
                        ["TurbineID"]    = ID,
                        ["TimeInterval"] = TimeInterval,
                        ["Description"]  = Description,
                        ["Code"]         = Code,
                        ["WindSpeed"]    = WindSpeed,
                        ["Ambient"]      = Ambient,
                        ["Rotor"]        = Rotor,
                        ["Power"]        = Power
                    };
                    updateProperty.AppendAdd("/TurbineID", ID.Value <string>());

                    log.LogInformation(updateProperty.ToString());
                    try
                    {
                        await client.PublishTelemetryAsync(deviceId, Guid.NewGuid().ToString(), JsonConvert.SerializeObject(turbineTelemetry));
                    }
                    catch (Exception e)
                    {
                        log.LogInformation(e.Message);
                    }
                }
            }
            catch (Exception e)
            {
                log.LogInformation(e.Message);
            }
        }
Ejemplo n.º 13
0
        public static async Task Run([IoTHubTrigger("messages/events", Connection = "IoTHubBuiltInConnection", ConsumerGroup = "function")] EventData message, ILogger log)
        {
            DigitalTwinsClient client;

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

                log.LogInformation($"ADT service client connection created.");
            }
            catch (Exception e)
            {
                log.LogError($"ADT service client connection failed. {e}");
                return;
            }

            if (client != null)
            {
                if (message != null && message.Body != null)
                {
                    var msg = Encoding.UTF8.GetString(message.Body.Array);
                    log.LogInformation($"C# IoT Hub trigger function processed a message: {msg}");

                    // Get device Id
                    string deviceId = (string)message.SystemProperties["iothub-connection-device-id"];

                    try
                    {
                        var sensordata = JsonConvert.DeserializeObject <SensorMessage>(msg);

                        JsonPatchDocument updateTwinData = new JsonPatchDocument();
                        updateTwinData.AppendReplace <string>("/Name", sensordata.SensorName);
                        updateTwinData.AppendReplace <float>("/Value", (float)sensordata.SensorValue);

                        await client.UpdateDigitalTwinAsync(deviceId, updateTwinData);   //deviceId == dtid
                    }
                    catch (JsonException jex)
                    {
                        log.LogError("Message parsing error.", jex);
                    }
                    catch (RequestFailedException exc)
                    {
                        log.LogInformation($"{deviceId}*** Error:{exc.Status}/{exc.Message}");

                        // 최초 Update 할 경우 Replace를 쓰면 오류발생. Add를 써야함.
                        var sensordata = JsonConvert.DeserializeObject <SensorMessage>(msg);

                        JsonPatchDocument addTwinData = new JsonPatchDocument();
                        addTwinData.AppendAdd <string>("/Name", sensordata.SensorName);
                        addTwinData.AppendAdd <float>("/Value", (float)sensordata.SensorValue);

                        await client.UpdateDigitalTwinAsync(deviceId, addTwinData);
                    }
                    catch (Exception ex)
                    {
                        log.LogError("Update Twin error.", ex);
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public async Task DigitalTwins_PatchTwinSucceedsIfCorrectETagProvided()
        {
            DigitalTwinsClient client = GetClient();

            string roomTwinId = await GetUniqueTwinIdAsync(client, TestAssetDefaults.RoomTwinIdPrefix).ConfigureAwait(false);

            string floorModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.FloorModelIdPrefix).ConfigureAwait(false);

            string roomModelId = await GetUniqueModelIdAsync(client, TestAssetDefaults.RoomModelIdPrefix).ConfigureAwait(false);

            try
            {
                // arrange

                // create room model
                string roomModel = TestAssetsHelper.GetRoomModelPayload(roomModelId, floorModelId);
                await CreateAndListModelsAsync(client, new List <string> {
                    roomModel
                }).ConfigureAwait(false);

                // act

                // create room twin
                BasicDigitalTwin roomTwin = TestAssetsHelper.GetRoomTwinPayload(roomModelId);
                await client.CreateOrReplaceDigitalTwinAsync <BasicDigitalTwin>(roomTwinId, roomTwin).ConfigureAwait(false);

                // update twin once
                JsonPatchDocument updateTwinPatchDocument = new JsonPatchDocument();
                updateTwinPatchDocument.AppendAdd("/Humidity", 30);
                updateTwinPatchDocument.AppendReplace("/Temperature", 70);
                updateTwinPatchDocument.AppendRemove("/EmployeeId");
                await client.UpdateDigitalTwinAsync(roomTwinId, updateTwinPatchDocument, ETag.All).ConfigureAwait(false);

                // get twin
                ETag?etagBeforeUpdate = (await client.GetDigitalTwinAsync <BasicDigitalTwin>(roomTwinId).ConfigureAwait(false)).Value.ETag;

                Assert.IsNotNull(etagBeforeUpdate);

                // update twin again, but with the correct etag
                JsonPatchDocument secondUpdateTwinPatchDocument = new JsonPatchDocument();
                secondUpdateTwinPatchDocument.AppendReplace("/Humidity", 80);
                try
                {
                    await client.UpdateDigitalTwinAsync(roomTwinId, secondUpdateTwinPatchDocument, etagBeforeUpdate).ConfigureAwait(false);
                }
                catch (RequestFailedException ex) when(ex.Status == (int)HttpStatusCode.PreconditionFailed)
                {
                    throw new AssertionException("UpdateDigitalTwin should not have thrown PreconditionFailed because the ETag was up to date", ex);
                }
            }
            catch (Exception ex)
            {
                Assert.Fail($"Failure in executing a step in the test case: {ex.Message}.");
            }
            finally
            {
                // cleanup
                try
                {
                    if (!string.IsNullOrWhiteSpace(roomModelId))
                    {
                        await client.DeleteModelAsync(roomModelId).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Assert.Fail($"Test clean up failed: {ex.Message}");
                }
            }
        }