#AzureIoT – How to create an Azure IoT module from an Azure #CustomVision project 👀 6/N

Buy Me A Coffee

Hi !

Today’s post will be mostly focused on code. And on the main tasks

  • Add a configuration property to the module to enable / disable the telemetry messages
  • Each time the Azure IoT Module process an image, it will trigger a telemetry with the information of the detected image

The sample running show how for each image analyzed (sent using Postman) a new message is triggered to Azure IoT.

The sample running show how for each image analyzed (sent using Postman) a new message is triggered to Azure IoT.

Let’s start from here.

Add a property to enable / disable the message trigger

Let’s start adding environment variable to the Azure IoT Module to define if the module will trigger messages.

Add environment variable to the Azure IoT Module to define if the module will trigger messages

Then I defined this function to read the environment value

def GetEnvVarBool(name):
  varVal = bool(os.environ[name])
  return varVal

And I reading the env value is as easy as:

trigger_enabled = GetEnvVarBool('ReportValues')

Send an Azure IoT Hub message for each processed image

As I defined in my previous posts, I have a variable named [module_client] that represents the Azure IoT Module. The following function will

  • Validate if the trigger messages is enabled
  • Load the json response from the Custom Vision image process
  • Sort the predictions results by probability
  • Add each tagName as a message property
  • Trigger the message
async def send_iot_message(strMessage):
    global module_client
    if (trigger_enabled == False):
        return

    message = Message("")

    # load json def and add each tag as properties
    jsonStr = strMessage.get_data(as_text=True)
    jsonObj = json.loads(jsonStr)

    preds = jsonObj['predictions'] 
    sorted_preds = sorted(preds, key=lambda x: x['probability'], reverse=True)
    if (sorted_preds):
        for pred in sorted_preds:
            # tag name and prob * 100
            tagName     = str(pred['tagName'])
            probability = pred['probability'] * 100
            message.custom_properties[tagName] = str(probability)

    await module_client.send_message(message)

And, finally the call to this function is performed on each http endpoint using asyncio.run() to avoid a thread block.

def predict_image_handler(project=None, publishedName=None):
    try:
        imageData = None
        if ('imageData' in request.files):
            imageData = request.files['imageData']
        elif ('imageData' in request.form):
            imageData = request.form['imageData']
        else:
            imageData = io.BytesIO(request.get_data())

        img = Image.open(imageData)
        results = predict_image(img)

        jsonResults = jsonify(results)
        asyncio.run(send_iot_message(jsonResults))

        return jsonResults

So far, so good. I covered a trivial scenario and I think is a good memory backup for me !

Resources

Happy coding!

Greetings

El Bruno



¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.