IoT Hub and Azure Functions using Python and Visual Studio Code

ChrisU 231 Reputation points
2022-05-03T14:42:50.71+00:00

To set the scene: I am new to coding and in my first coding/software support role having completed a diploma last year to bring about a career change. I am also new to IoT but have been tasked with delivering a IoT proof of concept to my employer. So far, I have managed to setup a couple of gateways and devices on a LoRaWAN network server, output to an Azure IoT Hub and store the data in an Azure SQL DB using a Stream analytics job.

However, the sensor environment data arrives encoded in hexadecimal format and so needs decoding. I have already set up a WebSocket output and a simple app that consumes and decodes the data to variables that you can then use/store. This is within Visual Studio Code and run from the console/terminal; I have not yet been able to create an Azure Function for this. I want to now use this decoding script I have written within an Azure function which will take the uplink data, decode the environment data, and then output these along with other data to an Azure database. The trigger being the receiving of uplink data within the IoT-Hub:

198546-image.png

In this, the decode function would replace the Stream analytics job. Would this work or would I require additional functionality?

From reading the documentation here, I think I am right in that an IoT-Hub is an Event hub? I am using Visual Studio Code and Python and I have found very little documentation on setting up Azure Functions for IoT Hub/Event Hub and those that I have found focus on C# and Visual studio. Is there any other resource that I can be pointed to that may help?

Thanks in advance

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,646 questions
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,157 questions
Azure Event Hubs
Azure Event Hubs
An Azure real-time data ingestion service.
598 questions
{count} votes

Accepted answer
  1. Bruno Lucas 4,421 Reputation points MVP
    2022-05-11T10:14:13.273+00:00

    Hi @ChrisU ,

    I cloned your code and it seems correct. I managed to debug it and deploy it.

    First. the debugging locally problem could be 2 things:

    1 - Firewall. the trigger function defaults to AMQP, so, it is trying to reach tpc ports 5671 and 5672. usually I fix this by creating a firewall rule but I see couple months ago Microsoft has finally provided the option to change it to amqpwebsocket. First try adjusting the firewall. if doesn't work, try to change your host.json to this:

    {  
      "version": "2.0",  
      "extensions": {  
        "eventHubs": {  
          "transportType" : "amqpWebSockets"  
        }  
      },  
      "logging": {  
        "applicationInsights": {  
          "samplingSettings": {  
            "isEnabled": true,  
            "excludedTypes": "Request"  
          }  
        }  
      },  
      "extensionBundle": {  
        "id": "Microsoft.Azure.Functions.ExtensionBundle",  
        "version": "[2.*, 3.0.0)"  
      }  
    }  
    

    2 - Did your VS Code generated the python environment? if so, you should have a folder called ".venv"
    200961-image.png

    Regarding deployment, did you use the vs code deploy?
    200972-image.png

    I think part of it is an add-on bug. you can try to deploy without an ide: https://learn.microsoft.com/en-us/azure/azure-functions/deployment-zip-push if you prefer, but back to vs code, for now, after deployment, just make sure the azure function settings (in the cloud) match the ones on the app.seetings.json. the hub connection string must be the same name in Azure. did you grab that here?:

    201023-image.png

    The storage is not mapped in the bindings but seems to be picked as long the name is "AzureWebJobsStorage". just need to make sure the value is correct.

    200914-image.png

    Before moving into testing (and after deploying) remember you need to stop the azure function in azure when testing locally, otherwise the cloud will always grab the messages.

    200992-image.png

    To send messages for testing, I use the iot hub add-on for vs code:

    https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.azure-iot-tools
    https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.azure-iot-toolkit

    200910-image.png
    200936-image.png

    Did you add any devices? the vs code message sending add-on will expect at least one device. If you don't, just add on under the iot hub in azure before using the add-on

    The right place to check if that is running in azure is here:

    Functions > [the function you want to check] > Monitor:

    200968-image.png

    ----------

    200987-image.png

    ----------

    the logs are good for initial troubleshoot. this line writes to that log:
    logging.info('Python EventHub trigger processed an event: %s',
    event.get_body().decode('utf-8'))

    200963-image.png

    to debug locally, make sure the azure function is stopped. hit f5 or click here :

    200930-image.png

    Remember to install this if you want to use the iot hub add-on: https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.azure-iot-tools . It helps testing/debugging

    The confusion in VS Code is where to go to use add-ons. if you were in the devug section, to find the "send message" you need to click in the explorer:

    200944-image.png

    you should see this:

    200966-image.png
    200985-image.png
    201002-image.png

    If everything is good, you should see this:
    200918-image.png

    Would be good to first debug locally to confirm you have the correct connection strings.

    Let me know if that helps.


6 additional answers

Sort by: Most helpful
  1. Matthijs van der Veer 4,376 Reputation points MVP
    2022-05-04T05:49:24.383+00:00

    You're on the right track! You could definitely replace Stream Analytics with an Azure Function, you could even use both in series if you wanted, but it seems like using the Function might be enough for your use case. Here's a link to an Event-Hub triggered Azure Function for Python. If you're not sure how to set up an Azure Function is VS Code, you can download this extension. The extension has a command to start a new Azure Functions project, which will ask you what binding you need:

    198724-image.png

    You will need to grab the Event Hub endpoint connection string from the portal to connect it up.
    198725-image.png

    You mentioned

    an IoT-Hub is an Event hub?

    That's not exactly right, an IoT Hub does expose a default Event Hub endpoint that you can grab messages off. But that Event Hub is only a small part of IoT Hub. In any case you can definitely use an Event Hub trigger in an Azure Function to retrieve the messages!

    1 person found this answer helpful.

  2. ChrisU 231 Reputation points
    2022-05-06T13:36:23.74+00:00

    So I am still struggling on with this. I have watched quite a few tutorials and read some more of the documentation and therefore understand a bit more. I decided to try and follow the documentation for the Azure IoT bindings and triggers and run it to see what will happen and what gets logged. However, I have not got even that far and wondering whether anyone can take a look and point out where I am going wrong.

    The issue is below, I set this within function.json and took the value from that displayed within the built in endpoints:
    199669-image.png

    My code:
    inti.py:
    199680-image.png

    function.json:
    199568-image.png

    host.json:
    199723-image.png

    The connection binding was taken from here:
    199731-image.png

    0 comments No comments

  3. Bruno Lucas 4,421 Reputation points MVP
    2022-05-06T23:23:18.773+00:00

    Hi @ChrisU ,

    You need to add a azure storage to it. that error appear to be you didn't add the conn strings to the az function settings. It won't pick up from the code file.

    Did you manage to run that using the visual studio debugger?

    I managed to debug and deploy. I committed my code here:

    https://github.com/blucas2016/PythonIoTTriggerSampleCode

    clone that and give it a try.

    I generated the code above using the vs code az function add-on. (you may want to close and restart vs code after installing those add-ons)
    199846-image.png

    If you run that it will guide you through setting up the app setting file (I recommend you create your azure storage before so you can choose when it prompt you to select storage ):
    199853-image.png

    That will generate something like this:

    199876-image.png

    You can see it added a local.settings.json with (#1). The azure storage conn string - (#2). the event hub connection string. When I run the debugger (after sending events to the hub) I do see it coming though (#3)

    Git won't commit "local.settings.json", add this to your solution if you need (add your own conn strings)

    {  
      "IsEncrypted": false,  
      "Values": {  
        "AzureWebJobsStorage": "DefaultEnxxointsProtoxxxxxxxxxxxxxxxxxx=f5KL1VKGwPL+CJQwsIsIASx57xxxxxxxxxxmHhxxxxxxxxdows.net",  
        "FUNCTIONS_WORKER_RUNTIME": "python",  
        "brunoqnadevhub_RootManageSharedAccessKey_EVENTHUB": "Enxpxxoint=sb:/xxxxxxxx20-18914xb4b61d8xxxxxxxxx;SharedAccessKey=gMZSeO70EELLzbAv31kRexxxx022"  
      }  
        
    }  
    

    The hub conn string is the one from "built-in endpoints":

    199883-image.png

    And the storage is the connection string:

    199787-image.png

    Now that i now the code works, it would make easier to deploy and narrow down possible errors. I used the az function deployment button from the vs code add on:

    199737-image.png

    199845-image.png

    For some reason the vs code deployment added (#1) but skipped the hub conn (#2) I manually added direct in azure

    after sending some messages I can now confirm deployment is successful

    199881-image.png

    Let me know if that helps. I can try to add more details . If that is enough, please Accept the answer. Cheers!


  4. ChrisU 231 Reputation points
    2022-05-10T12:20:13.33+00:00

    Bruno, so I have sought to replicate what you did above. Thank you for pointing out the need to define the storage and showing me how. Anyway, as you suggested I set up an eventhubtrigger connecting to my IoT Hub and replicated what you did. I did not change the init.py or the json files as suggested here and here.

    My repo is here.

    The local.settings.json:
    200597-image.png

    When tapping F5 to run locally I got the following in the terminal:
    200548-image.png

    Can you explain this?

    I did however upload to Azure where, like you I had to add the event hub connection key and value. What was weird was that the AzureWebJobsStorage Value was different to that I had set within the local.settings.json. I decide to run it with this value and then with the value within the local.settings.json.

    Run with initial AzureWebJobsStorage value:
    Started the function within the Azure Hub. I have only found Azure function tutorials on the HTTP triggers (there are lots so I know how to test that!) but I do not know the specifics of testing an Event hub trigger once deployed to Azure. So I started the function app within the Azure GUI and then started the streaming logs from VSC. I then right clicked on the function and selected to ‘Execute Function now’ within VSC with the test message (is this the correct way to test?):
    200598-image.png

    This resulted in the below logged entries with in live metrics:
    200661-image.png

    Nothing within the init.py is displayed and the request is below listed as an error:
    200633-image.png

    Run with AzureWebJobsStorage Value from local.settings.json:
    This seemed better in that no exception errors occurred and a trace entry was recorded when I executed the function within VSC. However I get a 404 error:
    200652-image.png
    200653-image.png

    This seems like an improvement. However:

    1. I get the 404 error
    2. I get the error messages within the dev environment (2nd screen grab); this is problem if I want to test and deploy.
    3. My IoT Hub was receiving data throughout all of this and nothing was posted to the live metrics
    4. How do I get to this view:
      200671-image.png

    Thanks for your help thus far; your comments on the above would be welcome.

    0 comments No comments