Connect Device from Azure IoT Central to Azure Digital Twin - azure

I have a device in Azure IoT central that has been receiving data. How can I send its telemetry data to its Azure Digital Twin so that they are connected?

You first need to pass the data from Azure IoT Central device to a cloud end point such as Service Bus or Event Hub. You can create an Azure Function and trigger it based on the end point you passed the data to. Within the Azure function you can create the code to push data to the Azure Digitial Twins.
Refer the following resources for data export
Export IoT data to Service Bus
Export IoT Hub data to Event Hubs
Once you have the data routed, use either of the following resources based on your clod end point to build Azure function
Run an Azure function when a Service Bus queue or topic message is created
Respond to events send to Event Hub event stream
Once you have the data flow into the Azure function, before you push the data to the Azure Digital Twin, ensure you have a Model created on the Azure digital twin representing you IoT device data.
If you haven't already done so, refer the Upload a model section to create a Data model for your Azure Digital Twin. Once you have the data model created, you can create Azure Digital Twin either from the Azure Digital Twin explorer or though the code Create Azure Digital Twin.
Once you have the Digital Twin created, you can then push data from your Azure function you created earlier. Here is the code I have tested through ServiceBus Queue trigger.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Azure;
using Azure.Core.Pipeline;
using Azure.DigitalTwins.Core;
using Azure.Identity;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RajIoTCentral.Function
{
public class RajIoTCentralServiceBusQueue
{
private static readonly HttpClient httpClient = new HttpClient();
private static string adtServiceUrl = "https://<yourdigitaltwinendpoint>.digitaltwins.azure.net";
[FunctionName("RajIoTCentralServiceBusQueue")]
public async Task RunAsync([ServiceBusTrigger("iotcentraldata", Connection = "RajIoTDataServiceBus_SERVICEBUS")] string myQueueItem, ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(myQueueItem);
try
{
var temperature = deviceMessage["telemetry"]["temperature"];
var deviceId = "TemperatureSensor";
log.LogInformation($"Temperature is:{temperature.Value<double>()}");
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.");
var updateTwinData = new JsonPatchDocument();
updateTwinData.AppendReplace("/Temperature", temperature.Value<double>());
await client.UpdateDigitalTwinAsync(deviceId, updateTwinData);
}
catch (Exception ex) { log.LogInformation("No temperature in the telemetry data"); }
}
}
}
In the above code, I am pushing the Temperature value I received from the Service Bus queue on to the Azure Digital Twin.
Please refer the following resources for more information on the above code and the approach
Ingest IoT Hub telemetry into Azure Digital Twins
Build out an end-to-end solution
A similar post has been addressed on the Microsoft Q&A forum in the past. Please refer the question here Unable to view result of pipeline which trasport a value from a sensor to digital twin

Related

IoTHubTrigger Azure Function does not trigger

I have an Azure function with the following signature:
[FunctionName("MyFunction")]
[return: EventHub("eventhubname", Connection = "EVENTHUB_OUTPUT_CONNECTIONSTRING")]
public static string Run([IoTHubTrigger("messages/events", Connection = "IOTHUB_CONNECTIONSTRING", ConsumerGroup = "consumergroup")] EventData message, ILogger log)
I am running another Azure Functions with HTTP trigger. When i post to this function, it sends a device message to IoThub. I can see the message coming into the IoT Hub.
My routes have been setup as follows:
My routes have no special queries and i can see them hitting all the endpoints.
I have used the connectionstring from this page:
When i run in debug and when published to Azure, my function does not trigger when sending device messages. I have created 2 consumer groups and I am running 2 partitions.
Any idea what i could change to make this work?

Microsoft.Azure.Devices.Client.Exceptions.UnauthorizedException: 'CONNECT failed: RefusedNotAuthorized'

I have successfully configured my Azure IoT Dev Kit MXChip and I am able to send the data to the IoT Hub. I have also created a logic app with a router in it to receive a mail when the temperature is more than expected and a SQL server to save the Stream Analytics Job data. Basically, I followed the tutorial and till this point, everything was working fine, now I am just creating a simulator device where I can simulate events as mentioned in this tutorial. But whenever I run the application, I am always getting an error as below.
Microsoft.Azure.Devices.Client.Exceptions.UnauthorizedException:
'CONNECT failed: RefusedNotAuthorized'
I am not sure what I am missing here though I understand it is an authentication issue, and I have already changed my Hub Uri and device key as mentioned in the tutorial.
private readonly static string s_iotHubUri = "";
// This is the primary key for the device. This is in the portal.
// Find your IoT hub in the portal > IoT devices > select your device > copy the key.
private readonly static string s_deviceKey = "";
I just figured out what is making this error. I thought the device id we can use here is just a dummy one as it is not mentioned in the tutorial, but not. So, I had two option,
To create a new IoT device in the IoT Hub with the device Id I used in the simulator app (test-device) and update the device id and the key in the app
Use the device Id available already
I just created a new test-device in the Hub.
private readonly static string s_myDeviceId = "test-device";
private readonly static string s_iotHubUri = "youriothubname.azure-devices.net";
private readonly static string s_deviceKey = "devicekey";
After doing that changes, everything was working fine as expected.

Azure Function Triggered by IoT Hub event - the messaging entity could not be found

When developing Azure Function thru Class Library approach (local development) I came across issue when using Even Hub compatible endpoint of IoTHub for triggering my function. This is set thru IoTHubTrigger attribute:
[FunctionName("IoTHubMessageProcessor")]
public static void Run([IoTHubTrigger("messages/events", Connection= "IoTHubReceiveEventsConnectionEndpoint")]EventData message, ILogger log)
When using provided connection string and messages/events endpoint I received error stating that "messaging entity could not be found".
Solution was to alter the connection string and include also Event Hub compatible name in connection string as an entity path so it looks like this:
Endpoint=sb://<Event hub-compatible endpoint>.servicebus.windows.net/;EntityPath=<Event Hub compatible name>;SharedAccessKeyName=<keyName>;SharedAccessKey=<key>"

Azure ioT and Event Hub?

I am trying to read the events that my device is sending. I am using azure npm lib to read the what i think is right.
Ok so first, under my Azure ioT Hub account for that service there is a tab call Messaging. There is something called "Event Hub-compatible name" and "Event Hub-compativle endpoint". Do i have to create a new Event hub with the name of "Event Hub-compatible name" or what? I am a bit confused :D
If not what is the connection string and topic and so on?
Here is how the code is now...
var azure = require('azure');
var serviceBusService = azure.createServiceBusService("Endpoint=XXXXXXXXXX.servicebus.windows.net/");
var isWaiting = false;
function waitForMessages(){
console.log("Checking Queue...");
isWaiting = true;
serviceBusService.receiveQueueMessage("messages","events",function (error, receivedMessage){
console.log(error);
console.log(receivedMessage);
isWaiting = false;
});
}
// Start messages listener
setInterval(function () {
if(!isWaiting){
waitForMessages();
}
}, 200);
The Event Hub-compatible name does not mean that you have to create a Event Hub with the same name.
IOT Hub provides an endpoint that is backward compatible with Event Hub API. I think the actual implementation is a little more complex, but you can think of IOT Hub as inheriting from or at least an implementation of Event Hubs. Use this Event Hub compatible name with any Event Hub SDKs or code examples as part of the connection string.
For explaining the concepts of Event Hub-compatible name & Event Hub-compatible endpoint, you can refer to the section How to read from Event Hubs-compatible endpoints of the offical doc Azure IoT Hub developer guide. You can use the Azure Service Bus SDK for .NET or the Event Hubs - Event Processor Host to read events from IoT Hub in C#.
Otherwise, there are two Azure IoT SDKs for NodeJS using connection string: Azure IoT Service SDK (API Reference) & Azure IoT Device SDK (API Reference).
The connection string that you can find it at the one policy of the tab Shared Access Policies in the All settings, please see the pic below from the doc Tutorial: Get started with Azure IoT Hub.
According to your needs for reading events from IoT Hub, you can follow these samples to code using Azure IoT SDKs for NodeJS.
Using Azure IoT Service SDK to list the deviceIds registed in your IoT Hub, please see the sample https://github.com/Azure/azure-iot-sdks/blob/master/node/service/samples/registry_sample.js.
Using Azure IoT Device SDK to monitor events from IoT Hub, please see the sample https://github.com/Azure/azure-iot-sdks/blob/master/node/device/samples/remote_monitoring.js.
Hope it helps. Any concern, please feel free to let me know.
You can use the Event Hubs SDK for Node.js to see events/messages sent by your device to your IoT Hub:
https://www.npmjs.com/package/azure-event-hubs
The client object of the event hubs SDK can accept an IoT Hub connection string, so you don't need to use the Event Hubs connection string.
If you're just trying to debug your device and want to verify that it's actually sending messages, you can use the tool called iothub-explorer provided with the Azure IoT Hub SDK:
https://github.com/Azure/azure-iot-sdks/tree/master/tools/iothub-explorer
Also a couple of clarifications regarding the previous answer: the Service SDK allows to send messages to devices, and to read the "feedback" message that the device sends, which is used to know if the device accepted or rejected the command message but contains no data. It doesn't help to read data events sent by the device.
Connect to the IoT Hub to receiving the data:
var protocol = 'amqps';
var eventHubHost = '{your event hub-compatible namespace}';
var sasName = 'iothubowner';
var sasKey = '{your iot hub key}';
var eventHubName = '{your event hub-compatible name}';
var numPartitions = 2;
Protocol
var protocol = 'amqps';
It is the Event Hub-compatible endpoint: sb://abcdefnamespace.servicebus.windows.net/
but without the sb:// and .service windows.net/
Like that: abcdefnamespace
var eventHubHost = '{your event hub-compatible namespace}';
Its so OK
var sasName = 'iothubowner';
Primary key, like this: 83wSUdsSdl6iFM4huqiLGFPVI27J2AlAkdCCNvQ==
var sasKey = '{your iot hub key}';
Name like this: iothub-ehub-testsss-12922-ds333s
var eventHubName = '{your event hub-compatible name}';
Its so OK
var numPartitions = 2;
Every Iot Hub instance comes with a built in endpoint that is compatible with Event Hubs. The Event Hub compatible endpoint you see in the Azure portal would be the connection string pointing to the Event Hub instance from where you can read all the messages sent to your Iot Hub instance.
You can use this connection string to the instantiate the EventHubConsumerClient class from the #azure/event-hubs library and read your messages.
In the event of a failover, it is said that this backing built-in endpoint would change. So, you would have to fetch the new connection string and restart the process. Another option is to use the sample code in the azure-iot-samples-node repo to get the Event Hub compatible connection string by passing in the Iot Hub connection string and then use the #azure/event-hubs library to read your messages. See more in Read from the built-in endpoint

CRM 2013-Azure Integration issue

We are facing problem in CRM 2013-Azure Integration.
Below lines explains the CRM 2013 –Azure integration.
1.Plugin will read the data from CRM record and send the data to Azure Service Bus Queue.
2.Azure worker role will read the data from service bus queue and send it to WCF service which will insert/update the data in Azure DB.
When we call the send method to send the data to service bus queue we are getting “channel open did not complete within the specified timeout” error. Below is the code snippet of Azure Service Bus call.
Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri(ConfigurationManager.AppSettings["schemaName"], ConfigurationManager.AppSettings["serviceNamespace"], string.Empty);
MessagingFactory mf = MessagingFactory.Create(runtimeUri,TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationManager.AppSettings["keyName"], ConfigurationManager.AppSettings["sharedAccessKey"]));
sendClient = mf.CreateQueueClient(ConfigurationManager.AppSettings["queuePath"]);
BrokeredMessage helloMessage = new BrokeredMessage(list of CRM data));
helloMessage.MessageId = Guid.NewGuid().ToString();
sendClient.Send(helloMessage);
But when we do the same operation from local(Outside CRM) it is working fine. Please suggest us some solution if you have any.

Resources