Azure IoT Hub MQTT device and device twin changes - azure

I have a device that is an mqtt client to Azure IoT Hub and want the devcie to be notified about changes/updates in the device-twin for that device.
I've successfully connected and updated the reported value in the device-twin from the device but can't seem to get an event when I change some of the desired properties in the device-twin from the Azure shell (https://shell.azure.com/) using a command like this:
az iot hub device-twin update -n <myIotHubBame> -d <myDeviceId> --set properties.desired='{"foo":"bar"}'
On the device I've tried subscribing to $iothub/twin/res/# and devices/<myDeviceId>/messages/devicebound/# but am not receiving any message after issuing the az command from the Azure shell.
I tried also setting a message route with Data Source = Twin Change Events and Endpoint = event but still no message being received in the device.
Anyone has a suggestion on how to get notification to the device when properties in the device-twin changes ?

The MQTT device needs to subscribe on the following topic
$iothub/twin/PATCH/properties/desired/#
for receiving a notification changes on the device twin desired properties.

Related

The message from Azure IoT hub is reaching partially to Stream Analytics and thereby SQL db

The message from Azure IoT edge device installed on Raspberry Pi is sent to the cloud.
In the logs of IoT edge device on Azure Portal the message sent to the cloud is seen (in the troubleshoot section).
In the Stream Analytics the input is referring to IoT hub, the connection is valid.
In the Query section of Stream Analytics when loading the received message content some part of the message is lost. However, the message sent to the cloud from the device is full.
Is there any way to see where the message is lost?
Is the to make a query before stream analytics to find out the data type maybe?
We have to investigate this much more deeper, but i have few suggestions to look at this issue, sharing as below, helping with initial query...!
Try this sample query that you can use to check the message flow from the IoT Edge device to the Stream Analytics job:
IoTHub
| where DeviceId == "your_device_id"
| join (
StreamAnalytics
| where JobName == "your_stream_analytics_job_name"
) on IoTHub.MessageId == StreamAnalytics.InputMessageId
| project TimeGenerated, DeviceId, IoTHub.MessageId, StreamAnalytics.InputMessageId
Try below query to check the data type of the messages being sent from the IoT Edge device:
IoTHub
| where DeviceId == "your_device_id"
| project TimeGenerated, DeviceId, MessageId, json_tostring(Properties) as Properties
I prefer to use "Test" feature in the Stream Analytics query section to see if it processes the message as expected.

Create a device in Azure IoT Hub by Terraform

I am trying to automate setting up of IoT Hub. But I am not able to find any code related to creating a device in the IoT Hub. I found the below command:
resource “azurerm_iothub_device” “example” {
name = “device_name” iothub_name = azurerm_iothub.iothub12.name
}
But it does not seem to be valid.
I have installed the extensions azure IoT Hub and IoT Device Workbench.
How can I do it?
A workaround I use is to use a local provisioner. I use it in my iothub resource for creation. The downside is that it only works on resource creation (or deletion) - so if devices need to be updated at a later stage without recreating the IoT hub you would need to create a new resource with said provisioner.
My provisioner:
provisioner "local-exec" {
command = "${path.module}/create-iot-device.sh ${azurerm_iothub.<your-resource-name>.name}"
}
And the create-iot-device.sh
#!/bin/bash
az iot hub device-identity create --device-id dev-1 --hub-name $1
According to EliiseS, as of now, support for IoT Hub device creation using Terraform is not available.

Sending data to Azure IoT hub using REST

I am trying to learn the Azure IoT hub, but I am unable to send data to my IoT hub using Postman.
I did the following:
Create Azure IoT hub
Create a device using Azure Portal CLI
Copied the text where it said "primary key" on the Device page
My request looks as follows:
POST https://myhub.azure-devices.net/devices/MyDevice/messages/events?api-version=2020-03-13
I have added the authorization header, which has the value:
SharedAccessSignature=SharedAccessSignature sr=myhub.azure-devices.net%2Fdevices%2FMyDevice&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Where the key is the copied text from the "primary key" field from the device page.
Content-type is set to application/json. But the body is currently empty.
I am getting the following response:
"Message": "ErrorCode:ServerError;InternalServerError",
Note: Hub and device name are not the same as stated here.
For a quick-start on this, we have 3 stages 1) SAS key generation from Visual Studio Code see below images(Or from CLI please see the answer posted by silent) 2) Use Postman 3) Monitor via VS code
Steps: VS Code
1) Install VS Code extension tools for Azure IoT & Connect your IoT Hub as per onscreen instructions
2) You can see the list of devices in VS code Explorer. Now right click the device (created in the portal) and select 'Generate SAS Token for the device', give the time in hours like 24 and hit enter.Copy the SAS key from output window fully (entire). Sample shown below.
SharedAccessSignature
sr=deviothub.azure-devices.net%2Fdevices%2FNewDevice&sig=H3II%2FCa5Km5V2pieP5Ti1SI%3D&se=1590867649
Steps Postman
1) I hope you have already visited this document on Azure IoT Hub REST API
Replace the required sections with your IoT Hub values.
POST
https://fully-qualified-iothubname.azure-devices.net/devices/{id}/messages/events?api-version=2020-03-13
2) Make sure to include the fully copied SAS token and use it in the header section of POST call
3) Body content : It depends on your use case.
example 'raw'--JSON--> {"Temperature":54}
**You can see the accepted response from IoT Hub as '204 No Content'
Step Monitor the Telemetry the easy way
1) Open the VS Code editor and right click the particular device and slect 'Start Monitoring the in built events'
2) Send another telemetry from Postman and you can see the message arrived at IoT Hub and is visible on the VS code Monitoring screen.
Happy Azure IoT Learning
You need to calculate the auth header based on your primary key, not just put it into the header. See here for examples how to do this, for instance by using CLI az iot hub generate-sas-token

How to pull Microsoft Azure Event Hub instance details like event hub connection string ,from our application

I am using Microsoft Azure Resource Manager API
https://learn.microsoft.com/en-us/rest/api/resources/resources/listbyresourcegroup
I am able to pull all event hub namespaces under particular
Subscription & resource group . But I am unable to pull event hub instances details like , event hub connection string and name of availabile event hub instances.
Seams that there is no such option in the rest api you mentioned.
You should use the following apis for fetching event hub connection string and name of event hub instances respectively.
For names of event hub instances, use this api, you need to specify the namespce:
GET
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs?api-version=2017-04-01
For connection strings, use this api. You should specify namespace / event hub name / connection string name:
POST
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/eventhubs/{eventHubName}/authorizationRules/{authorizationRuleName}/ListKeys?api-version=2017-04-01
Response for connection string of event hub:
Hope it helps.

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

Resources