public static async Task Run( [EventHubTrigger("deviceevents", Connection = "EVENTHUB_CONNECTIONSTRING")] EventData[] events, 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"); } var exceptions = new List <Exception>(); foreach (EventData eventData in events) { try { // Get message body string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count); // Create Digital Twin client var cred = new ManagedIdentityCredential("https://digitaltwins.azure.net"); var client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) }); // Reading Device ID from message headers JObject jbody = (JObject)JsonConvert.DeserializeObject(messageBody); string deviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString(); string dtId = deviceId; // simple mapping // Extracting temperature from device telemetry double temperature = Convert.ToDouble(jbody["Temperature"].ToString()); // Update device Temperature property UpdateOperationsUtility uou = new UpdateOperationsUtility(); uou.AppendAddOp("/Temperature", temperature); await client.UpdateDigitalTwinAsync(dtId, uou.Serialize()); log.LogInformation($"Updated Temperature of device Twin '{dtId}' to: {temperature}"); } catch (Exception e) { // We need to keep processing the rest of the batch - capture this exception and continue. exceptions.Add(e); } } if (exceptions.Count > 1) { throw new AggregateException(exceptions); } if (exceptions.Count == 1) { throw exceptions.Single(); } }
public static string GetRoomTwinUpdatePayload() { var uou = new UpdateOperationsUtility(); uou.AppendAddOp("/Humidity", 30); uou.AppendReplaceOp("/Temperature", 70); uou.AppendRemoveOp("/EmployeeId"); return(RemoveNewLines(uou.Serialize())); }
public override async Task HandleMessageAsync(DeviceTelemetryMessage requestBody, RequestDetails requestDetails, RequestMessageHeaders headers, IExtensionGatewayClient client, ILogger log) { //write telemetry to statestore await client.PutDeviceTelemetryAsync(requestDetails.DeviceName, requestBody); // Create a secret client using the DefaultAzureCredential DefaultAzureCredential cred = new DefaultAzureCredential(); DigitalTwinsClient dtcli = new DigitalTwinsClient(new Uri("https://mobility-vss.api.wus2.digitaltwins.azure.net"), cred); DTUnit du = JsonSerializer.Deserialize <DTUnit>((string)requestBody.Payload); var updateOps = new UpdateOperationsUtility(); if (du.type == "boolean") { updateOps.AppendAddOp(du.path, bool.Parse(du.value)); } else if ((du.type == "date") || (du.type == "datetime") || (du.type == "time")) { updateOps.AppendAddOp(du.path, DateTime.Parse(du.value)); } else if (du.type == "double") { updateOps.AppendAddOp(du.path, double.Parse(du.value)); } else if (du.type == "float") { updateOps.AppendAddOp(du.path, float.Parse(du.value)); } else if (du.type == "integer") { updateOps.AppendAddOp(du.path, int.Parse(du.value)); } else if (du.type == "long") { updateOps.AppendAddOp(du.path, long.Parse(du.value)); } else { updateOps.AppendAddOp(du.path, du.value); } string patchPayload = updateOps.Serialize(); await dtcli.UpdateDigitalTwinAsync(du.dtID, patchPayload); // send stuff to the analytics pipeline var telemetryItem = new { VehicleId = requestDetails.VehicleId, TelemetryName = requestBody.TelemetryName, Time = requestBody.Time, Payload = patchPayload }; await client.SendToAnalyticsPipeline(telemetryItem); }
public static async Task Run( [EventHubTrigger("deviceevents", Connection = "EVENTHUB_CONNECTIONSTRING")] EventData[] events, ILogger log) { var exceptions = new List <Exception>(); foreach (EventData eventData in events) { try { // Get message body string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count); // Create Digital Twin client var cred = new ManagedIdentityCredential(adtAppId); var client = new DigitalTwinsClient(new Uri(adtInstanceUrl), cred, new DigitalTwinsClientOptions { Transport = new HttpClientTransport(httpClient) }); // Reading Device ID from message headers JObject jbody = (JObject)JsonConvert.DeserializeObject(messageBody); string deviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString(); string dtId = deviceId; // simple mapping // Extracting temperature from device telemetry double temperature = Convert.ToDouble(jbody["Temperature"].ToString()); // Update device Temperature property UpdateOperationsUtility uou = new UpdateOperationsUtility(); uou.AppendAddOp("/Temperature", temperature); await client.UpdateDigitalTwinAsync(dtId, uou.Serialize()); log.LogInformation($"Updated Temperature of device Twin '{dtId}' to: {temperature}"); } catch (Exception e) { // We need to keep processing the rest of the batch - capture this exception and continue. exceptions.Add(e); } } if (exceptions.Count > 1) { throw new AggregateException(exceptions); } if (exceptions.Count == 1) { throw exceptions.Single(); } }
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(); }
private static void GetPatchPayload(string jsonInput, ref string dtid, ref string patchpayload) { var updateOps = new UpdateOperationsUtility(); DTUnit du = JsonSerializer.Deserialize <DTUnit>(jsonInput); dtid = du.dtID; if (du.type == "boolean") { updateOps.AppendAddOp(du.path, bool.Parse(du.value)); } else if ((du.type == "date") || (du.type == "datetime") || (du.type == "time")) { updateOps.AppendAddOp(du.path, DateTime.Parse(du.value)); } else if (du.type == "double") { updateOps.AppendAddOp(du.path, double.Parse(du.value)); } else if (du.type == "float") { updateOps.AppendAddOp(du.path, float.Parse(du.value)); } else if (du.type == "integer") { updateOps.AppendAddOp(du.path, int.Parse(du.value)); } else if (du.type == "long") { updateOps.AppendAddOp(du.path, long.Parse(du.value)); } else { updateOps.AppendAddOp(du.path, du.value); } patchpayload = updateOps.Serialize(); }
public async void Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log) { if (adtInstanceUrl == null) { log.LogError("Application setting \"ADT_SERVICE_URL\" not set"); } try { //Authenticate with Digital Twins ManagedIdentityCredential cred = new ManagedIdentityCredential("https://digital-twin-demo-jc.api.wcus.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 (eventGridEvent != null && eventGridEvent.Data != null) { log.LogInformation(eventGridEvent.Data.ToString()); // Reading deviceId, temperature, humidity, pressure, magnetometer, accelerometer and gyroscope for IoT Hub JSON JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(eventGridEvent.Data.ToString()); string deviceId = (string)deviceMessage["systemProperties"]["iothub-connection-device-id"]; byte[] body = System.Convert.FromBase64String(deviceMessage["body"].ToString()); var value = System.Text.ASCIIEncoding.ASCII.GetString(body); var bodyProperty = (JObject)JsonConvert.DeserializeObject(value); var temperature = bodyProperty["temperature"]; var humidity = bodyProperty["humidity"]; var pressure = bodyProperty["pressure"]; var magnetometer_x = bodyProperty["magnetometer_x"]; var magnetometer_y = bodyProperty["magnetometer_y"]; var magnetometer_z = bodyProperty["magnetometer_z"]; var accelerometer_x = bodyProperty["accelerometer_x"]; var accelerometer_y = bodyProperty["accelerometer_y"]; var accelerometer_z = bodyProperty["accelerometer_z"]; var gyroscope_x = bodyProperty["gyroscope_x"]; var gyroscope_y = bodyProperty["gyroscope_y"]; var gyroscope_z = bodyProperty["gyroscope_z"]; log.LogInformation($"Device:{deviceId} Temperature is: {temperature}"); //note: AppendReplaceOp only works if model properties are instantiated when twin created. var uou = new UpdateOperationsUtility(); if (temperature != null) //accounting for null values from I2C bus on MXChip dev kits { uou.AppendAddOp("/temperature", temperature.Value <double>()); } else { temperature = -1000; uou.AppendAddOp("/temperature", temperature.Value <double>()); } if (humidity != null) { uou.AppendAddOp("/humidity", humidity.Value <double>()); } else { humidity = -1000; uou.AppendAddOp("/humidity", humidity.Value <double>()); } if (pressure != null) { uou.AppendAddOp("/pressure", pressure.Value <double>()); } else { pressure = -1000; uou.AppendAddOp("/pressure", pressure.Value <double>()); } if (magnetometer_x != null) { uou.AppendAddOp("/magnetometer_x", magnetometer_x.Value <double>()); } else { magnetometer_x = -1000; uou.AppendAddOp("/magnetometer_x", magnetometer_x.Value <double>()); } if (magnetometer_y != null) { uou.AppendAddOp("/magnetometer_y", magnetometer_y.Value <double>()); } else { magnetometer_y = -1000; uou.AppendAddOp("/magnetometer_y", magnetometer_y.Value <double>()); } if (magnetometer_z != null) { uou.AppendAddOp("/magnetometer_z", magnetometer_z.Value <double>()); } else { magnetometer_z = -1000; uou.AppendAddOp("/magnetometer_z", magnetometer_z.Value <double>()); } if (accelerometer_x != null) { uou.AppendAddOp("/accelerometer_x", accelerometer_x.Value <double>()); } else { accelerometer_x = -1000; uou.AppendAddOp("/accelerometer_x", accelerometer_x.Value <double>()); } if (accelerometer_y != null) { uou.AppendAddOp("/accelerometer_y", accelerometer_y.Value <double>()); } else { accelerometer_y = -1000; uou.AppendAddOp("/accelerometer_y", accelerometer_y.Value <double>()); } if (accelerometer_z != null) { uou.AppendAddOp("/accelerometer_z", accelerometer_z.Value <double>()); } else { accelerometer_z = -1000; uou.AppendAddOp("/accelerometer_z", accelerometer_z.Value <double>()); } if (gyroscope_x != null) { uou.AppendAddOp("/gyroscope_x", gyroscope_x.Value <double>()); } else { gyroscope_x = -1000; uou.AppendAddOp("/gyroscope_x", gyroscope_x.Value <double>()); } if (gyroscope_y != null) { uou.AppendAddOp("/gyroscope_y", gyroscope_y.Value <double>()); } else { gyroscope_y = -1000; uou.AppendAddOp("/gyroscope_y", gyroscope_y.Value <double>()); } if (gyroscope_z != null) { uou.AppendAddOp("/gyroscope_z", gyroscope_z.Value <double>()); } else { gyroscope_z = -1000; uou.AppendAddOp("/gyroscope_z", gyroscope_z.Value <double>()); } await client.UpdateDigitalTwinAsync(deviceId, uou.Serialize()); log.LogInformation($"Device:{deviceId} Pressure is: {pressure}"); } } catch (Exception e) { log.LogError($"Error in ingest function: {e.Message}"); } }