how to send data from azure function app to iothub device

Sai Devaraj Manoharan 40 Reputation points
2024-03-11T16:28:18.06+00:00

Hi

,I'm currently trying to send a "Hello" string from azure function app (http trigger) to my IoTHub device.

The agenda is if the http trigger happens the azure function should send the hello string to one of the device connected in IoTHub. From device side I have the python receive code.

What I tried is I manually sent the string using azure iot explorer Cloud to device message option, I'm able to receive the string in my python receive code. So I want to do this using Azure function app.

if it is not possible any other option available like backend, because only one connection can be done to single device at a time. Thanks in advance.

import random
import sys
from azure.iot.hub import IoTHubRegistryManager

MESSAGE_COUNT = 2
AVG_WIND_SPEED = 10.0
MSG_TXT = "{\"service client sent a message\": %.2f}"  CONNECTION_STRING = "Connection string as you mentioned above (service connect)" 
DEVICE_ID = "device01" 
def iothub_messaging_sample_run():
    try:
        # Create IoTHubRegistryManager
        registry_manager = IoTHubRegistryManager(CONNECTION_STRING)

        for i in range(0, MESSAGE_COUNT):
            print ( 'Sending message: {0}'.format(i) )
            data = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))

            props={}
            # optional: assign system properties
            props.update(messageId = "message_%d" % i)
            props.update(correlationId = "correlation_%d" % i)
            props.update(contentType = "application/json")

            # optional: assign application properties
            prop_text = "PropMsg_%d" % i
            props.update(testProperty = prop_text)

            registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)

        try:
            # Try Python 2.xx first
            raw_input("Press Enter to continue...\n")
        except:
            pass
            # Use Python 3.xx in the case of exception
            input("Press Enter to continue...\n")

    except Exception as ex:
        print ( "Unexpected error {0}" .format(ex) )
        return
    except KeyboardInterrupt:
        print ( "IoT Hub C2D Messaging service sample stopped" )
        
        
if __name__ == '__main__':
    print ( "Starting the Python IoT Hub C2D Messaging service sample..." )

    iothub_messaging_sample_run()

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

Accepted answer
  1. LeelaRajeshSayana-MSFT 13,781 Reputation points
    2024-03-11T18:39:03.23+00:00

    Hi @Sai Devaraj Manoharan Thank you for posting the question here.

    only one connection can be done to single device at a time

    Your understanding is correct that the device connection string can be used by only one application. If two applications try to connect using this string, one of them disconnects.

    if it is not possible any other option available like backend

    You can use the IoT Hub Service Client which uses IoT Hub Service connection string from Shared Access policy to establish a connection. Please refer the below image for reference.

    Screenshot that shows how to retrieve the connection string from your IoT Hub in the Azure portal.

    Using the service client, you can send the cloud to device message. Here is a reference snippet of the method that sends the message.

    private async static Task SendCloudToDeviceMessageAsync()
    {
         var commandMessage = new
          Message(Encoding.ASCII.GetBytes("Cloud to device message."));
         await serviceClient.SendAsync(targetDevice, commandMessage);
    }
    

    For more details, please refer to the article section Send a cloud-to-device message. If you prefer a Python implementation, for the Azure function Cloud to device message, please refer here

    You can then use the device connection string to receive this message from your Python application.

    Hope this helps! Please let us know if you have any additional questions or need further assistance.


    If the response helped, please do click Accept Answer and Yes for the answer provided. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.


0 additional answers

Sort by: Most helpful