Message Handler Custom Function

Message Handler Custom Function

When data is received from endpoints such as gateways or smart devices in the Zoho IoT application, you can use a message handler to perform additional processing. This includes running complex computations, calling external APIs, and enriching the incoming data. Zoho IoT allows message handlers to be configured at the device model or device instance level, and this is achieved through message handler custom functions.

Message handler custom functions must be written using the Deluge scripting language.

This document describes the steps to create one, how to associate it with a device model or a device, and an example script demonstrating its use.

Creating a Message Handler Custom Function

To create a message handler custom function,

  1. Click Add Custom Function.



  2. Select Message Handler in the Category field.



  3. Provide the required values in the appropriate fields.

    Example -

    Language : Deluge
    Model/Module: Home Gateway (Select the model on which the device, asset, or location is to based on)
    Display Name: Temperature Delta (Provide a name of your choice)
    Function Name: temperature_delta(Provide a name of your choice)
    Description: A message handler that appends outside temperature and the difference compared to internal temperature to the payload.
    State Memory: OFF


    Notes
    Learn more about each field required in configuring message handler custom function. 
  4. Click Save. This will open the Code Editor.



  5. Provide the required code.



  6. Click Save and Close.


Configuring Message Handler Custom Function fields

Details about each field required to be configured while adding a message handler custom function.

Language: Deluge is the supported language for writing message handler custom function.

Module/Model: The model/module to which the message handler applies is selected in this field. This associates the message handler with all device instances created based on the model. Alternatively, you can create a message handler specific to an individual device instance. Click here to learn more.

State Memory: Enabling state memory provides a dedicated space for the device to store and retrieve contextual data between successive messages. This enhances the functionality of your message handler by allowing it to retain and utilize context across multiple messages from the same device.

For example, consider an energy meter sending periodic usage data. With state memory enabled, the system can store the cumulative energy consumption for the month. When a new reading is received, the message handler adds this value to the stored total, updating the monthly consumption. This approach enables real-time tracking of total energy usage for the month.

Reset State Memory: When state memory is enabled, you also have the option to reset the stored value if the message handler function encounters a failure. Using the counter example from the State Memory example, this means you can reset and reinitialize the counter if the message handler function does not execute successfully.

Message Handler Custom Function Code Example

Below is an example of a custom function used in a message handler. When temperature data is received from an AM103 device, the function calls a weather API to retrieve the external temperature, calculates the difference between the room and outdoor temperatures, and appends this value to the incoming JSON payload.

headerMap = header.toMap();
deviceId = headerMap.get("deviceid");
topic = headerMap.get("topic");
communication_status_flag = headerMap.get("data_internal");
 
if(topic == "telemetry" && communication_status_flag == false)
{
    payload = message.toMap();
    if(payload.containsKey("data"))
    {
        deviceMessage = payload.get("data");
    }
    else
    {
        deviceMessage = payload;
    }
    roomTemp = deviceMessage.get("temperature");
 
    if(roomTemp != null)
    {
        /* Call external Weather API */
        weatherResponse = invokeurl
        [
            url : "https://api.open-meteo.com/v1/forecast?latitude=12.97&longitude=77.59&                  current_weather=true"
            type : GET
        ];
info weatherResponse;
        weatherMap = weatherResponse.toMap();
        outdoorTemp = weatherMap.get("current_weather").get("temperature");
 
        /* Calculate temperature difference */
        tempDifference = roomTemp - outdoorTemp;
 
        /* Append new value to payload */
        deviceMessage.put("outdoor_temperature", outdoorTemp);
        deviceMessage.put("temperature_difference", tempDifference);
    }
}
else
{
    deviceMessage = Map();
    deviceMessage.put("header", headerMap);
}
return deviceMessage;
Input Payload for message handler custom function:
 
{
"temperature" : 27
}
 
Output Payload by message handler custom function:
 
{

"temperature_difference": 3.1,

"temperature": 27,

"outdoor_temperature": 23.9
}

Associating to a device/device model

Once the message handler custom function is created, it becomes available for the device model and the instances created from it. You can associate the function at the model level to apply it to all device instances, or assign it to a specific device instance as required.

Associating the custom function to a device model

In the developer application,
  1. Access the Developer Application.
  2. In the Models tab, select Devices in the left pane.



  3. Click on the device model for which you created the message handler custom function. For this illustration, Home Gateway device model is selected.



  4. Scroll down in the templates section and click on the Message Handler option.



  5. Click Configure Message Handler.



  6. Click Choose Custom Function.



  7. Select the required custom function and click Associate.



  8. Click Save.



  9. Click Update in the confirmation dialog box.


The message handler custom function is now associated with the device model and is enabled for all device instances created from this model.

Associating the custom function to a specific device instance

In the end application,
  1. Go to Devices > Devices.



  2. Click the device instance to which you want to associate the message handler custom function. For this illustration, Arduino Home GW device is selected. 



  3. Select Actions > Message Formatter and Handler.



  4. Click Edit Message Handler.



  5. Toggle to Instance to associate the message handler only with this device instance.



    Notes
    Note: Toggle to Model to associate the message handler with this device instance and all other instances of the same model.

  6. Click Choose Custom Function.



  7. Select the required message handler custom function and click Associate.



  8. Click Save.



  9. Click Update in the confirmation dialog box. 


The message handler custom function is now associated with the selected device instance.






        Create. Review. Publish.

        Write, edit, collaborate on, and publish documents to different content management platforms.

        Get Started Now


          Access your files securely from anywhere

            Zoho CRM Training Programs

            Learn how to use the best tools for sales force automation and better customer engagement from Zoho's implementation specialists.

            Zoho CRM Training
              Redefine the way you work
              with Zoho Workplace

                Zoho DataPrep Personalized Demo

                If you'd like a personalized walk-through of our data preparation tool, please request a demo and we'll be happy to show you how to get the best out of Zoho DataPrep.

                Zoho CRM Training

                  Create, share, and deliver

                  beautiful slides from anywhere.

                  Get Started Now


                    Zoho Sign now offers specialized one-on-one training for both administrators and developers.

                    BOOK A SESSION







                                Quick LinksWorkflow AutomationData Collection
                                Web FormsEnterpriseOnline Data Collection Tool
                                Embeddable FormsBankingBegin Data Collection
                                Interactive FormsWorkplaceData Collection App
                                CRM FormsCustomer ServiceAccessible Forms
                                Digital FormsMarketingForms for Small Business
                                HTML FormsEducationForms for Enterprise
                                Contact FormsE-commerceForms for any business
                                Lead Generation FormsHealthcareForms for Startups
                                Wordpress FormsCustomer onboardingForms for Small Business
                                No Code FormsConstructionRSVP tool for holidays
                                Free FormsTravelFeatures for Order Forms
                                Prefill FormsNon-Profit

                                Intake FormsLegal
                                Mobile App
                                Form DesignerHR
                                Mobile Forms
                                Card FormsFoodOffline Forms
                                Assign FormsPhotographyMobile Forms Features
                                Translate FormsReal EstateKiosk in Mobile Forms
                                Electronic Forms
                                Drag & drop form builder

                                Notification Emails for FormsAlternativesSecurity & Compliance
                                Holiday FormsGoogle Forms alternative GDPR
                                Form to PDFJotform alternativeHIPAA Forms
                                Email FormsFormstack alternativeEncrypted Forms

                                Wufoo alternativeSecure Forms

                                TypeformWCAG


                                    All-in-one knowledge management and training platform for your employees and customers.

                                              Create. Review. Publish.

                                              Write, edit, collaborate on, and publish documents to different content management platforms.

                                              Get Started Now




                                                                You are currently viewing the help pages of Qntrl’s earlier version. Click here to view our latest version—Qntrl 3.0's help articles.




                                                                    Manage your brands on social media


                                                                      • Desk Community Learning Series


                                                                      • Digest


                                                                      • Functions


                                                                      • Meetups


                                                                      • Kbase


                                                                      • Resources


                                                                      • Glossary


                                                                      • Desk Marketplace


                                                                      • MVP Corner


                                                                      • Word of the Day


                                                                      • Ask the Experts


                                                                        Zoho Sheet Resources

                                                                         

                                                                            Zoho Forms Resources


                                                                              Secure your business
                                                                              communication with Zoho Mail


                                                                              Mail on the move with
                                                                              Zoho Mail mobile application

                                                                                Stay on top of your schedule
                                                                                at all times


                                                                                Carry your calendar with you
                                                                                Anytime, anywhere




                                                                                      Zoho Sign Resources

                                                                                        Sign, Paperless!

                                                                                        Sign and send business documents on the go!

                                                                                        Get Started Now




                                                                                                Zoho TeamInbox Resources





                                                                                                          Zoho DataPrep Demo

                                                                                                          Get a personalized demo or POC

                                                                                                          REGISTER NOW


                                                                                                            Design. Discuss. Deliver.

                                                                                                            Create visually engaging stories with Zoho Show.

                                                                                                            Get Started Now








                                                                                                                                • Related Articles

                                                                                                                                • Testing a Message Handler Custom Function

                                                                                                                                  While creating a message handler custom function, you can test the function to see if the desired output is received. For testing, you can provide the expected value and see if the expected output value is obtained. For the message handler custom ...
                                                                                                                                • Testing State Memory Enabled Message Handler Custom Function

                                                                                                                                  With state memory enabled, you can store values that can be used in successive messages to handle the incoming messages. We will go through a sample code to understand how state memory works while creating a custom function. headerMap = ...
                                                                                                                                • Creating a Message Handler

                                                                                                                                  A message handler can be created in a Zoho IoT application by selecting "Message Handler" in the Category field while creating a custom function. Configuring the fields while creating a message handler Language: Deluge is the supported language for ...
                                                                                                                                • Understanding message formatter and message handler

                                                                                                                                  In the Zoho IoT application, data sent from the gateway/smart device can be enhanced further. This includes decoding raw payload into a usable JSON format and performing additional computations and enrich by calling external API's. This is achieved ...
                                                                                                                                • Adding a Message Handler through a Device Instance

                                                                                                                                  A message handler custom function can be added through a device instance in the end application. To add a message handler through a device, Access the End Application. Select Devices > Devices in the left pane. Click on the name of the device for ...
                                                                                                                                  Wherever you are is as good as
                                                                                                                                  your workplace

                                                                                                                                    Resources

                                                                                                                                    Videos

                                                                                                                                    Watch comprehensive videos on features and other important topics that will help you master Zoho CRM.



                                                                                                                                    eBooks

                                                                                                                                    Download free eBooks and access a range of topics to get deeper insight on successfully using Zoho CRM.



                                                                                                                                    Webinars

                                                                                                                                    Sign up for our webinars and learn the Zoho CRM basics, from customization to sales force automation and more.



                                                                                                                                    CRM Tips

                                                                                                                                    Make the most of Zoho CRM with these useful tips.



                                                                                                                                      Zoho Show Resources