Skip to main content
All CollectionsDeveloper Guides
UbiFunctions: Manage Downlink messages with Sigfox and Ubidots
UbiFunctions: Manage Downlink messages with Sigfox and Ubidots

Learn to handle downlink messages from Sigfox Backend with Ubidots.

Sergio M avatar
Written by Sergio M
Updated over 2 months ago

Sigfox wide-area, low power devices with Ubidots IoT Application Development platform makes for a simple to integrate IoT solution all the way from hardware to the end-user's experience.

By following the steps provided is this tutorial, you will be able to handle and send downlink messages to your Sigfox Device from Ubidots

This integration will require UbiFunctions , a featured tool of Ubidots IoT Application Development platform that allows users to create a private, custom API endpoint or endpoints for their applications.

If you desire to learn how to manage Uplink messages from the Sigfox Backend to Ubidots, please refer to this guide.

If you are not familiar with Sigfox or the Sigfox Backend, we recommend you check out this Sigfox Technology Overview before proceeding much further with your POC or hardware setup.

Requirements

1. Understanding Sigfox Downlink requests with Ubidots 

Downlink messages let your IoT Sigfox devices perform control actions based on a received message. For a better understanding, let's suppose that you want to be able to modify the "update frequency" of a device by adjusting a variable in your Ubidots dashboard.

To execute a downlink message and sent input data from Ubidots to your Sigfox device you'll need a Ubidots platform to assign the value which is going to establish the new update frequency value for the hardware.

For a better understanding of the Downlink Integration Process between your Sigfox Devices and Ubidots, refer to the step-by-step of the image below:

To clarify the understanding of the Sigfox Downlink messages, you can also refer to the video below:

 2. Create Control Variables for the Downlink Message in Ubidots 

1. Go to your Ubidots account. If you already don't have one, create it by clicking here

[PROTIP] - To handle an industrial & scalable communication between your IoT hardware and Ubidots the IDs or MAC address of the hardware will be used as the Device Labels for Ubidots. The Device Label is the unique identifier that keeps your hardware devices matching its digital twin the Ubidots. For a better understanding of Device Labels in Ubidots, please refer to the guide below:

2. Now, assuming that you already have a Sigfox Device transmitting data to Ubidots account by using the Sigfox device ID as Device Label, it's time to create a variable to set the desired update frequency inside the device. 

To create the control variable, press "Add Variable –> Raw". Then assign "update frequency" as name. Once the variable is created, please verify if the variable label assigned is "update-frequency":

3. Next, go to the Dashboard section of your Ubidots account by clicking "Data".

4. Then, add a new control widget to the dashboard. To add the new widget press the "+" icon located at the right upper side of the page, then select "Control –> Slider –> Add Variable –> Sigfox Device (Sigfox Device ID) –> "Update Frequency" Variable (previously created)

Once the widget is created, you will be able to set the desired update frequency in minutes by using the slider as shown above. Where, the maximum value is 60 minutes, and the minimum is 10 minutes:

3. Configure UbiFunction in Ubidots

Now we are going to show how to configure an UbiFunction to:

  • Retrieve the update frequency value assigned by the user from the Ubidots Dashboard 

  • Return the expected data by Sigfox containing the new update frequency value 

Note: an UbiFunction is a Node.js cloud function executed when a GET or POST request is made in the Function's URL, as illustrated below. 

  1. Create an UbiFunction by going to your Ubidots account –> Devices –> Functions. 

NOTE:  If you cannot see the "Functions" module in your account's menu, you will need to upgrade your plan to a Professional plan or above in the billing section of your account

2. Click the blue "+" icon in the upper-right corner to create a new function: 

3. By default, every UbiFunction is populated with a sample code without any configuration. You will need to configure the function in order to make it work best for your needs. The sample function will not work with Sigfox.

The default configurations for the function are as shown below:

To begin, assign the name desired for your UbiFunction. We recommend using the format "Brand-Reference", i.e. "Sigfox-Suntech", "Sigfox-Oyster" or "Sigfox-Thinxtra". Also, it is advisable to relate the name to the kind of message is being sent; for example, "downlink" can be placed at the end of our function's Name: "Sigfox-Suntech-downlink." 

For this tutorial, the function will be titled "Sigfox-Device-Downlink."  

4. Select GET as HTTP Method and NodeJS 8 as Runtime. With these parameters the Function setup will look as follows:

5. Now it is time to deploy the UbiFunction in order to generate the API endpoint URL which is going to be used to transmit the data from the Sigfox Backend to Ubidots

To deploy the UbiFunction click "Make it live":

Now, the resulting URL endpoint built by the UbiFunctions engine and privately hosted for your Ubidots Application will look a little something like this:

IMPORTANT NOTE: This resulting URL Endpoint is important because it is the endpoint that you will direct your Sigfox callback to send the uplink message that requests the downlink message. If this is confusing, please watch this explainer video.  
As you might have noticed the resulting URL endpoint generated by the UbiFunction is: 

https://parse.ubidots.com/prv/ubidots-tutorials/sigfox-device-downlink

Where, ubidots-tutorial is your Ubidots username and sigfox-device-downlink is the Name assigned to the function within the UbiFuctions engine.

Save the API endpoint URL to be used and assigned later in the Sigfox Callback configuration. 

6. Erase and replace the default code located in the UbiFunction editor, with the sample code provided below. Copy and paste the below sample code into the UbiFunction code editor: 

/*

 * This code demonstrates a how to handle Downlink Message with Sigfox and Ubidots by an

 * HTTP endpoint that receives an Ubidots token, Sigfox Device ID and variable desired to

 * be sent in the downlink message. Then, this parameters will be used to handle and check

 * data from Ubidots to build and send the data expected by Sigfox.

 *

 * You can build a URL as explained below, and paste it into your web browser to

 * test the parser. Example:

 *

 * https://parse.ubidots.com/{your-parser-URL}/?token={YOUR-TOKEN}&device={SIGFOX-DEVICE-ID}&variable={VARIABLE_LABEL}

 *

 * created 9 August 2018

 * by Maria C. Hernandez

 */

// Import the 'request-promise' library so we can make HTTP request from the parser

var request = require('request-promise');

// Main function - runs every time the parser is executed.

// "args" is a dictionary containing ubidots token, Sigfox device ID, and variable label.

async function main(args) {

    // Grab the token, device label and variable label from URL parameters

    var ubidots_token = args.token;

    var device_label = args.device;

    var variable_label = args.variable;

    // Check if the variable already existed, if not it will be created automatically with a default update

    // frequency of 10 minutes

    var variable_status = await ubidots_request_variable_status(ubidots_token, device_label, variable_label);

    if (variable_status >= 400) {

        var response = await ubidots_request_variable_creation(ubidots_token, device_label, variable_label);

        console.log("New Variable Created! - Update Frequency = 10 minutes");

    }

    // Retrieve the last value of the variable assigned    

    var downlink_data = await ubidots_get_lastvalue(ubidots_token, device_label, variable_label);

    // Encode the last value received to HEX

    var downlink_data_hex = Buffer.from([downlink_data]).toString('hex');

    // Complete the 8 bytes downlink data

    downlink_data_hex = (Array(16).join('0') + downlink_data_hex).slice(-16);

    // Debuggin messages

    console.log("Value assigned in the Control Widget: " + downlink_data);

    console.log("Donwlink Data to be sent: " + downlink_data_hex);

    console.log("Triggering downlink message!");

    // Return Downlink Data to Sigfox Cloud

    return sigfox_downLink(device_label, downlink_data_hex);

}

/**************************************************

 *                 AUX ROUTINES                   *

 **************************************************/

/*

    Build the Downlink Message to be sent to Sigfox Cloud

    - device_id: Sigfox Device ID

    - downlinkDaTa: Value desired to be sent as Downlink Message

*/

async function sigfox_downLink(device_id, downLink_data) {

    // Return data to SIGFOX - hardcoding the return data for debugging

    var data = {};

    data[device_id] = { "downlinkData": downLink_data };

    return data;

}

/*

    Build & Handle a GET HTTP request to Ubidots retrieve last value

    - ubidots_token: Token (Access Key) of your Ubidots Account

    - device_label: Device Label where the variable desired is located

    - variable_label: Variable Label desired to obtain data (last value)

*/

async function ubidots_get_lastvalue(ubidots_token, device_label, variable_label) {

    var options = {

        url: 'https://industrial.api.ubidots.com/api/v1.6/devices/' + device_label + '/' + variable_label + '/lv',

        headers: {

            "x-auth-token": ubidots_token

        },

        json: true

    };

    return await request.get(options);

}

/*

    Build & Handle a POST HTTP request to create a variable in Ubidots

    - ubidots_token: Token (Access Key) of your Ubidots Account

    - device_label: Device Label where the variable is going to be created (Sigfox Device ID)

    - variable_Label: Variable Label desired to create the variable

*/

async function ubidots_request_variable_creation(ubidots_token, device_label, variable_label) {

    var options = {

        method: 'POST',

        url: 'https://industrial.api.ubidots.com/api/v1.6/devices/' + device_label + "/" + variable_label + "/values",

        body: {value: 10},

        json: true,

        headers: {

            'Content-Type': 'application/json',

            'X-Auth-Token': ubidots_token

        }

    };

    return await request.post(options);

}

/*

    Build & Handle a GET HTTP request to verify if the variable already exist

    - ubidots_token: Token (Access Key) of your Ubidots Account

    - device_label: Sigfox device ID  

    - variable_Label: Variable Label of the device desired to check

*/

async function ubidots_request_variable_status(ubidots_token, device_label, variable_label) {

    var status_code;

    var options = {

        url: 'https://industrial.api.ubidots.com/api/v1.6/devices/' + device_label + '/' + variable_label,

        headers: {

            "x-auth-token": ubidots_token

        },

        json: true,

        resolveWithFullResponse: true

    };

    try {

        var response = await request.get(options);

        status_code = response.statusCode;

    } catch(error) {

        status_code = JSON.stringify(error.statusCode);

    }

    return status_code;

}

At this point, the sample code provided is designed to retrieve the last value assigned as update frequency value. Then, the function will return the expected data by Sigfox which contains the new update frequency value plus the Sigfox device ID to know which device is going to being updating its update frequency.

Sigfox is expecting to receive the following data:

{
  '{{deviceId}}': {
'downlinkData':{{data}}
 }
}

Ubidots will be returning the following data:

{
  "2BF076": {
    "downlinkData": "000000000000000A"
  }
}


7.  Now it's time to save the changes made, and deploy the downlink function in the UbiFunctions engine. To do so, just press the "Make it live."

With the changes already saved, let's setup the Sigfox Callback to start receiving the downlink data from Ubidots into the Sigfox Device.  

4. Configure Downlink Message in Sigfox

The management of the data between Sigfox and Ubidots requires a "Callback". 

Sigfox Callbacks use HTTP requests to transmit data bi-directionally with Ubidots. In this case, we are going to show you how to configure the Sigfox Callback to transmit data from Ubidots to Sigfox Devices using the UbiFunctions engine previously discussed.

1. To begin, access to the Sigfox Backend where your hardware is transmitting data.

2. Go to the Device section and select the Device Type of the desired downlink device:

3. Edit the Device Type by pressing the edit button located in the right-upper corner of the page:

Set callback as a Downlink: 

To save the changes press "Ok".

4. Next, verify your device information and select "CALLBACKS" from the menu on the left-hand side of the page, as shown below:

At this point, a new callback is needed. To create a new callback, select "New". Then, select "Custom callback". 

In the below window, you will note that you must fill the configurations of the callback which should be communicating data with Ubidots bidirectionally.  

To establish the communication with Ubidots, assign the parameters mentioned below and leave the remaining parameters and fields as default:

  • Type: DATA  - BIDIR 

  • URL Pattern

https://parse.ubidots.com/{UBIFUNCTION-URL}/?token={UBIDOTS-TOKEN}&device={SIGFOX-DEVICE-ID}&variable={VARIABLE_LABEL}

The following keys ({keys} ) should also be replaced with the following parameters:

  •  {UBIFUNCTION-URL} :  API endpoint URL generated by UbiFunction

  •  {SIGFOX-DEVICE-ID} :  Device Key related to the Sigfox Device ID ({device} ) assigned by Sigfox Backend

  • {VARIABLE_LABEL} : Variable label of the control variable sending data back to Sigfox in the downlink message

Once all the parameters are correctly updated, the final URL should look like the one below:

https://parse.ubidots.com/prv/ubidots-tutorials/sigfox-device-downlink?token=BBFF-Rfcgaxns6HlVb155WA0RhSY85xNDmB&device={device}&variable=update-frequency

To avoid issue, we highly recommend you compare the callbacks configurations below with yours:

Once you've verified the callback, press "OK" tp save the changes. 

5. By default the BIDIR callback will be inactive after creation. Please activate it, by selecting Downlink check box:

When activated: 

Now your callback is ready and enabled to handle data from Ubidots to Sigfox Devices. At this point, the data is going to be requested by the Sigfox Device via an uplink message pointing to the UbiFunction engine (previous step). The function will be executed upon receipt of data and will return the expected response from the control variable to be used as the downlink message.

IMPORTANT DEPLOYMENT NOTE:  Ubidots and Sigfox communicate via either URL or Batch URL (used for large deployments). This tutorial explains the standard URL channel. If you have a large scale sensor network, please contact sales@ubidots.com to receive additional information for Batch URL integrations.

5. Sending Downlink request to Sigfox 

With the UbiFunction and Sigfox Callback configured, you'll be able of trigger downlink messages from Ubidots to your Sigfox Device once the Sigfox Device request it (using an uplink message).

As we mentioned above, the device will send a uplink message requesting the downlink message to Ubidots.

How can I request a downlink message from my device? - This depends on the manufacture and documentation for each Sigfox Device. It's important to mention that requesting downlink messages will be different for most, if not all different hardware manufacturers. Accordingly, Ubidots recommendations to refer directly to the Technical Documentation of the manufacturer to better understand the configuration required to fit the required "Downlink Messages" structure.

Now, for testing purpose we decided to used a Thinxtra Xkit previously configured to request a downlink once the embed button of the board is pressed.

In the image below you can see how the value assigned from the Ubidots Control Widget was encoded properly and received in a few seconds by the Sigfox Device after the embed button was pressed:

Now the value received can be assigned as a new update frequency value in the device configurations.

To make things easier for you, plus the logic and follow up of this guide, we created a new raw variable in Ubidots to set the value desired to be triggered as Downlink message, but this it's not necessary thanks to the code provided above. 

Remember that any time a new device label is recognized by Ubidots, a new device is automatically created. This is true for using this UbiFunction sample coded provided. And, with this function, multiple different pieces of hardware can point to the same UbiFunction and based on the Sigfox Device Label, Ubidots will create a digital device in the platfrom, or update the digital device that already matches the Device Label of the incoming or outgoing data. With this simplicity to onboard 100s and 1,000s of devices, it is now time to create the dashboards and events of your IoT App and start controlling & monitoring you devices using Ubidots IoT Application Development Platform.   

6. Troubleshooting

If you wish to deploy multiple Sigfox Devices efficiently, the below step-by-step setup should be followed:

  1. Setup UbiFunction

  2. Setup Sigfox Callback

  3. Request First Downlink Message

  4. Create the Ubidots Control Widgets desired 

So in the step #3, if the variable assigned in the downlink message request does not already exist, because the downlink first comes to Ubidots as an uplink request, any variables labels attached to that uplink will be automatically created. This includes the downlink variable if properly coded using the sample code or your own code. IMPORTANT: Even though the sample code will automatically create the control variable, in order to fully control and send a downlink, you still must create the control widget that will update the control variable.

[PRO-TIPs] For debugging purposes:

1. To verify if the message was properly triggered by the UbiFunction engine, simply press the "envelop" icon located in the control bar of the function you're looking to track. This will display the logs and executions of your function.

At this point, you will be able to see the logs of the function provided, plus the data which is being returned to Sigfox Cloud: 

2. To verify the if the downlink message was requested and sent properly in the Sigfox backend, go to the "Messages" from the Device ID tab. In this section, you will be able to see all the messages (uplink & downlink) handled by a device selected.

The image below shows the response of the uplink message requesting the downlink message:

The image below shown the response of the downlink message containing the data which is going to be sent to the device:

6. Summary

With this, your Sigfox Callback ready and the UbiFunction engine are properly configured and transmitting data from Ubidots to your Sigfox Devices. Now it is time to develop your application with Ubidots IoT Application Development and Deployment Tools.

Ubidots is an Internet of Things (IoT) Application Development Platform that empowers system integrators and innovators to launch control, monitoring, and automation applications that turn sensor data into actionable insights. Hiring an engineering team to merge the physical world with a digital world and create an IoT application that both functions and looks great is costly in both time and money, so Ubidots did it for you. Ubidots exists as an efficient and economical resource to develop private cloud-based IoT applications and integrate data-driven solutions into enterprises and research to improve our working economy. 

Other users also found useful:

Did this answer your question?