Write back to Azure Iot hub using Logic App

Ankit Kumar 71 Reputation points
2022-02-14T15:36:01.197+00:00

I am currently doing a POC where I would like to know if this is possible using Azure Services. I get certain data from Iot hub in my Event hub which triggers a logic app, and based on the message received from Event hub, My logic app would send a message to IoT Edge device. i would like to know if it is possible to send message to IoT hub device from logic app? and if yes how can we do that?

I am more looking Yes or No answer to my question and If I get the services to be used to achieve this.. It will be great

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,127 questions
{count} votes

Accepted answer
  1. QuantumCache 20,031 Reputation points
    2022-02-14T21:25:17.203+00:00

    Hello @Ankit Kumar , Thanks for posting this interesting question,

    I hope the below information will help you with your query!

    Sending message from LOGIC APP to Azure IOTHUB

    • Create SAS token:Link Make sure the SAS token validity is long enough for your requirement!
    • Get IoTHub+Device info: Link
    • Get the IotHUB URI: example https://**iothubname**.azure-devices.net/devices/**devicename**/messages/events?api-version=2016-02-03
    • Design the LogicAPP: As shown in the below image, make use of 'HTTP' action.
    • Send the Message\Telemetry to IoTHub: Start the logic App!
    • Monitor the IoT hub for incoming messages or use Device Explorer!

    174215-image.png

    Option 2: If you want to quickly test your newly created\provisioned 'Azure IoTHub +IoT Edge Device' without any physical device, then please make use of the famous RaspberryPi Simulator portal. This portal simulator will send the messages to the IoTHub!!!! You can customize the code as well!!!

    URL: https://azure-samples.github.io/raspberry-pi-web-simulator/

    174245-image.png

    Scenario: Azure IoTHUb to LogicAPP : Receive messages to LogicApp

    Make use of the 'HTTP' action shape for Get request.

    174224-image.png

    Send a text message from your favorite Tool to Azure IoTHub targetting the device! I am using the Device Explorer tool, you may use the RaspberryPi Web Simulator!

    174144-image.png

    Now Run the LogicApp Get call to see the message!!!
    Decode the base64 content string format to read the proper message!!!

    174110-image.png

    Please comment in the below section if you need further information in this regard. Happy to help!

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Sander van de Velde 28,796 Reputation points MVP
    2022-02-14T20:47:01.223+00:00

    Hello @Ankit Kumar ,

    it is possible to interact with devices, from the cloud, using the IoT Hub.

    There are several ways for cloud-to-device communication:

    • Direct methods
    • Desired properties
    • Cloud messages

    Here is a code example with all three solutions:

    using Microsoft.Azure.Devices;  
    using System;  
    using System.Text;  
    using System.Threading.Tasks;  
      
    internal class Program  
    {  
        /// https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-device-management-get-started  
        static async Task Main(string[] args)  
        {  
            Console.WriteLine("Hello ServiceClient World!");  
      
            var serviceClient = ServiceClient.CreateFromConnectionString("[insert iot hub connectionstring]");  
      
            string deviceId = "device5";  
      
            await SendMessage(serviceClient, deviceId); // fire and forget  
      
            await InvokeDirectMethod(serviceClient, deviceId); // waits for an answer or timeout  
      
            var registryManager = RegistryManager.CreateFromConnectionString("[insert iot hub connectionstring]");  
      
            await UpdateDesiredProperties(registryManager, deviceId); // fire and forget  
        }  
      
        private static async Task InvokeDirectMethod(ServiceClient serviceClient, string deviceId)  
        {  
            var messagePayload = "10"; // could also have been a JSON message.  
      
            CloudToDeviceMethod method = new CloudToDeviceMethod("SetTelemetryInterval");  
            method.SetPayloadJson(messagePayload);  
            method.ConnectionTimeout= TimeSpan.FromSeconds(30);  
            method.ResponseTimeout = TimeSpan.FromSeconds(30);  
      
            var result = await serviceClient.InvokeDeviceMethodAsync(deviceId, method);  
      
            Console.WriteLine($"Status: {result.Status}");  
        }  
      
        private static async Task UpdateDesiredProperties(RegistryManager registryManager, string deviceId)  
        {  
            var twin = await registryManager.GetTwinAsync(deviceId);  
      
            var patch =  
    @"{  
    ""properties"": {  
    ""desired"": {  
        ""customKey"": ""customValue""  
    }  
    }  
    }";  
      
            await registryManager.UpdateTwinAsync(twin.DeviceId, patch, twin.ETag);  
        }  
      
        private static async Task SendMessage(ServiceClient serviceClient, string deviceId)  
        {  
            var temperature = 25;  
            var humidity = 70;  
            string messagePayload = $"{<!-- -->{\"temperature\":{temperature},\"humidity\":{humidity}}}";  
      
            using var eventMessage = new Message(Encoding.UTF8.GetBytes(messagePayload))  
            {  
                MessageId = Guid.NewGuid().ToString(),  
                ContentEncoding = Encoding.UTF8.ToString(),  
                ContentType = "application/json",  
            };  
      
            await serviceClient.SendAsync(deviceId, eventMessage);  
        }  
    }  
    

    We make use of the Azure IoT SDK, made available by the "Microsoft.Azure.Devices" NuGet package.

    Notice you have to provide this iothub connectionstring.

    This code is typically executed in an Azure Function, in Azure, so the connectionstring does not leave Azure (for security reasons).

    The code for a test device can be found here.

    It's up to you to decide what logic triggers this Azure function.

    In an IoT platform we see three main resources triggering actions:

    • the Azure function itself
    • Azure Stream Analytics
    • Logic Apps