public async Task Send(string jsonPayload) { using (X509Certificate2 cert = new X509Certificate2(this.path)) { if (!Program.GetInfo(in cert, out string deviceName, out string vehicleUuid)) { return; } // Retrieves vehicle with Authentication Info from CVS. This step is required to parse out the service authentication key needed // to retrieve the vehicle connection information using (VehicleConnectionClient vc = new VehicleConnectionClient(new Uri(String.Format("https://{0}:8510", this.domain)), cert)) { DeviceCredentialInformation deviceInfo = new DeviceCredentialInformation { VehicleUuid = vehicleUuid }; DeviceConnectionInformation connectionInfo = vc.GetDeviceConnectionInfoAsync(deviceInfo, deviceName).Result; if (connectionInfo == null) { Console.WriteLine("Vehicle ID or device name not found. Please try again"); return; } DeviceClient deviceClient = DeviceClient.Create( connectionInfo.PrimaryIoTHubName, new DeviceAuthenticationWithRegistrySymmetricKey( connectionInfo.IoTDeviceId, connectionInfo.IoTAuthenticationInformation.SymmetricKey.PrimaryKey), TransportType.Mqtt_Tcp_Only); Console.WriteLine("------------------------"); // construct a basic Device Telemetry Message DeviceTelemetryMessage telemetryMessage = new DeviceTelemetryMessage { TelemetryName = this.telemName, // needs to match the prefix of our telemetry extension Payload = jsonPayload, Priority = MessagePriority.Normal }; // construct the actual IoT message. Setting the content type is necessary for prioritization to function properly within CVS. DeviceMessage deviceMessage = new DeviceMessage(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(telemetryMessage))); deviceMessage.ContentType = "application/json"; await deviceClient.SendEventAsync(deviceMessage); Console.WriteLine($"Sent telemetry message to IoT hub!"); Console.WriteLine("------------------------"); } } }
public override async Task HandleMessageAsync( DeviceTelemetryMessage requestBody, RequestDetails requestDetails, RequestMessageHeaders headers, IExtensionGatewayClient client, ILogger log) { await client.PutDeviceTelemetryAsync(requestDetails.DeviceName, requestBody); }
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 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); BasicRelationship rel = JsonSerializer.Deserialize <BasicRelationship>((string)requestBody.Payload); string relationshipId = Guid.NewGuid().ToString(); await dtcli.CreateRelationshipAsync(rel.SourceId, relationshipId, (string)requestBody.Payload); }
private static async Task HandleDeviceMessage(DeviceMessage deviceCommandMessage, DeviceClient primaryClient, DeviceClient secondaryClient, string firstHubName, string secondHubName) { // this section demonstrates how to parse a non-binary DeviceCommandMessage that was sent down. // Later more advanced kits will discuss using binary payloads as another possibility. string rawContent; using (StreamReader reader = new StreamReader(deviceCommandMessage.BodyStream)) { rawContent = await reader.ReadToEndAsync(); } //DeviceCommandMessage parsedMessage = JsonConvert.DeserializeObject<DeviceCommandMessage>(rawContent); DeviceCommandMessage parsedMessage = System.Text.Json.JsonSerializer.Deserialize <DeviceCommandMessage>(rawContent); // 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); BasicDigitalTwin twinData = new BasicDigitalTwin(); JsonElement ele = (JsonElement)parsedMessage.Payload; twinData.Id = ele.GetProperty("$dtId").ToString(); twinData.Metadata.ModelId = ele.GetProperty("$metadata").GetProperty("$model").ToString(); await dtcli.CreateDigitalTwinAsync(twinData.Id, System.Text.Json.JsonSerializer.Serialize(twinData)); await primaryClient.CompleteAsync(deviceCommandMessage); Console.WriteLine("The received command name is: " + parsedMessage.CommandName); Console.Write("Enter a response string:\n>"); string responseString = Console.ReadLine(); // construct a basic Device Telemetry Message with a minimal set of fields. This will be used to respond to the command. DeviceTelemetryMessage telemetryMessage = new DeviceTelemetryMessage { TelemetryName = parsedMessage.CommandName, Payload = new { rawContent }, Priority = MessagePriority.Normal, CorrelationId = parsedMessage.CorrelationId // setting the correlation ID allows the platform to recognize this is a response to the previous device command message. }; // construct the actual IoT message. Setting the content type is necessary for prioritization to function properly within CVS. using (DeviceMessage deviceMessage = new DeviceMessage(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(telemetryMessage)))) { deviceMessage.ContentType = "application/json"; // enqueues the event within IoTHub. The completion of this event means that it has been enqueued to the cloud, but // does not imply that the cloud has actually processed the telemetry message yet. try { await primaryClient.SendEventAsync(deviceMessage); Console.WriteLine($"Sent telemetry message to {firstHubName} IoTHub in response!"); } catch (Exception) { await secondaryClient.SendEventAsync(deviceMessage); Console.WriteLine($"Sent telemetry message to {secondHubName} IoTHub in response!"); } } }